context-mode 1.0.169 → 2.0.0-next.6

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 (382) hide show
  1. package/.claude-plugin/marketplace.json +4 -22
  2. package/.claude-plugin/plugin.json +9 -24
  3. package/.codex-plugin/hooks.json +18 -33
  4. package/.codex-plugin/mcp.json +5 -4
  5. package/.codex-plugin/plugin.json +8 -27
  6. package/SHA256SUMS +37 -0
  7. package/claude-code/skills/ctx-doctor/SKILL.md +6 -0
  8. package/claude-code/skills/ctx-stats/SKILL.md +6 -0
  9. package/claude-code/skills/ctx-upgrade/SKILL.md +6 -0
  10. package/cli.mjs +6859 -0
  11. package/codex/skills/ctx-doctor/SKILL.md +6 -0
  12. package/codex/skills/ctx-stats/SKILL.md +6 -0
  13. package/codex/skills/ctx-upgrade/SKILL.md +6 -0
  14. package/copilot/plugin.json +14 -0
  15. package/fixtures/hook-roundtrip.json +22 -0
  16. package/gemini-extension.json +14 -0
  17. package/hook.mjs +202 -0
  18. package/hooks/claude-code.json +50 -0
  19. package/hooks/codex.json +50 -0
  20. package/hooks/copilot-cli.json +33 -0
  21. package/hooks/hooks.json +16 -111
  22. package/hooks/kiro.json +69 -0
  23. package/hooks/qwen.json +50 -0
  24. package/hooks/vscode.json +40 -0
  25. package/hooks/zcode.json +53 -0
  26. package/opencode/plugin.js +22491 -0
  27. package/package.json +32 -114
  28. package/pi/index.js +50876 -0
  29. package/pi/skills/ctx-doctor/SKILL.md +6 -0
  30. package/pi/skills/ctx-stats/SKILL.md +6 -0
  31. package/pi/skills/ctx-upgrade/SKILL.md +6 -0
  32. package/qwen-extension.json +15 -0
  33. package/run.mjs +5639 -0
  34. package/search.mjs +5639 -0
  35. package/server.mjs +48214 -0
  36. package/skills/ctx-doctor/SKILL.md +3 -19
  37. package/skills/ctx-stats/SKILL.md +3 -23
  38. package/skills/ctx-upgrade/SKILL.md +3 -28
  39. package/.openclaw-plugin/index.ts +0 -12
  40. package/.openclaw-plugin/openclaw.plugin.json +0 -38
  41. package/.openclaw-plugin/package.json +0 -28
  42. package/LICENSE +0 -94
  43. package/README.md +0 -1619
  44. package/bin/statusline.mjs +0 -378
  45. package/build/adapters/antigravity/index.d.ts +0 -51
  46. package/build/adapters/antigravity/index.js +0 -169
  47. package/build/adapters/antigravity-cli/index.d.ts +0 -51
  48. package/build/adapters/antigravity-cli/index.js +0 -342
  49. package/build/adapters/base.d.ts +0 -92
  50. package/build/adapters/base.js +0 -135
  51. package/build/adapters/claude-code/config.d.ts +0 -8
  52. package/build/adapters/claude-code/config.js +0 -8
  53. package/build/adapters/claude-code/hooks.d.ts +0 -106
  54. package/build/adapters/claude-code/hooks.js +0 -183
  55. package/build/adapters/claude-code/index.d.ts +0 -80
  56. package/build/adapters/claude-code/index.js +0 -569
  57. package/build/adapters/claude-code-base.d.ts +0 -49
  58. package/build/adapters/claude-code-base.js +0 -113
  59. package/build/adapters/client-map.d.ts +0 -10
  60. package/build/adapters/client-map.js +0 -42
  61. package/build/adapters/codex/config.d.ts +0 -8
  62. package/build/adapters/codex/config.js +0 -8
  63. package/build/adapters/codex/hooks.d.ts +0 -55
  64. package/build/adapters/codex/hooks.js +0 -64
  65. package/build/adapters/codex/index.d.ts +0 -87
  66. package/build/adapters/codex/index.js +0 -992
  67. package/build/adapters/codex/paths.d.ts +0 -1
  68. package/build/adapters/codex/paths.js +0 -12
  69. package/build/adapters/codex/usage.d.ts +0 -107
  70. package/build/adapters/codex/usage.js +0 -227
  71. package/build/adapters/copilot-base.d.ts +0 -94
  72. package/build/adapters/copilot-base.js +0 -297
  73. package/build/adapters/copilot-cli/hooks.d.ts +0 -33
  74. package/build/adapters/copilot-cli/hooks.js +0 -64
  75. package/build/adapters/copilot-cli/index.d.ts +0 -48
  76. package/build/adapters/copilot-cli/index.js +0 -341
  77. package/build/adapters/cursor/config.d.ts +0 -4
  78. package/build/adapters/cursor/config.js +0 -4
  79. package/build/adapters/cursor/hooks.d.ts +0 -55
  80. package/build/adapters/cursor/hooks.js +0 -82
  81. package/build/adapters/cursor/index.d.ts +0 -64
  82. package/build/adapters/cursor/index.js +0 -517
  83. package/build/adapters/detect.d.ts +0 -136
  84. package/build/adapters/detect.js +0 -623
  85. package/build/adapters/gemini-cli/config.d.ts +0 -8
  86. package/build/adapters/gemini-cli/config.js +0 -8
  87. package/build/adapters/gemini-cli/hooks.d.ts +0 -83
  88. package/build/adapters/gemini-cli/hooks.js +0 -115
  89. package/build/adapters/gemini-cli/index.d.ts +0 -80
  90. package/build/adapters/gemini-cli/index.js +0 -483
  91. package/build/adapters/jetbrains-copilot/config.d.ts +0 -8
  92. package/build/adapters/jetbrains-copilot/config.js +0 -8
  93. package/build/adapters/jetbrains-copilot/hooks.d.ts +0 -59
  94. package/build/adapters/jetbrains-copilot/hooks.js +0 -87
  95. package/build/adapters/jetbrains-copilot/index.d.ts +0 -31
  96. package/build/adapters/jetbrains-copilot/index.js +0 -131
  97. package/build/adapters/kimi/config.d.ts +0 -8
  98. package/build/adapters/kimi/config.js +0 -8
  99. package/build/adapters/kimi/hooks.d.ts +0 -28
  100. package/build/adapters/kimi/hooks.js +0 -34
  101. package/build/adapters/kimi/index.d.ts +0 -66
  102. package/build/adapters/kimi/index.js +0 -537
  103. package/build/adapters/kimi/paths.d.ts +0 -21
  104. package/build/adapters/kimi/paths.js +0 -52
  105. package/build/adapters/kimi/usage.d.ts +0 -82
  106. package/build/adapters/kimi/usage.js +0 -217
  107. package/build/adapters/kiro/hooks.d.ts +0 -61
  108. package/build/adapters/kiro/hooks.js +0 -94
  109. package/build/adapters/kiro/index.d.ts +0 -61
  110. package/build/adapters/kiro/index.js +0 -301
  111. package/build/adapters/omp/index.d.ts +0 -65
  112. package/build/adapters/omp/index.js +0 -182
  113. package/build/adapters/omp/plugin.d.ts +0 -81
  114. package/build/adapters/omp/plugin.js +0 -331
  115. package/build/adapters/omp/usage.d.ts +0 -49
  116. package/build/adapters/omp/usage.js +0 -110
  117. package/build/adapters/openclaw/config.d.ts +0 -8
  118. package/build/adapters/openclaw/config.js +0 -8
  119. package/build/adapters/openclaw/hooks.d.ts +0 -50
  120. package/build/adapters/openclaw/hooks.js +0 -61
  121. package/build/adapters/openclaw/index.d.ts +0 -74
  122. package/build/adapters/openclaw/index.js +0 -439
  123. package/build/adapters/openclaw/mcp-tools.d.ts +0 -54
  124. package/build/adapters/openclaw/mcp-tools.js +0 -207
  125. package/build/adapters/openclaw/plugin.d.ts +0 -141
  126. package/build/adapters/openclaw/plugin.js +0 -818
  127. package/build/adapters/openclaw/session-db.d.ts +0 -55
  128. package/build/adapters/openclaw/session-db.js +0 -88
  129. package/build/adapters/openclaw/usage.d.ts +0 -34
  130. package/build/adapters/openclaw/usage.js +0 -52
  131. package/build/adapters/openclaw/workspace-router.d.ts +0 -29
  132. package/build/adapters/openclaw/workspace-router.js +0 -64
  133. package/build/adapters/opencode/config.d.ts +0 -8
  134. package/build/adapters/opencode/config.js +0 -8
  135. package/build/adapters/opencode/hooks.d.ts +0 -38
  136. package/build/adapters/opencode/hooks.js +0 -50
  137. package/build/adapters/opencode/index.d.ts +0 -67
  138. package/build/adapters/opencode/index.js +0 -463
  139. package/build/adapters/opencode/plugin.d.ts +0 -184
  140. package/build/adapters/opencode/plugin.js +0 -558
  141. package/build/adapters/opencode/zod3tov4.d.ts +0 -1
  142. package/build/adapters/opencode/zod3tov4.js +0 -132
  143. package/build/adapters/pi/extension.d.ts +0 -81
  144. package/build/adapters/pi/extension.js +0 -861
  145. package/build/adapters/pi/index.d.ts +0 -57
  146. package/build/adapters/pi/index.js +0 -173
  147. package/build/adapters/pi/mcp-bridge.d.ts +0 -268
  148. package/build/adapters/pi/mcp-bridge.js +0 -894
  149. package/build/adapters/qwen-code/hooks.d.ts +0 -26
  150. package/build/adapters/qwen-code/hooks.js +0 -29
  151. package/build/adapters/qwen-code/index.d.ts +0 -40
  152. package/build/adapters/qwen-code/index.js +0 -361
  153. package/build/adapters/qwen-code/usage.d.ts +0 -90
  154. package/build/adapters/qwen-code/usage.js +0 -222
  155. package/build/adapters/types.d.ts +0 -360
  156. package/build/adapters/types.js +0 -118
  157. package/build/adapters/vscode-copilot/config.d.ts +0 -8
  158. package/build/adapters/vscode-copilot/config.js +0 -8
  159. package/build/adapters/vscode-copilot/hooks.d.ts +0 -71
  160. package/build/adapters/vscode-copilot/hooks.js +0 -98
  161. package/build/adapters/vscode-copilot/index.d.ts +0 -32
  162. package/build/adapters/vscode-copilot/index.js +0 -222
  163. package/build/adapters/zed/index.d.ts +0 -40
  164. package/build/adapters/zed/index.js +0 -163
  165. package/build/cli.d.ts +0 -34
  166. package/build/cli.js +0 -1827
  167. package/build/db-base.d.ts +0 -179
  168. package/build/db-base.js +0 -569
  169. package/build/executor.d.ts +0 -72
  170. package/build/executor.js +0 -678
  171. package/build/exit-classify.d.ts +0 -19
  172. package/build/exit-classify.js +0 -12
  173. package/build/fetch-cache.d.ts +0 -13
  174. package/build/fetch-cache.js +0 -15
  175. package/build/lifecycle.d.ts +0 -124
  176. package/build/lifecycle.js +0 -278
  177. package/build/runPool.d.ts +0 -36
  178. package/build/runPool.js +0 -51
  179. package/build/runtime.d.ts +0 -71
  180. package/build/runtime.js +0 -659
  181. package/build/search/auto-memory.d.ts +0 -47
  182. package/build/search/auto-memory.js +0 -170
  183. package/build/search/ctx-search-schema.d.ts +0 -90
  184. package/build/search/ctx-search-schema.js +0 -135
  185. package/build/search/flood-guard.d.ts +0 -57
  186. package/build/search/flood-guard.js +0 -80
  187. package/build/search/unified.d.ts +0 -56
  188. package/build/search/unified.js +0 -104
  189. package/build/security.d.ts +0 -206
  190. package/build/security.js +0 -780
  191. package/build/server.d.ts +0 -184
  192. package/build/server.js +0 -4563
  193. package/build/session/analytics.d.ts +0 -773
  194. package/build/session/analytics.js +0 -2420
  195. package/build/session/db.d.ts +0 -468
  196. package/build/session/db.js +0 -1308
  197. package/build/session/error-classifier.d.ts +0 -87
  198. package/build/session/error-classifier.js +0 -303
  199. package/build/session/event-emit.d.ts +0 -48
  200. package/build/session/event-emit.js +0 -101
  201. package/build/session/extract.d.ts +0 -333
  202. package/build/session/extract.js +0 -2688
  203. package/build/session/model-prices.json +0 -429
  204. package/build/session/persist-tool-calls.d.ts +0 -54
  205. package/build/session/persist-tool-calls.js +0 -105
  206. package/build/session/pricing.d.ts +0 -64
  207. package/build/session/pricing.js +0 -151
  208. package/build/session/project-attribution.d.ts +0 -73
  209. package/build/session/project-attribution.js +0 -245
  210. package/build/session/purge.d.ts +0 -138
  211. package/build/session/purge.js +0 -240
  212. package/build/session/retrieval-marker.d.ts +0 -39
  213. package/build/session/retrieval-marker.js +0 -65
  214. package/build/session/snapshot.d.ts +0 -46
  215. package/build/session/snapshot.js +0 -532
  216. package/build/store-directory.d.ts +0 -56
  217. package/build/store-directory.js +0 -254
  218. package/build/store.d.ts +0 -147
  219. package/build/store.js +0 -1714
  220. package/build/truncate.d.ts +0 -57
  221. package/build/truncate.js +0 -142
  222. package/build/types.d.ts +0 -117
  223. package/build/types.js +0 -20
  224. package/build/util/claude-config.d.ts +0 -32
  225. package/build/util/claude-config.js +0 -84
  226. package/build/util/hook-config.d.ts +0 -27
  227. package/build/util/hook-config.js +0 -76
  228. package/build/util/jsonc.d.ts +0 -14
  229. package/build/util/jsonc.js +0 -104
  230. package/build/util/plugin-cache-integrity.d.ts +0 -51
  231. package/build/util/plugin-cache-integrity.js +0 -146
  232. package/build/util/project-dir.d.ts +0 -149
  233. package/build/util/project-dir.js +0 -340
  234. package/build/util/sibling-mcp.d.ts +0 -79
  235. package/build/util/sibling-mcp.js +0 -181
  236. package/cli.bundle.mjs +0 -1236
  237. package/configs/antigravity/GEMINI.md +0 -68
  238. package/configs/antigravity/mcp_config.json +0 -7
  239. package/configs/antigravity-cli/hooks/hooks.json +0 -37
  240. package/configs/antigravity-cli/hooks.json +0 -37
  241. package/configs/antigravity-cli/mcp_config.json +0 -10
  242. package/configs/antigravity-cli/plugin.json +0 -14
  243. package/configs/antigravity-cli/rules/context-mode.md +0 -77
  244. package/configs/antigravity-cli/skills/context-mode/SKILL.md +0 -77
  245. package/configs/claude-code/CLAUDE.md +0 -91
  246. package/configs/codex/AGENTS.md +0 -99
  247. package/configs/codex/config.toml +0 -8
  248. package/configs/codex/hooks.json +0 -47
  249. package/configs/copilot-cli/.github/plugin/plugin.json +0 -23
  250. package/configs/copilot-cli/.mcp.json +0 -12
  251. package/configs/copilot-cli/README.md +0 -47
  252. package/configs/copilot-cli/hooks.json +0 -41
  253. package/configs/copilot-cli/skills/context-mode/SKILL.md +0 -38
  254. package/configs/cursor/context-mode.mdc +0 -76
  255. package/configs/cursor/hooks.json +0 -21
  256. package/configs/cursor/mcp.json +0 -7
  257. package/configs/gemini-cli/GEMINI.md +0 -88
  258. package/configs/gemini-cli/mcp.json +0 -7
  259. package/configs/gemini-cli/settings.json +0 -60
  260. package/configs/jetbrains-copilot/copilot-instructions.md +0 -80
  261. package/configs/jetbrains-copilot/hooks.json +0 -16
  262. package/configs/jetbrains-copilot/mcp.json +0 -7
  263. package/configs/kilo/AGENTS.md +0 -84
  264. package/configs/kilo/kilo.json +0 -6
  265. package/configs/kimi/hooks.json +0 -54
  266. package/configs/kiro/KIRO.md +0 -84
  267. package/configs/kiro/agent.json +0 -18
  268. package/configs/kiro/mcp.json +0 -7
  269. package/configs/omp/SYSTEM.md +0 -85
  270. package/configs/omp/mcp.json +0 -7
  271. package/configs/openclaw/AGENTS.md +0 -87
  272. package/configs/openclaw/openclaw.json +0 -13
  273. package/configs/opencode/AGENTS.md +0 -84
  274. package/configs/opencode/opencode.json +0 -6
  275. package/configs/pi/AGENTS.md +0 -3
  276. package/configs/qwen-code/QWEN.md +0 -91
  277. package/configs/vscode-copilot/copilot-instructions.md +0 -80
  278. package/configs/vscode-copilot/hooks.json +0 -16
  279. package/configs/vscode-copilot/mcp.json +0 -7
  280. package/configs/zed/AGENTS.md +0 -68
  281. package/hooks/antigravity-cli/payload.mjs +0 -98
  282. package/hooks/antigravity-cli/posttooluse.mjs +0 -138
  283. package/hooks/antigravity-cli/pretooluse.mjs +0 -78
  284. package/hooks/antigravity-cli/stop.mjs +0 -58
  285. package/hooks/auto-injection.mjs +0 -102
  286. package/hooks/cache-heal-utils.mjs +0 -379
  287. package/hooks/codex/platform.mjs +0 -1
  288. package/hooks/codex/posttooluse.mjs +0 -66
  289. package/hooks/codex/precompact.mjs +0 -70
  290. package/hooks/codex/pretooluse.mjs +0 -42
  291. package/hooks/codex/sessionstart.mjs +0 -121
  292. package/hooks/codex/stop.mjs +0 -138
  293. package/hooks/codex/userpromptsubmit.mjs +0 -75
  294. package/hooks/copilot-cli/posttooluse.mjs +0 -79
  295. package/hooks/copilot-cli/precompact.mjs +0 -66
  296. package/hooks/copilot-cli/pretooluse.mjs +0 -41
  297. package/hooks/copilot-cli/sessionstart.mjs +0 -121
  298. package/hooks/copilot-cli/stop.mjs +0 -59
  299. package/hooks/copilot-cli/userpromptsubmit.mjs +0 -77
  300. package/hooks/core/codex-caps.mjs +0 -112
  301. package/hooks/core/formatters.mjs +0 -356
  302. package/hooks/core/mcp-ready.mjs +0 -109
  303. package/hooks/core/platform-detect.mjs +0 -49
  304. package/hooks/core/routing.mjs +0 -1017
  305. package/hooks/core/stdin.mjs +0 -90
  306. package/hooks/core/tool-naming.mjs +0 -57
  307. package/hooks/cursor/afteragentresponse.mjs +0 -74
  308. package/hooks/cursor/hooks.json +0 -31
  309. package/hooks/cursor/posttooluse.mjs +0 -72
  310. package/hooks/cursor/pretooluse.mjs +0 -26
  311. package/hooks/cursor/sessionstart.mjs +0 -97
  312. package/hooks/cursor/stop.mjs +0 -48
  313. package/hooks/ensure-deps.mjs +0 -254
  314. package/hooks/formatters/claude-code.mjs +0 -113
  315. package/hooks/formatters/cursor.mjs +0 -37
  316. package/hooks/formatters/gemini-cli.mjs +0 -55
  317. package/hooks/formatters/vscode-copilot.mjs +0 -55
  318. package/hooks/gemini-cli/aftermodel.mjs +0 -70
  319. package/hooks/gemini-cli/aftertool.mjs +0 -61
  320. package/hooks/gemini-cli/beforeagent.mjs +0 -99
  321. package/hooks/gemini-cli/beforetool.mjs +0 -27
  322. package/hooks/gemini-cli/precompress.mjs +0 -55
  323. package/hooks/gemini-cli/sessionstart.mjs +0 -137
  324. package/hooks/heal-partial-install.mjs +0 -712
  325. package/hooks/jetbrains-copilot/posttooluse.mjs +0 -61
  326. package/hooks/jetbrains-copilot/precompact.mjs +0 -55
  327. package/hooks/jetbrains-copilot/pretooluse.mjs +0 -27
  328. package/hooks/jetbrains-copilot/sessionstart.mjs +0 -124
  329. package/hooks/kimi/platform.mjs +0 -1
  330. package/hooks/kimi/posttooluse.mjs +0 -72
  331. package/hooks/kimi/precompact.mjs +0 -80
  332. package/hooks/kimi/pretooluse.mjs +0 -42
  333. package/hooks/kimi/sessionend.mjs +0 -61
  334. package/hooks/kimi/sessionstart.mjs +0 -113
  335. package/hooks/kimi/stop.mjs +0 -132
  336. package/hooks/kimi/userpromptsubmit.mjs +0 -90
  337. package/hooks/kiro/agentspawn.mjs +0 -97
  338. package/hooks/kiro/posttooluse.mjs +0 -51
  339. package/hooks/kiro/pretooluse.mjs +0 -64
  340. package/hooks/kiro/userpromptsubmit.mjs +0 -88
  341. package/hooks/normalize-hooks.mjs +0 -323
  342. package/hooks/platform-bridge.mjs +0 -340
  343. package/hooks/posttooluse.mjs +0 -225
  344. package/hooks/precompact.mjs +0 -100
  345. package/hooks/pretooluse.mjs +0 -227
  346. package/hooks/qwen-code/platform.mjs +0 -1
  347. package/hooks/qwen-code/stop.mjs +0 -168
  348. package/hooks/routing-block.mjs +0 -105
  349. package/hooks/run-hook.mjs +0 -95
  350. package/hooks/security.bundle.mjs +0 -2
  351. package/hooks/session-attribution.bundle.mjs +0 -1
  352. package/hooks/session-db.bundle.mjs +0 -144
  353. package/hooks/session-directive.mjs +0 -520
  354. package/hooks/session-extract.bundle.mjs +0 -3
  355. package/hooks/session-helpers.mjs +0 -428
  356. package/hooks/session-loaders.mjs +0 -448
  357. package/hooks/session-snapshot.bundle.mjs +0 -32
  358. package/hooks/sessionstart.mjs +0 -464
  359. package/hooks/stop.mjs +0 -82
  360. package/hooks/suppress-stderr.mjs +0 -25
  361. package/hooks/userpromptsubmit.mjs +0 -108
  362. package/hooks/vscode-copilot/posttooluse.mjs +0 -61
  363. package/hooks/vscode-copilot/precompact.mjs +0 -55
  364. package/hooks/vscode-copilot/pretooluse.mjs +0 -27
  365. package/hooks/vscode-copilot/sessionstart.mjs +0 -129
  366. package/openclaw.plugin.json +0 -38
  367. package/scripts/heal-better-sqlite3.mjs +0 -430
  368. package/scripts/heal-installed-plugins.mjs +0 -598
  369. package/scripts/plugin-cache-integrity.mjs +0 -248
  370. package/scripts/postinstall.mjs +0 -384
  371. package/server.bundle.mjs +0 -1162
  372. package/skills/.ignore +0 -7
  373. package/skills/context-mode/SKILL.md +0 -300
  374. package/skills/context-mode/references/anti-patterns.md +0 -283
  375. package/skills/context-mode/references/patterns-javascript.md +0 -298
  376. package/skills/context-mode/references/patterns-python.md +0 -304
  377. package/skills/context-mode/references/patterns-shell.md +0 -277
  378. package/skills/ctx-index/SKILL.md +0 -46
  379. package/skills/ctx-insight/SKILL.md +0 -24
  380. package/skills/ctx-purge/SKILL.md +0 -49
  381. package/skills/ctx-search/SKILL.md +0 -35
  382. package/start.mjs +0 -616
package/build/security.js DELETED
@@ -1,780 +0,0 @@
1
- import { readFileSync, realpathSync } from "node:fs";
2
- import { relative, resolve, sep } from "node:path";
3
- import { resolveAdapterGlobalSettingsPaths } from "./util/claude-config.js";
4
- // ==============================================================================
5
- // Pattern Parsing
6
- // ==============================================================================
7
- /**
8
- * Extract the glob from a Bash permission pattern.
9
- * "Bash(sudo *)" returns "sudo *", "Read(.env)" returns null.
10
- */
11
- export function parseBashPattern(pattern) {
12
- // .+ is greedy: for "Bash(echo (foo))" it captures "echo (foo)"
13
- // because $ forces the final \) to match only the last paren.
14
- const match = pattern.match(/^Bash\((.+)\)$/);
15
- return match ? match[1] : null;
16
- }
17
- /**
18
- * Parse any tool permission pattern like "ToolName(glob)".
19
- * Returns { tool, glob } or null if not a valid pattern.
20
- */
21
- export function parseToolPattern(pattern) {
22
- // .+ is greedy: for "Read(some(path))" it captures "some(path)"
23
- // because $ forces the final \) to match only the last paren.
24
- const match = pattern.match(/^(\w+)\((.+)\)$/);
25
- return match ? { tool: match[1], glob: match[2] } : null;
26
- }
27
- // ==============================================================================
28
- // Glob-to-Regex Conversion
29
- // ==============================================================================
30
- /** Escape all regex special characters (including *). */
31
- function escapeRegex(str) {
32
- return str.replace(/[.*+?^${}()|[\]\\\/\-]/g, "\\$&");
33
- }
34
- /** Escape regex specials except *, then convert * to .* */
35
- function convertGlobPart(glob) {
36
- return glob
37
- .replace(/[.+?^${}()|[\]\\\/\-]/g, "\\$&")
38
- .replace(/\*/g, ".*");
39
- }
40
- /**
41
- * Convert a Bash permission glob to a regex.
42
- *
43
- * Two formats:
44
- * - Colon: "tree:*" becomes /^tree(\s.*)?$/ (command with optional args)
45
- * - Space: "sudo *" becomes /^sudo .*$/ (literal glob match)
46
- */
47
- export function globToRegex(glob, caseInsensitive = false) {
48
- let regexStr;
49
- const colonIdx = glob.indexOf(":");
50
- if (colonIdx !== -1) {
51
- // Colon format: "command:argsGlob"
52
- const command = glob.slice(0, colonIdx);
53
- const argsGlob = glob.slice(colonIdx + 1);
54
- const escapedCmd = escapeRegex(command);
55
- const argsRegex = convertGlobPart(argsGlob);
56
- // Match command alone OR command + space + args
57
- regexStr = `^${escapedCmd}(\\s${argsRegex})?$`;
58
- }
59
- else {
60
- // Plain glob: "sudo *", "ls*", "* commit *"
61
- regexStr = `^${convertGlobPart(glob)}$`;
62
- }
63
- return new RegExp(regexStr, caseInsensitive ? "i" : "");
64
- }
65
- /**
66
- * Convert a file path glob to a regex.
67
- *
68
- * Unlike `globToRegex` (which handles command patterns with colon and
69
- * space semantics), this handles file path globs where:
70
- * - `**` matches any number of path segments (including zero)
71
- * - `*` matches anything except path separators
72
- * - Paths are matched with forward slashes (callers normalize first)
73
- */
74
- export function fileGlobToRegex(glob, caseInsensitive = false) {
75
- let regexStr = "";
76
- let i = 0;
77
- while (i < glob.length) {
78
- // Handle ** (globstar): match any number of directory segments
79
- if (glob[i] === "*" && glob[i + 1] === "*") {
80
- // **/ at the start or after a slash means "zero or more directories"
81
- if (i + 2 < glob.length && glob[i + 2] === "/") {
82
- regexStr += "(.*/)?";
83
- i += 3; // skip "*" "*" "/"
84
- }
85
- else {
86
- // Trailing ** matches everything
87
- regexStr += ".*";
88
- i += 2;
89
- }
90
- }
91
- else if (glob[i] === "*") {
92
- // Single * matches anything except /
93
- regexStr += "[^/]*";
94
- i++;
95
- }
96
- else if (glob[i] === "?") {
97
- regexStr += "[^/]";
98
- i++;
99
- }
100
- else {
101
- // Escape regex-special characters
102
- regexStr += glob[i].replace(/[.+^${}()|[\]\\\/\-]/g, "\\$&");
103
- i++;
104
- }
105
- }
106
- return new RegExp(`^${regexStr}$`, caseInsensitive ? "i" : "");
107
- }
108
- /**
109
- * Check if a command matches any Bash pattern in the list.
110
- * Returns the matching pattern string, or null.
111
- */
112
- export function matchesAnyPattern(command, patterns, caseInsensitive = false) {
113
- for (const pattern of patterns) {
114
- const glob = parseBashPattern(pattern);
115
- if (!glob)
116
- continue;
117
- if (globToRegex(glob, caseInsensitive).test(command))
118
- return pattern;
119
- }
120
- return null;
121
- }
122
- // ==============================================================================
123
- // Chained Command Splitting & Subshell Extraction
124
- // ==============================================================================
125
- function isEscaped(command, index) {
126
- let backslashes = 0;
127
- for (let i = index - 1; i >= 0 && command[i] === "\\"; i--) {
128
- backslashes++;
129
- }
130
- return backslashes % 2 === 1;
131
- }
132
- /**
133
- * Split a shell command on chain operators (&&, ||, ;, |, \n, \r, &) while
134
- * respecting single/double quotes, backticks, subshells, and escape backslashes.
135
- *
136
- * "echo hello && sudo rm -rf /" → ["echo hello", "sudo rm -rf /"]
137
- *
138
- * This prevents bypassing deny patterns by prepending innocent commands.
139
- */
140
- export function splitChainedCommands(command) {
141
- const parts = [];
142
- let current = "";
143
- let inSingle = false;
144
- let inDouble = false;
145
- let inBacktick = false;
146
- let dollarParenDepth = 0;
147
- for (let i = 0; i < command.length; i++) {
148
- const ch = command[i];
149
- const escaped = isEscaped(command, i);
150
- if (ch === "'" && !inDouble && !inBacktick && !escaped) {
151
- inSingle = !inSingle;
152
- current += ch;
153
- }
154
- else if (ch === '"' && !inSingle && !inBacktick && !escaped) {
155
- inDouble = !inDouble;
156
- current += ch;
157
- }
158
- else if (ch === "`" && !inSingle && !inDouble && !escaped) {
159
- inBacktick = !inBacktick;
160
- current += ch;
161
- }
162
- else if (!inSingle && !inDouble && !inBacktick) {
163
- if (ch === "$" && command[i + 1] === "(" && !escaped) {
164
- dollarParenDepth++;
165
- current += ch + command[i + 1];
166
- i++;
167
- }
168
- else if (dollarParenDepth > 0 && ch === "(" && !escaped) {
169
- dollarParenDepth++;
170
- current += ch;
171
- }
172
- else if (ch === ")" && dollarParenDepth > 0 && !escaped) {
173
- dollarParenDepth--;
174
- current += ch;
175
- }
176
- else if (dollarParenDepth === 0 &&
177
- (ch === ";" || ch === "\n" || ch === "\r") &&
178
- !escaped) {
179
- parts.push(current.trim());
180
- current = "";
181
- }
182
- else if (dollarParenDepth === 0 && ch === "|" && command[i + 1] === "|") {
183
- parts.push(current.trim());
184
- current = "";
185
- i++; // skip second |
186
- }
187
- else if (dollarParenDepth === 0 && ch === "&" && command[i + 1] === "&") {
188
- parts.push(current.trim());
189
- current = "";
190
- i++; // skip second &
191
- }
192
- else if (dollarParenDepth === 0 && ch === "&" && !escaped) {
193
- parts.push(current.trim());
194
- current = "";
195
- }
196
- else if (dollarParenDepth === 0 && ch === "|") {
197
- // Single pipe — left side is a command too
198
- parts.push(current.trim());
199
- current = "";
200
- }
201
- else {
202
- current += ch;
203
- }
204
- }
205
- else {
206
- current += ch;
207
- }
208
- }
209
- if (current.trim())
210
- parts.push(current.trim());
211
- return parts.filter((p) => p.length > 0);
212
- }
213
- /**
214
- * Recursively extract all nested subshell commands from `$()` and `` `...` ``.
215
- * Handles escaping and quote contexts to ensure correct command boundary detection.
216
- */
217
- export function extractSubshellCommands(command) {
218
- const subshells = [];
219
- let inSingle = false;
220
- let inDouble = false;
221
- let backtickStart = -1;
222
- const dollarParenStarts = [];
223
- const dollarParenDepths = [];
224
- let parenDepth = 0;
225
- for (let i = 0; i < command.length; i++) {
226
- const ch = command[i];
227
- const escaped = isEscaped(command, i);
228
- if (ch === "'" && !inDouble && backtickStart === -1 && !escaped) {
229
- inSingle = !inSingle;
230
- }
231
- else if (ch === '"' && !inSingle && backtickStart === -1 && !escaped) {
232
- inDouble = !inDouble;
233
- }
234
- else if (ch === "`" && !inSingle && !inDouble && !escaped) {
235
- if (backtickStart === -1) {
236
- backtickStart = i + 1;
237
- }
238
- else {
239
- const sub = command.slice(backtickStart, i);
240
- subshells.push(sub);
241
- subshells.push(...extractSubshellCommands(sub));
242
- backtickStart = -1;
243
- }
244
- }
245
- else if (!inSingle && backtickStart === -1) {
246
- if (ch === "$" && command[i + 1] === "(" && !escaped) {
247
- if (command[i + 2] === "(") {
248
- // Arithmetic expansion is not command execution, but nested command
249
- // substitutions inside it still get discovered by the scanner.
250
- parenDepth += 2;
251
- i += 2; // skip '(('
252
- }
253
- else {
254
- dollarParenStarts.push(i + 2);
255
- dollarParenDepths.push(parenDepth);
256
- parenDepth++;
257
- i++; // skip '('
258
- }
259
- }
260
- else if (ch === "(" && !escaped) {
261
- parenDepth++;
262
- }
263
- else if (ch === ")" && !escaped) {
264
- if (parenDepth > 0) {
265
- parenDepth--;
266
- }
267
- if (dollarParenDepths.length > 0 &&
268
- parenDepth === dollarParenDepths[dollarParenDepths.length - 1]) {
269
- dollarParenDepths.pop();
270
- const start = dollarParenStarts.pop();
271
- const sub = command.slice(start, i);
272
- subshells.push(sub);
273
- }
274
- }
275
- }
276
- }
277
- return subshells;
278
- }
279
- function collectCommandElements(command) {
280
- const elements = [];
281
- const segments = splitChainedCommands(command);
282
- for (const segment of segments) {
283
- elements.push(segment);
284
- for (const subshell of extractSubshellCommands(segment)) {
285
- elements.push(...collectCommandElements(subshell));
286
- }
287
- }
288
- return elements;
289
- }
290
- // ==============================================================================
291
- // Settings Reader
292
- // ==============================================================================
293
- /** Read one settings file and return a SecurityPolicy with only Bash patterns. */
294
- function readSingleSettings(path) {
295
- let raw;
296
- try {
297
- raw = readFileSync(path, "utf-8");
298
- }
299
- catch {
300
- return null;
301
- }
302
- let parsed;
303
- try {
304
- parsed = JSON.parse(raw);
305
- }
306
- catch {
307
- return null;
308
- }
309
- const perms = parsed?.permissions;
310
- if (!perms || typeof perms !== "object")
311
- return null;
312
- const filterBash = (arr) => {
313
- if (!Array.isArray(arr))
314
- return [];
315
- return arr.filter((p) => typeof p === "string" && parseBashPattern(p) !== null);
316
- };
317
- return {
318
- allow: filterBash(perms.allow),
319
- deny: filterBash(perms.deny),
320
- ask: filterBash(perms.ask),
321
- };
322
- }
323
- /**
324
- * Read Bash permission policies from up to 3 settings files.
325
- *
326
- * Returns policies in precedence order (most local first):
327
- * 1. .claude/settings.local.json (project-local)
328
- * 2. .claude/settings.json (project-shared)
329
- * 3. ~/.claude/settings.json (global)
330
- *
331
- * Missing or invalid files are silently skipped.
332
- */
333
- export function readBashPolicies(projectDir, globalSettingsPath) {
334
- const policies = [];
335
- if (projectDir) {
336
- const localPath = resolve(projectDir, ".claude", "settings.local.json");
337
- const localPolicy = readSingleSettings(localPath);
338
- if (localPolicy)
339
- policies.push(localPolicy);
340
- const sharedPath = resolve(projectDir, ".claude", "settings.json");
341
- const sharedPolicy = readSingleSettings(sharedPath);
342
- if (sharedPolicy)
343
- policies.push(sharedPolicy);
344
- }
345
- // Issue #451 round-3: read settings from EVERY adapter-specific global path
346
- // PLUS the claude global (defense in depth). When the caller passes an
347
- // explicit globalSettingsPath we honor it verbatim (back-compat with tests
348
- // and callers that already know which file to read).
349
- const globalPaths = globalSettingsPath !== undefined
350
- ? [globalSettingsPath]
351
- : resolveAdapterGlobalSettingsPaths();
352
- for (const globalPath of globalPaths) {
353
- const globalPolicy = readSingleSettings(globalPath);
354
- if (globalPolicy)
355
- policies.push(globalPolicy);
356
- }
357
- return policies;
358
- }
359
- /**
360
- * Read deny patterns for a specific tool from settings files.
361
- *
362
- * Reads the same 3-tier settings as `readBashPolicies`, but extracts
363
- * only deny globs for the given tool. Used for Read and Grep enforcement
364
- * — checks if file paths should be blocked by deny patterns.
365
- *
366
- * Returns an array of arrays (one per settings file, in precedence order).
367
- * Each inner array contains the extracted glob strings.
368
- */
369
- export function readToolDenyPatterns(toolName, projectDir, globalSettingsPath) {
370
- return readToolPermissionPatterns(toolName, "deny", projectDir, globalSettingsPath);
371
- }
372
- /**
373
- * Read `permissions.{deny|allow}` globs for a tool from every settings file in
374
- * precedence order (project local → project shared → adapter globals).
375
- *
376
- * Generalizes the original deny-only reader so the project-boundary guard
377
- * (#852) can consult the SAME `permissions.allow` rules the user already
378
- * maintains for the host's `Read` tool — instead of inventing a context-mode-
379
- * specific opt-out env that would rot into dead code. A user who legitimately
380
- * needs an out-of-project read expresses it once, in the host config, e.g.
381
- * `"permissions": { "allow": ["Read(/var/log/**)"] }`, and both the host and
382
- * context-mode honor it.
383
- */
384
- export function readToolPermissionPatterns(toolName, kind, projectDir, globalSettingsPath) {
385
- const result = [];
386
- const extractGlobs = (path) => {
387
- let raw;
388
- try {
389
- raw = readFileSync(path, "utf-8");
390
- }
391
- catch {
392
- return null;
393
- }
394
- let parsed;
395
- try {
396
- parsed = JSON.parse(raw);
397
- }
398
- catch {
399
- return null;
400
- }
401
- const entries = parsed?.permissions?.[kind];
402
- if (!Array.isArray(entries))
403
- return [];
404
- const globs = [];
405
- for (const entry of entries) {
406
- if (typeof entry !== "string")
407
- continue;
408
- const tp = parseToolPattern(entry);
409
- if (tp && tp.tool === toolName) {
410
- globs.push(tp.glob);
411
- }
412
- }
413
- return globs;
414
- };
415
- if (projectDir) {
416
- const localGlobs = extractGlobs(resolve(projectDir, ".claude", "settings.local.json"));
417
- if (localGlobs !== null)
418
- result.push(localGlobs);
419
- const sharedGlobs = extractGlobs(resolve(projectDir, ".claude", "settings.json"));
420
- if (sharedGlobs !== null)
421
- result.push(sharedGlobs);
422
- }
423
- // Issue #451 round-3: union over every adapter-specific global path PLUS
424
- // claude global. Each settings file contributes its own globs array entry
425
- // so the precedence ordering downstream remains per-file rather than
426
- // collapsed.
427
- const globalPaths = globalSettingsPath !== undefined
428
- ? [globalSettingsPath]
429
- : resolveAdapterGlobalSettingsPaths();
430
- for (const globalPath of globalPaths) {
431
- const globalGlobs = extractGlobs(globalPath);
432
- if (globalGlobs !== null)
433
- result.push(globalGlobs);
434
- }
435
- return result;
436
- }
437
- /**
438
- * Evaluate a command against policies in precedence order.
439
- *
440
- * Splits chained commands (&&, ||, ;, |) and checks each segment
441
- * against deny patterns — prevents bypassing deny by prepending
442
- * innocent commands like "echo ok && sudo rm -rf /".
443
- *
444
- * Within each policy: deny > ask > allow (most restrictive wins).
445
- * First definitive match across policies wins.
446
- * Default (no match in any policy): "ask".
447
- */
448
- export function evaluateCommand(command, policies, caseInsensitive = process.platform === "win32" || process.platform === "darwin") {
449
- // Extract all main segments and nested subshell commands
450
- const allCommands = collectCommandElements(command);
451
- // 1. Deny check: If ANY segment or subshell command is denied, block the entire command
452
- for (const cmdElement of allCommands) {
453
- for (const policy of policies) {
454
- const denyMatch = matchesAnyPattern(cmdElement, policy.deny, caseInsensitive);
455
- if (denyMatch)
456
- return { decision: "deny", matchedPattern: denyMatch };
457
- }
458
- }
459
- // 2. Allow/Ask check: Evaluate segment-by-segment in precedence order.
460
- // The command is allowed if and only if EVERY segment and subshell is explicitly allowed.
461
- // If any element matches an ask pattern or matches no allow pattern, it defaults to ask.
462
- for (const policy of policies) {
463
- let allAllowed = true;
464
- let anyAsk = false;
465
- let matchedAskPattern;
466
- let matchedAllowPattern;
467
- for (const cmdElement of allCommands) {
468
- const askMatch = matchesAnyPattern(cmdElement, policy.ask, caseInsensitive);
469
- if (askMatch) {
470
- anyAsk = true;
471
- matchedAskPattern = askMatch;
472
- break; // Ask wins immediately within this policy
473
- }
474
- const allowMatch = matchesAnyPattern(cmdElement, policy.allow, caseInsensitive);
475
- if (!allowMatch) {
476
- allAllowed = false;
477
- }
478
- else {
479
- matchedAllowPattern = allowMatch;
480
- }
481
- }
482
- if (anyAsk) {
483
- return { decision: "ask", matchedPattern: matchedAskPattern };
484
- }
485
- if (allAllowed && allCommands.length > 0) {
486
- return { decision: "allow", matchedPattern: matchedAllowPattern };
487
- }
488
- }
489
- return { decision: "ask" };
490
- }
491
- /**
492
- * Server-side variant: only enforce deny patterns.
493
- *
494
- * The server has no UI for "ask" prompts, so allow/ask patterns are
495
- * irrelevant. Returns "deny" if any deny pattern matches, otherwise "allow".
496
- *
497
- * Also splits chained commands and nested subshells to prevent bypass.
498
- */
499
- export function evaluateCommandDenyOnly(command, policies, caseInsensitive = process.platform === "win32" || process.platform === "darwin") {
500
- const allCommands = collectCommandElements(command);
501
- for (const cmdElement of allCommands) {
502
- for (const policy of policies) {
503
- const denyMatch = matchesAnyPattern(cmdElement, policy.deny, caseInsensitive);
504
- if (denyMatch)
505
- return { decision: "deny", matchedPattern: denyMatch };
506
- }
507
- }
508
- return { decision: "allow" };
509
- }
510
- // ==============================================================================
511
- // File Path Evaluation
512
- // ==============================================================================
513
- /**
514
- * Check if a file path should be denied based on deny globs.
515
- *
516
- * Normalizes backslashes to forward slashes before matching so that
517
- * Windows paths work with Unix-style glob patterns.
518
- *
519
- * When `projectRoot` is supplied, the path is also matched in its
520
- * fully-resolved absolute form **and** — when the file exists — in
521
- * its canonical form (`fs.realpathSync`). This prevents two classes
522
- * of bypass:
523
- *
524
- * 1. `..` traversal: a relative path like `../../.ssh/id_rsa` no
525
- * longer evades absolute-path deny rules.
526
- * 2. Symlink escape: a project-local path whose realpath points
527
- * outside the project (e.g. `safe.log -> ~/.ssh/id_rsa`) no
528
- * longer evades absolute-path deny rules.
529
- *
530
- * realpath is best-effort: if the file does not exist yet (ENOENT)
531
- * or the syscall fails for any reason, the lexical resolved form is
532
- * still checked. This keeps the function usable for paths that will
533
- * be created during execution.
534
- */
535
- export function evaluateFilePath(filePath, denyGlobs, caseInsensitive = process.platform === "win32" || process.platform === "darwin", projectRoot) {
536
- const toForward = (path) => path.replace(/\\/g, "/");
537
- // Match against the raw input, the lexically-resolved absolute path,
538
- // and the canonical (symlink-resolved) path when the file exists.
539
- // Deduplicated so absolute inputs and paths that don't cross symlinks
540
- // don't pay the matching cost multiple times.
541
- const candidates = new Set();
542
- candidates.add(toForward(filePath));
543
- if (projectRoot) {
544
- const lexical = resolve(projectRoot, filePath);
545
- candidates.add(toForward(lexical));
546
- try {
547
- candidates.add(toForward(realpathSync(lexical)));
548
- }
549
- catch {
550
- // File does not exist yet, or realpath failed — rely on lexical form.
551
- }
552
- }
553
- for (const globs of denyGlobs) {
554
- for (const glob of globs) {
555
- // Normalize the glob's path separators the same way candidates were
556
- // normalized — otherwise a Windows absolute deny rule like
557
- // `Read(C:\Users\...\secret.env)` parses with literal backslashes that
558
- // never match a forward-slash candidate.
559
- const regex = fileGlobToRegex(toForward(glob), caseInsensitive);
560
- for (const candidate of candidates) {
561
- if (regex.test(candidate)) {
562
- return { denied: true, matchedPattern: glob };
563
- }
564
- }
565
- }
566
- }
567
- return { denied: false };
568
- }
569
- // ==============================================================================
570
- // Project-Boundary Containment (Issue #852)
571
- // ==============================================================================
572
- /**
573
- * Pure, algorithmic (no-regex) test: does `filePath` resolve to a location
574
- * inside `projectRoot`?
575
- *
576
- * Issue #852 — `ctx_execute_file` previously fed its `path` argument straight
577
- * into `resolve(projectRoot, path)`. Because `path.resolve` lets an *absolute*
578
- * argument win outright, an agent could read any file on the host
579
- * (`/home/user/secret`, `/etc/passwd`) regardless of the project root, and
580
- * `../` traversal escaped just as easily. Claude Code's harness sandbox cannot
581
- * inspect MCP input params, so the user approving the MCP call could not see
582
- * that the path escaped the workspace. This guard re-anchors the path to the
583
- * project boundary.
584
- *
585
- * Containment is decided on the *resolved* form. When the file (or its parent
586
- * chain) exists, the symlink-canonical form is ALSO required to stay inside —
587
- * this closes the symlink-escape class (a project-local `safe.log` whose
588
- * realpath points at `~/.ssh/id_rsa`), mirroring `evaluateFilePath`.
589
- *
590
- * A path equal to the project root itself counts as inside. Comparison is
591
- * case-insensitive on Windows/macOS to match those filesystems' semantics.
592
- *
593
- * Returns `true` when `projectRoot` is falsy (no boundary to enforce) so the
594
- * caller's fail-open posture is preserved when the root cannot be resolved.
595
- */
596
- export function isPathInsideProject(filePath, projectRoot, caseInsensitive = process.platform === "win32" || process.platform === "darwin") {
597
- if (!projectRoot)
598
- return true;
599
- const root = resolve(projectRoot);
600
- const lexical = resolve(projectRoot, filePath);
601
- const within = (root, candidate) => {
602
- let a = root;
603
- let b = candidate;
604
- if (caseInsensitive) {
605
- a = a.toLowerCase();
606
- b = b.toLowerCase();
607
- }
608
- if (a === b)
609
- return true;
610
- // `path.relative` is pure string arithmetic — no regex. A candidate inside
611
- // the root yields a relative path that neither starts with `..` (escapes
612
- // upward) nor is absolute (a different drive/root on Windows that cannot be
613
- // expressed relatively).
614
- const rel = relative(a, b);
615
- if (rel === "")
616
- return true;
617
- if (rel === ".." || rel.startsWith(".." + sep))
618
- return false;
619
- if (isAbsoluteRel(rel))
620
- return false;
621
- return true;
622
- };
623
- // Lexical containment is the primary gate.
624
- if (!within(root, lexical))
625
- return false;
626
- // Defense-in-depth: when the path (or a parent) is a symlink that points
627
- // outside the project, the canonical form must ALSO stay inside. Best-effort
628
- // — a not-yet-created file (ENOENT) falls back to the lexical decision above.
629
- try {
630
- const canonicalRoot = realpathSync(root);
631
- const canonical = realpathSync(lexical);
632
- if (!within(canonicalRoot, canonical))
633
- return false;
634
- }
635
- catch {
636
- /* file does not exist yet / realpath failed — lexical decision stands */
637
- }
638
- return true;
639
- }
640
- /** Pure helper: is a `path.relative` result an absolute path? (no regex) */
641
- function isAbsoluteRel(rel) {
642
- if (rel.startsWith("/"))
643
- return true; // POSIX absolute
644
- // Windows drive-absolute: "C:\..." or "C:/..."
645
- if (rel.length >= 3 && rel[1] === ":" && (rel[2] === "\\" || rel[2] === "/")) {
646
- const c = rel.charCodeAt(0);
647
- return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
648
- }
649
- return false;
650
- }
651
- /**
652
- * Decide whether `filePath` may be processed, given the project boundary AND
653
- * the user's existing host `Read(...)` allow rules.
654
- *
655
- * Decision order:
656
- * 1. Inside the project root → allowed (the common case; no config needed).
657
- * 2. Outside the project, but matching a `permissions.allow` `Read(...)` glob
658
- * the user already configured for the host → allowed. This is the
659
- * principled escape hatch: a deliberate out-of-project read is expressed
660
- * ONCE in the host config the user already maintains, reusing the same
661
- * mechanism Claude Code itself uses to whitelist a path outside the
662
- * sandbox — no context-mode-specific opt-out env that would rot into
663
- * dead code.
664
- * 3. Outside the project, no allow match → denied (closes the #852 escape).
665
- *
666
- * `allowGlobs` has the same per-settings-file shape as the deny globs returned
667
- * by `readToolPermissionPatterns(toolName, "allow", …)`. Allow-matching reuses
668
- * `evaluateFilePath` so absolute/`..`/symlink-canonical candidate resolution is
669
- * identical to the deny path — one matcher, no divergence.
670
- *
671
- * Fail-open on an unknown project root (boundary cannot be computed) so the
672
- * guard never blocks legitimate in-project work when resolution fails.
673
- */
674
- export function evaluateProjectContainment(filePath, projectRoot, allowGlobs = [], caseInsensitive = process.platform === "win32" || process.platform === "darwin") {
675
- if (isPathInsideProject(filePath, projectRoot, caseInsensitive)) {
676
- return { allowed: true, reason: "inside" };
677
- }
678
- // Outside the project — permit only if the user explicitly allowed this path
679
- // for the host Read tool. `evaluateFilePath` returns `denied:true` when a glob
680
- // MATCHES, so a match here means "explicitly allowed".
681
- if (allowGlobs.some((g) => g.length > 0)) {
682
- const matched = evaluateFilePath(filePath, allowGlobs, caseInsensitive, projectRoot);
683
- if (matched.denied)
684
- return { allowed: true, reason: "allow-rule" };
685
- }
686
- return { allowed: false, reason: "outside" };
687
- }
688
- // ==============================================================================
689
- // Shell-Escape Scanner
690
- // ==============================================================================
691
- // Regex patterns that detect shell-escape calls in non-shell languages.
692
- // Each pattern uses capture groups so that the embedded command string
693
- // can be extracted from the last non-quote group.
694
- //
695
- // NOTE: These regexes contain literal strings like "execSync" — they are
696
- // patterns for *detecting* shell escapes in user code, not actual usage.
697
- const SHELL_ESCAPE_PATTERNS = {
698
- python: [
699
- /os\.system\(\s*(['"])(.*?)\1\s*\)/g,
700
- /subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g,
701
- ],
702
- javascript: [
703
- /exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,
704
- /spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g,
705
- ],
706
- typescript: [
707
- /exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,
708
- /spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g,
709
- ],
710
- ruby: [
711
- /system\(\s*(['"])(.*?)\1/g,
712
- /`(.*?)`/g,
713
- ],
714
- go: [
715
- /exec\.Command\(\s*(['"`])(.*?)\1/g,
716
- ],
717
- php: [
718
- /shell_exec\(\s*(['"`])(.*?)\1/g,
719
- /(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,
720
- /(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,
721
- /passthru\(\s*(['"`])(.*?)\1/g,
722
- /proc_open\(\s*(['"`])(.*?)\1/g,
723
- ],
724
- rust: [
725
- /Command::new\(\s*(['"`])(.*?)\1/g,
726
- ],
727
- };
728
- /**
729
- * Extract all string elements from a Python subprocess list call.
730
- *
731
- * subprocess.run(["rm", "-rf", "/"]) → "rm -rf /"
732
- *
733
- * This catches the list-of-strings form that the single-string regex misses.
734
- */
735
- function extractPythonSubprocessListArgs(code) {
736
- const commands = [];
737
- const pattern = /subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g;
738
- let match;
739
- while ((match = pattern.exec(code)) !== null) {
740
- const listContent = match[1];
741
- const args = [...listContent.matchAll(/(['"])(.*?)\1/g)].map((m) => m[2]);
742
- if (args.length > 0) {
743
- commands.push(args.join(" "));
744
- }
745
- }
746
- return commands;
747
- }
748
- /**
749
- * Scan non-shell code for shell-escape calls and extract the embedded
750
- * command strings.
751
- *
752
- * Returns an array of command strings found in the code. For unknown
753
- * languages or code without shell-escape calls, returns an empty array.
754
- */
755
- export function extractShellCommands(code, language) {
756
- const patterns = SHELL_ESCAPE_PATTERNS[language];
757
- if (!patterns && language !== "python")
758
- return [];
759
- const commands = [];
760
- if (patterns) {
761
- for (const pattern of patterns) {
762
- // Reset lastIndex since we reuse the global regex
763
- pattern.lastIndex = 0;
764
- let match;
765
- while ((match = pattern.exec(code)) !== null) {
766
- // The command string is in the last capture group that isn't the
767
- // quote delimiter. For patterns with 2 groups (quote + content),
768
- // it's group 2. For Ruby backticks with 1 group, it's group 1.
769
- const command = match[match.length - 1];
770
- if (command)
771
- commands.push(command);
772
- }
773
- }
774
- }
775
- // Python: also extract subprocess list-form args
776
- if (language === "python") {
777
- commands.push(...extractPythonSubprocessListArgs(code));
778
- }
779
- return commands;
780
- }