@namzu/sdk 70.0.0 → 71.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (409) hide show
  1. package/CHANGELOG.md +123 -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/store/session-index/index.d.ts +5 -0
  206. package/dist/store/session-index/index.d.ts.map +1 -1
  207. package/dist/store/session-index/index.js +5 -1
  208. package/dist/store/session-index/index.js.map +1 -1
  209. package/dist/store/session-index/rebuild.d.ts +18 -0
  210. package/dist/store/session-index/rebuild.d.ts.map +1 -1
  211. package/dist/store/session-index/rebuild.js +79 -5
  212. package/dist/store/session-index/rebuild.js.map +1 -1
  213. package/dist/store/session-index/sqlite.d.ts +8 -0
  214. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  215. package/dist/store/session-index/sqlite.js +23 -1
  216. package/dist/store/session-index/sqlite.js.map +1 -1
  217. package/dist/tools/builtins/bash-cwd.d.ts.map +1 -1
  218. package/dist/tools/builtins/bash-cwd.js +2 -0
  219. package/dist/tools/builtins/bash-cwd.js.map +1 -1
  220. package/dist/tools/builtins/bash.d.ts.map +1 -1
  221. package/dist/tools/builtins/bash.js +79 -11
  222. package/dist/tools/builtins/bash.js.map +1 -1
  223. package/dist/tools/builtins/exit-semantics.d.ts +6 -0
  224. package/dist/tools/builtins/exit-semantics.d.ts.map +1 -1
  225. package/dist/tools/builtins/exit-semantics.js +10 -0
  226. package/dist/tools/builtins/exit-semantics.js.map +1 -1
  227. package/dist/tools/builtins/glob.d.ts.map +1 -1
  228. package/dist/tools/builtins/glob.js +68 -13
  229. package/dist/tools/builtins/glob.js.map +1 -1
  230. package/dist/tools/builtins/grep.d.ts.map +1 -1
  231. package/dist/tools/builtins/grep.js +37 -12
  232. package/dist/tools/builtins/grep.js.map +1 -1
  233. package/dist/tools/builtins/index.d.ts +11 -0
  234. package/dist/tools/builtins/index.d.ts.map +1 -1
  235. package/dist/tools/builtins/index.js +14 -0
  236. package/dist/tools/builtins/index.js.map +1 -1
  237. package/dist/tools/builtins/job.js +1 -1
  238. package/dist/tools/builtins/job.js.map +1 -1
  239. package/dist/tools/builtins/monitor.d.ts +1 -1
  240. package/dist/tools/builtins/monitor.d.ts.map +1 -1
  241. package/dist/tools/builtins/monitor.js +4 -2
  242. package/dist/tools/builtins/monitor.js.map +1 -1
  243. package/dist/tools/builtins/notebook-cells.d.ts +31 -0
  244. package/dist/tools/builtins/notebook-cells.d.ts.map +1 -0
  245. package/dist/tools/builtins/notebook-cells.js +160 -0
  246. package/dist/tools/builtins/notebook-cells.js.map +1 -0
  247. package/dist/tools/builtins/notebook-edit.d.ts +8 -0
  248. package/dist/tools/builtins/notebook-edit.d.ts.map +1 -0
  249. package/dist/tools/builtins/notebook-edit.js +249 -0
  250. package/dist/tools/builtins/notebook-edit.js.map +1 -0
  251. package/dist/tools/builtins/notebook-guard.d.ts.map +1 -1
  252. package/dist/tools/builtins/notebook-guard.js +2 -1
  253. package/dist/tools/builtins/notebook-guard.js.map +1 -1
  254. package/dist/tools/builtins/push-notification.d.ts +49 -0
  255. package/dist/tools/builtins/push-notification.d.ts.map +1 -0
  256. package/dist/tools/builtins/push-notification.js +107 -0
  257. package/dist/tools/builtins/push-notification.js.map +1 -0
  258. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  259. package/dist/tools/builtins/read-file.js +8 -3
  260. package/dist/tools/builtins/read-file.js.map +1 -1
  261. package/dist/tools/builtins/read-media.d.ts.map +1 -1
  262. package/dist/tools/builtins/read-media.js +2 -1
  263. package/dist/tools/builtins/read-media.js.map +1 -1
  264. package/dist/tools/builtins/read-render.d.ts.map +1 -1
  265. package/dist/tools/builtins/read-render.js +5 -3
  266. package/dist/tools/builtins/read-render.js.map +1 -1
  267. package/dist/tools/builtins/search-support.d.ts +6 -4
  268. package/dist/tools/builtins/search-support.d.ts.map +1 -1
  269. package/dist/tools/builtins/search-support.js +15 -3
  270. package/dist/tools/builtins/search-support.js.map +1 -1
  271. package/dist/tools/builtins/skill.d.ts.map +1 -1
  272. package/dist/tools/builtins/skill.js +28 -8
  273. package/dist/tools/builtins/skill.js.map +1 -1
  274. package/dist/tools/builtins/sleep-guard.d.ts +20 -0
  275. package/dist/tools/builtins/sleep-guard.d.ts.map +1 -1
  276. package/dist/tools/builtins/sleep-guard.js +125 -1
  277. package/dist/tools/builtins/sleep-guard.js.map +1 -1
  278. package/dist/tools/builtins/wait-for-job.js +1 -1
  279. package/dist/tools/builtins/wait-for-job.js.map +1 -1
  280. package/dist/tools/builtins/web.d.ts +2 -0
  281. package/dist/tools/builtins/web.d.ts.map +1 -1
  282. package/dist/tools/builtins/web.js +97 -3
  283. package/dist/tools/builtins/web.js.map +1 -1
  284. package/dist/tools/command-shell.d.ts +50 -0
  285. package/dist/tools/command-shell.d.ts.map +1 -1
  286. package/dist/tools/command-shell.js +145 -0
  287. package/dist/tools/command-shell.js.map +1 -1
  288. package/dist/tools/env-scrub.d.ts +2 -0
  289. package/dist/tools/env-scrub.d.ts.map +1 -1
  290. package/dist/tools/env-scrub.js +15 -1
  291. package/dist/tools/env-scrub.js.map +1 -1
  292. package/dist/tools/git-config-env.d.ts +55 -0
  293. package/dist/tools/git-config-env.d.ts.map +1 -0
  294. package/dist/tools/git-config-env.js +130 -0
  295. package/dist/tools/git-config-env.js.map +1 -0
  296. package/dist/tools/schedules/schedule-tool.d.ts +7 -0
  297. package/dist/tools/schedules/schedule-tool.d.ts.map +1 -1
  298. package/dist/tools/schedules/schedule-tool.js +72 -3
  299. package/dist/tools/schedules/schedule-tool.js.map +1 -1
  300. package/dist/tools/schedules/types.d.ts +38 -2
  301. package/dist/tools/schedules/types.d.ts.map +1 -1
  302. package/dist/types/connector/mcp.d.ts +24 -0
  303. package/dist/types/connector/mcp.d.ts.map +1 -1
  304. package/dist/types/message/index.d.ts +21 -1
  305. package/dist/types/message/index.d.ts.map +1 -1
  306. package/dist/types/message/index.js +37 -2
  307. package/dist/types/message/index.js.map +1 -1
  308. package/dist/types/plugin/index.d.ts +10 -2
  309. package/dist/types/plugin/index.d.ts.map +1 -1
  310. package/dist/types/plugin/index.js.map +1 -1
  311. package/dist/types/tool/index.d.ts +6 -0
  312. package/dist/types/tool/index.d.ts.map +1 -1
  313. package/dist/types/tool/index.js.map +1 -1
  314. package/dist/utils/plain-terminal-text.d.ts +21 -0
  315. package/dist/utils/plain-terminal-text.d.ts.map +1 -0
  316. package/dist/utils/plain-terminal-text.js +156 -0
  317. package/dist/utils/plain-terminal-text.js.map +1 -0
  318. package/package.json +1 -1
  319. package/src/authorization/bare-repository.ts +70 -0
  320. package/src/authorization/command-line.ts +18 -4
  321. package/src/authorization/gate.ts +11 -0
  322. package/src/authorization/protected-paths.ts +45 -1
  323. package/src/authorization/readonly-commands.ts +75 -6
  324. package/src/authorization/readonly-flags.ts +103 -0
  325. package/src/authorization/shell-lexer.ts +126 -3
  326. package/src/authorization/shell-paths.ts +386 -0
  327. package/src/authorization/shell-session-state.ts +97 -0
  328. package/src/authorization/shell-session.ts +23 -0
  329. package/src/authorization/skill-grant.ts +1 -0
  330. package/src/compaction/extractor.ts +1 -0
  331. package/src/compaction/hooks.ts +43 -1
  332. package/src/compaction/manual.ts +6 -0
  333. package/src/compaction/restore.ts +3 -2
  334. package/src/config/runtime.ts +7 -0
  335. package/src/connector/mcp/client.ts +61 -4
  336. package/src/connector/web/types.ts +8 -0
  337. package/src/constants/compaction/index.ts +1 -1
  338. package/src/execution/code-runtime/worker-program.ts +9 -5
  339. package/src/execution/local.ts +6 -1
  340. package/src/peers/index.ts +8 -2
  341. package/src/peers/record.ts +45 -1
  342. package/src/peers/registry.ts +21 -5
  343. package/src/plugin/bin-path.ts +149 -0
  344. package/src/plugin/common-layout/read.ts +1 -1
  345. package/src/plugin/common-layout-names.ts +0 -1
  346. package/src/plugin/hook-module/scan.ts +74 -2
  347. package/src/plugin/hook-module/worker-source.ts +56 -0
  348. package/src/plugin/lifecycle.ts +67 -0
  349. package/src/plugin/shell-hook-tool-names.ts +1 -0
  350. package/src/plugin/shell-hook.ts +23 -4
  351. package/src/public-runtime.ts +21 -0
  352. package/src/public-tools.ts +32 -1
  353. package/src/public-types.ts +3 -1
  354. package/src/runtime/jobs/monitor-stream.ts +18 -4
  355. package/src/runtime/jobs/registry.ts +22 -2
  356. package/src/runtime/query/auto-review/git-status.ts +3 -2
  357. package/src/runtime/query/executor.ts +79 -5
  358. package/src/runtime/query/index.ts +5 -2
  359. package/src/runtime/query/iteration/outstanding-work.ts +22 -4
  360. package/src/runtime/query/iteration/phases/compaction.ts +14 -1
  361. package/src/runtime/query/iteration/phases/tool-review.ts +24 -7
  362. package/src/runtime/query/path-escalation.ts +52 -4
  363. package/src/runtime/query/review-policy.ts +5 -2
  364. package/src/runtime/query/steering.ts +32 -4
  365. package/src/sandbox/provider/local.ts +3 -1
  366. package/src/schedules/describe.ts +2 -0
  367. package/src/schedules/evaluate.ts +29 -1
  368. package/src/schedules/index.ts +9 -1
  369. package/src/schedules/next-fire.ts +9 -0
  370. package/src/schedules/spec.ts +42 -0
  371. package/src/schedules/types.ts +33 -3
  372. package/src/schedules/watch.ts +71 -0
  373. package/src/session/workspace/git-worktree.ts +3 -1
  374. package/src/skills/arguments.ts +250 -0
  375. package/src/skills/index.ts +10 -0
  376. package/src/skills/inline-shell.ts +1268 -14
  377. package/src/store/session-index/index.ts +10 -1
  378. package/src/store/session-index/rebuild.ts +81 -5
  379. package/src/store/session-index/sqlite.ts +30 -1
  380. package/src/tools/builtins/bash-cwd.ts +2 -0
  381. package/src/tools/builtins/bash.ts +93 -13
  382. package/src/tools/builtins/exit-semantics.ts +10 -0
  383. package/src/tools/builtins/glob.ts +79 -15
  384. package/src/tools/builtins/grep.ts +37 -10
  385. package/src/tools/builtins/index.ts +15 -0
  386. package/src/tools/builtins/job.ts +1 -1
  387. package/src/tools/builtins/monitor.ts +4 -2
  388. package/src/tools/builtins/notebook-cells.ts +196 -0
  389. package/src/tools/builtins/notebook-edit.ts +280 -0
  390. package/src/tools/builtins/notebook-guard.ts +2 -1
  391. package/src/tools/builtins/push-notification.ts +138 -0
  392. package/src/tools/builtins/read-file.ts +9 -3
  393. package/src/tools/builtins/read-media.ts +2 -1
  394. package/src/tools/builtins/read-render.ts +5 -3
  395. package/src/tools/builtins/search-support.ts +17 -3
  396. package/src/tools/builtins/skill.ts +27 -7
  397. package/src/tools/builtins/sleep-guard.ts +128 -1
  398. package/src/tools/builtins/wait-for-job.ts +1 -1
  399. package/src/tools/builtins/web.ts +100 -3
  400. package/src/tools/command-shell.ts +166 -0
  401. package/src/tools/env-scrub.ts +13 -1
  402. package/src/tools/git-config-env.ts +143 -0
  403. package/src/tools/schedules/schedule-tool.ts +79 -3
  404. package/src/tools/schedules/types.ts +47 -9
  405. package/src/types/connector/mcp.ts +25 -0
  406. package/src/types/message/index.ts +53 -1
  407. package/src/types/plugin/index.ts +10 -2
  408. package/src/types/tool/index.ts +6 -0
  409. package/src/utils/plain-terminal-text.ts +142 -0
@@ -1,3 +1,4 @@
1
+ import { stat } from 'node:fs/promises'
1
2
  import { isAbsolute, join, relative, sep } from 'node:path'
2
3
  import { z } from 'zod'
3
4
  import { walkFilesLocally } from '../../sandbox/file-walk.js'
@@ -7,6 +8,7 @@ import { resolveWithin, resolveWithinAny, resolveWithinAnyReal, toolRoots } from
7
8
  import { relativePosix, resolveWithinPosix } from '../posix-path.js'
8
9
  import {
9
10
  SEARCH_BUDGET_MS,
11
+ SEARCH_TOOL_TIMEOUT_MS,
10
12
  hostDisplayPath,
11
13
  ignoredHint,
12
14
  isEntryLimit,
@@ -19,6 +21,12 @@ import {
19
21
 
20
22
  const MAX_GLOB_RESULTS = 500
21
23
 
24
+ /**
25
+ * Matches a host search collects before it sorts them newest first. Every one is
26
+ * stat'ed, so this bounds that pass; past it the notice says "at least".
27
+ */
28
+ const MAX_GLOB_COLLECTED = 10_000
29
+
22
30
  const inputSchema = z.object({
23
31
  pattern: z
24
32
  .string()
@@ -68,7 +76,7 @@ function relativePattern(pattern: string, root: string, sandboxed: boolean): str
68
76
  export const GlobTool = defineTool({
69
77
  name: 'glob',
70
78
  description:
71
- 'Finds regular files by glob pattern in a bounded search. "*" searches one directory; use "**" explicitly for recursive discovery. Skips files that .gitignore and .ignore rules exclude unless include_ignored is set, and files the read rules of the session deny. Returns at most 500 paths and says when a result is limited or a search stopped early. Does not follow symlinks. To search inside files, use grep.',
79
+ 'Finds regular files by glob pattern in a bounded search. "*" searches one directory; use "**" explicitly for recursive discovery. Skips files that .gitignore and .ignore rules exclude unless include_ignored is set, and files the read rules of the session deny. Returns at most 500 paths, newest first, and says how many matched when a result is limited or a search stopped early. Does not follow symlinks. To search inside files, use grep.',
72
80
  inputSchema,
73
81
  category: 'filesystem',
74
82
  // Declared so a path outside the turn's roots can be reviewed before the
@@ -78,7 +86,7 @@ export const GlobTool = defineTool({
78
86
  readOnly: true,
79
87
  destructive: false,
80
88
  concurrencySafe: true,
81
- timeoutMs: 15_000,
89
+ timeoutMs: SEARCH_TOOL_TIMEOUT_MS,
82
90
 
83
91
  presentCall(input) {
84
92
  if (typeof input.pattern !== 'string') return undefined
@@ -117,7 +125,9 @@ export const GlobTool = defineTool({
117
125
  const options: SandboxWalkFilesOptions = {
118
126
  pattern,
119
127
  signal: budget.signal,
120
- maxEntries: MAX_GLOB_RESULTS + 1,
128
+ // On the host every match is collected (up to the file bound), so the cap keeps
129
+ // the newest files; a sandbox reports no times, so it stops at the cap.
130
+ maxEntries: sandbox ? MAX_GLOB_RESULTS + 1 : MAX_GLOB_COLLECTED + 1,
121
131
  includeHidden: input.include_hidden ?? true,
122
132
  respectIgnore: input.include_ignored !== true,
123
133
  onSummary: (value) => {
@@ -125,7 +135,7 @@ export const GlobTool = defineTool({
125
135
  },
126
136
  }
127
137
  const entries = walkSandbox ? walkSandbox(root, options) : walkFilesLocally(root, options)
128
- const files: string[] = []
138
+ const found: { shown: string; host?: string }[] = []
129
139
  let capped = false
130
140
  let timedOut = false
131
141
  let legacyEntryLimit = false
@@ -137,20 +147,23 @@ export const GlobTool = defineTool({
137
147
  ? resolveWithinPosix(root, entry.path)
138
148
  : resolveWithin(root, entry.path)
139
149
  if (isReadDenied(context, absolute, sandbox?.rootDir)) continue
140
- if (files.length === MAX_GLOB_RESULTS) {
150
+ if (found.length === (sandbox ? MAX_GLOB_RESULTS : MAX_GLOB_COLLECTED)) {
141
151
  capped = true
142
152
  break
143
153
  }
144
154
  // Readers resolve relative input against the original working path,
145
155
  // which may be a symlink. Project back through the selected alias
146
156
  // before relativizing so added directories remain reachable.
147
- files.push(
157
+ found.push(
148
158
  sandbox
149
- ? relativePosix(sandbox.rootDir, absolute)
150
- : hostDisplayPath(
151
- context.workingDirectory,
152
- join(lexicalRoot, relative(root, absolute)),
153
- ),
159
+ ? { shown: relativePosix(sandbox.rootDir, absolute) }
160
+ : {
161
+ shown: hostDisplayPath(
162
+ context.workingDirectory,
163
+ join(lexicalRoot, relative(root, absolute)),
164
+ ),
165
+ host: absolute,
166
+ },
154
167
  )
155
168
  }
156
169
  } catch (error) {
@@ -161,6 +174,17 @@ export const GlobTool = defineTool({
161
174
  } finally {
162
175
  budget.close()
163
176
  }
177
+ const totalFound = found.length
178
+ let files: string[]
179
+ if (sandbox) {
180
+ files = found.map((entry) => entry.shown)
181
+ } else {
182
+ // A timed-out search is already over; sorting what it found must not
183
+ // be cancelled by the same spent budget, only by the caller.
184
+ files = (await sortNewestFirst(found, context.abortSignal)).map((entry) => entry.shown)
185
+ }
186
+ const overCap = files.length > MAX_GLOB_RESULTS
187
+ if (overCap) files = files.slice(0, MAX_GLOB_RESULTS)
164
188
  const endState = summary as SandboxWalkSummary | undefined
165
189
  const entryLimit = endState?.stopped === 'entry-limit' || legacyEntryLimit
166
190
  const incomplete = timedOut || entryLimit
@@ -172,11 +196,16 @@ export const GlobTool = defineTool({
172
196
  }
173
197
  }
174
198
  const notices = [
175
- ...(capped
199
+ ...(sandbox && capped
176
200
  ? [
177
201
  `(Showing the first ${plural(MAX_GLOB_RESULTS, 'matching file')}; more match. Narrow the pattern or path to see the rest.)`,
178
202
  ]
179
203
  : []),
204
+ ...(!sandbox && overCap
205
+ ? [
206
+ `(Showing the ${plural(MAX_GLOB_RESULTS, 'newest matching file')} of ${capped || incomplete ? 'at least ' : ''}${totalFound.toLocaleString('en-US')} that matched. Narrow the pattern or path to see the rest.)`,
207
+ ]
208
+ : []),
180
209
  ...(incomplete ? [stoppedNotice(timedOut ? 'time' : 'entries', endState?.visited)] : []),
181
210
  ...(failure ? [`[Search incomplete: ${failure}]`] : []),
182
211
  ]
@@ -188,8 +217,9 @@ export const GlobTool = defineTool({
188
217
  output: [...files.map(quoteControlPath), ...notices].join('\n') || empty,
189
218
  data: {
190
219
  count: files.length,
220
+ total: totalFound,
191
221
  files,
192
- truncated: capped || incomplete,
222
+ truncated: capped || overCap || incomplete,
193
223
  ...(sandbox ? { sandboxed: true } : {}),
194
224
  },
195
225
  facts: {
@@ -197,11 +227,45 @@ export const GlobTool = defineTool({
197
227
  pattern: input.pattern,
198
228
  ...(input.path !== undefined ? { path: input.path } : {}),
199
229
  count: files.length,
200
- truncated: capped || incomplete,
201
- ...(capped ? { limited: true } : {}),
230
+ truncated: capped || overCap || incomplete,
231
+ ...(capped || overCap ? { limited: true } : {}),
202
232
  ...(incomplete ? { incomplete: true } : {}),
203
233
  },
204
234
  ...(failure ? { error: failure } : {}),
205
235
  }
206
236
  },
207
237
  })
238
+
239
+ /**
240
+ * Newest modification first; ties by path. A file that cannot be stat'ed sorts
241
+ * as oldest. Stats run in small batches so a cancelled call stops promptly.
242
+ */
243
+ async function sortNewestFirst<T extends { shown: string; host?: string }>(
244
+ files: readonly T[],
245
+ signal?: AbortSignal,
246
+ ): Promise<T[]> {
247
+ const stamped: { file: T; mtime: number }[] = []
248
+ for (let i = 0; i < files.length; i += 256) {
249
+ signal?.throwIfAborted()
250
+ const batch = files.slice(i, i + 256)
251
+ stamped.push(
252
+ ...(await Promise.all(
253
+ batch.map(async (file) => {
254
+ if (file.host === undefined) return { file, mtime: 0 }
255
+ try {
256
+ return { file, mtime: (await stat(file.host)).mtimeMs }
257
+ } catch {
258
+ return { file, mtime: 0 }
259
+ }
260
+ }),
261
+ )),
262
+ )
263
+ }
264
+ return stamped
265
+ .sort(
266
+ (a, b) =>
267
+ b.mtime - a.mtime ||
268
+ (a.file.shown < b.file.shown ? -1 : a.file.shown > b.file.shown ? 1 : 0),
269
+ )
270
+ .map((entry) => entry.file)
271
+ }
@@ -25,6 +25,7 @@ import {
25
25
  import {
26
26
  MAX_FILES_SEARCHED,
27
27
  SEARCH_BUDGET_MS,
28
+ SEARCH_TOOL_TIMEOUT_MS,
28
29
  hostDisplayPath,
29
30
  ignoredHint,
30
31
  isEntryLimit,
@@ -334,7 +335,7 @@ function isBinaryContent(buffer: Buffer): boolean {
334
335
  export const GrepTool = defineTool({
335
336
  name: 'grep',
336
337
  description:
337
- 'Searches file contents using a regular expression. By default returns the paths of matching files, newest first; output_mode "content" returns matching lines with file paths, line numbers and optional context lines, and "count" returns the number of matching lines per file. Set multiline for a pattern that spans lines and type (js, py, rust, ...) to search one kind of file. In content mode, before_context and after_context override symmetric context_lines; only_matching returns matched substrings without context. Results are paged: head_limit (default 250, 0 for none) and offset. A line over 500 characters is replaced by a notice. Searches hidden files unless include_hidden is false. Skips files that .gitignore and .ignore rules exclude unless include_ignored is set, and files the read rules of the session deny. Says when a result is limited or a search stopped early. Skips binary files, files over 5 MB, and symlinks. Choose the narrowest relevant directory. To find files by name, use glob.',
338
+ 'Searches file contents using a regular expression. By default returns the paths of matching files, newest first; output_mode "content" returns matching lines with file paths, line numbers and optional context lines, and "count" returns the number of matching lines per file. Set multiline for a pattern that spans lines and type (js, py, rust, ...) to search one kind of file. In content mode, before_context and after_context override symmetric context_lines; only_matching returns matched substrings without context. Content and count rows are ordered by file path. Results are paged: head_limit (default 250, 0 for none) and offset. A line over 500 characters is replaced by a notice. Searches hidden files unless include_hidden is false. Skips files that .gitignore and .ignore rules exclude unless include_ignored is set, and files the read rules of the session deny. Says when a result is limited or a search stopped early. Skips binary files, files over 5 MB, and symlinks. Choose the narrowest relevant directory. To find files by name, use glob.',
338
339
  inputSchema,
339
340
  category: 'analysis',
340
341
  // Declared so a path outside the turn's roots can be reviewed before the
@@ -359,7 +360,7 @@ export const GrepTool = defineTool({
359
360
  },
360
361
  }
361
362
  },
362
- timeoutMs: 15_000,
363
+ timeoutMs: SEARCH_TOOL_TIMEOUT_MS,
363
364
 
364
365
  async execute(input, context) {
365
366
  context.abortSignal?.throwIfAborted()
@@ -429,7 +430,8 @@ export const GrepTool = defineTool({
429
430
  const afterContext = input.after_context ?? input.context_lines ?? 0
430
431
  // Content lines in output order. Only content mode uses them as the
431
432
  // result; the other modes build from `matchedFiles`.
432
- const results: string[] = []
433
+ let results: string[] = []
434
+ const contentFiles: { relPath: string; lines: string[] }[] = []
433
435
  const matchedFiles: { relPath: string; host?: string; count: number }[] = []
434
436
  let totalMatches = 0
435
437
  let filesSearched = 0
@@ -441,8 +443,9 @@ export const GrepTool = defineTool({
441
443
  let timedOut = false
442
444
  let legacyEntryLimit = false
443
445
  let fileLimit = false
444
- // A file list is ordered newest first, so the walk cannot stop at the
445
- // first page: it reads a generous multiple of it, then sorts and pages.
446
+ // A file list is ordered newest first and content and count rows by path,
447
+ // so the walk cannot stop at the first page: it reads a generous multiple
448
+ // of it, then sorts and pages.
446
449
  // The count includes the offset, so every page the model is told to ask
447
450
  // for can be served.
448
451
  const filesToCollect =
@@ -514,6 +517,7 @@ export const GrepTool = defineTool({
514
517
  : (walked?.displayName(filePath) ??
515
518
  hostDisplayPath(context.workingDirectory, join(lexicalRoot, relative(root, filePath))))
516
519
 
520
+ results = []
517
521
  if (mode === 'content' && input.only_matching) {
518
522
  for (const fragment of matchingFragments(content, regex, multiline)) {
519
523
  signal?.throwIfAborted()
@@ -525,7 +529,11 @@ export const GrepTool = defineTool({
525
529
  break
526
530
  }
527
531
  }
528
- if (pageHasMore) break
532
+ if (results.length > 0) contentFiles.push({ relPath, lines: results })
533
+ if (contentFiles.length >= filesToCollect) {
534
+ enough = true
535
+ break
536
+ }
529
537
  continue
530
538
  }
531
539
 
@@ -574,7 +582,13 @@ export const GrepTool = defineTool({
574
582
  count: fileMatches,
575
583
  })
576
584
  }
577
- if (pageHasMore) break
585
+ if (mode === 'content' && results.length > 0) {
586
+ contentFiles.push({ relPath, lines: results })
587
+ if (contentFiles.length >= filesToCollect) {
588
+ enough = true
589
+ break
590
+ }
591
+ }
578
592
  if (mode === 'files_with_matches' && matchedFiles.length >= filesToCollect) {
579
593
  enough = true
580
594
  break
@@ -605,9 +619,17 @@ export const GrepTool = defineTool({
605
619
  // Entries as the model will page through them.
606
620
  let entriesOut: string[]
607
621
  if (mode === 'content') {
608
- entriesOut = results
622
+ // By file path, so a page asked for later is the same on every run:
623
+ // the walk's own order is whatever the file system lists.
624
+ entriesOut = []
625
+ for (const file of [...contentFiles].sort((a, b) => byPath(a.relPath, b.relPath))) {
626
+ if ((beforeContext > 0 || afterContext > 0) && entriesOut.length > 0) entriesOut.push('--')
627
+ entriesOut.push(...file.lines)
628
+ }
609
629
  } else if (mode === 'count') {
610
- entriesOut = matchedFiles.map((f) => `${f.relPath}:${f.count}`)
630
+ entriesOut = [...matchedFiles]
631
+ .sort((a, b) => byPath(a.relPath, b.relPath))
632
+ .map((f) => `${f.relPath}:${f.count}`)
611
633
  } else {
612
634
  entriesOut = (await sortByNewest(matchedFiles)).map((f) => f.relPath)
613
635
  }
@@ -647,7 +669,7 @@ export const GrepTool = defineTool({
647
669
  const notices = [
648
670
  ...(moreRemain
649
671
  ? [
650
- `[More results are available: pass offset: ${offset + headLimit} to continue, or narrow the path or pattern.${enough ? ` Files are ordered newest first among the first ${filesToCollect.toLocaleString('en-US')} that matched.` : ''}]`,
672
+ `[More results are available: pass offset: ${offset + headLimit} to continue, or narrow the path or pattern.${enough ? ` Files are ordered ${mode === 'files_with_matches' ? 'newest first' : 'by path'} among the first ${filesToCollect.toLocaleString('en-US')} that matched.` : ''}]`,
651
673
  ]
652
674
  : []),
653
675
  ...(stoppedEarly
@@ -694,6 +716,11 @@ function clipLine(line: string, kind: 'matching' | 'context'): string {
694
716
  return line.length > MAX_LINE_COLUMNS ? `[Omitted long ${kind} line]` : line
695
717
  }
696
718
 
719
+ /** Code-unit order, the same on every machine and locale. */
720
+ function byPath(a: string, b: string): number {
721
+ return a < b ? -1 : a > b ? 1 : 0
722
+ }
723
+
697
724
  /**
698
725
  * Newest modification first; ties by path. A file that cannot be stat'ed, and
699
726
  * every file in a sandbox (which reports no modification time), sorts as
@@ -1,6 +1,7 @@
1
1
  export { ReadFileTool } from './read-file.js'
2
2
  export { WriteFileTool } from './write-file.js'
3
3
  export { EditTool } from './edit.js'
4
+ export { NotebookEditTool } from './notebook-edit.js'
4
5
  export { BashTool } from './bash.js'
5
6
  export { GlobTool } from './glob.js'
6
7
  export {
@@ -50,6 +51,7 @@ import { EditTool } from './edit.js'
50
51
  import { GlobTool } from './glob.js'
51
52
  import { GrepTool } from './grep.js'
52
53
  import { JobTool } from './job.js'
54
+ import { NotebookEditTool } from './notebook-edit.js'
53
55
  import { ReadFileTool } from './read-file.js'
54
56
  import { VerifyOutputsTool } from './verify-outputs.js'
55
57
  import { WaitForJobTool } from './wait-for-job.js'
@@ -66,6 +68,19 @@ import { WriteFileTool } from './write-file.js'
66
68
  // `Append` tool is gone.
67
69
  // Hosts that genuinely want LS/search can still register them explicitly.
68
70
 
71
+ /**
72
+ * The notebook tool, for a host that loads it on demand.
73
+ *
74
+ * Not in `getBuiltinTools()`: its schema is about two kilobytes on every
75
+ * request and most turns never touch a notebook. A host mounts it deferred, so
76
+ * the model finds it through `search_tools` from the first line of its
77
+ * description (which names Jupyter notebooks and .ipynb cells), and mounts it
78
+ * plainly when it loads every tool up front.
79
+ */
80
+ export function getNotebookTools(): ToolDefinition[] {
81
+ return [NotebookEditTool]
82
+ }
83
+
69
84
  export function getBuiltinTools(): ToolDefinition[] {
70
85
  // `job` ships alongside `bash` rather than being opt-in, because the two
71
86
  // are one capability. `bash run_in_background` returns an id, and an id
@@ -49,7 +49,7 @@ type JobInput = z.infer<typeof inputSchema>
49
49
  export const JobTool = defineTool({
50
50
  name: 'job',
51
51
  description:
52
- 'Reads, lists and stops background jobs started by bash with run_in_background, and monitors started by monitor (whose stderr, which is not an event, is read here). To find out whether a job finished, use wait_for_job: it blocks until the job ends (or goes quiet, or runs long) and returns the output in one call, while repeated "read" calls spend turns checking. Use "read" to see output while a job keeps running, or to pick up after a wait_for_job call gave up, passing the previous call\'s next_offset to see only new output.',
52
+ 'Reads, lists and stops background jobs started by bash with run_in_background, and monitors started by monitor (whose stderr, which is not an event, is read here). You are told when a job exits: do not poll it. Use "read" for its output, passing the previous call\'s next_offset to see only new output.',
53
53
  inputSchema,
54
54
  category: 'shell',
55
55
  permissions: ['shell_execute'],
@@ -136,10 +136,10 @@ export const MONITOR_TOOL_NAME = 'monitor'
136
136
  * rule: the watch is never run on the host to get around the sandbox.
137
137
  */
138
138
  export const MONITOR_CANNOT_DETACH =
139
- 'monitor is unavailable: this sandbox cannot start a detached process, and the watch will not be run on the host to get around it. Run the command in the foreground with bash, with a timeout.'
139
+ 'monitor is unavailable: this sandbox cannot start a detached process, and the watch will not be run on the host to get around it. Run the command in the foreground with bash.'
140
140
 
141
141
  const MONITOR_DESCRIPTION =
142
- 'Starts a command and tells you about each line it prints to stdout, as it prints it, while you keep working. Lines that arrive within 200 ms come together as one event. Use it to watch a log, a test or deploy run, a status endpoint — anything where you must react to something happening INSIDE a long-running command. For ONE notification when something finishes, do not use this: run bash with run_in_background and wait_for_job. Every stage of a pipe must flush per line or events arrive late or never (grep --line-buffered, awk with fflush(), sed -u; `head` cannot). Make the filter match failure as well as success (crash, Traceback, Error, FAILED, Killed…): silence from a monitor is not success. Poll a remote API no faster than every 30 seconds. stderr is not an event; read it with job. A monitor that prints too much is stopped, so filter at the source. It expires after the timeout (default 5 minutes, at most 30) and you get one notice; start it again if you still need it. Stop one early with job {"action":"kill","id":"<id>"}. ' +
142
+ 'Starts a command and tells you about each line it prints to stdout, as it prints it, while you keep working. Lines that arrive within 200 ms come together as one event. Use it to watch a log, a test or deploy run, a status endpoint — anything where you must react to something happening INSIDE a long-running command. For one finish, do not use this: run bash with run_in_background and end your turn, you are told when it exits. Each event wakes you, also while you wait for the person; an event is not their reply. Every stage of a pipe must flush per line or events arrive late or never (grep --line-buffered, awk with fflush(), sed -u; `head` cannot). Make the filter match failure as well as success (crash, Traceback, Error, FAILED, Killed…): silence from a monitor is not success. Poll a remote API no faster than every 30 seconds. stderr is not an event; read it with job. A monitor that prints too much is stopped, so filter at the source. It expires after the timeout (default 5 minutes, at most 30) and you get one notice. A long watch sets the maximum and starts again on that notice. Stop one early with job {"action":"kill","id":"<id>"}. ' +
143
143
  'To watch a service that PUSHES events (a CI or log stream, a change feed) give ws instead of command: { "url": "wss://…", "protocols": [...] }. Each line of each text frame becomes an event, binary frames are only counted, and the watch ends when the server closes the connection. Use it for a push stream, not for request and response. It connects from this machine, so private and local addresses are refused, and you are asked before it connects.'
144
144
 
145
145
  /** What a host can tune about the WebSocket source; for tests only, see {@link WebSocketVetOptions}. */
@@ -343,12 +343,14 @@ export function createMonitorTool(options: MonitorToolOptions = {}) {
343
343
  success: true,
344
344
  output: `WebSocket monitor started (job ${job.id}, expires in ${formatMonitorDuration(timeoutMs)} unless the server closes the connection first; you get one notice at expiry — start it again if you still need the watch). Each line of each text frame the server sends reaches you as an event while you keep working; binary frames are only counted. The connection opens in the background: if it fails you are told in an event. Do not poll or sleep. Stop it with job {"action":"kill","id":"${job.id}"}. An event may arrive while you are waiting for the user — it is not their reply.`,
345
345
  data: { jobId: job.id, monitor: true, timeoutMs, transport: 'websocket' },
346
+ launched: true,
346
347
  }
347
348
  }
348
349
  return {
349
350
  success: true,
350
351
  output: `Monitor started (job ${job.id}, expires in ${formatMonitorDuration(timeoutMs)} unless the command ends first; you get one notice at expiry — start it again if you still need the watch). Each line the command prints to stdout reaches you as an event while you keep working; do not poll or sleep. Stop it with job {"action":"kill","id":"${job.id}"}. An event may arrive while you are waiting for the user — it is not their reply.`,
351
352
  data: { jobId: job.id, monitor: true, timeoutMs },
353
+ launched: true,
352
354
  facts: {
353
355
  kind: 'command',
354
356
  command: input.command as string,
@@ -0,0 +1,196 @@
1
+ import { randomBytes } from 'node:crypto'
2
+
3
+ /**
4
+ * Cell-level changes to the text of a notebook, kept apart from the tool so
5
+ * they are plain input to output: a body in, a body out, or a plain refusal.
6
+ *
7
+ * What a change leaves alone is the point. Every key it does not name keeps its
8
+ * place and value, the notebook's indentation, line endings, byte-order mark
9
+ * and final newline come back as they were, and the ids of the other cells do
10
+ * not change. A cell is touched only where the change says so.
11
+ */
12
+
13
+ export type NotebookEditMode = 'replace' | 'insert' | 'delete'
14
+ export type NotebookCellType = 'code' | 'markdown'
15
+
16
+ export interface NotebookCellEdit {
17
+ readonly cellId?: string | undefined
18
+ readonly newSource?: string | undefined
19
+ readonly cellType?: NotebookCellType | undefined
20
+ readonly editMode: NotebookEditMode
21
+ }
22
+
23
+ export type NotebookEditOutcome =
24
+ | {
25
+ readonly ok: true
26
+ readonly content: string
27
+ /** The id the cell has, when it has one: a new cell's fresh id, or the id that was named. */
28
+ readonly cellId: string | undefined
29
+ readonly cellType: string
30
+ readonly oldSource: string | undefined
31
+ readonly editMode: NotebookEditMode
32
+ }
33
+ | { readonly ok: false; readonly error: string }
34
+
35
+ type Json = Record<string, unknown>
36
+
37
+ function isRecord(value: unknown): value is Json {
38
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
39
+ }
40
+
41
+ function sourceText(source: unknown): string {
42
+ if (typeof source === 'string') return source
43
+ if (Array.isArray(source)) return source.filter((s) => typeof s === 'string').join('')
44
+ return ''
45
+ }
46
+
47
+ /** The lines a notebook stores for a body: each keeps its newline, and an empty body is no lines. */
48
+ function sourceLines(text: string): string[] {
49
+ if (text === '') return []
50
+ return text.split(/(?<=\n)/u)
51
+ }
52
+
53
+ function indentOf(body: string): string {
54
+ return /^\{\r?\n([ \t]+)"/u.exec(body)?.[1] ?? ' '
55
+ }
56
+
57
+ /** A fresh cell id: eight lower-case hex digits, never one already in the notebook. */
58
+ function freshId(taken: ReadonlySet<string>): string {
59
+ for (;;) {
60
+ const id = randomBytes(4).toString('hex')
61
+ if (!taken.has(id)) return id
62
+ }
63
+ }
64
+
65
+ /** Where a cell is, by its id or by the `cell-N` name a read gives a cell that has no id. */
66
+ function locate(cells: readonly Json[], cellId: string): number | string {
67
+ const byId = cells.findIndex((cell) => cell.id === cellId)
68
+ if (byId >= 0) return byId
69
+ const named = /^cell-(\d+)$/u.exec(cellId)?.[1]
70
+ if (named === undefined) return `Cell with ID "${cellId}" not found in notebook.`
71
+ const index = Number.parseInt(named, 10)
72
+ if (cells[index] === undefined) return `Cell with index ${index} does not exist in notebook.`
73
+ return index
74
+ }
75
+
76
+ const HAS_ATTACHMENTS_TO_CODE =
77
+ 'The notebook was not changed: this cell has attachments (such as pasted images), and a code cell cannot hold attachments. To add code after this cell, use edit_mode "insert" with cell_type "code" and the same cell_id. To edit this cell\'s text, leave out cell_type and keep any `attachment:` links in new_source. Deleting this cell loses the attachments, so do that only if the user agrees.'
78
+
79
+ export function applyNotebookEdit(body: string, edit: NotebookCellEdit): NotebookEditOutcome {
80
+ const bom = body.startsWith('\uFEFF') ? '\uFEFF' : ''
81
+ const text = bom ? body.slice(1) : body
82
+ let parsed: unknown
83
+ try {
84
+ parsed = JSON.parse(text)
85
+ } catch (error) {
86
+ return {
87
+ ok: false,
88
+ error: `The notebook is not valid JSON (${error instanceof Error ? error.message : String(error)}). It was not changed.`,
89
+ }
90
+ }
91
+ // A rewrite goes through JSON.parse and JSON.stringify. Two things it cannot
92
+ // give back as they were: an indent over ten characters (cut to ten, so every
93
+ // line changes) and an integer beyond 2^53 (rounded, so a value changes).
94
+ // Refuse and leave the file alone rather than damage cells the call did not name.
95
+ if ((indentOf(text) ?? '').length > 10 || /[:[,]\s*-?\d{16,}(?![\d.eE])/u.test(text)) {
96
+ return {
97
+ ok: false,
98
+ error:
99
+ 'The notebook was not changed: it uses an indent wider than ten characters or holds an integer too large to rewrite exactly, so saving it would alter parts the edit does not name. Use `edit` for this file.',
100
+ }
101
+ }
102
+ if (!isRecord(parsed)) {
103
+ return { ok: false, error: 'The notebook is not a valid Jupyter notebook. It was not changed.' }
104
+ }
105
+ const nbformat = parsed.nbformat
106
+ if (typeof nbformat !== 'number' || nbformat < 4) {
107
+ return {
108
+ ok: false,
109
+ error:
110
+ 'Only notebooks in format 4 or later have a top-level "cells" list that this tool changes. It was not changed.',
111
+ }
112
+ }
113
+ if (!Array.isArray(parsed.cells) || !parsed.cells.every(isRecord)) {
114
+ return {
115
+ ok: false,
116
+ error:
117
+ 'The notebook is not a valid Jupyter notebook (top-level "cells" must be a list of cell objects). It was not changed.',
118
+ }
119
+ }
120
+ const cells = parsed.cells as Json[]
121
+ const { editMode } = edit
122
+
123
+ if (editMode !== 'insert' && edit.cellId === undefined) {
124
+ return { ok: false, error: 'Cell ID must be specified when not inserting a new cell.' }
125
+ }
126
+ if (editMode === 'insert' && edit.cellType === undefined) {
127
+ return { ok: false, error: 'Cell type is required when using edit_mode "insert".' }
128
+ }
129
+ if (editMode !== 'delete' && edit.newSource === undefined) {
130
+ return { ok: false, error: `new_source is required when edit_mode is "${editMode}".` }
131
+ }
132
+
133
+ let at = 0
134
+ if (edit.cellId !== undefined) {
135
+ const found = locate(cells, edit.cellId)
136
+ if (typeof found === 'string') return { ok: false, error: found }
137
+ at = found
138
+ }
139
+
140
+ const minor = typeof parsed.nbformat_minor === 'number' ? parsed.nbformat_minor : 0
141
+ const givesIds = nbformat > 4 || minor >= 5
142
+ let cellId: string | undefined = edit.cellId
143
+ let cellType: string
144
+ let oldSource: string | undefined
145
+
146
+ if (editMode === 'delete') {
147
+ const cell = cells[at] as Json
148
+ cellType = typeof cell.cell_type === 'string' ? cell.cell_type : 'code'
149
+ oldSource = sourceText(cell.source)
150
+ cells.splice(at, 1)
151
+ } else if (editMode === 'insert') {
152
+ const type = edit.cellType as NotebookCellType
153
+ cellType = type
154
+ cellId = undefined
155
+ const cell: Json = { cell_type: type }
156
+ if (givesIds) {
157
+ cellId = freshId(new Set(cells.flatMap((c) => (typeof c.id === 'string' ? [c.id] : []))))
158
+ cell.id = cellId
159
+ }
160
+ cell.metadata = {}
161
+ if (type === 'code') {
162
+ cell.execution_count = null
163
+ cell.outputs = []
164
+ }
165
+ cell.source = sourceLines(edit.newSource as string)
166
+ cells.splice(edit.cellId === undefined ? 0 : at + 1, 0, cell)
167
+ } else {
168
+ const cell = cells[at] as Json
169
+ const had = typeof cell.cell_type === 'string' ? cell.cell_type : 'code'
170
+ const next = edit.cellType ?? had
171
+ if (next === 'code' && had !== 'code' && isRecord(cell.attachments)) {
172
+ if (Object.keys(cell.attachments).length > 0) {
173
+ return { ok: false, error: HAS_ATTACHMENTS_TO_CODE }
174
+ }
175
+ }
176
+ oldSource = sourceText(cell.source)
177
+ cell.source = sourceLines(edit.newSource as string)
178
+ cell.cell_type = next
179
+ cellType = next
180
+ if (next === 'code') {
181
+ // What the cell printed belongs to the code it ran, which is gone.
182
+ cell.execution_count = null
183
+ cell.outputs = []
184
+ cell.attachments = undefined
185
+ } else {
186
+ cell.execution_count = undefined
187
+ cell.outputs = undefined
188
+ }
189
+ }
190
+
191
+ const eol = text.includes('\r\n') ? '\r\n' : '\n'
192
+ let out = JSON.stringify(parsed, null, indentOf(text))
193
+ if (text.endsWith('\n')) out += '\n'
194
+ if (eol === '\r\n') out = out.replace(/\r?\n/gu, '\r\n')
195
+ return { ok: true, content: bom + out, cellId, cellType, oldSource, editMode }
196
+ }