@wrongstack/tools 0.313.0 → 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 (134) hide show
  1. package/dist/audit.js +10 -4055
  2. package/dist/bash.js +9 -2308
  3. package/dist/batch-tool-use.js +2 -187
  4. package/dist/browser/index.js +25 -1339
  5. package/dist/builtin.js +69 -33949
  6. package/dist/chunk-2CTB3UK5.js +197 -0
  7. package/dist/chunk-2ME7ZWDD.js +1272 -0
  8. package/dist/chunk-2TFQDEPU.js +113 -0
  9. package/dist/chunk-2ZCJNKFE.js +315 -0
  10. package/dist/chunk-3PVYQFRQ.js +472 -0
  11. package/dist/chunk-3QMQBO5Z.js +89 -0
  12. package/dist/chunk-42AKKX7O.js +385 -0
  13. package/dist/chunk-42SKEETB.js +113 -0
  14. package/dist/chunk-4BHUSMNL.js +104 -0
  15. package/dist/chunk-4I4LWFOO.js +431 -0
  16. package/dist/chunk-553IQUMO.js +478 -0
  17. package/dist/chunk-55KF77OK.js +1944 -0
  18. package/dist/chunk-6HLZK37X.js +359 -0
  19. package/dist/chunk-6RNIFLG4.js +305 -0
  20. package/dist/chunk-A6BRWIXN.js +317 -0
  21. package/dist/chunk-AHHDWNXC.js +200 -0
  22. package/dist/chunk-B2CIOKWP.js +899 -0
  23. package/dist/chunk-BTSFTGIL.js +7 -0
  24. package/dist/chunk-D33S4RQG.js +222 -0
  25. package/dist/chunk-DIJKHSUO.js +134 -0
  26. package/dist/chunk-DPL47QGS.js +3515 -0
  27. package/dist/chunk-EMRGN4KM.js +170 -0
  28. package/dist/chunk-FGOABE4Z.js +955 -0
  29. package/dist/chunk-FW65TP4G.js +520 -0
  30. package/dist/chunk-GOIZNNOA.js +221 -0
  31. package/dist/chunk-H5MJUAA6.js +295 -0
  32. package/dist/chunk-H5OHH6F4.js +223 -0
  33. package/dist/chunk-HC5RM4WY.js +199 -0
  34. package/dist/chunk-HEQFMLZ7.js +190 -0
  35. package/dist/chunk-HFXSNKCV.js +196 -0
  36. package/dist/chunk-HXSBQ2SE.js +1723 -0
  37. package/dist/chunk-ILESNGNM.js +163 -0
  38. package/dist/chunk-INF5CGAO.js +137 -0
  39. package/dist/chunk-IWDFZ6XR.js +337 -0
  40. package/dist/chunk-IXMNTNW5.js +238 -0
  41. package/dist/chunk-J4SRJKBW.js +428 -0
  42. package/dist/chunk-J5SKD6LN.js +235 -0
  43. package/dist/chunk-JRJJX3L5.js +424 -0
  44. package/dist/chunk-KXNDHMUB.js +366 -0
  45. package/dist/chunk-LIJQMYYX.js +59 -0
  46. package/dist/chunk-MAN26PZ5.js +260 -0
  47. package/dist/chunk-MKRQMLZA.js +474 -0
  48. package/dist/chunk-NBDZMMG2.js +169 -0
  49. package/dist/chunk-NHA6BEIH.js +101 -0
  50. package/dist/chunk-OA6YJIWL.js +4412 -0
  51. package/dist/chunk-OZC255IC.js +2830 -0
  52. package/dist/chunk-PUR6WU2B.js +154 -0
  53. package/dist/chunk-Q5JPPCZC.js +12 -0
  54. package/dist/chunk-QBV725YG.js +128 -0
  55. package/dist/chunk-QHVW4AAM.js +892 -0
  56. package/dist/chunk-QNJ7AQ4B.js +1000 -0
  57. package/dist/chunk-RGISBZBD.js +231 -0
  58. package/dist/chunk-RJZQWEMS.js +84 -0
  59. package/dist/chunk-RP2ZA47V.js +15 -0
  60. package/dist/chunk-RXISBFR5.js +315 -0
  61. package/dist/chunk-S5CCLZL3.js +99 -0
  62. package/dist/chunk-TVTCSBJF.js +122 -0
  63. package/dist/chunk-U4D5S3VQ.js +21 -0
  64. package/dist/chunk-U4VAATKP.js +193 -0
  65. package/dist/chunk-UKU2ZX4C.js +203 -0
  66. package/dist/chunk-UNSKG6DC.js +159 -0
  67. package/dist/chunk-URFKEIHM.js +1091 -0
  68. package/dist/chunk-UTV7YAW7.js +178 -0
  69. package/dist/chunk-V43EQ6VR.js +68 -0
  70. package/dist/chunk-VB3MJGCV.js +610 -0
  71. package/dist/chunk-WHIIIREL.js +223 -0
  72. package/dist/chunk-XMIFYKUT.js +1371 -0
  73. package/dist/chunk-YF2RSV34.js +54 -0
  74. package/dist/chunk-Z6DAKQ3U.js +1 -0
  75. package/dist/chunk-ZIGAZFWE.js +522 -0
  76. package/dist/circuit-breaker.js +3 -191
  77. package/dist/codebase-index/index.js +84 -13688
  78. package/dist/codebase-index/parser-worker-script.js +8 -3995
  79. package/dist/codebase-index/project-server.js +60 -8548
  80. package/dist/codebase-index/worker.js +20 -8416
  81. package/dist/design.js +2 -299
  82. package/dist/diff.js +4 -256
  83. package/dist/document.js +4 -222
  84. package/dist/e2e.js +5 -476
  85. package/dist/edit.js +14 -10200
  86. package/dist/exec.js +16 -3131
  87. package/dist/fetch.js +8 -398
  88. package/dist/format.js +10 -3750
  89. package/dist/generic-parser-VUXDIAOZ.js +13 -0
  90. package/dist/git.js +4 -380
  91. package/dist/glob.js +6 -280
  92. package/dist/go-parser-6CA77WZ4.js +469 -0
  93. package/dist/grep.js +7 -604
  94. package/dist/index.js +318 -35387
  95. package/dist/install.js +10 -4091
  96. package/dist/json-parser-7YMDJSBJ.js +213 -0
  97. package/dist/json.js +4 -665
  98. package/dist/kanban.js +3 -2096
  99. package/dist/languages/index.js +23 -4664
  100. package/dist/legacy-bridge-7UKZT46G.js +18 -0
  101. package/dist/lint.js +10 -3706
  102. package/dist/logs.js +4 -287
  103. package/dist/memory.js +6 -215
  104. package/dist/mode.js +3 -99
  105. package/dist/outdated.js +4 -5170
  106. package/dist/pack.js +65 -33897
  107. package/dist/parser-dispatch-VPOFDO2U.js +14 -0
  108. package/dist/patch.js +13 -9935
  109. package/dist/plan.js +5 -3286
  110. package/dist/process-registry.js +8 -651
  111. package/dist/ps-slash.js +12 -1439
  112. package/dist/py-parser-GPM5VYRG.js +16 -0
  113. package/dist/read.js +13 -9816
  114. package/dist/replace.js +15 -10014
  115. package/dist/rs-parser-WVQ4KYCX.js +81 -0
  116. package/dist/scaffold.js +4 -253
  117. package/dist/search.js +5 -585
  118. package/dist/session-kanban.js +30 -972
  119. package/dist/skill.js +2 -215
  120. package/dist/task.js +5 -3410
  121. package/dist/test.js +10 -3773
  122. package/dist/todo.js +4 -2891
  123. package/dist/tool-help.js +3 -123
  124. package/dist/tool-search.js +3 -79
  125. package/dist/tool-tier.js +68 -33984
  126. package/dist/tool-use.js +2 -93
  127. package/dist/tree-sitter-parser-YCILHGZD.js +17 -0
  128. package/dist/tree.js +4 -288
  129. package/dist/ts-parser-YH4ZMWMH.js +232 -0
  130. package/dist/typecheck.js +10 -3753
  131. package/dist/win32.js +6 -60
  132. package/dist/write.js +14 -9882
  133. package/dist/yaml-parser-GFAOKV53.js +157 -0
  134. package/package.json +5 -5
@@ -0,0 +1,472 @@
1
+ import {
2
+ CircuitBreaker
3
+ } from "./chunk-HFXSNKCV.js";
4
+
5
+ // src/process-registry.ts
6
+ import { spawn } from "node:child_process";
7
+ import * as os from "node:os";
8
+
9
+ // src/_redact-command.ts
10
+ import { expectDefined } from "@wrongstack/core/utils";
11
+ var SENSITIVE_FLAG_PATTERNS = [
12
+ // --flag=value or --flag "value" (value captured up to next space or comma)
13
+ /--(?: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,
14
+ // -t short flag (token): attached (-tVALUE), separated (-t VALUE), or -t=VALUE.
15
+ // (?<![-\w]) anchors to a token start so we don't match the `-t` inside `--token`.
16
+ // The value must be token-like (>= 8 chars) so ordinary combined flags such
17
+ // as `tar -tf` / `ssh -tt` are not eaten. Global flag: EVERY occurrence is
18
+ // redacted, not just the first.
19
+ // NOTE: synced with @wrongstack/core observability/redact-command.ts.
20
+ /(?<![-\w])-t(?:[=\s]+)?[^\s,-]{8,}/g,
21
+ // -p|-password|-a (redis auth) short flags: attached + separated + =value.
22
+ // Same token-start anchor; over-redaction is an accepted tradeoff for a
23
+ // redaction function. Synced with core copy.
24
+ /(?<![-\w])-(?:password|p|a)(?:[=\s]+)?[^\s,-]+/gi,
25
+ // env var–style secrets: TOKEN=x, API_KEY=y, etc.
26
+ /(?: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,
27
+ // Generic high-entropy look: base64 strings >32 chars or hex strings >32 digits — but only
28
+ // when preceded by a flag name (e.g. --github-token=EyJ...). Global flag so
29
+ // every such flag in the command line is redacted, not just the first.
30
+ /--\w*(?:token|key|secret|password|passwd|auth|credential)\w*[=\s,][A-Za-z0-9+/=]{32,}/g
31
+ ];
32
+ function redactCommand(cmd) {
33
+ let result = cmd;
34
+ for (const pattern of SENSITIVE_FLAG_PATTERNS) {
35
+ result = result.replace(pattern, (match) => {
36
+ const eq = match.indexOf("=");
37
+ const sp = match.search(/\s/);
38
+ const delim = eq !== -1 ? "=" : sp !== -1 ? match[sp] : null;
39
+ if (delim !== null) {
40
+ const flag = match.slice(0, match.indexOf(expectDefined(delim)) + 1);
41
+ return `${flag}[REDACTED]`;
42
+ }
43
+ if (match.startsWith("--")) {
44
+ return match;
45
+ }
46
+ return `${match.slice(0, 2)}[REDACTED]`;
47
+ });
48
+ }
49
+ return result;
50
+ }
51
+
52
+ // src/process-registry.ts
53
+ var DEFAULT_GRACE_MS = 2e3;
54
+ var WIN32_TASKKILL_TIMEOUT_MS = 5e3;
55
+ function killWin32Tree(pid, opts = {}) {
56
+ try {
57
+ const child = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
58
+ stdio: "ignore",
59
+ windowsHide: true
60
+ });
61
+ let settled = false;
62
+ let timeout;
63
+ const settle = () => {
64
+ if (settled) return;
65
+ settled = true;
66
+ if (timeout) clearTimeout(timeout);
67
+ try {
68
+ opts.onSettled?.();
69
+ } catch {
70
+ }
71
+ };
72
+ child.on("error", settle);
73
+ child.on("close", settle);
74
+ timeout = setTimeout(
75
+ () => {
76
+ try {
77
+ child.kill();
78
+ } catch {
79
+ }
80
+ settle();
81
+ },
82
+ Math.max(1, opts.timeoutMs ?? WIN32_TASKKILL_TIMEOUT_MS)
83
+ );
84
+ timeout.unref?.();
85
+ child.unref();
86
+ return true;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+ var ProcessRegistryImpl = class {
92
+ processes = /* @__PURE__ */ new Map();
93
+ breaker;
94
+ /**
95
+ * Auto kill/reset config. When the breaker trips and `autoKillResetMs > 0`,
96
+ * a countdown is armed; on expiry all tracked processes are killed and the
97
+ * breaker is reset to closed (forced recovery). Zero means manual recovery
98
+ * only (`/kill reset`).
99
+ */
100
+ autoKillResetMs = 0;
101
+ autoKillTimer = null;
102
+ autoKillArmedAt = null;
103
+ breakerCountdownListeners = [];
104
+ constructor(breakerConfig) {
105
+ this.breaker = new CircuitBreaker(breakerConfig);
106
+ this.breaker.onTrip = () => this._armAutoKillReset();
107
+ this.breaker.onReset = () => this._cancelAutoKillReset();
108
+ this.breaker.setEnabled(false);
109
+ }
110
+ register(info) {
111
+ this.processes.set(info.pid, {
112
+ ...info,
113
+ killed: false,
114
+ protected: info.protected ?? false,
115
+ background: info.background ?? false
116
+ });
117
+ }
118
+ _isSafeSignalPid(pid) {
119
+ return Number.isInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid;
120
+ }
121
+ _canSignalProcessGroup(p) {
122
+ return os.platform() !== "win32" && p.processGroupLeader === true && this._isSafeSignalPid(p.pid) && p.child !== null && typeof p.child.pid === "number" && p.child.pid === p.pid;
123
+ }
124
+ _killChildDirect(p, signal) {
125
+ try {
126
+ if (p.child) {
127
+ p.child.kill(signal);
128
+ return;
129
+ }
130
+ if (this._isSafeSignalPid(p.pid)) process.kill(p.pid, signal);
131
+ } catch {
132
+ }
133
+ }
134
+ _killPosix(p, signal) {
135
+ if (this._canSignalProcessGroup(p)) {
136
+ try {
137
+ process.kill(-p.pid, signal);
138
+ return;
139
+ } catch {
140
+ }
141
+ }
142
+ this._killChildDirect(p, signal);
143
+ }
144
+ /** Unregister a process by PID. Called on 'close' / 'exit' events. */
145
+ unregister(pid) {
146
+ this.processes.delete(pid);
147
+ }
148
+ /** Get a single process by PID. */
149
+ get(pid) {
150
+ this._pruneStale(pid);
151
+ return this.processes.get(pid);
152
+ }
153
+ /** Get all tracked processes. */
154
+ list() {
155
+ this._pruneAllStale();
156
+ return Array.from(this.processes.values());
157
+ }
158
+ /** Get processes filtered by name (e.g. 'bash', 'exec'). */
159
+ byName(name) {
160
+ return this.list().filter((p) => p.name === name);
161
+ }
162
+ /** Get processes filtered by session. */
163
+ bySession(sessionId) {
164
+ return this.list().filter((p) => p.sessionId === sessionId);
165
+ }
166
+ /** Count of active (non-killed) processes. */
167
+ get activeCount() {
168
+ let n = 0;
169
+ for (const p of this.processes.values()) {
170
+ if (!p.killed) n++;
171
+ }
172
+ return n;
173
+ }
174
+ /** Count of active jobs explicitly launched in background mode. */
175
+ get activeBackgroundCount() {
176
+ let n = 0;
177
+ for (const p of this.processes.values()) {
178
+ if (p.background && !p.killed) n++;
179
+ }
180
+ return n;
181
+ }
182
+ /**
183
+ * Combined stats for observability — used by /ps and the TUI status bar.
184
+ */
185
+ stats() {
186
+ this._pruneAllStale();
187
+ return {
188
+ activeCount: this.activeCount,
189
+ backgroundCount: this.activeBackgroundCount,
190
+ totalCount: this.processes.size,
191
+ breaker: this.breaker.snapshot()
192
+ };
193
+ }
194
+ /**
195
+ * Returns true if the circuit allows a new bash/exec call to proceed.
196
+ * When false, callers MUST NOT spawn a process.
197
+ */
198
+ get canProceed() {
199
+ return this.breaker.canProceed;
200
+ }
201
+ /**
202
+ * Called before spawning a process. Returns true if allowed; false if
203
+ * the circuit breaker is open.
204
+ *
205
+ * @param bypass - If true, skip circuit breaker check (for background processes).
206
+ */
207
+ beforeCall(bypass = false) {
208
+ return this.breaker.beforeCall(bypass);
209
+ }
210
+ /**
211
+ * Called after a process finishes. `durationMs` is wall-clock time;
212
+ * `failed` is true for non-zero exit codes.
213
+ *
214
+ * @param bypass - If true, do not update circuit breaker state (for background processes).
215
+ */
216
+ afterCall(durationMs, failed, bypass = false) {
217
+ this.breaker.afterCall(durationMs, failed, bypass);
218
+ }
219
+ /** Force-open the circuit breaker (Ctrl+C, /kill force). */
220
+ forceBreakerOpen() {
221
+ this.breaker.forceOpen();
222
+ }
223
+ /** Force-reset the circuit breaker to closed (/kill reset). */
224
+ forceBreakerReset() {
225
+ this.breaker.forceReset();
226
+ }
227
+ /**
228
+ * Configure circuit-breaker protection at runtime. Called from `/settings`
229
+ * (instant, all modes) and on TUI mount (applies persisted config).
230
+ *
231
+ * - `enabled` toggles whether the breaker gates `bash`/`exec`.
232
+ * - `autoKillResetMs` arms the auto kill/reset countdown when the breaker
233
+ * trips (0 = manual recovery only).
234
+ *
235
+ * Re-applies cleanly on every call: cancels a pending countdown when the
236
+ * timeout is cleared or protection disabled, and re-arms if the breaker is
237
+ * currently open under the new settings.
238
+ */
239
+ setBreakerConfig(cfg) {
240
+ if (cfg.enabled !== void 0) this.breaker.setEnabled(cfg.enabled);
241
+ if (cfg.autoKillResetMs !== void 0) this.autoKillResetMs = Math.max(0, cfg.autoKillResetMs);
242
+ if (this.autoKillResetMs <= 0) {
243
+ this._cancelAutoKillReset();
244
+ return;
245
+ }
246
+ if (this.breaker.isEnabled && this.breaker.snapshot().state === "open") {
247
+ this._armAutoKillReset();
248
+ }
249
+ }
250
+ /**
251
+ * Live countdown to the next auto kill/reset, or null when nothing is armed.
252
+ * The TUI polls this on a 1s tick while armed so the statusline decrements.
253
+ */
254
+ getBreakerCountdown() {
255
+ if (this.autoKillArmedAt === null || this.autoKillResetMs <= 0) return null;
256
+ const elapsed = Date.now() - this.autoKillArmedAt;
257
+ return {
258
+ remainingMs: Math.max(0, this.autoKillResetMs - elapsed),
259
+ totalMs: this.autoKillResetMs
260
+ };
261
+ }
262
+ /**
263
+ * Subscribe to countdown arm/cancel events. Returns an unsubscribe function.
264
+ * Use {@link getBreakerCountdown} for the live ticking value between events.
265
+ */
266
+ onBreakerCountdownChange(listener) {
267
+ this.breakerCountdownListeners.push(listener);
268
+ return () => {
269
+ this.breakerCountdownListeners = this.breakerCountdownListeners.filter((l) => l !== listener);
270
+ };
271
+ }
272
+ _emitBreakerCountdown() {
273
+ const snap = this.getBreakerCountdown();
274
+ for (const l of this.breakerCountdownListeners) {
275
+ try {
276
+ l(snap);
277
+ } catch {
278
+ }
279
+ }
280
+ }
281
+ /**
282
+ * Arm the auto kill/reset countdown. Idempotent: re-arming resets the window
283
+ * (a fresh trip after a failed half-open probe restarts the clock). No-op
284
+ * when protection is off or no timeout is configured.
285
+ */
286
+ _armAutoKillReset() {
287
+ if (this.autoKillResetMs <= 0 || !this.breaker.isEnabled) return;
288
+ this._clearAutoKillTimer();
289
+ this.autoKillArmedAt = Date.now();
290
+ this.autoKillTimer = setTimeout(() => {
291
+ this.autoKillTimer = null;
292
+ this.autoKillArmedAt = null;
293
+ this.killAll({ force: false, preserveBackground: true });
294
+ this.breaker.forceReset();
295
+ this._emitBreakerCountdown();
296
+ }, this.autoKillResetMs);
297
+ this.autoKillTimer.unref?.();
298
+ this._emitBreakerCountdown();
299
+ }
300
+ _cancelAutoKillReset() {
301
+ const wasArmed = this.autoKillArmedAt !== null;
302
+ this._clearAutoKillTimer();
303
+ if (wasArmed) {
304
+ this.autoKillArmedAt = null;
305
+ this._emitBreakerCountdown();
306
+ }
307
+ }
308
+ _clearAutoKillTimer() {
309
+ if (this.autoKillTimer !== null) {
310
+ clearTimeout(this.autoKillTimer);
311
+ this.autoKillTimer = null;
312
+ }
313
+ }
314
+ /** Kill a single process by PID.
315
+ *
316
+ * On POSIX: sends SIGTERM to the *process group* (-pid) so that
317
+ * runaway grandchild processes (`sleep 9999 & disown`) are also killed.
318
+ * After `graceMs` a SIGKILL is sent if the process hasn't exited.
319
+ *
320
+ * On Windows: `child.kill()` maps to TerminateProcess — process groups
321
+ * are not meaningfully supported. A second `force=true` call sends
322
+ * SIGKILL (which maps to TerminateProcess again — the distinction is
323
+ * in the exit code, not the signal).
324
+ *
325
+ * Returns true if the process was found and kill was attempted.
326
+ */
327
+ kill(pid, opts = {}) {
328
+ this._pruneStale(pid);
329
+ const p = this.processes.get(pid);
330
+ if (!p) return false;
331
+ if (p.killed && opts.force !== true) return true;
332
+ if (p.protected && opts.includeProtected !== true) return false;
333
+ if (opts.preserveBackground && p.background) return false;
334
+ const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
335
+ const isWin = os.platform() === "win32";
336
+ if (isWin) {
337
+ const liveRealChild = p.child === null || p.child.exitCode === null && typeof p.child.pid === "number";
338
+ const directFallback = () => {
339
+ if (p.child && p.child.exitCode === null) {
340
+ try {
341
+ p.child.kill("SIGKILL");
342
+ } catch {
343
+ }
344
+ }
345
+ };
346
+ if (liveRealChild && killWin32Tree(pid, {
347
+ timeoutMs: Math.max(graceMs, WIN32_TASKKILL_TIMEOUT_MS),
348
+ onSettled: directFallback
349
+ })) {
350
+ } else {
351
+ this._killChildDirect(p, force ? "SIGKILL" : "SIGTERM");
352
+ }
353
+ p.killed = true;
354
+ return true;
355
+ }
356
+ try {
357
+ if (force) {
358
+ this._killPosix(p, "SIGKILL");
359
+ } else {
360
+ this._killPosix(p, "SIGTERM");
361
+ const timer = setTimeout(() => {
362
+ if (this.processes.has(pid) && !p.child?.killed) {
363
+ this._killPosix(p, "SIGKILL");
364
+ }
365
+ }, graceMs);
366
+ timer.unref?.();
367
+ }
368
+ } catch {
369
+ }
370
+ p.killed = true;
371
+ return true;
372
+ }
373
+ /**
374
+ * Kill all tracked processes.
375
+ * Returns the PIDs that were kill()ed.
376
+ */
377
+ killAll(opts = {}) {
378
+ const pids = Array.from(this.processes.keys());
379
+ const killed = [];
380
+ const includeProtected = opts.includeProtected === true;
381
+ for (const pid of pids) {
382
+ const p = this.processes.get(pid);
383
+ if (!p) continue;
384
+ if (p.protected && !includeProtected) continue;
385
+ if (opts.preserveBackground && p.background) continue;
386
+ if (this.kill(pid, opts)) killed.push(pid);
387
+ }
388
+ return killed;
389
+ }
390
+ /**
391
+ * Kill all processes for a specific session.
392
+ * Returns the PIDs that were kill()ed.
393
+ */
394
+ killSession(sessionId, opts = {}) {
395
+ const pids = this.bySession(sessionId).map((p) => p.pid);
396
+ const killed = [];
397
+ for (const pid of pids) {
398
+ if (this.kill(pid, opts)) killed.push(pid);
399
+ }
400
+ return killed;
401
+ }
402
+ /**
403
+ * Check whether a tracked process entry is stale — the child has exited
404
+ * (exitCode !== null) AND it's been in the registry long enough that the
405
+ * OS may have reused the PID for a new, unrelated process.
406
+ *
407
+ * P3 #24 (before-release.md): on POSIX, PIDs are reused after process
408
+ * exit. If a tracked process exits but its 'close' event hasn't fired yet
409
+ * (or was missed), the registry still holds the entry. A new process
410
+ * gets the same PID, and PID-based lookups (get, kill, shouldBlockKill)
411
+ * may incorrectly protect or target the wrong process.
412
+ *
413
+ * The 60s threshold is conservative — the OS typically waits much longer
414
+ * before reusing a PID, but we want to clean up before that becomes a risk.
415
+ */
416
+ _isStaleEntry(entry) {
417
+ if (entry.child === null) {
418
+ if (Date.now() - entry.startedAt <= 6e4) return false;
419
+ if (os.platform() === "win32") return false;
420
+ try {
421
+ process.kill(entry.pid, 0);
422
+ return false;
423
+ } catch (err) {
424
+ return err.code !== "EPERM";
425
+ }
426
+ }
427
+ return entry.child.exitCode !== null && Date.now() - entry.startedAt > 6e4;
428
+ }
429
+ /**
430
+ * Remove a stale entry for a specific PID before any PID-based lookup.
431
+ * This prevents PID reuse from causing the registry to act on a dead
432
+ * process that has been replaced by a new one with the same PID.
433
+ */
434
+ _pruneStale(pid) {
435
+ const entry = this.processes.get(pid);
436
+ if (entry && this._isStaleEntry(entry)) {
437
+ this.processes.delete(pid);
438
+ }
439
+ }
440
+ /**
441
+ * Remove every stale entry, not just one PID. `list()`/`stats()` — the
442
+ * surfaces the TUI status bar and `/ps` poll — must prune too: a child
443
+ * whose 'close' event never fires (e.g. Windows grandchildren holding stdio
444
+ * open) would otherwise linger in the registry until someone looks up its
445
+ * exact PID, and PID reuse meanwhile makes `get()`/`kill()` target the
446
+ * wrong process. RAM-leak audit 2026-07-31, MEDIUM.
447
+ */
448
+ _pruneAllStale() {
449
+ for (const [pid, entry] of this.processes) {
450
+ if (this._isStaleEntry(entry)) this.processes.delete(pid);
451
+ }
452
+ }
453
+ };
454
+ var _registry;
455
+ function getProcessRegistry() {
456
+ if (!_registry) {
457
+ _registry = new ProcessRegistryImpl();
458
+ }
459
+ return _registry;
460
+ }
461
+ function _resetProcessRegistry() {
462
+ _registry = void 0;
463
+ }
464
+
465
+ export {
466
+ redactCommand,
467
+ killWin32Tree,
468
+ ProcessRegistryImpl,
469
+ getProcessRegistry,
470
+ _resetProcessRegistry
471
+ };
472
+ //# sourceMappingURL=chunk-3PVYQFRQ.js.map
@@ -0,0 +1,89 @@
1
+ // src/_syntax-check.ts
2
+ import * as path from "node:path";
3
+ var TS_LIKE = /* @__PURE__ */ new Set([".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"]);
4
+ var MAX_CHECK_CHARS = 15e5;
5
+ var MAX_ERRORS = 5;
6
+ var tsLoad = null;
7
+ function loadTypescript() {
8
+ tsLoad ??= import("@typescript/typescript6").then(
9
+ (m) => m.default ?? m,
10
+ () => null
11
+ );
12
+ return tsLoad;
13
+ }
14
+ async function checkSyntax(filePath, content, previousContent) {
15
+ const errors = await parseErrors(filePath, content);
16
+ if (errors === void 0) return void 0;
17
+ if (errors.length === 0) return { errors, preExisting: false };
18
+ let preExisting = false;
19
+ if (previousContent !== void 0) {
20
+ const prevErrors = await parseErrors(filePath, previousContent);
21
+ preExisting = prevErrors !== void 0 && prevErrors.length > 0;
22
+ }
23
+ return { errors, preExisting };
24
+ }
25
+ function isJsoncFile(filePath) {
26
+ const base = path.basename(filePath).toLowerCase();
27
+ if (base.endsWith(".jsonc")) return true;
28
+ if (/^(tsconfig|jsconfig)([.-].*)?\.json$/.test(base)) return true;
29
+ const dir = path.basename(path.dirname(filePath)).toLowerCase();
30
+ return dir === ".vscode";
31
+ }
32
+ async function parseErrors(filePath, content) {
33
+ if (content.length > MAX_CHECK_CHARS) return void 0;
34
+ const ext = path.extname(filePath).toLowerCase();
35
+ if (ext === ".json" || ext === ".jsonc") {
36
+ try {
37
+ JSON.parse(content);
38
+ return [];
39
+ } catch (err) {
40
+ if (isJsoncFile(filePath)) {
41
+ const ts2 = await loadTypescript();
42
+ if (ts2) {
43
+ const jsonc = ts2.parseConfigFileTextToJson(filePath, content);
44
+ if (!jsonc.error) return [];
45
+ return [formatDiag(ts2, jsonc.error, content)];
46
+ }
47
+ }
48
+ return [`JSON parse error: ${err.message}`];
49
+ }
50
+ }
51
+ if (!TS_LIKE.has(ext)) return void 0;
52
+ const ts = await loadTypescript();
53
+ if (!ts) return void 0;
54
+ const scriptKind = ext === ".tsx" ? ts.ScriptKind.TSX : ext === ".ts" || ext === ".mts" || ext === ".cts" ? ts.ScriptKind.TS : (
55
+ // Plain JS may legitimately contain JSX; the JSX grammar is a
56
+ // superset for untyped code, so parsing .js/.jsx as JSX avoids
57
+ // false positives on React files.
58
+ ts.ScriptKind.JSX
59
+ );
60
+ const sourceFile = ts.createSourceFile(
61
+ path.basename(filePath),
62
+ content,
63
+ ts.ScriptTarget.Latest,
64
+ /* setParentNodes */
65
+ false,
66
+ scriptKind
67
+ );
68
+ const diags = sourceFile.parseDiagnostics ?? [];
69
+ return diags.slice(0, MAX_ERRORS).map((d) => formatDiag(ts, d, content, sourceFile));
70
+ }
71
+ function formatDiag(ts, diag, content, sourceFile) {
72
+ const message = ts.flattenDiagnosticMessageText(diag.messageText, " ");
73
+ if (diag.start === void 0) return message;
74
+ let line;
75
+ if (sourceFile) {
76
+ line = sourceFile.getLineAndCharacterOfPosition(diag.start).line + 1;
77
+ } else {
78
+ line = 1;
79
+ for (let i = 0; i < diag.start && i < content.length; i++) {
80
+ if (content.charCodeAt(i) === 10) line++;
81
+ }
82
+ }
83
+ return `line ${line}: ${message}`;
84
+ }
85
+
86
+ export {
87
+ checkSyntax
88
+ };
89
+ //# sourceMappingURL=chunk-3QMQBO5Z.js.map