@wrongstack/tools 0.313.0 → 0.316.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 (182) hide show
  1. package/dist/_edit-match.d.ts +3 -2
  2. package/dist/_output-spool.d.ts +4 -3
  3. package/dist/_shell-pick.d.ts +2 -1
  4. package/dist/_spawn-stream.d.ts +2 -1
  5. package/dist/_syntax-check.d.ts +2 -1
  6. package/dist/audit.js +10 -4055
  7. package/dist/bash-kill-guard.d.ts +3 -6
  8. package/dist/bash.js +9 -2308
  9. package/dist/batch-tool-use.js +2 -187
  10. package/dist/browser/index.js +25 -1339
  11. package/dist/browser/network-guard-proxy.d.ts +2 -1
  12. package/dist/builtin.js +69 -33949
  13. package/dist/chunk-22B7GE5T.js +260 -0
  14. package/dist/chunk-2VSZC6QM.js +113 -0
  15. package/dist/chunk-3PVYQFRQ.js +472 -0
  16. package/dist/chunk-42BHI7TN.js +337 -0
  17. package/dist/chunk-4BHUSMNL.js +104 -0
  18. package/dist/chunk-4I4LWFOO.js +431 -0
  19. package/dist/chunk-4UESMQDP.js +122 -0
  20. package/dist/chunk-553IQUMO.js +478 -0
  21. package/dist/chunk-5H4GSJAI.js +223 -0
  22. package/dist/chunk-6RNIFLG4.js +305 -0
  23. package/dist/chunk-7EY5DCRO.js +434 -0
  24. package/dist/chunk-A6BRWIXN.js +317 -0
  25. package/dist/chunk-AHHDWNXC.js +200 -0
  26. package/dist/chunk-BSLVR56S.js +199 -0
  27. package/dist/chunk-BTSFTGIL.js +7 -0
  28. package/dist/chunk-D33S4RQG.js +222 -0
  29. package/dist/chunk-DA4KNE2H.js +4412 -0
  30. package/dist/chunk-DR7JOQTC.js +520 -0
  31. package/dist/chunk-EEOFQDT6.js +898 -0
  32. package/dist/chunk-EJWSCQ6D.js +137 -0
  33. package/dist/chunk-EMRGN4KM.js +170 -0
  34. package/dist/chunk-FQZOHLG3.js +89 -0
  35. package/dist/chunk-GOIZNNOA.js +221 -0
  36. package/dist/chunk-HFXSNKCV.js +196 -0
  37. package/dist/chunk-HYX2TZ7O.js +1272 -0
  38. package/dist/chunk-I64BS3VC.js +15 -0
  39. package/dist/chunk-IVWV2UM6.js +955 -0
  40. package/dist/chunk-IXMNTNW5.js +238 -0
  41. package/dist/chunk-IYK7XGDZ.js +892 -0
  42. package/dist/chunk-J5SKD6LN.js +235 -0
  43. package/dist/chunk-JNNVRHMV.js +2111 -0
  44. package/dist/chunk-JOHXDF3D.js +295 -0
  45. package/dist/chunk-JRJJX3L5.js +424 -0
  46. package/dist/chunk-K3WNSHUF.js +1371 -0
  47. package/dist/chunk-L25CVUVR.js +2830 -0
  48. package/dist/chunk-LIJQMYYX.js +59 -0
  49. package/dist/chunk-LWKUTMD5.js +197 -0
  50. package/dist/chunk-MQX2KXVW.js +54 -0
  51. package/dist/chunk-MZZN7VCD.js +359 -0
  52. package/dist/chunk-NBDZMMG2.js +169 -0
  53. package/dist/chunk-NKJW5GFO.js +366 -0
  54. package/dist/chunk-NKNOBUBU.js +522 -0
  55. package/dist/chunk-O4MBV4AX.js +134 -0
  56. package/dist/chunk-OUBDL3WH.js +3515 -0
  57. package/dist/chunk-PQKK5JH7.js +101 -0
  58. package/dist/chunk-PY2IOS7C.js +1000 -0
  59. package/dist/chunk-Q5JPPCZC.js +12 -0
  60. package/dist/chunk-QBV725YG.js +128 -0
  61. package/dist/chunk-QZQSPUBF.js +315 -0
  62. package/dist/chunk-RGISBZBD.js +231 -0
  63. package/dist/chunk-RJZQWEMS.js +84 -0
  64. package/dist/chunk-RXISBFR5.js +315 -0
  65. package/dist/chunk-S5CCLZL3.js +99 -0
  66. package/dist/chunk-SDLVH5RZ.js +178 -0
  67. package/dist/chunk-T2F4S7U4.js +1723 -0
  68. package/dist/chunk-TEBQ4VPZ.js +163 -0
  69. package/dist/chunk-U4D5S3VQ.js +21 -0
  70. package/dist/chunk-U4VAATKP.js +193 -0
  71. package/dist/chunk-UCYQTZ7F.js +113 -0
  72. package/dist/chunk-UKU2ZX4C.js +203 -0
  73. package/dist/chunk-UNSKG6DC.js +159 -0
  74. package/dist/chunk-V43EQ6VR.js +68 -0
  75. package/dist/chunk-VB3MJGCV.js +610 -0
  76. package/dist/chunk-VFKPWSOX.js +154 -0
  77. package/dist/chunk-VJNHFZ7J.js +190 -0
  78. package/dist/chunk-VXECAJJ7.js +1091 -0
  79. package/dist/chunk-WHIIIREL.js +223 -0
  80. package/dist/chunk-Z6DAKQ3U.js +1 -0
  81. package/dist/chunk-ZJQ4IGXK.js +474 -0
  82. package/dist/chunk-ZLTFLC25.js +385 -0
  83. package/dist/circuit-breaker.js +3 -191
  84. package/dist/codebase-index/ast-invariant-engine.d.ts +5 -4
  85. package/dist/codebase-index/binary-frame.d.ts +0 -2
  86. package/dist/codebase-index/bm25.d.ts +1 -1
  87. package/dist/codebase-index/circuit-breaker.d.ts +2 -1
  88. package/dist/codebase-index/codebase-ast-replace-tool.d.ts +3 -2
  89. package/dist/codebase-index/codebase-impact-analysis-tool.d.ts +4 -3
  90. package/dist/codebase-index/codebase-invariant-check-tool.d.ts +3 -2
  91. package/dist/codebase-index/codebase-repo-map-tool.d.ts +3 -2
  92. package/dist/codebase-index/codebase-skeleton-tool.d.ts +3 -2
  93. package/dist/codebase-index/codebase-targeted-test-tool.d.ts +3 -2
  94. package/dist/codebase-index/content-hash.d.ts +0 -2
  95. package/dist/codebase-index/import-extractor.d.ts +0 -13
  96. package/dist/codebase-index/index-service.d.ts +1 -1
  97. package/dist/codebase-index/index.js +84 -13688
  98. package/dist/codebase-index/languages.d.ts +2 -1
  99. package/dist/codebase-index/module-roots.d.ts +3 -2
  100. package/dist/codebase-index/parser-batch.d.ts +0 -5
  101. package/dist/codebase-index/parser-dispatch.d.ts +2 -1
  102. package/dist/codebase-index/parser-output.d.ts +4 -3
  103. package/dist/codebase-index/parser-worker-pool.d.ts +0 -2
  104. package/dist/codebase-index/parser-worker-script.d.ts +1 -16
  105. package/dist/codebase-index/parser-worker-script.js +8 -3995
  106. package/dist/codebase-index/project-server-client-state.d.ts +2 -2
  107. package/dist/codebase-index/project-server-endpoint.d.ts +0 -15
  108. package/dist/codebase-index/project-server.js +60 -8548
  109. package/dist/codebase-index/tree-sitter/visitor.d.ts +2 -1
  110. package/dist/codebase-index/tree-sitter-parser.d.ts +0 -2
  111. package/dist/codebase-index/ts-parser.d.ts +1 -1
  112. package/dist/codebase-index/vector-search.d.ts +2 -1
  113. package/dist/codebase-index/wal-maintenance.d.ts +3 -2
  114. package/dist/codebase-index/worker.js +20 -8416
  115. package/dist/codebase-index/writer-admin.d.ts +0 -1
  116. package/dist/codebase-index/writer-search.d.ts +0 -9
  117. package/dist/design.js +2 -299
  118. package/dist/diff.js +4 -256
  119. package/dist/document.js +4 -222
  120. package/dist/e2e.js +5 -476
  121. package/dist/edit.js +14 -10200
  122. package/dist/exec.js +16 -3131
  123. package/dist/fetch.js +8 -398
  124. package/dist/format.js +10 -3750
  125. package/dist/generic-parser-VUXDIAOZ.js +13 -0
  126. package/dist/git.js +4 -380
  127. package/dist/glob.js +6 -280
  128. package/dist/go-parser-JXYKJHRC.js +469 -0
  129. package/dist/grep.js +7 -604
  130. package/dist/index.js +318 -35387
  131. package/dist/install.js +10 -4091
  132. package/dist/json-parser-IBHZ4BZC.js +213 -0
  133. package/dist/json.js +4 -665
  134. package/dist/kanban-contract-actions.d.ts +1 -1
  135. package/dist/kanban-detail-actions.d.ts +2 -1
  136. package/dist/kanban-presence.d.ts +2 -1
  137. package/dist/kanban-serializer.d.ts +0 -8
  138. package/dist/kanban-split-task-handler.d.ts +2 -2
  139. package/dist/kanban-tool-types.d.ts +2 -1
  140. package/dist/kanban.js +3 -2096
  141. package/dist/languages/diagnostics.d.ts +2 -1
  142. package/dist/languages/index.js +23 -4664
  143. package/dist/languages/legacy-bridge.d.ts +3 -2
  144. package/dist/languages/types.d.ts +2 -1
  145. package/dist/legacy-bridge-7M6QLUQN.js +18 -0
  146. package/dist/lint.js +10 -3706
  147. package/dist/logs.js +4 -287
  148. package/dist/memory.js +6 -215
  149. package/dist/mode.js +3 -99
  150. package/dist/outdated.js +4 -5170
  151. package/dist/pack.js +65 -33897
  152. package/dist/parser-dispatch-QH4XPGG6.js +14 -0
  153. package/dist/patch.js +13 -9935
  154. package/dist/plan.js +5 -3286
  155. package/dist/process-registry.js +8 -651
  156. package/dist/ps-slash.js +12 -1439
  157. package/dist/pwsh.d.ts +0 -1
  158. package/dist/py-parser-IS4HKYMF.js +16 -0
  159. package/dist/read.js +13 -9816
  160. package/dist/replace.js +15 -10014
  161. package/dist/rs-parser-XHUUO2KZ.js +81 -0
  162. package/dist/scaffold.js +4 -253
  163. package/dist/search.js +5 -585
  164. package/dist/session-kanban-sync.d.ts +0 -6
  165. package/dist/session-kanban.js +30 -972
  166. package/dist/skill.js +2 -215
  167. package/dist/spawn-background.d.ts +1 -1
  168. package/dist/task.js +5 -3410
  169. package/dist/test.js +10 -3773
  170. package/dist/todo.js +4 -2891
  171. package/dist/tool-help.js +3 -123
  172. package/dist/tool-search.js +3 -79
  173. package/dist/tool-tier.js +68 -33984
  174. package/dist/tool-use.js +2 -93
  175. package/dist/tree-sitter-parser-AIERW3YI.js +15 -0
  176. package/dist/tree.js +4 -288
  177. package/dist/ts-parser-RCTYKSVI.js +232 -0
  178. package/dist/typecheck.js +10 -3753
  179. package/dist/win32.js +6 -60
  180. package/dist/write.js +14 -9882
  181. package/dist/yaml-parser-4SAXV3PL.js +157 -0
  182. package/package.json +5 -5
package/dist/exec.js CHANGED
@@ -1,3135 +1,20 @@
1
- // src/exec.ts
2
- import { spawn as spawn2 } from "node:child_process";
3
1
  import {
4
- emitProcessCompleted,
5
- emitProcessOutput,
6
- emitProcessStarted
7
- } from "@wrongstack/core/observability";
8
- import { toErrorMessage as toErrorMessage2 } from "@wrongstack/core/utils/error";
9
-
10
- // src/_danger-detect.ts
11
- var argHas = (args, value) => args.includes(value);
12
- var argMatches = (args, re) => args.some((a) => re.test(a));
13
- var hasShortFlags = (args, letters) => {
14
- const seen = /* @__PURE__ */ new Set();
15
- for (const a of args) {
16
- if (!/^-[a-zA-Z]+$/.test(a)) continue;
17
- for (const ch of a.slice(1)) seen.add(ch);
18
- }
19
- return letters.split("").every((l) => seen.has(l));
20
- };
21
- var RULES = [
22
- // ----- rm / rmdir: recursive force delete (any path) -----
23
- // Note: BLOCKED_ARG_PATTERNS already hard-denies root/home/glob paths,
24
- // but `rm -rf ./build` is a normal dev workflow that the user might
25
- // want to do intentionally. We downgrade it to 'destructive' so the
26
- // confirm prompt can approve.
27
- {
28
- id: "rm-recursive",
29
- level: "destructive",
30
- test: (cmd, args) => (cmd === "rm" || cmd === "rmdir") && hasShortFlags(args, "rf"),
31
- reason: "recursive force-delete"
32
- },
33
- // ----- Windows PowerShell Remove-Item: -Recurse -Force -----
34
- {
35
- id: "powershell-remove-item-recursive-force",
36
- level: "destructive",
37
- test: (cmd, args) => {
38
- if (cmd !== "powershell" && cmd !== "pwsh") return false;
39
- const hasRecurse = argMatches(args, /^-(?:R|Recurse|Recurse\s)/);
40
- const hasForce = argHas(args, "-Force") || argHas(args, "-F");
41
- if (argHas(args, "-WhatIf")) return false;
42
- return hasRecurse && hasForce;
43
- },
44
- reason: "Remove-Item with -Recurse -Force"
45
- },
46
- // ----- Windows PowerShell Disk & Volume destruction -----
47
- {
48
- id: "powershell-disk-volume-destroy",
49
- level: "destructive",
50
- test: (cmd, args) => {
51
- if (cmd !== "powershell" && cmd !== "pwsh") return false;
52
- return args.some(
53
- (a) => /^(?:Format-Volume|Clear-Disk|Initialize-Disk|Remove-Partition|Clear-Volume)(?:\s|$)/i.test(a)
54
- );
55
- },
56
- reason: "PowerShell disk/volume partition destruction"
57
- },
58
- // ----- Windows PowerShell System Restart / Shutdown -----
59
- {
60
- id: "powershell-stop-restart-computer",
61
- level: "destructive",
62
- test: (cmd, args) => {
63
- if (cmd !== "powershell" && cmd !== "pwsh") return false;
64
- return args.some((a) => /^(?:Stop-Computer|Restart-Computer)(?:\s|$)/i.test(a));
65
- },
66
- reason: "PowerShell system shutdown or restart"
67
- },
68
- // ----- Windows PowerShell ExecutionPolicy / Payload evasion -----
69
- {
70
- id: "powershell-execution-policy-bypass",
71
- level: "caution",
72
- test: (cmd, args) => {
73
- if (cmd !== "powershell" && cmd !== "pwsh") return false;
74
- return args.some(
75
- (a) => /Set-ExecutionPolicy\s+(?:Bypass|Unrestricted)|-(?:EncodedCommand|enc)\b/i.test(a)
76
- );
77
- },
78
- reason: "PowerShell execution policy bypass or encoded command"
79
- },
80
- // ----- find -exec / -ok / -execdir -----
81
- {
82
- id: "find-exec",
83
- level: "destructive",
84
- test: (cmd, args) => {
85
- if (cmd !== "find") return false;
86
- return args.some(
87
- (a) => a === "-exec" || a === "-exec;" || a === "-ok" || a === "-ok;" || a === "-execdir" || a === "-execdir;" || a.startsWith("-exec=") || a.startsWith("-ok=") || a.startsWith("-execdir=")
88
- );
89
- },
90
- reason: "find with -exec/-ok (executes arbitrary command on matches)"
91
- },
92
- // ----- git --exec= / --upload-pack= / --receive-pack= -----
93
- // These run arbitrary commands via the git transport layer.
94
- {
95
- id: "git-exec",
96
- level: "destructive",
97
- test: (cmd, args) => cmd === "git" && args.some(
98
- (a) => a.startsWith("--exec=") || a.startsWith("--upload-pack=") || a.startsWith("--receive-pack=") || a === "--exec" || a === "--upload-pack" || a === "--receive-pack"
99
- ),
100
- reason: "git with --exec/--upload-pack/--receive-pack (runs arbitrary code)"
101
- },
102
- // ----- Windows: format / diskpart / bcdedit -----
103
- {
104
- id: "win32-format",
105
- level: "destructive",
106
- test: (cmd) => cmd === "format" || cmd === "format.exe",
107
- reason: "format (Windows disk format)"
108
- },
109
- {
110
- id: "win32-diskpart",
111
- level: "destructive",
112
- test: (cmd) => cmd === "diskpart" || cmd === "diskpart.exe",
113
- reason: "diskpart (Windows partition editor)"
114
- },
115
- {
116
- id: "win32-bcdedit",
117
- level: "destructive",
118
- test: (cmd) => cmd === "bcdedit" || cmd === "bcdedit.exe",
119
- reason: "bcdedit (Windows boot config editor)"
120
- },
121
- // ----- mkfs family -----
122
- {
123
- id: "mkfs",
124
- level: "destructive",
125
- test: (cmd) => /^mkfs(\.[a-z0-9]+)?$/.test(cmd) || cmd === "mkswap",
126
- reason: "mkfs (filesystem creation \u2014 destroys existing data)"
127
- },
128
- // ----- dd writing to a block device -----
129
- {
130
- id: "dd-to-block-device",
131
- level: "destructive",
132
- test: (cmd, args) => {
133
- if (cmd !== "dd") return false;
134
- return args.some((a) => /of=\/dev\/(sd|hd|nvme|vd|mmcblk|xvd|loop|disk)/.test(a));
135
- },
136
- reason: "dd writing to a block device"
137
- },
138
- // ----- Secure-erase tools -----
139
- {
140
- id: "shred",
141
- level: "destructive",
142
- test: (cmd) => cmd === "shred" || cmd === "shred.exe",
143
- reason: "shred (secure file delete)"
144
- },
145
- {
146
- id: "wipefs",
147
- level: "destructive",
148
- test: (cmd) => cmd === "wipefs" || cmd === "wipefs.exe",
149
- reason: "wipefs (signature wipe \u2014 destroys filesystem headers)"
150
- },
151
- {
152
- id: "sdelete",
153
- level: "destructive",
154
- test: (cmd) => cmd === "sdelete" || cmd === "sdelete.exe",
155
- reason: "sdelete (Sysinternals secure delete)"
156
- },
157
- // ----- VCS history rewrite (destructive) -----
158
- // `git push --force` / `-f` rewrites remote history. `--force-with-lease`
159
- // is the safer variant (checks remote hasn't moved) but still rewrites.
160
- {
161
- id: "git-push-force",
162
- level: "destructive",
163
- test: (cmd, args) => {
164
- if (cmd !== "git") return false;
165
- const pushIdx = args.indexOf("push");
166
- if (pushIdx < 0) return false;
167
- for (let i = pushIdx + 1; i < args.length; i++) {
168
- const a = args[i];
169
- if (a === "--force" || a === "-f" || a === "--force-with-lease") return true;
170
- if (!a.startsWith("-") && !a.includes("=")) continue;
171
- if (a.startsWith("--force")) return true;
172
- }
173
- return false;
174
- },
175
- reason: "git push with --force / -f (rewrites remote history)"
176
- },
177
- // ----- git reset --hard (destructive) -----
178
- {
179
- id: "git-reset-hard",
180
- level: "destructive",
181
- test: (cmd, args) => cmd === "git" && args.some((a) => a === "--hard" || a.startsWith("--hard=")),
182
- reason: "git reset --hard (discards working tree + index)"
183
- },
184
- // ----- git clean -f / -fd (destructive) -----
185
- {
186
- id: "git-clean-force",
187
- level: "destructive",
188
- test: (cmd, args) => {
189
- if (cmd !== "git") return false;
190
- const cleanIdx = args.indexOf("clean");
191
- if (cleanIdx < 0) return false;
192
- return args.slice(cleanIdx + 1).some(
193
- (a) => a === "-f" || a === "--force" || a.startsWith("-f") || a.startsWith("--force=")
194
- );
195
- },
196
- reason: "git clean -f (deletes untracked files)"
197
- },
198
- // ----- package publish (destructive — public, irreversible) -----
199
- {
200
- id: "npm-publish",
201
- level: "destructive",
202
- test: (cmd, args) => {
203
- if (!["npm", "pnpm", "yarn", "bun", "cargo"].includes(cmd)) return false;
204
- return args.includes("publish") || cmd === "cargo" && args.includes("yank");
205
- },
206
- reason: "publishing to a public package registry (hard to reverse)"
207
- },
208
- // ----- k8s cluster-wide destructive ops (destructive) -----
209
- {
210
- id: "kubectl-delete-namespace",
211
- level: "destructive",
212
- test: (cmd, args) => {
213
- if (cmd !== "kubectl") return false;
214
- const delIdx = args.indexOf("delete");
215
- if (delIdx < 0) return false;
216
- const after = args.slice(delIdx + 1);
217
- return after[0] === "namespace" || after[0] === "ns";
218
- },
219
- reason: "kubectl delete namespace (deletes all resources in the namespace)"
220
- },
221
- {
222
- id: "kubectl-drain",
223
- level: "destructive",
224
- test: (cmd, args) => cmd === "kubectl" && args.includes("drain"),
225
- reason: "kubectl drain (evicts pods, marks node unschedulable)"
226
- },
227
- // ----- inline code evaluation (caution — high false-positive) -----
228
- // Common in scripts: `python -c "..."`, `node -e "..."`, `bash -c "..."`.
229
- // We tag 'caution' rather than 'destructive' because these are used in
230
- // many legitimate one-liners (e.g. `python -c "print(1)"`).
231
- {
232
- id: "inline-eval",
233
- level: "caution",
234
- test: (cmd, args) => {
235
- if (![
236
- "python",
237
- "python3",
238
- "python2",
239
- "node",
240
- "bash",
241
- "sh",
242
- "zsh",
243
- "ruby",
244
- "perl",
245
- "lua"
246
- ].includes(cmd)) {
247
- return false;
248
- }
249
- return args.some(
250
- (a) => a === "-c" || a === "-e" || a === "--eval" || a === "-eval" || a === "-E"
251
- );
252
- },
253
- reason: "inline script evaluation (-c / -e / --eval)"
254
- },
255
- // ----- pipe-to-shell (destructive — download-and-run pattern) -----
256
- // The classic `curl https://... | sh` download-and-run vector. Detected by
257
- // looking for a known fetcher piped into a shell or expression evaluator.
258
- // A shell command passed through `bash -c` / `pwsh -Command` arrives as one
259
- // argv string, so scan the reconstructed argv text rather than individual
260
- // tokens only.
261
- {
262
- id: "pipe-to-shell",
263
- level: "destructive",
264
- test: (cmd, args) => /\b(?:curl|wget|fetch|httpie|http|irm|iwr|Invoke-WebRequest|Invoke-RestMethod)\b[\s\S]{0,300}\|\s*(?:sudo\s+)?(?:sh|bash|zsh|fish|pwsh|powershell|iex|Invoke-Expression)\b/i.test(
265
- [cmd, ...args].join(" ")
266
- ),
267
- reason: "network fetch piped to a shell (download-and-run pattern)"
268
- },
269
- // ----- privilege escalation (caution) -----
270
- {
271
- id: "sudo",
272
- level: "caution",
273
- test: (cmd) => cmd === "sudo" || cmd === "doas",
274
- reason: "privilege escalation (sudo / doas)"
275
- },
276
- {
277
- id: "runas",
278
- level: "caution",
279
- test: (cmd) => cmd === "runas" || cmd === "runas.exe",
280
- reason: "Windows runas (run as different user)"
281
- },
282
- // ----- world-writable permissions (caution) -----
283
- // `chmod 777` is rarely correct. `chmod -R 777` is almost always wrong.
284
- // We only flag octal modes; symbolic modes like `chmod o+w` are
285
- // left to the operator's discretion.
286
- {
287
- id: "chmod-world-writable",
288
- level: "caution",
289
- test: (cmd, args) => {
290
- if (cmd !== "chmod") return false;
291
- return args.some((a) => /^[0-7]{3,4}$/.test(a) && /7/.test(a));
292
- },
293
- reason: "chmod with world-writable octal mode (e.g. 777)"
294
- },
295
- // ----- network recon / offensive scanners (caution) -----
296
- // These tools are purpose-built for network reconnaissance and offensive
297
- // security. They have legitimate uses in dev (security testing, infra
298
- // debugging) but their presence in an agent's command stream is worth a
299
- // caution banner so the user can notice an unexpected scan.
300
- {
301
- id: "network-scanner",
302
- level: "caution",
303
- test: (cmd) => cmd === "nmap" || cmd === "masscan" || cmd === "zmap" || cmd === "nuclei" || cmd === "hping3" || cmd === "naabu" || cmd === "katana" || cmd === "amass" || cmd === "subfinder" || cmd === "httpx" || cmd === "rustscan" || cmd === "zgrab",
304
- reason: "network scanner / offensive reconnaissance tool"
305
- },
306
- // ----- process termination (caution) -----
307
- // kill/killall/pkill terminate processes. The exec kill guard
308
- // (exec-kill-guard.ts) hard-blocks attempts on protected WrongStack
309
- // processes; this rule adds a caution banner for generic process
310
- // termination so the user sees a warning even for non-protected targets.
311
- {
312
- id: "process-kill",
313
- level: "caution",
314
- test: (cmd) => cmd === "kill" || cmd === "killall" || cmd === "pkill",
315
- reason: "process termination command"
316
- },
317
- // ----- shell/interpreter launchers (caution) -----
318
- // `env bash -c '…'`, `timeout sh`, `nohup perl -e '…'` etc. wrap a child
319
- // binary that bypasses the allowlist name-gate entirely (the wrapper
320
- // resolves the child from PATH, not from the allowlist). We flag caution
321
- // when a known launcher has a shell/interpreter as its target program.
322
- {
323
- id: "shell-launcher",
324
- level: "caution",
325
- test: (cmd, args) => {
326
- const launchers = [
327
- "env",
328
- "timeout",
329
- "nohup",
330
- "nice",
331
- "script",
332
- "expect",
333
- "tmux",
334
- "screen",
335
- "byobu",
336
- "dtach"
337
- ];
338
- if (!launchers.includes(cmd)) return false;
339
- const shells = [
340
- "sh",
341
- "bash",
342
- "zsh",
343
- "fish",
344
- "python",
345
- "python3",
346
- "perl",
347
- "ruby",
348
- "node",
349
- "pwsh",
350
- "powershell",
351
- "cmd"
352
- ];
353
- if (cmd === "env") {
354
- const prog = args.find((a) => !a.includes("=") && !a.startsWith("-"));
355
- return prog !== void 0 && shells.includes(prog);
356
- }
357
- return args.some((a) => shells.includes(a));
358
- },
359
- reason: "launcher wrapping a shell/interpreter (bypasses allowlist name-gate)"
360
- }
361
- ];
362
- function detectDanger(cmd, args, bypass) {
363
- const reasons = [];
364
- let level = "safe";
365
- let matchedRule;
366
- for (const rule of RULES) {
367
- if (bypass?.has(rule.id)) continue;
368
- if (!rule.test(cmd, args)) continue;
369
- reasons.push(rule.reason);
370
- if (matchedRule === void 0 || levelRank(rule.level) >= levelRank(level)) {
371
- matchedRule = rule.id;
372
- }
373
- if (levelRank(rule.level) > levelRank(level)) {
374
- level = rule.level;
375
- }
376
- }
377
- if (level === "safe") return { level: "safe", reasons: [] };
378
- const result = { level, reasons };
379
- if (matchedRule !== void 0) result.matchedRule = matchedRule;
380
- return result;
381
- }
382
- function levelRank(level) {
383
- switch (level) {
384
- case "safe":
385
- return 0;
386
- case "caution":
387
- return 1;
388
- case "destructive":
389
- return 2;
390
- }
391
- }
392
-
393
- // src/_env.ts
394
- import { buildChildEnv } from "@wrongstack/core/utils";
395
-
396
- // src/_output-spool.ts
397
- import { createWriteStream, mkdirSync } from "node:fs";
398
- import * as fsp from "node:fs/promises";
399
- import * as path from "node:path";
400
- import { wstackGlobalRoot } from "@wrongstack/core/utils";
401
- var SPOOL_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
402
- var SPOOL_WRITE_HWM_BYTES = 4 * 1024 * 1024;
403
- var sweepStarted = false;
404
- function toolOutputDir() {
405
- return path.join(wstackGlobalRoot(), "tool-output");
406
- }
407
- function sweepOldSpoolFiles(dir) {
408
- if (sweepStarted) return;
409
- sweepStarted = true;
410
- void (async () => {
411
- try {
412
- const now = Date.now();
413
- for (const name of await fsp.readdir(dir)) {
414
- if (!name.endsWith(".log")) continue;
415
- const p = path.join(dir, name);
416
- try {
417
- const st = await fsp.stat(p);
418
- if (now - st.mtimeMs > SPOOL_RETENTION_MS) await fsp.unlink(p);
419
- } catch {
420
- }
421
- }
422
- } catch {
423
- }
424
- })();
425
- }
426
- function spoolNote(info) {
427
- const dropped = info.droppedBytes > 0 ? `, ~${info.droppedBytes} bytes dropped under backpressure` : "";
428
- return `
429
- [output truncated \u2014 full ${info.bytes} bytes at ${info.path}${dropped}; read/grep that file selectively instead of re-running with more output]`;
430
- }
431
- function createOutputSpool(opts) {
432
- const threshold = opts.thresholdBytes ?? 32768;
433
- const safeTool = opts.tool.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 40) || "tool";
434
- let head = "";
435
- let headBytes = 0;
436
- let totalBytes = 0;
437
- let droppedBytes = 0;
438
- let stream = null;
439
- let filePath = null;
440
- let failed = false;
441
- let finalized = false;
442
- const open = () => {
443
- if (stream || failed) return;
444
- try {
445
- const dir = toolOutputDir();
446
- mkdirSync(dir, { recursive: true });
447
- sweepOldSpoolFiles(dir);
448
- const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
449
- const rand = Math.random().toString(36).slice(2, 6);
450
- filePath = path.join(dir, `${stamp}-${safeTool}-${rand}.log`);
451
- stream = createWriteStream(filePath, { flags: "w", encoding: "utf8" });
452
- stream.on("error", () => {
453
- failed = true;
454
- stream = null;
455
- filePath = null;
456
- });
457
- stream.write(head);
458
- } catch {
459
- failed = true;
460
- stream = null;
461
- filePath = null;
462
- }
463
- };
464
- return {
465
- write(text) {
466
- if (finalized || !text) return;
467
- const textBytes = Buffer.byteLength(text, "utf8");
468
- totalBytes += textBytes;
469
- if (!stream && !failed) {
470
- if (headBytes + textBytes <= threshold) {
471
- head += text;
472
- headBytes += textBytes;
473
- return;
474
- }
475
- head += text;
476
- open();
477
- head = "";
478
- return;
479
- }
480
- if (stream) {
481
- if (stream.writableLength > SPOOL_WRITE_HWM_BYTES) {
482
- droppedBytes += textBytes;
483
- return;
484
- }
485
- stream.write(text);
486
- }
487
- },
488
- finalize() {
489
- if (finalized) {
490
- return filePath ? { path: filePath, bytes: totalBytes, droppedBytes } : null;
491
- }
492
- finalized = true;
493
- head = "";
494
- if (!stream || !filePath) return null;
495
- try {
496
- stream.end();
497
- } catch {
498
- }
499
- return { path: filePath, bytes: totalBytes, droppedBytes };
500
- }
501
- };
502
- }
503
-
504
- // src/_util.ts
505
- import * as fsp2 from "node:fs/promises";
506
- import * as path2 from "node:path";
507
- import * as Core from "@wrongstack/core/utils";
508
- function resolvePath(input, ctx) {
509
- return path2.isAbsolute(input) ? path2.normalize(input) : path2.resolve(ctx.workingDir ?? ctx.cwd, input);
510
- }
511
- function allowedRoots(ctx) {
512
- return [path2.resolve(ctx.projectRoot), path2.resolve(Core.wstackGlobalRoot())];
513
- }
514
- function isInsideAny(target, roots) {
515
- return roots.some((root) => {
516
- const rel = path2.relative(root, target);
517
- return rel === "" || !rel.startsWith("..") && !path2.isAbsolute(rel);
518
- });
519
- }
520
- function ensureInsideRoot(absPath, ctx) {
521
- const target = path2.resolve(absPath);
522
- if (ctx.allowOutsideProjectRoot) return target;
523
- if (isInsideAny(target, allowedRoots(ctx))) return target;
524
- throw new Error(`Path "${absPath}" is outside project root "${path2.resolve(ctx.projectRoot)}"`);
525
- }
526
- function safeResolve(input, ctx) {
527
- return ensureInsideRoot(resolvePath(input, ctx), ctx);
528
- }
529
- async function resolveRealInsideRoot(absPath, ctx) {
530
- if (ctx.allowOutsideProjectRoot) return absPath;
531
- const realRoots = await Promise.all(
532
- allowedRoots(ctx).map((r) => fsp2.realpath(r).catch(() => path2.resolve(r)))
533
- );
534
- let probe = absPath;
535
- const pendingTail = [];
536
- for (; ; ) {
537
- let real;
538
- try {
539
- real = await fsp2.realpath(probe);
540
- } catch (err) {
541
- if (err.code === "ENOENT") {
542
- const parent = path2.dirname(probe);
543
- if (parent === probe) return absPath;
544
- pendingTail.unshift(path2.basename(probe));
545
- probe = parent;
546
- continue;
547
- }
548
- throw err;
549
- }
550
- const candidate = pendingTail.length > 0 ? path2.join(real, ...pendingTail) : real;
551
- if (isInsideAny(candidate, realRoots)) {
552
- return candidate;
553
- }
554
- throw new Error(
555
- `Path "${absPath}" resolves through a symlink outside project root "${realRoots[0]}"`
556
- );
557
- }
558
- }
559
- async function safeResolveReal(input, ctx) {
560
- const abs = safeResolve(input, ctx);
561
- return await resolveRealInsideRoot(abs, ctx);
562
- }
563
- var COMMAND_OUTPUT_MAX_BYTES = 32768;
564
- var REPEAT_RUN_THRESHOLD = 3;
565
- function collapseCarriageReturns(text) {
566
- const lf = text.replace(/\r\n/g, "\n");
567
- if (!lf.includes("\r")) return lf;
568
- return lf.split("\n").map((line) => line.includes("\r") ? line.slice(line.lastIndexOf("\r") + 1) : line).join("\n");
569
- }
570
- function collapseConsecutiveDuplicates(text, minRun = REPEAT_RUN_THRESHOLD) {
571
- const lines = text.split("\n");
572
- const out = [];
573
- let i = 0;
574
- while (i < lines.length) {
575
- let j = i + 1;
576
- while (j < lines.length && lines[j] === lines[i]) j++;
577
- const run = j - i;
578
- if (run >= minRun) {
579
- out.push(lines[i], `\u2026 \u27E8repeated ${run}\xD7\u27E9`);
580
- } else {
581
- for (let k = i; k < j; k++) out.push(lines[k]);
582
- }
583
- i = j;
584
- }
585
- return out.join("\n");
586
- }
587
- function takeHeadBytes(s, maxBytes) {
588
- if (maxBytes <= 0) return "";
589
- if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
590
- let lo = 0;
591
- let hi = s.length;
592
- while (lo < hi) {
593
- const mid = Math.ceil((lo + hi) / 2);
594
- if (Buffer.byteLength(s.slice(0, mid), "utf8") <= maxBytes) lo = mid;
595
- else hi = mid - 1;
596
- }
597
- return s.slice(0, lo);
598
- }
599
- function takeTailBytes(s, maxBytes) {
600
- if (maxBytes <= 0) return "";
601
- if (Buffer.byteLength(s, "utf8") <= maxBytes) return s;
602
- let lo = 0;
603
- let hi = s.length;
604
- while (lo < hi) {
605
- const mid = Math.ceil((lo + hi) / 2);
606
- if (Buffer.byteLength(s.slice(s.length - mid), "utf8") <= maxBytes) lo = mid;
607
- else hi = mid - 1;
608
- }
609
- return s.slice(s.length - lo);
610
- }
611
- function truncateHeadTail(s, maxBytes) {
612
- const total = Buffer.byteLength(s, "utf8");
613
- if (total <= maxBytes) return s;
614
- const MARKER_RESERVE = 64;
615
- const avail = Math.max(0, maxBytes - MARKER_RESERVE);
616
- const headBudget = Math.floor(avail * 0.45);
617
- const head = takeHeadBytes(s, headBudget);
618
- const tail = takeTailBytes(s, avail - Buffer.byteLength(head, "utf8"));
619
- const kept = Buffer.byteLength(head, "utf8") + Buffer.byteLength(tail, "utf8");
620
- return `${head}
621
- \u2026[truncated ${total - kept} bytes]\u2026
622
- ${tail}`;
623
- }
624
- function normalizeCommandOutput(raw, opts = {}) {
625
- if (!raw) return raw;
626
- let text = Core.stripAnsi(raw);
627
- text = collapseCarriageReturns(text);
628
- text = text.replace(/[ \t]+$/gm, "");
629
- text = collapseConsecutiveDuplicates(text);
630
- text = text.replace(/\n{3,}/g, "\n\n");
631
- return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);
632
- }
633
-
634
- // src/_win32-resolve.ts
635
- import * as fs from "node:fs";
636
- import * as path3 from "node:path";
637
- function resolveWin32Command(cmd) {
638
- if (process.platform !== "win32") return cmd;
639
- if (cmd.includes("/") || cmd.includes("\\") || path3.extname(cmd.replace(/\//g, "\\"))) {
640
- return cmd;
641
- }
642
- const pathext = (process.env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC").toLowerCase().split(";");
643
- const pathDirs = (process.env["PATH"] ?? "").split(path3.delimiter);
644
- for (const dir of pathDirs) {
645
- const base = path3.join(dir, cmd);
646
- for (const ext of pathext) {
647
- const full = `${base}${ext}`;
648
- try {
649
- fs.accessSync(full, fs.constants.X_OK);
650
- return full;
651
- } catch {
652
- }
653
- }
654
- }
655
- return cmd;
656
- }
657
- var WIN32_SHELL_META = /[&|<>"%\r\n\0]/;
658
- function assertSafeWin32ShellArgs(args) {
659
- for (const arg of args) {
660
- if (typeof arg === "string" && WIN32_SHELL_META.test(arg)) {
661
- throw new Error(
662
- 'win32 cmd shim spawn: argument contains a shell metacharacter (one of & | < > " %, or a newline) that could enable command injection through the .cmd/.bat wrapper - refusing to run. Offending argument: ' + JSON.stringify(arg)
663
- );
664
- }
665
- }
666
- }
667
- function buildWin32CmdShimInvocation(command, args = []) {
668
- assertSafeWin32ShellArgs([command, ...args]);
669
- const line = ["call", quoteWin32CmdArg(command), ...args.map(quoteWin32CmdArg)].join(" ");
670
- return {
671
- command: process.env["COMSPEC"] ?? "cmd.exe",
672
- args: ["/d", "/c", line],
673
- windowsVerbatimArguments: true
674
- };
675
- }
676
- function quoteWin32CmdArg(arg) {
677
- return `"${arg}"`;
678
- }
679
-
680
- // src/exec-kill-guard.ts
681
- import * as os3 from "node:os";
682
- import * as path5 from "node:path";
683
-
684
- // src/process-registry-persistent.ts
685
- import * as fs2 from "node:fs/promises";
686
- import * as os2 from "node:os";
687
- import { wstackGlobalRoot as wstackGlobalRoot3 } from "@wrongstack/core/utils";
688
- import * as path4 from "node:path";
689
-
690
- // src/process-registry.ts
691
- import { spawn } from "node:child_process";
692
- import * as os from "node:os";
693
-
694
- // src/circuit-breaker.ts
695
- var DEFAULT_MAX_CONSECUTIVE_FAILURES = 5;
696
- var DEFAULT_SLOW_CALL_THRESHOLD_MS = 18e4;
697
- var DEFAULT_MAX_SLOW_CALLS = 3;
698
- var DEFAULT_WINDOW_MS = 6e4;
699
- var DEFAULT_MAX_CALLS_PER_WINDOW = 30;
700
- var DEFAULT_COOLDOWN_MS = 3e4;
701
- var CircuitBreaker = class {
702
- maxConsecutiveFailures;
703
- slowCallThresholdMs;
704
- maxSlowCalls;
705
- windowMs;
706
- maxCallsPerWindow;
707
- cooldownMs;
708
- state = "closed";
709
- consecutiveFailures = 0;
710
- window = [];
711
- lastFailureAt = null;
712
- lastSlowAt = null;
713
- /** Timestamp when the breaker was opened (for cooldown calculation). */
714
- openedAt = null;
715
- /**
716
- * Master enable flag. When false the breaker is bypassed: `beforeCall`
717
- * always returns true and `afterCall` records nothing. The class itself
718
- * defaults to enabled (so the standalone unit tests exercise tripping); the
719
- * ProcessRegistry flips this off until the user opts in via `/settings`.
720
- */
721
- enabled = true;
722
- /**
723
- * Fired (best-effort) when the breaker transitions into the `open` state.
724
- * The registry uses this to arm its auto kill/reset countdown.
725
- */
726
- onTrip;
727
- /**
728
- * Fired (best-effort) when the breaker returns to `closed` after having been
729
- * open/half-open. The registry uses this to cancel a pending kill/reset.
730
- */
731
- onReset;
732
- constructor(config = {}) {
733
- this.maxConsecutiveFailures = config.maxConsecutiveFailures ?? DEFAULT_MAX_CONSECUTIVE_FAILURES;
734
- this.slowCallThresholdMs = config.slowCallThresholdMs ?? DEFAULT_SLOW_CALL_THRESHOLD_MS;
735
- this.maxSlowCalls = config.maxSlowCalls ?? DEFAULT_MAX_SLOW_CALLS;
736
- this.windowMs = config.windowMs ?? DEFAULT_WINDOW_MS;
737
- this.maxCallsPerWindow = config.maxCallsPerWindow ?? DEFAULT_MAX_CALLS_PER_WINDOW;
738
- this.cooldownMs = config.cooldownMs ?? DEFAULT_COOLDOWN_MS;
739
- }
740
- /** Toggle the master enable. Disabling resets to a clean `closed` state. */
741
- setEnabled(enabled) {
742
- if (this.enabled === enabled) return;
743
- this.enabled = enabled;
744
- if (!enabled) this._reset();
745
- }
746
- get isEnabled() {
747
- return this.enabled;
748
- }
749
- /**
750
- * Returns true if the circuit allows a new call to proceed.
751
- * When false, callers should abort the tool call and return a
752
- * circuit-breaker error instead of spawning a process.
753
- */
754
- get canProceed() {
755
- if (!this.enabled) return true;
756
- this._checkStateTransition();
757
- return this.state !== "open";
758
- }
759
- /**
760
- * Snapshot of the current breaker state for observability (`/kill`).
761
- */
762
- snapshot() {
763
- this._checkStateTransition();
764
- const now = Date.now();
765
- let cooldownRemaining = null;
766
- if (this.openedAt !== null && this.state === "open") {
767
- const elapsed = now - this.openedAt;
768
- cooldownRemaining = Math.max(0, this.cooldownMs - elapsed);
769
- }
770
- return {
771
- state: this.state,
772
- consecutiveFailures: this.consecutiveFailures,
773
- slowCallsInWindow: this.window.filter((c) => c.slow).length,
774
- callsInWindow: this.window.length,
775
- windowMs: this.windowMs,
776
- cooldownRemainingMs: cooldownRemaining,
777
- lastFailureAt: this.lastFailureAt,
778
- lastSlowAt: this.lastSlowAt
779
- };
780
- }
781
- /**
782
- * Call this BEFORE spawning a bash/exec process.
783
- * Returns true if the call is allowed; false if the breaker is open.
784
- * When false, callers MUST NOT spawn a process.
785
- *
786
- * @param bypass - If true, skip the circuit breaker check entirely.
787
- * Use for background/fire-and-forget processes that should
788
- * not affect breaker state.
789
- */
790
- beforeCall(bypass = false) {
791
- if (bypass || !this.enabled) return true;
792
- this._checkStateTransition();
793
- if (this.state === "open") return false;
794
- return true;
795
- }
796
- /**
797
- * Call this AFTER a bash/exec process finishes (success or failure).
798
- * `durationMs` is the wall-clock time the process ran.
799
- * `failed` is true when the process returned a non-zero exit code or
800
- * threw an exception before spawning.
801
- *
802
- * @param bypass - If true, do not update breaker state.
803
- * Use for background/fire-and-forget processes.
804
- */
805
- afterCall(durationMs, failed, bypass = false) {
806
- if (bypass || !this.enabled) return;
807
- const now = Date.now();
808
- if (this.state === "half-open") {
809
- if (failed) {
810
- this._trip();
811
- return;
812
- }
813
- this._reset();
814
- return;
815
- }
816
- this._pruneWindow(now);
817
- const slow = durationMs >= this.slowCallThresholdMs;
818
- this.window.push({ at: now, failed, slow });
819
- if (failed) {
820
- this.consecutiveFailures++;
821
- this.lastFailureAt = now;
822
- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
823
- this._trip();
824
- }
825
- return;
826
- }
827
- this.consecutiveFailures = 0;
828
- if (slow) {
829
- this.lastSlowAt = now;
830
- const slowCount = this.window.filter((c) => c.slow).length;
831
- if (slowCount >= this.maxSlowCalls) {
832
- this._trip();
833
- }
834
- }
835
- const callCount = this.window.length;
836
- if (callCount >= this.maxCallsPerWindow) {
837
- this._trip();
838
- }
839
- }
840
- /** Force the breaker open. Used by /kill force and Ctrl+C. */
841
- forceOpen() {
842
- this._trip();
843
- }
844
- /** Force a reset to closed. Used by tests and /kill reset. */
845
- forceReset() {
846
- this._reset();
847
- }
848
- _trip() {
849
- if (this.state === "open") return;
850
- this.state = "open";
851
- this.openedAt = Date.now();
852
- this.window = [];
853
- try {
854
- this.onTrip?.();
855
- } catch {
856
- }
857
- }
858
- _reset() {
859
- const wasRecovering = this.state !== "closed";
860
- this.state = "closed";
861
- this.consecutiveFailures = 0;
862
- this.window = [];
863
- this.openedAt = null;
864
- if (wasRecovering) {
865
- try {
866
- this.onReset?.();
867
- } catch {
868
- }
869
- }
870
- }
871
- /** Transition from open → half-open when cooldown elapses. */
872
- _checkStateTransition() {
873
- if (this.state !== "open" || this.openedAt === null) return;
874
- const elapsed = Date.now() - this.openedAt;
875
- if (elapsed >= this.cooldownMs) {
876
- this.state = "half-open";
877
- this.openedAt = null;
878
- }
879
- }
880
- _pruneWindow(now) {
881
- const cutoff = now - this.windowMs;
882
- this.window = this.window.filter((c) => c.at >= cutoff);
883
- }
884
- };
885
-
886
- // src/_redact-command.ts
887
- import { expectDefined } from "@wrongstack/core/utils";
888
- var SENSITIVE_FLAG_PATTERNS = [
889
- // --flag=value or --flag "value" (value captured up to next space or comma)
890
- /--(?: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,
891
- // -t short flag (token): attached (-tVALUE), separated (-t VALUE), or -t=VALUE.
892
- // (?<![-\w]) anchors to a token start so we don't match the `-t` inside `--token`.
893
- // The value must be token-like (>= 8 chars) so ordinary combined flags such
894
- // as `tar -tf` / `ssh -tt` are not eaten. Global flag: EVERY occurrence is
895
- // redacted, not just the first.
896
- // NOTE: synced with @wrongstack/core observability/redact-command.ts.
897
- /(?<![-\w])-t(?:[=\s]+)?[^\s,-]{8,}/g,
898
- // -p|-password|-a (redis auth) short flags: attached + separated + =value.
899
- // Same token-start anchor; over-redaction is an accepted tradeoff for a
900
- // redaction function. Synced with core copy.
901
- /(?<![-\w])-(?:password|p|a)(?:[=\s]+)?[^\s,-]+/gi,
902
- // env var–style secrets: TOKEN=x, API_KEY=y, etc.
903
- /(?: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,
904
- // Generic high-entropy look: base64 strings >32 chars or hex strings >32 digits — but only
905
- // when preceded by a flag name (e.g. --github-token=EyJ...). Global flag so
906
- // every such flag in the command line is redacted, not just the first.
907
- /--\w*(?:token|key|secret|password|passwd|auth|credential)\w*[=\s,][A-Za-z0-9+/=]{32,}/g
908
- ];
909
- function redactCommand(cmd) {
910
- let result = cmd;
911
- for (const pattern of SENSITIVE_FLAG_PATTERNS) {
912
- result = result.replace(pattern, (match) => {
913
- const eq = match.indexOf("=");
914
- const sp = match.search(/\s/);
915
- const delim = eq !== -1 ? "=" : sp !== -1 ? match[sp] : null;
916
- if (delim !== null) {
917
- const flag = match.slice(0, match.indexOf(expectDefined(delim)) + 1);
918
- return `${flag}[REDACTED]`;
919
- }
920
- if (match.startsWith("--")) {
921
- return match;
922
- }
923
- return `${match.slice(0, 2)}[REDACTED]`;
924
- });
925
- }
926
- return result;
927
- }
928
-
929
- // src/process-registry.ts
930
- var DEFAULT_GRACE_MS = 2e3;
931
- var WIN32_TASKKILL_TIMEOUT_MS = 5e3;
932
- function killWin32Tree(pid, opts = {}) {
933
- try {
934
- const child = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
935
- stdio: "ignore",
936
- windowsHide: true
937
- });
938
- let settled = false;
939
- let timeout;
940
- const settle = () => {
941
- if (settled) return;
942
- settled = true;
943
- if (timeout) clearTimeout(timeout);
944
- try {
945
- opts.onSettled?.();
946
- } catch {
947
- }
948
- };
949
- child.on("error", settle);
950
- child.on("close", settle);
951
- timeout = setTimeout(
952
- () => {
953
- try {
954
- child.kill();
955
- } catch {
956
- }
957
- settle();
958
- },
959
- Math.max(1, opts.timeoutMs ?? WIN32_TASKKILL_TIMEOUT_MS)
960
- );
961
- timeout.unref?.();
962
- child.unref();
963
- return true;
964
- } catch {
965
- return false;
966
- }
967
- }
968
- var ProcessRegistryImpl = class {
969
- processes = /* @__PURE__ */ new Map();
970
- breaker;
971
- /**
972
- * Auto kill/reset config. When the breaker trips and `autoKillResetMs > 0`,
973
- * a countdown is armed; on expiry all tracked processes are killed and the
974
- * breaker is reset to closed (forced recovery). Zero means manual recovery
975
- * only (`/kill reset`).
976
- */
977
- autoKillResetMs = 0;
978
- autoKillTimer = null;
979
- autoKillArmedAt = null;
980
- breakerCountdownListeners = [];
981
- constructor(breakerConfig) {
982
- this.breaker = new CircuitBreaker(breakerConfig);
983
- this.breaker.onTrip = () => this._armAutoKillReset();
984
- this.breaker.onReset = () => this._cancelAutoKillReset();
985
- this.breaker.setEnabled(false);
986
- }
987
- register(info) {
988
- this.processes.set(info.pid, {
989
- ...info,
990
- killed: false,
991
- protected: info.protected ?? false,
992
- background: info.background ?? false
993
- });
994
- }
995
- _isSafeSignalPid(pid) {
996
- return Number.isInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid;
997
- }
998
- _canSignalProcessGroup(p) {
999
- return os.platform() !== "win32" && p.processGroupLeader === true && this._isSafeSignalPid(p.pid) && p.child !== null && typeof p.child.pid === "number" && p.child.pid === p.pid;
1000
- }
1001
- _killChildDirect(p, signal) {
1002
- try {
1003
- if (p.child) {
1004
- p.child.kill(signal);
1005
- return;
1006
- }
1007
- if (this._isSafeSignalPid(p.pid)) process.kill(p.pid, signal);
1008
- } catch {
1009
- }
1010
- }
1011
- _killPosix(p, signal) {
1012
- if (this._canSignalProcessGroup(p)) {
1013
- try {
1014
- process.kill(-p.pid, signal);
1015
- return;
1016
- } catch {
1017
- }
1018
- }
1019
- this._killChildDirect(p, signal);
1020
- }
1021
- /** Unregister a process by PID. Called on 'close' / 'exit' events. */
1022
- unregister(pid) {
1023
- this.processes.delete(pid);
1024
- }
1025
- /** Get a single process by PID. */
1026
- get(pid) {
1027
- this._pruneStale(pid);
1028
- return this.processes.get(pid);
1029
- }
1030
- /** Get all tracked processes. */
1031
- list() {
1032
- this._pruneAllStale();
1033
- return Array.from(this.processes.values());
1034
- }
1035
- /** Get processes filtered by name (e.g. 'bash', 'exec'). */
1036
- byName(name) {
1037
- return this.list().filter((p) => p.name === name);
1038
- }
1039
- /** Get processes filtered by session. */
1040
- bySession(sessionId) {
1041
- return this.list().filter((p) => p.sessionId === sessionId);
1042
- }
1043
- /** Count of active (non-killed) processes. */
1044
- get activeCount() {
1045
- let n = 0;
1046
- for (const p of this.processes.values()) {
1047
- if (!p.killed) n++;
1048
- }
1049
- return n;
1050
- }
1051
- /** Count of active jobs explicitly launched in background mode. */
1052
- get activeBackgroundCount() {
1053
- let n = 0;
1054
- for (const p of this.processes.values()) {
1055
- if (p.background && !p.killed) n++;
1056
- }
1057
- return n;
1058
- }
1059
- /**
1060
- * Combined stats for observability — used by /ps and the TUI status bar.
1061
- */
1062
- stats() {
1063
- this._pruneAllStale();
1064
- return {
1065
- activeCount: this.activeCount,
1066
- backgroundCount: this.activeBackgroundCount,
1067
- totalCount: this.processes.size,
1068
- breaker: this.breaker.snapshot()
1069
- };
1070
- }
1071
- /**
1072
- * Returns true if the circuit allows a new bash/exec call to proceed.
1073
- * When false, callers MUST NOT spawn a process.
1074
- */
1075
- get canProceed() {
1076
- return this.breaker.canProceed;
1077
- }
1078
- /**
1079
- * Called before spawning a process. Returns true if allowed; false if
1080
- * the circuit breaker is open.
1081
- *
1082
- * @param bypass - If true, skip circuit breaker check (for background processes).
1083
- */
1084
- beforeCall(bypass = false) {
1085
- return this.breaker.beforeCall(bypass);
1086
- }
1087
- /**
1088
- * Called after a process finishes. `durationMs` is wall-clock time;
1089
- * `failed` is true for non-zero exit codes.
1090
- *
1091
- * @param bypass - If true, do not update circuit breaker state (for background processes).
1092
- */
1093
- afterCall(durationMs, failed, bypass = false) {
1094
- this.breaker.afterCall(durationMs, failed, bypass);
1095
- }
1096
- /** Force-open the circuit breaker (Ctrl+C, /kill force). */
1097
- forceBreakerOpen() {
1098
- this.breaker.forceOpen();
1099
- }
1100
- /** Force-reset the circuit breaker to closed (/kill reset). */
1101
- forceBreakerReset() {
1102
- this.breaker.forceReset();
1103
- }
1104
- /**
1105
- * Configure circuit-breaker protection at runtime. Called from `/settings`
1106
- * (instant, all modes) and on TUI mount (applies persisted config).
1107
- *
1108
- * - `enabled` toggles whether the breaker gates `bash`/`exec`.
1109
- * - `autoKillResetMs` arms the auto kill/reset countdown when the breaker
1110
- * trips (0 = manual recovery only).
1111
- *
1112
- * Re-applies cleanly on every call: cancels a pending countdown when the
1113
- * timeout is cleared or protection disabled, and re-arms if the breaker is
1114
- * currently open under the new settings.
1115
- */
1116
- setBreakerConfig(cfg) {
1117
- if (cfg.enabled !== void 0) this.breaker.setEnabled(cfg.enabled);
1118
- if (cfg.autoKillResetMs !== void 0) this.autoKillResetMs = Math.max(0, cfg.autoKillResetMs);
1119
- if (this.autoKillResetMs <= 0) {
1120
- this._cancelAutoKillReset();
1121
- return;
1122
- }
1123
- if (this.breaker.isEnabled && this.breaker.snapshot().state === "open") {
1124
- this._armAutoKillReset();
1125
- }
1126
- }
1127
- /**
1128
- * Live countdown to the next auto kill/reset, or null when nothing is armed.
1129
- * The TUI polls this on a 1s tick while armed so the statusline decrements.
1130
- */
1131
- getBreakerCountdown() {
1132
- if (this.autoKillArmedAt === null || this.autoKillResetMs <= 0) return null;
1133
- const elapsed = Date.now() - this.autoKillArmedAt;
1134
- return {
1135
- remainingMs: Math.max(0, this.autoKillResetMs - elapsed),
1136
- totalMs: this.autoKillResetMs
1137
- };
1138
- }
1139
- /**
1140
- * Subscribe to countdown arm/cancel events. Returns an unsubscribe function.
1141
- * Use {@link getBreakerCountdown} for the live ticking value between events.
1142
- */
1143
- onBreakerCountdownChange(listener) {
1144
- this.breakerCountdownListeners.push(listener);
1145
- return () => {
1146
- this.breakerCountdownListeners = this.breakerCountdownListeners.filter((l) => l !== listener);
1147
- };
1148
- }
1149
- _emitBreakerCountdown() {
1150
- const snap = this.getBreakerCountdown();
1151
- for (const l of this.breakerCountdownListeners) {
1152
- try {
1153
- l(snap);
1154
- } catch {
1155
- }
1156
- }
1157
- }
1158
- /**
1159
- * Arm the auto kill/reset countdown. Idempotent: re-arming resets the window
1160
- * (a fresh trip after a failed half-open probe restarts the clock). No-op
1161
- * when protection is off or no timeout is configured.
1162
- */
1163
- _armAutoKillReset() {
1164
- if (this.autoKillResetMs <= 0 || !this.breaker.isEnabled) return;
1165
- this._clearAutoKillTimer();
1166
- this.autoKillArmedAt = Date.now();
1167
- this.autoKillTimer = setTimeout(() => {
1168
- this.autoKillTimer = null;
1169
- this.autoKillArmedAt = null;
1170
- this.killAll({ force: false, preserveBackground: true });
1171
- this.breaker.forceReset();
1172
- this._emitBreakerCountdown();
1173
- }, this.autoKillResetMs);
1174
- this.autoKillTimer.unref?.();
1175
- this._emitBreakerCountdown();
1176
- }
1177
- _cancelAutoKillReset() {
1178
- const wasArmed = this.autoKillArmedAt !== null;
1179
- this._clearAutoKillTimer();
1180
- if (wasArmed) {
1181
- this.autoKillArmedAt = null;
1182
- this._emitBreakerCountdown();
1183
- }
1184
- }
1185
- _clearAutoKillTimer() {
1186
- if (this.autoKillTimer !== null) {
1187
- clearTimeout(this.autoKillTimer);
1188
- this.autoKillTimer = null;
1189
- }
1190
- }
1191
- /** Kill a single process by PID.
1192
- *
1193
- * On POSIX: sends SIGTERM to the *process group* (-pid) so that
1194
- * runaway grandchild processes (`sleep 9999 & disown`) are also killed.
1195
- * After `graceMs` a SIGKILL is sent if the process hasn't exited.
1196
- *
1197
- * On Windows: `child.kill()` maps to TerminateProcess — process groups
1198
- * are not meaningfully supported. A second `force=true` call sends
1199
- * SIGKILL (which maps to TerminateProcess again — the distinction is
1200
- * in the exit code, not the signal).
1201
- *
1202
- * Returns true if the process was found and kill was attempted.
1203
- */
1204
- kill(pid, opts = {}) {
1205
- this._pruneStale(pid);
1206
- const p = this.processes.get(pid);
1207
- if (!p) return false;
1208
- if (p.killed && opts.force !== true) return true;
1209
- if (p.protected && opts.includeProtected !== true) return false;
1210
- if (opts.preserveBackground && p.background) return false;
1211
- const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
1212
- const isWin3 = os.platform() === "win32";
1213
- if (isWin3) {
1214
- const liveRealChild = p.child === null || p.child.exitCode === null && typeof p.child.pid === "number";
1215
- const directFallback = () => {
1216
- if (p.child && p.child.exitCode === null) {
1217
- try {
1218
- p.child.kill("SIGKILL");
1219
- } catch {
1220
- }
1221
- }
1222
- };
1223
- if (liveRealChild && killWin32Tree(pid, {
1224
- timeoutMs: Math.max(graceMs, WIN32_TASKKILL_TIMEOUT_MS),
1225
- onSettled: directFallback
1226
- })) {
1227
- } else {
1228
- this._killChildDirect(p, force ? "SIGKILL" : "SIGTERM");
1229
- }
1230
- p.killed = true;
1231
- return true;
1232
- }
1233
- try {
1234
- if (force) {
1235
- this._killPosix(p, "SIGKILL");
1236
- } else {
1237
- this._killPosix(p, "SIGTERM");
1238
- const timer = setTimeout(() => {
1239
- if (this.processes.has(pid) && !p.child?.killed) {
1240
- this._killPosix(p, "SIGKILL");
1241
- }
1242
- }, graceMs);
1243
- timer.unref?.();
1244
- }
1245
- } catch {
1246
- }
1247
- p.killed = true;
1248
- return true;
1249
- }
1250
- /**
1251
- * Kill all tracked processes.
1252
- * Returns the PIDs that were kill()ed.
1253
- */
1254
- killAll(opts = {}) {
1255
- const pids = Array.from(this.processes.keys());
1256
- const killed = [];
1257
- const includeProtected = opts.includeProtected === true;
1258
- for (const pid of pids) {
1259
- const p = this.processes.get(pid);
1260
- if (!p) continue;
1261
- if (p.protected && !includeProtected) continue;
1262
- if (opts.preserveBackground && p.background) continue;
1263
- if (this.kill(pid, opts)) killed.push(pid);
1264
- }
1265
- return killed;
1266
- }
1267
- /**
1268
- * Kill all processes for a specific session.
1269
- * Returns the PIDs that were kill()ed.
1270
- */
1271
- killSession(sessionId, opts = {}) {
1272
- const pids = this.bySession(sessionId).map((p) => p.pid);
1273
- const killed = [];
1274
- for (const pid of pids) {
1275
- if (this.kill(pid, opts)) killed.push(pid);
1276
- }
1277
- return killed;
1278
- }
1279
- /**
1280
- * Check whether a tracked process entry is stale — the child has exited
1281
- * (exitCode !== null) AND it's been in the registry long enough that the
1282
- * OS may have reused the PID for a new, unrelated process.
1283
- *
1284
- * P3 #24 (before-release.md): on POSIX, PIDs are reused after process
1285
- * exit. If a tracked process exits but its 'close' event hasn't fired yet
1286
- * (or was missed), the registry still holds the entry. A new process
1287
- * gets the same PID, and PID-based lookups (get, kill, shouldBlockKill)
1288
- * may incorrectly protect or target the wrong process.
1289
- *
1290
- * The 60s threshold is conservative — the OS typically waits much longer
1291
- * before reusing a PID, but we want to clean up before that becomes a risk.
1292
- */
1293
- _isStaleEntry(entry) {
1294
- if (entry.child === null) {
1295
- if (Date.now() - entry.startedAt <= 6e4) return false;
1296
- if (os.platform() === "win32") return false;
1297
- try {
1298
- process.kill(entry.pid, 0);
1299
- return false;
1300
- } catch (err) {
1301
- return err.code !== "EPERM";
1302
- }
1303
- }
1304
- return entry.child.exitCode !== null && Date.now() - entry.startedAt > 6e4;
1305
- }
1306
- /**
1307
- * Remove a stale entry for a specific PID before any PID-based lookup.
1308
- * This prevents PID reuse from causing the registry to act on a dead
1309
- * process that has been replaced by a new one with the same PID.
1310
- */
1311
- _pruneStale(pid) {
1312
- const entry = this.processes.get(pid);
1313
- if (entry && this._isStaleEntry(entry)) {
1314
- this.processes.delete(pid);
1315
- }
1316
- }
1317
- /**
1318
- * Remove every stale entry, not just one PID. `list()`/`stats()` — the
1319
- * surfaces the TUI status bar and `/ps` poll — must prune too: a child
1320
- * whose 'close' event never fires (e.g. Windows grandchildren holding stdio
1321
- * open) would otherwise linger in the registry until someone looks up its
1322
- * exact PID, and PID reuse meanwhile makes `get()`/`kill()` target the
1323
- * wrong process. RAM-leak audit 2026-07-31, MEDIUM.
1324
- */
1325
- _pruneAllStale() {
1326
- for (const [pid, entry] of this.processes) {
1327
- if (this._isStaleEntry(entry)) this.processes.delete(pid);
1328
- }
1329
- }
1330
- };
1331
- var _registry;
1332
- function getProcessRegistry() {
1333
- if (!_registry) {
1334
- _registry = new ProcessRegistryImpl();
1335
- }
1336
- return _registry;
1337
- }
1338
-
1339
- // src/process-registry-persistent.ts
1340
- var REGISTRY_FILE = "process-registry.json";
1341
- function toErrorMessage(err) {
1342
- return err instanceof Error ? err.message : String(err);
1343
- }
1344
- function emitStructuredLog(level, event, message, error) {
1345
- const payload = {
1346
- level,
1347
- event,
1348
- message,
1349
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1350
- };
1351
- if (error !== void 0) {
1352
- payload.error = toErrorMessage(error);
1353
- }
1354
- console.log(JSON.stringify(payload));
1355
- }
1356
- var HEARTBEAT_INTERVAL_MS = 5e3;
1357
- var STALE_THRESHOLD_MS = 3e4;
1358
- var LOCK_STALE_MS = 3e4;
1359
- var LOCKFILE = ".process-registry.lock";
1360
- function generateInstanceId() {
1361
- const hostname2 = os2.hostname();
1362
- const pid = process.pid;
1363
- const random = Math.random().toString(36).slice(2, 8);
1364
- return `${hostname2}:${pid}:${random}`;
1365
- }
1366
- function isNodeError(err) {
1367
- return typeof err === "object" && err !== null && "code" in err;
1368
- }
1369
- async function acquireLock(lockfilePath, timeoutMs = 5e3) {
1370
- const start = Date.now();
1371
- const pidStr = String(process.pid);
1372
- const hostStr = os2.hostname();
1373
- try {
1374
- await fs2.mkdir(path4.dirname(lockfilePath), { recursive: true });
1375
- } catch {
1376
- }
1377
- while (Date.now() - start < timeoutMs) {
1378
- try {
1379
- await fs2.writeFile(lockfilePath, `${pidStr}:${hostStr}:${Date.now()}`, { flag: "wx" });
1380
- return async () => {
1381
- try {
1382
- await fs2.unlink(lockfilePath);
1383
- } catch {
1384
- }
1385
- };
1386
- } catch (err) {
1387
- if (isNodeError(err) && err.code === "EEXIST") {
1388
- try {
1389
- const content = await fs2.readFile(lockfilePath, "utf-8");
1390
- const parts = content.split(":");
1391
- const lockPid = parseInt(parts[0] ?? "0", 10);
1392
- const lockTs = Number(parts[parts.length - 1]);
1393
- const staleByAge = Number.isFinite(lockTs) && Date.now() - lockTs > LOCK_STALE_MS;
1394
- let holderDead = false;
1395
- if (process.platform !== "win32" && Number.isFinite(lockPid) && lockPid > 0) {
1396
- try {
1397
- process.kill(lockPid, 0);
1398
- } catch {
1399
- holderDead = true;
1400
- }
1401
- }
1402
- if (holderDead || staleByAge) {
1403
- await fs2.unlink(lockfilePath).catch(() => {
1404
- });
1405
- continue;
1406
- }
1407
- } catch {
1408
- await fs2.unlink(lockfilePath).catch(() => {
1409
- });
1410
- continue;
1411
- }
1412
- await new Promise((r) => setTimeout(r, 100));
1413
- continue;
1414
- }
1415
- throw err;
1416
- }
1417
- }
1418
- throw new Error(`Failed to acquire lock after ${timeoutMs}ms`);
1419
- }
1420
- function freshRegistryData() {
1421
- return {
1422
- version: 1,
1423
- instances: /* @__PURE__ */ new Map(),
1424
- protectedPatterns: ["wrongstack", "node"],
1425
- lastCleanup: Date.now()
1426
- };
1427
- }
1428
- async function readRegistryFile(filePath) {
1429
- let content;
1430
- try {
1431
- content = await fs2.readFile(filePath, "utf-8");
1432
- } catch (err) {
1433
- if (isNodeError(err) && err.code === "ENOENT") return freshRegistryData();
1434
- throw err;
1435
- }
1436
- try {
1437
- const parsed = JSON.parse(content);
1438
- if (!parsed || typeof parsed !== "object") return freshRegistryData();
1439
- const base = freshRegistryData();
1440
- return {
1441
- version: 1,
1442
- instances: Array.isArray(parsed.instances) ? new Map(parsed.instances) : base.instances,
1443
- protectedPatterns: Array.isArray(parsed.protectedPatterns) ? parsed.protectedPatterns : base.protectedPatterns,
1444
- lastCleanup: typeof parsed.lastCleanup === "number" ? parsed.lastCleanup : base.lastCleanup
1445
- };
1446
- } catch {
1447
- return freshRegistryData();
1448
- }
1449
- }
1450
- async function writeRegistryFile(filePath, data) {
1451
- const tmpPath = `${filePath}.tmp.${process.pid}`;
1452
- const content = JSON.stringify(
1453
- data,
1454
- (_k, v) => {
1455
- if (v instanceof Map) {
1456
- return Array.from(v.entries());
1457
- }
1458
- return v;
1459
- },
1460
- 2
1461
- );
1462
- await fs2.writeFile(tmpPath, content, "utf-8");
1463
- await fs2.rename(tmpPath, filePath);
1464
- }
1465
- var PersistentProcessRegistry = class {
1466
- instanceId;
1467
- registryPath;
1468
- lockPath;
1469
- baseRegistry;
1470
- heartbeatInterval = null;
1471
- cleanupInterval = null;
1472
- heartbeatRunning = false;
1473
- cleanupRunning = false;
1474
- isShuttingDown = false;
1475
- onProcessExit = () => {
1476
- this.runInBackground(
1477
- this.syncToPersistent(),
1478
- "process_registry.exit_sync_failed",
1479
- "PersistentProcessRegistry: exit sync failed"
1480
- );
1481
- };
1482
- constructor(baseRegistry) {
1483
- this.instanceId = generateInstanceId();
1484
- const globalRoot = wstackGlobalRoot3();
1485
- this.registryPath = path4.join(globalRoot, REGISTRY_FILE);
1486
- this.lockPath = path4.join(globalRoot, LOCKFILE);
1487
- this.baseRegistry = baseRegistry ?? getProcessRegistry();
1488
- this.ensureDirectory().catch((err) => {
1489
- emitStructuredLog(
1490
- "warn",
1491
- "process_registry.dir_create_failed",
1492
- "PersistentProcessRegistry: failed to create .wrongstack directory",
1493
- err
1494
- );
1495
- });
1496
- }
1497
- async ensureDirectory() {
1498
- const dir = path4.dirname(this.registryPath);
1499
- try {
1500
- await fs2.mkdir(dir, { recursive: true });
1501
- } catch (err) {
1502
- if (!isNodeError(err) || err.code !== "EEXIST") throw err;
1503
- }
1504
- }
1505
- runInBackground(operation, event, message) {
1506
- void operation.catch((err) => {
1507
- emitStructuredLog("warn", event, message, err);
1508
- });
1509
- }
1510
- /**
1511
- * Start the heartbeat and periodic cleanup tasks.
1512
- */
1513
- start() {
1514
- if (this.heartbeatInterval) return;
1515
- this.isShuttingDown = false;
1516
- this.heartbeat();
1517
- this.heartbeatInterval = setInterval(() => {
1518
- this.heartbeat();
1519
- }, HEARTBEAT_INTERVAL_MS);
1520
- this.heartbeatInterval.unref?.();
1521
- this.cleanupInterval = setInterval(() => {
1522
- this.cleanup();
1523
- }, STALE_THRESHOLD_MS);
1524
- this.cleanupInterval.unref?.();
1525
- this.registerMainProcess();
1526
- process.on("exit", this.onProcessExit);
1527
- }
1528
- /**
1529
- * Stop the heartbeat and clean up.
1530
- */
1531
- stop() {
1532
- this.isShuttingDown = true;
1533
- if (this.heartbeatInterval) {
1534
- clearInterval(this.heartbeatInterval);
1535
- this.heartbeatInterval = null;
1536
- }
1537
- if (this.cleanupInterval) {
1538
- clearInterval(this.cleanupInterval);
1539
- this.cleanupInterval = null;
1540
- }
1541
- process.off("exit", this.onProcessExit);
1542
- this.runInBackground(
1543
- this.syncToPersistent(),
1544
- "process_registry.stop_sync_failed",
1545
- "PersistentProcessRegistry: stop sync failed"
1546
- );
1547
- }
1548
- /**
1549
- * Register the main WrongStack process as protected.
1550
- */
1551
- registerMainProcess() {
1552
- const mainPid = process.pid;
1553
- this.runInBackground(
1554
- this.updatePersistentEntry({
1555
- pid: mainPid,
1556
- name: "wrongstack-main",
1557
- command: process.argv.slice(0, 3).join(" "),
1558
- startedAt: Date.now(),
1559
- lastHeartbeat: Date.now(),
1560
- instanceId: this.instanceId,
1561
- hostname: os2.hostname(),
1562
- protected: true,
1563
- spawnMode: "main",
1564
- parentPid: process.ppid,
1565
- platform: process.platform
1566
- }),
1567
- "process_registry.main_register_failed",
1568
- "PersistentProcessRegistry: failed to register main process"
1569
- );
1570
- }
1571
- /**
1572
- * Register a spawned child process with the persistent registry.
1573
- */
1574
- registerChildProcess(pid, name, command, sessionId, spawnMode = "spawn") {
1575
- const entry = {
1576
- pid,
1577
- name,
1578
- command,
1579
- startedAt: Date.now(),
1580
- lastHeartbeat: Date.now(),
1581
- instanceId: this.instanceId,
1582
- hostname: os2.hostname(),
1583
- protected: true,
1584
- // All WrongStack child processes are protected by default
1585
- spawnMode,
1586
- parentPid: process.pid,
1587
- platform: process.platform
1588
- };
1589
- if (sessionId) {
1590
- entry.sessionId = sessionId;
1591
- }
1592
- this.runInBackground(
1593
- this.updatePersistentEntry(entry),
1594
- "process_registry.child_register_failed",
1595
- "PersistentProcessRegistry: failed to register child process"
1596
- );
1597
- }
1598
- /**
1599
- * Update or add an entry in the persistent registry.
1600
- */
1601
- async updatePersistentEntry(entry) {
1602
- const release = await acquireLock(this.lockPath);
1603
- try {
1604
- const data = await readRegistryFile(this.registryPath);
1605
- data.instances.set(String(entry.pid), entry);
1606
- this.baseRegistry.register({
1607
- pid: entry.pid,
1608
- name: entry.name,
1609
- command: entry.command,
1610
- startedAt: entry.startedAt,
1611
- sessionId: entry.sessionId,
1612
- protected: entry.protected,
1613
- child: null
1614
- });
1615
- await writeRegistryFile(this.registryPath, data);
1616
- } finally {
1617
- await release();
1618
- }
1619
- }
1620
- /**
1621
- * Unregister a process from the persistent registry.
1622
- */
1623
- async unregister(pid) {
1624
- const release = await acquireLock(this.lockPath);
1625
- try {
1626
- const data = await readRegistryFile(this.registryPath);
1627
- data.instances.delete(String(pid));
1628
- await writeRegistryFile(this.registryPath, data);
1629
- } finally {
1630
- await release();
1631
- }
1632
- }
1633
- /**
1634
- * Send heartbeat to mark all this instance's processes as alive.
1635
- */
1636
- heartbeat() {
1637
- if (this.isShuttingDown || this.heartbeatRunning) return;
1638
- this.heartbeatRunning = true;
1639
- void this.syncToPersistent().catch((err) => {
1640
- emitStructuredLog(
1641
- "warn",
1642
- "process_registry.heartbeat_failed",
1643
- "PersistentProcessRegistry: heartbeat failed",
1644
- err
1645
- );
1646
- }).finally(() => {
1647
- this.heartbeatRunning = false;
1648
- });
1649
- }
1650
- cleanup() {
1651
- if (this.isShuttingDown || this.cleanupRunning) return;
1652
- this.cleanupRunning = true;
1653
- void this.cleanupStaleEntries().catch((err) => {
1654
- emitStructuredLog(
1655
- "warn",
1656
- "process_registry.periodic_cleanup_failed",
1657
- "PersistentProcessRegistry: periodic cleanup failed",
1658
- err
1659
- );
1660
- }).finally(() => {
1661
- this.cleanupRunning = false;
1662
- });
1663
- }
1664
- /**
1665
- * Sync this instance's processes to the persistent registry.
1666
- */
1667
- async syncToPersistent() {
1668
- const release = await acquireLock(this.lockPath);
1669
- try {
1670
- const data = await readRegistryFile(this.registryPath);
1671
- const now = Date.now();
1672
- const updatedInstances = /* @__PURE__ */ new Map();
1673
- for (const [_pidStr, entry] of data.instances) {
1674
- if (entry.instanceId === this.instanceId) {
1675
- entry.lastHeartbeat = now;
1676
- }
1677
- if (entry.instanceId === this.instanceId || now - entry.lastHeartbeat < STALE_THRESHOLD_MS) {
1678
- updatedInstances.set(_pidStr, entry);
1679
- }
1680
- }
1681
- data.instances = updatedInstances;
1682
- data.lastCleanup = now;
1683
- await writeRegistryFile(this.registryPath, data);
1684
- } catch (err) {
1685
- emitStructuredLog(
1686
- "warn",
1687
- "process_registry.sync_failed",
1688
- "PersistentProcessRegistry: sync failed",
1689
- err
1690
- );
1691
- } finally {
1692
- await release();
1693
- }
1694
- }
1695
- /**
1696
- * Remove entries for processes that are no longer running.
1697
- */
1698
- async cleanupStaleEntries() {
1699
- const release = await acquireLock(this.lockPath);
1700
- try {
1701
- const data = await readRegistryFile(this.registryPath);
1702
- const now = Date.now();
1703
- const stalePids = [];
1704
- for (const [_pidStr, entry] of data.instances) {
1705
- const age = now - entry.lastHeartbeat;
1706
- if (age > STALE_THRESHOLD_MS) {
1707
- try {
1708
- if (process.platform !== "win32") {
1709
- process.kill(entry.pid, 0);
1710
- } else {
1711
- emitStructuredLog(
1712
- "debug",
1713
- "process_registry.stale_pid_check",
1714
- `PersistentProcessRegistry: checking stale pid ${entry.pid} (${age}ms old)`
1715
- );
1716
- }
1717
- } catch {
1718
- stalePids.push(_pidStr);
1719
- }
1720
- }
1721
- }
1722
- if (stalePids.length > 0) {
1723
- for (const pidStr of stalePids) {
1724
- data.instances.delete(pidStr);
1725
- }
1726
- await writeRegistryFile(this.registryPath, data);
1727
- }
1728
- } catch (err) {
1729
- emitStructuredLog(
1730
- "warn",
1731
- "process_registry.cleanup_failed",
1732
- "PersistentProcessRegistry: cleanup failed",
1733
- err
1734
- );
1735
- } finally {
1736
- await release();
1737
- }
1738
- }
1739
- /**
1740
- * Check if a PID belongs to a WrongStack process and should be protected.
1741
- */
1742
- async isProtectedPid(pid) {
1743
- const release = await acquireLock(this.lockPath);
1744
- try {
1745
- const data = await readRegistryFile(this.registryPath);
1746
- const entry = data.instances.get(String(pid));
1747
- if (!entry) return false;
1748
- if (Date.now() - entry.lastHeartbeat > STALE_THRESHOLD_MS) {
1749
- return false;
1750
- }
1751
- return entry.protected;
1752
- } finally {
1753
- await release();
1754
- }
1755
- }
1756
- /**
1757
- * Get all protected PIDs from all WrongStack instances.
1758
- */
1759
- async getAllProtectedPids() {
1760
- const release = await acquireLock(this.lockPath);
1761
- try {
1762
- const data = await readRegistryFile(this.registryPath);
1763
- const now = Date.now();
1764
- const protectedPids = [];
1765
- for (const [_pidStr, entry] of data.instances) {
1766
- if (entry.protected && now - entry.lastHeartbeat < STALE_THRESHOLD_MS) {
1767
- protectedPids.push(entry.pid);
1768
- }
1769
- }
1770
- return protectedPids;
1771
- } finally {
1772
- await release();
1773
- }
1774
- }
1775
- /**
1776
- * Get complete status of all tracked processes across all instances.
1777
- */
1778
- async getGlobalStatus() {
1779
- const release = await acquireLock(this.lockPath);
1780
- try {
1781
- const data = await readRegistryFile(this.registryPath);
1782
- const now = Date.now();
1783
- const instances = /* @__PURE__ */ new Map();
1784
- let protectedCount = 0;
1785
- let staleCount = 0;
1786
- for (const [_pidStr, entry] of data.instances) {
1787
- const instanceEntries = instances.get(entry.instanceId) ?? [];
1788
- instanceEntries.push(entry);
1789
- instances.set(entry.instanceId, instanceEntries);
1790
- if (entry.protected) protectedCount++;
1791
- if (now - entry.lastHeartbeat > STALE_THRESHOLD_MS) staleCount++;
1792
- }
1793
- return {
1794
- instances,
1795
- totalProcesses: data.instances.size,
1796
- protectedCount,
1797
- staleCount
1798
- };
1799
- } finally {
1800
- await release();
1801
- }
1802
- }
1803
- /**
1804
- * Get the instance ID for this process.
1805
- */
1806
- getInstanceId() {
1807
- return this.instanceId;
1808
- }
1809
- /**
1810
- * Check if a kill command should be blocked.
1811
- * Returns true if the kill should be blocked (target is a WrongStack process).
1812
- */
1813
- async shouldBlockKill(pid) {
1814
- const protectedPids = await this.getAllProtectedPids();
1815
- return protectedPids.includes(pid);
1816
- }
1817
- /**
1818
- * Add a pattern-based protection rule.
1819
- * Processes whose command matches any protected pattern are protected.
1820
- */
1821
- async addProtectedPattern(pattern) {
1822
- const release = await acquireLock(this.lockPath);
1823
- try {
1824
- const data = await readRegistryFile(this.registryPath);
1825
- if (!data.protectedPatterns.includes(pattern)) {
1826
- data.protectedPatterns.push(pattern);
1827
- await writeRegistryFile(this.registryPath, data);
1828
- }
1829
- } finally {
1830
- await release();
1831
- }
1832
- }
1833
- };
1834
- var _persistentRegistry;
1835
- function getPersistentProcessRegistry() {
1836
- if (!_persistentRegistry) {
1837
- _persistentRegistry = new PersistentProcessRegistry();
1838
- }
1839
- return _persistentRegistry;
1840
- }
1841
-
1842
- // src/exec-kill-guard.ts
1843
- var isWin = os3.platform() === "win32";
1844
- async function checkExecKillCommand(cmd, args) {
1845
- if (!cmd) return { blocked: false };
1846
- const cmdLower = cmd.toLowerCase().trim();
1847
- const fullCommand = [cmdLower, ...args].join(" ").replace(/\s+/g, " ").trim();
1848
- if (isWin) {
1849
- if (cmdLower === "taskkill" || cmdLower === "taskkill.exe") {
1850
- const hasForce = args.some((a) => a.toUpperCase() === "/F" || a.toUpperCase() === "-F");
1851
- const signal = hasForce ? "FORCE" : "TERM";
1852
- for (let i = 0; i < args.length; i++) {
1853
- const a = args[i];
1854
- if (a.toUpperCase() === "/IM" || a.toUpperCase() === "-IM") {
1855
- const nameArg = args[i + 1];
1856
- if (nameArg) {
1857
- const result = await checkKillTarget({ name: nameArg, signal, cmd: fullCommand });
1858
- if (result.blocked) return result;
1859
- }
1860
- }
1861
- }
1862
- for (let i = 0; i < args.length; i++) {
1863
- const a = args[i];
1864
- if (a.toUpperCase() === "/PID" || a.toUpperCase() === "-PID") {
1865
- const pidArg = args[i + 1];
1866
- if (pidArg && /^\d+$/.test(pidArg)) {
1867
- const result = await checkKillTarget({
1868
- pid: parseInt(pidArg, 10),
1869
- signal,
1870
- cmd: fullCommand
1871
- });
1872
- if (result.blocked) return result;
1873
- }
1874
- }
1875
- }
1876
- for (let i = 0; i < args.length; i++) {
1877
- const a = args[i];
1878
- if (a.toUpperCase() === "/FI" || a.toUpperCase() === "-FI") {
1879
- const filterArg = args[i + 1];
1880
- if (filterArg) {
1881
- const nameMatch = filterArg.match(/IMAGENAME\s+eq\s+"?([^"\s]+)/i);
1882
- if (nameMatch?.[1]) {
1883
- const result = await checkKillTarget({
1884
- name: nameMatch[1],
1885
- signal,
1886
- cmd: fullCommand
1887
- });
1888
- if (result.blocked) return result;
1889
- }
1890
- }
1891
- }
1892
- }
1893
- return { blocked: false };
1894
- }
1895
- if (cmdLower === "powershell" || cmdLower === "powershell.exe" || cmdLower === "pwsh" || cmdLower === "pwsh.exe" || cmdLower === "cmd" || cmdLower === "cmd.exe") {
1896
- const shellFlagIndex = args.findIndex((arg) => {
1897
- const lower = arg.toLowerCase();
1898
- return lower === "-c" || lower === "-command" || lower === "/c";
1899
- });
1900
- if (shellFlagIndex >= 0) {
1901
- const innerTokens = tokenizeShellCommand(args.slice(shellFlagIndex + 1).join(" "));
1902
- const innerCommand = innerTokens[0];
1903
- if (innerCommand) {
1904
- const result = await checkExecKillCommand(innerCommand, innerTokens.slice(1));
1905
- if (result.blocked) return result;
1906
- }
1907
- }
1908
- }
1909
- if (cmdLower === "stop-process" || cmdLower === "kill") {
1910
- for (let i = 0; i < args.length; i++) {
1911
- const a = args[i];
1912
- if (a === "-Name" || a === "-n") {
1913
- const nameArg = args[i + 1]?.replace(/^['"]|['"]$/g, "");
1914
- if (nameArg) {
1915
- const result = await checkKillTarget({
1916
- name: nameArg,
1917
- signal: "FORCE",
1918
- cmd: fullCommand
1919
- });
1920
- if (result.blocked) return result;
1921
- }
1922
- }
1923
- if (a === "-Id" || a === "-PID" || a === "-pid") {
1924
- const pidArg = args[i + 1];
1925
- if (pidArg && /^\d+$/.test(pidArg)) {
1926
- const result = await checkKillTarget({
1927
- pid: parseInt(pidArg, 10),
1928
- signal: "FORCE",
1929
- cmd: fullCommand
1930
- });
1931
- if (result.blocked) return result;
1932
- }
1933
- }
1934
- }
1935
- const firstNonFlag = args.find((a) => !a.startsWith("-"));
1936
- if (firstNonFlag) {
1937
- const name = firstNonFlag.replace(/^['"]|['"]$/g, "");
1938
- const result = await checkKillTarget({ name, signal: "TERM", cmd: fullCommand });
1939
- if (result.blocked) return result;
1940
- }
1941
- }
1942
- if (cmdLower === "wmic" || cmdLower === "wmic.exe") {
1943
- const joined = args.join(" ").toLowerCase();
1944
- if (/\bprocess\b/.test(joined) && /\bdelete\b/.test(joined)) {
1945
- const nameMatch = joined.match(/name\s*=\s*['"]?([^'"]+)/);
1946
- if (nameMatch?.[1]) {
1947
- const result = await checkKillTarget({
1948
- name: nameMatch[1].trim(),
1949
- signal: "FORCE",
1950
- cmd: fullCommand
1951
- });
1952
- if (result.blocked) return result;
1953
- }
1954
- return {
1955
- blocked: true,
1956
- reason: "Blocked: wmic process delete targets all matched processes \u2014 would include protected WrongStack processes."
1957
- };
1958
- }
1959
- }
1960
- if (cmdLower === "node" || cmdLower === "node.exe") {
1961
- if (args.includes("-e") || args.includes("--eval")) {
1962
- const evalIdx = args.indexOf("-e") !== -1 ? args.indexOf("-e") : args.indexOf("--eval");
1963
- const evalCode = args[evalIdx + 1] ?? "";
1964
- if (/\bprocess\.kill\s*\(/.test(evalCode)) {
1965
- const pidMatch = evalCode.match(/process\.kill\s*\(\s*(\d+)/);
1966
- if (pidMatch?.[1]) {
1967
- const pid = parseInt(pidMatch[1], 10);
1968
- const result = await checkKillTarget({ pid, signal: "SIGTERM", cmd: fullCommand });
1969
- if (result.blocked) return result;
1970
- }
1971
- return {
1972
- blocked: true,
1973
- reason: "Blocked: node -e with process.kill() \u2014 would target protected WrongStack process(es)."
1974
- };
1975
- }
1976
- }
1977
- }
1978
- } else {
1979
- if (cmdLower === "kill") {
1980
- for (const a of args) {
1981
- const num = a.replace(/^-/, "");
1982
- if (/^\d+$/.test(num)) {
1983
- const pid = parseInt(num, 10);
1984
- const result = await checkKillTarget({ pid, signal: "SIGTERM", cmd: fullCommand });
1985
- if (result.blocked) return result;
1986
- }
1987
- }
1988
- }
1989
- if (cmdLower === "pkill" || cmdLower === "killall") {
1990
- const firstNonFlag = args.find((a) => !a.startsWith("-"));
1991
- if (firstNonFlag) {
1992
- const result = await checkKillTarget({
1993
- name: firstNonFlag,
1994
- signal: "SIGTERM",
1995
- cmd: fullCommand
1996
- });
1997
- if (result.blocked) return result;
1998
- }
1999
- }
2000
- }
2001
- return { blocked: false };
2002
- }
2003
- function tokenizeShellCommand(command) {
2004
- const tokens = [];
2005
- let current = "";
2006
- let quote = null;
2007
- for (const char of command.trim()) {
2008
- if (quote) {
2009
- if (char === quote) quote = null;
2010
- else current += char;
2011
- continue;
2012
- }
2013
- if (char === '"' || char === "'") {
2014
- quote = char;
2015
- } else if (/\s/.test(char)) {
2016
- if (current) {
2017
- tokens.push(current);
2018
- current = "";
2019
- }
2020
- } else {
2021
- current += char;
2022
- }
2023
- }
2024
- if (current) tokens.push(current);
2025
- return tokens;
2026
- }
2027
- async function checkKillTarget(target) {
2028
- const registry = getPersistentProcessRegistry();
2029
- if (target.pid !== void 0) {
2030
- const blocked = await registry.shouldBlockKill(target.pid);
2031
- if (blocked) {
2032
- return {
2033
- blocked: true,
2034
- reason: `Blocked: kill ${target.signal} PID ${target.pid} targets a protected WrongStack process (${target.cmd.slice(0, 80)}).`
2035
- };
2036
- }
2037
- if (target.pid === process.pid) {
2038
- return {
2039
- blocked: true,
2040
- reason: "Blocked: cannot kill the current WrongStack process."
2041
- };
2042
- }
2043
- if (target.pid === process.ppid) {
2044
- return {
2045
- blocked: true,
2046
- reason: "Blocked: cannot kill the parent terminal hosting WrongStack."
2047
- };
2048
- }
2049
- return { blocked: false };
2050
- }
2051
- if (target.name) {
2052
- const nameLower = target.name.toLowerCase().replace(/\.exe$/, "");
2053
- if (nameLower.includes("wrongstack")) {
2054
- return {
2055
- blocked: true,
2056
- reason: `Blocked: kill ${target.signal} '${target.name}' targets a WrongStack process name.`
2057
- };
2058
- }
2059
- const currentImage = path5.basename(process.execPath).toLowerCase().replace(/\.exe$/, "");
2060
- const targetsNodeRuntime = nameLower === "node" || nameLower.startsWith("node");
2061
- if (targetsNodeRuntime && currentImage === "node") {
2062
- return {
2063
- blocked: true,
2064
- reason: `Blocked: kill ${target.signal} '${target.name}' would kill the active WrongStack node.exe runtime.`
2065
- };
2066
- }
2067
- const protectedPids = await registry.getAllProtectedPids();
2068
- if (protectedPids.length > 0 && targetsNodeRuntime) {
2069
- return {
2070
- blocked: true,
2071
- reason: `Blocked: kill ${target.signal} '${target.name}' would kill all node.exe processes including active WrongStack instance(s).`
2072
- };
2073
- }
2074
- return { blocked: false };
2075
- }
2076
- return { blocked: false };
2077
- }
2078
-
2079
- // src/exec-allowlist.ts
2080
- var DEFAULT_ALLOWED_COMMANDS = /* @__PURE__ */ new Set([
2081
- // JS / TS toolchain
2082
- "node",
2083
- "npm",
2084
- "pnpm",
2085
- "yarn",
2086
- "npx",
2087
- "bun",
2088
- "deno",
2089
- "corepack",
2090
- "tsc",
2091
- "tsx",
2092
- "ts-node",
2093
- "vite",
2094
- "vitest",
2095
- "jest",
2096
- "biome",
2097
- "eslint",
2098
- "prettier",
2099
- "turbo",
2100
- "nx",
2101
- "webpack",
2102
- "rollup",
2103
- "parcel",
2104
- "next",
2105
- "astro",
2106
- "playwright",
2107
- "cypress",
2108
- // version control
2109
- "git",
2110
- // Rust
2111
- "cargo",
2112
- "rustc",
2113
- // Go
2114
- "go",
2115
- // Python
2116
- "python",
2117
- "python3",
2118
- "pip",
2119
- "pip3",
2120
- "pytest",
2121
- "ruff",
2122
- "mypy",
2123
- "uv",
2124
- "uvx",
2125
- "poetry",
2126
- "hatch",
2127
- "tox",
2128
- // Ruby
2129
- "ruby",
2130
- "gem",
2131
- "bundle",
2132
- // PHP
2133
- "php",
2134
- "composer",
2135
- "phpunit",
2136
- // JVM
2137
- "java",
2138
- "javac",
2139
- "mvn",
2140
- "gradle",
2141
- "gradlew",
2142
- // .NET
2143
- "dotnet",
2144
- // C / C++ / native build
2145
- "make",
2146
- "cmake",
2147
- "ninja",
2148
- "clang",
2149
- "clang-cl",
2150
- "gcc",
2151
- "g++",
2152
- "link",
2153
- "msbuild",
2154
- // containers / orchestration
2155
- "docker",
2156
- "podman",
2157
- "kubectl",
2158
- // network fetch tools. Per-arg safety is NOT enforced by BLOCKED_ARG_PATTERNS
2159
- // (no curl/wget entries) — the real boundary is the per-call `confirm`
2160
- // permission gate (exec.ts permission:'confirm', subjectKey:'command'),
2161
- // the `pipe-to-shell` danger rule, and the kill guard. The allowlist is a
2162
- // guidance layer, not a security boundary on its own.
2163
- "curl",
2164
- "wget",
2165
- // common POSIX file/text utilities
2166
- "pwd",
2167
- "ls",
2168
- "cat",
2169
- "head",
2170
- "tail",
2171
- "wc",
2172
- "grep",
2173
- "rg",
2174
- "find",
2175
- "echo",
2176
- "sort",
2177
- "uniq",
2178
- "sed",
2179
- "awk",
2180
- "mkdir",
2181
- "cp",
2182
- "mv",
2183
- "rm",
2184
- "touch",
2185
- "tar",
2186
- // Windows-native tooling (win32). All non-destructive binaries; per-arg
2187
- // safety is still enforced by BLOCKED_ARG_PATTERNS + the destructive-ops
2188
- // gate in bash-kill-guard.ts. `gh` is included even though it lives at
2189
- // "C:\Program Files\GitHub CLI\gh.exe" — resolveWin32Command handles the
2190
- // space in the path.
2191
- "gh",
2192
- "where",
2193
- "tasklist",
2194
- "systeminfo",
2195
- "wmic",
2196
- "sc",
2197
- "netstat",
2198
- "ipconfig",
2199
- "nslookup",
2200
- "tracert",
2201
- "pathping",
2202
- // Windows shell interpreters. Without these, `exec` cannot run cmd builtins
2203
- // (`dir`, `type`, `copy`, …) or any PowerShell cmdlet on Windows — a major
2204
- // gap since those are the platform's primary shells. Arbitrary execution
2205
- // through `cmd /c …` / `powershell -c …` is NOT a new hole: the permission
2206
- // policy reconstructs the full command line (shellCommandLineFromInput) and
2207
- // still runs it through the YOLO destructive classifier, so a genuinely
2208
- // destructive `cmd /c del /s /q C:\…` continues to require confirmation.
2209
- "cmd",
2210
- "cmd.exe",
2211
- "powershell",
2212
- "powershell.exe",
2213
- "pwsh",
2214
- "pwsh.exe",
2215
- // [core] Extended default allowlist (added 4b3d18d1 + this commit). Broadly
2216
- // used dev binaries — NOT all non-destructive: this section contains
2217
- // process/system tools (kill, chown, mount, userdel), network scanners
2218
- // (nmap, masscan, zmap, nuclei), and launchers (env, perl, timeout, tmux).
2219
- // The real safety boundary for these is the per-call `confirm` permission
2220
- // gate (exec.ts permission:'confirm', subjectKey:'command' renders the full
2221
- // invocation) plus the danger rules in _danger-detect.ts. Per-arg hard-deny
2222
- // is still enforced by BLOCKED_ARG_PATTERNS + bash-kill-guard.ts, but only
2223
- // for the commands that have entries there (git, find, rm).
2224
- // --- Archives & compression ---
2225
- "7z",
2226
- "7za",
2227
- "bzip2",
2228
- "gzip",
2229
- "xz",
2230
- "unzip",
2231
- "zip",
2232
- "gtar",
2233
- "bsdtar",
2234
- "star",
2235
- "pax",
2236
- "cpio",
2237
- // --- Android / mobile dev ---
2238
- "adb",
2239
- "fastboot",
2240
- "sdkmanager",
2241
- // --- DevOps / config mgmt ---
2242
- "ansible",
2243
- "ansible-playbook",
2244
- "ansible-vault",
2245
- "ansible-lint",
2246
- "ansible-galaxy",
2247
- "molecule",
2248
- // --- Cloud CLIs ---
2249
- "aws",
2250
- "aws-vault",
2251
- "awslocal",
2252
- "az",
2253
- "azcopy",
2254
- "gcloud",
2255
- "gsutil",
2256
- "doctl",
2257
- "linode-cli",
2258
- // --- Native / C / C++ / linker tools ---
2259
- "clang++",
2260
- "clang-format",
2261
- "clang-tidy",
2262
- "clangd",
2263
- "lld",
2264
- "lldb",
2265
- "ctest",
2266
- "gmake",
2267
- "meson",
2268
- "conan",
2269
- "vcpkg",
2270
- "cl",
2271
- "rc",
2272
- "mt",
2273
- "dumpbin",
2274
- "dotnet-format",
2275
- // --- Image / media / binary tools ---
2276
- "convert",
2277
- "ffmpeg",
2278
- "ffprobe",
2279
- "magick",
2280
- "gs",
2281
- "exiftool",
2282
- // --- HTTP / fetch ---
2283
- "wget2",
2284
- "aria2c",
2285
- "axel",
2286
- "httpie",
2287
- "hey",
2288
- "ab",
2289
- "wrk",
2290
- "http",
2291
- // --- Diff / patch / merge ---
2292
- "diff",
2293
- "diff3",
2294
- "patch",
2295
- "meld",
2296
- "kdiff3",
2297
- "kompare",
2298
- // --- Encoding / file inspection ---
2299
- "dos2unix",
2300
- "unix2dos",
2301
- "iconv",
2302
- "file",
2303
- "stat",
2304
- "xxd",
2305
- "hexdump",
2306
- "od",
2307
- "base64",
2308
- // --- SSH / crypto / signing ---
2309
- "ssh",
2310
- "ssh-add",
2311
- "ssh-keygen",
2312
- "ssh-keyscan",
2313
- "scp",
2314
- "sftp",
2315
- "rsync",
2316
- "gpg",
2317
- "gpg2",
2318
- "gpg-agent",
2319
- "openssl",
2320
- "step",
2321
- "keytool",
2322
- // --- Search ---
2323
- "egrep",
2324
- "fgrep",
2325
- "ag",
2326
- "ack",
2327
- "sift",
2328
- "ugrep",
2329
- "fd",
2330
- "fdfind",
2331
- "jq",
2332
- "yq",
2333
- "xq",
2334
- "fx",
2335
- "gron",
2336
- // --- K8s / container ecosystem ---
2337
- "kubectl.exe",
2338
- "kubeadm",
2339
- "kubelet",
2340
- "helm",
2341
- "k9s",
2342
- "kustomize",
2343
- "skaffold",
2344
- "tilt",
2345
- "minikube",
2346
- "kind",
2347
- "k3d",
2348
- "k3s",
2349
- "docker-compose",
2350
- "buildah",
2351
- "skopeo",
2352
- "nerdctl",
2353
- "ctr",
2354
- "ctr.exe",
2355
- // --- Databases ---
2356
- "sqlite3",
2357
- "sqlite",
2358
- "psql",
2359
- "pg_dump",
2360
- "pg_restore",
2361
- "mysql",
2362
- "mysqladmin",
2363
- "mysqldump",
2364
- "mariadb",
2365
- "mariadb-dump",
2366
- "redis-cli",
2367
- "redis-server",
2368
- "memcached",
2369
- "etcdctl",
2370
- "consul",
2371
- "vault",
2372
- "nomad",
2373
- "mongosh",
2374
- "mongo",
2375
- "mongoexport",
2376
- "mongoimport",
2377
- "mongodump",
2378
- "mongorestore",
2379
- // --- Windows extended (read-mostly ops) ---
2380
- "taskkill",
2381
- "gpupdate",
2382
- "gpresult",
2383
- "hostname",
2384
- "whoami",
2385
- "who",
2386
- "net",
2387
- "net1",
2388
- // --- VCS ecosystem ---
2389
- "glab",
2390
- "hub",
2391
- "tea",
2392
- "git-lfs",
2393
- "tig",
2394
- "lazygit",
2395
- // --- POSIX text utilities (extended) ---
2396
- "gawk",
2397
- "tr",
2398
- "cut",
2399
- "paste",
2400
- "join",
2401
- "comm",
2402
- "expand",
2403
- "unexpand",
2404
- "fold",
2405
- "fmt",
2406
- "nl",
2407
- "pr",
2408
- "column",
2409
- "tsort",
2410
- "tty",
2411
- "ul",
2412
- "units",
2413
- "factor",
2414
- "seq",
2415
- "shuf",
2416
- "look",
2417
- "yes",
2418
- "true",
2419
- "false",
2420
- "test",
2421
- "[",
2422
- "printf",
2423
- "env",
2424
- "tree",
2425
- "locate",
2426
- "which",
2427
- "whereis",
2428
- // NOTE: shell builtins with no standalone binary (type, hash, pushd,
2429
- // popd, dirs, history, fc, jobs, bg, fg, wait, ulimit, umask, trap,
2430
- // exit, return, source, ., alias, unalias, set, unset, export, readonly,
2431
- // typeset, declare, local, eval, exec) are intentionally excluded —
2432
- // spawn() would fail with ENOENT on every platform because they only
2433
- // exist inside a shell process. Use the `bash` tool for builtins.
2434
- "nice",
2435
- "nohup",
2436
- "timeout",
2437
- "time",
2438
- // --- Process / system inspection ---
2439
- "htop",
2440
- "top",
2441
- "atop",
2442
- "glances",
2443
- "iotop",
2444
- "nethogs",
2445
- "iftop",
2446
- "lsof",
2447
- "strace",
2448
- "ltrace",
2449
- "sysstat",
2450
- "vmstat",
2451
- "iostat",
2452
- "mpstat",
2453
- "sar",
2454
- "free",
2455
- "df",
2456
- "du",
2457
- "mount",
2458
- "umount",
2459
- "lsblk",
2460
- "blkid",
2461
- "kill",
2462
- "killall",
2463
- "pkill",
2464
- "pgrep",
2465
- "pidof",
2466
- "ps",
2467
- "ps.exe",
2468
- // --- Network inspection ---
2469
- "ip",
2470
- "ss",
2471
- "route",
2472
- "arp",
2473
- "arping",
2474
- "ping",
2475
- "ping6",
2476
- "hping3",
2477
- "mtr",
2478
- "tracepath",
2479
- "tcpdump",
2480
- "nmap",
2481
- "netcat",
2482
- "nc",
2483
- "ncat",
2484
- "socat",
2485
- // --- Sync / backup ---
2486
- "rclone",
2487
- "restic",
2488
- "borg",
2489
- "duplicati",
2490
- "duplicacy",
2491
- "syncthing",
2492
- "syncthing-cli",
2493
- // --- Permissions / users / ACLs (POSIX) ---
2494
- "useradd",
2495
- "userdel",
2496
- "usermod",
2497
- "groupadd",
2498
- "groupdel",
2499
- "groupmod",
2500
- "chown",
2501
- "chmod",
2502
- "chgrp",
2503
- "getfacl",
2504
- "setfacl",
2505
- "setcap",
2506
- "getcap",
2507
- // --- Crypto / cert mgmt (extended) ---
2508
- "certbot",
2509
- "mkcert",
2510
- "jarsigner",
2511
- // --- Editors ---
2512
- "subl",
2513
- "code",
2514
- "code-insiders",
2515
- "cursor",
2516
- "atom",
2517
- "nano",
2518
- "vim",
2519
- "nvim",
2520
- "vi",
2521
- "emacs",
2522
- "helix",
2523
- "hx",
2524
- "micro",
2525
- "jed",
2526
- "ed",
2527
- "ex",
2528
- "mg",
2529
- // --- Terminal multiplexers ---
2530
- "asciinema",
2531
- "script",
2532
- "scriptreplay",
2533
- "expect",
2534
- "screen",
2535
- "tmux",
2536
- "byobu",
2537
- "dtach",
2538
- "abduco",
2539
- // --- Calculators / REPLs / scientific ---
2540
- "bc",
2541
- "dc",
2542
- "calc",
2543
- "qalc",
2544
- "genius",
2545
- "octave",
2546
- "R",
2547
- "Rscript",
2548
- "julia",
2549
- "irb",
2550
- "pry",
2551
- "ghci",
2552
- "stack",
2553
- "cabal",
2554
- "ghc",
2555
- // --- PHP / Lua / Perl / Ruby ecosystem (extended) ---
2556
- "php8",
2557
- "php7",
2558
- "phpcs",
2559
- "phpcbf",
2560
- "phpmd",
2561
- "phpstan",
2562
- "psalm",
2563
- "lua",
2564
- "lua5.1",
2565
- "lua5.2",
2566
- "lua5.3",
2567
- "lua5.4",
2568
- "luarocks",
2569
- "perl",
2570
- "cpan",
2571
- "prove",
2572
- "plackup",
2573
- "rake",
2574
- "rspec",
2575
- "jekyll",
2576
- "node-gyp",
2577
- "node-pre-gyp",
2578
- // --- JS / TS toolchain (extended) ---
2579
- "electron",
2580
- "electron-builder",
2581
- "electron-forge",
2582
- "vite-preview",
2583
- "swc",
2584
- "swc-cli",
2585
- "swcpack",
2586
- "mocha",
2587
- "chai",
2588
- "jasmine",
2589
- "puppeteer",
2590
- "lighthouse",
2591
- // --- Linters / formatters (extended) ---
2592
- "tslint",
2593
- "stylelint",
2594
- "htmlhint",
2595
- "jshint",
2596
- "jslint",
2597
- "jscs",
2598
- // --- Document conversion ---
2599
- "pandoc",
2600
- "weasyprint",
2601
- "wkhtmltopdf",
2602
- "wkhtmltoimage",
2603
- "prince",
2604
- "mdp",
2605
- "markdown",
2606
- "multimarkdown",
2607
- "cmark",
2608
- "cmark-gfm",
2609
- // --- Office / spreadsheet ---
2610
- "soffice",
2611
- "libreoffice",
2612
- "unoconv",
2613
- "abiword",
2614
- "gnumeric",
2615
- // --- Spell / grammar ---
2616
- "aspell",
2617
- "hunspell",
2618
- "enchant",
2619
- "languagetool",
2620
- // --- Source-highlight / diff tools ---
2621
- "delta",
2622
- "bat",
2623
- "ccat",
2624
- "hl",
2625
- "highlight",
2626
- "source-highlight",
2627
- "ansifilter",
2628
- // --- Job schedulers ---
2629
- "pueue",
2630
- "task-spooler",
2631
- "ts",
2632
- "at",
2633
- "atd",
2634
- "anacron",
2635
- "fcron",
2636
- "cronie",
2637
- "systemd-run",
2638
- "systemd-cat",
2639
- // --- Plotting / visualization ---
2640
- "gnuplot",
2641
- "gnuplot-nox",
2642
- "veusz",
2643
- "scidavis",
2644
- "grace",
2645
- "xmgrace",
2646
- "labplot",
2647
- // --- Security / recon (network + web) ---
2648
- "masscan",
2649
- "zmap",
2650
- "rustscan",
2651
- "amass",
2652
- "subfinder",
2653
- "httpx",
2654
- "nuclei",
2655
- "naabu",
2656
- "katana",
2657
- "dnsx",
2658
- "assetfinder",
2659
- "findomain",
2660
- "gau",
2661
- "waybackurls",
2662
- "httprobe",
2663
- "meg",
2664
- "subjack",
2665
- "sublert",
2666
- "chaos"
2667
- ]);
2668
-
2669
- // src/exec.ts
2670
- var isWin2 = process.platform === "win32";
2671
- var allowedCommands = new Set(DEFAULT_ALLOWED_COMMANDS);
2672
- var normalizeCmd = (c) => c.trim();
2673
- function configureExecPolicy(opts = {}) {
2674
- const next = new Set(DEFAULT_ALLOWED_COMMANDS);
2675
- for (const c of opts.allow ?? []) {
2676
- const n = normalizeCmd(c);
2677
- if (n) next.add(n);
2678
- }
2679
- for (const c of opts.deny ?? []) next.delete(normalizeCmd(c));
2680
- allowedCommands = next;
2681
- }
2682
- function resetExecPolicy() {
2683
- allowedCommands = new Set(DEFAULT_ALLOWED_COMMANDS);
2684
- }
2685
- var dangerBypass = /* @__PURE__ */ new Set();
2686
- function configureDangerBypass(opts = {}) {
2687
- const next = /* @__PURE__ */ new Set();
2688
- for (const id of opts.bypass ?? []) {
2689
- const trimmed = id.trim();
2690
- if (trimmed) next.add(trimmed);
2691
- }
2692
- dangerBypass = next;
2693
- }
2694
- function resetDangerBypass() {
2695
- dangerBypass = /* @__PURE__ */ new Set();
2696
- }
2697
- function getDangerBypass() {
2698
- return dangerBypass;
2699
- }
2700
- function isExecCommandAllowed(cmd) {
2701
- return allowedCommands.has(normalizeCmd(cmd));
2702
- }
2703
- function getExecAllowlist() {
2704
- return [...allowedCommands].sort();
2705
- }
2706
- var MAX_ARGS = 20;
2707
- var MAX_OUTPUT = 2e5;
2708
- var DEFAULT_TIMEOUT_MS = 3e4;
2709
- var MAX_TIMEOUT_MS = 6e5;
2710
- var BLOCKED_ARG_PATTERNS = {
2711
- python: [],
2712
- // git --exec=<cmd> runs arbitrary commands via upload-pack/receive-pack;
2713
- // -C <dir> changes working directory, bypassing cwd sandbox;
2714
- // -c/--config <k>=<v> injects config that runs commands
2715
- // (e.g. core.sshCommand, core.pager, http.proxy, alias.x=!cmd).
2716
- git: [
2717
- /^--exec=/,
2718
- /^--upload-pack=/,
2719
- /^--receive-pack=/,
2720
- /^-C$/,
2721
- /^-c$/,
2722
- /^--config$/,
2723
- /^-c=/,
2724
- /^--config=/,
2725
- /^--config-env=/
2726
- ],
2727
- node: [],
2728
- go: [],
2729
- bun: [],
2730
- docker: [],
2731
- // find -exec/-ok/-execdir execute arbitrary commands
2732
- find: [
2733
- /^-exec$/,
2734
- /^-exec;$/,
2735
- /^-ok$/,
2736
- /^-ok;$/,
2737
- /^-execdir$/,
2738
- /^-execdir;$/,
2739
- /^-exec=/,
2740
- /^-ok=/,
2741
- /^-execdir=/
2742
- ],
2743
- // rm -rf / is catastrophic — block absolute paths, home, dot-dirs,
2744
- // and glob patterns that could expand to dangerous targets.
2745
- // `rm -rf ./src/*` expands to project files; `rm -rf ../../` escapes upward;
2746
- // `rm -rf /*` targets the filesystem root. All are blocked.
2747
- rm: [/^\//, /^[A-Za-z]:[\\/]/, /^~\//, /^~$/, /^\.$/, /^\.\.$/, /\*$/, /\/$/, /\/\*$/, /\.\//],
2748
- // npm/pnpm subcommands are checked separately below. Matching every arg here
2749
- // over-blocked normal dev flows such as `pnpm vitest run ...`.
2750
- npm: [],
2751
- pnpm: [],
2752
- npx: []
2753
- };
2754
- var BLOCKED_OPTION_NAMES = {
2755
- git: /* @__PURE__ */ new Set([
2756
- "--exec",
2757
- "--upload-pack",
2758
- "--receive-pack",
2759
- "--exec-path",
2760
- "--git-dir",
2761
- "--work-tree",
2762
- "--namespace",
2763
- "-c",
2764
- "--config",
2765
- "--config-env",
2766
- "-C"
2767
- ]),
2768
- find: /* @__PURE__ */ new Set(["-exec", "-ok", "-execdir"])
2769
- };
2770
- function optionName(arg) {
2771
- const eq = arg.indexOf("=");
2772
- return eq > 0 ? arg.slice(0, eq) : arg;
2773
- }
2774
- var BLOCKED_SUBCOMMANDS = {
2775
- docker: /* @__PURE__ */ new Set(["push"]),
2776
- podman: /* @__PURE__ */ new Set(["push"]),
2777
- npm: /* @__PURE__ */ new Set(["publish", "deploy"]),
2778
- pnpm: /* @__PURE__ */ new Set(["publish", "deploy"]),
2779
- yarn: /* @__PURE__ */ new Set(["publish"])
2780
- };
2781
- var BLOCKED_SUBCOMMAND_SEQUENCES = {
2782
- yarn: [["npm", "publish"]]
2783
- };
2784
- function firstSubcommand(args) {
2785
- for (const arg of args) {
2786
- if (arg === "--") return null;
2787
- if (!arg.startsWith("-")) return arg;
2788
- }
2789
- return null;
2790
- }
2791
- function subcommandArgs(args) {
2792
- const out = [];
2793
- for (const arg of args) {
2794
- if (arg === "--") break;
2795
- if (!arg.startsWith("-")) out.push(arg);
2796
- }
2797
- return out;
2798
- }
2799
- function validateArgs(cmd, args) {
2800
- const blockedSubcommands = BLOCKED_SUBCOMMANDS[cmd];
2801
- const subcommand = firstSubcommand(args);
2802
- if (blockedSubcommands && subcommand && blockedSubcommands.has(subcommand)) {
2803
- return `Blocked subcommand "${subcommand}" for command "${cmd}"`;
2804
- }
2805
- const blockedSequences = BLOCKED_SUBCOMMAND_SEQUENCES[cmd];
2806
- if (blockedSequences) {
2807
- const actual = subcommandArgs(args);
2808
- const blocked2 = blockedSequences.find((seq) => seq.every((part, idx) => actual[idx] === part));
2809
- if (blocked2) return `Blocked subcommand "${blocked2.join(" ")}" for command "${cmd}"`;
2810
- }
2811
- const blockedOptions = BLOCKED_OPTION_NAMES[cmd];
2812
- if (blockedOptions) {
2813
- for (const arg of args) {
2814
- if (arg === "--") break;
2815
- if (blockedOptions.has(optionName(arg))) {
2816
- return `Blocked option "${optionName(arg)}" for command "${cmd}"`;
2817
- }
2818
- }
2819
- }
2820
- const blocked = BLOCKED_ARG_PATTERNS[cmd];
2821
- if (!blocked) return null;
2822
- for (const arg of args) {
2823
- for (const pattern of blocked) {
2824
- if (pattern.test(arg)) {
2825
- return `Blocked argument "${arg}" for command "${cmd}" (matches security pattern ${pattern})`;
2826
- }
2827
- }
2828
- }
2829
- return null;
2830
- }
2831
- var SAFE_DANGER = { level: "safe", reasons: [] };
2832
- var execTool = {
2833
- name: "exec",
2834
- category: "Shell",
2835
- description: "Execute a command from a **curated command roster** with argument validation and confirm gating. This is the **preferred** alternative to the `bash` tool for running development tools (node, npm, pnpm, tsc, git, tests, linters, etc.). It is NOT a sandbox \u2014 several rostered commands (node, python, powershell, \u2026) can run arbitrary code \u2014 so prefer least-privilege commands.",
2836
- usageHint: "PREFERRED SHELL TOOL for most cases.\n\nUse this instead of `bash` whenever possible.\n- `command` must be in the allowlist. Defaults cover JS (node/npm/pnpm/yarn/bun/deno/tsc/vitest/eslint/biome), Go (`go build`/`go test`), Rust (cargo), Python (python/pip), Ruby (gem/bundle), JVM (java/mvn/gradle), .NET (dotnet), native (make/cmake), and git. Users can extend it via `tools.exec.allow` in config.\n- Arguments are passed as a clean array (no shell interpretation).\n- `cwd` is validated to stay inside the project.\n- If a command is not allowlisted, the error explains how to add it; for one-off arbitrary commands, fall back to `bash` (with strong justification).\nThe curated roster + confirm gating narrows the surface compared to full shell access, but this is not a sandbox \u2014 prefer least-privilege commands.",
2837
- selection: {
2838
- doNotUseWhen: "the operation requires pipes, redirection, shell expansion, or a non-allowlisted command.",
2839
- useInstead: ["bash"]
2840
- },
2841
- permission: "confirm",
2842
- // WS-046: without this, every exec call collapsed onto the bare tool name.
2843
- // Three consequences followed: "always allow" stored a rule that could never
2844
- // match, pressing "no" once blocked ALL exec for the session, and the
2845
- // permission cache keyed one decision for every command. `subjectKey:
2846
- // 'command'` renders the FULL invocation (`command` + `args`) — using the
2847
- // program alone would make `exec git status` and `exec git push --force` the
2848
- // same subject, so trusting one would silently authorize the other.
2849
- subjectKey: "command",
2850
- mutating: true,
2851
- riskTier: "standard",
2852
- // Executor-level abort ceiling. Must sit ABOVE the per-call timeout ceiling
2853
- // (MAX_TIMEOUT_MS): the tool's own timer resolves with exit 124 + registry
2854
- // tree-kill; the executor's AbortSignal.timeout is a blunt abort that would
2855
- // otherwise fire first and discard the structured timeout result. The 10s
2856
- // margin covers the kill/teardown window. (The executor additionally clamps
2857
- // to config `tools.maxToolTimeoutMs`.)
2858
- timeoutMs: MAX_TIMEOUT_MS + 1e4,
2859
- capabilities: ["shell.restricted"],
2860
- icon: "terminal",
2861
- inputSchema: {
2862
- type: "object",
2863
- properties: {
2864
- command: {
2865
- type: "string",
2866
- description: 'The base command to run. Must be in the internal allowlist (e.g. "node", "pnpm", "git", "tsc").'
2867
- },
2868
- args: {
2869
- type: "array",
2870
- items: { type: "string" },
2871
- description: "Arguments passed to the command. Passed as an array (no shell parsing)."
2872
- },
2873
- cwd: {
2874
- type: "string",
2875
- description: "Optional working directory. Must resolve inside the project root."
2876
- },
2877
- timeout: {
2878
- type: "integer",
2879
- description: "Per-command timeout in milliseconds (default 30000, max 600000)."
2880
- }
2881
- },
2882
- required: ["command"]
2883
- },
2884
- async execute(input, ctx, opts) {
2885
- const registry = getProcessRegistry();
2886
- if (!registry.canProceed) {
2887
- return {
2888
- command: input.command,
2889
- args: input.args ?? [],
2890
- stdout: "",
2891
- stderr: "Circuit breaker is open \u2014 too many consecutive failures. Use /kill reset to recover.",
2892
- exitCode: 1,
2893
- truncated: false,
2894
- allowed: false,
2895
- danger: SAFE_DANGER
2896
- };
2897
- }
2898
- const cmd = input.command.trim();
2899
- if (!cmd)
2900
- return {
2901
- command: cmd,
2902
- args: [],
2903
- stdout: "",
2904
- stderr: "Empty command",
2905
- exitCode: 1,
2906
- truncated: false,
2907
- allowed: false,
2908
- danger: SAFE_DANGER
2909
- };
2910
- if (!isExecCommandAllowed(cmd)) {
2911
- return {
2912
- command: cmd,
2913
- args: input.args ?? [],
2914
- stdout: "",
2915
- stderr: `Command "${cmd}" not in allowlist. Add it to your active profile config (~/.wrongstack/profiles/<name>/config.json) under "tools": { "exec": { "allow": ["${cmd}"] } }, or use the bash tool for one-off arbitrary commands.`,
2916
- exitCode: 1,
2917
- truncated: false,
2918
- allowed: false,
2919
- danger: SAFE_DANGER
2920
- };
2921
- }
2922
- const args = (input.args ?? []).slice(0, MAX_ARGS);
2923
- const timeout = Math.max(1, Math.min(input.timeout ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS));
2924
- const danger = detectDanger(cmd, args, dangerBypass);
2925
- const killCheck = await checkExecKillCommand(cmd, args);
2926
- if (killCheck.blocked) {
2927
- return {
2928
- command: cmd,
2929
- args,
2930
- stdout: "",
2931
- stderr: killCheck.reason ?? "Kill command blocked: targets a protected WrongStack process.",
2932
- exitCode: 1,
2933
- truncated: false,
2934
- allowed: false,
2935
- danger
2936
- };
2937
- }
2938
- const argError = validateArgs(cmd, args);
2939
- if (argError) {
2940
- return {
2941
- command: cmd,
2942
- args,
2943
- stdout: "",
2944
- stderr: argError,
2945
- exitCode: 1,
2946
- truncated: false,
2947
- allowed: false,
2948
- danger
2949
- };
2950
- }
2951
- const defaultCwd = ctx.workingDir ?? ctx.cwd;
2952
- let cwd;
2953
- try {
2954
- cwd = input.cwd ? await safeResolveReal(input.cwd, ctx) : await safeResolveReal(defaultCwd, ctx);
2955
- } catch {
2956
- return {
2957
- command: cmd,
2958
- args,
2959
- stdout: "",
2960
- stderr: `cwd "${input.cwd ?? defaultCwd}" resolves outside project root`,
2961
- exitCode: 1,
2962
- truncated: false,
2963
- allowed: false,
2964
- danger
2965
- };
2966
- }
2967
- const signal = opts.signal;
2968
- return runCommand(cmd, args, cwd, timeout, signal, ctx.session?.id, danger);
2969
- }
2970
- };
2971
- function runCommand(cmd, args, cwd, timeout, signal, sessionId, danger) {
2972
- return new Promise((resolve2) => {
2973
- let stdout = "";
2974
- let stderr = "";
2975
- let killed = false;
2976
- const resolvedOnce = { value: false };
2977
- const finish = (result) => {
2978
- if (resolvedOnce.value) return;
2979
- resolvedOnce.value = true;
2980
- resolve2(result);
2981
- };
2982
- const startedAt = Date.now();
2983
- let stdoutBytes = 0;
2984
- let stderrBytes = 0;
2985
- let telemetryCompleted = false;
2986
- let timedOut = false;
2987
- const spool = createOutputSpool({ tool: `exec-${cmd}`, thresholdBytes: MAX_OUTPUT });
2988
- const resolved = resolveWin32Command(cmd);
2989
- const needsShell = isWin2 && (resolved.endsWith(".cmd") || resolved.endsWith(".bat"));
2990
- const shim = needsShell ? buildWin32CmdShimInvocation(resolved, args) : null;
2991
- const spawnCmd = shim?.command ?? resolved;
2992
- const spawnArgs = shim?.args ?? args;
2993
- const emitCompletedOnce = (exitCode, pid2, signal2) => {
2994
- if (telemetryCompleted) return;
2995
- telemetryCompleted = true;
2996
- emitProcessCompleted({
2997
- ...pid2 !== void 0 ? { pid: pid2 } : {},
2998
- exitCode,
2999
- ...signal2 ? { signal: signal2 } : {},
3000
- durationMs: Date.now() - startedAt,
3001
- stdoutBytes,
3002
- stderrBytes,
3003
- timedOut,
3004
- endedAt: (/* @__PURE__ */ new Date()).toISOString()
3005
- });
3006
- };
3007
- let child;
3008
- try {
3009
- child = spawn2(spawnCmd, spawnArgs, {
3010
- cwd,
3011
- env: buildChildEnv(sessionId),
3012
- stdio: ["ignore", "pipe", "pipe"],
3013
- windowsHide: true,
3014
- ...isWin2 ? {} : { signal },
3015
- ...shim ? { windowsVerbatimArguments: shim.windowsVerbatimArguments } : {}
3016
- });
3017
- } catch (err) {
3018
- spool.finalize();
3019
- emitProcessStarted({
3020
- parentPid: process.pid,
3021
- command: redactCommand(`${cmd} ${args.join(" ")}`),
3022
- args: redactCommand(args.join(" ")).split(" ").filter(Boolean),
3023
- cwd,
3024
- background: false,
3025
- startedAt: new Date(startedAt).toISOString()
3026
- });
3027
- emitCompletedOnce(1, void 0);
3028
- finish({
3029
- command: cmd,
3030
- args,
3031
- stdout: "",
3032
- stderr: `spawn failed: ${toErrorMessage2(err)}`,
3033
- exitCode: 1,
3034
- truncated: false,
3035
- allowed: true,
3036
- danger
3037
- });
3038
- return;
3039
- }
3040
- emitProcessStarted({
3041
- ...child.pid !== void 0 ? { pid: child.pid } : {},
3042
- parentPid: process.pid,
3043
- command: redactCommand(`${cmd} ${args.join(" ")}`),
3044
- args: redactCommand(args.join(" ")).split(" ").filter(Boolean),
3045
- cwd,
3046
- background: false,
3047
- startedAt: new Date(startedAt).toISOString()
3048
- });
3049
- child.on("error", (err) => {
3050
- const isAbort = err && err.code === "ABORT_ERR";
3051
- const stderrText = isAbort ? `Aborted: ${err.message}` : err.message;
3052
- clearTimeout(timer);
3053
- if (isWin2) signal.removeEventListener("abort", onAbort);
3054
- if (typeof pid === "number") registry.unregister(pid);
3055
- registry.afterCall(Date.now() - startedAt, true);
3056
- spool.finalize();
3057
- emitCompletedOnce(isAbort ? 124 : 1, child.pid, isAbort ? "ABORT" : void 0);
3058
- finish({
3059
- command: cmd,
3060
- args,
3061
- stdout: normalizeCommandOutput(stdout),
3062
- stderr: stderrText,
3063
- exitCode: isAbort ? 124 : 1,
3064
- truncated: Buffer.byteLength(stdout, "utf8") > COMMAND_OUTPUT_MAX_BYTES,
3065
- allowed: true,
3066
- danger
3067
- });
3068
- });
3069
- const registry = getProcessRegistry();
3070
- const pid = child.pid;
3071
- if (typeof pid === "number") {
3072
- const fullCommand = `${cmd} ${args.join(" ")}`;
3073
- registry.register({
3074
- pid,
3075
- name: "exec",
3076
- command: redactCommand(fullCommand),
3077
- startedAt: Date.now(),
3078
- sessionId,
3079
- child
3080
- });
3081
- }
3082
- const timer = setTimeout(() => {
3083
- killed = true;
3084
- timedOut = true;
3085
- if (typeof pid === "number") registry.kill(pid);
3086
- else child.kill("SIGTERM");
3087
- }, timeout);
3088
- const onAbort = () => {
3089
- killed = true;
3090
- if (typeof pid === "number") registry.kill(pid, { force: true });
3091
- else child.kill("SIGTERM");
3092
- };
3093
- if (isWin2) {
3094
- if (signal.aborted) onAbort();
3095
- else signal.addEventListener("abort", onAbort, { once: true });
3096
- }
3097
- child.stdout?.on("data", (chunk) => {
3098
- const text = chunk.toString();
3099
- stdoutBytes += chunk.byteLength;
3100
- emitProcessOutput({ pid, stream: "stdout", chunk });
3101
- if (stdout.length < MAX_OUTPUT) stdout += text;
3102
- spool.write(text);
3103
- });
3104
- child.stderr?.on("data", (chunk) => {
3105
- const text = chunk.toString();
3106
- stderrBytes += chunk.byteLength;
3107
- emitProcessOutput({ pid, stream: "stderr", chunk });
3108
- if (stderr.length < MAX_OUTPUT) stderr += text;
3109
- spool.write(text);
3110
- });
3111
- child.on("close", (code) => {
3112
- clearTimeout(timer);
3113
- if (isWin2) signal.removeEventListener("abort", onAbort);
3114
- if (typeof pid === "number") registry.unregister(pid);
3115
- const durationMs = Date.now() - startedAt;
3116
- const exitCode = killed ? 124 : code ?? 1;
3117
- emitCompletedOnce(exitCode, pid);
3118
- registry.afterCall(durationMs, exitCode !== 0);
3119
- const spooled = spool.finalize();
3120
- finish({
3121
- command: cmd,
3122
- args,
3123
- stdout: normalizeCommandOutput(stdout) + (spooled ? spoolNote(spooled) : ""),
3124
- stderr: normalizeCommandOutput(stderr),
3125
- exitCode,
3126
- truncated: Buffer.byteLength(stdout, "utf8") > COMMAND_OUTPUT_MAX_BYTES || Buffer.byteLength(stderr, "utf8") > COMMAND_OUTPUT_MAX_BYTES,
3127
- allowed: true,
3128
- danger
3129
- });
3130
- });
3131
- });
3132
- }
2
+ configureDangerBypass,
3
+ configureExecPolicy,
4
+ execTool,
5
+ getDangerBypass,
6
+ getExecAllowlist,
7
+ isExecCommandAllowed,
8
+ resetDangerBypass,
9
+ resetExecPolicy
10
+ } from "./chunk-T2F4S7U4.js";
11
+ import "./chunk-BTSFTGIL.js";
12
+ import "./chunk-NKNOBUBU.js";
13
+ import "./chunk-2VSZC6QM.js";
14
+ import "./chunk-3PVYQFRQ.js";
15
+ import "./chunk-HFXSNKCV.js";
16
+ import "./chunk-V43EQ6VR.js";
17
+ import "./chunk-D33S4RQG.js";
3133
18
  export {
3134
19
  configureDangerBypass,
3135
20
  configureExecPolicy,