@namzu/sdk 70.0.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 (394) hide show
  1. package/CHANGELOG.md +117 -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.map +1 -1
  14. package/dist/authorization/protected-paths.js +46 -1
  15. package/dist/authorization/protected-paths.js.map +1 -1
  16. package/dist/authorization/readonly-commands.d.ts +17 -5
  17. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  18. package/dist/authorization/readonly-commands.js +77 -6
  19. package/dist/authorization/readonly-commands.js.map +1 -1
  20. package/dist/authorization/readonly-flags.d.ts.map +1 -1
  21. package/dist/authorization/readonly-flags.js +98 -0
  22. package/dist/authorization/readonly-flags.js.map +1 -1
  23. package/dist/authorization/shell-lexer.d.ts +15 -0
  24. package/dist/authorization/shell-lexer.d.ts.map +1 -1
  25. package/dist/authorization/shell-lexer.js +108 -3
  26. package/dist/authorization/shell-lexer.js.map +1 -1
  27. package/dist/authorization/shell-paths.d.ts.map +1 -1
  28. package/dist/authorization/shell-paths.js +276 -0
  29. package/dist/authorization/shell-paths.js.map +1 -1
  30. package/dist/authorization/shell-session-state.d.ts +47 -0
  31. package/dist/authorization/shell-session-state.d.ts.map +1 -0
  32. package/dist/authorization/shell-session-state.js +70 -0
  33. package/dist/authorization/shell-session-state.js.map +1 -0
  34. package/dist/authorization/shell-session.d.ts +9 -0
  35. package/dist/authorization/shell-session.d.ts.map +1 -0
  36. package/dist/authorization/shell-session.js +19 -0
  37. package/dist/authorization/shell-session.js.map +1 -0
  38. package/dist/authorization/skill-grant.d.ts.map +1 -1
  39. package/dist/authorization/skill-grant.js +1 -0
  40. package/dist/authorization/skill-grant.js.map +1 -1
  41. package/dist/compaction/extractor.d.ts.map +1 -1
  42. package/dist/compaction/extractor.js +2 -0
  43. package/dist/compaction/extractor.js.map +1 -1
  44. package/dist/compaction/hooks.d.ts +16 -0
  45. package/dist/compaction/hooks.d.ts.map +1 -1
  46. package/dist/compaction/hooks.js +26 -1
  47. package/dist/compaction/hooks.js.map +1 -1
  48. package/dist/compaction/manual.d.ts.map +1 -1
  49. package/dist/compaction/manual.js +6 -1
  50. package/dist/compaction/manual.js.map +1 -1
  51. package/dist/compaction/restore.d.ts.map +1 -1
  52. package/dist/compaction/restore.js +3 -2
  53. package/dist/compaction/restore.js.map +1 -1
  54. package/dist/config/runtime.d.ts +2 -0
  55. package/dist/config/runtime.d.ts.map +1 -1
  56. package/dist/config/runtime.js +7 -0
  57. package/dist/config/runtime.js.map +1 -1
  58. package/dist/connector/mcp/client.d.ts +7 -0
  59. package/dist/connector/mcp/client.d.ts.map +1 -1
  60. package/dist/connector/mcp/client.js +54 -4
  61. package/dist/connector/mcp/client.js.map +1 -1
  62. package/dist/connector/web/types.d.ts +8 -0
  63. package/dist/connector/web/types.d.ts.map +1 -1
  64. package/dist/constants/compaction/index.d.ts.map +1 -1
  65. package/dist/constants/compaction/index.js +1 -1
  66. package/dist/constants/compaction/index.js.map +1 -1
  67. package/dist/execution/code-runtime/worker-program.d.ts +1 -1
  68. package/dist/execution/code-runtime/worker-program.d.ts.map +1 -1
  69. package/dist/execution/code-runtime/worker-program.js +9 -5
  70. package/dist/execution/code-runtime/worker-program.js.map +1 -1
  71. package/dist/execution/local.d.ts.map +1 -1
  72. package/dist/execution/local.js +6 -1
  73. package/dist/execution/local.js.map +1 -1
  74. package/dist/peers/index.d.ts +2 -2
  75. package/dist/peers/index.d.ts.map +1 -1
  76. package/dist/peers/index.js +1 -1
  77. package/dist/peers/index.js.map +1 -1
  78. package/dist/peers/record.d.ts +74 -0
  79. package/dist/peers/record.d.ts.map +1 -1
  80. package/dist/peers/record.js +41 -1
  81. package/dist/peers/record.js.map +1 -1
  82. package/dist/peers/registry.d.ts.map +1 -1
  83. package/dist/peers/registry.js +20 -3
  84. package/dist/peers/registry.js.map +1 -1
  85. package/dist/plugin/bin-path.d.ts +41 -0
  86. package/dist/plugin/bin-path.d.ts.map +1 -0
  87. package/dist/plugin/bin-path.js +146 -0
  88. package/dist/plugin/bin-path.js.map +1 -0
  89. package/dist/plugin/common-layout/read.js +1 -1
  90. package/dist/plugin/common-layout/read.js.map +1 -1
  91. package/dist/plugin/common-layout-names.d.ts.map +1 -1
  92. package/dist/plugin/common-layout-names.js +0 -1
  93. package/dist/plugin/common-layout-names.js.map +1 -1
  94. package/dist/plugin/hook-module/scan.d.ts +16 -0
  95. package/dist/plugin/hook-module/scan.d.ts.map +1 -1
  96. package/dist/plugin/hook-module/scan.js +67 -2
  97. package/dist/plugin/hook-module/scan.js.map +1 -1
  98. package/dist/plugin/hook-module/worker-source.d.ts.map +1 -1
  99. package/dist/plugin/hook-module/worker-source.js +56 -0
  100. package/dist/plugin/hook-module/worker-source.js.map +1 -1
  101. package/dist/plugin/lifecycle.d.ts +21 -0
  102. package/dist/plugin/lifecycle.d.ts.map +1 -1
  103. package/dist/plugin/lifecycle.js +64 -0
  104. package/dist/plugin/lifecycle.js.map +1 -1
  105. package/dist/plugin/shell-hook-tool-names.d.ts.map +1 -1
  106. package/dist/plugin/shell-hook-tool-names.js +1 -0
  107. package/dist/plugin/shell-hook-tool-names.js.map +1 -1
  108. package/dist/plugin/shell-hook.d.ts +1 -1
  109. package/dist/plugin/shell-hook.d.ts.map +1 -1
  110. package/dist/plugin/shell-hook.js +22 -4
  111. package/dist/plugin/shell-hook.js.map +1 -1
  112. package/dist/public-runtime.d.ts +8 -6
  113. package/dist/public-runtime.d.ts.map +1 -1
  114. package/dist/public-runtime.js +8 -5
  115. package/dist/public-runtime.js.map +1 -1
  116. package/dist/public-tools.d.ts +6 -2
  117. package/dist/public-tools.d.ts.map +1 -1
  118. package/dist/public-tools.js +6 -2
  119. package/dist/public-tools.js.map +1 -1
  120. package/dist/public-types.d.ts +2 -2
  121. package/dist/public-types.d.ts.map +1 -1
  122. package/dist/runtime/jobs/monitor-stream.d.ts +9 -1
  123. package/dist/runtime/jobs/monitor-stream.d.ts.map +1 -1
  124. package/dist/runtime/jobs/monitor-stream.js +13 -4
  125. package/dist/runtime/jobs/monitor-stream.js.map +1 -1
  126. package/dist/runtime/jobs/registry.d.ts +4 -0
  127. package/dist/runtime/jobs/registry.d.ts.map +1 -1
  128. package/dist/runtime/jobs/registry.js +12 -2
  129. package/dist/runtime/jobs/registry.js.map +1 -1
  130. package/dist/runtime/query/auto-review/git-status.d.ts.map +1 -1
  131. package/dist/runtime/query/auto-review/git-status.js +3 -2
  132. package/dist/runtime/query/auto-review/git-status.js.map +1 -1
  133. package/dist/runtime/query/executor.d.ts +16 -6
  134. package/dist/runtime/query/executor.d.ts.map +1 -1
  135. package/dist/runtime/query/executor.js +60 -5
  136. package/dist/runtime/query/executor.js.map +1 -1
  137. package/dist/runtime/query/index.d.ts.map +1 -1
  138. package/dist/runtime/query/index.js +2 -2
  139. package/dist/runtime/query/index.js.map +1 -1
  140. package/dist/runtime/query/iteration/outstanding-work.d.ts.map +1 -1
  141. package/dist/runtime/query/iteration/outstanding-work.js +14 -4
  142. package/dist/runtime/query/iteration/outstanding-work.js.map +1 -1
  143. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  144. package/dist/runtime/query/iteration/phases/compaction.js +11 -1
  145. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  146. package/dist/runtime/query/iteration/phases/tool-review.d.ts +2 -0
  147. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  148. package/dist/runtime/query/iteration/phases/tool-review.js +19 -8
  149. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  150. package/dist/runtime/query/path-escalation.d.ts +6 -0
  151. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  152. package/dist/runtime/query/path-escalation.js +58 -4
  153. package/dist/runtime/query/path-escalation.js.map +1 -1
  154. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  155. package/dist/runtime/query/review-policy.js +4 -2
  156. package/dist/runtime/query/review-policy.js.map +1 -1
  157. package/dist/runtime/query/steering.d.ts +11 -2
  158. package/dist/runtime/query/steering.d.ts.map +1 -1
  159. package/dist/runtime/query/steering.js +18 -4
  160. package/dist/runtime/query/steering.js.map +1 -1
  161. package/dist/sandbox/provider/local.d.ts.map +1 -1
  162. package/dist/sandbox/provider/local.js +3 -1
  163. package/dist/sandbox/provider/local.js.map +1 -1
  164. package/dist/schedules/describe.d.ts.map +1 -1
  165. package/dist/schedules/describe.js +2 -0
  166. package/dist/schedules/describe.js.map +1 -1
  167. package/dist/schedules/evaluate.d.ts +4 -0
  168. package/dist/schedules/evaluate.d.ts.map +1 -1
  169. package/dist/schedules/evaluate.js +26 -1
  170. package/dist/schedules/evaluate.js.map +1 -1
  171. package/dist/schedules/index.d.ts +3 -1
  172. package/dist/schedules/index.d.ts.map +1 -1
  173. package/dist/schedules/index.js +2 -1
  174. package/dist/schedules/index.js.map +1 -1
  175. package/dist/schedules/next-fire.d.ts.map +1 -1
  176. package/dist/schedules/next-fire.js +10 -0
  177. package/dist/schedules/next-fire.js.map +1 -1
  178. package/dist/schedules/spec.d.ts +9 -0
  179. package/dist/schedules/spec.d.ts.map +1 -1
  180. package/dist/schedules/spec.js +33 -0
  181. package/dist/schedules/spec.js.map +1 -1
  182. package/dist/schedules/types.d.ts +32 -4
  183. package/dist/schedules/types.d.ts.map +1 -1
  184. package/dist/schedules/types.js +3 -2
  185. package/dist/schedules/types.js.map +1 -1
  186. package/dist/schedules/watch.d.ts +23 -0
  187. package/dist/schedules/watch.d.ts.map +1 -0
  188. package/dist/schedules/watch.js +46 -0
  189. package/dist/schedules/watch.js.map +1 -0
  190. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  191. package/dist/session/workspace/git-worktree.js +2 -1
  192. package/dist/session/workspace/git-worktree.js.map +1 -1
  193. package/dist/skills/arguments.d.ts +58 -0
  194. package/dist/skills/arguments.d.ts.map +1 -0
  195. package/dist/skills/arguments.js +208 -0
  196. package/dist/skills/arguments.js.map +1 -0
  197. package/dist/skills/index.d.ts +3 -1
  198. package/dist/skills/index.d.ts.map +1 -1
  199. package/dist/skills/index.js +1 -0
  200. package/dist/skills/index.js.map +1 -1
  201. package/dist/skills/inline-shell.d.ts +17 -0
  202. package/dist/skills/inline-shell.d.ts.map +1 -1
  203. package/dist/skills/inline-shell.js +1232 -14
  204. package/dist/skills/inline-shell.js.map +1 -1
  205. package/dist/tools/builtins/bash-cwd.d.ts.map +1 -1
  206. package/dist/tools/builtins/bash-cwd.js +2 -0
  207. package/dist/tools/builtins/bash-cwd.js.map +1 -1
  208. package/dist/tools/builtins/bash.d.ts.map +1 -1
  209. package/dist/tools/builtins/bash.js +79 -11
  210. package/dist/tools/builtins/bash.js.map +1 -1
  211. package/dist/tools/builtins/exit-semantics.d.ts +6 -0
  212. package/dist/tools/builtins/exit-semantics.d.ts.map +1 -1
  213. package/dist/tools/builtins/exit-semantics.js +10 -0
  214. package/dist/tools/builtins/exit-semantics.js.map +1 -1
  215. package/dist/tools/builtins/glob.d.ts.map +1 -1
  216. package/dist/tools/builtins/glob.js +68 -13
  217. package/dist/tools/builtins/glob.js.map +1 -1
  218. package/dist/tools/builtins/grep.d.ts.map +1 -1
  219. package/dist/tools/builtins/grep.js +37 -12
  220. package/dist/tools/builtins/grep.js.map +1 -1
  221. package/dist/tools/builtins/index.d.ts +11 -0
  222. package/dist/tools/builtins/index.d.ts.map +1 -1
  223. package/dist/tools/builtins/index.js +14 -0
  224. package/dist/tools/builtins/index.js.map +1 -1
  225. package/dist/tools/builtins/job.js +1 -1
  226. package/dist/tools/builtins/job.js.map +1 -1
  227. package/dist/tools/builtins/monitor.d.ts +1 -1
  228. package/dist/tools/builtins/monitor.d.ts.map +1 -1
  229. package/dist/tools/builtins/monitor.js +4 -2
  230. package/dist/tools/builtins/monitor.js.map +1 -1
  231. package/dist/tools/builtins/notebook-cells.d.ts +31 -0
  232. package/dist/tools/builtins/notebook-cells.d.ts.map +1 -0
  233. package/dist/tools/builtins/notebook-cells.js +160 -0
  234. package/dist/tools/builtins/notebook-cells.js.map +1 -0
  235. package/dist/tools/builtins/notebook-edit.d.ts +8 -0
  236. package/dist/tools/builtins/notebook-edit.d.ts.map +1 -0
  237. package/dist/tools/builtins/notebook-edit.js +249 -0
  238. package/dist/tools/builtins/notebook-edit.js.map +1 -0
  239. package/dist/tools/builtins/notebook-guard.d.ts.map +1 -1
  240. package/dist/tools/builtins/notebook-guard.js +2 -1
  241. package/dist/tools/builtins/notebook-guard.js.map +1 -1
  242. package/dist/tools/builtins/push-notification.d.ts +49 -0
  243. package/dist/tools/builtins/push-notification.d.ts.map +1 -0
  244. package/dist/tools/builtins/push-notification.js +107 -0
  245. package/dist/tools/builtins/push-notification.js.map +1 -0
  246. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  247. package/dist/tools/builtins/read-file.js +8 -3
  248. package/dist/tools/builtins/read-file.js.map +1 -1
  249. package/dist/tools/builtins/read-media.d.ts.map +1 -1
  250. package/dist/tools/builtins/read-media.js +2 -1
  251. package/dist/tools/builtins/read-media.js.map +1 -1
  252. package/dist/tools/builtins/read-render.d.ts.map +1 -1
  253. package/dist/tools/builtins/read-render.js +5 -3
  254. package/dist/tools/builtins/read-render.js.map +1 -1
  255. package/dist/tools/builtins/search-support.d.ts +6 -4
  256. package/dist/tools/builtins/search-support.d.ts.map +1 -1
  257. package/dist/tools/builtins/search-support.js +15 -3
  258. package/dist/tools/builtins/search-support.js.map +1 -1
  259. package/dist/tools/builtins/skill.d.ts.map +1 -1
  260. package/dist/tools/builtins/skill.js +28 -8
  261. package/dist/tools/builtins/skill.js.map +1 -1
  262. package/dist/tools/builtins/sleep-guard.d.ts +20 -0
  263. package/dist/tools/builtins/sleep-guard.d.ts.map +1 -1
  264. package/dist/tools/builtins/sleep-guard.js +125 -1
  265. package/dist/tools/builtins/sleep-guard.js.map +1 -1
  266. package/dist/tools/builtins/wait-for-job.js +1 -1
  267. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  268. package/dist/tools/builtins/web.d.ts +2 -0
  269. package/dist/tools/builtins/web.d.ts.map +1 -1
  270. package/dist/tools/builtins/web.js +97 -3
  271. package/dist/tools/builtins/web.js.map +1 -1
  272. package/dist/tools/command-shell.d.ts +50 -0
  273. package/dist/tools/command-shell.d.ts.map +1 -1
  274. package/dist/tools/command-shell.js +145 -0
  275. package/dist/tools/command-shell.js.map +1 -1
  276. package/dist/tools/env-scrub.d.ts +2 -0
  277. package/dist/tools/env-scrub.d.ts.map +1 -1
  278. package/dist/tools/env-scrub.js +15 -1
  279. package/dist/tools/env-scrub.js.map +1 -1
  280. package/dist/tools/git-config-env.d.ts +55 -0
  281. package/dist/tools/git-config-env.d.ts.map +1 -0
  282. package/dist/tools/git-config-env.js +130 -0
  283. package/dist/tools/git-config-env.js.map +1 -0
  284. package/dist/tools/schedules/schedule-tool.d.ts +7 -0
  285. package/dist/tools/schedules/schedule-tool.d.ts.map +1 -1
  286. package/dist/tools/schedules/schedule-tool.js +72 -3
  287. package/dist/tools/schedules/schedule-tool.js.map +1 -1
  288. package/dist/tools/schedules/types.d.ts +38 -2
  289. package/dist/tools/schedules/types.d.ts.map +1 -1
  290. package/dist/types/connector/mcp.d.ts +24 -0
  291. package/dist/types/connector/mcp.d.ts.map +1 -1
  292. package/dist/types/message/index.d.ts +21 -1
  293. package/dist/types/message/index.d.ts.map +1 -1
  294. package/dist/types/message/index.js +37 -2
  295. package/dist/types/message/index.js.map +1 -1
  296. package/dist/types/plugin/index.d.ts +10 -2
  297. package/dist/types/plugin/index.d.ts.map +1 -1
  298. package/dist/types/plugin/index.js.map +1 -1
  299. package/dist/types/tool/index.d.ts +6 -0
  300. package/dist/types/tool/index.d.ts.map +1 -1
  301. package/dist/types/tool/index.js.map +1 -1
  302. package/dist/utils/plain-terminal-text.d.ts +21 -0
  303. package/dist/utils/plain-terminal-text.d.ts.map +1 -0
  304. package/dist/utils/plain-terminal-text.js +156 -0
  305. package/dist/utils/plain-terminal-text.js.map +1 -0
  306. package/package.json +1 -1
  307. package/src/authorization/bare-repository.ts +70 -0
  308. package/src/authorization/command-line.ts +18 -4
  309. package/src/authorization/gate.ts +11 -0
  310. package/src/authorization/protected-paths.ts +45 -1
  311. package/src/authorization/readonly-commands.ts +75 -6
  312. package/src/authorization/readonly-flags.ts +103 -0
  313. package/src/authorization/shell-lexer.ts +126 -3
  314. package/src/authorization/shell-paths.ts +386 -0
  315. package/src/authorization/shell-session-state.ts +97 -0
  316. package/src/authorization/shell-session.ts +23 -0
  317. package/src/authorization/skill-grant.ts +1 -0
  318. package/src/compaction/extractor.ts +1 -0
  319. package/src/compaction/hooks.ts +43 -1
  320. package/src/compaction/manual.ts +6 -0
  321. package/src/compaction/restore.ts +3 -2
  322. package/src/config/runtime.ts +7 -0
  323. package/src/connector/mcp/client.ts +61 -4
  324. package/src/connector/web/types.ts +8 -0
  325. package/src/constants/compaction/index.ts +1 -1
  326. package/src/execution/code-runtime/worker-program.ts +9 -5
  327. package/src/execution/local.ts +6 -1
  328. package/src/peers/index.ts +8 -2
  329. package/src/peers/record.ts +45 -1
  330. package/src/peers/registry.ts +21 -5
  331. package/src/plugin/bin-path.ts +149 -0
  332. package/src/plugin/common-layout/read.ts +1 -1
  333. package/src/plugin/common-layout-names.ts +0 -1
  334. package/src/plugin/hook-module/scan.ts +74 -2
  335. package/src/plugin/hook-module/worker-source.ts +56 -0
  336. package/src/plugin/lifecycle.ts +67 -0
  337. package/src/plugin/shell-hook-tool-names.ts +1 -0
  338. package/src/plugin/shell-hook.ts +23 -4
  339. package/src/public-runtime.ts +21 -0
  340. package/src/public-tools.ts +32 -1
  341. package/src/public-types.ts +3 -1
  342. package/src/runtime/jobs/monitor-stream.ts +18 -4
  343. package/src/runtime/jobs/registry.ts +22 -2
  344. package/src/runtime/query/auto-review/git-status.ts +3 -2
  345. package/src/runtime/query/executor.ts +79 -5
  346. package/src/runtime/query/index.ts +5 -2
  347. package/src/runtime/query/iteration/outstanding-work.ts +22 -4
  348. package/src/runtime/query/iteration/phases/compaction.ts +14 -1
  349. package/src/runtime/query/iteration/phases/tool-review.ts +24 -7
  350. package/src/runtime/query/path-escalation.ts +52 -4
  351. package/src/runtime/query/review-policy.ts +5 -2
  352. package/src/runtime/query/steering.ts +32 -4
  353. package/src/sandbox/provider/local.ts +3 -1
  354. package/src/schedules/describe.ts +2 -0
  355. package/src/schedules/evaluate.ts +29 -1
  356. package/src/schedules/index.ts +9 -1
  357. package/src/schedules/next-fire.ts +9 -0
  358. package/src/schedules/spec.ts +42 -0
  359. package/src/schedules/types.ts +33 -3
  360. package/src/schedules/watch.ts +71 -0
  361. package/src/session/workspace/git-worktree.ts +3 -1
  362. package/src/skills/arguments.ts +250 -0
  363. package/src/skills/index.ts +10 -0
  364. package/src/skills/inline-shell.ts +1268 -14
  365. package/src/tools/builtins/bash-cwd.ts +2 -0
  366. package/src/tools/builtins/bash.ts +93 -13
  367. package/src/tools/builtins/exit-semantics.ts +10 -0
  368. package/src/tools/builtins/glob.ts +79 -15
  369. package/src/tools/builtins/grep.ts +37 -10
  370. package/src/tools/builtins/index.ts +15 -0
  371. package/src/tools/builtins/job.ts +1 -1
  372. package/src/tools/builtins/monitor.ts +4 -2
  373. package/src/tools/builtins/notebook-cells.ts +196 -0
  374. package/src/tools/builtins/notebook-edit.ts +280 -0
  375. package/src/tools/builtins/notebook-guard.ts +2 -1
  376. package/src/tools/builtins/push-notification.ts +138 -0
  377. package/src/tools/builtins/read-file.ts +9 -3
  378. package/src/tools/builtins/read-media.ts +2 -1
  379. package/src/tools/builtins/read-render.ts +5 -3
  380. package/src/tools/builtins/search-support.ts +17 -3
  381. package/src/tools/builtins/skill.ts +27 -7
  382. package/src/tools/builtins/sleep-guard.ts +128 -1
  383. package/src/tools/builtins/wait-for-job.ts +1 -1
  384. package/src/tools/builtins/web.ts +100 -3
  385. package/src/tools/command-shell.ts +166 -0
  386. package/src/tools/env-scrub.ts +13 -1
  387. package/src/tools/git-config-env.ts +143 -0
  388. package/src/tools/schedules/schedule-tool.ts +79 -3
  389. package/src/tools/schedules/types.ts +47 -9
  390. package/src/types/connector/mcp.ts +25 -0
  391. package/src/types/message/index.ts +53 -1
  392. package/src/types/plugin/index.ts +10 -2
  393. package/src/types/tool/index.ts +6 -0
  394. package/src/utils/plain-terminal-text.ts +142 -0
@@ -1,11 +1,15 @@
1
1
  import { withheldEnvNoticeText } from '../../tools/env-scrub.js'
2
- import { createRuntimeContextMessage } from '../../types/message/index.js'
2
+ import {
3
+ type RuntimeContextOriginKind,
4
+ createRuntimeContextMessage,
5
+ } from '../../types/message/index.js'
3
6
  import type { Message, UserMessage } from '../../types/message/index.js'
4
7
  import { NOTICE_TAG, frameNotice, readOperatorNotice } from '../../types/message/notice-frame.js'
5
8
  import {
6
9
  MONITOR_EVENT_CONTENT_MAX_CHARS,
7
10
  MONITOR_NOTIFICATION_MAX_CHARS,
8
11
  } from '../jobs/monitor-stream.js'
12
+ import { formatMonitorDuration } from '../jobs/monitor-stream.js'
9
13
  import { type BackgroundJob, type MonitorEvent, describeMonitorEnd } from '../jobs/registry.js'
10
14
  import { formatSystemEvent, oneMetadataLine } from '../system-events.js'
11
15
 
@@ -55,6 +59,11 @@ export interface SteeringChannel {
55
59
  * not send a blank message.
56
60
  */
57
61
  steer(text: string): void
62
+ /**
63
+ * What the undelivered text is about (the ids it was queued under), taken
64
+ * without draining. Optional: a host's own channel need not say.
65
+ */
66
+ keys?(): readonly string[]
58
67
 
59
68
  /** Take everything queued, leaving the channel empty. */
60
69
  drain(): string | undefined
@@ -86,6 +95,12 @@ export class SteeringBinding implements SteeringChannel {
86
95
  return this.queued.length !== before
87
96
  }
88
97
 
98
+ keys(): readonly string[] {
99
+ return [
100
+ ...new Set(this.queued.flatMap((entry) => (entry.key === undefined ? [] : [entry.key]))),
101
+ ]
102
+ }
103
+
89
104
  drain(): string | undefined {
90
105
  if (this.queued.length === 0) return undefined
91
106
  const joined = this.queued.map((entry) => entry.text).join('\n')
@@ -113,7 +128,7 @@ export const JOB_NOTICE_INLINE_OUTPUT_MAX_BYTES = 2048
113
128
  */
114
129
  export function formatJobExitNotice(
115
130
  job: Pick<BackgroundJob, 'id' | 'command' | 'status' | 'exitCode' | 'signal'> &
116
- Partial<Pick<BackgroundJob, 'exitedAt'>>,
131
+ Partial<Pick<BackgroundJob, 'exitedAt' | 'startedAt' | 'outputFile'>>,
117
132
  output?: {
118
133
  readonly chunk: string
119
134
  readonly nextOffset: number
@@ -125,7 +140,12 @@ export function formatJobExitNotice(
125
140
  ? 'was stopped'
126
141
  : `exited with code ${job.exitCode ?? 'unknown'}${job.signal ? ` (${job.signal})` : ''}`
127
142
  const endedAt = job.exitedAt === undefined ? '' : ` at ${new Date(job.exitedAt).toISOString()}`
128
- const head = `Background job ${job.id} (${job.command}) ${outcome}${endedAt}.`
143
+ const ran =
144
+ job.exitedAt !== undefined && job.startedAt !== undefined
145
+ ? ` after ${formatMonitorDuration(Math.max(0, job.exitedAt - job.startedAt))}`
146
+ : ''
147
+ const saved = job.outputFile === undefined ? '' : ` Its output is saved to ${job.outputFile}.`
148
+ const head = `Background job ${job.id} (${job.command}) ${outcome}${endedAt}${ran}.${saved}`
129
149
  if (
130
150
  output === undefined ||
131
151
  output.chunk.length === 0 ||
@@ -399,12 +419,20 @@ export function takeNoticeMessage(
399
419
  * here, and a premature drop would strand the exit.
400
420
  */
401
421
  onDelivered?: () => void,
422
+ /** The typed origin the recorded message carries: which kind of news, and the jobs it names. */
423
+ originKind?: RuntimeContextOriginKind,
402
424
  ): UserMessage | undefined {
403
425
  if (!channel?.pending || !hasToolResult(messages)) return undefined
426
+ // Read before the drain empties the queue.
427
+ const jobIds = originKind ? (channel.keys?.() ?? []) : []
404
428
  const text = channel.drain()
405
429
  if (text === undefined) return undefined
406
430
  onDelivered?.()
407
- return createRuntimeContextMessage(format(text), 'job-exit')
431
+ return createRuntimeContextMessage(
432
+ format(text),
433
+ 'job-exit',
434
+ originKind ? [{ kind: originKind, jobIds }] : undefined,
435
+ )
408
436
  }
409
437
 
410
438
  /**
@@ -28,6 +28,7 @@ import {
28
28
  // every bug the original's comment was written to record.
29
29
  import { killTree } from '../../process/kill-tree.js'
30
30
  import { SESSION_CHILD_ENV } from '../../process/session-child.js'
31
+ import { withSafeGitConfig } from '../../tools/git-config-env.js'
31
32
  import { resolveWithinAny, resolveWithinAnyReal } from '../../tools/paths.js'
32
33
  import type { SandboxId } from '../../types/ids/index.js'
33
34
  import type {
@@ -605,7 +606,8 @@ export function buildSafeEnv(
605
606
  setEnvironmentEntry(env, SESSION_CHILD_ENV, '1')
606
607
 
607
608
  // A shell inside the sandbox can run `node` when the user's PATH has none.
608
- return withNodeOnPath(env)
609
+ // And git inside it ignores a folder that only looks like a repository.
610
+ return withSafeGitConfig(withNodeOnPath(env))
609
611
  }
610
612
 
611
613
  /**
@@ -125,6 +125,8 @@ export function describeSchedule(
125
125
  return `once at ${formatWall(Date.parse(spec.at), tz)} (${tz})`
126
126
  case 'every':
127
127
  return describeInterval(spec.everyMs)
128
+ case 'watch':
129
+ return `when ${spec.uri} changes on the tool server ${spec.server} (at most one run every ${describeInterval(spec.minIntervalMs).replace(/^every /, '')}; paused past ${spec.maxEventsPerHour} updates an hour)`
128
130
  case 'cron': {
129
131
  let e: CronExpression
130
132
  try {
@@ -24,6 +24,10 @@
24
24
  * `missed` record; older than the window, nothing fires.
25
25
  * 5. An unfinished run of the same job skips what came due meanwhile.
26
26
  * 6. A provider quota hold skips what comes due before the hold ends.
27
+ * 7. A job with `expiresAt` never fires an occurrence at or after it. The
28
+ * first evaluation at or after that instant expires the job, in any
29
+ * state, and records what came due before it as one `job-expired` skip:
30
+ * a job past its time box does not run, not even to catch up.
27
31
  */
28
32
 
29
33
  import { countOccurrences, nextFireTime, previousFireTime } from './next-fire.js'
@@ -64,11 +68,15 @@ export function evaluateJob(input: ScheduleEvaluationInput): ScheduleDecision {
64
68
  if (state.jobRevision !== undefined && state.jobRevision !== job.revision) {
65
69
  baseMs = Math.max(baseMs, Date.parse(job.updatedAt))
66
70
  }
71
+ const expiresMs = job.expiresAt === undefined ? Number.NaN : Date.parse(job.expiresAt)
72
+ const timeBoxed = Number.isFinite(expiresMs)
67
73
  const nextState = (evaluatedMs: number): ScheduleDecision['nextState'] => {
68
74
  const next = nextFireTime(job.spec, new Date(evaluatedMs))
75
+ // A time at or after the time box is not a next run.
76
+ const within = next && !(timeBoxed && next.getTime() >= expiresMs)
69
77
  return {
70
78
  lastEvaluatedAt: new Date(evaluatedMs),
71
- ...(next ? { nextFireAt: next } : {}),
79
+ ...(within ? { nextFireAt: next } : {}),
72
80
  jobRevision: job.revision,
73
81
  }
74
82
  }
@@ -82,6 +90,26 @@ export function evaluateJob(input: ScheduleEvaluationInput): ScheduleDecision {
82
90
  // Rule 2: a clock that went backwards decides nothing new.
83
91
  if (nowMs <= baseMs) return { skip: [], nextState: nextState(baseMs) }
84
92
 
93
+ // Rule 7: past the time box nothing fires, and the job is done.
94
+ if (timeBoxed && nowMs >= expiresMs) {
95
+ // Occurrences strictly before the box closed (ranges count `(from, to]`).
96
+ const before =
97
+ expiresMs - 1 > baseMs
98
+ ? countOccurrences(job.spec, new Date(baseMs), new Date(expiresMs - 1))
99
+ : undefined
100
+ return {
101
+ skip:
102
+ before && before.count > 0 && before.latest
103
+ ? [{ scheduledFor: before.latest, reason: 'job-expired', count: before.count }]
104
+ : [],
105
+ jobTransition: 'expired',
106
+ nextState: {
107
+ lastEvaluatedAt: new Date(nowMs),
108
+ jobRevision: job.revision,
109
+ },
110
+ }
111
+ }
112
+
85
113
  const due = countOccurrences(job.spec, new Date(baseMs), now)
86
114
  if (due.count === 0 || !due.latest) {
87
115
  if (job.spec.kind === 'at' && Date.parse(job.spec.at) <= baseMs && job.state !== 'active') {
@@ -12,7 +12,15 @@ export {
12
12
  nextFireTime,
13
13
  previousFireTime,
14
14
  } from './next-fire.js'
15
- export { parseDuration, parseScheduleSpec, upcomingFireTimes } from './spec.js'
15
+ export { parseDuration, parseScheduleExpiry, parseScheduleSpec, upcomingFireTimes } from './spec.js'
16
16
  export type { ParseScheduleOptions } from './spec.js'
17
17
  export { hostTimeZone, validateTimeZone } from './tz.js'
18
+ export {
19
+ SCHEDULE_WATCH_DEFAULT_INTERVAL_MS,
20
+ SCHEDULE_WATCH_DEFAULT_MAX_EVENTS_PER_HOUR,
21
+ SCHEDULE_WATCH_MAX_EVENTS_PER_HOUR,
22
+ SCHEDULE_WATCH_MIN_INTERVAL_MS,
23
+ parseWatchSpec,
24
+ } from './watch.js'
25
+ export type { ParseWatchOptions } from './watch.js'
18
26
  export type * from './types.js'
@@ -117,6 +117,9 @@ export function nextFireTime(spec: ScheduleSpec, afterExclusive: Date): Date | n
117
117
  const at = Date.parse(spec.at)
118
118
  return Number.isFinite(at) && at > after ? new Date(at) : null
119
119
  }
120
+ // A watch has no times: the host's subscription starts its runs.
121
+ case 'watch':
122
+ return null
120
123
  case 'every': {
121
124
  const anchor = validEvery(spec)
122
125
  const k = after < anchor ? 1 : Math.floor((after - anchor) / spec.everyMs) + 1
@@ -147,6 +150,8 @@ export function previousFireTime(spec: ScheduleSpec, atOrBefore: Date): Date | n
147
150
  const at = Date.parse(spec.at)
148
151
  return Number.isFinite(at) && at <= before ? new Date(at) : null
149
152
  }
153
+ case 'watch':
154
+ return null
150
155
  case 'every': {
151
156
  const anchor = validEvery(spec)
152
157
  const k = Math.floor((before - anchor) / spec.everyMs)
@@ -189,6 +194,8 @@ export function countOccurrences(
189
194
  ? { count: 1, capped: false, first: new Date(at), latest: new Date(at) }
190
195
  : { count: 0, capped: false }
191
196
  }
197
+ case 'watch':
198
+ return { count: 0, capped: false }
192
199
  case 'every': {
193
200
  const anchor = validEvery(spec)
194
201
  const firstK = from < anchor ? 1 : Math.floor((from - anchor) / spec.everyMs) + 1
@@ -242,6 +249,8 @@ export function countOccurrences(
242
249
 
243
250
  /** Validate a spec as a whole: its zone, its expression, and that it can ever fire after `now`. */
244
251
  export function assertSpecFires(spec: ScheduleSpec, now: Date): void {
252
+ // A watch fires on an event, not on a time; its fields are checked by `parseWatchSpec`.
253
+ if (spec.kind === 'watch') return
245
254
  if (spec.kind === 'cron') {
246
255
  validateTimeZone(spec.tz)
247
256
  cronOf(spec.expr)
@@ -208,3 +208,45 @@ export function upcomingFireTimes(spec: ScheduleSpec, after: Date, count = 3): D
208
208
  }
209
209
  return out
210
210
  }
211
+
212
+ /**
213
+ * Turn the words for a job's time box into one absolute instant (ISO-8601
214
+ * UTC), written down at creation so `in 7d` means seven days from now and not
215
+ * from every later read. The words are a time: `in 7d`, `at 2026-12-31 17:00`
216
+ * (read in `tz`), a bare `2026-12-31 17:00` or an ISO instant. A repeating
217
+ * schedule is refused. The instant must be after the spec's first run, or the
218
+ * job would end before it ran once.
219
+ */
220
+ export function parseScheduleExpiry(
221
+ input: string,
222
+ spec: ScheduleSpec,
223
+ options: ParseScheduleOptions = {},
224
+ ): string {
225
+ const now = options.now ?? new Date()
226
+ const text = input.trim()
227
+ if (text === '') throw new ScheduleValidationError('expires needs a time', '')
228
+ const lower = text.toLowerCase()
229
+ const words = lower.startsWith('in ') || lower.startsWith('at ') ? text : `at ${text}`
230
+ let parsed: ScheduleSpec
231
+ try {
232
+ parsed = parseScheduleSpec(words, options)
233
+ } catch (error) {
234
+ if (error instanceof ScheduleValidationError)
235
+ throw new ScheduleValidationError(`expires: ${error.message}`, error.token)
236
+ throw error
237
+ }
238
+ if (parsed.kind !== 'at') {
239
+ throw new ScheduleValidationError(
240
+ 'expires is a time (in 7d, at 2026-12-31 17:00), not a repeating schedule',
241
+ text,
242
+ )
243
+ }
244
+ const first = nextFireTime(spec, now)
245
+ if (first && Date.parse(parsed.at) <= first.getTime()) {
246
+ throw new ScheduleValidationError(
247
+ `expires ${parsed.at} is not after the first run (${first.toISOString()}); the job would end before it ran`,
248
+ text,
249
+ )
250
+ }
251
+ return parsed.at
252
+ }
@@ -4,8 +4,9 @@
4
4
  * The SDK owns WHEN something is due and nothing about how a host stores a
5
5
  * job or runs it: the CLI keeps its job files, claims and history records to
6
6
  * itself, so its on-disk format is not SDK API. The unions exported here
7
- * (`ScheduleDecision`, `ScheduleSkipReason`, `ScheduleMissedReason`) may grow
8
- * in a minor release; switch over them with a `default:` branch.
7
+ * (`ScheduleSpec`, `ScheduleDecision`, `ScheduleSkipReason`,
8
+ * `ScheduleMissedReason`) may grow in a minor release; switch over them with
9
+ * a `default:` branch.
9
10
  */
10
11
 
11
12
  /** A single instant (ISO-8601 UTC). */
@@ -34,7 +35,29 @@ export interface ScheduleCronSpec {
34
35
  readonly tz: string
35
36
  }
36
37
 
37
- export type ScheduleSpec = ScheduleAtSpec | ScheduleEverySpec | ScheduleCronSpec
38
+ /**
39
+ * Not a time: the job wakes when one resource of one tool server changes.
40
+ * The evaluator never finds an occurrence for it (the host's watch is what
41
+ * starts a run), so the time engine reports no next run and a time box, a
42
+ * pause or a pending confirmation still apply as for any job.
43
+ */
44
+ export interface ScheduleWatchSpec {
45
+ readonly kind: 'watch'
46
+ /** The tool server's configured name. */
47
+ readonly server: string
48
+ /** The resource's address, exactly as the server lists it. */
49
+ readonly uri: string
50
+ /**
51
+ * At least this long between two runs; updates that arrive meanwhile
52
+ * collapse into the next run. Whole seconds, at least
53
+ * {@link SCHEDULE_WATCH_MIN_INTERVAL_MS}.
54
+ */
55
+ readonly minIntervalMs: number
56
+ /** More updates than this in one hour pause the job. A positive whole number. */
57
+ readonly maxEventsPerHour: number
58
+ }
59
+
60
+ export type ScheduleSpec = ScheduleAtSpec | ScheduleEverySpec | ScheduleCronSpec | ScheduleWatchSpec
38
61
 
39
62
  /** A parsed cron expression: each field as the sorted set of values it allows. */
40
63
  export interface CronExpression {
@@ -67,6 +90,7 @@ export type ScheduleSkipReason =
67
90
  | 'beyond-catch-up-window'
68
91
  | 'one-shot-expired'
69
92
  | 'quota-hold'
93
+ | 'job-expired'
70
94
 
71
95
  /** Why occurrences were missed. Best effort; may grow in a minor release. */
72
96
  export type ScheduleMissedReason = 'daemon-not-running' | 'machine-asleep' | 'clock-jumped-forward'
@@ -89,6 +113,12 @@ export interface ScheduleEvaluationJob {
89
113
  readonly updatedAt: string
90
114
  /** Bumped on every definition change. */
91
115
  readonly revision: number
116
+ /**
117
+ * The job's time box, ISO-8601 UTC. An occurrence at or after this instant
118
+ * never fires, and the first evaluation at or after it ends the job
119
+ * (`jobTransition: 'expired'`), whatever state it was in.
120
+ */
121
+ readonly expiresAt?: string
92
122
  }
93
123
 
94
124
  /** What the host remembers between evaluations of one job. */
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The watch kind of {@link ScheduleSpec}: a job that wakes when one resource
3
+ * of one tool server changes. The SDK owns what a valid watch is; the host
4
+ * owns the subscription, what it reads and how it starts a run.
5
+ */
6
+
7
+ import { ScheduleValidationError } from './errors.js'
8
+ import type { ScheduleWatchSpec } from './types.js'
9
+
10
+ /** The shortest gap a watch may keep between two runs: one minute. */
11
+ export const SCHEDULE_WATCH_MIN_INTERVAL_MS = 60_000
12
+ /** The gap when none is given: five minutes. */
13
+ export const SCHEDULE_WATCH_DEFAULT_INTERVAL_MS = 5 * 60_000
14
+ /** Updates in one hour past which a watch pauses its job, when none is given. */
15
+ export const SCHEDULE_WATCH_DEFAULT_MAX_EVENTS_PER_HOUR = 60
16
+ /** The most a watch may be told to accept in an hour. */
17
+ export const SCHEDULE_WATCH_MAX_EVENTS_PER_HOUR = 3_600
18
+
19
+ export interface ParseWatchOptions {
20
+ readonly server: string
21
+ readonly uri: string
22
+ readonly minIntervalMs?: number
23
+ readonly maxEventsPerHour?: number
24
+ }
25
+
26
+ /** Control and hidden characters: no name or address a person confirms may carry one. */
27
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: that is the point
28
+ const UNSEEN = /[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁠-⁤]/
29
+
30
+ /** A validated watch spec, or a {@link ScheduleValidationError} saying what to fix. */
31
+ export function parseWatchSpec(options: ParseWatchOptions): ScheduleWatchSpec {
32
+ const server = options.server.trim()
33
+ const uri = options.uri.trim()
34
+ if (server === '') throw new ScheduleValidationError('a watch needs the tool server to watch', '')
35
+ if (uri === '') throw new ScheduleValidationError('a watch needs the resource to watch', '')
36
+ if (UNSEEN.test(server) || server.length > 128) {
37
+ throw new ScheduleValidationError(
38
+ 'the tool server name has a control or hidden character, or is over 128 characters',
39
+ server.slice(0, 40),
40
+ )
41
+ }
42
+ if (UNSEEN.test(uri) || uri.length > 2_048) {
43
+ throw new ScheduleValidationError(
44
+ 'the resource address has a control or hidden character, or is over 2048 characters',
45
+ uri.slice(0, 40),
46
+ )
47
+ }
48
+ const minIntervalMs = options.minIntervalMs ?? SCHEDULE_WATCH_DEFAULT_INTERVAL_MS
49
+ if (
50
+ !Number.isSafeInteger(minIntervalMs) ||
51
+ minIntervalMs < SCHEDULE_WATCH_MIN_INTERVAL_MS ||
52
+ minIntervalMs % 60_000 !== 0
53
+ ) {
54
+ throw new ScheduleValidationError(
55
+ 'the gap between a watch’s runs must be a whole number of minutes, at least one',
56
+ String(minIntervalMs),
57
+ )
58
+ }
59
+ const maxEventsPerHour = options.maxEventsPerHour ?? SCHEDULE_WATCH_DEFAULT_MAX_EVENTS_PER_HOUR
60
+ if (
61
+ !Number.isSafeInteger(maxEventsPerHour) ||
62
+ maxEventsPerHour < 1 ||
63
+ maxEventsPerHour > SCHEDULE_WATCH_MAX_EVENTS_PER_HOUR
64
+ ) {
65
+ throw new ScheduleValidationError(
66
+ `the most updates a watch accepts in an hour must be a whole number from 1 to ${SCHEDULE_WATCH_MAX_EVENTS_PER_HOUR}`,
67
+ String(maxEventsPerHour),
68
+ )
69
+ }
70
+ return { kind: 'watch', server, uri, minIntervalMs, maxEventsPerHour }
71
+ }
@@ -17,6 +17,7 @@ import { realpath } from 'node:fs/promises'
17
17
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
18
18
  import { promisify } from 'node:util'
19
19
  import { NAMZU } from '../../constants/telemetry/index.js'
20
+ import { hostGitEnv } from '../../tools/git-config-env.js'
20
21
  import type { GitWorktreeBackendMeta, WorkspaceRef } from '../../types/workspace/ref.js'
21
22
  import { generateWorkspaceId } from '../../utils/id.js'
22
23
  import { SCOPE_ATTRIBUTE } from '../../utils/log/types.js'
@@ -49,7 +50,8 @@ export interface ExecFileResult {
49
50
  */
50
51
  export type ExecFile = (file: string, args: readonly string[]) => Promise<ExecFileResult>
51
52
 
52
- const defaultExecFile: ExecFile = async (file, args) => execFileAsync(file, [...args])
53
+ const defaultExecFile: ExecFile = async (file, args) =>
54
+ execFileAsync(file, [...args], file === 'git' ? { env: hostGitEnv() } : {})
53
55
 
54
56
  /**
55
57
  * Configuration for {@link GitWorktreeDriver}.
@@ -0,0 +1,250 @@
1
+ /**
2
+ * How a skill or a command file receives the text typed (or sent) after its name.
3
+ *
4
+ * The placeholders a body may hold:
5
+ *
6
+ * - `$ARGUMENTS`, the whole text;
7
+ * - `$0`, `$1`, ... and `$ARGUMENTS[0]`, `$ARGUMENTS[1]`, ..., one word each, where
8
+ * the words are read the way a shell reads a command line (spaces separate, a
9
+ * quote groups, a backslash keeps the next character). A word that does not
10
+ * exist leaves its placeholder as written. `$1` right before a letter, digit or
11
+ * underscore (`$1st`) is not a placeholder.
12
+ * - `\$ARGUMENTS` and `\$1` stand for the text itself, without the backslash.
13
+ *
14
+ * When the text holds none of them and arguments were given, the arguments are
15
+ * appended as a last line, `ARGUMENTS: <value>`, so what was typed is never
16
+ * dropped. That line is plain prompt text: when the body holds shell commands the
17
+ * value goes through the same escaping as every other value, so it can neither
18
+ * start a command nor hide one.
19
+ */
20
+
21
+ import type { ShellDialect } from '../types/tool/index.js'
22
+ import {
23
+ type PlaceholderRead,
24
+ type PlaceholderReader,
25
+ findInlineShell,
26
+ normalizeInlineShellText,
27
+ substituteEscaped,
28
+ } from './inline-shell.js'
29
+
30
+ /** Past this many characters the arguments are split on whitespace instead of read like a shell line. */
31
+ export const SKILL_ARGUMENTS_SHELL_READ_MAX_CHARS = 10_000
32
+
33
+ const ALL = '$ARGUMENTS'
34
+ /** Marks the line that carries arguments no placeholder took. */
35
+ export const SKILL_ARGUMENTS_LINE_LABEL = 'ARGUMENTS: '
36
+
37
+ /**
38
+ * The words of the arguments. Whitespace separates them; single quotes keep
39
+ * everything inside as it is; double quotes group, and a backslash inside them keeps
40
+ * the quote from ending the group; outside quotes a backslash keeps the next
41
+ * character. A quote that never closes, or a text over
42
+ * {@link SKILL_ARGUMENTS_SHELL_READ_MAX_CHARS}, is read by plain whitespace instead.
43
+ */
44
+ export function splitSkillArguments(input: string): string[] {
45
+ const text = input.trim()
46
+ if (text === '') return []
47
+ const plain = (): string[] => text.split(/\s+/).filter((word) => word !== '')
48
+ if (text.length > SKILL_ARGUMENTS_SHELL_READ_MAX_CHARS) return plain()
49
+ const words: string[] = []
50
+ let current = ''
51
+ let inWord = false
52
+ for (let i = 0; i < text.length; i++) {
53
+ const c = text[i] as string
54
+ if (/\s/.test(c)) {
55
+ if (inWord) words.push(current)
56
+ current = ''
57
+ inWord = false
58
+ continue
59
+ }
60
+ inWord = true
61
+ if (c === '\\' && i + 1 < text.length) {
62
+ current += text[i + 1]
63
+ i += 1
64
+ continue
65
+ }
66
+ if (c === "'" || c === '"') {
67
+ let j = i + 1
68
+ let closed = false
69
+ for (; j < text.length; j++) {
70
+ const d = text[j] as string
71
+ if (c === '"' && d === '\\' && j + 1 < text.length) {
72
+ j += 1
73
+ continue
74
+ }
75
+ if (d === c) {
76
+ closed = true
77
+ break
78
+ }
79
+ }
80
+ if (!closed) return plain()
81
+ current += text.slice(i + 1, j)
82
+ i = j
83
+ continue
84
+ }
85
+ current += c
86
+ }
87
+ if (inWord) words.push(current)
88
+ return words
89
+ }
90
+
91
+ const WORD_CHAR = /[A-Za-z0-9_]/
92
+
93
+ /** The placeholder reader for a body, given the words of its arguments. */
94
+ function readerFor(
95
+ words: readonly string[],
96
+ variables: Readonly<Record<string, string>>,
97
+ ): PlaceholderReader {
98
+ const names = Object.keys(variables)
99
+ .filter((name) => name.length > 0)
100
+ .sort((a, b) => b.length - a.length)
101
+ return (text, at): PlaceholderRead | undefined => {
102
+ const c = text[at]
103
+ if (c === '\\') {
104
+ // `\$ARGUMENTS` and `\$1` are the text itself, unless the backslash is itself escaped.
105
+ if (text[at + 1] !== '$' || text[at - 1] === '\\') return undefined
106
+ if (text.startsWith(ALL, at + 1) || /\d/.test(text[at + 2] ?? '')) {
107
+ return { kind: 'literal', text: '$', length: 2 }
108
+ }
109
+ return undefined
110
+ }
111
+ if (c !== '$') return undefined
112
+ if (text.startsWith(ALL, at)) {
113
+ const subscriptAt = /\[(\d+)\]/y
114
+ subscriptAt.lastIndex = at + ALL.length
115
+ const subscript = subscriptAt.exec(text)
116
+ // A subscript is never the whole text followed by brackets: a word that does not
117
+ // exist leaves `$ARGUMENTS[7]` as written.
118
+ if (subscript) {
119
+ const written = `${ALL}${subscript[0]}`
120
+ return words[Number(subscript[1])] === undefined
121
+ ? { kind: 'literal', text: written, length: written.length }
122
+ : { kind: 'value', token: written, whole: true }
123
+ }
124
+ return { kind: 'value', token: ALL }
125
+ }
126
+ const digits = /^\d+/.exec(text.slice(at + 1, at + 25))
127
+ if (digits) {
128
+ const after = text[at + 1 + digits[0].length] ?? ''
129
+ if (WORD_CHAR.test(after) || words[Number(digits[0])] === undefined) {
130
+ // Not a placeholder, or one with no word to take: it stays as written, and what
131
+ // follows is read on its own.
132
+ return { kind: 'literal', text: `$${digits[0]}`, length: 1 + digits[0].length }
133
+ }
134
+ return { kind: 'value', token: `$${digits[0]}`, whole: true }
135
+ }
136
+ const name = names.find((candidate) => text.startsWith(candidate, at))
137
+ return name === undefined ? undefined : { kind: 'value', token: name }
138
+ }
139
+ }
140
+
141
+ interface Plan {
142
+ readonly values: Record<string, string>
143
+ /** Whether the body has a placeholder that takes arguments. */
144
+ readonly takes: boolean
145
+ readonly reader: PlaceholderReader
146
+ }
147
+
148
+ /** The values the body's placeholders take, by token. */
149
+ function planFor(
150
+ template: string,
151
+ trimmed: string,
152
+ words: readonly string[],
153
+ variables: Readonly<Record<string, string>>,
154
+ ): Plan {
155
+ const reader = readerFor(words, variables)
156
+ const values: Record<string, string> = {}
157
+ let takes = false
158
+ let i = 0
159
+ while (i < template.length) {
160
+ const found = reader(template, i)
161
+ if (found === undefined) {
162
+ i += 1
163
+ continue
164
+ }
165
+ if (found.kind === 'literal') {
166
+ i += found.length
167
+ continue
168
+ }
169
+ const token = found.token
170
+ if (token in variables) {
171
+ values[token] = variables[token] as string
172
+ } else if (token === ALL) {
173
+ values[token] = trimmed
174
+ takes = true
175
+ } else {
176
+ const index = /\d+/.exec(token)
177
+ values[token] = words[Number(index?.[0])] as string
178
+ takes = true
179
+ }
180
+ i += token.length
181
+ }
182
+ return { values, takes, reader }
183
+ }
184
+
185
+ export interface FillArgumentsOptions {
186
+ /**
187
+ * Other tokens and the text they stand for, such as the skill's folder. They are
188
+ * put in like the arguments (escaped inside a shell command) but never count as
189
+ * taking them.
190
+ */
191
+ readonly variables?: Readonly<Record<string, string>>
192
+ /** Append `ARGUMENTS: <value>` when no placeholder took them. The default is `true`. */
193
+ readonly append?: boolean
194
+ /** The shell that reads the commands in the body; the default is the host's. */
195
+ readonly dialect?: ShellDialect
196
+ /**
197
+ * Escape values for the shell commands in the body. The default is `true`. A host
198
+ * that will not run any command passes `false`: the values go in as plain text, and
199
+ * a value that could not be put inside a command refuses nothing.
200
+ */
201
+ readonly escape?: boolean
202
+ }
203
+
204
+ /** Whether the body has a placeholder that takes arguments (so they need not be appended). */
205
+ export function takesSkillArguments(body: string, args: string | undefined): boolean {
206
+ const trimmed = (args ?? '').trim()
207
+ return planFor(normalizeInlineShellText(body), trimmed, splitSkillArguments(trimmed), {}).takes
208
+ }
209
+
210
+ /**
211
+ * The body with the arguments put in. Throws `InlineShellError` when the body holds
212
+ * shell commands and a value cannot be made safe for them.
213
+ */
214
+ export function fillArguments(
215
+ body: string,
216
+ args: string | undefined,
217
+ options: FillArgumentsOptions = {},
218
+ ): string {
219
+ const variables = options.variables ?? {}
220
+ const trimmed = (args ?? '').trim()
221
+ const words = splitSkillArguments(trimmed)
222
+ const hasShell = options.escape !== false && findInlineShell(body).length > 0
223
+ const base = hasShell ? normalizeInlineShellText(body) : body
224
+ const first = planFor(base, trimmed, words, variables)
225
+ const append = options.append !== false && !first.takes && trimmed !== ''
226
+ const template = append ? `${base}\n\n${SKILL_ARGUMENTS_LINE_LABEL}${ALL}` : base
227
+ const { values, reader } = append ? planFor(template, trimmed, words, variables) : first
228
+ if (hasShell) {
229
+ return substituteEscaped(template, values, {
230
+ ...(options.dialect !== undefined ? { dialect: options.dialect } : {}),
231
+ reader,
232
+ })
233
+ }
234
+ let out = ''
235
+ let i = 0
236
+ while (i < template.length) {
237
+ const found = reader(template, i)
238
+ if (found === undefined) {
239
+ out += template[i]
240
+ i += 1
241
+ } else if (found.kind === 'literal') {
242
+ out += found.text
243
+ i += found.length
244
+ } else {
245
+ out += values[found.token] as string
246
+ i += found.token.length
247
+ }
248
+ }
249
+ return out
250
+ }