@namzu/sdk 69.4.0 → 71.0.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 (436) hide show
  1. package/CHANGELOG.md +161 -0
  2. package/dist/authorization/bare-repository.d.ts +21 -0
  3. package/dist/authorization/bare-repository.d.ts.map +1 -0
  4. package/dist/authorization/bare-repository.js +62 -0
  5. package/dist/authorization/bare-repository.js.map +1 -0
  6. package/dist/authorization/command-line.d.ts.map +1 -1
  7. package/dist/authorization/command-line.js +10 -3
  8. package/dist/authorization/command-line.js.map +1 -1
  9. package/dist/authorization/gate.d.ts +7 -0
  10. package/dist/authorization/gate.d.ts.map +1 -1
  11. package/dist/authorization/gate.js +4 -0
  12. package/dist/authorization/gate.js.map +1 -1
  13. package/dist/authorization/protected-paths.d.ts +24 -6
  14. package/dist/authorization/protected-paths.d.ts.map +1 -1
  15. package/dist/authorization/protected-paths.js +83 -10
  16. package/dist/authorization/protected-paths.js.map +1 -1
  17. package/dist/authorization/readonly-commands.d.ts +17 -5
  18. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  19. package/dist/authorization/readonly-commands.js +77 -6
  20. package/dist/authorization/readonly-commands.js.map +1 -1
  21. package/dist/authorization/readonly-flags.d.ts.map +1 -1
  22. package/dist/authorization/readonly-flags.js +98 -0
  23. package/dist/authorization/readonly-flags.js.map +1 -1
  24. package/dist/authorization/shell-lexer.d.ts +15 -0
  25. package/dist/authorization/shell-lexer.d.ts.map +1 -1
  26. package/dist/authorization/shell-lexer.js +370 -2
  27. package/dist/authorization/shell-lexer.js.map +1 -1
  28. package/dist/authorization/shell-paths.d.ts.map +1 -1
  29. package/dist/authorization/shell-paths.js +276 -0
  30. package/dist/authorization/shell-paths.js.map +1 -1
  31. package/dist/authorization/shell-session-state.d.ts +47 -0
  32. package/dist/authorization/shell-session-state.d.ts.map +1 -0
  33. package/dist/authorization/shell-session-state.js +70 -0
  34. package/dist/authorization/shell-session-state.js.map +1 -0
  35. package/dist/authorization/shell-session.d.ts +9 -0
  36. package/dist/authorization/shell-session.d.ts.map +1 -0
  37. package/dist/authorization/shell-session.js +19 -0
  38. package/dist/authorization/shell-session.js.map +1 -0
  39. package/dist/authorization/skill-grant.d.ts.map +1 -1
  40. package/dist/authorization/skill-grant.js +1 -0
  41. package/dist/authorization/skill-grant.js.map +1 -1
  42. package/dist/compaction/extractor.d.ts.map +1 -1
  43. package/dist/compaction/extractor.js +2 -0
  44. package/dist/compaction/extractor.js.map +1 -1
  45. package/dist/compaction/hooks.d.ts +16 -0
  46. package/dist/compaction/hooks.d.ts.map +1 -1
  47. package/dist/compaction/hooks.js +26 -1
  48. package/dist/compaction/hooks.js.map +1 -1
  49. package/dist/compaction/manual.d.ts.map +1 -1
  50. package/dist/compaction/manual.js +6 -1
  51. package/dist/compaction/manual.js.map +1 -1
  52. package/dist/compaction/restore.d.ts.map +1 -1
  53. package/dist/compaction/restore.js +3 -2
  54. package/dist/compaction/restore.js.map +1 -1
  55. package/dist/config/runtime.d.ts +2 -0
  56. package/dist/config/runtime.d.ts.map +1 -1
  57. package/dist/config/runtime.js +7 -0
  58. package/dist/config/runtime.js.map +1 -1
  59. package/dist/connector/mcp/client.d.ts +7 -0
  60. package/dist/connector/mcp/client.d.ts.map +1 -1
  61. package/dist/connector/mcp/client.js +54 -4
  62. package/dist/connector/mcp/client.js.map +1 -1
  63. package/dist/connector/web/guarded-fetch.d.ts +30 -0
  64. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  65. package/dist/connector/web/guarded-fetch.js +85 -0
  66. package/dist/connector/web/guarded-fetch.js.map +1 -1
  67. package/dist/connector/web/index.d.ts +1 -1
  68. package/dist/connector/web/index.d.ts.map +1 -1
  69. package/dist/connector/web/index.js +1 -1
  70. package/dist/connector/web/index.js.map +1 -1
  71. package/dist/connector/web/types.d.ts +8 -0
  72. package/dist/connector/web/types.d.ts.map +1 -1
  73. package/dist/constants/compaction/index.d.ts.map +1 -1
  74. package/dist/constants/compaction/index.js +1 -1
  75. package/dist/constants/compaction/index.js.map +1 -1
  76. package/dist/execution/code-runtime/worker-program.d.ts +1 -1
  77. package/dist/execution/code-runtime/worker-program.d.ts.map +1 -1
  78. package/dist/execution/code-runtime/worker-program.js +9 -5
  79. package/dist/execution/code-runtime/worker-program.js.map +1 -1
  80. package/dist/execution/local.d.ts.map +1 -1
  81. package/dist/execution/local.js +6 -1
  82. package/dist/execution/local.js.map +1 -1
  83. package/dist/peers/index.d.ts +2 -2
  84. package/dist/peers/index.d.ts.map +1 -1
  85. package/dist/peers/index.js +1 -1
  86. package/dist/peers/index.js.map +1 -1
  87. package/dist/peers/record.d.ts +74 -0
  88. package/dist/peers/record.d.ts.map +1 -1
  89. package/dist/peers/record.js +41 -1
  90. package/dist/peers/record.js.map +1 -1
  91. package/dist/peers/registry.d.ts.map +1 -1
  92. package/dist/peers/registry.js +20 -3
  93. package/dist/peers/registry.js.map +1 -1
  94. package/dist/plugin/bin-path.d.ts +41 -0
  95. package/dist/plugin/bin-path.d.ts.map +1 -0
  96. package/dist/plugin/bin-path.js +146 -0
  97. package/dist/plugin/bin-path.js.map +1 -0
  98. package/dist/plugin/common-layout/read.js +3 -3
  99. package/dist/plugin/common-layout/read.js.map +1 -1
  100. package/dist/plugin/common-layout-names.d.ts.map +1 -1
  101. package/dist/plugin/common-layout-names.js +0 -1
  102. package/dist/plugin/common-layout-names.js.map +1 -1
  103. package/dist/plugin/hook-module/capabilities.d.ts +12 -0
  104. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  105. package/dist/plugin/hook-module/capabilities.js +82 -10
  106. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  107. package/dist/plugin/hook-module/consent.d.ts +11 -0
  108. package/dist/plugin/hook-module/consent.d.ts.map +1 -1
  109. package/dist/plugin/hook-module/consent.js +31 -0
  110. package/dist/plugin/hook-module/consent.js.map +1 -1
  111. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  112. package/dist/plugin/hook-module/host.js +69 -23
  113. package/dist/plugin/hook-module/host.js.map +1 -1
  114. package/dist/plugin/hook-module/index.d.ts +1 -1
  115. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  116. package/dist/plugin/hook-module/index.js +1 -1
  117. package/dist/plugin/hook-module/index.js.map +1 -1
  118. package/dist/plugin/hook-module/scan.d.ts +16 -0
  119. package/dist/plugin/hook-module/scan.d.ts.map +1 -1
  120. package/dist/plugin/hook-module/scan.js +68 -3
  121. package/dist/plugin/hook-module/scan.js.map +1 -1
  122. package/dist/plugin/hook-module/worker-source.d.ts +5 -4
  123. package/dist/plugin/hook-module/worker-source.d.ts.map +1 -1
  124. package/dist/plugin/hook-module/worker-source.js +254 -28
  125. package/dist/plugin/hook-module/worker-source.js.map +1 -1
  126. package/dist/plugin/lifecycle.d.ts +21 -0
  127. package/dist/plugin/lifecycle.d.ts.map +1 -1
  128. package/dist/plugin/lifecycle.js +64 -0
  129. package/dist/plugin/lifecycle.js.map +1 -1
  130. package/dist/plugin/shell-hook-tool-names.d.ts.map +1 -1
  131. package/dist/plugin/shell-hook-tool-names.js +1 -0
  132. package/dist/plugin/shell-hook-tool-names.js.map +1 -1
  133. package/dist/plugin/shell-hook.d.ts +1 -1
  134. package/dist/plugin/shell-hook.d.ts.map +1 -1
  135. package/dist/plugin/shell-hook.js +22 -4
  136. package/dist/plugin/shell-hook.js.map +1 -1
  137. package/dist/public-runtime.d.ts +11 -9
  138. package/dist/public-runtime.d.ts.map +1 -1
  139. package/dist/public-runtime.js +11 -8
  140. package/dist/public-runtime.js.map +1 -1
  141. package/dist/public-tools.d.ts +7 -3
  142. package/dist/public-tools.d.ts.map +1 -1
  143. package/dist/public-tools.js +7 -3
  144. package/dist/public-tools.js.map +1 -1
  145. package/dist/public-types.d.ts +2 -2
  146. package/dist/public-types.d.ts.map +1 -1
  147. package/dist/runtime/jobs/monitor-stream.d.ts +9 -1
  148. package/dist/runtime/jobs/monitor-stream.d.ts.map +1 -1
  149. package/dist/runtime/jobs/monitor-stream.js +13 -4
  150. package/dist/runtime/jobs/monitor-stream.js.map +1 -1
  151. package/dist/runtime/jobs/registry.d.ts +4 -0
  152. package/dist/runtime/jobs/registry.d.ts.map +1 -1
  153. package/dist/runtime/jobs/registry.js +12 -2
  154. package/dist/runtime/jobs/registry.js.map +1 -1
  155. package/dist/runtime/query/auto-review/git-status.d.ts.map +1 -1
  156. package/dist/runtime/query/auto-review/git-status.js +3 -2
  157. package/dist/runtime/query/auto-review/git-status.js.map +1 -1
  158. package/dist/runtime/query/executor.d.ts +16 -6
  159. package/dist/runtime/query/executor.d.ts.map +1 -1
  160. package/dist/runtime/query/executor.js +135 -15
  161. package/dist/runtime/query/executor.js.map +1 -1
  162. package/dist/runtime/query/index.d.ts.map +1 -1
  163. package/dist/runtime/query/index.js +2 -2
  164. package/dist/runtime/query/index.js.map +1 -1
  165. package/dist/runtime/query/iteration/outstanding-work.d.ts.map +1 -1
  166. package/dist/runtime/query/iteration/outstanding-work.js +14 -4
  167. package/dist/runtime/query/iteration/outstanding-work.js.map +1 -1
  168. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  169. package/dist/runtime/query/iteration/phases/compaction.js +11 -1
  170. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  171. package/dist/runtime/query/iteration/phases/tool-review.d.ts +2 -0
  172. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  173. package/dist/runtime/query/iteration/phases/tool-review.js +19 -8
  174. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  175. package/dist/runtime/query/path-escalation.d.ts +6 -0
  176. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  177. package/dist/runtime/query/path-escalation.js +58 -4
  178. package/dist/runtime/query/path-escalation.js.map +1 -1
  179. package/dist/runtime/query/review-policy.d.ts +21 -3
  180. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  181. package/dist/runtime/query/review-policy.js +39 -21
  182. package/dist/runtime/query/review-policy.js.map +1 -1
  183. package/dist/runtime/query/steering.d.ts +11 -2
  184. package/dist/runtime/query/steering.d.ts.map +1 -1
  185. package/dist/runtime/query/steering.js +18 -4
  186. package/dist/runtime/query/steering.js.map +1 -1
  187. package/dist/sandbox/provider/local.d.ts.map +1 -1
  188. package/dist/sandbox/provider/local.js +3 -1
  189. package/dist/sandbox/provider/local.js.map +1 -1
  190. package/dist/schedules/describe.d.ts.map +1 -1
  191. package/dist/schedules/describe.js +2 -0
  192. package/dist/schedules/describe.js.map +1 -1
  193. package/dist/schedules/evaluate.d.ts +4 -0
  194. package/dist/schedules/evaluate.d.ts.map +1 -1
  195. package/dist/schedules/evaluate.js +26 -1
  196. package/dist/schedules/evaluate.js.map +1 -1
  197. package/dist/schedules/index.d.ts +3 -1
  198. package/dist/schedules/index.d.ts.map +1 -1
  199. package/dist/schedules/index.js +2 -1
  200. package/dist/schedules/index.js.map +1 -1
  201. package/dist/schedules/next-fire.d.ts.map +1 -1
  202. package/dist/schedules/next-fire.js +10 -0
  203. package/dist/schedules/next-fire.js.map +1 -1
  204. package/dist/schedules/spec.d.ts +9 -0
  205. package/dist/schedules/spec.d.ts.map +1 -1
  206. package/dist/schedules/spec.js +33 -0
  207. package/dist/schedules/spec.js.map +1 -1
  208. package/dist/schedules/types.d.ts +32 -4
  209. package/dist/schedules/types.d.ts.map +1 -1
  210. package/dist/schedules/types.js +3 -2
  211. package/dist/schedules/types.js.map +1 -1
  212. package/dist/schedules/watch.d.ts +23 -0
  213. package/dist/schedules/watch.d.ts.map +1 -0
  214. package/dist/schedules/watch.js +46 -0
  215. package/dist/schedules/watch.js.map +1 -0
  216. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  217. package/dist/session/workspace/git-worktree.js +2 -1
  218. package/dist/session/workspace/git-worktree.js.map +1 -1
  219. package/dist/skills/arguments.d.ts +58 -0
  220. package/dist/skills/arguments.d.ts.map +1 -0
  221. package/dist/skills/arguments.js +208 -0
  222. package/dist/skills/arguments.js.map +1 -0
  223. package/dist/skills/index.d.ts +3 -1
  224. package/dist/skills/index.d.ts.map +1 -1
  225. package/dist/skills/index.js +1 -0
  226. package/dist/skills/index.js.map +1 -1
  227. package/dist/skills/inline-shell-host.d.ts +6 -0
  228. package/dist/skills/inline-shell-host.d.ts.map +1 -1
  229. package/dist/skills/inline-shell-host.js +8 -0
  230. package/dist/skills/inline-shell-host.js.map +1 -1
  231. package/dist/skills/inline-shell.d.ts +26 -1
  232. package/dist/skills/inline-shell.d.ts.map +1 -1
  233. package/dist/skills/inline-shell.js +1308 -22
  234. package/dist/skills/inline-shell.js.map +1 -1
  235. package/dist/tools/builtins/bash-cwd.d.ts.map +1 -1
  236. package/dist/tools/builtins/bash-cwd.js +2 -0
  237. package/dist/tools/builtins/bash-cwd.js.map +1 -1
  238. package/dist/tools/builtins/bash.d.ts.map +1 -1
  239. package/dist/tools/builtins/bash.js +79 -11
  240. package/dist/tools/builtins/bash.js.map +1 -1
  241. package/dist/tools/builtins/exit-semantics.d.ts +6 -0
  242. package/dist/tools/builtins/exit-semantics.d.ts.map +1 -1
  243. package/dist/tools/builtins/exit-semantics.js +10 -0
  244. package/dist/tools/builtins/exit-semantics.js.map +1 -1
  245. package/dist/tools/builtins/glob.d.ts.map +1 -1
  246. package/dist/tools/builtins/glob.js +68 -13
  247. package/dist/tools/builtins/glob.js.map +1 -1
  248. package/dist/tools/builtins/grep.d.ts.map +1 -1
  249. package/dist/tools/builtins/grep.js +37 -12
  250. package/dist/tools/builtins/grep.js.map +1 -1
  251. package/dist/tools/builtins/index.d.ts +11 -0
  252. package/dist/tools/builtins/index.d.ts.map +1 -1
  253. package/dist/tools/builtins/index.js +14 -0
  254. package/dist/tools/builtins/index.js.map +1 -1
  255. package/dist/tools/builtins/job.js +1 -1
  256. package/dist/tools/builtins/job.js.map +1 -1
  257. package/dist/tools/builtins/monitor.d.ts +1 -1
  258. package/dist/tools/builtins/monitor.d.ts.map +1 -1
  259. package/dist/tools/builtins/monitor.js +4 -2
  260. package/dist/tools/builtins/monitor.js.map +1 -1
  261. package/dist/tools/builtins/notebook-cells.d.ts +31 -0
  262. package/dist/tools/builtins/notebook-cells.d.ts.map +1 -0
  263. package/dist/tools/builtins/notebook-cells.js +160 -0
  264. package/dist/tools/builtins/notebook-cells.js.map +1 -0
  265. package/dist/tools/builtins/notebook-edit.d.ts +8 -0
  266. package/dist/tools/builtins/notebook-edit.d.ts.map +1 -0
  267. package/dist/tools/builtins/notebook-edit.js +249 -0
  268. package/dist/tools/builtins/notebook-edit.js.map +1 -0
  269. package/dist/tools/builtins/notebook-guard.d.ts.map +1 -1
  270. package/dist/tools/builtins/notebook-guard.js +2 -1
  271. package/dist/tools/builtins/notebook-guard.js.map +1 -1
  272. package/dist/tools/builtins/push-notification.d.ts +49 -0
  273. package/dist/tools/builtins/push-notification.d.ts.map +1 -0
  274. package/dist/tools/builtins/push-notification.js +107 -0
  275. package/dist/tools/builtins/push-notification.js.map +1 -0
  276. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  277. package/dist/tools/builtins/read-file.js +8 -3
  278. package/dist/tools/builtins/read-file.js.map +1 -1
  279. package/dist/tools/builtins/read-media.d.ts.map +1 -1
  280. package/dist/tools/builtins/read-media.js +2 -1
  281. package/dist/tools/builtins/read-media.js.map +1 -1
  282. package/dist/tools/builtins/read-render.d.ts.map +1 -1
  283. package/dist/tools/builtins/read-render.js +5 -3
  284. package/dist/tools/builtins/read-render.js.map +1 -1
  285. package/dist/tools/builtins/search-support.d.ts +6 -4
  286. package/dist/tools/builtins/search-support.d.ts.map +1 -1
  287. package/dist/tools/builtins/search-support.js +15 -3
  288. package/dist/tools/builtins/search-support.js.map +1 -1
  289. package/dist/tools/builtins/skill.d.ts.map +1 -1
  290. package/dist/tools/builtins/skill.js +30 -8
  291. package/dist/tools/builtins/skill.js.map +1 -1
  292. package/dist/tools/builtins/sleep-guard.d.ts +20 -0
  293. package/dist/tools/builtins/sleep-guard.d.ts.map +1 -1
  294. package/dist/tools/builtins/sleep-guard.js +125 -1
  295. package/dist/tools/builtins/sleep-guard.js.map +1 -1
  296. package/dist/tools/builtins/wait-for-job.js +1 -1
  297. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  298. package/dist/tools/builtins/web.d.ts +2 -0
  299. package/dist/tools/builtins/web.d.ts.map +1 -1
  300. package/dist/tools/builtins/web.js +97 -3
  301. package/dist/tools/builtins/web.js.map +1 -1
  302. package/dist/tools/command-shell.d.ts +50 -0
  303. package/dist/tools/command-shell.d.ts.map +1 -1
  304. package/dist/tools/command-shell.js +145 -0
  305. package/dist/tools/command-shell.js.map +1 -1
  306. package/dist/tools/env-scrub.d.ts +2 -0
  307. package/dist/tools/env-scrub.d.ts.map +1 -1
  308. package/dist/tools/env-scrub.js +15 -1
  309. package/dist/tools/env-scrub.js.map +1 -1
  310. package/dist/tools/git-config-env.d.ts +55 -0
  311. package/dist/tools/git-config-env.d.ts.map +1 -0
  312. package/dist/tools/git-config-env.js +130 -0
  313. package/dist/tools/git-config-env.js.map +1 -0
  314. package/dist/tools/schedules/schedule-tool.d.ts +7 -0
  315. package/dist/tools/schedules/schedule-tool.d.ts.map +1 -1
  316. package/dist/tools/schedules/schedule-tool.js +72 -3
  317. package/dist/tools/schedules/schedule-tool.js.map +1 -1
  318. package/dist/tools/schedules/types.d.ts +38 -2
  319. package/dist/tools/schedules/types.d.ts.map +1 -1
  320. package/dist/types/connector/mcp.d.ts +24 -0
  321. package/dist/types/connector/mcp.d.ts.map +1 -1
  322. package/dist/types/message/index.d.ts +21 -1
  323. package/dist/types/message/index.d.ts.map +1 -1
  324. package/dist/types/message/index.js +37 -2
  325. package/dist/types/message/index.js.map +1 -1
  326. package/dist/types/permission/index.d.ts +11 -2
  327. package/dist/types/permission/index.d.ts.map +1 -1
  328. package/dist/types/permission/index.js +12 -2
  329. package/dist/types/permission/index.js.map +1 -1
  330. package/dist/types/plugin/index.d.ts +10 -2
  331. package/dist/types/plugin/index.d.ts.map +1 -1
  332. package/dist/types/plugin/index.js.map +1 -1
  333. package/dist/types/tool/index.d.ts +13 -0
  334. package/dist/types/tool/index.d.ts.map +1 -1
  335. package/dist/types/tool/index.js.map +1 -1
  336. package/dist/utils/plain-terminal-text.d.ts +21 -0
  337. package/dist/utils/plain-terminal-text.d.ts.map +1 -0
  338. package/dist/utils/plain-terminal-text.js +156 -0
  339. package/dist/utils/plain-terminal-text.js.map +1 -0
  340. package/package.json +1 -1
  341. package/src/authorization/bare-repository.ts +70 -0
  342. package/src/authorization/command-line.ts +18 -4
  343. package/src/authorization/gate.ts +11 -0
  344. package/src/authorization/protected-paths.ts +89 -10
  345. package/src/authorization/readonly-commands.ts +75 -6
  346. package/src/authorization/readonly-flags.ts +103 -0
  347. package/src/authorization/shell-lexer.ts +367 -2
  348. package/src/authorization/shell-paths.ts +386 -0
  349. package/src/authorization/shell-session-state.ts +97 -0
  350. package/src/authorization/shell-session.ts +23 -0
  351. package/src/authorization/skill-grant.ts +1 -0
  352. package/src/compaction/extractor.ts +1 -0
  353. package/src/compaction/hooks.ts +43 -1
  354. package/src/compaction/manual.ts +6 -0
  355. package/src/compaction/restore.ts +3 -2
  356. package/src/config/runtime.ts +7 -0
  357. package/src/connector/mcp/client.ts +61 -4
  358. package/src/connector/web/guarded-fetch.ts +92 -0
  359. package/src/connector/web/index.ts +6 -1
  360. package/src/connector/web/types.ts +8 -0
  361. package/src/constants/compaction/index.ts +1 -1
  362. package/src/execution/code-runtime/worker-program.ts +9 -5
  363. package/src/execution/local.ts +6 -1
  364. package/src/peers/index.ts +8 -2
  365. package/src/peers/record.ts +45 -1
  366. package/src/peers/registry.ts +21 -5
  367. package/src/plugin/bin-path.ts +149 -0
  368. package/src/plugin/common-layout/read.ts +3 -3
  369. package/src/plugin/common-layout-names.ts +0 -1
  370. package/src/plugin/hook-module/capabilities.ts +94 -10
  371. package/src/plugin/hook-module/consent.ts +36 -0
  372. package/src/plugin/hook-module/host.ts +72 -21
  373. package/src/plugin/hook-module/index.ts +2 -0
  374. package/src/plugin/hook-module/scan.ts +76 -4
  375. package/src/plugin/hook-module/worker-source.ts +255 -28
  376. package/src/plugin/lifecycle.ts +67 -0
  377. package/src/plugin/shell-hook-tool-names.ts +1 -0
  378. package/src/plugin/shell-hook.ts +23 -4
  379. package/src/public-runtime.ts +27 -0
  380. package/src/public-tools.ts +36 -2
  381. package/src/public-types.ts +3 -1
  382. package/src/runtime/jobs/monitor-stream.ts +18 -4
  383. package/src/runtime/jobs/registry.ts +22 -2
  384. package/src/runtime/query/auto-review/git-status.ts +3 -2
  385. package/src/runtime/query/executor.ts +153 -12
  386. package/src/runtime/query/index.ts +5 -2
  387. package/src/runtime/query/iteration/outstanding-work.ts +22 -4
  388. package/src/runtime/query/iteration/phases/compaction.ts +14 -1
  389. package/src/runtime/query/iteration/phases/tool-review.ts +24 -7
  390. package/src/runtime/query/path-escalation.ts +52 -4
  391. package/src/runtime/query/review-policy.ts +47 -15
  392. package/src/runtime/query/steering.ts +32 -4
  393. package/src/sandbox/provider/local.ts +3 -1
  394. package/src/schedules/describe.ts +2 -0
  395. package/src/schedules/evaluate.ts +29 -1
  396. package/src/schedules/index.ts +9 -1
  397. package/src/schedules/next-fire.ts +9 -0
  398. package/src/schedules/spec.ts +42 -0
  399. package/src/schedules/types.ts +33 -3
  400. package/src/schedules/watch.ts +71 -0
  401. package/src/session/workspace/git-worktree.ts +3 -1
  402. package/src/skills/arguments.ts +250 -0
  403. package/src/skills/index.ts +10 -0
  404. package/src/skills/inline-shell-host.ts +16 -0
  405. package/src/skills/inline-shell.ts +1358 -22
  406. package/src/tools/builtins/bash-cwd.ts +2 -0
  407. package/src/tools/builtins/bash.ts +93 -13
  408. package/src/tools/builtins/exit-semantics.ts +10 -0
  409. package/src/tools/builtins/glob.ts +79 -15
  410. package/src/tools/builtins/grep.ts +37 -10
  411. package/src/tools/builtins/index.ts +15 -0
  412. package/src/tools/builtins/job.ts +1 -1
  413. package/src/tools/builtins/monitor.ts +4 -2
  414. package/src/tools/builtins/notebook-cells.ts +196 -0
  415. package/src/tools/builtins/notebook-edit.ts +280 -0
  416. package/src/tools/builtins/notebook-guard.ts +2 -1
  417. package/src/tools/builtins/push-notification.ts +138 -0
  418. package/src/tools/builtins/read-file.ts +9 -3
  419. package/src/tools/builtins/read-media.ts +2 -1
  420. package/src/tools/builtins/read-render.ts +5 -3
  421. package/src/tools/builtins/search-support.ts +17 -3
  422. package/src/tools/builtins/skill.ts +29 -7
  423. package/src/tools/builtins/sleep-guard.ts +128 -1
  424. package/src/tools/builtins/wait-for-job.ts +1 -1
  425. package/src/tools/builtins/web.ts +100 -3
  426. package/src/tools/command-shell.ts +166 -0
  427. package/src/tools/env-scrub.ts +13 -1
  428. package/src/tools/git-config-env.ts +143 -0
  429. package/src/tools/schedules/schedule-tool.ts +79 -3
  430. package/src/tools/schedules/types.ts +47 -9
  431. package/src/types/connector/mcp.ts +25 -0
  432. package/src/types/message/index.ts +53 -1
  433. package/src/types/permission/index.ts +20 -3
  434. package/src/types/plugin/index.ts +10 -2
  435. package/src/types/tool/index.ts +13 -0
  436. package/src/utils/plain-terminal-text.ts +142 -0
@@ -218,10 +218,324 @@ export class InlineShellError extends Error {
218
218
  this.name = 'InlineShellError';
219
219
  }
220
220
  }
221
+ /** Stands where the value goes while a command is read for what surrounds it. */
222
+ const VALUE_MARK = '\uE001';
223
+ /** Stands for a word the shell computes: an expansion, a substitution, a decoded string. */
224
+ const COMPUTED_MARK = '\uE000';
225
+ /**
226
+ * Read a command the way the shell does, once, so everything after it works on one text:
227
+ * a `#` comment is dropped (an apostrophe in it is not a quote), a backslash before a
228
+ * newline joins the lines except inside a comment or single quotes, `$'...'` is read to
229
+ * its real end (`\'` is an escape in it), a quote inside a `$( )` inside double quotes is
230
+ * its own, and a closed here-document body is dropped. Anything it cannot read with
231
+ * certainty sets `refuse`: a quote, here-document or group that never closes, a value
232
+ * inside a comment, an ANSI-C string or a here-document body, and a `case` inside a
233
+ * substitution.
234
+ */
235
+ function canonicalize(before, after) {
236
+ const text = `${before}${VALUE_MARK}${after}`;
237
+ const markAt = before.length;
238
+ const frames = [{ kind: 'code', dollar: false, inDq: false }];
239
+ let out = '';
240
+ let markOut = -1;
241
+ let refuse = false;
242
+ let lex = 'norm';
243
+ let escaped = false;
244
+ let ansiBody = '';
245
+ let prev = '\n';
246
+ const pending = [];
247
+ const push = (kind, dollar, inDq = false) => {
248
+ frames.push({ kind, dollar, inDq });
249
+ };
250
+ for (let i = 0; i < text.length; i++) {
251
+ const c = text[i];
252
+ if (i === markAt) {
253
+ markOut = out.length;
254
+ if (lex === 'comment' || lex === 'ansi')
255
+ refuse = true;
256
+ prev = 'x';
257
+ continue;
258
+ }
259
+ if (lex === 'single') {
260
+ out += c;
261
+ if (c === "'") {
262
+ lex = 'norm';
263
+ prev = "'";
264
+ }
265
+ continue;
266
+ }
267
+ if (lex === 'ansi') {
268
+ ansiBody += c;
269
+ if (escaped)
270
+ escaped = false;
271
+ else if (c === '\\')
272
+ escaped = true;
273
+ else if (c === "'") {
274
+ const body = ansiBody.slice(0, -1);
275
+ out += body.includes('\\') ? `'${COMPUTED_MARK}'` : `'${body}'`;
276
+ lex = 'norm';
277
+ prev = "'";
278
+ }
279
+ continue;
280
+ }
281
+ if (lex === 'comment') {
282
+ if (c !== '\n')
283
+ continue;
284
+ lex = 'norm';
285
+ }
286
+ if (lex === 'backtick') {
287
+ out += c;
288
+ if (escaped)
289
+ escaped = false;
290
+ else if (c === '\\')
291
+ escaped = true;
292
+ else if (c === '`') {
293
+ lex = 'norm';
294
+ prev = 'x';
295
+ }
296
+ continue;
297
+ }
298
+ const top = frames[frames.length - 1];
299
+ const next = text[i + 1];
300
+ if (top.kind === 'dq' || top.kind === 'param') {
301
+ if (c === '\\') {
302
+ if (next === '\n') {
303
+ i += 1;
304
+ continue;
305
+ }
306
+ out += c;
307
+ if (next !== undefined && next !== VALUE_MARK) {
308
+ out += next;
309
+ i += 1;
310
+ }
311
+ continue;
312
+ }
313
+ if (top.kind === 'dq' && c === '"') {
314
+ frames.pop();
315
+ out += c;
316
+ prev = '"';
317
+ continue;
318
+ }
319
+ if (top.kind === 'param') {
320
+ if (c === '}') {
321
+ frames.pop();
322
+ out += c;
323
+ prev = 'x';
324
+ continue;
325
+ }
326
+ if (c === '"') {
327
+ push('dq', false);
328
+ out += c;
329
+ continue;
330
+ }
331
+ if (c === "'" && !top.inDq) {
332
+ lex = 'single';
333
+ out += c;
334
+ continue;
335
+ }
336
+ }
337
+ if (c === '$' && next === '(') {
338
+ push('sub', true);
339
+ out += '$(';
340
+ i += 1;
341
+ prev = '(';
342
+ continue;
343
+ }
344
+ if (c === '$' && next === '{') {
345
+ push('param', false, top.kind === 'dq' || top.inDq);
346
+ out += '${';
347
+ i += 1;
348
+ continue;
349
+ }
350
+ if (c === '`') {
351
+ lex = 'backtick';
352
+ escaped = false;
353
+ out += c;
354
+ continue;
355
+ }
356
+ out += c;
357
+ continue;
358
+ }
359
+ // Code: the top level, or inside a `$( )`, `( )` or `<( )`.
360
+ if (c === '\\') {
361
+ if (next === '\n') {
362
+ i += 1;
363
+ continue;
364
+ }
365
+ out += c;
366
+ if (next !== undefined && next !== VALUE_MARK) {
367
+ out += next;
368
+ i += 1;
369
+ }
370
+ prev = 'x';
371
+ continue;
372
+ }
373
+ if (c === "'") {
374
+ lex = 'single';
375
+ out += c;
376
+ continue;
377
+ }
378
+ if (c === '$' && next === "'") {
379
+ lex = 'ansi';
380
+ ansiBody = '';
381
+ escaped = false;
382
+ i += 1;
383
+ continue;
384
+ }
385
+ if (c === '"') {
386
+ push('dq', false);
387
+ out += c;
388
+ prev = '"';
389
+ continue;
390
+ }
391
+ if (c === '`') {
392
+ lex = 'backtick';
393
+ escaped = false;
394
+ out += c;
395
+ continue;
396
+ }
397
+ if (c === '$' && next === '(') {
398
+ push('sub', true);
399
+ out += '$(';
400
+ i += 1;
401
+ prev = '(';
402
+ continue;
403
+ }
404
+ if (c === '$' && next === '{') {
405
+ push('param', false);
406
+ out += '${';
407
+ i += 1;
408
+ continue;
409
+ }
410
+ if ((c === '<' || c === '>') && next === '(') {
411
+ push('sub', true);
412
+ out += `${c}(`;
413
+ i += 1;
414
+ prev = '(';
415
+ continue;
416
+ }
417
+ if (c === '(') {
418
+ push('sub', false);
419
+ out += c;
420
+ prev = '(';
421
+ continue;
422
+ }
423
+ if (c === ')') {
424
+ if (frames.length > 1 && top.kind === 'sub') {
425
+ frames.pop();
426
+ prev = top.dollar ? 'x' : ')';
427
+ }
428
+ else
429
+ prev = ')';
430
+ out += c;
431
+ continue;
432
+ }
433
+ if (c === '#' && /[\s;|&()<>]/.test(prev)) {
434
+ lex = 'comment';
435
+ continue;
436
+ }
437
+ if (c === 'c' &&
438
+ text.startsWith('case', i) &&
439
+ /\s/.test(text[i + 4] ?? 'x') &&
440
+ /[\s;|&(]/.test(prev) &&
441
+ frames.some((f) => f.kind === 'sub')) {
442
+ // Where a pattern's `)` ends is not something to guess inside a substitution.
443
+ refuse = true;
444
+ }
445
+ if (c === '<' && next === '<' && text[i + 2] !== '<' && text[i - 1] !== '<') {
446
+ let j = i + 2;
447
+ let strip = false;
448
+ if (text[j] === '-') {
449
+ strip = true;
450
+ j += 1;
451
+ }
452
+ while (text[j] === ' ' || text[j] === '\t')
453
+ j += 1;
454
+ let delim = '';
455
+ while (j < text.length) {
456
+ const d = text[j];
457
+ if (d === "'" || d === '"') {
458
+ const close = text.indexOf(d, j + 1);
459
+ if (close === -1) {
460
+ refuse = true;
461
+ j = text.length;
462
+ break;
463
+ }
464
+ delim += text.slice(j + 1, close);
465
+ j = close + 1;
466
+ continue;
467
+ }
468
+ if (d === '\\' && j + 1 < text.length) {
469
+ delim += text[j + 1];
470
+ j += 2;
471
+ continue;
472
+ }
473
+ if (/[\s;|&()<>]/.test(d))
474
+ break;
475
+ delim += d;
476
+ j += 1;
477
+ }
478
+ if (delim === '' || delim.includes(VALUE_MARK))
479
+ refuse = true;
480
+ if (markAt > i && markAt < j) {
481
+ refuse = true;
482
+ markOut = out.length;
483
+ }
484
+ pending.push({ delim: delim.replaceAll(VALUE_MARK, ''), strip });
485
+ out += '<h';
486
+ prev = 'x';
487
+ i = j - 1;
488
+ continue;
489
+ }
490
+ if (c === '\n') {
491
+ out += c;
492
+ prev = '\n';
493
+ if (pending.length > 0) {
494
+ let pos = i + 1;
495
+ for (const heredoc of pending) {
496
+ let closed = false;
497
+ while (pos <= text.length) {
498
+ const end = text.indexOf('\n', pos);
499
+ const lineEnd = end === -1 ? text.length : end;
500
+ const line = text.slice(pos, lineEnd);
501
+ if (markAt >= pos && markAt <= lineEnd) {
502
+ refuse = true;
503
+ if (markOut === -1)
504
+ markOut = out.length;
505
+ }
506
+ pos = end === -1 ? text.length + 1 : end + 1;
507
+ if ((heredoc.strip ? line.replace(/^\t+/, '') : line) === heredoc.delim) {
508
+ closed = true;
509
+ break;
510
+ }
511
+ if (end === -1)
512
+ break;
513
+ }
514
+ if (!closed)
515
+ refuse = true;
516
+ }
517
+ pending.length = 0;
518
+ i = pos - 1;
519
+ }
520
+ continue;
521
+ }
522
+ out += c;
523
+ prev = c;
524
+ }
525
+ if (lex !== 'norm' && lex !== 'comment')
526
+ refuse = true;
527
+ if (frames.length > 1 || pending.length > 0)
528
+ refuse = true;
529
+ if (markOut === -1) {
530
+ refuse = true;
531
+ markOut = out.length;
532
+ }
533
+ return { prefix: out.slice(0, markOut), suffix: out.slice(markOut), refuse };
534
+ }
221
535
  /**
222
536
  * How the shell reads the position at the end of `prefix`, the text of one
223
537
  * command up to a value: outside any quote, inside single or double quotes, or
224
- * somewhere a value cannot be made safe (a comment, a dangling backslash, a here-document, a `${...}`, an
538
+ * somewhere a value cannot be made safe (a comment, a dangling backslash or a bare `$`, a here-document, a `${...}`, an
225
539
  * arithmetic or backtick expansion, an ANSI-C string that is not closed).
226
540
  *
227
541
  * A `$( ... )` starts a fresh reading of its own, so a value inside one is
@@ -272,8 +586,27 @@ function shellContextAt(prefix) {
272
586
  if (c === '$') {
273
587
  const next = prefix[i + 1];
274
588
  if (next === '(') {
275
- if (prefix[i + 2] === '(')
276
- return 'unsafe';
589
+ if (prefix[i + 2] === '(') {
590
+ // A closed arithmetic expansion is one word; a value inside one is not quotable.
591
+ let depth = 0;
592
+ let end = -1;
593
+ for (let j = i + 2; j < prefix.length; j++) {
594
+ if (prefix[j] === '(')
595
+ depth += 1;
596
+ else if (prefix[j] === ')') {
597
+ depth -= 1;
598
+ if (depth === 0) {
599
+ end = j;
600
+ break;
601
+ }
602
+ }
603
+ }
604
+ if (end === -1 || prefix[end + 1] !== ')')
605
+ return 'unsafe';
606
+ i = end + 1;
607
+ wordStart = false;
608
+ continue;
609
+ }
277
610
  stack.push('sub');
278
611
  i += 1;
279
612
  wordStart = true;
@@ -294,7 +627,10 @@ function shellContextAt(prefix) {
294
627
  i = end;
295
628
  wordStart = false;
296
629
  continue;
297
- }
630
+ } // A `$` right before the value would join its first character: `$` and a
631
+ // quote read as an ANSI-C string, `$` and `(` or a name as an expansion.
632
+ if (i === prefix.length - 1)
633
+ return 'unsafe';
298
634
  }
299
635
  if (c === '`') {
300
636
  const end = skipTo(i + 1, '`');
@@ -330,7 +666,14 @@ function shellContextAt(prefix) {
330
666
  wordStart = true;
331
667
  continue;
332
668
  }
333
- if (c === '<' && prefix[i + 1] === '<' && prefix[i + 2] !== '<')
669
+ // A here-string (`<<<`) takes an ordinary word, so the whole run is skipped before a
670
+ // here-document (`<<`) is looked for.
671
+ if (c === '<' && prefix.startsWith('<<<', i)) {
672
+ i += 2;
673
+ wordStart = true;
674
+ continue;
675
+ }
676
+ if (c === '<' && prefix[i + 1] === '<')
334
677
  return 'unsafe';
335
678
  if (c === '#' && wordStart) {
336
679
  const end = prefix.indexOf('\n', i);
@@ -347,6 +690,848 @@ function shellContextAt(prefix) {
347
690
  return 'single';
348
691
  return stack[stack.length - 1] === 'double' ? 'double' : 'none';
349
692
  }
693
+ /** Builtins whose arguments the shell reads again as shell text, a subscript or arithmetic. */
694
+ const REREAD_BUILTINS = new Set([
695
+ 'trap',
696
+ 'eval',
697
+ 'let',
698
+ 'source',
699
+ '.',
700
+ 'mapfile',
701
+ 'readarray',
702
+ 'unset',
703
+ 'getopts',
704
+ ]);
705
+ /** Programs that hand a string to a shell of their own. */
706
+ const REREAD_PROGRAMS = new Set(['ssh', 'su', 'watch', 'parallel']);
707
+ /** Builtins that take names: a value in the name position is read as a name with a subscript. */
708
+ const NAME_BUILTINS = new Set(['declare', 'typeset', 'local', 'readonly', 'export']);
709
+ const SHELL_NAMES = new Set([
710
+ 'sh',
711
+ 'bash',
712
+ 'zsh',
713
+ 'dash',
714
+ 'ksh',
715
+ 'ash',
716
+ 'fish',
717
+ 'rbash',
718
+ 'csh',
719
+ 'tcsh',
720
+ 'mksh',
721
+ 'yash',
722
+ 'pwsh',
723
+ 'powershell',
724
+ ]);
725
+ /** Programs that run a `-c` string like a shell does. */
726
+ const STRING_RUNNERS = new Set(['flock', 'script', 'runuser', 'sg']);
727
+ /** Words that only begin a statement; the command follows them. */
728
+ const SYNTAX_PREFIXES = new Set(['!', '{', 'if', 'then', 'else', 'elif', 'while', 'until', 'do']);
729
+ /** Words that run the next command, with options of their own before it. */
730
+ const COMMAND_WRAPPERS = new Set([
731
+ ...SYNTAX_PREFIXES,
732
+ 'time',
733
+ 'command',
734
+ 'builtin',
735
+ 'exec',
736
+ 'env',
737
+ 'sudo',
738
+ 'doas',
739
+ 'nohup',
740
+ 'nice',
741
+ 'ionice',
742
+ 'timeout',
743
+ 'xargs',
744
+ 'setsid',
745
+ 'stdbuf',
746
+ 'coproc',
747
+ ]);
748
+ /** Programs that start another command from their arguments, with options not listed here. */
749
+ const OTHER_WRAPPERS = new Set([
750
+ 'taskset',
751
+ 'unshare',
752
+ 'setpriv',
753
+ 'bwrap',
754
+ 'chroot',
755
+ 'nsenter',
756
+ 'strace',
757
+ 'ltrace',
758
+ 'systemd-run',
759
+ 'tmux',
760
+ 'screen',
761
+ 'firejail',
762
+ 'faketime',
763
+ 'fakeroot',
764
+ 'chrt',
765
+ 'proot',
766
+ 'busybox',
767
+ 'find',
768
+ ]);
769
+ /** The options of each wrapper that take the next word as their argument. */
770
+ const WRAPPER_OPTION_ARGS = {
771
+ sudo: ['-u', '-g', '-h', '-p', '-C', '-D', '-R', '-T', '-U', '-r', '-t'],
772
+ doas: ['-u', '-C'],
773
+ env: ['-u', '-C', '-a'],
774
+ nice: ['-n'],
775
+ ionice: ['-c', '-n', '-p', '-P', '-u'],
776
+ timeout: ['-s', '-k'],
777
+ xargs: ['-a', '-d', '-E', '-e', '-I', '-L', '-l', '-n', '-P', '-s'],
778
+ stdbuf: ['-i', '-o', '-e'],
779
+ exec: ['-a'],
780
+ time: ['-f', '-o'],
781
+ };
782
+ /** Names a wrapper may be followed by, anywhere, that read a string as shell text. */
783
+ const REREAD_AFTER_WRAPPER = new Set(['eval', 'trap', 'source', 'let']);
784
+ const ASSIGNMENT_WORD = /^[A-Za-z_]\w*(\[[^\]]*\])?\+?=/;
785
+ /** A redirection with its target in the same word, or a bare operator whose target is the next word. */
786
+ const REDIRECTION_WORD = /^(\d*|&)(>>?|<<?<?|>&|<&|>\||<>|&>>?)/;
787
+ const REDIRECTION_OPERATOR = /^(\d*|&)(>>?|<<?<?|>&|<&|>\||<>|&>>?)$/;
788
+ /** A shell option that carries the command string. */
789
+ const COMMAND_STRING_FLAG = /^(-[a-zA-Z]*[cC][a-zA-Z]*|--command)$/;
790
+ const ARITHMETIC_TEST = /(?:^|\s)-(?:eq|ne|lt|gt|le|ge|v|R)(?:\s|$)/;
791
+ /** A later use, in the same command, that evaluates a variable as arithmetic or prompt text. */
792
+ const EVALUATES_LATER = /\$\(\(|\$\[|\(\(|\blet\b|\bset\s+(?:-\w*x|-o\s+xtrace)|\b(?:declare|typeset|integer)\s+-\w*i|\[\[[^\n]*?\s-(?:eq|ne|lt|gt|le|ge)\s/;
793
+ /** Variables the shell expands as text, with command substitution, every time they are used. */
794
+ const EXPANDED_VARIABLES = /^(?:PS[0-4]|PROMPT_COMMAND|BASH_ENV|ENV|SHELLOPTS|BASHOPTS|RANDOM|SRANDOM|OPTIND)\+?=/;
795
+ /** A word that is not a literal: it holds an expansion, a substitution or a brace list. */
796
+ const DYNAMIC_WORD = /[${\uE000\uE002]/;
797
+ /** A word that may name a program only after the shell expands it: a glob in a name. */
798
+ const GLOB_WORD = /[*?[]|[@+!]\(/;
799
+ /** A word the shell computes: an expansion, a substitution, a process substitution. */
800
+ const COMPUTED_WORD = /[$\uE000\uE002]/;
801
+ /** An expansion that reads a variable as a subscript, an offset, an indirect name or prompt text. */
802
+ const PARAM_REREAD = /\$\{(?:!|#?\w+\[(?!\s*(?:@|\*|\d+)\s*\])|\w+:(?![-+=?]|\s*\d+(?::\s*\d+)?\s*\})|\w+@[PQEAaKk])/;
803
+ /** An assignment to a subscript that is not a number: the subscript is read as arithmetic. */
804
+ const SUBSCRIPT_ASSIGNMENT = /^[A-Za-z_]\w*\[(?!\d+\])[^\]]+\]\+?=/;
805
+ /**
806
+ * The words of the statement the end of `prefix` sits in, quotes removed. With `collect`,
807
+ * every statement of the text is handed to it as well, each as its words.
808
+ */
809
+ function statementWordsAt(prefix, collect) {
810
+ const fresh = (sub, psub = false, ancestor) => ({
811
+ words: [],
812
+ cur: '',
813
+ has: false,
814
+ double: false,
815
+ sub,
816
+ psub,
817
+ ancestor,
818
+ });
819
+ const stack = [fresh(false)];
820
+ let single = false;
821
+ const top = () => stack[stack.length - 1];
822
+ const endWord = (f) => {
823
+ if (f.has || f.cur !== '')
824
+ f.words.push(f.cur);
825
+ f.cur = '';
826
+ f.has = false;
827
+ };
828
+ const reset = (f) => {
829
+ if (collect !== undefined && f.words.length > 0)
830
+ collect.push(f.words);
831
+ f.words = [];
832
+ };
833
+ const open = (f, psub) => {
834
+ const cur = psub ? f.cur.replace(/\d*[<>]$/, '') : f.cur;
835
+ const finished = f.words[f.words.length - 1] ?? '';
836
+ stack.push(fresh(true, psub, {
837
+ words: [...f.words, cur],
838
+ psub,
839
+ afterRedirect: psub && REDIRECTION_OPERATOR.test(finished),
840
+ }));
841
+ };
842
+ const close = () => {
843
+ const child = stack.pop();
844
+ const parent = top();
845
+ if (child.psub)
846
+ parent.cur = parent.cur.replace(/\d*[<>]$/, '');
847
+ parent.cur += child.psub ? '' : '';
848
+ parent.has = true;
849
+ };
850
+ for (let i = 0; i < prefix.length; i++) {
851
+ const c = prefix[i];
852
+ const f = top();
853
+ if (single) {
854
+ if (c === "'")
855
+ single = false;
856
+ else
857
+ f.cur += c;
858
+ continue;
859
+ }
860
+ if (c === '\\') {
861
+ f.cur += prefix[i + 1] ?? '';
862
+ f.has = true;
863
+ i += 1;
864
+ continue;
865
+ }
866
+ if (c === '`') {
867
+ const end = prefix.indexOf('`', i + 1);
868
+ f.cur += '';
869
+ f.has = true;
870
+ if (end === -1)
871
+ break;
872
+ i = end;
873
+ continue;
874
+ }
875
+ if (c === '$' && prefix[i + 1] === '(') {
876
+ if (prefix[i + 2] === '(') {
877
+ // Arithmetic: one computed word, unless it is still open.
878
+ let depth = 0;
879
+ let end = -1;
880
+ for (let j = i + 2; j < prefix.length; j++) {
881
+ if (prefix[j] === '(')
882
+ depth += 1;
883
+ else if (prefix[j] === ')') {
884
+ depth -= 1;
885
+ if (depth === 0) {
886
+ end = j;
887
+ break;
888
+ }
889
+ }
890
+ }
891
+ if (end === -1)
892
+ break;
893
+ if (prefix[end + 1] === ')') {
894
+ f.cur += '';
895
+ f.has = true;
896
+ i = end + 1;
897
+ continue;
898
+ }
899
+ }
900
+ open(f, false);
901
+ i += 1;
902
+ continue;
903
+ }
904
+ if (f.double) {
905
+ if (c === '"')
906
+ f.double = false;
907
+ else
908
+ f.cur += c;
909
+ continue;
910
+ }
911
+ if (c === "'") {
912
+ single = true;
913
+ f.has = true;
914
+ continue;
915
+ }
916
+ if (c === '"') {
917
+ f.double = true;
918
+ f.has = true;
919
+ continue;
920
+ }
921
+ if (/\s/.test(c)) {
922
+ endWord(f);
923
+ if (c === '\n')
924
+ reset(f);
925
+ continue;
926
+ }
927
+ // `>&2`, `2>&1`, `&>f` and `<&3` are redirections, not a statement break.
928
+ if (c === '&' && (prefix[i - 1] === '>' || prefix[i - 1] === '<' || prefix[i + 1] === '>')) {
929
+ f.cur += c;
930
+ continue;
931
+ }
932
+ if (c === ';' || c === '|' || c === '&') {
933
+ endWord(f);
934
+ reset(f);
935
+ continue;
936
+ }
937
+ if (c === '(') {
938
+ if (/^\d*[<>]$/.test(f.cur) && !f.has) {
939
+ open(f, true);
940
+ }
941
+ else if (f.cur === '' && !f.has) {
942
+ reset(f);
943
+ if (prefix[i + 1] === '(') {
944
+ f.words = ['(('];
945
+ i += 1;
946
+ }
947
+ }
948
+ else
949
+ f.cur += c;
950
+ continue;
951
+ }
952
+ if (c === ')') {
953
+ if (f.sub && stack.length > 1) {
954
+ endWord(f);
955
+ reset(f);
956
+ close();
957
+ }
958
+ else {
959
+ endWord(f);
960
+ reset(f);
961
+ }
962
+ continue;
963
+ }
964
+ f.cur += c;
965
+ }
966
+ if (collect !== undefined) {
967
+ for (const frame of stack) {
968
+ endWord(frame);
969
+ if (frame.words.length > 0)
970
+ collect.push(frame.words);
971
+ }
972
+ }
973
+ const f = top();
974
+ const words = [...f.words];
975
+ const mid = f.has || f.cur !== '' || single;
976
+ if (mid)
977
+ words.push(f.cur);
978
+ const ancestors = stack.slice(1).map((frame) => frame.ancestor);
979
+ return { words, mid, ancestors };
980
+ }
981
+ /**
982
+ * Where the end of `prefix` sits in a bracketed region the shell reads as an
983
+ * expression: a subscript, a `[[ ... ]]` test, a `(( ... ))` command. A `[`
984
+ * inside quotes is text, except `$[`; every other `[` that follows a name, a
985
+ * parenthesis, or sits in an array initialiser opens a subscript, whatever
986
+ * space follows it.
987
+ */
988
+ function regionsAt(prefix) {
989
+ let single = false;
990
+ // Double quotes and the `$( )` opened inside them, innermost last.
991
+ const quotes = [];
992
+ const inDouble = () => quotes[quotes.length - 1]?.kind === 'dq';
993
+ let open = 0;
994
+ let doubleBracketAt = -1;
995
+ let arithmetic = false;
996
+ let arithmeticDepth = 0;
997
+ let wordStart = true;
998
+ const parens = [];
999
+ for (let i = 0; i < prefix.length; i++) {
1000
+ const c = prefix[i];
1001
+ const prev = prefix[i - 1] ?? '';
1002
+ if (single) {
1003
+ if (c === "'")
1004
+ single = false;
1005
+ continue;
1006
+ }
1007
+ if (c === '\\') {
1008
+ i += 1;
1009
+ wordStart = false;
1010
+ continue;
1011
+ }
1012
+ if (inDouble()) {
1013
+ if (c === '"')
1014
+ quotes.pop();
1015
+ else if (c === '$' && prefix[i + 1] === '[') {
1016
+ open += 1;
1017
+ i += 1;
1018
+ }
1019
+ else if (c === '$' && prefix[i + 1] === '(') {
1020
+ quotes.push({ kind: 'sub', parens: parens.length });
1021
+ parens.push(false);
1022
+ i += 1;
1023
+ wordStart = true;
1024
+ }
1025
+ continue;
1026
+ }
1027
+ if (c === "'") {
1028
+ single = true;
1029
+ wordStart = false;
1030
+ continue;
1031
+ }
1032
+ if (c === '"') {
1033
+ quotes.push({ kind: 'dq' });
1034
+ wordStart = false;
1035
+ continue;
1036
+ }
1037
+ if (arithmetic) {
1038
+ if (c === '(')
1039
+ arithmeticDepth += 1;
1040
+ else if (c === ')') {
1041
+ if (arithmeticDepth > 0)
1042
+ arithmeticDepth -= 1;
1043
+ else if (prefix[i + 1] === ')') {
1044
+ arithmetic = false;
1045
+ i += 1;
1046
+ }
1047
+ }
1048
+ continue;
1049
+ }
1050
+ if (c === '$' && prefix[i + 1] === '[') {
1051
+ open += 1;
1052
+ i += 1;
1053
+ wordStart = false;
1054
+ continue;
1055
+ }
1056
+ if (c === '(') {
1057
+ if (prefix[i + 1] === '(' && prev !== '$') {
1058
+ arithmetic = true;
1059
+ arithmeticDepth = 0;
1060
+ i += 1;
1061
+ }
1062
+ else
1063
+ parens.push(prev === '=');
1064
+ wordStart = true;
1065
+ continue;
1066
+ }
1067
+ if (c === ')') {
1068
+ parens.pop();
1069
+ const frame = quotes[quotes.length - 1];
1070
+ if (frame?.kind === 'sub' && frame.parens === parens.length)
1071
+ quotes.pop();
1072
+ wordStart = false;
1073
+ continue;
1074
+ }
1075
+ if (c === '[') {
1076
+ if (open > 0)
1077
+ open += 1;
1078
+ else if (prefix[i + 1] === '[' && wordStart && /\s/.test(prefix[i + 2] ?? ' ')) {
1079
+ if (doubleBracketAt === -1)
1080
+ doubleBracketAt = i;
1081
+ i += 1;
1082
+ }
1083
+ else if (/[\w)\]]/.test(prev) || (wordStart && parens[parens.length - 1] === true))
1084
+ open += 1;
1085
+ wordStart = false;
1086
+ continue;
1087
+ }
1088
+ if (c === ']') {
1089
+ if (doubleBracketAt !== -1 &&
1090
+ prefix[i + 1] === ']' &&
1091
+ wordStart &&
1092
+ /[\s;|&)]/.test(prefix[i + 2] ?? ' ')) {
1093
+ doubleBracketAt = -1;
1094
+ i += 1;
1095
+ }
1096
+ else if (open > 0)
1097
+ open -= 1;
1098
+ wordStart = false;
1099
+ continue;
1100
+ }
1101
+ wordStart = /[\s;|&(]/.test(c);
1102
+ }
1103
+ return { subscript: open > 0, doubleBracketAt, arithmetic };
1104
+ }
1105
+ /** The name of a command word: its path stripped. */
1106
+ function baseName(word) {
1107
+ return word.slice(word.lastIndexOf('/') + 1);
1108
+ }
1109
+ /** A command word that is not a literal name: it holds an expansion, or a glob that picks the program. */
1110
+ function unknownWord(name) {
1111
+ return DYNAMIC_WORD.test(name) || (name !== '[' && name !== '[[' && GLOB_WORD.test(name));
1112
+ }
1113
+ /** Where the command word of `words` is, past assignments, redirections, wrappers and their options. */
1114
+ function commandIndex(words) {
1115
+ let at = 0;
1116
+ let wrapper = -1;
1117
+ while (at < words.length) {
1118
+ const w = words[at];
1119
+ if (REDIRECTION_OPERATOR.test(w)) {
1120
+ at += 2;
1121
+ continue;
1122
+ }
1123
+ if (REDIRECTION_WORD.test(w) || ASSIGNMENT_WORD.test(w)) {
1124
+ at += 1;
1125
+ continue;
1126
+ }
1127
+ const base = baseName(w);
1128
+ if (base === 'function') {
1129
+ // `function name {`: the name is not a command.
1130
+ at += 2;
1131
+ if (words[at] === '()')
1132
+ at += 1;
1133
+ continue;
1134
+ }
1135
+ if (!COMMAND_WRAPPERS.has(base))
1136
+ break;
1137
+ if (!SYNTAX_PREFIXES.has(base) && wrapper === -1)
1138
+ wrapper = at;
1139
+ at += 1;
1140
+ // `coproc NAME { ... }`: the name is not a command.
1141
+ if (base === 'coproc' && words[at + 1] === '{')
1142
+ at += 1;
1143
+ const takes = WRAPPER_OPTION_ARGS[base] ?? [];
1144
+ while (at < words.length && /^-/.test(words[at])) {
1145
+ const option = words[at];
1146
+ at += 1;
1147
+ if (takes.includes(option) && at < words.length)
1148
+ at += 1;
1149
+ }
1150
+ if (base === 'timeout' && /^\d[\d.]*[smhd]?$/.test(words[at] ?? ''))
1151
+ at += 1;
1152
+ }
1153
+ const command = words[at];
1154
+ if (wrapper === -1 && command !== undefined && OTHER_WRAPPERS.has(baseName(command)))
1155
+ wrapper = at;
1156
+ return { at, wrapper };
1157
+ }
1158
+ /**
1159
+ * Whether the words after a shell's name, with a value to follow (joining the last word
1160
+ * when `mid`), make the value the command string of the shell: `-c` seen among the
1161
+ * options (which end at the first operand or `--`, `-o` and `-O` taking a word), and no
1162
+ * operand yet before the value.
1163
+ */
1164
+ function shellRunsValueAsScript(rest, mid) {
1165
+ let sawCommand = false;
1166
+ let i = 0;
1167
+ for (; i < rest.length; i++) {
1168
+ const w = rest[i];
1169
+ if (w === '--') {
1170
+ i += 1;
1171
+ break;
1172
+ }
1173
+ if (!/^[-+]./.test(w))
1174
+ break;
1175
+ if (COMMAND_STRING_FLAG.test(w))
1176
+ sawCommand = true;
1177
+ if (/^(?:[-+][a-zA-Z]*[oO]|--rcfile|--init-file)$/.test(w))
1178
+ i += 1;
1179
+ }
1180
+ if (!sawCommand)
1181
+ return false;
1182
+ const operands = Math.max(0, rest.length - i);
1183
+ return operands - (mid ? 1 : 0) <= 0;
1184
+ }
1185
+ /** The same for a program that runs a `-c` string like a shell, whose options may follow an operand. */
1186
+ function runnerRunsValueAsScript(rest, mid) {
1187
+ const flag = rest.findIndex((w) => COMMAND_STRING_FLAG.test(w));
1188
+ if (flag === -1)
1189
+ return false;
1190
+ return rest.length - flag - 1 - (mid ? 1 : 0) <= 0;
1191
+ }
1192
+ /** Whether a shell-like name, its words after it, and a value to follow, make the value a script. */
1193
+ function runsValueAsScript(name, rest, mid) {
1194
+ if (rest.some((w) => w === '<<<' || w.includes('')))
1195
+ return true;
1196
+ return STRING_RUNNERS.has(name)
1197
+ ? runnerRunsValueAsScript(rest, mid)
1198
+ : shellRunsValueAsScript(rest, mid);
1199
+ }
1200
+ /**
1201
+ * Whether, after a wrapper program, a later word is a shell or a command that reads a
1202
+ * string again and the value would be its script. The wrapper's own options and their
1203
+ * arguments are not told apart: every later word is looked at.
1204
+ */
1205
+ function wrappedRereads(words, wrapper, mid) {
1206
+ let from = wrapper + 1;
1207
+ if (baseName(words[wrapper]) === 'find') {
1208
+ const exec = words.findIndex((w, k) => k > wrapper && /^-(?:exec|execdir|ok|okdir)$/.test(w));
1209
+ if (exec === -1)
1210
+ return false;
1211
+ from = exec + 1;
1212
+ }
1213
+ for (let k = from; k < words.length; k++) {
1214
+ const name = baseName(words[k]);
1215
+ if (SHELL_NAMES.has(name) || STRING_RUNNERS.has(name) || unknownWord(name)) {
1216
+ if (runsValueAsScript(name, words.slice(k + 1), mid))
1217
+ return true;
1218
+ continue;
1219
+ }
1220
+ if (REREAD_AFTER_WRAPPER.has(name) || REREAD_PROGRAMS.has(name))
1221
+ return true;
1222
+ }
1223
+ return false;
1224
+ }
1225
+ /**
1226
+ * Whether the pipeline stage a value feeds, in the rest of its command, ends in a shell that
1227
+ * reads its input as commands (`| sh`, `| bash -s`).
1228
+ */
1229
+ function feedsShell(suffix) {
1230
+ const stage = suffix.split(/\n|;|&&|\|\||\)/)[0] ?? '';
1231
+ const stages = stage.split(/\|&?/).slice(1);
1232
+ for (const piece of stages) {
1233
+ const { words } = statementWordsAt(piece);
1234
+ const at = commandIndex(words).at;
1235
+ const command = words[at];
1236
+ if (command === undefined)
1237
+ continue;
1238
+ const isShell = SHELL_NAMES.has(baseName(command)) || unknownWord(baseName(command));
1239
+ if (!isShell)
1240
+ continue;
1241
+ const args = words.slice(at + 1);
1242
+ if (args.some((w) => COMMAND_STRING_FLAG.test(w)))
1243
+ continue;
1244
+ if (args.some((w) => /^-[a-zA-Z]*s/.test(w)) || args.every((w) => w.startsWith('-')))
1245
+ return true;
1246
+ }
1247
+ return false;
1248
+ }
1249
+ /** Whether a `mapfile` or `readarray` with these words would read the value as its callback or array name. */
1250
+ function mapfileTakesValue(rest, mid) {
1251
+ let operands = 0;
1252
+ for (let i = 0; i < rest.length; i++) {
1253
+ const w = rest[i];
1254
+ if (/^-/.test(w)) {
1255
+ if (/^-[a-zA-Z]*[Cc]/.test(w))
1256
+ return true;
1257
+ if (/^-[dnOsu]$/.test(w))
1258
+ i += 1;
1259
+ continue;
1260
+ }
1261
+ operands += 1;
1262
+ }
1263
+ return operands - (mid ? 1 : 0) <= 0;
1264
+ }
1265
+ /**
1266
+ * Whether a value at the end of `prefix` would sit, in the statement made of `words`
1267
+ * (`mid`: the value joins its last word), where the shell reads a word again: the first
1268
+ * word is not a literal, it evaluates its arguments (`trap`, `eval`, `let`, `source`, `.`,
1269
+ * a shell run with `-c`, `printf -v`, `read` names, `[ -v`), it takes names (`declare`,
1270
+ * `unset`, `export` in the name position), or the value is assigned to a variable the
1271
+ * shell evaluates.
1272
+ */
1273
+ function statementRereads(words, mid, prefix, suffix) {
1274
+ const last = mid ? words[words.length - 1] : undefined;
1275
+ if (last !== undefined && EXPANDED_VARIABLES.test(last))
1276
+ return true;
1277
+ if (last !== undefined &&
1278
+ ASSIGNMENT_WORD.test(last) &&
1279
+ (EVALUATES_LATER.test(suffix) || /\b(?:declare|typeset|integer|local)\s+-\w*i/.test(prefix)))
1280
+ return true;
1281
+ for (let i = 0; i < words.length; i++) {
1282
+ if (/^env$/.test(baseName(words[i])) &&
1283
+ /^(-[a-zA-Z]*S|--split-string)/.test(words[i + 1] ?? ''))
1284
+ return true;
1285
+ }
1286
+ const { at, wrapper } = commandIndex(words);
1287
+ // The value itself is the program to run (`env $ARGUMENTS`, `sudo $ARGUMENTS`,
1288
+ // `xargs $ARGUMENTS`, or a bare `$ARGUMENTS`): quoting it still lets it choose the program.
1289
+ if (mid ? at === words.length - 1 : at >= words.length && wrapper !== -1)
1290
+ return true;
1291
+ const first = words[at];
1292
+ if (first === undefined)
1293
+ return false;
1294
+ const rest = words.slice(at + 1);
1295
+ const name = baseName(first);
1296
+ // A first word that is not a literal cannot be shown not to be `eval`, `trap` or a shell.
1297
+ if (unknownWord(name))
1298
+ return true;
1299
+ if (wrapper !== -1 && wrappedRereads(words, wrapper, mid))
1300
+ return true;
1301
+ if (!first.includes('/') && REREAD_BUILTINS.has(name)) {
1302
+ if (name !== 'mapfile' && name !== 'readarray')
1303
+ return true;
1304
+ if (mapfileTakesValue(rest, mid))
1305
+ return true;
1306
+ }
1307
+ if (REREAD_PROGRAMS.has(name))
1308
+ return true;
1309
+ if (name === 'printf' && /^-v/.test(rest[0] ?? '')) {
1310
+ // Only the word after `-v` is a name; later words are printed.
1311
+ const attached = rest[0].length > 2;
1312
+ if (mid && rest.length === 1)
1313
+ return true;
1314
+ if (!attached && (mid ? rest.length === 2 : rest.length === 1))
1315
+ return true;
1316
+ }
1317
+ if ((name === 'compgen' || name === 'complete') && rest.some((w) => /^-[a-zA-Z]*[CFW]/.test(w)))
1318
+ return true;
1319
+ if (name === 'read') {
1320
+ // Every operand of `read` is a name, which the shell reads with its subscript; the
1321
+ // word after a redirection is a file.
1322
+ const redirectTarget = last !== undefined
1323
+ ? REDIRECTION_WORD.test(last)
1324
+ : REDIRECTION_OPERATOR.test(words[words.length - 1] ?? '');
1325
+ if (!redirectTarget && !last?.startsWith('-'))
1326
+ return true;
1327
+ }
1328
+ if ((name === '[' || name === 'test') && rest.some((w) => w === '-v' || w === '-R'))
1329
+ return true;
1330
+ if (NAME_BUILTINS.has(name)) {
1331
+ if (rest.some((w) => /^-[a-zA-Z]*[inI]/.test(w)))
1332
+ return true;
1333
+ // Where a value follows `=` it is a value; anywhere else it is a name.
1334
+ if (last === undefined || !last.includes('='))
1335
+ return true;
1336
+ }
1337
+ // A shell, or a program that runs a string like one, handed the value as its command string.
1338
+ if (SHELL_NAMES.has(name) || STRING_RUNNERS.has(name)) {
1339
+ if (runsValueAsScript(name, rest, mid))
1340
+ return true;
1341
+ }
1342
+ return false;
1343
+ }
1344
+ /** Whether a statement, wherever it is, reads a variable it is given as shell text, a subscript or a name. */
1345
+ function statementIsSink(words) {
1346
+ if (words.some((w) => SUBSCRIPT_ASSIGNMENT.test(w)))
1347
+ return true;
1348
+ if (words[0] === '((')
1349
+ return true;
1350
+ const { at, wrapper } = commandIndex(words);
1351
+ const first = words[at];
1352
+ if (first === undefined)
1353
+ return false;
1354
+ const rest = words.slice(at + 1);
1355
+ const name = baseName(first);
1356
+ const computed = (w) => w !== undefined && COMPUTED_WORD.test(w);
1357
+ if (wrapper !== -1) {
1358
+ for (let k = wrapper + 1; k < words.length; k++) {
1359
+ const n = baseName(words[k]);
1360
+ if (SHELL_NAMES.has(n) || STRING_RUNNERS.has(n) || REREAD_AFTER_WRAPPER.has(n))
1361
+ return true;
1362
+ }
1363
+ }
1364
+ if (!first.includes('/') && (name === 'source' || name === '.')) {
1365
+ return rest.some((w) => computed(w) || /^\/dev\//.test(w) || w === '-');
1366
+ }
1367
+ if (!first.includes('/') && (name === 'eval' || name === 'trap' || name === 'let')) {
1368
+ return rest.some((w) => computed(w));
1369
+ }
1370
+ if (SHELL_NAMES.has(name) || STRING_RUNNERS.has(name)) {
1371
+ let sawCommand = false;
1372
+ let sawStdin = false;
1373
+ let i = 0;
1374
+ for (; i < rest.length; i++) {
1375
+ const w = rest[i];
1376
+ if (w === '--') {
1377
+ i += 1;
1378
+ break;
1379
+ }
1380
+ if (!/^[-+]./.test(w))
1381
+ break;
1382
+ if (COMMAND_STRING_FLAG.test(w))
1383
+ sawCommand = true;
1384
+ if (/^-[a-zA-Z]*s/.test(w))
1385
+ sawStdin = true;
1386
+ if (/^(?:[-+][a-zA-Z]*[oO]|--rcfile|--init-file)$/.test(w))
1387
+ i += 1;
1388
+ }
1389
+ const operand = rest[i];
1390
+ if (sawCommand)
1391
+ return operand === undefined || computed(operand);
1392
+ return sawStdin || operand === undefined || operand === '-' || /^\/dev\//.test(operand);
1393
+ }
1394
+ if (name === 'printf' && /^-v/.test(rest[0] ?? ''))
1395
+ return computed(rest[0]) || computed(rest[1]);
1396
+ if (NAME_BUILTINS.has(name) ||
1397
+ name === 'unset' ||
1398
+ name === 'getopts' ||
1399
+ name === 'read' ||
1400
+ name === 'mapfile' ||
1401
+ name === 'readarray' ||
1402
+ name === 'compgen' ||
1403
+ name === 'complete' ||
1404
+ name === 'alias') {
1405
+ // A name reference or integer reads the whole value as a name or arithmetic.
1406
+ if (rest.some((w) => /^-[a-zA-Z]*[inI]/.test(w)) && rest.some((w) => computed(w)))
1407
+ return true;
1408
+ return rest.some((w) => computed(w.split('=')[0] || undefined));
1409
+ }
1410
+ if ((name === '[' || name === 'test') && rest.some((w) => w === '-v' || w === '-R'))
1411
+ return rest.some((w) => computed(w));
1412
+ return false;
1413
+ }
1414
+ /** Whether a statement runs something from a file or a shell: where a value written to a file would be read as commands. */
1415
+ function statementRunsFile(words) {
1416
+ const { at } = commandIndex(words);
1417
+ const first = words[at];
1418
+ if (first === undefined)
1419
+ return false;
1420
+ const name = baseName(first);
1421
+ return (SHELL_NAMES.has(name) ||
1422
+ STRING_RUNNERS.has(name) ||
1423
+ name === 'source' ||
1424
+ name === '.' ||
1425
+ name === 'chmod' ||
1426
+ name === 'exec');
1427
+ }
1428
+ function flowOf(frames, suffix) {
1429
+ const flow = { data: false, file: false };
1430
+ for (const { words, mid } of frames) {
1431
+ const last = mid ? words[words.length - 1] : undefined;
1432
+ if (last !== undefined && ASSIGNMENT_WORD.test(last))
1433
+ flow.data = true;
1434
+ if (words.some((w) => /^[A-Za-z_]\w*\+?=\(/.test(w)))
1435
+ flow.data = true;
1436
+ const finished = words[(mid ? words.length - 1 : words.length) - 1];
1437
+ if (finished !== undefined && /^<<<$/.test(finished))
1438
+ flow.data = true;
1439
+ if (last !== undefined && /^<<</.test(last))
1440
+ flow.data = true;
1441
+ const { at } = commandIndex(words);
1442
+ const name = baseName(words[at] ?? '');
1443
+ if (name === 'set' || name === 'select' || (name === 'for' && words.includes('in')))
1444
+ flow.data = true;
1445
+ if (name === 'tee' || words.some((w) => /^\d*>>?(?!&)/.test(w) && !/^\d*>&/.test(w)))
1446
+ flow.file = true;
1447
+ }
1448
+ const stage = suffix.split(/\n|;|&&|\|\||\)/)[0] ?? '';
1449
+ if (/\|/.test(stage))
1450
+ flow.data = true;
1451
+ if (/(?:^|[^\d&>])>>?\s*[^&\s]/.test(stage) || /\btee\b/.test(stage))
1452
+ flow.file = true;
1453
+ return flow;
1454
+ }
1455
+ /**
1456
+ * Whether the rest of a command, where a value has gone into a variable or a stream,
1457
+ * reads a variable as shell text, a name, a subscript, an offset or arithmetic.
1458
+ */
1459
+ function rereadsLater(whole, suffix, flow) {
1460
+ const statements = [];
1461
+ statementWordsAt(whole, statements);
1462
+ if (flow.data) {
1463
+ if (EVALUATES_LATER.test(suffix) || PARAM_REREAD.test(whole))
1464
+ return true;
1465
+ if (statements.some(statementIsSink))
1466
+ return true;
1467
+ }
1468
+ if (flow.file && statements.some(statementRunsFile))
1469
+ return true;
1470
+ return false;
1471
+ }
1472
+ /**
1473
+ * Whether a value at the end of `rawPrefix` (with `rawSuffix` the rest of the same command)
1474
+ * would sit where the shell reads a word again: a subscript that is still open
1475
+ * (`a[`, `a[ `, `arr=( [`, `$[`), an arithmetic command or a `[[` test with an arithmetic
1476
+ * operator, a command that evaluates its arguments (`trap`, `eval`, `let`, `source`, `.`,
1477
+ * a shell run with `-c` however many options come first, `printf -v`, `read` names, `[ -v`),
1478
+ * one that takes names (`declare`, `unset`, `export` in the name position), a first word
1479
+ * that is not a literal, a wrapper in front of any of these, a shell that reads the value
1480
+ * from a pipe, an alias, or a variable the value was put into that is evaluated later.
1481
+ * Quoting cannot make a value data there, so the load is refused.
1482
+ *
1483
+ * Both texts are the command as {@link canonicalize} read it.
1484
+ */
1485
+ function rereadsAt(prefix, suffix) {
1486
+ const regions = regionsAt(prefix);
1487
+ if (regions.subscript || regions.arithmetic)
1488
+ return true;
1489
+ if (regions.doubleBracketAt !== -1) {
1490
+ const close = suffix.search(/\s\]\]/);
1491
+ const region = prefix.slice(regions.doubleBracketAt) + (close === -1 ? suffix : suffix.slice(0, close));
1492
+ if (ARITHMETIC_TEST.test(region))
1493
+ return true;
1494
+ }
1495
+ const whole = `${prefix}x${suffix}`;
1496
+ // An alias is expanded as a command word, so any word may be a re-reading builtin.
1497
+ if (/expand_aliases/.test(whole))
1498
+ return true;
1499
+ if (feedsShell(suffix))
1500
+ return true;
1501
+ const state = statementWordsAt(prefix);
1502
+ if (statementRereads(state.words, state.mid, prefix, suffix))
1503
+ return true;
1504
+ for (const ancestor of state.ancestors) {
1505
+ const { at } = commandIndex(ancestor.words);
1506
+ const name = baseName(ancestor.words[at] ?? '');
1507
+ if (ancestor.psub && ancestor.afterRedirect) {
1508
+ // `sh < <( ... )` reads the output as commands; any other program reads it as data.
1509
+ if (SHELL_NAMES.has(name) || unknownWord(name))
1510
+ return true;
1511
+ continue;
1512
+ }
1513
+ if (ancestor.psub && SHELL_NAMES.has(name))
1514
+ return true;
1515
+ if (statementRereads(ancestor.words, true, prefix, suffix))
1516
+ return true;
1517
+ }
1518
+ const flow = flowOf([
1519
+ { words: state.words, mid: state.mid },
1520
+ ...state.ancestors.map((a) => ({ words: a.words, mid: true })),
1521
+ ], suffix);
1522
+ return (flow.data || flow.file) && rereadsLater(whole, suffix, flow);
1523
+ }
1524
+ /**
1525
+ * Whether the command text defines a shell function (`name() { ... }`, `name ( )`,
1526
+ * `function name { ... }`). A function can hand its argument to `trap`, `declare -i`,
1527
+ * arithmetic or `eval` where this reader cannot follow it, so a value in any command that
1528
+ * defines one is refused. Text that merely looks like a definition inside quotes is
1529
+ * refused too: the quotes are not read, so a definition can never be hidden behind them.
1530
+ */
1531
+ function definesFunction(whole) {
1532
+ return (/(?:^|[;&|(){}\n]|\b(?:then|do|else)\b)\s*function\s+[^\s;&|(){}<>]/.test(whole) ||
1533
+ /[^\s;&|(){}<>$=`]\s*\(\s*\)/.test(whole));
1534
+ }
350
1535
  /** One word as the shell reads it literally. */
351
1536
  function shellQuoteWord(word) {
352
1537
  return `'${word.replaceAll("'", "'\\''")}'`;
@@ -417,26 +1602,42 @@ function typedWords(value) {
417
1602
  * end the command where it is read), and neither can one where no quoting
418
1603
  * holds (a here-document, `${...}`): the load is refused.
419
1604
  */
420
- function quoteForCommand(value, prefix, dialect) {
1605
+ function quoteForCommand(value, prefix, dialect, whole = false, suffix = '') {
421
1606
  if (dialect === 'cmd') {
422
1607
  // No quoting here is known to hold in the Windows command interpreter, so only words
423
1608
  // made of characters it reads literally go in.
424
- const words = typedWords(value);
1609
+ const words = whole ? [value] : typedWords(value);
425
1610
  if (words.every((word) => /^[\w.\\/:=+,@-]+$/.test(word)))
426
1611
  return words.join(' ');
427
1612
  throw new InlineShellError('A value given to this skill or command has characters that cannot be put safely inside a command for the Windows command interpreter, so it was not loaded.', 'injection');
428
1613
  }
429
- const context = shellContextAt(prefix);
1614
+ // Digits are one inert word wherever they stand, arithmetic and subscripts included:
1615
+ // nothing in them is shell syntax. Only a `$` or a backslash right before would join them.
1616
+ if (/^[0-9]+$/.test(value) && !/[$\\]$/.test(prefix))
1617
+ return value;
1618
+ const command = canonicalize(prefix, suffix);
1619
+ if (command.refuse) {
1620
+ throw new InlineShellError('A value given to this skill or command would land in a shell command whose quotes, here-documents or groups cannot be read with certainty, so it was not loaded.', 'injection');
1621
+ }
1622
+ const context = shellContextAt(command.prefix);
430
1623
  if (context === 'unsafe' || value.includes('`')) {
431
1624
  throw new InlineShellError(context === 'unsafe'
432
- ? 'A value given to this skill or command would land inside a here-document or a ${...} or arithmetic expansion of a shell command, where it cannot be quoted, so it was not loaded.'
1625
+ ? 'A value given to this skill or command would land inside a here-document, a ${...} or arithmetic expansion, or right after a bare $ of a shell command, where it cannot be quoted, so it was not loaded.'
433
1626
  : 'A value given to this skill or command contains a backtick, which cannot be put inside a shell command, so it was not loaded.', 'injection');
434
1627
  }
1628
+ if (definesFunction(`${command.prefix}x${command.suffix}`)) {
1629
+ throw new InlineShellError('A value given to this skill or command would land in a shell command that defines a shell function, which could hand the value to the shell to read again as code, so it was not loaded. Move the value out of the command that defines the function, or write the template without a function.', 'injection');
1630
+ }
1631
+ if (rereadsAt(command.prefix, command.suffix)) {
1632
+ throw new InlineShellError('A value given to this skill or command would land where the shell reads it again as a command, a subscript or arithmetic (trap, eval, a subscript, a shell run with -c and the like), where it cannot be made safe, so it was not loaded.', 'injection');
1633
+ }
435
1634
  if (context === 'single')
436
1635
  return value.replaceAll("'", "'\\''");
437
1636
  if (context === 'double')
438
1637
  return value.replace(/[\\"$]/g, '\\$&');
439
- return typedWords(value).map(shellQuoteWord).join(' ');
1638
+ // A value that is already one word (a positional argument) stays one argument, even
1639
+ // when it holds spaces; the whole text a person typed is read back into its words.
1640
+ return whole ? shellQuoteWord(value) : typedWords(value).map(shellQuoteWord).join(' ');
440
1641
  }
441
1642
  /**
442
1643
  * Put values into a template, each escaped, and prove no value added a
@@ -448,32 +1649,45 @@ function quoteForCommand(value, prefix, dialect) {
448
1649
  * reads it as data ({@link quoteForCommand}), by where it sits: a person's
449
1650
  * `-n 5` stays two arguments, and `x; touch f #` stays words of an argument
450
1651
  * list. Throws {@link InlineShellError} when a value cannot be made safe, or the
451
- * substituted text holds more commands than the template does.
1652
+ * substituted text does not hold exactly the template's commands, in order.
452
1653
  */
453
1654
  export function substituteEscaped(template, values, options = {}) {
454
1655
  const normalized = normalizeInlineShellText(template);
455
1656
  const tokens = Object.keys(values).filter((token) => token.length > 0);
456
- if (tokens.length === 0)
1657
+ if (tokens.length === 0 && options.reader === undefined)
457
1658
  return normalized;
458
1659
  // Longest first, so `$ARGUMENTS_X` is never read as `$ARGUMENTS` plus a tail.
459
1660
  tokens.sort((a, b) => b.length - a.length);
1661
+ const read = options.reader ??
1662
+ ((text, at) => {
1663
+ const token = tokens.find((candidate) => text.startsWith(candidate, at));
1664
+ return token === undefined ? undefined : { kind: 'value', token };
1665
+ });
460
1666
  // The template with a word where each value goes: the commands the author wrote.
461
1667
  let neutral = '';
462
1668
  const pieces = [];
463
1669
  let text = '';
464
1670
  let i = 0;
465
1671
  while (i < normalized.length) {
466
- const token = tokens.find((candidate) => normalized.startsWith(candidate, i));
467
- if (token === undefined) {
1672
+ const found = read(normalized, i);
1673
+ if (found === undefined) {
468
1674
  text += normalized[i];
469
1675
  neutral += normalized[i];
470
1676
  i += 1;
471
1677
  continue;
472
1678
  }
1679
+ if (found.kind === 'literal') {
1680
+ text += found.text;
1681
+ neutral += found.text;
1682
+ i += found.length;
1683
+ continue;
1684
+ }
1685
+ const token = found.token;
473
1686
  if (text !== '')
474
1687
  pieces.push(text);
475
1688
  text = '';
476
1689
  pieces.push({
1690
+ whole: found.whole === true,
477
1691
  token,
478
1692
  at: neutral.length,
479
1693
  before: normalized[i - 1] ?? '',
@@ -489,22 +1703,47 @@ export function substituteEscaped(template, values, options = {}) {
489
1703
  const marker = markers.find((m) => m.start <= at && at < m.end);
490
1704
  if (marker === undefined)
491
1705
  return undefined;
492
- return marker.kind === 'inline' ? marker.start + 2 : neutral.indexOf('\n', marker.start) + 1;
1706
+ return marker.kind === 'inline'
1707
+ ? { from: marker.start + 2, end: marker.end - 1 }
1708
+ : {
1709
+ from: neutral.indexOf('\n', marker.start) + 1,
1710
+ // Up to the line that closes the fence, which is not part of the command.
1711
+ end: marker.start + marker.raw.lastIndexOf('\n'),
1712
+ };
493
1713
  };
494
1714
  let out = '';
1715
+ // Where each value landed: its place in the neutral text (one character wide) and in the output.
1716
+ const landed = [];
495
1717
  for (const piece of pieces) {
496
1718
  if (typeof piece === 'string') {
497
1719
  out += piece;
498
1720
  continue;
499
1721
  }
500
1722
  const value = values[piece.token];
501
- const from = commandAt(piece.at);
502
- out +=
503
- from === undefined
504
- ? escapeBetween(value, piece.before, piece.after)
505
- : quoteForCommand(value, neutral.slice(from, piece.at), options.dialect ?? hostCommandShell().dialect);
1723
+ const span = commandAt(piece.at);
1724
+ const from = span?.from;
1725
+ const put = from === undefined || span === undefined
1726
+ ? escapeBetween(value, piece.before, piece.after)
1727
+ : quoteForCommand(value, neutral.slice(from, piece.at), options.dialect ?? hostCommandShell().dialect, piece.whole, neutral.slice(piece.at + 1, span.end));
1728
+ landed.push({ at: piece.at, outAt: out.length, length: put.length });
1729
+ out += put;
506
1730
  }
507
- if (findInlineShell(out).length > markers.length) {
1731
+ // A neutral offset (a marker's edge) in the output text.
1732
+ const inOutput = (at) => {
1733
+ let shift = 0;
1734
+ for (const place of landed) {
1735
+ if (place.at >= at)
1736
+ break;
1737
+ shift += place.length - 1;
1738
+ }
1739
+ return at + shift;
1740
+ };
1741
+ // The commands the author wrote, values quoted in, are what must be there: the same
1742
+ // ones, in the same order. A count would let a value that masks one command and
1743
+ // creates another through.
1744
+ const expected = markers.map((m) => `${m.kind}\u0000${out.slice(inOutput(m.start), inOutput(m.end))}`);
1745
+ const found = findInlineShell(out).map((m) => `${m.kind}\u0000${m.raw}`);
1746
+ if (expected.length !== found.length || expected.some((raw, index) => raw !== found[index])) {
508
1747
  throw new InlineShellError('A value given to this skill or command contains text that would start a shell command, so it was not loaded.', 'injection');
509
1748
  }
510
1749
  return out;
@@ -571,7 +1810,10 @@ export async function expandInlineShell(text, options) {
571
1810
  throw new InlineShellError(`A shell command in ${shown(options.commandName)} is ${marker.command.length} characters, and at most ${INLINE_SHELL_MAX_COMMAND_CHARS} may run while it loads.`, 'limit');
572
1811
  }
573
1812
  }
1813
+ // A string is the text for that spot; a number is the place of a hand-off, whose note
1814
+ // is final once the count is known. Never a marker inside the text, which could collide.
574
1815
  const replacements = [];
1816
+ const handedOff = [];
575
1817
  let total = 0;
576
1818
  for (const marker of markers) {
577
1819
  options.signal?.throwIfAborted();
@@ -585,6 +1827,11 @@ export async function expandInlineShell(text, options) {
585
1827
  if (outcome.kind === 'denied') {
586
1828
  throw new InlineShellError(`Shell command permission check failed for pattern "${pattern}": ${outcome.reason}`, 'permission');
587
1829
  }
1830
+ if (outcome.kind === 'handoff') {
1831
+ handedOff.push(marker.command);
1832
+ replacements.push(handedOff.length - 1);
1833
+ continue;
1834
+ }
588
1835
  if (outcome.kind === 'hook') {
589
1836
  const verdict = outcome.verdict;
590
1837
  if (verdict.kind === 'stop') {
@@ -614,7 +1861,46 @@ export async function expandInlineShell(text, options) {
614
1861
  replacements.push(shaped);
615
1862
  }
616
1863
  let n = 0;
617
- return replaceMarkers(source, markers, () => replacements[n++]);
1864
+ if (handedOff.length === 0) {
1865
+ return replaceMarkers(source, markers, () => replacements[n++]);
1866
+ }
1867
+ const { header, spot } = handOffNotes(handedOff);
1868
+ const body = replaceMarkers(source, markers, () => {
1869
+ const r = replacements[n++];
1870
+ return typeof r === 'number' ? spot(r) : r;
1871
+ });
1872
+ return header === '' ? body : `${header}\n\n${body}`;
1873
+ }
1874
+ /** A command as it is written in a hand-off note: in backticks, or fenced when it holds a backtick or a newline. */
1875
+ function fenced(command) {
1876
+ const longest = Math.max(0, ...(command.match(/`+/g) ?? []).map((run) => run.length));
1877
+ const fence = '`'.repeat(Math.max(3, longest + 1));
1878
+ return `${fence}\n${command}\n${fence}`;
1879
+ }
1880
+ /**
1881
+ * The hand-off notes for the commands a model is asked to run itself. One command: its
1882
+ * note stands where the command was. Several: a short numbered list goes first (the
1883
+ * header), and each spot names its number.
1884
+ */
1885
+ function handOffNotes(commands) {
1886
+ const plain = (command) => !/[`\n]/.test(command);
1887
+ if (commands.length === 1) {
1888
+ const command = commands[0];
1889
+ const lead = '[run this first, exactly as written, with the bash tool and use its output:';
1890
+ const note = plain(command) ? `${lead} \`${command}\`]` : `${lead}]\n${fenced(command)}`;
1891
+ return { header: '', spot: () => note };
1892
+ }
1893
+ const head = `[Run these ${commands.length} commands first, exactly as written, with the bash tool, and use their output where each is named below. Run them one per call.]`;
1894
+ const list = commands.map((command, i) => plain(command) ? `${i + 1}. \`${command}\`` : `${i + 1}.\n${fenced(command)}`);
1895
+ return {
1896
+ header: [head, ...list].join('\n'),
1897
+ spot: (i) => {
1898
+ const command = commands[i];
1899
+ return plain(command)
1900
+ ? `[output of command ${i + 1}, \`${command}\`]`
1901
+ : `[output of command ${i + 1}]`;
1902
+ },
1903
+ };
618
1904
  }
619
1905
  function replaceMarkers(source, markers, replacement) {
620
1906
  let out = '';