open-multi-agent-kit 0.90.8 → 0.91.0

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 (350) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +21 -2
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +4 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/commands/doctor-provider-cli.d.ts +33 -0
  7. package/dist/commands/doctor-provider-cli.d.ts.map +1 -0
  8. package/dist/commands/doctor-provider-cli.js +215 -0
  9. package/dist/commands/doctor-provider-cli.js.map +1 -0
  10. package/dist/commands/doctor-provider-transport.d.ts +35 -0
  11. package/dist/commands/doctor-provider-transport.d.ts.map +1 -0
  12. package/dist/commands/doctor-provider-transport.js +185 -0
  13. package/dist/commands/doctor-provider-transport.js.map +1 -0
  14. package/dist/commands/doctor-provider.d.ts +121 -7
  15. package/dist/commands/doctor-provider.d.ts.map +1 -1
  16. package/dist/commands/doctor-provider.js +1295 -102
  17. package/dist/commands/doctor-provider.js.map +1 -1
  18. package/dist/commands/session-doctor-cli.d.ts +43 -0
  19. package/dist/commands/session-doctor-cli.d.ts.map +1 -0
  20. package/dist/commands/session-doctor-cli.js +494 -0
  21. package/dist/commands/session-doctor-cli.js.map +1 -0
  22. package/dist/commands/verify-ci.d.ts +21 -0
  23. package/dist/commands/verify-ci.d.ts.map +1 -0
  24. package/dist/commands/verify-ci.js +66 -0
  25. package/dist/commands/verify-ci.js.map +1 -0
  26. package/dist/core/agent-session-services.d.ts +3 -0
  27. package/dist/core/agent-session-services.d.ts.map +1 -1
  28. package/dist/core/agent-session-services.js +3 -0
  29. package/dist/core/agent-session-services.js.map +1 -1
  30. package/dist/core/agent-session.d.ts +140 -2
  31. package/dist/core/agent-session.d.ts.map +1 -1
  32. package/dist/core/agent-session.js +1179 -95
  33. package/dist/core/agent-session.js.map +1 -1
  34. package/dist/core/agent-tool-settings.d.ts +35 -0
  35. package/dist/core/agent-tool-settings.d.ts.map +1 -0
  36. package/dist/core/agent-tool-settings.js +155 -0
  37. package/dist/core/agent-tool-settings.js.map +1 -0
  38. package/dist/core/atomic-session-file.d.ts +14 -0
  39. package/dist/core/atomic-session-file.d.ts.map +1 -0
  40. package/dist/core/atomic-session-file.js +104 -0
  41. package/dist/core/atomic-session-file.js.map +1 -0
  42. package/dist/core/command-safety.d.ts.map +1 -1
  43. package/dist/core/command-safety.js +0 -8
  44. package/dist/core/command-safety.js.map +1 -1
  45. package/dist/core/compaction/compaction.d.ts +6 -0
  46. package/dist/core/compaction/compaction.d.ts.map +1 -1
  47. package/dist/core/compaction/compaction.js +12 -1
  48. package/dist/core/compaction/compaction.js.map +1 -1
  49. package/dist/core/compaction/hysteresis.d.ts +27 -0
  50. package/dist/core/compaction/hysteresis.d.ts.map +1 -0
  51. package/dist/core/compaction/hysteresis.js +84 -0
  52. package/dist/core/compaction/hysteresis.js.map +1 -0
  53. package/dist/core/compaction/index.d.ts +2 -0
  54. package/dist/core/compaction/index.d.ts.map +1 -1
  55. package/dist/core/compaction/index.js +2 -0
  56. package/dist/core/compaction/index.js.map +1 -1
  57. package/dist/core/compaction/transaction.d.ts +172 -0
  58. package/dist/core/compaction/transaction.d.ts.map +1 -0
  59. package/dist/core/compaction/transaction.js +824 -0
  60. package/dist/core/compaction/transaction.js.map +1 -0
  61. package/dist/core/context-budget-governor-v2.d.ts +2 -1
  62. package/dist/core/context-budget-governor-v2.d.ts.map +1 -1
  63. package/dist/core/context-budget-governor-v2.js +2 -1
  64. package/dist/core/context-budget-governor-v2.js.map +1 -1
  65. package/dist/core/context-budget-reserved-tokens.d.ts +110 -0
  66. package/dist/core/context-budget-reserved-tokens.d.ts.map +1 -0
  67. package/dist/core/context-budget-reserved-tokens.js +188 -0
  68. package/dist/core/context-budget-reserved-tokens.js.map +1 -0
  69. package/dist/core/context-budget-v2-cache-invalidation.d.ts +133 -0
  70. package/dist/core/context-budget-v2-cache-invalidation.d.ts.map +1 -0
  71. package/dist/core/context-budget-v2-cache-invalidation.js +452 -0
  72. package/dist/core/context-budget-v2-cache-invalidation.js.map +1 -0
  73. package/dist/core/context-budget-v2-cache-keys.d.ts +3 -0
  74. package/dist/core/context-budget-v2-cache-keys.d.ts.map +1 -1
  75. package/dist/core/context-budget-v2-cache-keys.js +6 -0
  76. package/dist/core/context-budget-v2-cache-keys.js.map +1 -1
  77. package/dist/core/context-budget-v2-cache-provider.d.ts +4 -0
  78. package/dist/core/context-budget-v2-cache-provider.d.ts.map +1 -1
  79. package/dist/core/context-budget-v2-cache-provider.js +19 -0
  80. package/dist/core/context-budget-v2-cache-provider.js.map +1 -1
  81. package/dist/core/context-budget-v2-plan-cache-keys.d.ts.map +1 -1
  82. package/dist/core/context-budget-v2-plan-cache-keys.js +1 -0
  83. package/dist/core/context-budget-v2-plan-cache-keys.js.map +1 -1
  84. package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
  85. package/dist/core/context-budget-v2-planner.js +1 -0
  86. package/dist/core/context-budget-v2-planner.js.map +1 -1
  87. package/dist/core/context-budget-v2-types.d.ts +4 -0
  88. package/dist/core/context-budget-v2-types.d.ts.map +1 -1
  89. package/dist/core/context-budget-v2-types.js.map +1 -1
  90. package/dist/core/durable-file-directory.d.ts +4 -0
  91. package/dist/core/durable-file-directory.d.ts.map +1 -0
  92. package/dist/core/durable-file-directory.js +76 -0
  93. package/dist/core/durable-file-directory.js.map +1 -0
  94. package/dist/core/durable-file-identity.d.ts +26 -0
  95. package/dist/core/durable-file-identity.d.ts.map +1 -0
  96. package/dist/core/durable-file-identity.js +118 -0
  97. package/dist/core/durable-file-identity.js.map +1 -0
  98. package/dist/core/durable-file-io.d.ts +29 -0
  99. package/dist/core/durable-file-io.d.ts.map +1 -0
  100. package/dist/core/durable-file-io.js +179 -0
  101. package/dist/core/durable-file-io.js.map +1 -0
  102. package/dist/core/durable-file-lock-cleanup.d.ts +12 -0
  103. package/dist/core/durable-file-lock-cleanup.d.ts.map +1 -0
  104. package/dist/core/durable-file-lock-cleanup.js +39 -0
  105. package/dist/core/durable-file-lock-cleanup.js.map +1 -0
  106. package/dist/core/durable-file-lock-owner.d.ts +18 -0
  107. package/dist/core/durable-file-lock-owner.d.ts.map +1 -0
  108. package/dist/core/durable-file-lock-owner.js +78 -0
  109. package/dist/core/durable-file-lock-owner.js.map +1 -0
  110. package/dist/core/durable-file-lock-storage.d.ts +35 -0
  111. package/dist/core/durable-file-lock-storage.d.ts.map +1 -0
  112. package/dist/core/durable-file-lock-storage.js +263 -0
  113. package/dist/core/durable-file-lock-storage.js.map +1 -0
  114. package/dist/core/durable-file-mode.d.ts +8 -0
  115. package/dist/core/durable-file-mode.d.ts.map +1 -0
  116. package/dist/core/durable-file-mode.js +41 -0
  117. package/dist/core/durable-file-mode.js.map +1 -0
  118. package/dist/core/extensions/loader.d.ts +12 -0
  119. package/dist/core/extensions/loader.d.ts.map +1 -1
  120. package/dist/core/extensions/loader.js +46 -37
  121. package/dist/core/extensions/loader.js.map +1 -1
  122. package/dist/core/footer-data-provider.d.ts +7 -1
  123. package/dist/core/footer-data-provider.d.ts.map +1 -1
  124. package/dist/core/footer-data-provider.js +12 -0
  125. package/dist/core/footer-data-provider.js.map +1 -1
  126. package/dist/core/index.d.ts +7 -2
  127. package/dist/core/index.d.ts.map +1 -1
  128. package/dist/core/index.js +6 -0
  129. package/dist/core/index.js.map +1 -1
  130. package/dist/core/metrics-sampler.d.ts +20 -0
  131. package/dist/core/metrics-sampler.d.ts.map +1 -1
  132. package/dist/core/metrics-sampler.js +52 -0
  133. package/dist/core/metrics-sampler.js.map +1 -1
  134. package/dist/core/model-registry.d.ts.map +1 -1
  135. package/dist/core/model-registry.js +4 -1
  136. package/dist/core/model-registry.js.map +1 -1
  137. package/dist/core/model-resolver.d.ts.map +1 -1
  138. package/dist/core/model-resolver.js +16 -7
  139. package/dist/core/model-resolver.js.map +1 -1
  140. package/dist/core/provider-resilience.d.ts +51 -0
  141. package/dist/core/provider-resilience.d.ts.map +1 -0
  142. package/dist/core/provider-resilience.js +86 -0
  143. package/dist/core/provider-resilience.js.map +1 -0
  144. package/dist/core/redaction.d.ts +8 -0
  145. package/dist/core/redaction.d.ts.map +1 -0
  146. package/dist/core/redaction.js +31 -0
  147. package/dist/core/redaction.js.map +1 -0
  148. package/dist/core/resource-loader.d.ts.map +1 -1
  149. package/dist/core/resource-loader.js +36 -0
  150. package/dist/core/resource-loader.js.map +1 -1
  151. package/dist/core/run-journal-store.d.ts +53 -0
  152. package/dist/core/run-journal-store.d.ts.map +1 -0
  153. package/dist/core/run-journal-store.js +278 -0
  154. package/dist/core/run-journal-store.js.map +1 -0
  155. package/dist/core/run-journal.d.ts +172 -0
  156. package/dist/core/run-journal.d.ts.map +1 -0
  157. package/dist/core/run-journal.js +1045 -0
  158. package/dist/core/run-journal.js.map +1 -0
  159. package/dist/core/sdk.d.ts +7 -0
  160. package/dist/core/sdk.d.ts.map +1 -1
  161. package/dist/core/sdk.js +94 -3
  162. package/dist/core/sdk.js.map +1 -1
  163. package/dist/core/session-doctor-plan.d.ts +128 -0
  164. package/dist/core/session-doctor-plan.d.ts.map +1 -0
  165. package/dist/core/session-doctor-plan.js +833 -0
  166. package/dist/core/session-doctor-plan.js.map +1 -0
  167. package/dist/core/session-file-compaction.d.ts +6 -0
  168. package/dist/core/session-file-compaction.d.ts.map +1 -0
  169. package/dist/core/session-file-compaction.js +169 -0
  170. package/dist/core/session-file-compaction.js.map +1 -0
  171. package/dist/core/session-file-head.d.ts +10 -0
  172. package/dist/core/session-file-head.d.ts.map +1 -0
  173. package/dist/core/session-file-head.js +78 -0
  174. package/dist/core/session-file-head.js.map +1 -0
  175. package/dist/core/session-file-persistence.d.ts +30 -0
  176. package/dist/core/session-file-persistence.d.ts.map +1 -0
  177. package/dist/core/session-file-persistence.js +106 -0
  178. package/dist/core/session-file-persistence.js.map +1 -0
  179. package/dist/core/session-integrity.d.ts +43 -0
  180. package/dist/core/session-integrity.d.ts.map +1 -0
  181. package/dist/core/session-integrity.js +420 -0
  182. package/dist/core/session-integrity.js.map +1 -0
  183. package/dist/core/session-manager.d.ts +24 -4
  184. package/dist/core/session-manager.d.ts.map +1 -1
  185. package/dist/core/session-manager.js +242 -125
  186. package/dist/core/session-manager.js.map +1 -1
  187. package/dist/core/session-owner-lease.d.ts +22 -0
  188. package/dist/core/session-owner-lease.d.ts.map +1 -0
  189. package/dist/core/session-owner-lease.js +176 -0
  190. package/dist/core/session-owner-lease.js.map +1 -0
  191. package/dist/core/session-path-policy.d.ts +132 -0
  192. package/dist/core/session-path-policy.d.ts.map +1 -0
  193. package/dist/core/session-path-policy.js +780 -0
  194. package/dist/core/session-path-policy.js.map +1 -0
  195. package/dist/core/session-repair-plan.d.ts +49 -0
  196. package/dist/core/session-repair-plan.d.ts.map +1 -0
  197. package/dist/core/session-repair-plan.js +202 -0
  198. package/dist/core/session-repair-plan.js.map +1 -0
  199. package/dist/core/session-termination.d.ts +106 -0
  200. package/dist/core/session-termination.d.ts.map +1 -0
  201. package/dist/core/session-termination.js +445 -0
  202. package/dist/core/session-termination.js.map +1 -0
  203. package/dist/core/settings-manager.d.ts +52 -0
  204. package/dist/core/settings-manager.d.ts.map +1 -1
  205. package/dist/core/settings-manager.js +54 -5
  206. package/dist/core/settings-manager.js.map +1 -1
  207. package/dist/core/system-prompt.d.ts.map +1 -1
  208. package/dist/core/system-prompt.js +1 -1
  209. package/dist/core/system-prompt.js.map +1 -1
  210. package/dist/core/tools/grep.d.ts.map +1 -1
  211. package/dist/core/tools/grep.js +47 -0
  212. package/dist/core/tools/grep.js.map +1 -1
  213. package/dist/core/tools/omp-pure-seams.d.ts +41 -0
  214. package/dist/core/tools/omp-pure-seams.d.ts.map +1 -0
  215. package/dist/core/tools/omp-pure-seams.js +142 -0
  216. package/dist/core/tools/omp-pure-seams.js.map +1 -0
  217. package/dist/core/tools/omp-seam-runtime.d.ts +100 -0
  218. package/dist/core/tools/omp-seam-runtime.d.ts.map +1 -0
  219. package/dist/core/tools/omp-seam-runtime.js +40 -0
  220. package/dist/core/tools/omp-seam-runtime.js.map +1 -0
  221. package/dist/core/tools/read.d.ts.map +1 -1
  222. package/dist/core/tools/read.js +34 -1
  223. package/dist/core/tools/read.js.map +1 -1
  224. package/dist/core/verified-bash-adapter.d.ts +36 -0
  225. package/dist/core/verified-bash-adapter.d.ts.map +1 -0
  226. package/dist/core/verified-bash-adapter.js +90 -0
  227. package/dist/core/verified-bash-adapter.js.map +1 -0
  228. package/dist/guardrails/command-redaction.d.ts +32 -0
  229. package/dist/guardrails/command-redaction.d.ts.map +1 -0
  230. package/dist/guardrails/command-redaction.js +776 -0
  231. package/dist/guardrails/command-redaction.js.map +1 -0
  232. package/dist/guardrails/evidence-attestation.d.ts +31 -0
  233. package/dist/guardrails/evidence-attestation.d.ts.map +1 -0
  234. package/dist/guardrails/evidence-attestation.js +178 -0
  235. package/dist/guardrails/evidence-attestation.js.map +1 -0
  236. package/dist/guardrails/evidence-receipt-store.d.ts +33 -0
  237. package/dist/guardrails/evidence-receipt-store.d.ts.map +1 -0
  238. package/dist/guardrails/evidence-receipt-store.js +446 -0
  239. package/dist/guardrails/evidence-receipt-store.js.map +1 -0
  240. package/dist/guardrails/evidence-receipt.d.ts +58 -0
  241. package/dist/guardrails/evidence-receipt.d.ts.map +1 -0
  242. package/dist/guardrails/evidence-receipt.js +389 -0
  243. package/dist/guardrails/evidence-receipt.js.map +1 -0
  244. package/dist/guardrails/evidence-system.d.ts +39 -15
  245. package/dist/guardrails/evidence-system.d.ts.map +1 -1
  246. package/dist/guardrails/evidence-system.js +255 -97
  247. package/dist/guardrails/evidence-system.js.map +1 -1
  248. package/dist/guardrails/replay-ledger-io.d.ts +6 -0
  249. package/dist/guardrails/replay-ledger-io.d.ts.map +1 -0
  250. package/dist/guardrails/replay-ledger-io.js +42 -0
  251. package/dist/guardrails/replay-ledger-io.js.map +1 -0
  252. package/dist/guardrails/replay-ledger-lock-owner.d.ts +32 -0
  253. package/dist/guardrails/replay-ledger-lock-owner.d.ts.map +1 -0
  254. package/dist/guardrails/replay-ledger-lock-owner.js +138 -0
  255. package/dist/guardrails/replay-ledger-lock-owner.js.map +1 -0
  256. package/dist/guardrails/replay-ledger-lock.d.ts +24 -0
  257. package/dist/guardrails/replay-ledger-lock.d.ts.map +1 -0
  258. package/dist/guardrails/replay-ledger-lock.js +135 -0
  259. package/dist/guardrails/replay-ledger-lock.js.map +1 -0
  260. package/dist/guardrails/replay-ledger-mutation-gate.d.ts +24 -0
  261. package/dist/guardrails/replay-ledger-mutation-gate.d.ts.map +1 -0
  262. package/dist/guardrails/replay-ledger-mutation-gate.js +205 -0
  263. package/dist/guardrails/replay-ledger-mutation-gate.js.map +1 -0
  264. package/dist/guardrails/replay-ledger-quarantine.d.ts +2 -0
  265. package/dist/guardrails/replay-ledger-quarantine.d.ts.map +1 -0
  266. package/dist/guardrails/replay-ledger-quarantine.js +19 -0
  267. package/dist/guardrails/replay-ledger-quarantine.js.map +1 -0
  268. package/dist/guardrails/replay-ledger-store.d.ts +32 -0
  269. package/dist/guardrails/replay-ledger-store.d.ts.map +1 -0
  270. package/dist/guardrails/replay-ledger-store.js +211 -0
  271. package/dist/guardrails/replay-ledger-store.js.map +1 -0
  272. package/dist/guardrails/shell-command-name-glob.d.ts +3 -0
  273. package/dist/guardrails/shell-command-name-glob.d.ts.map +1 -0
  274. package/dist/guardrails/shell-command-name-glob.js +233 -0
  275. package/dist/guardrails/shell-command-name-glob.js.map +1 -0
  276. package/dist/guardrails/shell-command-option.d.ts +7 -0
  277. package/dist/guardrails/shell-command-option.d.ts.map +1 -0
  278. package/dist/guardrails/shell-command-option.js +24 -0
  279. package/dist/guardrails/shell-command-option.js.map +1 -0
  280. package/dist/guardrails/shell-command-tokenizer.d.ts +29 -0
  281. package/dist/guardrails/shell-command-tokenizer.d.ts.map +1 -0
  282. package/dist/guardrails/shell-command-tokenizer.js +145 -0
  283. package/dist/guardrails/shell-command-tokenizer.js.map +1 -0
  284. package/dist/guardrails/shell-command-wrapper.d.ts +18 -0
  285. package/dist/guardrails/shell-command-wrapper.d.ts.map +1 -0
  286. package/dist/guardrails/shell-command-wrapper.js +42 -0
  287. package/dist/guardrails/shell-command-wrapper.js.map +1 -0
  288. package/dist/guardrails/verified-executor.d.ts +65 -0
  289. package/dist/guardrails/verified-executor.d.ts.map +1 -0
  290. package/dist/guardrails/verified-executor.js +171 -0
  291. package/dist/guardrails/verified-executor.js.map +1 -0
  292. package/dist/guardrails/workspace-fingerprint.d.ts +23 -0
  293. package/dist/guardrails/workspace-fingerprint.d.ts.map +1 -0
  294. package/dist/guardrails/workspace-fingerprint.js +634 -0
  295. package/dist/guardrails/workspace-fingerprint.js.map +1 -0
  296. package/dist/index.d.ts +15 -3
  297. package/dist/index.d.ts.map +1 -1
  298. package/dist/index.js +13 -1
  299. package/dist/index.js.map +1 -1
  300. package/dist/main.d.ts.map +1 -1
  301. package/dist/main.js +12 -0
  302. package/dist/main.js.map +1 -1
  303. package/dist/modes/interactive/components/footer.d.ts +1 -1
  304. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  305. package/dist/modes/interactive/components/footer.js +11 -8
  306. package/dist/modes/interactive/components/footer.js.map +1 -1
  307. package/dist/modes/interactive/interactive-mode.d.ts +3 -0
  308. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  309. package/dist/modes/interactive/interactive-mode.js +59 -9
  310. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  311. package/dist/modes/interactive/theme/omk-aurora-dark.json +80 -0
  312. package/dist/modes/interactive/theme/omk-aurora-light.json +80 -0
  313. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  314. package/dist/modes/interactive/theme/theme.js +5 -0
  315. package/dist/modes/interactive/theme/theme.js.map +1 -1
  316. package/dist/modes/print-mode.d.ts.map +1 -1
  317. package/dist/modes/print-mode.js +43 -2
  318. package/dist/modes/print-mode.js.map +1 -1
  319. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  320. package/dist/modes/rpc/rpc-mode.js +23 -5
  321. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  322. package/dist/modes/rpc/rpc-types.d.ts +3 -0
  323. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  324. package/dist/modes/rpc/rpc-types.js.map +1 -1
  325. package/dist/types/evidence.d.ts +211 -1
  326. package/dist/types/evidence.d.ts.map +1 -1
  327. package/dist/types/evidence.js.map +1 -1
  328. package/dist/verify-ci.d.ts +3 -0
  329. package/dist/verify-ci.d.ts.map +1 -0
  330. package/dist/verify-ci.js +30 -0
  331. package/dist/verify-ci.js.map +1 -0
  332. package/docs/adaptorch-preview.md +1 -1
  333. package/docs/compaction.md +38 -4
  334. package/docs/extensions.md +2 -0
  335. package/docs/provider-resilience.md +87 -0
  336. package/docs/sdk.md +238 -1
  337. package/docs/settings.md +80 -2
  338. package/docs/themes.md +2 -0
  339. package/docs/usage.md +38 -0
  340. package/examples/extensions/custom-provider-anthropic/package-lock.json +5 -5
  341. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  342. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  343. package/examples/extensions/gondolin/package-lock.json +2 -2
  344. package/examples/extensions/gondolin/package.json +1 -1
  345. package/examples/extensions/sandbox/package-lock.json +2 -2
  346. package/examples/extensions/sandbox/package.json +1 -1
  347. package/examples/extensions/with-deps/package-lock.json +4 -4
  348. package/examples/extensions/with-deps/package.json +1 -1
  349. package/npm-shrinkwrap.json +22 -13
  350. package/package.json +6 -5
@@ -0,0 +1,35 @@
1
+ import type { AgentOptions } from "omk-agent-core";
2
+ import type { SettingsManager } from "./settings-manager.ts";
3
+ /** §6.3 timeout categories. `undefined` category falls through to the global setting. */
4
+ export type ToolTimeoutCategory = "read" | "write" | "mcp" | "process" | "browser";
5
+ /** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */
6
+ export declare const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>>;
7
+ /**
8
+ * Classify a tool name into its §6.3 timeout category. Conservative on
9
+ * purpose: unknown names return `undefined` and keep the global timeout.
10
+ * A browser/computer-use match wins over the generic MCP category because
11
+ * browser automation is the slower bound.
12
+ */
13
+ export declare function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined;
14
+ /**
15
+ * Fill §6.3 category default timeouts for every active tool name that has no
16
+ * explicit per-name entry. Explicit entries (user settings and built-in
17
+ * defaults) always win and are all preserved; names without a category are
18
+ * omitted so they fall through to the global `toolTimeoutMs` at runtime.
19
+ */
20
+ export declare function applyCategoryTimeoutDefaults(toolNames: Iterable<string>, explicit: Readonly<Record<string, number>>): Record<string, number>;
21
+ type ToolScheduler = NonNullable<AgentOptions["toolScheduler"]>;
22
+ export interface ResolvedAgentToolSettings {
23
+ readonly toolScheduler: ToolScheduler;
24
+ readonly maxToolConcurrency: number | undefined;
25
+ readonly strictExtensionClaims: boolean;
26
+ readonly toolTimeoutMs: number;
27
+ readonly toolTimeouts: Record<string, number>;
28
+ }
29
+ export declare class AgentToolSettingsError extends Error {
30
+ readonly settingName: string;
31
+ constructor(settingName: string);
32
+ }
33
+ export declare function resolveAgentToolSettings(settingsManager: SettingsManager, env?: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>>): ResolvedAgentToolSettings;
34
+ export {};
35
+ //# sourceMappingURL=agent-tool-settings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-tool-settings.d.ts","sourceRoot":"","sources":["../../src/core/agent-tool-settings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAwB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAiBnF,0FAAyF;AACzF,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,GAAG,SAAS,GAAG,SAAS,CAAC;AAEnF,0IAAyI;AACzI,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,MAAM,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAM/E,CAAC;AASH;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAO5F;AAED;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC3C,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,EAC3B,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GACxC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAaxB;AAED,KAAK,aAAa,GAAG,WAAW,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,CAAC;AAEhE,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,aAAa,EAAE,aAAa,CAAC;IACtC,QAAQ,CAAC,kBAAkB,EAAE,MAAM,GAAG,SAAS,CAAC;IAChD,QAAQ,CAAC,qBAAqB,EAAE,OAAO,CAAC;IACxC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9C;AAED,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAE7B,YAAY,WAAW,EAAE,MAAM,EAI9B;CACD;AAiFD,wBAAgB,wBAAwB,CACvC,eAAe,EAAE,eAAe,EAChC,GAAG,GAAE,MAAM,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GACjF,yBAAyB,CAc3B","sourcesContent":["import type { AgentOptions } from \"omk-agent-core\";\nimport type { AgentRuntimeSettings, SettingsManager } from \"./settings-manager.ts\";\n\nconst DEFAULT_TOOL_SCHEDULER = \"dag-v2\";\nconst DEFAULT_MAX_TOOL_CONCURRENCY = 4;\nconst DEFAULT_TOOL_TIMEOUT_MS = 0;\nconst MAX_TOOL_TIMEOUT_MS = 2_147_483_647;\n\nconst DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>> = {\n\tbash: 300_000,\n\tedit: 60_000,\n\tfind: 30_000,\n\tgrep: 30_000,\n\tls: 30_000,\n\tread: 30_000,\n\twrite: 60_000,\n};\n\n/** §6.3 timeout categories. `undefined` category falls through to the global setting. */\nexport type ToolTimeoutCategory = \"read\" | \"write\" | \"mcp\" | \"process\" | \"browser\";\n\n/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */\nexport const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>> = Object.freeze({\n\tread: 30_000,\n\twrite: 60_000,\n\tmcp: 120_000,\n\tprocess: 300_000,\n\tbrowser: 180_000,\n});\n\nconst READ_CATEGORY_TOOLS = new Set([\"read\", \"ls\", \"find\", \"grep\", \"glob\", \"list\", \"search\"]);\nconst WRITE_CATEGORY_TOOLS = new Set([\"write\", \"edit\"]);\nconst PROCESS_CATEGORY_TOOLS = new Set([\"bash\"]);\n// Matches direct browser/computer-use tools and browser tools bridged through\n// MCP servers (e.g. `mcp__playwright__browser_click`).\nconst BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;\n\n/**\n * Classify a tool name into its §6.3 timeout category. Conservative on\n * purpose: unknown names return `undefined` and keep the global timeout.\n * A browser/computer-use match wins over the generic MCP category because\n * browser automation is the slower bound.\n */\nexport function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined {\n\tif (READ_CATEGORY_TOOLS.has(toolName)) return \"read\";\n\tif (WRITE_CATEGORY_TOOLS.has(toolName)) return \"write\";\n\tif (PROCESS_CATEGORY_TOOLS.has(toolName)) return \"process\";\n\tif (BROWSER_TOOL_PATTERN.test(toolName)) return \"browser\";\n\tif (toolName.startsWith(\"mcp__\")) return \"mcp\";\n\treturn undefined;\n}\n\n/**\n * Fill §6.3 category default timeouts for every active tool name that has no\n * explicit per-name entry. Explicit entries (user settings and built-in\n * defaults) always win and are all preserved; names without a category are\n * omitted so they fall through to the global `toolTimeoutMs` at runtime.\n */\nexport function applyCategoryTimeoutDefaults(\n\ttoolNames: Iterable<string>,\n\texplicit: Readonly<Record<string, number>>,\n): Record<string, number> {\n\tconst merged: Record<string, number> = Object.create(null);\n\tfor (const toolName of toolNames) {\n\t\tif (Object.hasOwn(explicit, toolName)) continue;\n\t\tconst category = resolveToolTimeoutCategory(toolName);\n\t\tif (category !== undefined) {\n\t\t\tmerged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];\n\t\t}\n\t}\n\tfor (const [toolName, timeoutMs] of Object.entries(explicit)) {\n\t\tmerged[toolName] = timeoutMs;\n\t}\n\treturn merged;\n}\n\ntype ToolScheduler = NonNullable<AgentOptions[\"toolScheduler\"]>;\n\nexport interface ResolvedAgentToolSettings {\n\treadonly toolScheduler: ToolScheduler;\n\treadonly maxToolConcurrency: number | undefined;\n\treadonly strictExtensionClaims: boolean;\n\treadonly toolTimeoutMs: number;\n\treadonly toolTimeouts: Record<string, number>;\n}\n\nexport class AgentToolSettingsError extends Error {\n\treadonly settingName: string;\n\n\tconstructor(settingName: string) {\n\t\tsuper(`Invalid ${settingName} setting`);\n\t\tthis.name = \"AgentToolSettingsError\";\n\t\tthis.settingName = settingName;\n\t}\n}\n\nfunction parseScheduler(value: unknown, settingName: string): ToolScheduler | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"waves-v1\" || value === \"dag-v2\") {\n\t\treturn value;\n\t}\n\tthrow new AgentToolSettingsError(settingName);\n}\n\nfunction parseTimeout(value: unknown, settingName: string, defaultValue: number): number {\n\tif (value === undefined) {\n\t\treturn defaultValue;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseConcurrency(value: unknown): number | undefined {\n\tif (value === undefined) {\n\t\treturn DEFAULT_MAX_TOOL_CONCURRENCY;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n\t\tthrow new AgentToolSettingsError(\"agent.maxToolConcurrency\");\n\t}\n\treturn value === 0 ? undefined : value;\n}\n\nfunction parseAgentSettings(value: AgentRuntimeSettings | undefined, settingName: string): AgentRuntimeSettings {\n\tif (value === undefined) {\n\t\treturn {};\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseToolTimeoutEntries(\n\tvalue: AgentRuntimeSettings[\"toolTimeouts\"],\n\tsettingName: string,\n): readonly (readonly [string, number])[] {\n\tif (value === undefined) {\n\t\treturn [];\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\n\treturn Object.entries(value).map(([toolName, timeoutMs]) => {\n\t\tif (toolName.length === 0) {\n\t\t\tthrow new AgentToolSettingsError(settingName);\n\t\t}\n\t\treturn [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)] as const;\n\t});\n}\n\nfunction resolveToolTimeouts(\n\tglobalSettings: AgentRuntimeSettings,\n\tprojectSettings: AgentRuntimeSettings,\n\teffectiveSettings: AgentRuntimeSettings,\n): Record<string, number> {\n\tconst timeouts: Record<string, number> = Object.create(null);\n\tconst entryGroups = [\n\t\tObject.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),\n\t\tparseToolTimeoutEntries(globalSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(projectSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(effectiveSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t];\n\tfor (const entries of entryGroups) {\n\t\tfor (const [toolName, timeoutMs] of entries) {\n\t\t\ttimeouts[toolName] = timeoutMs;\n\t\t}\n\t}\n\treturn timeouts;\n}\n\nexport function resolveAgentToolSettings(\n\tsettingsManager: SettingsManager,\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedAgentToolSettings {\n\tconst globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, \"agent\");\n\tconst projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, \"agent\");\n\tconst settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), \"agent\");\n\tconst envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, \"OMK_TOOL_SCHEDULER\");\n\tconst settingsScheduler = parseScheduler(settings.toolScheduler, \"agent.toolScheduler\");\n\n\treturn {\n\t\ttoolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,\n\t\tmaxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),\n\t\tstrictExtensionClaims: true,\n\t\ttoolTimeoutMs: parseTimeout(settings.toolTimeoutMs, \"agent.toolTimeoutMs\", DEFAULT_TOOL_TIMEOUT_MS),\n\t\ttoolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),\n\t};\n}\n"]}
@@ -0,0 +1,155 @@
1
+ const DEFAULT_TOOL_SCHEDULER = "dag-v2";
2
+ const DEFAULT_MAX_TOOL_CONCURRENCY = 4;
3
+ const DEFAULT_TOOL_TIMEOUT_MS = 0;
4
+ const MAX_TOOL_TIMEOUT_MS = 2_147_483_647;
5
+ const DEFAULT_BUILTIN_TOOL_TIMEOUTS = {
6
+ bash: 300_000,
7
+ edit: 60_000,
8
+ find: 30_000,
9
+ grep: 30_000,
10
+ ls: 30_000,
11
+ read: 30_000,
12
+ write: 60_000,
13
+ };
14
+ /** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */
15
+ export const TOOL_CATEGORY_TIMEOUTS = Object.freeze({
16
+ read: 30_000,
17
+ write: 60_000,
18
+ mcp: 120_000,
19
+ process: 300_000,
20
+ browser: 180_000,
21
+ });
22
+ const READ_CATEGORY_TOOLS = new Set(["read", "ls", "find", "grep", "glob", "list", "search"]);
23
+ const WRITE_CATEGORY_TOOLS = new Set(["write", "edit"]);
24
+ const PROCESS_CATEGORY_TOOLS = new Set(["bash"]);
25
+ // Matches direct browser/computer-use tools and browser tools bridged through
26
+ // MCP servers (e.g. `mcp__playwright__browser_click`).
27
+ const BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;
28
+ /**
29
+ * Classify a tool name into its §6.3 timeout category. Conservative on
30
+ * purpose: unknown names return `undefined` and keep the global timeout.
31
+ * A browser/computer-use match wins over the generic MCP category because
32
+ * browser automation is the slower bound.
33
+ */
34
+ export function resolveToolTimeoutCategory(toolName) {
35
+ if (READ_CATEGORY_TOOLS.has(toolName))
36
+ return "read";
37
+ if (WRITE_CATEGORY_TOOLS.has(toolName))
38
+ return "write";
39
+ if (PROCESS_CATEGORY_TOOLS.has(toolName))
40
+ return "process";
41
+ if (BROWSER_TOOL_PATTERN.test(toolName))
42
+ return "browser";
43
+ if (toolName.startsWith("mcp__"))
44
+ return "mcp";
45
+ return undefined;
46
+ }
47
+ /**
48
+ * Fill §6.3 category default timeouts for every active tool name that has no
49
+ * explicit per-name entry. Explicit entries (user settings and built-in
50
+ * defaults) always win and are all preserved; names without a category are
51
+ * omitted so they fall through to the global `toolTimeoutMs` at runtime.
52
+ */
53
+ export function applyCategoryTimeoutDefaults(toolNames, explicit) {
54
+ const merged = Object.create(null);
55
+ for (const toolName of toolNames) {
56
+ if (Object.hasOwn(explicit, toolName))
57
+ continue;
58
+ const category = resolveToolTimeoutCategory(toolName);
59
+ if (category !== undefined) {
60
+ merged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];
61
+ }
62
+ }
63
+ for (const [toolName, timeoutMs] of Object.entries(explicit)) {
64
+ merged[toolName] = timeoutMs;
65
+ }
66
+ return merged;
67
+ }
68
+ export class AgentToolSettingsError extends Error {
69
+ settingName;
70
+ constructor(settingName) {
71
+ super(`Invalid ${settingName} setting`);
72
+ this.name = "AgentToolSettingsError";
73
+ this.settingName = settingName;
74
+ }
75
+ }
76
+ function parseScheduler(value, settingName) {
77
+ if (value === undefined) {
78
+ return undefined;
79
+ }
80
+ if (value === "waves-v1" || value === "dag-v2") {
81
+ return value;
82
+ }
83
+ throw new AgentToolSettingsError(settingName);
84
+ }
85
+ function parseTimeout(value, settingName, defaultValue) {
86
+ if (value === undefined) {
87
+ return defaultValue;
88
+ }
89
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {
90
+ throw new AgentToolSettingsError(settingName);
91
+ }
92
+ return value;
93
+ }
94
+ function parseConcurrency(value) {
95
+ if (value === undefined) {
96
+ return DEFAULT_MAX_TOOL_CONCURRENCY;
97
+ }
98
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
99
+ throw new AgentToolSettingsError("agent.maxToolConcurrency");
100
+ }
101
+ return value === 0 ? undefined : value;
102
+ }
103
+ function parseAgentSettings(value, settingName) {
104
+ if (value === undefined) {
105
+ return {};
106
+ }
107
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
108
+ throw new AgentToolSettingsError(settingName);
109
+ }
110
+ return value;
111
+ }
112
+ function parseToolTimeoutEntries(value, settingName) {
113
+ if (value === undefined) {
114
+ return [];
115
+ }
116
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
117
+ throw new AgentToolSettingsError(settingName);
118
+ }
119
+ return Object.entries(value).map(([toolName, timeoutMs]) => {
120
+ if (toolName.length === 0) {
121
+ throw new AgentToolSettingsError(settingName);
122
+ }
123
+ return [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)];
124
+ });
125
+ }
126
+ function resolveToolTimeouts(globalSettings, projectSettings, effectiveSettings) {
127
+ const timeouts = Object.create(null);
128
+ const entryGroups = [
129
+ Object.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),
130
+ parseToolTimeoutEntries(globalSettings.toolTimeouts, "agent.toolTimeouts"),
131
+ parseToolTimeoutEntries(projectSettings.toolTimeouts, "agent.toolTimeouts"),
132
+ parseToolTimeoutEntries(effectiveSettings.toolTimeouts, "agent.toolTimeouts"),
133
+ ];
134
+ for (const entries of entryGroups) {
135
+ for (const [toolName, timeoutMs] of entries) {
136
+ timeouts[toolName] = timeoutMs;
137
+ }
138
+ }
139
+ return timeouts;
140
+ }
141
+ export function resolveAgentToolSettings(settingsManager, env = process.env) {
142
+ const globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, "agent");
143
+ const projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, "agent");
144
+ const settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), "agent");
145
+ const envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, "OMK_TOOL_SCHEDULER");
146
+ const settingsScheduler = parseScheduler(settings.toolScheduler, "agent.toolScheduler");
147
+ return {
148
+ toolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,
149
+ maxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),
150
+ strictExtensionClaims: true,
151
+ toolTimeoutMs: parseTimeout(settings.toolTimeoutMs, "agent.toolTimeoutMs", DEFAULT_TOOL_TIMEOUT_MS),
152
+ toolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),
153
+ };
154
+ }
155
+ //# sourceMappingURL=agent-tool-settings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-tool-settings.js","sourceRoot":"","sources":["../../src/core/agent-tool-settings.ts"],"names":[],"mappings":"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","sourcesContent":["import type { AgentOptions } from \"omk-agent-core\";\nimport type { AgentRuntimeSettings, SettingsManager } from \"./settings-manager.ts\";\n\nconst DEFAULT_TOOL_SCHEDULER = \"dag-v2\";\nconst DEFAULT_MAX_TOOL_CONCURRENCY = 4;\nconst DEFAULT_TOOL_TIMEOUT_MS = 0;\nconst MAX_TOOL_TIMEOUT_MS = 2_147_483_647;\n\nconst DEFAULT_BUILTIN_TOOL_TIMEOUTS: Readonly<Record<string, number>> = {\n\tbash: 300_000,\n\tedit: 60_000,\n\tfind: 30_000,\n\tgrep: 30_000,\n\tls: 30_000,\n\tread: 30_000,\n\twrite: 60_000,\n};\n\n/** §6.3 timeout categories. `undefined` category falls through to the global setting. */\nexport type ToolTimeoutCategory = \"read\" | \"write\" | \"mcp\" | \"process\" | \"browser\";\n\n/** §6.3 category default timeouts (ms): read/list/search 30s, write/edit 60s, MCP 120s, bash/process 300s, browser/computer-use 180s. */\nexport const TOOL_CATEGORY_TIMEOUTS: Readonly<Record<ToolTimeoutCategory, number>> = Object.freeze({\n\tread: 30_000,\n\twrite: 60_000,\n\tmcp: 120_000,\n\tprocess: 300_000,\n\tbrowser: 180_000,\n});\n\nconst READ_CATEGORY_TOOLS = new Set([\"read\", \"ls\", \"find\", \"grep\", \"glob\", \"list\", \"search\"]);\nconst WRITE_CATEGORY_TOOLS = new Set([\"write\", \"edit\"]);\nconst PROCESS_CATEGORY_TOOLS = new Set([\"bash\"]);\n// Matches direct browser/computer-use tools and browser tools bridged through\n// MCP servers (e.g. `mcp__playwright__browser_click`).\nconst BROWSER_TOOL_PATTERN = /(^|__)(browser_|computer[-_]?use$|computer_)/;\n\n/**\n * Classify a tool name into its §6.3 timeout category. Conservative on\n * purpose: unknown names return `undefined` and keep the global timeout.\n * A browser/computer-use match wins over the generic MCP category because\n * browser automation is the slower bound.\n */\nexport function resolveToolTimeoutCategory(toolName: string): ToolTimeoutCategory | undefined {\n\tif (READ_CATEGORY_TOOLS.has(toolName)) return \"read\";\n\tif (WRITE_CATEGORY_TOOLS.has(toolName)) return \"write\";\n\tif (PROCESS_CATEGORY_TOOLS.has(toolName)) return \"process\";\n\tif (BROWSER_TOOL_PATTERN.test(toolName)) return \"browser\";\n\tif (toolName.startsWith(\"mcp__\")) return \"mcp\";\n\treturn undefined;\n}\n\n/**\n * Fill §6.3 category default timeouts for every active tool name that has no\n * explicit per-name entry. Explicit entries (user settings and built-in\n * defaults) always win and are all preserved; names without a category are\n * omitted so they fall through to the global `toolTimeoutMs` at runtime.\n */\nexport function applyCategoryTimeoutDefaults(\n\ttoolNames: Iterable<string>,\n\texplicit: Readonly<Record<string, number>>,\n): Record<string, number> {\n\tconst merged: Record<string, number> = Object.create(null);\n\tfor (const toolName of toolNames) {\n\t\tif (Object.hasOwn(explicit, toolName)) continue;\n\t\tconst category = resolveToolTimeoutCategory(toolName);\n\t\tif (category !== undefined) {\n\t\t\tmerged[toolName] = TOOL_CATEGORY_TIMEOUTS[category];\n\t\t}\n\t}\n\tfor (const [toolName, timeoutMs] of Object.entries(explicit)) {\n\t\tmerged[toolName] = timeoutMs;\n\t}\n\treturn merged;\n}\n\ntype ToolScheduler = NonNullable<AgentOptions[\"toolScheduler\"]>;\n\nexport interface ResolvedAgentToolSettings {\n\treadonly toolScheduler: ToolScheduler;\n\treadonly maxToolConcurrency: number | undefined;\n\treadonly strictExtensionClaims: boolean;\n\treadonly toolTimeoutMs: number;\n\treadonly toolTimeouts: Record<string, number>;\n}\n\nexport class AgentToolSettingsError extends Error {\n\treadonly settingName: string;\n\n\tconstructor(settingName: string) {\n\t\tsuper(`Invalid ${settingName} setting`);\n\t\tthis.name = \"AgentToolSettingsError\";\n\t\tthis.settingName = settingName;\n\t}\n}\n\nfunction parseScheduler(value: unknown, settingName: string): ToolScheduler | undefined {\n\tif (value === undefined) {\n\t\treturn undefined;\n\t}\n\tif (value === \"waves-v1\" || value === \"dag-v2\") {\n\t\treturn value;\n\t}\n\tthrow new AgentToolSettingsError(settingName);\n}\n\nfunction parseTimeout(value: unknown, settingName: string, defaultValue: number): number {\n\tif (value === undefined) {\n\t\treturn defaultValue;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_TOOL_TIMEOUT_MS) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseConcurrency(value: unknown): number | undefined {\n\tif (value === undefined) {\n\t\treturn DEFAULT_MAX_TOOL_CONCURRENCY;\n\t}\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n\t\tthrow new AgentToolSettingsError(\"agent.maxToolConcurrency\");\n\t}\n\treturn value === 0 ? undefined : value;\n}\n\nfunction parseAgentSettings(value: AgentRuntimeSettings | undefined, settingName: string): AgentRuntimeSettings {\n\tif (value === undefined) {\n\t\treturn {};\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\treturn value;\n}\n\nfunction parseToolTimeoutEntries(\n\tvalue: AgentRuntimeSettings[\"toolTimeouts\"],\n\tsettingName: string,\n): readonly (readonly [string, number])[] {\n\tif (value === undefined) {\n\t\treturn [];\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new AgentToolSettingsError(settingName);\n\t}\n\n\treturn Object.entries(value).map(([toolName, timeoutMs]) => {\n\t\tif (toolName.length === 0) {\n\t\t\tthrow new AgentToolSettingsError(settingName);\n\t\t}\n\t\treturn [toolName, parseTimeout(timeoutMs, `${settingName}.${toolName}`, DEFAULT_TOOL_TIMEOUT_MS)] as const;\n\t});\n}\n\nfunction resolveToolTimeouts(\n\tglobalSettings: AgentRuntimeSettings,\n\tprojectSettings: AgentRuntimeSettings,\n\teffectiveSettings: AgentRuntimeSettings,\n): Record<string, number> {\n\tconst timeouts: Record<string, number> = Object.create(null);\n\tconst entryGroups = [\n\t\tObject.entries(DEFAULT_BUILTIN_TOOL_TIMEOUTS),\n\t\tparseToolTimeoutEntries(globalSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(projectSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t\tparseToolTimeoutEntries(effectiveSettings.toolTimeouts, \"agent.toolTimeouts\"),\n\t];\n\tfor (const entries of entryGroups) {\n\t\tfor (const [toolName, timeoutMs] of entries) {\n\t\t\ttimeouts[toolName] = timeoutMs;\n\t\t}\n\t}\n\treturn timeouts;\n}\n\nexport function resolveAgentToolSettings(\n\tsettingsManager: SettingsManager,\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): ResolvedAgentToolSettings {\n\tconst globalSettings = parseAgentSettings(settingsManager.getGlobalSettings().agent, \"agent\");\n\tconst projectSettings = parseAgentSettings(settingsManager.getProjectSettings().agent, \"agent\");\n\tconst settings = parseAgentSettings(settingsManager.getAgentRuntimeSettings(), \"agent\");\n\tconst envScheduler = parseScheduler(env.OMK_TOOL_SCHEDULER, \"OMK_TOOL_SCHEDULER\");\n\tconst settingsScheduler = parseScheduler(settings.toolScheduler, \"agent.toolScheduler\");\n\n\treturn {\n\t\ttoolScheduler: envScheduler ?? settingsScheduler ?? DEFAULT_TOOL_SCHEDULER,\n\t\tmaxToolConcurrency: parseConcurrency(settings.maxToolConcurrency),\n\t\tstrictExtensionClaims: true,\n\t\ttoolTimeoutMs: parseTimeout(settings.toolTimeoutMs, \"agent.toolTimeoutMs\", DEFAULT_TOOL_TIMEOUT_MS),\n\t\ttoolTimeouts: resolveToolTimeouts(globalSettings, projectSettings, settings),\n\t};\n}\n"]}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Atomically and durably replace the contents of `targetPath`.
3
+ *
4
+ * Writes a uniquely named temp file in the same directory, preserves the
5
+ * exact private mode 0600, fsyncs and closes the temp file, then renames it
6
+ * over the target so readers only ever observe the complete old or
7
+ * complete new content, never a truncated file. The parent directory is
8
+ * fsynced where supported. Windows and explicit unsupported-filesystem codes
9
+ * skip that final operation; real durability failures propagate. On any failure
10
+ * before the rename completes, the temp file is
11
+ * removed (best-effort) and the original target is left untouched.
12
+ */
13
+ export declare function atomicRewriteFileSync(targetPath: string, data: string | Uint8Array): void;
14
+ //# sourceMappingURL=atomic-session-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"atomic-session-file.d.ts","sourceRoot":"","sources":["../../src/core/atomic-session-file.ts"],"names":[],"mappings":"AAuBA;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAkEzF","sourcesContent":["import { randomBytes } from \"crypto\";\nimport {\n\tcloseSync,\n\tfsyncSync,\n\tlstatSync,\n\topenSync,\n\trealpathSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteSync,\n} from \"fs\";\nimport { basename, dirname, join } from \"path\";\nimport { enforcePrivateFileDescriptorModeSync } from \"./durable-file-mode.ts\";\n\nfunction assertRewriteTargetSafe(path: string): void {\n\ttry {\n\t\tif (statSync(path).nlink > 1) throw new Error(\"Atomic rewrite refused for a target with more than one hard link\");\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || !(\"code\" in error) || Reflect.get(error, \"code\") !== \"ENOENT\") throw error;\n\t}\n}\n\n/**\n * Atomically and durably replace the contents of `targetPath`.\n *\n * Writes a uniquely named temp file in the same directory, preserves the\n * exact private mode 0600, fsyncs and closes the temp file, then renames it\n * over the target so readers only ever observe the complete old or\n * complete new content, never a truncated file. The parent directory is\n * fsynced where supported. Windows and explicit unsupported-filesystem codes\n * skip that final operation; real durability failures propagate. On any failure\n * before the rename completes, the temp file is\n * removed (best-effort) and the original target is left untouched.\n */\nexport function atomicRewriteFileSync(targetPath: string, data: string | Uint8Array): void {\n\tlet rewritePath: string;\n\ttry {\n\t\trewritePath = realpathSync.native(targetPath);\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\t\tif (code !== \"ENOENT\") throw error;\n\t\tlet danglingLink = false;\n\t\ttry {\n\t\t\tdanglingLink = lstatSync(targetPath).isSymbolicLink();\n\t\t} catch (lstatError) {\n\t\t\tconst lstatCode =\n\t\t\t\tlstatError instanceof Error && \"code\" in lstatError ? Reflect.get(lstatError, \"code\") : undefined;\n\t\t\tif (lstatCode !== \"ENOENT\") throw lstatError;\n\t\t}\n\t\tif (danglingLink) throw error;\n\t\trewritePath = targetPath;\n\t}\n\tconst dir = dirname(rewritePath);\n\n\tassertRewriteTargetSafe(rewritePath);\n\tconst tempPath = join(dir, `.${basename(rewritePath)}.${process.pid}.${randomBytes(6).toString(\"hex\")}.tmp`);\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = openSync(tempPath, \"wx\", 0o600);\n\t\tenforcePrivateFileDescriptorModeSync(fd, rewritePath);\n\t\tconst buffer = typeof data === \"string\" ? Buffer.from(data, \"utf8\") : Buffer.from(data);\n\t\tlet offset = 0;\n\t\twhile (offset < buffer.length) {\n\t\t\toffset += writeSync(fd, buffer, offset);\n\t\t}\n\t\tfsyncSync(fd);\n\t\tcloseSync(fd);\n\t\tfd = undefined;\n\t\tassertRewriteTargetSafe(rewritePath);\n\t\trenameSync(tempPath, rewritePath);\n\t} catch (error) {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} catch (cleanupError) {\n\t\t\t\tif (!(cleanupError instanceof Error)) throw cleanupError;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tunlinkSync(tempPath);\n\t\t} catch (cleanupError) {\n\t\t\tif (!(cleanupError instanceof Error)) throw cleanupError;\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (process.platform === \"win32\") return;\n\ttry {\n\t\tconst dirFd = openSync(dir, \"r\");\n\t\ttry {\n\t\t\tfsyncSync(dirFd);\n\t\t} finally {\n\t\t\tcloseSync(dirFd);\n\t\t}\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\t\tif (typeof code !== \"string\" || !new Set([\"EINVAL\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\"]).has(code)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1,104 @@
1
+ import { randomBytes } from "crypto";
2
+ import { closeSync, fsyncSync, lstatSync, openSync, realpathSync, renameSync, statSync, unlinkSync, writeSync, } from "fs";
3
+ import { basename, dirname, join } from "path";
4
+ import { enforcePrivateFileDescriptorModeSync } from "./durable-file-mode.js";
5
+ function assertRewriteTargetSafe(path) {
6
+ try {
7
+ if (statSync(path).nlink > 1)
8
+ throw new Error("Atomic rewrite refused for a target with more than one hard link");
9
+ }
10
+ catch (error) {
11
+ if (!(error instanceof Error) || !("code" in error) || Reflect.get(error, "code") !== "ENOENT")
12
+ throw error;
13
+ }
14
+ }
15
+ /**
16
+ * Atomically and durably replace the contents of `targetPath`.
17
+ *
18
+ * Writes a uniquely named temp file in the same directory, preserves the
19
+ * exact private mode 0600, fsyncs and closes the temp file, then renames it
20
+ * over the target so readers only ever observe the complete old or
21
+ * complete new content, never a truncated file. The parent directory is
22
+ * fsynced where supported. Windows and explicit unsupported-filesystem codes
23
+ * skip that final operation; real durability failures propagate. On any failure
24
+ * before the rename completes, the temp file is
25
+ * removed (best-effort) and the original target is left untouched.
26
+ */
27
+ export function atomicRewriteFileSync(targetPath, data) {
28
+ let rewritePath;
29
+ try {
30
+ rewritePath = realpathSync.native(targetPath);
31
+ }
32
+ catch (error) {
33
+ const code = error instanceof Error && "code" in error ? Reflect.get(error, "code") : undefined;
34
+ if (code !== "ENOENT")
35
+ throw error;
36
+ let danglingLink = false;
37
+ try {
38
+ danglingLink = lstatSync(targetPath).isSymbolicLink();
39
+ }
40
+ catch (lstatError) {
41
+ const lstatCode = lstatError instanceof Error && "code" in lstatError ? Reflect.get(lstatError, "code") : undefined;
42
+ if (lstatCode !== "ENOENT")
43
+ throw lstatError;
44
+ }
45
+ if (danglingLink)
46
+ throw error;
47
+ rewritePath = targetPath;
48
+ }
49
+ const dir = dirname(rewritePath);
50
+ assertRewriteTargetSafe(rewritePath);
51
+ const tempPath = join(dir, `.${basename(rewritePath)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
52
+ let fd;
53
+ try {
54
+ fd = openSync(tempPath, "wx", 0o600);
55
+ enforcePrivateFileDescriptorModeSync(fd, rewritePath);
56
+ const buffer = typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data);
57
+ let offset = 0;
58
+ while (offset < buffer.length) {
59
+ offset += writeSync(fd, buffer, offset);
60
+ }
61
+ fsyncSync(fd);
62
+ closeSync(fd);
63
+ fd = undefined;
64
+ assertRewriteTargetSafe(rewritePath);
65
+ renameSync(tempPath, rewritePath);
66
+ }
67
+ catch (error) {
68
+ if (fd !== undefined) {
69
+ try {
70
+ closeSync(fd);
71
+ }
72
+ catch (cleanupError) {
73
+ if (!(cleanupError instanceof Error))
74
+ throw cleanupError;
75
+ }
76
+ }
77
+ try {
78
+ unlinkSync(tempPath);
79
+ }
80
+ catch (cleanupError) {
81
+ if (!(cleanupError instanceof Error))
82
+ throw cleanupError;
83
+ }
84
+ throw error;
85
+ }
86
+ if (process.platform === "win32")
87
+ return;
88
+ try {
89
+ const dirFd = openSync(dir, "r");
90
+ try {
91
+ fsyncSync(dirFd);
92
+ }
93
+ finally {
94
+ closeSync(dirFd);
95
+ }
96
+ }
97
+ catch (error) {
98
+ const code = error instanceof Error && "code" in error ? Reflect.get(error, "code") : undefined;
99
+ if (typeof code !== "string" || !new Set(["EINVAL", "ENOTSUP", "EOPNOTSUPP", "ENOSYS"]).has(code)) {
100
+ throw error;
101
+ }
102
+ }
103
+ }
104
+ //# sourceMappingURL=atomic-session-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"atomic-session-file.js","sourceRoot":"","sources":["../../src/core/atomic-session-file.ts"],"names":[],"mappings":"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","sourcesContent":["import { randomBytes } from \"crypto\";\nimport {\n\tcloseSync,\n\tfsyncSync,\n\tlstatSync,\n\topenSync,\n\trealpathSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteSync,\n} from \"fs\";\nimport { basename, dirname, join } from \"path\";\nimport { enforcePrivateFileDescriptorModeSync } from \"./durable-file-mode.ts\";\n\nfunction assertRewriteTargetSafe(path: string): void {\n\ttry {\n\t\tif (statSync(path).nlink > 1) throw new Error(\"Atomic rewrite refused for a target with more than one hard link\");\n\t} catch (error) {\n\t\tif (!(error instanceof Error) || !(\"code\" in error) || Reflect.get(error, \"code\") !== \"ENOENT\") throw error;\n\t}\n}\n\n/**\n * Atomically and durably replace the contents of `targetPath`.\n *\n * Writes a uniquely named temp file in the same directory, preserves the\n * exact private mode 0600, fsyncs and closes the temp file, then renames it\n * over the target so readers only ever observe the complete old or\n * complete new content, never a truncated file. The parent directory is\n * fsynced where supported. Windows and explicit unsupported-filesystem codes\n * skip that final operation; real durability failures propagate. On any failure\n * before the rename completes, the temp file is\n * removed (best-effort) and the original target is left untouched.\n */\nexport function atomicRewriteFileSync(targetPath: string, data: string | Uint8Array): void {\n\tlet rewritePath: string;\n\ttry {\n\t\trewritePath = realpathSync.native(targetPath);\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\t\tif (code !== \"ENOENT\") throw error;\n\t\tlet danglingLink = false;\n\t\ttry {\n\t\t\tdanglingLink = lstatSync(targetPath).isSymbolicLink();\n\t\t} catch (lstatError) {\n\t\t\tconst lstatCode =\n\t\t\t\tlstatError instanceof Error && \"code\" in lstatError ? Reflect.get(lstatError, \"code\") : undefined;\n\t\t\tif (lstatCode !== \"ENOENT\") throw lstatError;\n\t\t}\n\t\tif (danglingLink) throw error;\n\t\trewritePath = targetPath;\n\t}\n\tconst dir = dirname(rewritePath);\n\n\tassertRewriteTargetSafe(rewritePath);\n\tconst tempPath = join(dir, `.${basename(rewritePath)}.${process.pid}.${randomBytes(6).toString(\"hex\")}.tmp`);\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = openSync(tempPath, \"wx\", 0o600);\n\t\tenforcePrivateFileDescriptorModeSync(fd, rewritePath);\n\t\tconst buffer = typeof data === \"string\" ? Buffer.from(data, \"utf8\") : Buffer.from(data);\n\t\tlet offset = 0;\n\t\twhile (offset < buffer.length) {\n\t\t\toffset += writeSync(fd, buffer, offset);\n\t\t}\n\t\tfsyncSync(fd);\n\t\tcloseSync(fd);\n\t\tfd = undefined;\n\t\tassertRewriteTargetSafe(rewritePath);\n\t\trenameSync(tempPath, rewritePath);\n\t} catch (error) {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} catch (cleanupError) {\n\t\t\t\tif (!(cleanupError instanceof Error)) throw cleanupError;\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tunlinkSync(tempPath);\n\t\t} catch (cleanupError) {\n\t\t\tif (!(cleanupError instanceof Error)) throw cleanupError;\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (process.platform === \"win32\") return;\n\ttry {\n\t\tconst dirFd = openSync(dir, \"r\");\n\t\ttry {\n\t\t\tfsyncSync(dirFd);\n\t\t} finally {\n\t\t\tcloseSync(dirFd);\n\t\t}\n\t} catch (error) {\n\t\tconst code = error instanceof Error && \"code\" in error ? Reflect.get(error, \"code\") : undefined;\n\t\tif (typeof code !== \"string\" || !new Set([\"EINVAL\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\"]).has(code)) {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"command-safety.d.ts","sourceRoot":"","sources":["../../src/core/command-safety.ts"],"names":[],"mappings":"AACA,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,SAAS,GAAG,OAAO,CAAC;AAExD,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,WAAW,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CACf;AAsoBD,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,CAEpE;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEhE;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEhE;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAE9D","sourcesContent":["// allow: SIZE_OK - legacy safety rules table; this change only preserves existing typed behavior.\nexport type CommandRisk = \"block\" | \"confirm\" | \"allow\";\n\nexport interface CommandVerdict {\n\trisk: CommandRisk;\n\trule: string;\n\treason: string;\n}\n\ninterface CommandPrefixResult {\n\ttokens: string[];\n\tprivilege: string | undefined;\n}\n\nconst RISK_RANK: Readonly<Record<CommandRisk, number>> = {\n\tallow: 0,\n\tconfirm: 1,\n\tblock: 2,\n};\n\nconst PRIVILEGE_COMMANDS = new Set([\"sudo\", \"su\", \"doas\", \"pkexec\"]);\nconst SUDO_OPTIONS_WITH_VALUE = new Set([\n\t\"-C\",\n\t\"--close-from\",\n\t\"-g\",\n\t\"--group\",\n\t\"-h\",\n\t\"--host\",\n\t\"-p\",\n\t\"--prompt\",\n\t\"-T\",\n\t\"--command-timeout\",\n\t\"-u\",\n\t\"--user\",\n]);\nconst GIT_GLOBAL_OPTIONS_WITH_VALUE = new Set([\"-C\", \"-c\", \"--git-dir\", \"--work-tree\", \"--namespace\"]);\n\n/** Maximum recursion depth when unwrapping shell wrappers (bash -c, eval, xargs, find -exec). */\nconst MAX_WRAP_DEPTH = 6;\n\n/** Executables that run an inline command string passed via a `-c`-style flag. */\nconst SHELL_WRAPPERS = new Set([\"bash\", \"sh\", \"zsh\", \"dash\", \"ksh\", \"ash\"]);\n\n/**\n * Script interpreters that execute an inline program string (via a -c/-e/-r\n * style flag). Running inline code can execute arbitrary shell commands, so a\n * matched destructive/exec keyword inside the program escalates the call to\n * confirm-tier. A plain script-file path stays allow-tier.\n */\nconst INTERPRETER_INLINE_FLAGS: Readonly<Record<string, readonly string[]>> = {\n\tpython: [\"-c\"],\n\tpython2: [\"-c\"],\n\tpython3: [\"-c\"],\n\tnode: [\"-e\", \"--eval\", \"-p\", \"--print\"],\n\tperl: [\"-e\", \"-E\"],\n\truby: [\"-e\", \"-E\"],\n\tphp: [\"-r\", \"--run\"],\n\tlua: [\"-e\"],\n\texpect: [\"-c\"],\n};\n\n/**\n * Patterns that indicate an inline program invokes a shell command or\n * performs a destructive filesystem operation. Matching any of these inside\n * a `-c`/`-e`/`-r` program string escalates the call to confirm-tier.\n */\nconst INLINE_DESTRUCTIVE_PATTERNS: readonly RegExp[] = [\n\t/\\bos\\.system\\s*\\(/,\n\t/\\bos\\.remove\\s*\\(/,\n\t/\\bos\\.unlink\\s*\\(/,\n\t/\\bshutil\\.rmtree\\s*\\(/,\n\t/\\bsubprocess\\.(?:call|run|check_call|check_output|Popen)\\s*\\(/,\n\t/\\bexec(?:Sync|File)?\\s*\\(/,\n\t/\\bspawn(?:Sync)?\\s*\\(/,\n\t/\\bchild_process\\b/,\n\t/\\brequire\\s*\\(\\s*['\"]child_process['\"]\\s*\\)/,\n\t/\\b(?:system|popen)\\s*\\(/,\n\t/`[^`]*\\brm\\s+-/m,\n\t/\\$\\(\\s*[^)]*\\brm\\s+-/,\n];\n\n/** xargs options that consume a following value token before the wrapped command begins. */\nconst XARGS_OPTIONS_WITH_VALUE = new Set([\n\t\"-I\",\n\t\"-i\",\n\t\"-n\",\n\t\"-L\",\n\t\"-P\",\n\t\"-d\",\n\t\"-E\",\n\t\"-s\",\n\t\"-a\",\n\t\"--max-args\",\n\t\"--max-procs\",\n\t\"--delimiter\",\n\t\"--arg-file\",\n\t\"--max-lines\",\n\t\"--replace\",\n]);\n\n/**\n * Credential / secret file patterns. A bash argv token matching one of these is\n * treated as a `confirm`-tier access: headless callers (LLM tool calls, RPC bash)\n * deny by default, while an interactive user can still approve reading their own\n * files. These complement the §0.1 freedom safety floor, which hard-denies the\n * same paths on the entry points it guards.\n */\nconst SECRET_FILE_STRICT_PATTERNS: readonly RegExp[] = [\n\t/(^|\\/)\\.env(\\.|$)/i,\n\t/(^|\\/)\\.npmrc$/i,\n\t/(^|\\/)\\.netrc$/i,\n\t/(^|\\/)\\.pgpass$/i,\n\t/(^|\\/)\\.aws\\/credentials$/i,\n\t/(^|\\/)credentials$/i,\n\t/(^|\\/)auth\\.json$/i,\n\t/(^|\\/)id_(rsa|dsa|ecdsa|ed25519)$/i,\n\t/\\.(pem|key|p12|pfx|keystore|jks)$/i,\n\t/(^|\\/)secrets?(\\.[^/]+)?$/i,\n];\n\n/** Benign sibling files that look secret-ish but never hold credentials. */\nconst SECRET_FILE_ALLOW_PATTERNS: readonly RegExp[] = [/(^|\\/)\\.env\\.(example|sample|template|dist|defaults?)$/i];\nconst SEARCH_COMMANDS = new Set([\"grep\", \"egrep\", \"fgrep\", \"rg\"]);\nconst HOME_VARIABLE_RM_TARGETS = new Set([\"$home\", \"$\" + \"{home}\", \"$home/\", \"$\" + \"{home}/\"]);\n\nfunction verdict(risk: CommandRisk, rule: string, reason: string): CommandVerdict {\n\treturn { risk, rule, reason };\n}\n\nfunction allowVerdict(): CommandVerdict {\n\treturn verdict(\"allow\", \"command.allow\", \"No destructive or protected command pattern matched.\");\n}\n\nfunction isEnvAssignment(token: string | undefined): boolean {\n\treturn token !== undefined && /^[A-Za-z_][A-Za-z0-9_]*=.*/.test(token);\n}\n\nfunction tokenizeShellSegment(segment: string): string[] {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet quote: string | undefined;\n\tlet escaped = false;\n\n\tfor (const character of segment.trim()) {\n\t\tif (escaped) {\n\t\t\tcurrent += character;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (character === quote) {\n\t\t\t\tquote = undefined;\n\t\t\t} else {\n\t\t\t\tcurrent += character;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquote = character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/.test(character)) {\n\t\t\tif (current) {\n\t\t\t\ttokens.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += character;\n\t}\n\n\tif (escaped) current += \"\\\\\";\n\tif (current) tokens.push(current);\n\treturn tokens;\n}\n\nfunction splitShellCommands(command: string): string[] {\n\tconst segments: string[] = [];\n\tlet current = \"\";\n\tlet quote: string | undefined;\n\tlet escaped = false;\n\n\tfor (let index = 0; index < command.length; index += 1) {\n\t\tconst character = command[index];\n\t\tconst next = command[index + 1];\n\t\tif (escaped) {\n\t\t\tcurrent += character;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcurrent += character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tcurrent += character;\n\t\t\tif (character === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquote = character;\n\t\t\tcurrent += character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \";\" || character === \"|\" || character === \"\\n\" || character === \"\\r\") {\n\t\t\tif (current.trim()) segments.push(current.trim());\n\t\t\tcurrent = \"\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"&\") {\n\t\t\tif (current.trim()) segments.push(current.trim());\n\t\t\tcurrent = \"\";\n\t\t\tif (next === \"&\") index += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += character;\n\t}\n\n\tif (current.trim()) segments.push(current.trim());\n\treturn segments;\n}\n\nfunction skipEnvironmentPrefix(tokens: readonly string[], startIndex: number): number {\n\tlet index = startIndex;\n\twhile (isEnvAssignment(tokens[index])) index += 1;\n\tif (tokens[index]?.toLowerCase() !== \"env\") return index;\n\n\tindex += 1;\n\twhile (index < tokens.length) {\n\t\tconst token = tokens[index];\n\t\tif (isEnvAssignment(token)) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (token?.startsWith(\"-\")) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treturn index;\n}\n\nfunction optionConsumesValue(option: string, optionsWithValue: ReadonlySet<string>): boolean {\n\tif (option.includes(\"=\")) return false;\n\treturn optionsWithValue.has(option);\n}\n\nfunction skipPrivilegeOptions(tokens: readonly string[], startIndex: number, privilege: string): number {\n\tif (privilege !== \"sudo\" && privilege !== \"doas\") return startIndex;\n\n\tlet index = startIndex;\n\twhile (index < tokens.length) {\n\t\tconst token = tokens[index];\n\t\tif (!token?.startsWith(\"-\")) break;\n\t\tindex += 1;\n\t\tif (token === \"--\") break;\n\t\tif (optionConsumesValue(token, SUDO_OPTIONS_WITH_VALUE)) index += 1;\n\t}\n\treturn index;\n}\n\nfunction stripCommandPrefixes(tokens: readonly string[]): CommandPrefixResult {\n\tlet index = skipEnvironmentPrefix(tokens, 0);\n\tconst privilege = tokens[index]?.toLowerCase();\n\tif (!PRIVILEGE_COMMANDS.has(privilege ?? \"\")) {\n\t\treturn { tokens: tokens.slice(index), privilege: undefined };\n\t}\n\n\tindex += 1;\n\tindex = skipPrivilegeOptions(tokens, index, privilege ?? \"\");\n\tindex = skipEnvironmentPrefix(tokens, index);\n\treturn { tokens: tokens.slice(index), privilege };\n}\n\nfunction hasForkBomb(command: string): boolean {\n\treturn command.replace(/\\s/g, \"\").includes(\":(){:|:&};:\");\n}\n\nfunction normalizePathTarget(target: string): string {\n\treturn target.replace(/\\/+$/g, (match) => (target === match ? \"/\" : \"\")).replace(/\\/+/g, \"/\");\n}\n\nfunction classifyRmTarget(target: string): CommandVerdict | null {\n\tconst normalized = normalizePathTarget(target);\n\tif (normalized === \"/\" || normalized === \"/*\" || normalized === \"/.*\") {\n\t\treturn verdict(\"block\", \"fs.rm_rf_root\", \"Recursive forced rm targets filesystem root.\");\n\t}\n\tif (normalized === \"~\" || normalized === \"~/\" || normalized === \"~/*\" || normalized === \"~/.*\") {\n\t\treturn verdict(\"block\", \"fs.rm_rf_home\", \"Recursive forced rm targets the home directory.\");\n\t}\n\t// $HOME / ${HOME} expands to the user home directory at runtime.\n\tconst lower = normalized.toLowerCase();\n\tif (HOME_VARIABLE_RM_TARGETS.has(lower)) {\n\t\treturn verdict(\n\t\t\t\"confirm\",\n\t\t\t\"fs.rm_rf_home_var\",\n\t\t\t\"Recursive forced rm targets $HOME, which expands to the user home directory.\",\n\t\t);\n\t}\n\t// ~username targets another user home directory.\n\tif (/^~[A-Za-z0-9._-]/.test(normalized)) {\n\t\treturn verdict(\"confirm\", \"fs.rm_rf_user_home\", \"Recursive forced rm targets another user home directory.\");\n\t}\n\t// \".\" or \"./\" — current working directory (project root deletion risk).\n\tif (normalized === \".\") {\n\t\treturn verdict(\"confirm\", \"fs.rm_rf_cwd\", \"Recursive forced rm targets the current working directory.\");\n\t}\n\t// \"..\" — parent directory.\n\tif (normalized === \"..\") {\n\t\treturn verdict(\"confirm\", \"fs.rm_rf_parent\", \"Recursive forced rm targets the parent directory.\");\n\t}\n\treturn null;\n}\n\nfunction classifyRm(tokens: readonly string[]): CommandVerdict | null {\n\tlet hasRecursive = false;\n\tlet hasForce = false;\n\tlet endOfOptions = false;\n\tconst targets: string[] = [];\n\n\tfor (const token of tokens.slice(1)) {\n\t\tif (!endOfOptions && token === \"--\") {\n\t\t\tendOfOptions = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!endOfOptions && token.startsWith(\"-\") && token !== \"-\") {\n\t\t\tif (token === \"--recursive\") hasRecursive = true;\n\t\t\tif (token === \"--force\") hasForce = true;\n\t\t\tif (!token.startsWith(\"--\")) {\n\t\t\t\tconst flagCharacters = token.slice(1).split(\"\");\n\t\t\t\tif (flagCharacters.some((flag) => flag === \"r\" || flag === \"R\")) hasRecursive = true;\n\t\t\t\tif (flagCharacters.includes(\"f\")) hasForce = true;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\ttargets.push(token);\n\t}\n\n\tif (!hasRecursive || !hasForce) return null;\n\tfor (const target of targets) {\n\t\tconst targetVerdict = classifyRmTarget(target);\n\t\tif (targetVerdict) return targetVerdict;\n\t}\n\treturn null;\n}\n\nfunction isBlockDeviceOutput(token: string): boolean {\n\treturn /^of=\\/dev\\/(?:sd[a-z][a-z0-9]*|nvme[0-9a-z]+|disk(?:[0-9].*|\\/.*|$))/i.test(token);\n}\n\nfunction classifyDestructiveFilesystemCommand(command: string): CommandVerdict | null {\n\tif (hasForkBomb(command)) {\n\t\treturn verdict(\"block\", \"process.fork_bomb\", \"Shell fork bomb pattern would exhaust process resources.\");\n\t}\n\n\tconst { tokens } = stripCommandPrefixes(tokenizeShellSegment(command));\n\tconst executable = tokens[0]?.toLowerCase();\n\tif (!executable) return null;\n\tif (executable === \"rm\") return classifyRm(tokens);\n\tif (executable.startsWith(\"mkfs\")) {\n\t\treturn verdict(\"block\", \"fs.mkfs\", \"Filesystem formatting commands are blocked.\");\n\t}\n\tif (executable === \"dd\" && tokens.slice(1).some(isBlockDeviceOutput)) {\n\t\treturn verdict(\"block\", \"fs.dd_block_device\", \"dd writes directly to a block-device output path.\");\n\t}\n\treturn null;\n}\n\nfunction findGitCommand(tokens: readonly string[]): { command: string; args: string[]; originalArgs: string[] } | null {\n\tif (tokens[0]?.toLowerCase() !== \"git\") return null;\n\tlet index = 1;\n\twhile (index < tokens.length && tokens[index]?.startsWith(\"-\")) {\n\t\tconst option = tokens[index];\n\t\tconst normalizedOption = option.toLowerCase();\n\t\tindex += 1;\n\t\tif (option === \"--\") break;\n\t\tif (\n\t\t\toptionConsumesValue(option, GIT_GLOBAL_OPTIONS_WITH_VALUE) ||\n\t\t\toptionConsumesValue(normalizedOption, GIT_GLOBAL_OPTIONS_WITH_VALUE)\n\t\t) {\n\t\t\tindex += 1;\n\t\t}\n\t}\n\tconst command = tokens[index]?.toLowerCase();\n\tif (!command) return null;\n\tconst originalArgs = tokens.slice(index + 1);\n\treturn {\n\t\tcommand,\n\t\targs: originalArgs.map((argument) => argument.toLowerCase()),\n\t\toriginalArgs,\n\t};\n}\n\nfunction hasGitCleanForceDirectory(args: readonly string[]): boolean {\n\tlet hasForce = false;\n\tlet hasDirectory = false;\n\tfor (const arg of args) {\n\t\tif (arg === \"--force\") hasForce = true;\n\t\tif (arg === \"-f\") hasForce = true;\n\t\tif (arg === \"-d\") hasDirectory = true;\n\t\tif (arg.startsWith(\"-\") && !arg.startsWith(\"--\")) {\n\t\t\tconst flags = arg.slice(1).split(\"\");\n\t\t\tif (flags.includes(\"f\")) hasForce = true;\n\t\t\tif (flags.includes(\"d\")) hasDirectory = true;\n\t\t}\n\t}\n\treturn hasForce && hasDirectory;\n}\n\nfunction classifyProtectedGitCommand(command: string): CommandVerdict | null {\n\tconst { tokens } = stripCommandPrefixes(tokenizeShellSegment(command));\n\tconst gitCommand = findGitCommand(tokens);\n\tif (!gitCommand) return null;\n\n\tif (gitCommand.command === \"reset\" && gitCommand.args.includes(\"--hard\")) {\n\t\treturn verdict(\"confirm\", \"git.reset_hard\", \"git reset --hard can discard worktree changes.\");\n\t}\n\tif (gitCommand.command === \"restore\") {\n\t\tconst targetAll = gitCommand.originalArgs.includes(\".\") || gitCommand.originalArgs.includes(\"*\");\n\t\tconst rewritesWorktree = gitCommand.args.includes(\"--worktree\") || gitCommand.args.includes(\"--source\");\n\t\tif (targetAll || rewritesWorktree) {\n\t\t\treturn verdict(\"confirm\", \"git.restore\", \"git restore can discard or overwrite local worktree changes.\");\n\t\t}\n\t}\n\tif (gitCommand.command === \"checkout\" && gitCommand.originalArgs.includes(\".\")) {\n\t\treturn verdict(\"confirm\", \"git.checkout_dot\", \"git checkout . can overwrite local worktree changes.\");\n\t}\n\tif (gitCommand.command === \"clean\" && hasGitCleanForceDirectory(gitCommand.args)) {\n\t\treturn verdict(\"confirm\", \"git.clean_force\", \"git clean -fd can delete untracked files and directories.\");\n\t}\n\tif (gitCommand.command === \"stash\" && gitCommand.originalArgs.length === 0) {\n\t\treturn verdict(\"confirm\", \"git.stash_bare\", \"Bare git stash can hide local worktree changes.\");\n\t}\n\tif (gitCommand.command === \"add\") {\n\t\tif (gitCommand.originalArgs.includes(\".\")) {\n\t\t\treturn verdict(\"confirm\", \"git.add_dot\", \"git add . can stage unrelated local changes.\");\n\t\t}\n\t\tif (gitCommand.originalArgs.includes(\"-A\") || gitCommand.args.includes(\"--all\")) {\n\t\t\treturn verdict(\"confirm\", \"git.add_all\", \"git add -A can stage unrelated local changes.\");\n\t\t}\n\t}\n\tif (gitCommand.command === \"commit\" && gitCommand.args.includes(\"--no-verify\")) {\n\t\treturn verdict(\"confirm\", \"git.no_verify\", \"git commit --no-verify bypasses repository verification hooks.\");\n\t}\n\tif (gitCommand.command === \"push\" && gitCommand.args.includes(\"--no-verify\")) {\n\t\treturn verdict(\"confirm\", \"git.push_no_verify\", \"git push --no-verify bypasses remote verification hooks.\");\n\t}\n\tif (\n\t\tgitCommand.command === \"push\" &&\n\t\t(gitCommand.originalArgs.includes(\"-f\") ||\n\t\t\tgitCommand.args.includes(\"--force\") ||\n\t\t\tgitCommand.args.includes(\"--force-with-lease\"))\n\t) {\n\t\treturn verdict(\"confirm\", \"git.force_push\", \"Force-pushing can rewrite remote history.\");\n\t}\n\treturn null;\n}\n\nfunction classifyPrivilegeCommand(command: string): CommandVerdict | null {\n\tconst tokens = tokenizeShellSegment(command);\n\tconst index = skipEnvironmentPrefix(tokens, 0);\n\tconst privilege = tokens[index]?.toLowerCase();\n\tif (!PRIVILEGE_COMMANDS.has(privilege ?? \"\")) return null;\n\treturn verdict(\"confirm\", `priv.${privilege}`, `${privilege} requires explicit per-command confirmation.`);\n}\n\n/**\n * Locate the inline command-string argument for a `shell -c \"<cmd>\"` invocation.\n * Returns the token index of the command string, or -1 when the shell runs a\n * script file (no inline command to classify).\n */\nfunction findShellCommandStringIndex(tokens: readonly string[]): number {\n\tfor (let index = 1; index < tokens.length; index += 1) {\n\t\tconst token = tokens[index];\n\t\tif (!token.startsWith(\"-\")) return -1;\n\t\tif (/^-[a-z]*c$/i.test(token)) {\n\t\t\treturn index + 1 < tokens.length ? index + 1 : -1;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * Locate the inline program-string argument for an interpreter invocation\n * (`python -c`, `node -e`, `perl -e`, ...). Returns the token index of the\n * program string, or -1 when the interpreter runs a script file (no inline\n * program to classify).\n */\nfunction findInterpreterInlineIndex(tokens: readonly string[], flags: readonly string[]): number {\n\tfor (let index = 1; index < tokens.length; index += 1) {\n\t\tconst token = tokens[index];\n\t\tif (token === \"--\") return -1;\n\t\tif (!token.startsWith(\"-\")) return -1;\n\t\tif (flags.includes(token) || flags.includes(token.toLowerCase())) {\n\t\t\treturn index + 1 < tokens.length ? index + 1 : -1;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/** Drop leading xargs options (and their values) to expose the wrapped command. */\nfunction stripXargsOptions(args: readonly string[]): string[] {\n\tlet index = 0;\n\twhile (index < args.length) {\n\t\tconst token = args[index];\n\t\tif (!token.startsWith(\"-\") || token === \"-\") break;\n\t\tindex += 1;\n\t\tif (token === \"--\") break;\n\t\tif (!token.includes(\"=\") && XARGS_OPTIONS_WITH_VALUE.has(token)) index += 1;\n\t}\n\treturn args.slice(index);\n}\n\n/** Extract the command tokens of a `find ... -exec <cmd> {} ;|+` clause, if present. */\nfunction extractFindExec(tokens: readonly string[]): string[] | null {\n\tfor (let index = 1; index < tokens.length; index += 1) {\n\t\tconst token = tokens[index].toLowerCase();\n\t\tif (token === \"-exec\" || token === \"-execdir\" || token === \"-ok\" || token === \"-okdir\") {\n\t\t\tconst collected: string[] = [];\n\t\t\tfor (let inner = index + 1; inner < tokens.length; inner += 1) {\n\t\t\t\tconst piece = tokens[inner];\n\t\t\t\tif (piece === \";\" || piece === \"+\") break;\n\t\t\t\tif (piece === \"{}\") continue;\n\t\t\t\tcollected.push(piece);\n\t\t\t}\n\t\t\treturn collected.length > 0 ? collected : null;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Classify the effective command hidden inside a wrapper executable so a\n * destructive or protected command cannot be smuggled past the classifier via\n * `bash -c`, `eval`, `xargs`, or `find -exec`. Returns null when the segment is\n * not a recognized wrapper.\n */\nfunction classifyWrappedCommand(command: string, depth: number): CommandVerdict | null {\n\tif (depth >= MAX_WRAP_DEPTH) return null;\n\tconst { tokens } = stripCommandPrefixes(tokenizeShellSegment(command));\n\tconst executable = tokens[0]?.toLowerCase();\n\tif (!executable) return null;\n\n\tif (SHELL_WRAPPERS.has(executable)) {\n\t\tconst innerIndex = findShellCommandStringIndex(tokens);\n\t\tconst inner = innerIndex === -1 ? undefined : tokens[innerIndex];\n\t\treturn inner ? classifyShellCommandInternal(inner, depth + 1) : null;\n\t}\n\tif (executable === \"eval\") {\n\t\tconst inner = tokens.slice(1).join(\" \").trim();\n\t\treturn inner ? classifyShellCommandInternal(inner, depth + 1) : null;\n\t}\n\tif (executable === \"xargs\") {\n\t\tconst inner = stripXargsOptions(tokens.slice(1)).join(\" \").trim();\n\t\treturn inner ? classifyShellCommandInternal(inner, depth + 1) : null;\n\t}\n\tif (executable === \"find\") {\n\t\tconst lowered = tokens.map((token) => token.toLowerCase());\n\t\tconst hasDelete = lowered.includes(\"-delete\");\n\t\tconst execTokens = extractFindExec(tokens);\n\t\tconst inner = execTokens?.join(\" \").trim();\n\t\tconst innerVerdict = inner ? classifyShellCommandInternal(inner, depth + 1) : null;\n\t\tif (hasDelete) {\n\t\t\tconst deleteVerdict = verdict(\n\t\t\t\t\"confirm\",\n\t\t\t\t\"fs.find_delete\",\n\t\t\t\t\"find -delete removes matched files and directories.\",\n\t\t\t);\n\t\t\tif (!innerVerdict || RISK_RANK[deleteVerdict.risk] > RISK_RANK[innerVerdict.risk]) {\n\t\t\t\treturn deleteVerdict;\n\t\t\t}\n\t\t}\n\t\treturn innerVerdict ?? null;\n\t}\n\tconst inlineFlags = INTERPRETER_INLINE_FLAGS[executable];\n\tif (inlineFlags) {\n\t\tconst innerIndex = findInterpreterInlineIndex(tokens, inlineFlags);\n\t\tif (innerIndex === -1) return null; // script file path — allow\n\t\tconst program = tokens[innerIndex];\n\t\tif (INLINE_DESTRUCTIVE_PATTERNS.some((pattern) => pattern.test(program))) {\n\t\t\treturn verdict(\n\t\t\t\t\"confirm\",\n\t\t\t\t`interp.${executable}_inline_destructive`,\n\t\t\t\t`${executable} inline program can execute destructive shell commands.`,\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t}\n\treturn null;\n}\n\nfunction isSearchPatternArgument(tokens: readonly string[], index: number): boolean {\n\tconst executable = tokens[0]?.toLowerCase();\n\treturn SEARCH_COMMANDS.has(executable ?? \"\") && tokens[index - 1] === \"--\";\n}\n\n/** Flag commands that read, copy, or transmit a credential / secret file path. */\nfunction classifySecretAccess(command: string): CommandVerdict | null {\n\tconst { tokens } = stripCommandPrefixes(tokenizeShellSegment(command));\n\tif (tokens.length === 0) return null;\n\tfor (let index = 1; index < tokens.length; index += 1) {\n\t\tconst token = tokens[index];\n\t\tif (!token || token.startsWith(\"-\")) continue;\n\t\tif (isSearchPatternArgument(tokens, index)) continue;\n\t\tif (/\\s/.test(token)) continue;\n\t\tif (SECRET_FILE_ALLOW_PATTERNS.some((pattern) => pattern.test(token))) continue;\n\t\tif (SECRET_FILE_STRICT_PATTERNS.some((pattern) => pattern.test(token))) {\n\t\t\treturn verdict(\"confirm\", \"secret.read_path\", \"Command references a credential or secret file path.\");\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction classifySingleCommand(command: string, depth: number): CommandVerdict {\n\tconst trimmed = command.trim();\n\tif (!trimmed) return allowVerdict();\n\n\tconst destructiveFilesystem = classifyDestructiveFilesystemCommand(trimmed);\n\tif (destructiveFilesystem) return destructiveFilesystem;\n\n\tconst wrapped = classifyWrappedCommand(trimmed, depth);\n\tif (wrapped && wrapped.risk === \"block\") return wrapped;\n\n\tconst protectedGit = classifyProtectedGitCommand(trimmed);\n\tif (protectedGit) return protectedGit;\n\n\tconst privilege = classifyPrivilegeCommand(trimmed);\n\tif (privilege) return privilege;\n\n\tconst secret = classifySecretAccess(trimmed);\n\tif (secret) return secret;\n\n\tif (wrapped && RISK_RANK[wrapped.risk] > RISK_RANK.allow) return wrapped;\n\n\treturn allowVerdict();\n}\n\nfunction classifyShellCommandInternal(command: string, depth: number): CommandVerdict {\n\tlet selected = classifySingleCommand(command, depth);\n\tfor (const segment of splitShellCommands(command)) {\n\t\tconst candidate = classifySingleCommand(segment, depth);\n\t\tif (RISK_RANK[candidate.risk] > RISK_RANK[selected.risk]) selected = candidate;\n\t\tif (selected.risk === \"block\") break;\n\t}\n\treturn selected;\n}\n\nexport function classifyShellCommand(command: string): CommandVerdict {\n\treturn classifyShellCommandInternal(command, 0);\n}\n\nexport function isDestructiveFilesystem(command: string): boolean {\n\treturn classifyDestructiveFilesystemCommand(command) !== null;\n}\n\nexport function isProtectedGitOperation(command: string): boolean {\n\treturn classifyProtectedGitCommand(command) !== null;\n}\n\nexport function isPrivilegeEscalation(command: string): boolean {\n\treturn classifyPrivilegeCommand(command) !== null;\n}\n"]}
1
+ {"version":3,"file":"command-safety.d.ts","sourceRoot":"","sources":["../../src/core/command-safety.ts"],"names":[],"mappings":"AACA,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,SAAS,GAAG,OAAO,CAAC;AAExD,MAAM,WAAW,cAAc;IAC9B,IAAI,EAAE,WAAW,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CACf;AA8nBD,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,CAEpE;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEhE;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEhE;AAED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAE9D","sourcesContent":["// allow: SIZE_OK - legacy safety rules table; this change only preserves existing typed behavior.\nexport type CommandRisk = \"block\" | \"confirm\" | \"allow\";\n\nexport interface CommandVerdict {\n\trisk: CommandRisk;\n\trule: string;\n\treason: string;\n}\n\ninterface CommandPrefixResult {\n\ttokens: string[];\n\tprivilege: string | undefined;\n}\n\nconst RISK_RANK: Readonly<Record<CommandRisk, number>> = {\n\tallow: 0,\n\tconfirm: 1,\n\tblock: 2,\n};\n\nconst PRIVILEGE_COMMANDS = new Set([\"sudo\", \"su\", \"doas\", \"pkexec\"]);\nconst SUDO_OPTIONS_WITH_VALUE = new Set([\n\t\"-C\",\n\t\"--close-from\",\n\t\"-g\",\n\t\"--group\",\n\t\"-h\",\n\t\"--host\",\n\t\"-p\",\n\t\"--prompt\",\n\t\"-T\",\n\t\"--command-timeout\",\n\t\"-u\",\n\t\"--user\",\n]);\nconst GIT_GLOBAL_OPTIONS_WITH_VALUE = new Set([\"-C\", \"-c\", \"--git-dir\", \"--work-tree\", \"--namespace\"]);\n\n/** Maximum recursion depth when unwrapping shell wrappers (bash -c, eval, xargs, find -exec). */\nconst MAX_WRAP_DEPTH = 6;\n\n/** Executables that run an inline command string passed via a `-c`-style flag. */\nconst SHELL_WRAPPERS = new Set([\"bash\", \"sh\", \"zsh\", \"dash\", \"ksh\", \"ash\"]);\n\n/**\n * Script interpreters that execute an inline program string (via a -c/-e/-r\n * style flag). Running inline code can execute arbitrary shell commands, so a\n * matched destructive/exec keyword inside the program escalates the call to\n * confirm-tier. A plain script-file path stays allow-tier.\n */\nconst INTERPRETER_INLINE_FLAGS: Readonly<Record<string, readonly string[]>> = {\n\tpython: [\"-c\"],\n\tpython2: [\"-c\"],\n\tpython3: [\"-c\"],\n\tnode: [\"-e\", \"--eval\", \"-p\", \"--print\"],\n\tperl: [\"-e\", \"-E\"],\n\truby: [\"-e\", \"-E\"],\n\tphp: [\"-r\", \"--run\"],\n\tlua: [\"-e\"],\n\texpect: [\"-c\"],\n};\n\n/**\n * Patterns that indicate an inline program invokes a shell command or\n * performs a destructive filesystem operation. Matching any of these inside\n * a `-c`/`-e`/`-r` program string escalates the call to confirm-tier.\n */\nconst INLINE_DESTRUCTIVE_PATTERNS: readonly RegExp[] = [\n\t/\\bos\\.system\\s*\\(/,\n\t/\\bos\\.remove\\s*\\(/,\n\t/\\bos\\.unlink\\s*\\(/,\n\t/\\bshutil\\.rmtree\\s*\\(/,\n\t/\\bsubprocess\\.(?:call|run|check_call|check_output|Popen)\\s*\\(/,\n\t/\\bexec(?:Sync|File)?\\s*\\(/,\n\t/\\bspawn(?:Sync)?\\s*\\(/,\n\t/\\bchild_process\\b/,\n\t/\\brequire\\s*\\(\\s*['\"]child_process['\"]\\s*\\)/,\n\t/\\b(?:system|popen)\\s*\\(/,\n\t/`[^`]*\\brm\\s+-/m,\n\t/\\$\\(\\s*[^)]*\\brm\\s+-/,\n];\n\n/** xargs options that consume a following value token before the wrapped command begins. */\nconst XARGS_OPTIONS_WITH_VALUE = new Set([\n\t\"-I\",\n\t\"-i\",\n\t\"-n\",\n\t\"-L\",\n\t\"-P\",\n\t\"-d\",\n\t\"-E\",\n\t\"-s\",\n\t\"-a\",\n\t\"--max-args\",\n\t\"--max-procs\",\n\t\"--delimiter\",\n\t\"--arg-file\",\n\t\"--max-lines\",\n\t\"--replace\",\n]);\n\n/**\n * Credential / secret file patterns. A bash argv token matching one of these is\n * treated as a `confirm`-tier access: headless callers (LLM tool calls, RPC bash)\n * deny by default, while an interactive user can still approve reading their own\n * files. These complement the §0.1 freedom safety floor, which hard-denies the\n * same paths on the entry points it guards.\n */\nconst SECRET_FILE_STRICT_PATTERNS: readonly RegExp[] = [\n\t/(^|\\/)\\.env(\\.|$)/i,\n\t/(^|\\/)\\.npmrc$/i,\n\t/(^|\\/)\\.netrc$/i,\n\t/(^|\\/)\\.pgpass$/i,\n\t/(^|\\/)\\.aws\\/credentials$/i,\n\t/(^|\\/)credentials$/i,\n\t/(^|\\/)auth\\.json$/i,\n\t/(^|\\/)id_(rsa|dsa|ecdsa|ed25519)$/i,\n\t/\\.(pem|key|p12|pfx|keystore|jks)$/i,\n\t/(^|\\/)secrets?(\\.[^/]+)?$/i,\n];\n\n/** Benign sibling files that look secret-ish but never hold credentials. */\nconst SECRET_FILE_ALLOW_PATTERNS: readonly RegExp[] = [/(^|\\/)\\.env\\.(example|sample|template|dist|defaults?)$/i];\nconst SEARCH_COMMANDS = new Set([\"grep\", \"egrep\", \"fgrep\", \"rg\"]);\nconst HOME_VARIABLE_RM_TARGETS = new Set([\"$home\", \"$\" + \"{home}\", \"$home/\", \"$\" + \"{home}/\"]);\n\nfunction verdict(risk: CommandRisk, rule: string, reason: string): CommandVerdict {\n\treturn { risk, rule, reason };\n}\n\nfunction allowVerdict(): CommandVerdict {\n\treturn verdict(\"allow\", \"command.allow\", \"No destructive or protected command pattern matched.\");\n}\n\nfunction isEnvAssignment(token: string | undefined): boolean {\n\treturn token !== undefined && /^[A-Za-z_][A-Za-z0-9_]*=.*/.test(token);\n}\n\nfunction tokenizeShellSegment(segment: string): string[] {\n\tconst tokens: string[] = [];\n\tlet current = \"\";\n\tlet quote: string | undefined;\n\tlet escaped = false;\n\n\tfor (const character of segment.trim()) {\n\t\tif (escaped) {\n\t\t\tcurrent += character;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (character === quote) {\n\t\t\t\tquote = undefined;\n\t\t\t} else {\n\t\t\t\tcurrent += character;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquote = character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/.test(character)) {\n\t\t\tif (current) {\n\t\t\t\ttokens.push(current);\n\t\t\t\tcurrent = \"\";\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += character;\n\t}\n\n\tif (escaped) current += \"\\\\\";\n\tif (current) tokens.push(current);\n\treturn tokens;\n}\n\nfunction splitShellCommands(command: string): string[] {\n\tconst segments: string[] = [];\n\tlet current = \"\";\n\tlet quote: string | undefined;\n\tlet escaped = false;\n\n\tfor (let index = 0; index < command.length; index += 1) {\n\t\tconst character = command[index];\n\t\tconst next = command[index + 1];\n\t\tif (escaped) {\n\t\t\tcurrent += character;\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\" && quote !== \"'\") {\n\t\t\tescaped = true;\n\t\t\tcurrent += character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tcurrent += character;\n\t\t\tif (character === quote) quote = undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquote = character;\n\t\t\tcurrent += character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \";\" || character === \"|\" || character === \"\\n\" || character === \"\\r\") {\n\t\t\tif (current.trim()) segments.push(current.trim());\n\t\t\tcurrent = \"\";\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"&\") {\n\t\t\tif (current.trim()) segments.push(current.trim());\n\t\t\tcurrent = \"\";\n\t\t\tif (next === \"&\") index += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += character;\n\t}\n\n\tif (current.trim()) segments.push(current.trim());\n\treturn segments;\n}\n\nfunction skipEnvironmentPrefix(tokens: readonly string[], startIndex: number): number {\n\tlet index = startIndex;\n\twhile (isEnvAssignment(tokens[index])) index += 1;\n\tif (tokens[index]?.toLowerCase() !== \"env\") return index;\n\n\tindex += 1;\n\twhile (index < tokens.length) {\n\t\tconst token = tokens[index];\n\t\tif (isEnvAssignment(token)) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (token?.startsWith(\"-\")) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treturn index;\n}\n\nfunction optionConsumesValue(option: string, optionsWithValue: ReadonlySet<string>): boolean {\n\tif (option.includes(\"=\")) return false;\n\treturn optionsWithValue.has(option);\n}\n\nfunction skipPrivilegeOptions(tokens: readonly string[], startIndex: number, privilege: string): number {\n\tif (privilege !== \"sudo\" && privilege !== \"doas\") return startIndex;\n\n\tlet index = startIndex;\n\twhile (index < tokens.length) {\n\t\tconst token = tokens[index];\n\t\tif (!token?.startsWith(\"-\")) break;\n\t\tindex += 1;\n\t\tif (token === \"--\") break;\n\t\tif (optionConsumesValue(token, SUDO_OPTIONS_WITH_VALUE)) index += 1;\n\t}\n\treturn index;\n}\n\nfunction stripCommandPrefixes(tokens: readonly string[]): CommandPrefixResult {\n\tlet index = skipEnvironmentPrefix(tokens, 0);\n\tconst privilege = tokens[index]?.toLowerCase();\n\tif (!PRIVILEGE_COMMANDS.has(privilege ?? \"\")) {\n\t\treturn { tokens: tokens.slice(index), privilege: undefined };\n\t}\n\n\tindex += 1;\n\tindex = skipPrivilegeOptions(tokens, index, privilege ?? \"\");\n\tindex = skipEnvironmentPrefix(tokens, index);\n\treturn { tokens: tokens.slice(index), privilege };\n}\n\nfunction hasForkBomb(command: string): boolean {\n\treturn command.replace(/\\s/g, \"\").includes(\":(){:|:&};:\");\n}\n\nfunction normalizePathTarget(target: string): string {\n\treturn target.replace(/\\/+$/g, (match) => (target === match ? \"/\" : \"\")).replace(/\\/+/g, \"/\");\n}\n\nfunction classifyRmTarget(target: string): CommandVerdict | null {\n\tconst normalized = normalizePathTarget(target);\n\tif (normalized === \"/\" || normalized === \"/*\" || normalized === \"/.*\") {\n\t\treturn verdict(\"block\", \"fs.rm_rf_root\", \"Recursive forced rm targets filesystem root.\");\n\t}\n\tif (normalized === \"~\" || normalized === \"~/\" || normalized === \"~/*\" || normalized === \"~/.*\") {\n\t\treturn verdict(\"block\", \"fs.rm_rf_home\", \"Recursive forced rm targets the home directory.\");\n\t}\n\t// $HOME / ${HOME} expands to the user home directory at runtime.\n\tconst lower = normalized.toLowerCase();\n\tif (HOME_VARIABLE_RM_TARGETS.has(lower)) {\n\t\treturn verdict(\n\t\t\t\"confirm\",\n\t\t\t\"fs.rm_rf_home_var\",\n\t\t\t\"Recursive forced rm targets $HOME, which expands to the user home directory.\",\n\t\t);\n\t}\n\t// ~username targets another user home directory.\n\tif (/^~[A-Za-z0-9._-]/.test(normalized)) {\n\t\treturn verdict(\"confirm\", \"fs.rm_rf_user_home\", \"Recursive forced rm targets another user home directory.\");\n\t}\n\t// \".\" or \"./\" — current working directory (project root deletion risk).\n\tif (normalized === \".\") {\n\t\treturn verdict(\"confirm\", \"fs.rm_rf_cwd\", \"Recursive forced rm targets the current working directory.\");\n\t}\n\t// \"..\" — parent directory.\n\tif (normalized === \"..\") {\n\t\treturn verdict(\"confirm\", \"fs.rm_rf_parent\", \"Recursive forced rm targets the parent directory.\");\n\t}\n\treturn null;\n}\n\nfunction classifyRm(tokens: readonly string[]): CommandVerdict | null {\n\tlet hasRecursive = false;\n\tlet hasForce = false;\n\tlet endOfOptions = false;\n\tconst targets: string[] = [];\n\n\tfor (const token of tokens.slice(1)) {\n\t\tif (!endOfOptions && token === \"--\") {\n\t\t\tendOfOptions = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!endOfOptions && token.startsWith(\"-\") && token !== \"-\") {\n\t\t\tif (token === \"--recursive\") hasRecursive = true;\n\t\t\tif (token === \"--force\") hasForce = true;\n\t\t\tif (!token.startsWith(\"--\")) {\n\t\t\t\tconst flagCharacters = token.slice(1).split(\"\");\n\t\t\t\tif (flagCharacters.some((flag) => flag === \"r\" || flag === \"R\")) hasRecursive = true;\n\t\t\t\tif (flagCharacters.includes(\"f\")) hasForce = true;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\ttargets.push(token);\n\t}\n\n\tif (!hasRecursive || !hasForce) return null;\n\tfor (const target of targets) {\n\t\tconst targetVerdict = classifyRmTarget(target);\n\t\tif (targetVerdict) return targetVerdict;\n\t}\n\treturn null;\n}\n\nfunction isBlockDeviceOutput(token: string): boolean {\n\treturn /^of=\\/dev\\/(?:sd[a-z][a-z0-9]*|nvme[0-9a-z]+|disk(?:[0-9].*|\\/.*|$))/i.test(token);\n}\n\nfunction classifyDestructiveFilesystemCommand(command: string): CommandVerdict | null {\n\tif (hasForkBomb(command)) {\n\t\treturn verdict(\"block\", \"process.fork_bomb\", \"Shell fork bomb pattern would exhaust process resources.\");\n\t}\n\n\tconst { tokens } = stripCommandPrefixes(tokenizeShellSegment(command));\n\tconst executable = tokens[0]?.toLowerCase();\n\tif (!executable) return null;\n\tif (executable === \"rm\") return classifyRm(tokens);\n\tif (executable.startsWith(\"mkfs\")) {\n\t\treturn verdict(\"block\", \"fs.mkfs\", \"Filesystem formatting commands are blocked.\");\n\t}\n\tif (executable === \"dd\" && tokens.slice(1).some(isBlockDeviceOutput)) {\n\t\treturn verdict(\"block\", \"fs.dd_block_device\", \"dd writes directly to a block-device output path.\");\n\t}\n\treturn null;\n}\n\nfunction findGitCommand(tokens: readonly string[]): { command: string; args: string[]; originalArgs: string[] } | null {\n\tif (tokens[0]?.toLowerCase() !== \"git\") return null;\n\tlet index = 1;\n\twhile (index < tokens.length && tokens[index]?.startsWith(\"-\")) {\n\t\tconst option = tokens[index];\n\t\tconst normalizedOption = option.toLowerCase();\n\t\tindex += 1;\n\t\tif (option === \"--\") break;\n\t\tif (\n\t\t\toptionConsumesValue(option, GIT_GLOBAL_OPTIONS_WITH_VALUE) ||\n\t\t\toptionConsumesValue(normalizedOption, GIT_GLOBAL_OPTIONS_WITH_VALUE)\n\t\t) {\n\t\t\tindex += 1;\n\t\t}\n\t}\n\tconst command = tokens[index]?.toLowerCase();\n\tif (!command) return null;\n\tconst originalArgs = tokens.slice(index + 1);\n\treturn {\n\t\tcommand,\n\t\targs: originalArgs.map((argument) => argument.toLowerCase()),\n\t\toriginalArgs,\n\t};\n}\n\nfunction hasGitCleanForceDirectory(args: readonly string[]): boolean {\n\tlet hasForce = false;\n\tlet hasDirectory = false;\n\tfor (const arg of args) {\n\t\tif (arg === \"--force\") hasForce = true;\n\t\tif (arg === \"-f\") hasForce = true;\n\t\tif (arg === \"-d\") hasDirectory = true;\n\t\tif (arg.startsWith(\"-\") && !arg.startsWith(\"--\")) {\n\t\t\tconst flags = arg.slice(1).split(\"\");\n\t\t\tif (flags.includes(\"f\")) hasForce = true;\n\t\t\tif (flags.includes(\"d\")) hasDirectory = true;\n\t\t}\n\t}\n\treturn hasForce && hasDirectory;\n}\n\nfunction classifyProtectedGitCommand(command: string): CommandVerdict | null {\n\tconst { tokens } = stripCommandPrefixes(tokenizeShellSegment(command));\n\tconst gitCommand = findGitCommand(tokens);\n\tif (!gitCommand) return null;\n\n\tif (gitCommand.command === \"reset\" && gitCommand.args.includes(\"--hard\")) {\n\t\treturn verdict(\"confirm\", \"git.reset_hard\", \"git reset --hard can discard worktree changes.\");\n\t}\n\tif (gitCommand.command === \"restore\") {\n\t\tconst targetAll = gitCommand.originalArgs.includes(\".\") || gitCommand.originalArgs.includes(\"*\");\n\t\tconst rewritesWorktree = gitCommand.args.includes(\"--worktree\") || gitCommand.args.includes(\"--source\");\n\t\tif (targetAll || rewritesWorktree) {\n\t\t\treturn verdict(\"confirm\", \"git.restore\", \"git restore can discard or overwrite local worktree changes.\");\n\t\t}\n\t}\n\tif (gitCommand.command === \"checkout\" && gitCommand.originalArgs.includes(\".\")) {\n\t\treturn verdict(\"confirm\", \"git.checkout_dot\", \"git checkout . can overwrite local worktree changes.\");\n\t}\n\tif (gitCommand.command === \"clean\" && hasGitCleanForceDirectory(gitCommand.args)) {\n\t\treturn verdict(\"confirm\", \"git.clean_force\", \"git clean -fd can delete untracked files and directories.\");\n\t}\n\tif (gitCommand.command === \"stash\" && gitCommand.originalArgs.length === 0) {\n\t\treturn verdict(\"confirm\", \"git.stash_bare\", \"Bare git stash can hide local worktree changes.\");\n\t}\n\tif (gitCommand.command === \"commit\" && gitCommand.args.includes(\"--no-verify\")) {\n\t\treturn verdict(\"confirm\", \"git.no_verify\", \"git commit --no-verify bypasses repository verification hooks.\");\n\t}\n\tif (gitCommand.command === \"push\" && gitCommand.args.includes(\"--no-verify\")) {\n\t\treturn verdict(\"confirm\", \"git.push_no_verify\", \"git push --no-verify bypasses remote verification hooks.\");\n\t}\n\tif (\n\t\tgitCommand.command === \"push\" &&\n\t\t(gitCommand.originalArgs.includes(\"-f\") ||\n\t\t\tgitCommand.args.includes(\"--force\") ||\n\t\t\tgitCommand.args.includes(\"--force-with-lease\"))\n\t) {\n\t\treturn verdict(\"confirm\", \"git.force_push\", \"Force-pushing can rewrite remote history.\");\n\t}\n\treturn null;\n}\n\nfunction classifyPrivilegeCommand(command: string): CommandVerdict | null {\n\tconst tokens = tokenizeShellSegment(command);\n\tconst index = skipEnvironmentPrefix(tokens, 0);\n\tconst privilege = tokens[index]?.toLowerCase();\n\tif (!PRIVILEGE_COMMANDS.has(privilege ?? \"\")) return null;\n\treturn verdict(\"confirm\", `priv.${privilege}`, `${privilege} requires explicit per-command confirmation.`);\n}\n\n/**\n * Locate the inline command-string argument for a `shell -c \"<cmd>\"` invocation.\n * Returns the token index of the command string, or -1 when the shell runs a\n * script file (no inline command to classify).\n */\nfunction findShellCommandStringIndex(tokens: readonly string[]): number {\n\tfor (let index = 1; index < tokens.length; index += 1) {\n\t\tconst token = tokens[index];\n\t\tif (!token.startsWith(\"-\")) return -1;\n\t\tif (/^-[a-z]*c$/i.test(token)) {\n\t\t\treturn index + 1 < tokens.length ? index + 1 : -1;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/**\n * Locate the inline program-string argument for an interpreter invocation\n * (`python -c`, `node -e`, `perl -e`, ...). Returns the token index of the\n * program string, or -1 when the interpreter runs a script file (no inline\n * program to classify).\n */\nfunction findInterpreterInlineIndex(tokens: readonly string[], flags: readonly string[]): number {\n\tfor (let index = 1; index < tokens.length; index += 1) {\n\t\tconst token = tokens[index];\n\t\tif (token === \"--\") return -1;\n\t\tif (!token.startsWith(\"-\")) return -1;\n\t\tif (flags.includes(token) || flags.includes(token.toLowerCase())) {\n\t\t\treturn index + 1 < tokens.length ? index + 1 : -1;\n\t\t}\n\t}\n\treturn -1;\n}\n\n/** Drop leading xargs options (and their values) to expose the wrapped command. */\nfunction stripXargsOptions(args: readonly string[]): string[] {\n\tlet index = 0;\n\twhile (index < args.length) {\n\t\tconst token = args[index];\n\t\tif (!token.startsWith(\"-\") || token === \"-\") break;\n\t\tindex += 1;\n\t\tif (token === \"--\") break;\n\t\tif (!token.includes(\"=\") && XARGS_OPTIONS_WITH_VALUE.has(token)) index += 1;\n\t}\n\treturn args.slice(index);\n}\n\n/** Extract the command tokens of a `find ... -exec <cmd> {} ;|+` clause, if present. */\nfunction extractFindExec(tokens: readonly string[]): string[] | null {\n\tfor (let index = 1; index < tokens.length; index += 1) {\n\t\tconst token = tokens[index].toLowerCase();\n\t\tif (token === \"-exec\" || token === \"-execdir\" || token === \"-ok\" || token === \"-okdir\") {\n\t\t\tconst collected: string[] = [];\n\t\t\tfor (let inner = index + 1; inner < tokens.length; inner += 1) {\n\t\t\t\tconst piece = tokens[inner];\n\t\t\t\tif (piece === \";\" || piece === \"+\") break;\n\t\t\t\tif (piece === \"{}\") continue;\n\t\t\t\tcollected.push(piece);\n\t\t\t}\n\t\t\treturn collected.length > 0 ? collected : null;\n\t\t}\n\t}\n\treturn null;\n}\n\n/**\n * Classify the effective command hidden inside a wrapper executable so a\n * destructive or protected command cannot be smuggled past the classifier via\n * `bash -c`, `eval`, `xargs`, or `find -exec`. Returns null when the segment is\n * not a recognized wrapper.\n */\nfunction classifyWrappedCommand(command: string, depth: number): CommandVerdict | null {\n\tif (depth >= MAX_WRAP_DEPTH) return null;\n\tconst { tokens } = stripCommandPrefixes(tokenizeShellSegment(command));\n\tconst executable = tokens[0]?.toLowerCase();\n\tif (!executable) return null;\n\n\tif (SHELL_WRAPPERS.has(executable)) {\n\t\tconst innerIndex = findShellCommandStringIndex(tokens);\n\t\tconst inner = innerIndex === -1 ? undefined : tokens[innerIndex];\n\t\treturn inner ? classifyShellCommandInternal(inner, depth + 1) : null;\n\t}\n\tif (executable === \"eval\") {\n\t\tconst inner = tokens.slice(1).join(\" \").trim();\n\t\treturn inner ? classifyShellCommandInternal(inner, depth + 1) : null;\n\t}\n\tif (executable === \"xargs\") {\n\t\tconst inner = stripXargsOptions(tokens.slice(1)).join(\" \").trim();\n\t\treturn inner ? classifyShellCommandInternal(inner, depth + 1) : null;\n\t}\n\tif (executable === \"find\") {\n\t\tconst lowered = tokens.map((token) => token.toLowerCase());\n\t\tconst hasDelete = lowered.includes(\"-delete\");\n\t\tconst execTokens = extractFindExec(tokens);\n\t\tconst inner = execTokens?.join(\" \").trim();\n\t\tconst innerVerdict = inner ? classifyShellCommandInternal(inner, depth + 1) : null;\n\t\tif (hasDelete) {\n\t\t\tconst deleteVerdict = verdict(\n\t\t\t\t\"confirm\",\n\t\t\t\t\"fs.find_delete\",\n\t\t\t\t\"find -delete removes matched files and directories.\",\n\t\t\t);\n\t\t\tif (!innerVerdict || RISK_RANK[deleteVerdict.risk] > RISK_RANK[innerVerdict.risk]) {\n\t\t\t\treturn deleteVerdict;\n\t\t\t}\n\t\t}\n\t\treturn innerVerdict ?? null;\n\t}\n\tconst inlineFlags = INTERPRETER_INLINE_FLAGS[executable];\n\tif (inlineFlags) {\n\t\tconst innerIndex = findInterpreterInlineIndex(tokens, inlineFlags);\n\t\tif (innerIndex === -1) return null; // script file path — allow\n\t\tconst program = tokens[innerIndex];\n\t\tif (INLINE_DESTRUCTIVE_PATTERNS.some((pattern) => pattern.test(program))) {\n\t\t\treturn verdict(\n\t\t\t\t\"confirm\",\n\t\t\t\t`interp.${executable}_inline_destructive`,\n\t\t\t\t`${executable} inline program can execute destructive shell commands.`,\n\t\t\t);\n\t\t}\n\t\treturn null;\n\t}\n\treturn null;\n}\n\nfunction isSearchPatternArgument(tokens: readonly string[], index: number): boolean {\n\tconst executable = tokens[0]?.toLowerCase();\n\treturn SEARCH_COMMANDS.has(executable ?? \"\") && tokens[index - 1] === \"--\";\n}\n\n/** Flag commands that read, copy, or transmit a credential / secret file path. */\nfunction classifySecretAccess(command: string): CommandVerdict | null {\n\tconst { tokens } = stripCommandPrefixes(tokenizeShellSegment(command));\n\tif (tokens.length === 0) return null;\n\tfor (let index = 1; index < tokens.length; index += 1) {\n\t\tconst token = tokens[index];\n\t\tif (!token || token.startsWith(\"-\")) continue;\n\t\tif (isSearchPatternArgument(tokens, index)) continue;\n\t\tif (/\\s/.test(token)) continue;\n\t\tif (SECRET_FILE_ALLOW_PATTERNS.some((pattern) => pattern.test(token))) continue;\n\t\tif (SECRET_FILE_STRICT_PATTERNS.some((pattern) => pattern.test(token))) {\n\t\t\treturn verdict(\"confirm\", \"secret.read_path\", \"Command references a credential or secret file path.\");\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction classifySingleCommand(command: string, depth: number): CommandVerdict {\n\tconst trimmed = command.trim();\n\tif (!trimmed) return allowVerdict();\n\n\tconst destructiveFilesystem = classifyDestructiveFilesystemCommand(trimmed);\n\tif (destructiveFilesystem) return destructiveFilesystem;\n\n\tconst wrapped = classifyWrappedCommand(trimmed, depth);\n\tif (wrapped && wrapped.risk === \"block\") return wrapped;\n\n\tconst protectedGit = classifyProtectedGitCommand(trimmed);\n\tif (protectedGit) return protectedGit;\n\n\tconst privilege = classifyPrivilegeCommand(trimmed);\n\tif (privilege) return privilege;\n\n\tconst secret = classifySecretAccess(trimmed);\n\tif (secret) return secret;\n\n\tif (wrapped && RISK_RANK[wrapped.risk] > RISK_RANK.allow) return wrapped;\n\n\treturn allowVerdict();\n}\n\nfunction classifyShellCommandInternal(command: string, depth: number): CommandVerdict {\n\tlet selected = classifySingleCommand(command, depth);\n\tfor (const segment of splitShellCommands(command)) {\n\t\tconst candidate = classifySingleCommand(segment, depth);\n\t\tif (RISK_RANK[candidate.risk] > RISK_RANK[selected.risk]) selected = candidate;\n\t\tif (selected.risk === \"block\") break;\n\t}\n\treturn selected;\n}\n\nexport function classifyShellCommand(command: string): CommandVerdict {\n\treturn classifyShellCommandInternal(command, 0);\n}\n\nexport function isDestructiveFilesystem(command: string): boolean {\n\treturn classifyDestructiveFilesystemCommand(command) !== null;\n}\n\nexport function isProtectedGitOperation(command: string): boolean {\n\treturn classifyProtectedGitCommand(command) !== null;\n}\n\nexport function isPrivilegeEscalation(command: string): boolean {\n\treturn classifyPrivilegeCommand(command) !== null;\n}\n"]}
@@ -412,14 +412,6 @@ function classifyProtectedGitCommand(command) {
412
412
  if (gitCommand.command === "stash" && gitCommand.originalArgs.length === 0) {
413
413
  return verdict("confirm", "git.stash_bare", "Bare git stash can hide local worktree changes.");
414
414
  }
415
- if (gitCommand.command === "add") {
416
- if (gitCommand.originalArgs.includes(".")) {
417
- return verdict("confirm", "git.add_dot", "git add . can stage unrelated local changes.");
418
- }
419
- if (gitCommand.originalArgs.includes("-A") || gitCommand.args.includes("--all")) {
420
- return verdict("confirm", "git.add_all", "git add -A can stage unrelated local changes.");
421
- }
422
- }
423
415
  if (gitCommand.command === "commit" && gitCommand.args.includes("--no-verify")) {
424
416
  return verdict("confirm", "git.no_verify", "git commit --no-verify bypasses repository verification hooks.");
425
417
  }