@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
package/dist/bash.js CHANGED
@@ -1,2336 +1,13 @@
1
- // src/bash.ts
2
- import { spawn as spawn2 } from "node:child_process";
3
- import * as os4 from "node:os";
4
- import { StringDecoder } from "node:string_decoder";
5
1
  import {
6
- emitProcessCompleted,
7
- emitProcessOutput,
8
- emitProcessStarted
9
- } from "@wrongstack/core/observability";
10
-
11
- // src/_env.ts
12
- import { buildChildEnv } from "@wrongstack/core/utils";
13
-
14
- // src/_output-spool.ts
15
- import { createWriteStream, mkdirSync } from "node:fs";
16
- import * as fsp from "node:fs/promises";
17
- import * as path from "node:path";
18
- import { wstackGlobalRoot } from "@wrongstack/core/utils";
19
- var SPOOL_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
20
- var SPOOL_WRITE_HWM_BYTES = 4 * 1024 * 1024;
21
- var sweepStarted = false;
22
- function toolOutputDir() {
23
- return path.join(wstackGlobalRoot(), "tool-output");
24
- }
25
- function sweepOldSpoolFiles(dir) {
26
- if (sweepStarted) return;
27
- sweepStarted = true;
28
- void (async () => {
29
- try {
30
- const now = Date.now();
31
- for (const name of await fsp.readdir(dir)) {
32
- if (!name.endsWith(".log")) continue;
33
- const p = path.join(dir, name);
34
- try {
35
- const st = await fsp.stat(p);
36
- if (now - st.mtimeMs > SPOOL_RETENTION_MS) await fsp.unlink(p);
37
- } catch {
38
- }
39
- }
40
- } catch {
41
- }
42
- })();
43
- }
44
- function spoolNote(info) {
45
- const dropped = info.droppedBytes > 0 ? `, ~${info.droppedBytes} bytes dropped under backpressure` : "";
46
- return `
47
- [output truncated \u2014 full ${info.bytes} bytes at ${info.path}${dropped}; read/grep that file selectively instead of re-running with more output]`;
48
- }
49
- function createOutputSpool(opts) {
50
- const threshold = opts.thresholdBytes ?? 32768;
51
- const safeTool = opts.tool.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 40) || "tool";
52
- let head = "";
53
- let headBytes = 0;
54
- let totalBytes = 0;
55
- let droppedBytes = 0;
56
- let stream = null;
57
- let filePath = null;
58
- let failed = false;
59
- let finalized = false;
60
- const open = () => {
61
- if (stream || failed) return;
62
- try {
63
- const dir = toolOutputDir();
64
- mkdirSync(dir, { recursive: true });
65
- sweepOldSpoolFiles(dir);
66
- const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
67
- const rand = Math.random().toString(36).slice(2, 6);
68
- filePath = path.join(dir, `${stamp}-${safeTool}-${rand}.log`);
69
- stream = createWriteStream(filePath, { flags: "w", encoding: "utf8" });
70
- stream.on("error", () => {
71
- failed = true;
72
- stream = null;
73
- filePath = null;
74
- });
75
- stream.write(head);
76
- } catch {
77
- failed = true;
78
- stream = null;
79
- filePath = null;
80
- }
81
- };
82
- return {
83
- write(text) {
84
- if (finalized || !text) return;
85
- const textBytes = Buffer.byteLength(text, "utf8");
86
- totalBytes += textBytes;
87
- if (!stream && !failed) {
88
- if (headBytes + textBytes <= threshold) {
89
- head += text;
90
- headBytes += textBytes;
91
- return;
92
- }
93
- head += text;
94
- open();
95
- head = "";
96
- return;
97
- }
98
- if (stream) {
99
- if (stream.writableLength > SPOOL_WRITE_HWM_BYTES) {
100
- droppedBytes += textBytes;
101
- return;
102
- }
103
- stream.write(text);
104
- }
105
- },
106
- finalize() {
107
- if (finalized) {
108
- return filePath ? { path: filePath, bytes: totalBytes, droppedBytes } : null;
109
- }
110
- finalized = true;
111
- head = "";
112
- if (!stream || !filePath) return null;
113
- try {
114
- stream.end();
115
- } catch {
116
- }
117
- return { path: filePath, bytes: totalBytes, droppedBytes };
118
- }
119
- };
120
- }
121
-
122
- // src/_util.ts
123
- import * as Core from "@wrongstack/core/utils";
124
- var COMMAND_OUTPUT_MAX_BYTES = 32768;
125
- var REPEAT_RUN_THRESHOLD = 3;
126
- function collapseCarriageReturns(text) {
127
- const lf = text.replace(/\r\n/g, "\n");
128
- if (!lf.includes("\r")) return lf;
129
- return lf.split("\n").map((line) => line.includes("\r") ? line.slice(line.lastIndexOf("\r") + 1) : line).join("\n");
130
- }
131
- function collapseConsecutiveDuplicates(text, minRun = REPEAT_RUN_THRESHOLD) {
132
- const lines = text.split("\n");
133
- const out = [];
134
- let i = 0;
135
- while (i < lines.length) {
136
- let j = i + 1;
137
- while (j < lines.length && lines[j] === lines[i]) j++;
138
- const run = j - i;
139
- if (run >= minRun) {
140
- out.push(lines[i], `\u2026 \u27E8repeated ${run}\xD7\u27E9`);
141
- } else {
142
- for (let k = i; k < j; k++) out.push(lines[k]);
143
- }
144
- i = j;
145
- }
146
- return out.join("\n");
147
- }
148
- function takeHeadBytes(s, maxBytes) {
149
- if (maxBytes <= 0) return "";
150
- if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
151
- let lo = 0;
152
- let hi = s.length;
153
- while (lo < hi) {
154
- const mid = Math.ceil((lo + hi) / 2);
155
- if (Buffer.byteLength(s.slice(0, mid), "utf8") <= maxBytes) lo = mid;
156
- else hi = mid - 1;
157
- }
158
- return s.slice(0, lo);
159
- }
160
- function takeTailBytes(s, maxBytes) {
161
- if (maxBytes <= 0) return "";
162
- if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
163
- let lo = 0;
164
- let hi = s.length;
165
- while (lo < hi) {
166
- const mid = Math.ceil((lo + hi) / 2);
167
- if (Buffer.byteLength(s.slice(s.length - mid), "utf8") <= maxBytes) lo = mid;
168
- else hi = mid - 1;
169
- }
170
- return s.slice(s.length - lo);
171
- }
172
- function truncateHeadTail(s, maxBytes) {
173
- const total = Buffer.byteLength(s, "utf8");
174
- if (total <= maxBytes) return s;
175
- const MARKER_RESERVE = 64;
176
- const avail = Math.max(0, maxBytes - MARKER_RESERVE);
177
- const headBudget = Math.floor(avail * 0.45);
178
- const head = takeHeadBytes(s, headBudget);
179
- const tail = takeTailBytes(s, avail - Buffer.byteLength(head, "utf8"));
180
- const kept = Buffer.byteLength(head, "utf8") + Buffer.byteLength(tail, "utf8");
181
- return `${head}
182
- \u2026[truncated ${total - kept} bytes]\u2026
183
- ${tail}`;
184
- }
185
- function normalizeCommandOutput(raw, opts = {}) {
186
- if (!raw) return raw;
187
- let text = Core.stripAnsi(raw);
188
- text = collapseCarriageReturns(text);
189
- text = text.replace(/[ \t]+$/gm, "");
190
- text = collapseConsecutiveDuplicates(text);
191
- text = text.replace(/\n{3,}/g, "\n\n");
192
- return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);
193
- }
194
-
195
- // src/process-registry.ts
196
- import { spawn } from "node:child_process";
197
- import * as os from "node:os";
198
-
199
- // src/circuit-breaker.ts
200
- var DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
201
- var DEFAULT_SLOW_CALL_THRESHOLD_MS = 18e4;
202
- var DEFAULT_MAX_SLOW_CALLS = 3;
203
- var DEFAULT_WINDOW_MS = 6e4;
204
- var DEFAULT_MAX_CALLS_PER_WINDOW = 30;
205
- var DEFAULT_COOLDOWN_MS = 3e4;
206
- var CircuitBreaker = class {
207
- maxConsecutiveFailures;
208
- slowCallThresholdMs;
209
- maxSlowCalls;
210
- windowMs;
211
- maxCallsPerWindow;
212
- cooldownMs;
213
- state = "closed";
214
- consecutiveFailures = 0;
215
- window = [];
216
- lastFailureAt = null;
217
- lastSlowAt = null;
218
- /** Timestamp when the breaker was opened (for cooldown calculation). */
219
- openedAt = null;
220
- /**
221
- * Master enable flag. When false the breaker is bypassed: `beforeCall`
222
- * always returns true and `afterCall` records nothing. The class itself
223
- * defaults to enabled (so the standalone unit tests exercise tripping); the
224
- * ProcessRegistry flips this off until the user opts in via `/settings`.
225
- */
226
- enabled = true;
227
- /**
228
- * Fired (best-effort) when the breaker transitions into the `open` state.
229
- * The registry uses this to arm its auto kill/reset countdown.
230
- */
231
- onTrip;
232
- /**
233
- * Fired (best-effort) when the breaker returns to `closed` after having been
234
- * open/half-open. The registry uses this to cancel a pending kill/reset.
235
- */
236
- onReset;
237
- constructor(config = {}) {
238
- this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;
239
- this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;
240
- this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;
241
- this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;
242
- this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;
243
- this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;
244
- }
245
- /** Toggle the master enable. Disabling resets to a clean `closed` state. */
246
- setEnabled(enabled) {
247
- if (this.enabled === enabled) return;
248
- this.enabled = enabled;
249
- if (!enabled) this._reset();
250
- }
251
- get isEnabled() {
252
- return this.enabled;
253
- }
254
- /**
255
- * Returns true if the circuit allows a new call to proceed.
256
- * When false, callers should abort the tool call and return a
257
- * circuit-breaker error instead of spawning a process.
258
- */
259
- get canProceed() {
260
- if (!this.enabled) return true;
261
- this._checkStateTransition();
262
- return this.state !== "open";
263
- }
264
- /**
265
- * Snapshot of the current breaker state for observability (`/kill`).
266
- */
267
- snapshot() {
268
- this._checkStateTransition();
269
- const now = Date.now();
270
- let cooldownRemaining = null;
271
- if (this.openedAt !== null && this.state === "open") {
272
- const elapsed = now - this.openedAt;
273
- cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);
274
- }
275
- return {
276
- state: this.state,
277
- consecutiveFailures: this.consecutiveFailures,
278
- slowCallsInWindow: this.window.filter((c) => c.slow).length,
279
- callsInWindow: this.window.length,
280
- windowMs: this.windowMs,
281
- cooldownRemainingMs: cooldownRemaining,
282
- lastFailureAt: this.lastFailureAt,
283
- lastSlowAt: this.lastSlowAt
284
- };
285
- }
286
- /**
287
- * Call this BEFORE spawning a bash/exec process.
288
- * Returns true if the call is allowed; false if the breaker is open.
289
- * When false, callers MUST NOT spawn a process.
290
- *
291
- * @param bypass - If true, skip the circuit breaker check entirely.
292
- * Use for background/fire-and-forget processes that should
293
- * not affect breaker state.
294
- */
295
- beforeCall(bypass = false) {
296
- if (bypass || !this.enabled) return true;
297
- this._checkStateTransition();
298
- if (this.state === "open") return false;
299
- return true;
300
- }
301
- /**
302
- * Call this AFTER a bash/exec process finishes (success or failure).
303
- * `durationMs` is the wall-clock time the process ran.
304
- * `failed` is true when the process returned a non-zero exit code or
305
- * threw an exception before spawning.
306
- *
307
- * @param bypass - If true, do not update breaker state.
308
- * Use for background/fire-and-forget processes.
309
- */
310
- afterCall(durationMs, failed, bypass = false) {
311
- if (bypass || !this.enabled) return;
312
- const now = Date.now();
313
- if (this.state === "half-open") {
314
- if (failed) {
315
- this._trip();
316
- return;
317
- }
318
- this._reset();
319
- return;
320
- }
321
- this._pruneWindow(now);
322
- const slow = durationMs >= this.slowCallThresholdMs;
323
- this.window.push({ at: now, failed, slow });
324
- if (failed) {
325
- this.consecutiveFailures++;
326
- this.lastFailureAt = now;
327
- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
328
- this._trip();
329
- }
330
- return;
331
- }
332
- this.consecutiveFailures = 0;
333
- if (slow) {
334
- this.lastSlowAt = now;
335
- const slowCount = this.window.filter((c) => c.slow).length;
336
- if (slowCount >= this.maxSlowCalls) {
337
- this._trip();
338
- }
339
- }
340
- const callCount = this.window.length;
341
- if (callCount >= this.maxCallsPerWindow) {
342
- this._trip();
343
- }
344
- }
345
- /** Force the breaker open. Used by /kill force and Ctrl+C. */
346
- forceOpen() {
347
- this._trip();
348
- }
349
- /** Force a reset to closed. Used by tests and /kill reset. */
350
- forceReset() {
351
- this._reset();
352
- }
353
- _trip() {
354
- if (this.state === "open") return;
355
- this.state = "open";
356
- this.openedAt = Date.now();
357
- this.window = [];
358
- try {
359
- this.onTrip?.();
360
- } catch {
361
- }
362
- }
363
- _reset() {
364
- const wasRecovering = this.state !== "closed";
365
- this.state = "closed";
366
- this.consecutiveFailures = 0;
367
- this.window = [];
368
- this.openedAt = null;
369
- if (wasRecovering) {
370
- try {
371
- this.onReset?.();
372
- } catch {
373
- }
374
- }
375
- }
376
- /** Transition from open → half-open when cooldown elapses. */
377
- _checkStateTransition() {
378
- if (this.state !== "open" || this.openedAt === null) return;
379
- const elapsed = Date.now() - this.openedAt;
380
- if (elapsed >= this.cooldownMs) {
381
- this.state = "half-open";
382
- this.openedAt = null;
383
- }
384
- }
385
- _pruneWindow(now) {
386
- const cutoff = now - this.windowMs;
387
- this.window = this.window.filter((c) => c.at >= cutoff);
388
- }
389
- };
390
-
391
- // src/_redact-command.ts
392
- import { expectDefined } from "@wrongstack/core/utils";
393
- var SENSITIVE_FLAG_PATTERNS = [
394
- // --flag=value or --flag "value" (value captured up to next space or comma)
395
- /--(?: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,
396
- // -t short flag (token): attached (-tVALUE), separated (-t VALUE), or -t=VALUE.
397
- // (?<![-\w]) anchors to a token start so we don't match the `-t` inside `--token`.
398
- // The value must be token-like (>= 8 chars) so ordinary combined flags such
399
- // as `tar -tf` / `ssh -tt` are not eaten. Global flag: EVERY occurrence is
400
- // redacted, not just the first.
401
- // NOTE: synced with @wrongstack/core observability/redact-command.ts.
402
- /(?<![-\w])-t(?:[=\s]+)?[^\s,-]{8,}/g,
403
- // -p|-password|-a (redis auth) short flags: attached + separated + =value.
404
- // Same token-start anchor; over-redaction is an accepted tradeoff for a
405
- // redaction function. Synced with core copy.
406
- /(?<![-\w])-(?:password|p|a)(?:[=\s]+)?[^\s,-]+/gi,
407
- // env var–style secrets: TOKEN=x, API_KEY=y, etc.
408
- /(?: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,
409
- // Generic high-entropy look: base64 strings >32 chars or hex strings >32 digits — but only
410
- // when preceded by a flag name (e.g. --github-token=EyJ...). Global flag so
411
- // every such flag in the command line is redacted, not just the first.
412
- /--\w*(?:token|key|secret|password|passwd|auth|credential)\w*[=\s,][A-Za-z0-9+/=]{32,}/g
413
- ];
414
- function redactCommand(cmd) {
415
- let result = cmd;
416
- for (const pattern of SENSITIVE_FLAG_PATTERNS) {
417
- result = result.replace(pattern, (match) => {
418
- const eq = match.indexOf("=");
419
- const sp = match.search(/\s/);
420
- const delim = eq !== -1 ? "=" : sp !== -1 ? match[sp] : null;
421
- if (delim !== null) {
422
- const flag = match.slice(0, match.indexOf(expectDefined(delim)) + 1);
423
- return `${flag}[REDACTED]`;
424
- }
425
- if (match.startsWith("--")) {
426
- return match;
427
- }
428
- return `${match.slice(0, 2)}[REDACTED]`;
429
- });
430
- }
431
- return result;
432
- }
433
-
434
- // src/process-registry.ts
435
- var DEFAULT_GRACE_MS = 2e3;
436
- var WIN32_TASKKILL_TIMEOUT_MS = 5e3;
437
- function killWin32Tree(pid, opts = {}) {
438
- try {
439
- const child = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
440
- stdio: "ignore",
441
- windowsHide: true
442
- });
443
- let settled = false;
444
- let timeout;
445
- const settle = () => {
446
- if (settled) return;
447
- settled = true;
448
- if (timeout) clearTimeout(timeout);
449
- try {
450
- opts.onSettled?.();
451
- } catch {
452
- }
453
- };
454
- child.on("error", settle);
455
- child.on("close", settle);
456
- timeout = setTimeout(
457
- () => {
458
- try {
459
- child.kill();
460
- } catch {
461
- }
462
- settle();
463
- },
464
- Math.max(1, opts.timeoutMs ?? WIN32_TASKKILL_TIMEOUT_MS)
465
- );
466
- timeout.unref?.();
467
- child.unref();
468
- return true;
469
- } catch {
470
- return false;
471
- }
472
- }
473
- var ProcessRegistryImpl = class {
474
- processes = /* @__PURE__ */ new Map();
475
- breaker;
476
- /**
477
- * Auto kill/reset config. When the breaker trips and `autoKillResetMs > 0`,
478
- * a countdown is armed; on expiry all tracked processes are killed and the
479
- * breaker is reset to closed (forced recovery). Zero means manual recovery
480
- * only (`/kill reset`).
481
- */
482
- autoKillResetMs = 0;
483
- autoKillTimer = null;
484
- autoKillArmedAt = null;
485
- breakerCountdownListeners = [];
486
- constructor(breakerConfig) {
487
- this.breaker = new CircuitBreaker(breakerConfig);
488
- this.breaker.onTrip = () => this._armAutoKillReset();
489
- this.breaker.onReset = () => this._cancelAutoKillReset();
490
- this.breaker.setEnabled(false);
491
- }
492
- register(info) {
493
- this.processes.set(info.pid, {
494
- ...info,
495
- killed: false,
496
- protected: info.protected ?? false,
497
- background: info.background ?? false
498
- });
499
- }
500
- _isSafeSignalPid(pid) {
501
- return Number.isInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid;
502
- }
503
- _canSignalProcessGroup(p) {
504
- return os.platform() !== "win32" && p.processGroupLeader === true && this._isSafeSignalPid(p.pid) && p.child !== null && typeof p.child.pid === "number" && p.child.pid === p.pid;
505
- }
506
- _killChildDirect(p, signal) {
507
- try {
508
- if (p.child) {
509
- p.child.kill(signal);
510
- return;
511
- }
512
- if (this._isSafeSignalPid(p.pid)) process.kill(p.pid, signal);
513
- } catch {
514
- }
515
- }
516
- _killPosix(p, signal) {
517
- if (this._canSignalProcessGroup(p)) {
518
- try {
519
- process.kill(-p.pid, signal);
520
- return;
521
- } catch {
522
- }
523
- }
524
- this._killChildDirect(p, signal);
525
- }
526
- /** Unregister a process by PID. Called on 'close' / 'exit' events. */
527
- unregister(pid) {
528
- this.processes.delete(pid);
529
- }
530
- /** Get a single process by PID. */
531
- get(pid) {
532
- this._pruneStale(pid);
533
- return this.processes.get(pid);
534
- }
535
- /** Get all tracked processes. */
536
- list() {
537
- this._pruneAllStale();
538
- return Array.from(this.processes.values());
539
- }
540
- /** Get processes filtered by name (e.g. 'bash', 'exec'). */
541
- byName(name) {
542
- return this.list().filter((p) => p.name === name);
543
- }
544
- /** Get processes filtered by session. */
545
- bySession(sessionId) {
546
- return this.list().filter((p) => p.sessionId === sessionId);
547
- }
548
- /** Count of active (non-killed) processes. */
549
- get activeCount() {
550
- let n = 0;
551
- for (const p of this.processes.values()) {
552
- if (!p.killed) n++;
553
- }
554
- return n;
555
- }
556
- /** Count of active jobs explicitly launched in background mode. */
557
- get activeBackgroundCount() {
558
- let n = 0;
559
- for (const p of this.processes.values()) {
560
- if (p.background && !p.killed) n++;
561
- }
562
- return n;
563
- }
564
- /**
565
- * Combined stats for observability — used by /ps and the TUI status bar.
566
- */
567
- stats() {
568
- this._pruneAllStale();
569
- return {
570
- activeCount: this.activeCount,
571
- backgroundCount: this.activeBackgroundCount,
572
- totalCount: this.processes.size,
573
- breaker: this.breaker.snapshot()
574
- };
575
- }
576
- /**
577
- * Returns true if the circuit allows a new bash/exec call to proceed.
578
- * When false, callers MUST NOT spawn a process.
579
- */
580
- get canProceed() {
581
- return this.breaker.canProceed;
582
- }
583
- /**
584
- * Called before spawning a process. Returns true if allowed; false if
585
- * the circuit breaker is open.
586
- *
587
- * @param bypass - If true, skip circuit breaker check (for background processes).
588
- */
589
- beforeCall(bypass = false) {
590
- return this.breaker.beforeCall(bypass);
591
- }
592
- /**
593
- * Called after a process finishes. `durationMs` is wall-clock time;
594
- * `failed` is true for non-zero exit codes.
595
- *
596
- * @param bypass - If true, do not update circuit breaker state (for background processes).
597
- */
598
- afterCall(durationMs, failed, bypass = false) {
599
- this.breaker.afterCall(durationMs, failed, bypass);
600
- }
601
- /** Force-open the circuit breaker (Ctrl+C, /kill force). */
602
- forceBreakerOpen() {
603
- this.breaker.forceOpen();
604
- }
605
- /** Force-reset the circuit breaker to closed (/kill reset). */
606
- forceBreakerReset() {
607
- this.breaker.forceReset();
608
- }
609
- /**
610
- * Configure circuit-breaker protection at runtime. Called from `/settings`
611
- * (instant, all modes) and on TUI mount (applies persisted config).
612
- *
613
- * - `enabled` toggles whether the breaker gates `bash`/`exec`.
614
- * - `autoKillResetMs` arms the auto kill/reset countdown when the breaker
615
- * trips (0 = manual recovery only).
616
- *
617
- * Re-applies cleanly on every call: cancels a pending countdown when the
618
- * timeout is cleared or protection disabled, and re-arms if the breaker is
619
- * currently open under the new settings.
620
- */
621
- setBreakerConfig(cfg) {
622
- if (cfg.enabled !== void 0) this.breaker.setEnabled(cfg.enabled);
623
- if (cfg.autoKillResetMs !== void 0) this.autoKillResetMs = Math.max(0, cfg.autoKillResetMs);
624
- if (this.autoKillResetMs <= 0) {
625
- this._cancelAutoKillReset();
626
- return;
627
- }
628
- if (this.breaker.isEnabled && this.breaker.snapshot().state === "open") {
629
- this._armAutoKillReset();
630
- }
631
- }
632
- /**
633
- * Live countdown to the next auto kill/reset, or null when nothing is armed.
634
- * The TUI polls this on a 1s tick while armed so the statusline decrements.
635
- */
636
- getBreakerCountdown() {
637
- if (this.autoKillArmedAt === null || this.autoKillResetMs <= 0) return null;
638
- const elapsed = Date.now() - this.autoKillArmedAt;
639
- return {
640
- remainingMs: Math.max(0, this.autoKillResetMs - elapsed),
641
- totalMs: this.autoKillResetMs
642
- };
643
- }
644
- /**
645
- * Subscribe to countdown arm/cancel events. Returns an unsubscribe function.
646
- * Use {@link getBreakerCountdown} for the live ticking value between events.
647
- */
648
- onBreakerCountdownChange(listener) {
649
- this.breakerCountdownListeners.push(listener);
650
- return () => {
651
- this.breakerCountdownListeners = this.breakerCountdownListeners.filter((l) => l !== listener);
652
- };
653
- }
654
- _emitBreakerCountdown() {
655
- const snap = this.getBreakerCountdown();
656
- for (const l of this.breakerCountdownListeners) {
657
- try {
658
- l(snap);
659
- } catch {
660
- }
661
- }
662
- }
663
- /**
664
- * Arm the auto kill/reset countdown. Idempotent: re-arming resets the window
665
- * (a fresh trip after a failed half-open probe restarts the clock). No-op
666
- * when protection is off or no timeout is configured.
667
- */
668
- _armAutoKillReset() {
669
- if (this.autoKillResetMs <= 0 || !this.breaker.isEnabled) return;
670
- this._clearAutoKillTimer();
671
- this.autoKillArmedAt = Date.now();
672
- this.autoKillTimer = setTimeout(() => {
673
- this.autoKillTimer = null;
674
- this.autoKillArmedAt = null;
675
- this.killAll({ force: false, preserveBackground: true });
676
- this.breaker.forceReset();
677
- this._emitBreakerCountdown();
678
- }, this.autoKillResetMs);
679
- this.autoKillTimer.unref?.();
680
- this._emitBreakerCountdown();
681
- }
682
- _cancelAutoKillReset() {
683
- const wasArmed = this.autoKillArmedAt !== null;
684
- this._clearAutoKillTimer();
685
- if (wasArmed) {
686
- this.autoKillArmedAt = null;
687
- this._emitBreakerCountdown();
688
- }
689
- }
690
- _clearAutoKillTimer() {
691
- if (this.autoKillTimer !== null) {
692
- clearTimeout(this.autoKillTimer);
693
- this.autoKillTimer = null;
694
- }
695
- }
696
- /** Kill a single process by PID.
697
- *
698
- * On POSIX: sends SIGTERM to the *process group* (-pid) so that
699
- * runaway grandchild processes (`sleep 9999 & disown`) are also killed.
700
- * After `graceMs` a SIGKILL is sent if the process hasn't exited.
701
- *
702
- * On Windows: `child.kill()` maps to TerminateProcess — process groups
703
- * are not meaningfully supported. A second `force=true` call sends
704
- * SIGKILL (which maps to TerminateProcess again — the distinction is
705
- * in the exit code, not the signal).
706
- *
707
- * Returns true if the process was found and kill was attempted.
708
- */
709
- kill(pid, opts = {}) {
710
- this._pruneStale(pid);
711
- const p = this.processes.get(pid);
712
- if (!p) return false;
713
- if (p.killed && opts.force !== true) return true;
714
- if (p.protected && opts.includeProtected !== true) return false;
715
- if (opts.preserveBackground && p.background) return false;
716
- const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
717
- const isWin2 = os.platform() === "win32";
718
- if (isWin2) {
719
- const liveRealChild = p.child === null || p.child.exitCode === null && typeof p.child.pid === "number";
720
- const directFallback = () => {
721
- if (p.child && p.child.exitCode === null) {
722
- try {
723
- p.child.kill("SIGKILL");
724
- } catch {
725
- }
726
- }
727
- };
728
- if (liveRealChild && killWin32Tree(pid, {
729
- timeoutMs: Math.max(graceMs, WIN32_TASKKILL_TIMEOUT_MS),
730
- onSettled: directFallback
731
- })) {
732
- } else {
733
- this._killChildDirect(p, force ? "SIGKILL" : "SIGTERM");
734
- }
735
- p.killed = true;
736
- return true;
737
- }
738
- try {
739
- if (force) {
740
- this._killPosix(p, "SIGKILL");
741
- } else {
742
- this._killPosix(p, "SIGTERM");
743
- const timer = setTimeout(() => {
744
- if (this.processes.has(pid) && !p.child?.killed) {
745
- this._killPosix(p, "SIGKILL");
746
- }
747
- }, graceMs);
748
- timer.unref?.();
749
- }
750
- } catch {
751
- }
752
- p.killed = true;
753
- return true;
754
- }
755
- /**
756
- * Kill all tracked processes.
757
- * Returns the PIDs that were kill()ed.
758
- */
759
- killAll(opts = {}) {
760
- const pids = Array.from(this.processes.keys());
761
- const killed = [];
762
- const includeProtected = opts.includeProtected === true;
763
- for (const pid of pids) {
764
- const p = this.processes.get(pid);
765
- if (!p) continue;
766
- if (p.protected && !includeProtected) continue;
767
- if (opts.preserveBackground && p.background) continue;
768
- if (this.kill(pid, opts)) killed.push(pid);
769
- }
770
- return killed;
771
- }
772
- /**
773
- * Kill all processes for a specific session.
774
- * Returns the PIDs that were kill()ed.
775
- */
776
- killSession(sessionId, opts = {}) {
777
- const pids = this.bySession(sessionId).map((p) => p.pid);
778
- const killed = [];
779
- for (const pid of pids) {
780
- if (this.kill(pid, opts)) killed.push(pid);
781
- }
782
- return killed;
783
- }
784
- /**
785
- * Check whether a tracked process entry is stale — the child has exited
786
- * (exitCode !== null) AND it's been in the registry long enough that the
787
- * OS may have reused the PID for a new, unrelated process.
788
- *
789
- * P3 #24 (before-release.md): on POSIX, PIDs are reused after process
790
- * exit. If a tracked process exits but its 'close' event hasn't fired yet
791
- * (or was missed), the registry still holds the entry. A new process
792
- * gets the same PID, and PID-based lookups (get, kill, shouldBlockKill)
793
- * may incorrectly protect or target the wrong process.
794
- *
795
- * The 60s threshold is conservative — the OS typically waits much longer
796
- * before reusing a PID, but we want to clean up before that becomes a risk.
797
- */
798
- _isStaleEntry(entry) {
799
- if (entry.child === null) {
800
- if (Date.now() - entry.startedAt <= 6e4) return false;
801
- if (os.platform() === "win32") return false;
802
- try {
803
- process.kill(entry.pid, 0);
804
- return false;
805
- } catch (err) {
806
- return err.code !== "EPERM";
807
- }
808
- }
809
- return entry.child.exitCode !== null && Date.now() - entry.startedAt > 6e4;
810
- }
811
- /**
812
- * Remove a stale entry for a specific PID before any PID-based lookup.
813
- * This prevents PID reuse from causing the registry to act on a dead
814
- * process that has been replaced by a new one with the same PID.
815
- */
816
- _pruneStale(pid) {
817
- const entry = this.processes.get(pid);
818
- if (entry && this._isStaleEntry(entry)) {
819
- this.processes.delete(pid);
820
- }
821
- }
822
- /**
823
- * Remove every stale entry, not just one PID. `list()`/`stats()` — the
824
- * surfaces the TUI status bar and `/ps` poll — must prune too: a child
825
- * whose 'close' event never fires (e.g. Windows grandchildren holding stdio
826
- * open) would otherwise linger in the registry until someone looks up its
827
- * exact PID, and PID reuse meanwhile makes `get()`/`kill()` target the
828
- * wrong process. RAM-leak audit 2026-07-31, MEDIUM.
829
- */
830
- _pruneAllStale() {
831
- for (const [pid, entry] of this.processes) {
832
- if (this._isStaleEntry(entry)) this.processes.delete(pid);
833
- }
834
- }
835
- };
836
- var _registry;
837
- function getProcessRegistry() {
838
- if (!_registry) {
839
- _registry = new ProcessRegistryImpl();
840
- }
841
- return _registry;
842
- }
843
-
844
- // src/bash-kill-guard.ts
845
- import * as os3 from "node:os";
846
-
847
- // src/process-registry-persistent.ts
848
- import * as fs from "node:fs/promises";
849
- import * as os2 from "node:os";
850
- import { wstackGlobalRoot as wstackGlobalRoot3 } from "@wrongstack/core/utils";
851
- import * as path2 from "node:path";
852
- var REGISTRY_FILE = "process-registry.json";
853
- function toErrorMessage(err) {
854
- return err instanceof Error ? err.message : String(err);
855
- }
856
- function emitStructuredLog(level, event, message, error) {
857
- const payload = {
858
- level,
859
- event,
860
- message,
861
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
862
- };
863
- if (error !== void 0) {
864
- payload.error = toErrorMessage(error);
865
- }
866
- console.log(JSON.stringify(payload));
867
- }
868
- var HEARTBEAT_INTERVAL_MS = 5e3;
869
- var STALE_THRESHOLD_MS = 3e4;
870
- var LOCK_STALE_MS = 3e4;
871
- var LOCKFILE = ".process-registry.lock";
872
- function generateInstanceId() {
873
- const hostname2 = os2.hostname();
874
- const pid = process.pid;
875
- const random = Math.random().toString(36).slice(2, 8);
876
- return `${hostname2}:${pid}:${random}`;
877
- }
878
- function isNodeError(err) {
879
- return typeof err === "object" && err !== null && "code" in err;
880
- }
881
- async function acquireLock(lockfilePath, timeoutMs = 5e3) {
882
- const start = Date.now();
883
- const pidStr = String(process.pid);
884
- const hostStr = os2.hostname();
885
- try {
886
- await fs.mkdir(path2.dirname(lockfilePath), { recursive: true });
887
- } catch {
888
- }
889
- while (Date.now() - start < timeoutMs) {
890
- try {
891
- await fs.writeFile(lockfilePath, `${pidStr}:${hostStr}:${Date.now()}`, { flag: "wx" });
892
- return async () => {
893
- try {
894
- await fs.unlink(lockfilePath);
895
- } catch {
896
- }
897
- };
898
- } catch (err) {
899
- if (isNodeError(err) && err.code === "EEXIST") {
900
- try {
901
- const content = await fs.readFile(lockfilePath, "utf-8");
902
- const parts = content.split(":");
903
- const lockPid = parseInt(parts[0] ?? "0", 10);
904
- const lockTs = Number(parts[parts.length - 1]);
905
- const staleByAge = Number.isFinite(lockTs) && Date.now() - lockTs > LOCK_STALE_MS;
906
- let holderDead = false;
907
- if (process.platform !== "win32" && Number.isFinite(lockPid) && lockPid > 0) {
908
- try {
909
- process.kill(lockPid, 0);
910
- } catch {
911
- holderDead = true;
912
- }
913
- }
914
- if (holderDead || staleByAge) {
915
- await fs.unlink(lockfilePath).catch(() => {
916
- });
917
- continue;
918
- }
919
- } catch {
920
- await fs.unlink(lockfilePath).catch(() => {
921
- });
922
- continue;
923
- }
924
- await new Promise((r) => setTimeout(r, 100));
925
- continue;
926
- }
927
- throw err;
928
- }
929
- }
930
- throw new Error(`Failed to acquire lock after ${timeoutMs}ms`);
931
- }
932
- function freshRegistryData() {
933
- return {
934
- version: 1,
935
- instances: /* @__PURE__ */ new Map(),
936
- protectedPatterns: ["wrongstack", "node"],
937
- lastCleanup: Date.now()
938
- };
939
- }
940
- async function readRegistryFile(filePath) {
941
- let content;
942
- try {
943
- content = await fs.readFile(filePath, "utf-8");
944
- } catch (err) {
945
- if (isNodeError(err) && err.code === "ENOENT") return freshRegistryData();
946
- throw err;
947
- }
948
- try {
949
- const parsed = JSON.parse(content);
950
- if (!parsed || typeof parsed !== "object") return freshRegistryData();
951
- const base = freshRegistryData();
952
- return {
953
- version: 1,
954
- instances: Array.isArray(parsed.instances) ? new Map(parsed.instances) : base.instances,
955
- protectedPatterns: Array.isArray(parsed.protectedPatterns) ? parsed.protectedPatterns : base.protectedPatterns,
956
- lastCleanup: typeof parsed.lastCleanup === "number" ? parsed.lastCleanup : base.lastCleanup
957
- };
958
- } catch {
959
- return freshRegistryData();
960
- }
961
- }
962
- async function writeRegistryFile(filePath, data) {
963
- const tmpPath = `${filePath}.tmp.${process.pid}`;
964
- const content = JSON.stringify(
965
- data,
966
- (_k, v) => {
967
- if (v instanceof Map) {
968
- return Array.from(v.entries());
969
- }
970
- return v;
971
- },
972
- 2
973
- );
974
- await fs.writeFile(tmpPath, content, "utf-8");
975
- await fs.rename(tmpPath, filePath);
976
- }
977
- var PersistentProcessRegistry = class {
978
- instanceId;
979
- registryPath;
980
- lockPath;
981
- baseRegistry;
982
- heartbeatInterval = null;
983
- cleanupInterval = null;
984
- heartbeatRunning = false;
985
- cleanupRunning = false;
986
- isShuttingDown = false;
987
- onProcessExit = () => {
988
- this.runInBackground(
989
- this.syncToPersistent(),
990
- "process_registry.exit_sync_failed",
991
- "PersistentProcessRegistry: exit sync failed"
992
- );
993
- };
994
- constructor(baseRegistry) {
995
- this.instanceId = generateInstanceId();
996
- const globalRoot = wstackGlobalRoot3();
997
- this.registryPath = path2.join(globalRoot, REGISTRY_FILE);
998
- this.lockPath = path2.join(globalRoot, LOCKFILE);
999
- this.baseRegistry = baseRegistry ?? getProcessRegistry();
1000
- this.ensureDirectory().catch((err) => {
1001
- emitStructuredLog(
1002
- "warn",
1003
- "process_registry.dir_create_failed",
1004
- "PersistentProcessRegistry: failed to create .wrongstack directory",
1005
- err
1006
- );
1007
- });
1008
- }
1009
- async ensureDirectory() {
1010
- const dir = path2.dirname(this.registryPath);
1011
- try {
1012
- await fs.mkdir(dir, { recursive: true });
1013
- } catch (err) {
1014
- if (!isNodeError(err) || err.code !== "EEXIST") throw err;
1015
- }
1016
- }
1017
- runInBackground(operation, event, message) {
1018
- void operation.catch((err) => {
1019
- emitStructuredLog("warn", event, message, err);
1020
- });
1021
- }
1022
- /**
1023
- * Start the heartbeat and periodic cleanup tasks.
1024
- */
1025
- start() {
1026
- if (this.heartbeatInterval) return;
1027
- this.isShuttingDown = false;
1028
- this.heartbeat();
1029
- this.heartbeatInterval = setInterval(() => {
1030
- this.heartbeat();
1031
- }, HEARTBEAT_INTERVAL_MS);
1032
- this.heartbeatInterval.unref?.();
1033
- this.cleanupInterval = setInterval(() => {
1034
- this.cleanup();
1035
- }, STALE_THRESHOLD_MS);
1036
- this.cleanupInterval.unref?.();
1037
- this.registerMainProcess();
1038
- process.on("exit", this.onProcessExit);
1039
- }
1040
- /**
1041
- * Stop the heartbeat and clean up.
1042
- */
1043
- stop() {
1044
- this.isShuttingDown = true;
1045
- if (this.heartbeatInterval) {
1046
- clearInterval(this.heartbeatInterval);
1047
- this.heartbeatInterval = null;
1048
- }
1049
- if (this.cleanupInterval) {
1050
- clearInterval(this.cleanupInterval);
1051
- this.cleanupInterval = null;
1052
- }
1053
- process.off("exit", this.onProcessExit);
1054
- this.runInBackground(
1055
- this.syncToPersistent(),
1056
- "process_registry.stop_sync_failed",
1057
- "PersistentProcessRegistry: stop sync failed"
1058
- );
1059
- }
1060
- /**
1061
- * Register the main WrongStack process as protected.
1062
- */
1063
- registerMainProcess() {
1064
- const mainPid = process.pid;
1065
- this.runInBackground(
1066
- this.updatePersistentEntry({
1067
- pid: mainPid,
1068
- name: "wrongstack-main",
1069
- command: process.argv.slice(0, 3).join(" "),
1070
- startedAt: Date.now(),
1071
- lastHeartbeat: Date.now(),
1072
- instanceId: this.instanceId,
1073
- hostname: os2.hostname(),
1074
- protected: true,
1075
- spawnMode: "main",
1076
- parentPid: process.ppid,
1077
- platform: process.platform
1078
- }),
1079
- "process_registry.main_register_failed",
1080
- "PersistentProcessRegistry: failed to register main process"
1081
- );
1082
- }
1083
- /**
1084
- * Register a spawned child process with the persistent registry.
1085
- */
1086
- registerChildProcess(pid, name, command, sessionId, spawnMode = "spawn") {
1087
- const entry = {
1088
- pid,
1089
- name,
1090
- command,
1091
- startedAt: Date.now(),
1092
- lastHeartbeat: Date.now(),
1093
- instanceId: this.instanceId,
1094
- hostname: os2.hostname(),
1095
- protected: true,
1096
- // All WrongStack child processes are protected by default
1097
- spawnMode,
1098
- parentPid: process.pid,
1099
- platform: process.platform
1100
- };
1101
- if (sessionId) {
1102
- entry.sessionId = sessionId;
1103
- }
1104
- this.runInBackground(
1105
- this.updatePersistentEntry(entry),
1106
- "process_registry.child_register_failed",
1107
- "PersistentProcessRegistry: failed to register child process"
1108
- );
1109
- }
1110
- /**
1111
- * Update or add an entry in the persistent registry.
1112
- */
1113
- async updatePersistentEntry(entry) {
1114
- const release = await acquireLock(this.lockPath);
1115
- try {
1116
- const data = await readRegistryFile(this.registryPath);
1117
- data.instances.set(String(entry.pid), entry);
1118
- this.baseRegistry.register({
1119
- pid: entry.pid,
1120
- name: entry.name,
1121
- command: entry.command,
1122
- startedAt: entry.startedAt,
1123
- sessionId: entry.sessionId,
1124
- protected: entry.protected,
1125
- child: null
1126
- });
1127
- await writeRegistryFile(this.registryPath, data);
1128
- } finally {
1129
- await release();
1130
- }
1131
- }
1132
- /**
1133
- * Unregister a process from the persistent registry.
1134
- */
1135
- async unregister(pid) {
1136
- const release = await acquireLock(this.lockPath);
1137
- try {
1138
- const data = await readRegistryFile(this.registryPath);
1139
- data.instances.delete(String(pid));
1140
- await writeRegistryFile(this.registryPath, data);
1141
- } finally {
1142
- await release();
1143
- }
1144
- }
1145
- /**
1146
- * Send heartbeat to mark all this instance's processes as alive.
1147
- */
1148
- heartbeat() {
1149
- if (this.isShuttingDown || this.heartbeatRunning) return;
1150
- this.heartbeatRunning = true;
1151
- void this.syncToPersistent().catch((err) => {
1152
- emitStructuredLog(
1153
- "warn",
1154
- "process_registry.heartbeat_failed",
1155
- "PersistentProcessRegistry: heartbeat failed",
1156
- err
1157
- );
1158
- }).finally(() => {
1159
- this.heartbeatRunning = false;
1160
- });
1161
- }
1162
- cleanup() {
1163
- if (this.isShuttingDown || this.cleanupRunning) return;
1164
- this.cleanupRunning = true;
1165
- void this.cleanupStaleEntries().catch((err) => {
1166
- emitStructuredLog(
1167
- "warn",
1168
- "process_registry.periodic_cleanup_failed",
1169
- "PersistentProcessRegistry: periodic cleanup failed",
1170
- err
1171
- );
1172
- }).finally(() => {
1173
- this.cleanupRunning = false;
1174
- });
1175
- }
1176
- /**
1177
- * Sync this instance's processes to the persistent registry.
1178
- */
1179
- async syncToPersistent() {
1180
- const release = await acquireLock(this.lockPath);
1181
- try {
1182
- const data = await readRegistryFile(this.registryPath);
1183
- const now = Date.now();
1184
- const updatedInstances = /* @__PURE__ */ new Map();
1185
- for (const [_pidStr, entry] of data.instances) {
1186
- if (entry.instanceId === this.instanceId) {
1187
- entry.lastHeartbeat = now;
1188
- }
1189
- if (entry.instanceId === this.instanceId || now - entry.lastHeartbeat < STALE_THRESHOLD_MS) {
1190
- updatedInstances.set(_pidStr, entry);
1191
- }
1192
- }
1193
- data.instances = updatedInstances;
1194
- data.lastCleanup = now;
1195
- await writeRegistryFile(this.registryPath, data);
1196
- } catch (err) {
1197
- emitStructuredLog(
1198
- "warn",
1199
- "process_registry.sync_failed",
1200
- "PersistentProcessRegistry: sync failed",
1201
- err
1202
- );
1203
- } finally {
1204
- await release();
1205
- }
1206
- }
1207
- /**
1208
- * Remove entries for processes that are no longer running.
1209
- */
1210
- async cleanupStaleEntries() {
1211
- const release = await acquireLock(this.lockPath);
1212
- try {
1213
- const data = await readRegistryFile(this.registryPath);
1214
- const now = Date.now();
1215
- const stalePids = [];
1216
- for (const [_pidStr, entry] of data.instances) {
1217
- const age = now - entry.lastHeartbeat;
1218
- if (age > STALE_THRESHOLD_MS) {
1219
- try {
1220
- if (process.platform !== "win32") {
1221
- process.kill(entry.pid, 0);
1222
- } else {
1223
- emitStructuredLog(
1224
- "debug",
1225
- "process_registry.stale_pid_check",
1226
- `PersistentProcessRegistry: checking stale pid ${entry.pid} (${age}ms old)`
1227
- );
1228
- }
1229
- } catch {
1230
- stalePids.push(_pidStr);
1231
- }
1232
- }
1233
- }
1234
- if (stalePids.length > 0) {
1235
- for (const pidStr of stalePids) {
1236
- data.instances.delete(pidStr);
1237
- }
1238
- await writeRegistryFile(this.registryPath, data);
1239
- }
1240
- } catch (err) {
1241
- emitStructuredLog(
1242
- "warn",
1243
- "process_registry.cleanup_failed",
1244
- "PersistentProcessRegistry: cleanup failed",
1245
- err
1246
- );
1247
- } finally {
1248
- await release();
1249
- }
1250
- }
1251
- /**
1252
- * Check if a PID belongs to a WrongStack process and should be protected.
1253
- */
1254
- async isProtectedPid(pid) {
1255
- const release = await acquireLock(this.lockPath);
1256
- try {
1257
- const data = await readRegistryFile(this.registryPath);
1258
- const entry = data.instances.get(String(pid));
1259
- if (!entry) return false;
1260
- if (Date.now() - entry.lastHeartbeat > STALE_THRESHOLD_MS) {
1261
- return false;
1262
- }
1263
- return entry.protected;
1264
- } finally {
1265
- await release();
1266
- }
1267
- }
1268
- /**
1269
- * Get all protected PIDs from all WrongStack instances.
1270
- */
1271
- async getAllProtectedPids() {
1272
- const release = await acquireLock(this.lockPath);
1273
- try {
1274
- const data = await readRegistryFile(this.registryPath);
1275
- const now = Date.now();
1276
- const protectedPids = [];
1277
- for (const [_pidStr, entry] of data.instances) {
1278
- if (entry.protected && now - entry.lastHeartbeat < STALE_THRESHOLD_MS) {
1279
- protectedPids.push(entry.pid);
1280
- }
1281
- }
1282
- return protectedPids;
1283
- } finally {
1284
- await release();
1285
- }
1286
- }
1287
- /**
1288
- * Get complete status of all tracked processes across all instances.
1289
- */
1290
- async getGlobalStatus() {
1291
- const release = await acquireLock(this.lockPath);
1292
- try {
1293
- const data = await readRegistryFile(this.registryPath);
1294
- const now = Date.now();
1295
- const instances = /* @__PURE__ */ new Map();
1296
- let protectedCount = 0;
1297
- let staleCount = 0;
1298
- for (const [_pidStr, entry] of data.instances) {
1299
- const instanceEntries = instances.get(entry.instanceId) ?? [];
1300
- instanceEntries.push(entry);
1301
- instances.set(entry.instanceId, instanceEntries);
1302
- if (entry.protected) protectedCount++;
1303
- if (now - entry.lastHeartbeat > STALE_THRESHOLD_MS) staleCount++;
1304
- }
1305
- return {
1306
- instances,
1307
- totalProcesses: data.instances.size,
1308
- protectedCount,
1309
- staleCount
1310
- };
1311
- } finally {
1312
- await release();
1313
- }
1314
- }
1315
- /**
1316
- * Get the instance ID for this process.
1317
- */
1318
- getInstanceId() {
1319
- return this.instanceId;
1320
- }
1321
- /**
1322
- * Check if a kill command should be blocked.
1323
- * Returns true if the kill should be blocked (target is a WrongStack process).
1324
- */
1325
- async shouldBlockKill(pid) {
1326
- const protectedPids = await this.getAllProtectedPids();
1327
- return protectedPids.includes(pid);
1328
- }
1329
- /**
1330
- * Add a pattern-based protection rule.
1331
- * Processes whose command matches any protected pattern are protected.
1332
- */
1333
- async addProtectedPattern(pattern) {
1334
- const release = await acquireLock(this.lockPath);
1335
- try {
1336
- const data = await readRegistryFile(this.registryPath);
1337
- if (!data.protectedPatterns.includes(pattern)) {
1338
- data.protectedPatterns.push(pattern);
1339
- await writeRegistryFile(this.registryPath, data);
1340
- }
1341
- } finally {
1342
- await release();
1343
- }
1344
- }
1345
- };
1346
- var _persistentRegistry;
1347
- function getPersistentProcessRegistry() {
1348
- if (!_persistentRegistry) {
1349
- _persistentRegistry = new PersistentProcessRegistry();
1350
- }
1351
- return _persistentRegistry;
1352
- }
1353
-
1354
- // src/bash-kill-guard.ts
1355
- var isWin = os3.platform() === "win32";
1356
- var SCRIPT_KILL_RE = /^(?:\.\\|\.\/)?(?:kill|terminate|stop)\S*\.(?:ps1|bat|cmd|sh)(?:\s|$)/i;
1357
- var SCRIPT_KILL_RE_POSIX = /^(?:\.\/)?(?:kill|terminate|stop)\S*\.sh(?:\s|$)/i;
1358
- var SCRIPT_KILL_FALLBACK_RE = /^\S*(?:kill|terminate|stop)\S*\.(?:ps1|bat|cmd|sh)\b/i;
1359
- function extractKillCommand(command) {
1360
- const normalized = command.replace(/\s+/g, " ").trim();
1361
- const shellCMatch = normalized.match(/^.+?\s+-c\s+(['"])([\s\S]+)\1$/);
1362
- if (shellCMatch?.[2]) {
1363
- const inner = shellCMatch[2].trim();
1364
- return isKillRelatedCommand(inner) ? inner : null;
1365
- }
1366
- const shellCUnquoted = normalized.match(
1367
- /^.+?\s+-c\s+(kill(?:\s+-s\s+[a-zA-Z0-9]+|\s+-[a-zA-Z0-9]+)?\s+\d+)$/
1368
- );
1369
- if (shellCUnquoted?.[1]) {
1370
- return shellCUnquoted[1];
1371
- }
1372
- return null;
1373
- }
1374
- function isKillRelatedCommand(cmd) {
1375
- const normalized = cmd.toLowerCase().replace(/\s+/g, " ").trim();
1376
- if (isWin) {
1377
- if (/^taskkill\s/i.test(normalized)) return true;
1378
- if (/^tskill\s/i.test(normalized)) return true;
1379
- if (/^(stop-process|kill|stop)\s/i.test(normalized)) return true;
1380
- if (/^wmic\s+process\s/i.test(normalized) && /\bdelete\b/i.test(normalized)) return true;
1381
- if (SCRIPT_KILL_RE.test(normalized)) return true;
1382
- return false;
1383
- }
1384
- if (/^kill(\s|$)/.test(normalized)) return true;
1385
- if (/^(pkill|killall|pgrep|skill)\s/.test(normalized)) return true;
1386
- if (/^\/proc\/\d+\/(?:kill|fd)/.test(normalized)) return true;
1387
- if (SCRIPT_KILL_RE_POSIX.test(normalized)) return true;
1388
- return false;
1389
- }
1390
- function parseKillCommand(command) {
1391
- const normalized = command.replace(/\s+/g, " ").trim();
1392
- if (isWin) {
1393
- const hasTaskkillForce = /(?:^|\s)\/F(?=\s|$)/i.test(normalized);
1394
- const isSimpleTaskkill = /^taskkill\s+/i.test(normalized) && !/[|&<>]/.test(normalized);
1395
- const taskkillPidMatch = isSimpleTaskkill ? normalized.match(/(?:^|\s)\/PID\s+(\d+)(?=\s|$)/i) : null;
1396
- if (taskkillPidMatch?.[1]) {
1397
- return {
1398
- pid: parseInt(taskkillPidMatch[1], 10),
1399
- signal: hasTaskkillForce ? "FORCE" : "TERM",
1400
- isGroupKill: false,
1401
- isAllKill: false,
1402
- originalCommand: command
1403
- };
1404
- }
1405
- const taskkillImMatch = isSimpleTaskkill ? normalized.match(/(?:^|\s)\/IM\s+([^\s/]+)(?=\s|$)/i) : null;
1406
- if (taskkillImMatch?.[1]) {
1407
- return {
1408
- name: taskkillImMatch[1],
1409
- signal: hasTaskkillForce ? "FORCE" : "TERM",
1410
- isGroupKill: false,
1411
- isAllKill: false,
1412
- originalCommand: command
1413
- };
1414
- }
1415
- const taskkillFiMatch = isSimpleTaskkill ? normalized.match(/(?:^|\s)\/FI\s+"IMAGENAME\s+eq\s+([^"]+)"(?=\s|$)/i) : null;
1416
- if (taskkillFiMatch?.[1]) {
1417
- return {
1418
- name: taskkillFiMatch[1],
1419
- signal: hasTaskkillForce ? "FORCE" : "TERM",
1420
- isGroupKill: false,
1421
- isAllKill: false,
1422
- originalCommand: command
1423
- };
1424
- }
1425
- const tskillMatch = normalized.match(/^tskill\s+(\d+)/i);
1426
- if (tskillMatch?.[1]) {
1427
- return {
1428
- pid: parseInt(tskillMatch[1], 10),
1429
- signal: "TERM",
1430
- isGroupKill: false,
1431
- isAllKill: false,
1432
- originalCommand: command
1433
- };
1434
- }
1435
- const isStopProcIdCommand = /^(?:stop-process|kill)(?:\s+-(?:id|pid)\s+\d+|\s+-[a-zA-Z]+)+$/i.test(normalized);
1436
- const stopProcIdMatch = normalized.match(/(?:^|\s)-(?:id|pid)\s+(\d+)(?=\s|$)/i);
1437
- if (isStopProcIdCommand && stopProcIdMatch?.[1]) {
1438
- return {
1439
- pid: parseInt(stopProcIdMatch[1], 10),
1440
- signal: "FORCE",
1441
- isGroupKill: false,
1442
- isAllKill: false,
1443
- originalCommand: command
1444
- };
1445
- }
1446
- const killSignalOptionMatch = normalized.match(/^kill\s+-s\s+([a-zA-Z0-9]+)\s+(\d+)$/i);
1447
- if (killSignalOptionMatch?.[1] && killSignalOptionMatch[2]) {
1448
- return {
1449
- pid: parseInt(killSignalOptionMatch[2], 10),
1450
- signal: killSignalOptionMatch[1].toUpperCase(),
1451
- isGroupKill: false,
1452
- isAllKill: false,
1453
- originalCommand: command
1454
- };
1455
- }
1456
- const killPosixMatch = normalized.match(/^kill\s+(?:(-[a-zA-Z0-9]+)\s+)?(\d+)$/);
1457
- if (killPosixMatch?.[2]) {
1458
- const sig = killPosixMatch[1] ? killPosixMatch[1].slice(1).toUpperCase() : "TERM";
1459
- return {
1460
- pid: parseInt(killPosixMatch[2], 10),
1461
- signal: sig,
1462
- isGroupKill: false,
1463
- isAllKill: false,
1464
- originalCommand: command
1465
- };
1466
- }
1467
- const stopProcNameMatch = normalized.match(
1468
- /^(?:stop-process|kill)\s+-(?:name|n)\s+(?:['"]([a-zA-Z0-9_.-]+)['"]|([a-zA-Z0-9_.-]+))(?:\s|$)/i
1469
- );
1470
- const stopProcName = stopProcNameMatch?.[1] ?? stopProcNameMatch?.[2];
1471
- if (stopProcName) {
1472
- return {
1473
- name: stopProcName,
1474
- signal: "FORCE",
1475
- isGroupKill: false,
1476
- isAllKill: false,
1477
- originalCommand: command
1478
- };
1479
- }
1480
- const stopProcStandalone = normalized.match(
1481
- /^(?:stop-process|kill)\s+['"]?([a-zA-Z][a-zA-Z0-9_.-]+)['"]?$/i
1482
- );
1483
- if (stopProcStandalone?.[1]) {
1484
- return {
1485
- name: stopProcStandalone[1],
1486
- signal: "FORCE",
1487
- isGroupKill: false,
1488
- isAllKill: false,
1489
- originalCommand: command
1490
- };
1491
- }
1492
- const wmicMatch = normalized.match(
1493
- /^wmic\s+process\s+where\s+['"]?(?:name\s*=\s*['"]?)([a-zA-Z0-9_.-]+)/i
1494
- );
1495
- if (wmicMatch?.[1]) {
1496
- return {
1497
- name: wmicMatch[1],
1498
- signal: "FORCE",
1499
- isGroupKill: false,
1500
- isAllKill: false,
1501
- originalCommand: command
1502
- };
1503
- }
1504
- const wmicPidMatch = normalized.match(
1505
- /^wmic\s+process\s+where\s+['"]?processid\s*=\s*['"]?(\d+)/i
1506
- );
1507
- if (wmicPidMatch?.[1]) {
1508
- return {
1509
- pid: parseInt(wmicPidMatch[1], 10),
1510
- signal: "FORCE",
1511
- isGroupKill: false,
1512
- isAllKill: false,
1513
- originalCommand: command
1514
- };
1515
- }
1516
- const killScriptMatch = normalized.match(SCRIPT_KILL_RE);
1517
- if (killScriptMatch) {
1518
- return {
1519
- name: "kill-script",
1520
- // sentinel — isKillProtected always blocks "kill-script"
1521
- signal: "FORCE",
1522
- isGroupKill: false,
1523
- isAllKill: false,
1524
- originalCommand: command
1525
- };
1526
- }
1527
- return null;
1528
- }
1529
- const signalOptionMatch = normalized.match(/^kill\s+-s\s+([a-zA-Z0-9]+)\s+(\d+|-?\d+)$/i);
1530
- if (signalOptionMatch?.[1] && signalOptionMatch[2]) {
1531
- const pidOrGroup = signalOptionMatch[2];
1532
- const isGroupKill = pidOrGroup.startsWith("-");
1533
- return {
1534
- pid: parseInt(isGroupKill ? pidOrGroup.slice(1) : pidOrGroup, 10),
1535
- signal: signalOptionMatch[1].toUpperCase(),
1536
- isGroupKill,
1537
- isAllKill: false,
1538
- originalCommand: command
1539
- };
1540
- }
1541
- const simpleMatch = normalized.match(/^kill\s+(?:(-[a-zA-Z0-9]+)\s+)?(\d+|-?\d+)$/);
1542
- if (simpleMatch) {
1543
- const signal = simpleMatch[1] ?? "-TERM";
1544
- const pidOrGroup = simpleMatch[2];
1545
- if (!pidOrGroup) return null;
1546
- const isGroupKill = pidOrGroup.startsWith("-");
1547
- const pid = isGroupKill ? parseInt(pidOrGroup.slice(1), 10) : parseInt(pidOrGroup, 10);
1548
- return {
1549
- pid,
1550
- signal: signal.slice(1),
1551
- isGroupKill,
1552
- isAllKill: false,
1553
- originalCommand: command
1554
- };
1555
- }
1556
- const pkillMatch = normalized.match(/^pkill\s+(?:(-[a-zA-Z]+)\s+)?(.+)$/);
1557
- if (pkillMatch?.[2]) {
1558
- const name = pkillMatch[2];
1559
- const signalMatch = pkillMatch[1];
1560
- return {
1561
- name,
1562
- signal: signalMatch ? signalMatch.slice(1) : "TERM",
1563
- isGroupKill: false,
1564
- isAllKill: false,
1565
- originalCommand: command
1566
- };
1567
- }
1568
- const killallMatch = normalized.match(/^killall\s+(?:(-[a-zA-Z]+)\s+)?(.+)$/);
1569
- if (killallMatch?.[2]) {
1570
- const name = killallMatch[2];
1571
- const signalMatch = killallMatch[1];
1572
- return {
1573
- name,
1574
- signal: signalMatch ? signalMatch.slice(1) : "TERM",
1575
- isGroupKill: false,
1576
- isAllKill: false,
1577
- originalCommand: command
1578
- };
1579
- }
1580
- const pgrepMatch = normalized.match(/^pgrep\s+(.+)$/);
1581
- if (pgrepMatch) {
1582
- return null;
1583
- }
1584
- const posixScriptMatch = normalized.match(SCRIPT_KILL_RE_POSIX);
1585
- if (posixScriptMatch) {
1586
- return {
1587
- name: "kill-script",
1588
- signal: "FORCE",
1589
- isGroupKill: false,
1590
- isAllKill: false,
1591
- originalCommand: command
1592
- };
1593
- }
1594
- return null;
1595
- }
1596
- async function getProtectedEntries() {
1597
- const registry = getPersistentProcessRegistry();
1598
- const status = await registry.getGlobalStatus();
1599
- const entries = [];
1600
- for (const instanceEntries of status.instances.values()) {
1601
- for (const entry of instanceEntries) {
1602
- if (entry.protected && Date.now() - entry.lastHeartbeat < 3e4) {
1603
- entries.push(entry);
1604
- }
1605
- }
1606
- }
1607
- return entries;
1608
- }
1609
- async function isKillProtected(kill) {
1610
- const registry = getPersistentProcessRegistry();
1611
- if (kill.name === "kill-script") {
1612
- return true;
1613
- }
1614
- if (kill.name) {
1615
- const entries = await getProtectedEntries();
1616
- const killNameLower = kill.name.toLowerCase();
1617
- for (const entry of entries) {
1618
- if (entry.name?.toLowerCase().includes(killNameLower)) {
1619
- return true;
1620
- }
1621
- }
1622
- if (killNameLower.includes("wrongstack")) {
1623
- return true;
1624
- }
1625
- if (killNameLower.includes("node") && entries.length > 0) {
1626
- return true;
1627
- }
1628
- return false;
1629
- }
1630
- if (kill.isGroupKill) {
1631
- const protectedPids = await registry.getAllProtectedPids();
1632
- return protectedPids.length > 0;
1633
- }
1634
- if (kill.pid !== void 0) {
1635
- if (await registry.shouldBlockKill(kill.pid)) return true;
1636
- if (kill.pid === process.pid || kill.pid === process.ppid) return true;
1637
- return false;
1638
- }
1639
- return false;
1640
- }
1641
- async function checkAndBlockKillCommand(command) {
1642
- const normalized = command.replace(/\s+/g, " ").trim();
1643
- const killCmd = extractKillCommand(normalized) || (isKillRelatedCommand(normalized) ? normalized : null);
1644
- if (!killCmd) {
1645
- return { blocked: false };
1646
- }
1647
- const parsed = parseKillCommand(killCmd);
1648
- if (!parsed) {
1649
- if (killCmd.includes("kill") && /kill\s+.*\|/.test(killCmd)) {
1650
- return {
1651
- blocked: true,
1652
- reason: `Blocked: complex kill pipeline detected \u2014 "${killCmd.slice(0, 50)}..."`
1653
- };
1654
- }
1655
- if (SCRIPT_KILL_FALLBACK_RE.test(killCmd)) {
1656
- return {
1657
- blocked: true,
1658
- reason: `Blocked: script-based kill detected \u2014 "${killCmd.slice(0, 80)}" may target protected WrongStack processes (cannot inspect script body).`
1659
- };
1660
- }
1661
- return { blocked: false };
1662
- }
1663
- if (await isKillProtected(parsed)) {
1664
- let target;
1665
- if (parsed.name) {
1666
- target = `process name "${parsed.name}"`;
1667
- } else if (parsed.pid !== void 0) {
1668
- target = `PID ${parsed.pid}`;
1669
- } else {
1670
- target = "(unknown target)";
1671
- }
1672
- const signal = parsed.signal ? ` (${parsed.signal})` : "";
1673
- const groupNote = parsed.isGroupKill ? " (process group)" : "";
1674
- return {
1675
- blocked: true,
1676
- reason: `Blocked: kill${signal} ${target}${groupNote} targets a protected WrongStack process.`
1677
- };
1678
- }
1679
- return { blocked: false };
1680
- }
1681
-
1682
- // src/_shell-pick.ts
1683
- var POSIX_DEFAULT = "cmd";
1684
- function pickShell(platform4, command, env) {
1685
- if (platform4 !== "win32") return POSIX_DEFAULT;
1686
- const override = env.get("WRONGSTACK_SHELL")?.trim().toLowerCase();
1687
- if (override === "cmd" || override === "cmd.exe") return "cmd";
1688
- if (override === "powershell" || override === "powershell.exe") return "powershell";
1689
- if (override === "pwsh" || override === "pwsh.exe") return "pwsh";
1690
- if (looksLikePowerShell(command)) return "pwsh";
1691
- return "cmd";
1692
- }
1693
- function looksLikePowerShell(command) {
1694
- if (!command) return false;
1695
- const trimmed = command.trimStart();
1696
- if (/\.ps1\b/i.test(trimmed)) return true;
1697
- if (/^\s*#requires\s/i.test(trimmed)) return true;
1698
- if (/^\s*param\s*\(/i.test(trimmed)) return true;
1699
- if (/\$[\w:{]/i.test(trimmed)) return true;
1700
- if (/\$\(/.test(trimmed)) return true;
1701
- if (/@\s*['"]/.test(trimmed)) return true;
1702
- if (/&\s+\$/.test(trimmed)) return true;
1703
- if (/(^|\s)@\s*\(/.test(trimmed)) return true;
1704
- if (/(^|\s)@\{/.test(trimmed)) return true;
1705
- if (/(?:^|[\s[({,;])(?:-eq|-ne|-lt|-gt|-le|-ge|-like|-notlike|-match|-notmatch|-contains|-notcontains|-in|-notin|-and|-or|-not|-band|-bor|-bxor|-replace|-isplit|-csplit|-osplit|-join|-is|-as|-f)(?:$|[\s\])},;])/i.test(
1706
- trimmed
1707
- )) {
1708
- return true;
1709
- }
1710
- if (PS_VERB_RE.test(trimmed)) return true;
1711
- if (/(?:^|[\s;&|])(gci|gi|gp|gcm|gps)\b/i.test(trimmed)) {
1712
- return true;
1713
- }
1714
- if (looksLikePowerShellExtended(command)) return true;
1715
- return false;
1716
- }
1717
- function looksLikePowerShellExtended(command) {
1718
- if (!command) return false;
1719
- const trimmed = command.trimStart();
1720
- if (/(?:^|\s)[-/](?:WhatIf|Confirm|ErrorAction)(?::[^\s]+|\s|=|$)/i.test(trimmed)) {
1721
- return true;
1722
- }
1723
- if (/(?:^|[\s;&|])(Where-Object|ForEach-Object|Select-Object|Sort-Object|Group-Object|Measure-Object|Compare-Object|Tee-Object)(?:\s|$)/i.test(
1724
- trimmed
1725
- )) {
1726
- return true;
1727
- }
1728
- if (/\bWrite-(?:Host|Output|Error|Warning|Verbose|Debug|Information)(?:\s|$)/i.test(trimmed)) {
1729
- return true;
1730
- }
1731
- if (/HK(?:LM|CU|CR|U|CC|DD|PD):\\/i.test(trimmed)) return true;
1732
- if (/\[(?:string|int|bool|xml|double|float|decimal|char|byte|long|System\.)/i.test(trimmed)) {
1733
- return true;
1734
- }
1735
- if (/^\s*<#|#>\s*$/m.test(trimmed)) return true;
1736
- if (/(?:^|\s)[-//](?:AsPlainText|PipelineVariable|pv|FilterHashtable|OutVariable|ov)(?:\s|=|$)/i.test(
1737
- trimmed
1738
- )) {
1739
- return true;
1740
- }
1741
- return false;
1742
- }
1743
- function wrapPowerShellScript(command) {
1744
- const bootstrap = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8;$ConfirmPreference='None';$WhatIfPreference=$false";
1745
- return bootstrap + "\n$ErrorActionPreference='Stop'\n" + command + "\nif ($LASTEXITCODE -is [int]) { exit $LASTEXITCODE }";
1746
- }
1747
- var PS_VERB_RE = new RegExp(
1748
- // Boundaries: start-of-string, whitespace, `;`, `&`, `|`, `(`, `{`, `,`.
1749
- "(?:^|[\\s;&|\\(\\{,])(?:Get|Set|New|Remove|Add|Clear|Copy|Move|Rename|Test|Update|Write|Read|Push|Pop|Invoke|Start|Stop|Wait|Out|Format|Group|Measure|Compare|Resolve|ConvertTo|ConvertFrom|Convert|Import|Export|Select|Where|ForEach|Sort|Tee|Split|Join|Limit|Skip|Step|Trace|Debug|Register|Unregister|Enable|Disable|Restart|Suspend|Resume|Save|Open|Close|Lock|Unlock|Mount|Dismount|Enter|Exit|Use|Show|Hide|Find|Search|Watch|Initialize|Optimize|Compress|Expand|Merge|Checkpoint|Undo|Redo|Approve|Deny|Block|Grant|Revoke|Assert|Confirm|Receive|Send|Connect|Disconnect|Reset|Backup|Restore|Publish|Unpublish|Install|Uninstall|Build|Rebuild|Deploy|Submit|Process|Complete|Approve|Revoke|Pay|Refund|Decline|Receive|Send)-[A-Za-z][A-Za-z0-9]+(?:[\\-\\+][A-Za-z][A-Za-z0-9]+)*(?:$|[\\s\\-\\;\\&\\|\\(\\)\\{\\},])",
1750
- "i"
1751
- );
1752
- function shellArgs(shell) {
1753
- if (shell === "powershell" || shell === "pwsh") {
1754
- return ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", "-"];
1755
- }
1756
- return ["/c"];
1757
- }
1758
- function diagnoseBashism(command, shell) {
1759
- if (!command) return void 0;
1760
- const isCmd = shell === "cmd";
1761
- const hints = [];
1762
- const add = (h) => {
1763
- if (!hints.includes(h)) hints.push(h);
1764
- };
1765
- if (/\/dev\/null/.test(command)) {
1766
- add(
1767
- isCmd ? "use `nul` instead of `/dev/null` (e.g. `2>nul`)" : "use `$null` instead of `/dev/null` (e.g. `2>$null`)"
1768
- );
1769
- }
1770
- if (/(^|[;&|]\s*)export\s+[A-Za-z_]\w*=/.test(command)) {
1771
- add(
1772
- isCmd ? "set env vars with `set NAME=value`, not `export`" : "set env vars with `$env:NAME = 'value'`, not `export`"
1773
- );
1774
- }
1775
- if (/<<-?\s*['"]?[A-Za-z_]\w*/.test(command)) {
1776
- add(
1777
- isCmd ? "cmd has no heredocs \u2014 write the content to a file or use multiple `echo` lines" : "PowerShell has no heredocs \u2014 use a single-quoted here-string `@'\u2026'@` (closing `'@` at column 0)"
1778
- );
1779
- }
1780
- if (shell === "powershell" && /(&&|\|\|)/.test(command)) {
1781
- add(
1782
- "Windows PowerShell 5.1 has no `&&`/`||` \u2014 separate commands with `;` (check `$LASTEXITCODE`)"
1783
- );
1784
- }
1785
- if (/\brm\s+-[A-Za-z]*[rf]/.test(command)) {
1786
- add(
1787
- isCmd ? "`rm` is not a cmd builtin \u2014 use `del` (files) or `rmdir /s /q` (dirs)" : "use `Remove-Item -Recurse -Force` \u2014 the `rm -rf` bash flags don't exist in PowerShell"
1788
- );
1789
- }
1790
- if (/\bwhich\s+\S/.test(command)) {
1791
- add(
1792
- isCmd ? "use `where <cmd>` instead of `which`" : "use `Get-Command <cmd>` instead of `which`"
1793
- );
1794
- }
1795
- if (hints.length === 0) return void 0;
1796
- const label = isCmd ? "cmd.exe" : shell === "pwsh" ? "PowerShell 7" : "Windows PowerShell";
1797
- return `[wrongstack] This command failed and contains bash/POSIX syntax that ${label} does not accept \u2014 ${hints.join("; ")}. Rewrite it in ${isCmd ? "cmd" : "PowerShell"} syntax and retry.`;
1798
- }
1799
-
1800
- // src/_win32-resolve.ts
1801
- import * as fs2 from "node:fs";
1802
- import * as path3 from "node:path";
1803
- function resolveWin32Command(cmd) {
1804
- if (process.platform !== "win32") return cmd;
1805
- if (cmd.includes("/") || cmd.includes("\\") || path3.extname(cmd.replace(/\//g, "\\"))) {
1806
- return cmd;
1807
- }
1808
- const pathext = (process.env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC").toLowerCase().split(";");
1809
- const pathDirs = (process.env["PATH"] ?? "").split(path3.delimiter);
1810
- for (const dir of pathDirs) {
1811
- const base = path3.join(dir, cmd);
1812
- for (const ext of pathext) {
1813
- const full = `${base}${ext}`;
1814
- try {
1815
- fs2.accessSync(full, fs2.constants.X_OK);
1816
- return full;
1817
- } catch {
1818
- }
1819
- }
1820
- }
1821
- return cmd;
1822
- }
1823
- function resolvePowerShell(cmd) {
1824
- if (process.platform !== "win32") return cmd;
1825
- const lower = cmd.toLowerCase();
1826
- if (lower !== "pwsh" && lower !== "powershell" && lower !== "pwsh.exe" && lower !== "powershell.exe") {
1827
- return resolveWin32Command(cmd);
1828
- }
1829
- const primary = lower.startsWith("pwsh") ? "pwsh" : "powershell";
1830
- const fallback = lower.startsWith("pwsh") ? "powershell" : "pwsh";
1831
- const resolved = resolveWin32Command(primary);
1832
- if (resolved === primary) {
1833
- const fb = resolveWin32Command(fallback);
1834
- return fb === fallback ? cmd : fb;
1835
- }
1836
- return resolved;
1837
- }
1838
-
1839
- // src/bash.ts
1840
- var MAX_OUTPUT = 32768;
1841
- var DEFAULT_TIMEOUT_MS = 3e5;
1842
- var STREAM_FLUSH_INTERVAL_MS = 200;
1843
- var STREAM_FLUSH_BYTES = 4 * 1024;
1844
- var MAX_QUEUE_CHUNKS = 500;
1845
- var bashTool = {
1846
- name: "bash",
1847
- category: "Shell",
1848
- description: "Execute an arbitrary command in the user's default shell (bash/zsh/pwsh/cmd). stdout and stderr are merged into one stream. This is the most powerful and dangerous tool \u2014 it gives the model full access to the developer's machine. Prefer specialized tools whenever possible.",
1849
- usageHint: "SECURITY WARNING: This tool runs with the full privileges of the current user.\n\nBest practices for the model:\n- Strongly prefer `exec` for known safe commands (node, npm, pnpm, tsc, git, etc.).\n- Use bash only when you genuinely need shell features (pipes, redirection, complex one-liners).\n- Prefer single focused commands over huge `&&` chains.\n- Use `background: true` only for long-running processes (dev servers, watchers).\n- The working directory is the session working dir (changed via `set_working_dir`), defaulting to the project root.\n- Output may be truncated in the middle for very large results.",
1850
- selection: {
1851
- doNotUseWhen: "the command is allowlisted and does not require pipes, redirection, or shell expansion.",
1852
- useInstead: ["exec"]
1853
- },
1854
- permission: "confirm",
1855
- mutating: true,
1856
- riskTier: "destructive",
1857
- icon: "terminal",
1858
- // Trust rules match on the literal `command` string. Without subjectKey
1859
- // the policy heuristic would have done the same here, but declaring it
1860
- // explicitly removes the implicit cross-tool aliasing.
1861
- subjectKey: "command",
1862
- capabilities: ["shell.arbitrary"],
1863
- // Executor-level abort ceiling. Must sit ABOVE the per-call `timeout_ms`
1864
- // ceiling (600_000): the tool's own timer tree-kills and returns a
1865
- // structured `timed_out: true` result, while the executor's
1866
- // AbortSignal.timeout is a blunt abort. The old value (300_000) meant any
1867
- // timeout_ms > 5min was silently cut short by the executor. The 10s margin
1868
- // covers the kill/teardown window. (The executor additionally clamps to
1869
- // config `tools.maxToolTimeoutMs`.)
1870
- timeoutMs: 61e4,
1871
- maxOutputBytes: MAX_OUTPUT,
1872
- estimatedDurationMs: 3e4,
1873
- inputSchema: {
1874
- type: "object",
1875
- properties: {
1876
- command: {
1877
- type: "string",
1878
- description: "The exact shell command to run. Prefer simple, focused commands."
1879
- },
1880
- timeout_ms: {
1881
- type: "integer",
1882
- description: "Optional timeout for this specific command in milliseconds (default 300000, max 600000)."
1883
- },
1884
- background: {
1885
- type: "boolean",
1886
- description: "If true, launch the process in the background and return the PID immediately."
1887
- }
1888
- },
1889
- required: ["command"]
1890
- },
1891
- async execute(input, ctx, opts) {
1892
- let final;
1893
- const executeStream = bashTool.executeStream;
1894
- if (!executeStream) throw new Error("bashTool: stream execution unavailable");
1895
- for await (const ev of executeStream(input, ctx, opts)) {
1896
- if (ev.type === "final") final = ev.output;
1897
- }
1898
- if (!final) throw new Error("bash: stream ended without final event");
1899
- return final;
1900
- },
1901
- async *executeStream(input, ctx, opts) {
1902
- if (!input?.command) throw new Error("bash: command is required");
1903
- const registry = getProcessRegistry();
1904
- const bypassBreaker = !!input.background;
1905
- if (!registry.beforeCall(bypassBreaker)) {
1906
- yield {
1907
- type: "final",
1908
- output: {
1909
- output: "",
1910
- exit_code: 1,
1911
- timed_out: false,
1912
- pid: null,
1913
- error: "bash: circuit breaker open \u2014 too many consecutive failures or slow calls. Use /kill to inspect or /kill reset to recover."
1914
- }
1915
- };
1916
- return;
1917
- }
1918
- const killCheck = await checkAndBlockKillCommand(input.command);
1919
- if (killCheck.blocked) {
1920
- yield {
1921
- type: "final",
1922
- output: {
1923
- output: "",
1924
- exit_code: 1,
1925
- timed_out: false,
1926
- pid: null,
1927
- error: killCheck.reason || "Kill command blocked: targets a protected WrongStack process."
1928
- }
1929
- };
1930
- return;
1931
- }
1932
- const PIPE_TO_SHELL_PATTERN = /\|\s*(sh|bash|ksh|zsh|fish|cmd|powershell|pwsh)/i;
1933
- const pipeToShellNote = PIPE_TO_SHELL_PATTERN.test(input.command) ? "\n\n[wrongstack] Caution: this command pipes output into a shell interpreter (pipe-to-shell). Piped content executes as arbitrary code \u2014 review the source before trusting the result, and prefer downloading to a file and inspecting it first." : "";
1934
- const timeoutMs = Math.max(1, Math.min(input.timeout_ms ?? DEFAULT_TIMEOUT_MS, 6e5));
1935
- const isWin2 = os4.platform() === "win32";
1936
- let plan;
1937
- let winShellKind;
1938
- if (isWin2) {
1939
- const shell2 = pickShell("win32", input.command, {
1940
- get: (k) => process.env[k]
1941
- });
1942
- winShellKind = shell2;
1943
- const bin = shell2 === "powershell" ? resolvePowerShell("powershell.exe") : shell2 === "pwsh" ? resolvePowerShell("pwsh.exe") : process.env["COMSPEC"] ?? "cmd.exe";
1944
- plan = {
1945
- bin,
1946
- argv: shellArgs(shell2),
1947
- useStdin: shell2 === "powershell" || shell2 === "pwsh",
1948
- stdinBody: shell2 === "powershell" || shell2 === "pwsh" ? wrapPowerShellScript(input.command) : void 0
1949
- };
1950
- } else {
1951
- const explicit = process.env["WRONGSTACK_SHELL"];
1952
- let bin;
1953
- if (explicit) bin = explicit;
1954
- else {
1955
- const fromEnv = process.env["SHELL"];
1956
- if (fromEnv) {
1957
- const name = fromEnv.split("/").pop() ?? "";
1958
- if (["bash", "zsh", "sh", "dash", "fish"].includes(name)) bin = fromEnv;
1959
- else bin = "/bin/bash";
1960
- } else bin = "/bin/bash";
1961
- }
1962
- plan = { bin, argv: ["-c"], useStdin: false, stdinBody: void 0 };
1963
- }
1964
- const shell = plan.bin;
1965
- const args = plan.useStdin ? [...plan.argv] : [...plan.argv, input.command];
1966
- const env = buildChildEnv(ctx.session?.id);
1967
- const spawnCwd = ctx.workingDir ?? ctx.projectRoot;
1968
- const detached = !isWin2;
1969
- const startedAt = Date.now();
1970
- if (input.background) {
1971
- const child2 = spawn2(shell, args, {
1972
- cwd: spawnCwd,
1973
- env,
1974
- // PowerShell takes the script on stdin (no argv quoting); cmd.exe
1975
- // and POSIX shells ignore stdin when given the command inline.
1976
- stdio: [plan.useStdin ? "pipe" : "ignore", "ignore", "ignore"],
1977
- // win32: CreateProcess IGNORES CREATE_NO_WINDOW (windowsHide) when
1978
- // DETACHED_PROCESS (detached: true) is set, so the console-less
1979
- // cmd.exe's grandchildren (node, dev servers) each allocate a fresh
1980
- // VISIBLE console window. detached: false lets CREATE_NO_WINDOW
1981
- // apply: the child gets a hidden console that grandchildren inherit.
1982
- // Windows children survive parent exit either way. POSIX keeps
1983
- // detached for the process-group kill semantics.
1984
- detached: !isWin2,
1985
- windowsHide: true
1986
- });
1987
- if (plan.useStdin) {
1988
- try {
1989
- child2.stdin?.write(plan.stdinBody ?? input.command);
1990
- child2.stdin?.end();
1991
- } catch {
1992
- }
1993
- }
1994
- const pid2 = child2.pid;
1995
- const stdoutBytes2 = 0;
1996
- const stderrBytes2 = 0;
1997
- let telemetryCompleted2 = false;
1998
- emitProcessStarted({
1999
- ...pid2 !== void 0 ? { pid: pid2 } : {},
2000
- parentPid: process.pid,
2001
- command: redactCommand(`${shell} ${args.join(" ")}`),
2002
- args: redactCommand(args.join(" ")).split(" ").filter(Boolean),
2003
- cwd: spawnCwd,
2004
- background: true,
2005
- startedAt: new Date(startedAt).toISOString()
2006
- });
2007
- const completeBackground = (exitCode, signal) => {
2008
- if (telemetryCompleted2) return;
2009
- telemetryCompleted2 = true;
2010
- emitProcessCompleted({
2011
- ...pid2 !== void 0 ? { pid: pid2 } : {},
2012
- exitCode,
2013
- ...signal ? { signal } : {},
2014
- durationMs: Date.now() - startedAt,
2015
- stdoutBytes: stdoutBytes2,
2016
- stderrBytes: stderrBytes2,
2017
- timedOut: false,
2018
- endedAt: (/* @__PURE__ */ new Date()).toISOString()
2019
- });
2020
- };
2021
- if (typeof pid2 === "number") {
2022
- registry.register({
2023
- pid: pid2,
2024
- name: "bash",
2025
- command: redactCommand(input.command),
2026
- startedAt: Date.now(),
2027
- sessionId: ctx.session?.id,
2028
- child: child2,
2029
- processGroupLeader: detached && child2.pid === pid2,
2030
- background: true
2031
- });
2032
- child2.on("close", () => registry.unregister(pid2));
2033
- }
2034
- child2.on("error", () => {
2035
- if (typeof pid2 === "number") registry.unregister(pid2);
2036
- registry.afterCall(Date.now() - startedAt, true, bypassBreaker);
2037
- completeBackground(1);
2038
- });
2039
- child2.on("close", (code, signal) => {
2040
- registry.afterCall(Date.now() - startedAt, false, bypassBreaker);
2041
- completeBackground(code ?? (signal ? 1 : 0), signal ?? void 0);
2042
- });
2043
- if (typeof pid2 === "number") child2.unref();
2044
- yield {
2045
- type: "final",
2046
- output: {
2047
- // Background runs have no captured output; the pipe-to-shell caution
2048
- // (when present) is the only thing worth surfacing.
2049
- output: pipeToShellNote.trim(),
2050
- exit_code: null,
2051
- timed_out: false,
2052
- pid: pid2
2053
- }
2054
- };
2055
- ctx.recordSideEffect?.({
2056
- toolUseId: `bash-bg-${Date.now()}`,
2057
- toolName: "bash",
2058
- ts: (/* @__PURE__ */ new Date()).toISOString(),
2059
- input: { command: redactCommand(input.command), background: true },
2060
- outcome: `launched (pid ${pid2 ?? "unknown"})`,
2061
- risk: "shell"
2062
- });
2063
- return;
2064
- }
2065
- const child = spawn2(shell, args, {
2066
- cwd: spawnCwd,
2067
- env,
2068
- // PowerShell takes the script on stdin (no argv quoting); cmd.exe
2069
- // and POSIX shells ignore stdin when given the command inline.
2070
- stdio: [plan.useStdin ? "pipe" : "ignore", "pipe", "pipe"],
2071
- detached,
2072
- windowsHide: true,
2073
- ...isWin2 ? {} : { signal: opts.signal }
2074
- });
2075
- if (plan.useStdin) {
2076
- try {
2077
- child.stdin?.write(plan.stdinBody ?? input.command);
2078
- child.stdin?.end();
2079
- } catch {
2080
- }
2081
- }
2082
- const pid = child.pid;
2083
- let stdoutBytes = 0;
2084
- let stderrBytes = 0;
2085
- let telemetryCompleted = false;
2086
- emitProcessStarted({
2087
- ...pid !== void 0 ? { pid } : {},
2088
- parentPid: process.pid,
2089
- command: redactCommand(`${shell} ${args.join(" ")}`),
2090
- args: redactCommand(args.join(" ")).split(" ").filter(Boolean),
2091
- cwd: spawnCwd,
2092
- background: false,
2093
- startedAt: new Date(startedAt).toISOString()
2094
- });
2095
- const completeForeground = (exitCode, signal) => {
2096
- if (telemetryCompleted) return;
2097
- telemetryCompleted = true;
2098
- emitProcessCompleted({
2099
- ...pid !== void 0 ? { pid } : {},
2100
- exitCode,
2101
- ...signal ? { signal } : {},
2102
- durationMs: Date.now() - startedAt,
2103
- stdoutBytes,
2104
- stderrBytes,
2105
- timedOut,
2106
- endedAt: (/* @__PURE__ */ new Date()).toISOString()
2107
- });
2108
- };
2109
- if (typeof pid === "number") {
2110
- registry.register({
2111
- pid,
2112
- name: "bash",
2113
- command: redactCommand(input.command),
2114
- startedAt: Date.now(),
2115
- sessionId: ctx.session?.id,
2116
- child,
2117
- processGroupLeader: detached && child.pid === pid
2118
- });
2119
- }
2120
- let buf = "";
2121
- let pending = "";
2122
- let timedOut = false;
2123
- const timers = [];
2124
- const spool = createOutputSpool({ tool: "bash", thresholdBytes: MAX_OUTPUT });
2125
- function killWithTimeout(child2, timeoutMs2) {
2126
- if (isWin2) {
2127
- if (typeof child2.pid === "number" && child2.exitCode === null) {
2128
- const attempted = registry.kill(child2.pid, { force: true, graceMs: timeoutMs2 });
2129
- if (!attempted) {
2130
- try {
2131
- child2.kill();
2132
- } catch {
2133
- }
2134
- }
2135
- } else {
2136
- try {
2137
- child2.kill();
2138
- } catch {
2139
- }
2140
- }
2141
- return;
2142
- }
2143
- if (typeof child2.pid === "number") {
2144
- registry.kill(child2.pid, { graceMs: timeoutMs2 });
2145
- } else {
2146
- try {
2147
- child2.kill("SIGTERM");
2148
- } catch {
2149
- }
2150
- const killTimer = setTimeout(() => {
2151
- try {
2152
- child2.kill("SIGKILL");
2153
- } catch {
2154
- }
2155
- }, timeoutMs2);
2156
- timers.push(killTimer);
2157
- killTimer.unref?.();
2158
- }
2159
- }
2160
- const timer = setTimeout(() => {
2161
- timedOut = true;
2162
- killWithTimeout(child, 2e3);
2163
- }, timeoutMs);
2164
- timers.push(timer);
2165
- timer.unref?.();
2166
- const onAbort = () => killWithTimeout(child, 2e3);
2167
- if (isWin2) {
2168
- if (opts.signal.aborted) onAbort();
2169
- else opts.signal.addEventListener("abort", onAbort, { once: true });
2170
- }
2171
- const queue = [];
2172
- let resolveNext = null;
2173
- const push = (c) => {
2174
- if (resolveNext) {
2175
- const r = resolveNext;
2176
- resolveNext = null;
2177
- r(c);
2178
- } else {
2179
- queue.push(c);
2180
- }
2181
- };
2182
- const next = () => new Promise((resolve) => {
2183
- const c = queue.shift();
2184
- if (c) resolve(c);
2185
- else resolveNext = resolve;
2186
- });
2187
- let lastFlush = Date.now();
2188
- const flush = () => {
2189
- if (pending.length === 0) return null;
2190
- const text = pending;
2191
- pending = "";
2192
- lastFlush = Date.now();
2193
- return text;
2194
- };
2195
- let paused = false;
2196
- const pauseIfFlooded = () => {
2197
- if (!paused && queue.length >= MAX_QUEUE_CHUNKS) {
2198
- paused = true;
2199
- child.stdout?.pause();
2200
- child.stderr?.pause();
2201
- }
2202
- };
2203
- const resumeIfDrained = () => {
2204
- if (paused && queue.length < MAX_QUEUE_CHUNKS) {
2205
- paused = false;
2206
- child.stdout?.resume();
2207
- child.stderr?.resume();
2208
- }
2209
- };
2210
- const stdoutDecoder = new StringDecoder("utf8");
2211
- const stderrDecoder = new StringDecoder("utf8");
2212
- const onData = (chunk, stream) => {
2213
- const text = (stream === "stdout" ? stdoutDecoder : stderrDecoder).write(chunk);
2214
- if (stream === "stdout") stdoutBytes += chunk.byteLength;
2215
- else stderrBytes += chunk.byteLength;
2216
- emitProcessOutput({ pid, stream, chunk });
2217
- if (buf.length < MAX_OUTPUT) {
2218
- buf += text.slice(0, MAX_OUTPUT - buf.length);
2219
- }
2220
- spool.write(text);
2221
- pending += text;
2222
- push({ kind: "data", text });
2223
- pauseIfFlooded();
2224
- };
2225
- const onStdoutData = (chunk) => onData(chunk, "stdout");
2226
- const onStderrData = (chunk) => onData(chunk, "stderr");
2227
- child.stdout?.on("data", onStdoutData);
2228
- child.stderr?.on("data", onStderrData);
2229
- child.on("error", (err) => {
2230
- for (const t of timers) clearTimeout(t);
2231
- registry.afterCall(Date.now() - startedAt, true);
2232
- completeForeground(1);
2233
- push({ kind: "error", err });
2234
- });
2235
- child.on("close", (code, signal) => {
2236
- for (const t of timers) clearTimeout(t);
2237
- if (typeof pid === "number") registry.unregister(pid);
2238
- registry.afterCall(Date.now() - startedAt, code !== 0 && code !== null);
2239
- completeForeground(timedOut ? 124 : code ?? (signal ? 1 : 0), signal ?? void 0);
2240
- const tail = stdoutDecoder.end() + stderrDecoder.end();
2241
- if (tail) {
2242
- if (buf.length < MAX_OUTPUT) buf += tail.slice(0, MAX_OUTPUT - buf.length);
2243
- spool.write(tail);
2244
- pending += tail;
2245
- }
2246
- push({ kind: "end", code });
2247
- });
2248
- try {
2249
- while (true) {
2250
- const c = await next();
2251
- resumeIfDrained();
2252
- if (c.kind === "error") throw c.err;
2253
- if (c.kind === "end") {
2254
- const remainder = flush();
2255
- if (remainder !== null) {
2256
- yield { type: "partial_output", text: remainder };
2257
- }
2258
- const spooled = spool.finalize();
2259
- const hint = !timedOut && typeof c.code === "number" && c.code !== 0 && winShellKind ? diagnoseBashism(input.command, winShellKind) : void 0;
2260
- yield {
2261
- type: "final",
2262
- output: {
2263
- output: normalizeCommandOutput(buf) + (spooled ? spoolNote(spooled) : "") + (hint ? `
2264
-
2265
- ${hint}` : "") + pipeToShellNote,
2266
- exit_code: c.code,
2267
- timed_out: timedOut
2268
- }
2269
- };
2270
- ctx.recordSideEffect?.({
2271
- toolUseId: `bash-${Date.now()}`,
2272
- toolName: "bash",
2273
- ts: (/* @__PURE__ */ new Date()).toISOString(),
2274
- input: { command: redactCommand(input.command) },
2275
- outcome: timedOut ? `timed out (exit ${c.code})` : `exit ${c.code}`,
2276
- risk: "shell"
2277
- });
2278
- return;
2279
- }
2280
- const now = Date.now();
2281
- if (pending.length >= STREAM_FLUSH_BYTES || now - lastFlush >= STREAM_FLUSH_INTERVAL_MS) {
2282
- const text = flush();
2283
- if (text) yield { type: "partial_output", text };
2284
- }
2285
- }
2286
- } finally {
2287
- for (const t of timers) clearTimeout(t);
2288
- spool.finalize();
2289
- if (isWin2) opts.signal.removeEventListener("abort", onAbort);
2290
- child.stdout?.off("data", onStdoutData);
2291
- child.stderr?.off("data", onStderrData);
2292
- child.stdout?.destroy();
2293
- child.stderr?.destroy();
2294
- if (child.exitCode === null && !child.killed) {
2295
- if (typeof pid === "number") registry.kill(pid, { force: true });
2296
- else killWithTimeout(child, 2e3);
2297
- }
2298
- }
2299
- },
2300
- /**
2301
- * Tool-level teardown fired by `ToolExecutor.runToolCleanup()` when the
2302
- * tool's run is aborted/timeout'd. The generator's `finally` block above
2303
- * already force-kills the direct child, but that only runs if the
2304
- * executor closes the async iterator (via `iter.return()`). When the
2305
- * executor tears down without iterating — or a re-entrant abort races
2306
- * with the generator — a bash-spawned process tree can survive in the
2307
- * ProcessRegistry with `killed === false`, continuing to write files,
2308
- * consume CPU, or hold inherited stdio pipes open for the rest of the
2309
- * session.
2310
- *
2311
- * This is the defensive layer the executor calls via `tool.cleanup()`
2312
- * (see `types/tool.ts`): kill every bash-owned process still tracked
2313
- * for this session that hasn't exited yet. `registry.kill()` already
2314
- * handles process-group / taskkill tree-kill and the SIGTERM→SIGKILL
2315
- * grace window, so this just scopes the registry's existing kill path
2316
- * to "this session's runaway bash children". Idempotent — a process
2317
- * that already exited is skipped by `kill()` (it returns false), and a
2318
- * `protected` infrastructure process (dev server the user intentionally
2319
- * backgrounded) is left alone by design.
2320
- */
2321
- async cleanup(_input, ctx) {
2322
- const registry = getProcessRegistry();
2323
- const sessionId = ctx.session?.id;
2324
- if (!sessionId) return;
2325
- for (const entry of registry.bySession(sessionId)) {
2326
- if (entry.name !== "bash") continue;
2327
- if (entry.child && entry.child.exitCode !== null) continue;
2328
- if (entry.background) continue;
2329
- if (entry.protected) continue;
2330
- registry.kill(entry.pid, { force: true });
2331
- }
2332
- }
2333
- };
2
+ bashTool
3
+ } from "./chunk-FGOABE4Z.js";
4
+ import "./chunk-BTSFTGIL.js";
5
+ import "./chunk-ZIGAZFWE.js";
6
+ import "./chunk-2TFQDEPU.js";
7
+ import "./chunk-3PVYQFRQ.js";
8
+ import "./chunk-HFXSNKCV.js";
9
+ import "./chunk-V43EQ6VR.js";
10
+ import "./chunk-D33S4RQG.js";
2334
11
  export {
2335
12
  bashTool
2336
13
  };