@nordhavnhq/runner 0.0.0-stage → 0.96.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 (338) hide show
  1. package/bin/cliclick +0 -0
  2. package/dist/brand.d.ts +5 -0
  3. package/dist/brand.js +18 -0
  4. package/dist/cli/agent.d.ts +9 -0
  5. package/dist/cli/agent.js +39 -0
  6. package/dist/cli/folder.d.ts +2 -0
  7. package/dist/cli/folder.js +103 -0
  8. package/dist/cli/init.d.ts +2 -0
  9. package/dist/cli/init.js +67 -0
  10. package/dist/cli/lifecycle.d.ts +3 -0
  11. package/dist/cli/lifecycle.js +149 -0
  12. package/dist/cli/link.d.ts +20 -0
  13. package/dist/cli/link.js +312 -0
  14. package/dist/cli/logs.d.ts +2 -0
  15. package/dist/cli/logs.js +144 -0
  16. package/dist/cli/prompts.d.ts +7 -0
  17. package/dist/cli/prompts.js +13 -0
  18. package/dist/cli/ps.d.ts +2 -0
  19. package/dist/cli/ps.js +80 -0
  20. package/dist/cli/relay.d.ts +4 -0
  21. package/dist/cli/relay.js +29 -0
  22. package/dist/cli/update.d.ts +6 -0
  23. package/dist/cli/update.js +131 -0
  24. package/dist/config.d.ts +166 -0
  25. package/dist/config.js +383 -0
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.js +135 -0
  28. package/dist/legacy-env.d.ts +4 -0
  29. package/dist/legacy-env.js +32 -0
  30. package/dist/paths.d.ts +37 -0
  31. package/dist/paths.js +92 -0
  32. package/dist/runtime/daemon.d.ts +57 -0
  33. package/dist/runtime/daemon.js +159 -0
  34. package/dist/runtime/dev-start.d.ts +31 -0
  35. package/dist/runtime/dev-start.js +110 -0
  36. package/dist/runtime/file-claims.d.ts +58 -0
  37. package/dist/runtime/file-claims.js +174 -0
  38. package/dist/runtime/fs-browse.d.ts +18 -0
  39. package/dist/runtime/fs-browse.js +104 -0
  40. package/dist/runtime/fs-checkout.d.ts +154 -0
  41. package/dist/runtime/fs-checkout.js +1049 -0
  42. package/dist/runtime/fs-git-index.d.ts +22 -0
  43. package/dist/runtime/fs-git-index.js +133 -0
  44. package/dist/runtime/fs-git.d.ts +16 -0
  45. package/dist/runtime/fs-git.js +424 -0
  46. package/dist/runtime/git-relay.d.ts +46 -0
  47. package/dist/runtime/git-relay.js +259 -0
  48. package/dist/runtime/git-unpushed.d.ts +36 -0
  49. package/dist/runtime/git-unpushed.js +93 -0
  50. package/dist/runtime/node-version.d.ts +12 -0
  51. package/dist/runtime/node-version.js +39 -0
  52. package/dist/runtime/preview-tunnel.d.ts +16 -0
  53. package/dist/runtime/preview-tunnel.js +135 -0
  54. package/dist/runtime/processes.d.ts +61 -0
  55. package/dist/runtime/processes.js +408 -0
  56. package/dist/runtime/project-node-download.d.ts +17 -0
  57. package/dist/runtime/project-node-download.js +137 -0
  58. package/dist/runtime/project-node.d.ts +65 -0
  59. package/dist/runtime/project-node.js +223 -0
  60. package/dist/runtime/reap-scratch.d.ts +22 -0
  61. package/dist/runtime/reap-scratch.js +112 -0
  62. package/dist/runtime/spill-tool-output.d.ts +14 -0
  63. package/dist/runtime/spill-tool-output.js +84 -0
  64. package/dist/runtime/up.d.ts +6 -0
  65. package/dist/runtime/up.js +1324 -0
  66. package/dist/tools/_coerce.d.ts +2 -0
  67. package/dist/tools/_coerce.js +26 -0
  68. package/dist/tools/_commit-scope.d.ts +14 -0
  69. package/dist/tools/_commit-scope.js +70 -0
  70. package/dist/tools/_jail.d.ts +68 -0
  71. package/dist/tools/_jail.js +209 -0
  72. package/dist/tools/_output.d.ts +24 -0
  73. package/dist/tools/_output.js +48 -0
  74. package/dist/tools/_ripgrep.d.ts +46 -0
  75. package/dist/tools/_ripgrep.js +148 -0
  76. package/dist/tools/_run-worktree.d.ts +10 -0
  77. package/dist/tools/_run-worktree.js +27 -0
  78. package/dist/tools/_shell-words.d.ts +15 -0
  79. package/dist/tools/_shell-words.js +43 -0
  80. package/dist/tools/_sonar/astro.d.ts +6 -0
  81. package/dist/tools/_sonar/astro.js +45 -0
  82. package/dist/tools/_sonar/blade.d.ts +3 -0
  83. package/dist/tools/_sonar/blade.js +53 -0
  84. package/dist/tools/_sonar/build.d.ts +44 -0
  85. package/dist/tools/_sonar/build.js +147 -0
  86. package/dist/tools/_sonar/changed.d.ts +21 -0
  87. package/dist/tools/_sonar/changed.js +230 -0
  88. package/dist/tools/_sonar/diagnose/delta.d.ts +27 -0
  89. package/dist/tools/_sonar/diagnose/delta.js +64 -0
  90. package/dist/tools/_sonar/diagnose/detect.d.ts +39 -0
  91. package/dist/tools/_sonar/diagnose/detect.js +117 -0
  92. package/dist/tools/_sonar/diagnose/index.d.ts +13 -0
  93. package/dist/tools/_sonar/diagnose/index.js +217 -0
  94. package/dist/tools/_sonar/diagnose/lint-worker.d.ts +1 -0
  95. package/dist/tools/_sonar/diagnose/lint-worker.js +48 -0
  96. package/dist/tools/_sonar/diagnose/pool.d.ts +22 -0
  97. package/dist/tools/_sonar/diagnose/pool.js +149 -0
  98. package/dist/tools/_sonar/diagnose/rules.d.ts +23 -0
  99. package/dist/tools/_sonar/diagnose/rules.js +131 -0
  100. package/dist/tools/_sonar/diagnose/types-worker.d.ts +1 -0
  101. package/dist/tools/_sonar/diagnose/types-worker.js +183 -0
  102. package/dist/tools/_sonar/files.d.ts +14 -0
  103. package/dist/tools/_sonar/files.js +121 -0
  104. package/dist/tools/_sonar/graph.d.ts +34 -0
  105. package/dist/tools/_sonar/graph.js +164 -0
  106. package/dist/tools/_sonar/hints.d.ts +116 -0
  107. package/dist/tools/_sonar/hints.js +545 -0
  108. package/dist/tools/_sonar/imports.d.ts +38 -0
  109. package/dist/tools/_sonar/imports.js +275 -0
  110. package/dist/tools/_sonar/index.d.ts +79 -0
  111. package/dist/tools/_sonar/index.js +462 -0
  112. package/dist/tools/_sonar/keys.d.ts +5 -0
  113. package/dist/tools/_sonar/keys.js +248 -0
  114. package/dist/tools/_sonar/laravel-routes.d.ts +15 -0
  115. package/dist/tools/_sonar/laravel-routes.js +263 -0
  116. package/dist/tools/_sonar/laravel.d.ts +64 -0
  117. package/dist/tools/_sonar/laravel.js +326 -0
  118. package/dist/tools/_sonar/location.d.ts +33 -0
  119. package/dist/tools/_sonar/location.js +137 -0
  120. package/dist/tools/_sonar/map.d.ts +43 -0
  121. package/dist/tools/_sonar/map.js +212 -0
  122. package/dist/tools/_sonar/parse.d.ts +3 -0
  123. package/dist/tools/_sonar/parse.js +76 -0
  124. package/dist/tools/_sonar/prewarm.d.ts +9 -0
  125. package/dist/tools/_sonar/prewarm.js +96 -0
  126. package/dist/tools/_sonar/prisma.d.ts +9 -0
  127. package/dist/tools/_sonar/prisma.js +51 -0
  128. package/dist/tools/_sonar/refs.d.ts +7 -0
  129. package/dist/tools/_sonar/refs.js +273 -0
  130. package/dist/tools/_sonar/render.d.ts +66 -0
  131. package/dist/tools/_sonar/render.js +498 -0
  132. package/dist/tools/_sonar/resolve.d.ts +63 -0
  133. package/dist/tools/_sonar/resolve.js +402 -0
  134. package/dist/tools/_sonar/roots.d.ts +4 -0
  135. package/dist/tools/_sonar/roots.js +42 -0
  136. package/dist/tools/_sonar/routes.d.ts +5 -0
  137. package/dist/tools/_sonar/routes.js +247 -0
  138. package/dist/tools/_sonar/serve.d.ts +12 -0
  139. package/dist/tools/_sonar/serve.js +104 -0
  140. package/dist/tools/_sonar/suggest.d.ts +23 -0
  141. package/dist/tools/_sonar/suggest.js +114 -0
  142. package/dist/tools/_sonar/tests.d.ts +21 -0
  143. package/dist/tools/_sonar/tests.js +134 -0
  144. package/dist/tools/_sonar/tsconfig.d.ts +34 -0
  145. package/dist/tools/_sonar/tsconfig.js +188 -0
  146. package/dist/tools/_sonar/types.d.ts +81 -0
  147. package/dist/tools/_sonar/types.js +6 -0
  148. package/dist/tools/_symbols.d.ts +27 -0
  149. package/dist/tools/_symbols.js +461 -0
  150. package/dist/tools/_test-report.d.ts +47 -0
  151. package/dist/tools/_test-report.js +203 -0
  152. package/dist/tools/_touched.d.ts +44 -0
  153. package/dist/tools/_touched.js +195 -0
  154. package/dist/tools/_upload.d.ts +26 -0
  155. package/dist/tools/_upload.js +132 -0
  156. package/dist/tools/_worktree-setup.d.ts +29 -0
  157. package/dist/tools/_worktree-setup.js +204 -0
  158. package/dist/tools/browser.d.ts +2 -0
  159. package/dist/tools/browser.js +8 -0
  160. package/dist/tools/commit-guard.d.ts +44 -0
  161. package/dist/tools/commit-guard.js +165 -0
  162. package/dist/tools/computer.d.ts +13 -0
  163. package/dist/tools/computer.js +952 -0
  164. package/dist/tools/console.d.ts +44 -0
  165. package/dist/tools/console.js +739 -0
  166. package/dist/tools/database.d.ts +28 -0
  167. package/dist/tools/database.js +152 -0
  168. package/dist/tools/filesystem.d.ts +36 -0
  169. package/dist/tools/filesystem.js +506 -0
  170. package/dist/tools/git-tag.d.ts +10 -0
  171. package/dist/tools/git-tag.js +164 -0
  172. package/dist/tools/git.d.ts +52 -0
  173. package/dist/tools/git.js +1272 -0
  174. package/dist/tools/http.d.ts +12 -0
  175. package/dist/tools/http.js +119 -0
  176. package/dist/tools/image.d.ts +8 -0
  177. package/dist/tools/image.js +551 -0
  178. package/dist/tools/index.d.ts +13 -0
  179. package/dist/tools/index.js +58 -0
  180. package/dist/tools/outline.d.ts +20 -0
  181. package/dist/tools/outline.js +98 -0
  182. package/dist/tools/search.d.ts +17 -0
  183. package/dist/tools/search.js +391 -0
  184. package/dist/tools/sonar.d.ts +17 -0
  185. package/dist/tools/sonar.js +231 -0
  186. package/dist/tools/testing.d.ts +36 -0
  187. package/dist/tools/testing.js +273 -0
  188. package/dist/tools/upload.d.ts +8 -0
  189. package/dist/tools/upload.js +106 -0
  190. package/dist/tools/webcam.d.ts +28 -0
  191. package/dist/tools/webcam.js +967 -0
  192. package/dist/update/install-kind.d.ts +35 -0
  193. package/dist/update/install-kind.js +109 -0
  194. package/dist/update/install.d.ts +32 -0
  195. package/dist/update/install.js +187 -0
  196. package/dist/update/manifest.d.ts +18 -0
  197. package/dist/update/manifest.js +73 -0
  198. package/dist/update/peers.d.ts +18 -0
  199. package/dist/update/peers.js +43 -0
  200. package/dist/update/policy.d.ts +20 -0
  201. package/dist/update/policy.js +49 -0
  202. package/dist/update/supervisor.d.ts +25 -0
  203. package/dist/update/supervisor.js +83 -0
  204. package/dist/update/updater.d.ts +44 -0
  205. package/dist/update/updater.js +116 -0
  206. package/dist/utils/format.d.ts +50 -0
  207. package/dist/utils/format.js +190 -0
  208. package/dist/version.d.ts +17 -0
  209. package/dist/version.js +63 -0
  210. package/dist/version.json +5 -0
  211. package/node_modules/@nordhavnhq/runner-browser/dist/act-tools.d.ts +15 -0
  212. package/node_modules/@nordhavnhq/runner-browser/dist/act-tools.js +541 -0
  213. package/node_modules/@nordhavnhq/runner-browser/dist/cast-hub.d.ts +25 -0
  214. package/node_modules/@nordhavnhq/runner-browser/dist/cast-hub.js +137 -0
  215. package/node_modules/@nordhavnhq/runner-browser/dist/guard.d.ts +21 -0
  216. package/node_modules/@nordhavnhq/runner-browser/dist/guard.js +104 -0
  217. package/node_modules/@nordhavnhq/runner-browser/dist/host-protocol.d.ts +47 -0
  218. package/node_modules/@nordhavnhq/runner-browser/dist/host-protocol.js +41 -0
  219. package/node_modules/@nordhavnhq/runner-browser/dist/host.d.ts +18 -0
  220. package/node_modules/@nordhavnhq/runner-browser/dist/host.js +15 -0
  221. package/node_modules/@nordhavnhq/runner-browser/dist/index.d.ts +13 -0
  222. package/node_modules/@nordhavnhq/runner-browser/dist/index.js +28 -0
  223. package/node_modules/@nordhavnhq/runner-browser/dist/live-input.d.ts +74 -0
  224. package/node_modules/@nordhavnhq/runner-browser/dist/live-input.js +93 -0
  225. package/node_modules/@nordhavnhq/runner-browser/dist/live-open.d.ts +4 -0
  226. package/node_modules/@nordhavnhq/runner-browser/dist/live-open.js +57 -0
  227. package/node_modules/@nordhavnhq/runner-browser/dist/live.d.ts +148 -0
  228. package/node_modules/@nordhavnhq/runner-browser/dist/live.js +179 -0
  229. package/node_modules/@nordhavnhq/runner-browser/dist/local-live.d.ts +31 -0
  230. package/node_modules/@nordhavnhq/runner-browser/dist/local-live.js +262 -0
  231. package/node_modules/@nordhavnhq/runner-browser/dist/marks.d.ts +36 -0
  232. package/node_modules/@nordhavnhq/runner-browser/dist/marks.js +173 -0
  233. package/node_modules/@nordhavnhq/runner-browser/dist/page-events.d.ts +27 -0
  234. package/node_modules/@nordhavnhq/runner-browser/dist/page-events.js +82 -0
  235. package/node_modules/@nordhavnhq/runner-browser/dist/page-tools.d.ts +13 -0
  236. package/node_modules/@nordhavnhq/runner-browser/dist/page-tools.js +526 -0
  237. package/node_modules/@nordhavnhq/runner-browser/dist/params.d.ts +12 -0
  238. package/node_modules/@nordhavnhq/runner-browser/dist/params.js +32 -0
  239. package/node_modules/@nordhavnhq/runner-browser/dist/pick.d.ts +24 -0
  240. package/node_modules/@nordhavnhq/runner-browser/dist/pick.js +76 -0
  241. package/node_modules/@nordhavnhq/runner-browser/dist/session.d.ts +225 -0
  242. package/node_modules/@nordhavnhq/runner-browser/dist/session.js +507 -0
  243. package/node_modules/@nordhavnhq/runner-browser/dist/shots.d.ts +11 -0
  244. package/node_modules/@nordhavnhq/runner-browser/dist/shots.js +103 -0
  245. package/node_modules/@nordhavnhq/runner-browser/dist/show.d.ts +10 -0
  246. package/node_modules/@nordhavnhq/runner-browser/dist/show.js +190 -0
  247. package/node_modules/@nordhavnhq/runner-browser/dist/target.d.ts +37 -0
  248. package/node_modules/@nordhavnhq/runner-browser/dist/target.js +82 -0
  249. package/node_modules/@nordhavnhq/runner-browser/dist/tour.d.ts +19 -0
  250. package/node_modules/@nordhavnhq/runner-browser/dist/tour.js +178 -0
  251. package/node_modules/@nordhavnhq/runner-browser/package.json +18 -0
  252. package/node_modules/@nordhavnhq/runner-runtime/dist/config.d.ts +96 -0
  253. package/node_modules/@nordhavnhq/runner-runtime/dist/config.js +25 -0
  254. package/node_modules/@nordhavnhq/runner-runtime/dist/connection.d.ts +276 -0
  255. package/node_modules/@nordhavnhq/runner-runtime/dist/connection.js +507 -0
  256. package/node_modules/@nordhavnhq/runner-runtime/dist/constants.d.ts +48 -0
  257. package/node_modules/@nordhavnhq/runner-runtime/dist/constants.js +95 -0
  258. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/batch.d.ts +94 -0
  259. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/batch.js +219 -0
  260. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/calls.d.ts +136 -0
  261. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/calls.js +214 -0
  262. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/fs.d.ts +735 -0
  263. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/fs.js +40 -0
  264. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/loop.d.ts +362 -0
  265. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/loop.js +703 -0
  266. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/own-files.d.ts +105 -0
  267. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/own-files.js +202 -0
  268. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/phases.d.ts +204 -0
  269. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/phases.js +497 -0
  270. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/pins.d.ts +45 -0
  271. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/pins.js +176 -0
  272. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/processes.d.ts +74 -0
  273. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/processes.js +72 -0
  274. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/release-tag.d.ts +59 -0
  275. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/release-tag.js +117 -0
  276. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/replay.d.ts +62 -0
  277. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/replay.js +84 -0
  278. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/tool-names.d.ts +27 -0
  279. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/tool-names.js +80 -0
  280. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/version.d.ts +22 -0
  281. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/version.js +22 -0
  282. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/wire.d.ts +595 -0
  283. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/wire.js +85 -0
  284. package/node_modules/@nordhavnhq/runner-runtime/dist/index.d.ts +43 -0
  285. package/node_modules/@nordhavnhq/runner-runtime/dist/index.js +50 -0
  286. package/node_modules/@nordhavnhq/runner-runtime/dist/inference.d.ts +135 -0
  287. package/node_modules/@nordhavnhq/runner-runtime/dist/inference.js +945 -0
  288. package/node_modules/@nordhavnhq/runner-runtime/dist/mcp.d.ts +67 -0
  289. package/node_modules/@nordhavnhq/runner-runtime/dist/mcp.js +47 -0
  290. package/node_modules/@nordhavnhq/runner-runtime/dist/platform.d.ts +21 -0
  291. package/node_modules/@nordhavnhq/runner-runtime/dist/platform.js +25 -0
  292. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/auto-load.d.ts +39 -0
  293. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/auto-load.js +67 -0
  294. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/background-commands.d.ts +61 -0
  295. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/background-commands.js +58 -0
  296. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/chat-run-ends.d.ts +23 -0
  297. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/chat-run-ends.js +42 -0
  298. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/duration.d.ts +6 -0
  299. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/duration.js +12 -0
  300. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/events.d.ts +150 -0
  301. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/events.js +36 -0
  302. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/extract-json.d.ts +14 -0
  303. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/extract-json.js +49 -0
  304. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-chat.d.ts +109 -0
  305. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-chat.js +894 -0
  306. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-task.d.ts +73 -0
  307. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-task.js +765 -0
  308. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/loop.d.ts +246 -0
  309. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/loop.js +621 -0
  310. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/messages.d.ts +88 -0
  311. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/messages.js +188 -0
  312. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/pending-steers.d.ts +15 -0
  313. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/pending-steers.js +10 -0
  314. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/phased-loop.d.ts +16 -0
  315. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/phased-loop.js +97 -0
  316. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/project-instructions.d.ts +22 -0
  317. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/project-instructions.js +47 -0
  318. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/run-tools.d.ts +26 -0
  319. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/run-tools.js +48 -0
  320. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/scratch-prompt.d.ts +8 -0
  321. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/scratch-prompt.js +19 -0
  322. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/side-question.d.ts +76 -0
  323. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/side-question.js +155 -0
  324. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/task-validation.d.ts +43 -0
  325. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/task-validation.js +37 -0
  326. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/unload-toolset.d.ts +49 -0
  327. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/unload-toolset.js +104 -0
  328. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/write-scope.d.ts +16 -0
  329. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/write-scope.js +6 -0
  330. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/delegate.d.ts +86 -0
  331. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/delegate.js +141 -0
  332. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/index.d.ts +179 -0
  333. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/index.js +35 -0
  334. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/mcp.d.ts +21 -0
  335. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/mcp.js +179 -0
  336. package/node_modules/@nordhavnhq/runner-runtime/package.json +18 -0
  337. package/package.json +33 -4
  338. package/README.md +0 -3
@@ -0,0 +1,1272 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, isAbsolute, join, relative, sep } from 'node:path';
6
+ import { splitOwnFiles } from '@nordhavnhq/runner-runtime';
7
+ import { githubRepo, relayBranch, RELAY_BUNDLE_MAX_BYTES } from '../runtime/git-relay.js';
8
+ import { unpushedAnnotatedTags } from '../runtime/git-unpushed.js';
9
+ import { hasWriteScope, missingScopeError, missingWriteScope, resolveInCheckout, resolveInJail } from './_jail.js';
10
+ import { commitOutsideScope, outOfScopeError, outOfScopePaths, scopePathspec } from './_commit-scope.js';
11
+ import { runWorktreeSetup } from './_worktree-setup.js';
12
+ import { findMissingImports, missingImportsMessage, repoTop, restoreIndex, snapshotIndex, stagedFiles } from './commit-guard.js';
13
+ // ─── Git Tools ──────────────────────────────
14
+ //
15
+ // Structured git operations without shell interpolation. Every call goes
16
+ // through `execFile('git', [...args])` with a real argument array, so branch
17
+ // names, messages and paths can never be interpreted by a shell. Guardrails
18
+ // live in code, not regexes:
19
+ //
20
+ // - Switching branches in place is allowed only on a CLEAN tree: either
21
+ // runner_git_branch create with `switch: true` (new branch) or
22
+ // runner_git_branch `switch` (existing branch). A dirty tree is never
23
+ // silently carried across a switch - commit, stash (runner_git_stash) or
24
+ // use a worktree (runner_git_worktree) instead.
25
+ // - Syncing with a remote is first-class and non-destructive: runner_git_fetch
26
+ // only updates remote-tracking refs, and runner_git_pull integrates them
27
+ // into a CLEAN tree (default --ff-only; rebase/merge on request, and any
28
+ // half-applied rebase/merge is auto-aborted on conflict so the tree never
29
+ // gets stuck). runner_git_merge folds one branch into the current one under
30
+ // the same clean-tree + abort-on-conflict contract.
31
+ // - Push is user-initiated, not banned. Publishing to a remote is a human
32
+ // decision, so `runner_git_push` is the ONLY push route (the shell still
33
+ // blocks `git push`) and it is gated two ways: it refuses in task runs
34
+ // where no user is present, and its contract lets the agent call it only
35
+ // when the user asked for a push (never offered by the agent). Committing
36
+ // stays free and unconfirmed - commits are local and reversible.
37
+ // - No push via `gh` (pr create/merge, repo sync, release create): those are
38
+ // still shell-blocked and have no tool. Publishing a PR/release is a person's
39
+ // job, not the agent's.
40
+ // - Destructive operations (reset --hard, force-delete, force-push, clean)
41
+ // simply do not exist in this toolset. `runner_git_push` never force-pushes,
42
+ // and pull/merge abort rather than leave a conflicted tree behind.
43
+ //
44
+ // Repo paths are jailed to the project root + agent home via _jail.ts.
45
+ const execFileAsync = promisify(execFile);
46
+ const FALLBACK_NAME = 'Forge';
47
+ const FALLBACK_EMAIL = 'forge@justmade.be';
48
+ const PROTECTED_BRANCHES = ['main', 'master'];
49
+ const BRANCH_NAMING = /^(feat|fix|chore|test|task)\//;
50
+ const DIFF_MAX_LINES = 200;
51
+ // ─── Helpers ────────────────────────────────
52
+ export async function runGit(cwd, args) {
53
+ const { stdout, stderr } = await execFileAsync('git', args, {
54
+ cwd,
55
+ maxBuffer: 10 * 1024 * 1024,
56
+ timeout: 60_000,
57
+ });
58
+ return { stdout, stderr };
59
+ }
60
+ /** Extract a readable message from a failed execFile call. */
61
+ export function gitErrorMessage(err) {
62
+ const e = err;
63
+ const detail = (e.stderr || e.stdout || e.message || 'unknown git error').trim();
64
+ return detail.split('\n').slice(0, 5).join('\n');
65
+ }
66
+ /** Resolve the repo path inside the jail and verify it is a git work tree. */
67
+ export async function resolveRepo(params, context, opts = {}) {
68
+ const repoParam = typeof params.repo === 'string' && params.repo.length > 0 ? params.repo : '.';
69
+ let resolved;
70
+ try {
71
+ // The repo names where git works: any repo of the checkout, also outside
72
+ // a session's scope (commits check their own files). A call that rewrites
73
+ // the working tree (switch, pull, merge, stash) needs the repo inside it.
74
+ resolved = opts.changesTree ? resolveInJail(repoParam, context) : resolveInCheckout(repoParam, context);
75
+ }
76
+ catch (err) {
77
+ return { error: `Error: ${err.message}` };
78
+ }
79
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
80
+ return { error: `Error: repo path not found or not a directory: ${repoParam}` };
81
+ }
82
+ try {
83
+ const { stdout } = await runGit(resolved, ['rev-parse', '--is-inside-work-tree']);
84
+ if (stdout.trim() !== 'true')
85
+ return { error: `Error: "${repoParam}" is not inside a git work tree.` };
86
+ }
87
+ catch {
88
+ return { error: `Error: "${repoParam}" is not a git repository.` };
89
+ }
90
+ return { repo: resolved };
91
+ }
92
+ /** Validate a ref/branch name: no option injection, no shell-hostile chars. */
93
+ export function validateRefName(name, label = 'branch') {
94
+ if (!name)
95
+ return `Error: ${label} name is required`;
96
+ if (name.startsWith('-'))
97
+ return `Error: ${label} name must not start with "-"`;
98
+ if (name.includes('..') || name.endsWith('.lock') || name.endsWith('/')) {
99
+ return `Error: invalid ${label} name "${name}"`;
100
+ }
101
+ if (!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(name)) {
102
+ return `Error: invalid ${label} name "${name}". Allowed: letters, digits, ".", "_", "/", "-".`;
103
+ }
104
+ return null;
105
+ }
106
+ /** Validate a ref range like "main..feat/x" or a single ref. */
107
+ function validateRefRange(range) {
108
+ if (range.startsWith('-'))
109
+ return `Error: ref range must not start with "-"`;
110
+ if (!/^[A-Za-z0-9][A-Za-z0-9._/~^-]*(\.\.\.?[A-Za-z0-9][A-Za-z0-9._/~^-]*)?$/.test(range)) {
111
+ return `Error: invalid ref range "${range}"`;
112
+ }
113
+ return null;
114
+ }
115
+ /** True when the working tree (incl. index) has no changes. */
116
+ async function isClean(repo) {
117
+ const { stdout } = await runGit(repo, ['status', '--porcelain']);
118
+ return stdout.trim().length === 0;
119
+ }
120
+ /** Current branch name, or null when detached. */
121
+ async function currentBranch(repo) {
122
+ const { stdout } = await runGit(repo, ['branch', '--show-current']);
123
+ const name = stdout.trim();
124
+ return name.length > 0 ? name : null;
125
+ }
126
+ /** True when `branch` already has an upstream configured. */
127
+ async function hasUpstream(repo, branch) {
128
+ try {
129
+ await runGit(repo, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', `${branch}@{upstream}`]);
130
+ return true;
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }
136
+ /** True when this dispatch has a live user who can approve a push. Only the
137
+ * chat handler sets `userPresent`; a task run never does. Not derived from
138
+ * `taskUid`/`queueUid`: a chat carries a `queueUid` as well, which is how
139
+ * every chat push got refused as if it were a task run. */
140
+ function userPresent(context) {
141
+ return context?.userPresent === true;
142
+ }
143
+ /** The agent's own commit address: `<slug>@justmade.be`. */
144
+ function agentEmail(context) {
145
+ const slug = trailerPart(context?.agentSlug ?? '');
146
+ return slug ? `${slug}@justmade.be` : FALLBACK_EMAIL;
147
+ }
148
+ /** The agent's own commit name: its display name, its slug before the studio sent a name. */
149
+ function agentAuthorName(context) {
150
+ return trailerPart(context?.agentName ?? '') || trailerPart(context?.agentSlug ?? '') || FALLBACK_NAME;
151
+ }
152
+ /** Repo-local identity, falling back to the agent identity when unset. */
153
+ async function identityArgs(repo, context) {
154
+ const get = async (key) => {
155
+ try {
156
+ const { stdout } = await runGit(repo, ['config', key]);
157
+ return stdout.trim();
158
+ }
159
+ catch {
160
+ return '';
161
+ }
162
+ };
163
+ const name = await get('user.name');
164
+ const email = await get('user.email');
165
+ if (name && email)
166
+ return [];
167
+ return ['-c', `user.name=${name || agentAuthorName(context)}`, '-c', `user.email=${email || agentEmail(context)}`];
168
+ }
169
+ /** Parse `git status --porcelain=v2 --branch`. Paths are relative to the repo's top level. */
170
+ function parseStatus(stdout) {
171
+ const out = { branch: null, upstream: null, ahead: 0, behind: 0, staged: [], unstaged: [], untracked: [] };
172
+ for (const line of stdout.split('\n')) {
173
+ if (!line)
174
+ continue;
175
+ if (line.startsWith('# branch.head ')) {
176
+ const head = line.slice('# branch.head '.length);
177
+ out.branch = head === '(detached)' ? null : head;
178
+ }
179
+ else if (line.startsWith('# branch.upstream ')) {
180
+ out.upstream = line.slice('# branch.upstream '.length);
181
+ }
182
+ else if (line.startsWith('# branch.ab ')) {
183
+ const m = line.match(/\+(\d+) -(\d+)/);
184
+ if (m) {
185
+ out.ahead = parseInt(m[1] ?? '0', 10);
186
+ out.behind = parseInt(m[2] ?? '0', 10);
187
+ }
188
+ }
189
+ else if (line.startsWith('1 ') || line.startsWith('2 ')) {
190
+ // ordinary changed / renamed entry: XY is field 2
191
+ const parts = line.split(' ');
192
+ const xy = parts[1] ?? '..';
193
+ // porcelain v2: "1" entries end in <path>; "2" (rename) entries end in
194
+ // <path>\t<origPath> - take the NEW path (before the tab).
195
+ const rest = line.startsWith('2 ') ? parts.slice(9).join(' ') : parts.slice(8).join(' ');
196
+ const path = line.startsWith('2 ') ? (rest.split('\t')[0] ?? rest) : rest;
197
+ if (xy[0] !== '.')
198
+ out.staged.push(path);
199
+ if (xy[1] !== '.')
200
+ out.unstaged.push(path);
201
+ }
202
+ else if (line.startsWith('? ')) {
203
+ out.untracked.push(line.slice(2));
204
+ }
205
+ }
206
+ return out;
207
+ }
208
+ /**
209
+ * Where a repo's top level sits in the checkout (`''` = the checkout itself),
210
+ * so the run's own files (named from the project root) line up with git's
211
+ * paths (named from the top level). Null without own files to go by, or for a
212
+ * repo outside the checkout (the agent's home).
213
+ */
214
+ async function ownFilesPrefix(repo, context) {
215
+ if (!context?.ownFiles || !context.projectRoot)
216
+ return null;
217
+ try {
218
+ const { stdout } = await runGit(repo, ['rev-parse', '--show-toplevel']);
219
+ const rel = relative(realpathSync(context.projectRoot), realpathSync(stdout.trim()));
220
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
221
+ return null;
222
+ return rel.split(sep).join('/');
223
+ }
224
+ catch {
225
+ return null;
226
+ }
227
+ }
228
+ /** The repo's changed paths split in the run's own and the rest; null when the run keeps no own files here. */
229
+ async function ownSplit(repo, status, context) {
230
+ const prefix = await ownFilesPrefix(repo, context);
231
+ if (prefix == null || !context?.ownFiles)
232
+ return null;
233
+ const changed = new Set([...status.staged, ...status.unstaged, ...status.untracked]);
234
+ return splitOwnFiles(changed, context.ownFiles, prefix);
235
+ }
236
+ // ─── runner_git_status ──────────────────────
237
+ const statusDefinition = {
238
+ name: 'runner_git_status',
239
+ description: 'Structured git status for a repo: branch, ahead/behind, staged/unstaged/untracked files, clean flag. In a project checkout it also splits the changed files (paths from the repo\'s top level) in `yours`, the files this chat or task changed itself (runner_write_file, runner_edit_file, and what a runner_run_command that ran to its end changed) and has not committed since (a working copy\'s included), and `others`: another run\'s, a person\'s, or what a background command changed. Commit `yours` with runner_git_commit `mine: true`; never commit, revert or tidy `others`.',
240
+ parameters: {
241
+ type: 'object',
242
+ properties: {
243
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
244
+ },
245
+ required: [],
246
+ },
247
+ };
248
+ /** Exported for tests. */
249
+ export async function executeStatus(params, context) {
250
+ const resolved = await resolveRepo(params, context);
251
+ if ('error' in resolved)
252
+ return resolved.error;
253
+ const { repo } = resolved;
254
+ try {
255
+ const { stdout } = await runGit(repo, ['status', '--porcelain=v2', '--branch']);
256
+ const status = parseStatus(stdout);
257
+ const { branch, staged, unstaged, untracked } = status;
258
+ const split = await ownSplit(repo, status, context);
259
+ return JSON.stringify({
260
+ repo: params.repo ?? '.',
261
+ branch,
262
+ detached: branch === null,
263
+ upstream: status.upstream,
264
+ ahead: status.ahead,
265
+ behind: status.behind,
266
+ staged,
267
+ unstaged,
268
+ untracked,
269
+ clean: staged.length === 0 && unstaged.length === 0 && untracked.length === 0,
270
+ ...(split ? { yours: split.yours, others: split.others } : {}),
271
+ });
272
+ }
273
+ catch (err) {
274
+ return `Error: ${gitErrorMessage(err)}`;
275
+ }
276
+ }
277
+ // ─── runner_git_log ─────────────────────────
278
+ const logDefinition = {
279
+ name: 'runner_git_log',
280
+ description: 'Structured git log: hash, author, date, subject per commit.',
281
+ parameters: {
282
+ type: 'object',
283
+ properties: {
284
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
285
+ limit: { type: 'number', description: 'Max commits to return. Default: 20, max: 100.' },
286
+ ref: { type: 'string', description: 'Branch or ref to log. Default: current HEAD.' },
287
+ },
288
+ required: [],
289
+ },
290
+ };
291
+ async function executeLog(params, context) {
292
+ const resolved = await resolveRepo(params, context);
293
+ if ('error' in resolved)
294
+ return resolved.error;
295
+ const { repo } = resolved;
296
+ const limit = Math.min(Math.max(typeof params.limit === 'number' ? params.limit : 20, 1), 100);
297
+ const args = ['log', `-${limit}`, '--format=%H%x1f%an%x1f%ae%x1f%aI%x1f%s%x1e'];
298
+ if (typeof params.ref === 'string' && params.ref.length > 0) {
299
+ const invalid = validateRefRange(params.ref);
300
+ if (invalid)
301
+ return invalid;
302
+ args.push(params.ref);
303
+ }
304
+ try {
305
+ const { stdout } = await runGit(repo, args);
306
+ const commits = stdout
307
+ .split('\x1e')
308
+ .map(c => c.trim())
309
+ .filter(c => c.length > 0)
310
+ .map(c => {
311
+ const [hash = '', author, email, date, subject] = c.split('\x1f');
312
+ return { hash, shortHash: hash.slice(0, 7), author, email, date, subject };
313
+ });
314
+ return JSON.stringify({ repo: params.repo ?? '.', count: commits.length, commits });
315
+ }
316
+ catch (err) {
317
+ return `Error: ${gitErrorMessage(err)}`;
318
+ }
319
+ }
320
+ // ─── runner_git_diff ────────────────────────
321
+ const diffDefinition = {
322
+ name: 'runner_git_diff',
323
+ description: `Git diff with truncation at ${DIFF_MAX_LINES} lines. Supports staged diff, path filter and ref ranges.`,
324
+ parameters: {
325
+ type: 'object',
326
+ properties: {
327
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
328
+ staged: { type: 'boolean', description: 'Diff the index (staged changes) instead of the working tree. Default: false.' },
329
+ path: { type: 'string', description: 'Limit the diff to this file or directory (relative to the repo).' },
330
+ range: { type: 'string', description: 'Ref range, e.g. "main..feat/x" or a single ref. Ignores "staged".' },
331
+ },
332
+ required: [],
333
+ },
334
+ };
335
+ async function executeDiff(params, context) {
336
+ const resolved = await resolveRepo(params, context);
337
+ if ('error' in resolved)
338
+ return resolved.error;
339
+ const { repo } = resolved;
340
+ const args = ['diff'];
341
+ if (typeof params.range === 'string' && params.range.length > 0) {
342
+ const invalid = validateRefRange(params.range);
343
+ if (invalid)
344
+ return invalid;
345
+ args.push(params.range);
346
+ }
347
+ else if (params.staged === true) {
348
+ args.push('--staged');
349
+ }
350
+ if (typeof params.path === 'string' && params.path.length > 0) {
351
+ if (params.path.startsWith('-'))
352
+ return 'Error: path must not start with "-"';
353
+ args.push('--', params.path);
354
+ }
355
+ try {
356
+ const { stdout } = await runGit(repo, args);
357
+ if (!stdout.trim())
358
+ return JSON.stringify({ repo: params.repo ?? '.', diff: '', empty: true });
359
+ const lines = stdout.split('\n');
360
+ const truncated = lines.length > DIFF_MAX_LINES;
361
+ const diff = truncated ? lines.slice(0, DIFF_MAX_LINES).join('\n') : stdout;
362
+ return JSON.stringify({
363
+ repo: params.repo ?? '.',
364
+ diff,
365
+ totalLines: lines.length,
366
+ truncated,
367
+ ...(truncated ? { hint: `Diff truncated at ${DIFF_MAX_LINES} of ${lines.length} lines. Narrow with the "path" parameter.` } : {}),
368
+ });
369
+ }
370
+ catch (err) {
371
+ return `Error: ${gitErrorMessage(err)}`;
372
+ }
373
+ }
374
+ // ─── runner_git_worktree ────────────────────
375
+ const worktreeDefinition = {
376
+ name: 'runner_git_worktree',
377
+ description: `Manage git worktrees: the safe way to work on another branch without touching the main working dir. Actions: create (new worktree in <repo>/.worktrees/<branch>, kept out of git; links node_modules/vendor from the main checkout, copies its git-ignored .env files and runs the project's \`worktree:setup\` npm script (or composer \`worktree-setup\`) when it has one, so the worktree is ready to work in), list, remove.`,
378
+ parameters: {
379
+ type: 'object',
380
+ properties: {
381
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
382
+ action: { type: 'string', enum: ['create', 'list', 'remove'], description: 'What to do.' },
383
+ branch: { type: 'string', description: 'Branch name. create: branch for the new worktree (created with -b when it does not exist yet). remove: branch whose worktree should go.' },
384
+ force: { type: 'boolean', description: 'remove only: allow removing a dirty worktree. Default: false.' },
385
+ setup: { type: 'boolean', description: 'create only: link the dependencies, copy the env files and run the project\'s worktree:setup script. Default: true.' },
386
+ },
387
+ required: ['action'],
388
+ },
389
+ };
390
+ /**
391
+ * Worktrees live INSIDE the repo, in `.worktrees/`: that is inside the agent's
392
+ * jail (the repo is one of its roots), where a sibling `<repo>-worktrees/` never
393
+ * was. The folder is kept out of git through the repo's own `info/exclude`, so
394
+ * it works in every repo without touching its `.gitignore`.
395
+ */
396
+ const WORKTREES_DIR = '.worktrees';
397
+ /** Path where a new worktree for `branch` goes: <repo>/.worktrees/<branch with / -> ->. */
398
+ export function worktreePathFor(repo, branch) {
399
+ return `${repo}/${WORKTREES_DIR}/${branch.replace(/\//g, '-')}`;
400
+ }
401
+ async function listWorktrees(repo) {
402
+ const { stdout } = await runGit(repo, ['worktree', 'list', '--porcelain']);
403
+ const worktrees = [];
404
+ let cur = null;
405
+ for (const line of stdout.split('\n')) {
406
+ if (line.startsWith('worktree ')) {
407
+ if (cur)
408
+ worktrees.push(cur);
409
+ cur = { path: line.slice('worktree '.length) };
410
+ }
411
+ else if (cur && line.startsWith('HEAD ')) {
412
+ cur.head = line.slice('HEAD '.length, 'HEAD '.length + 7);
413
+ }
414
+ else if (cur && line.startsWith('branch ')) {
415
+ cur.branch = line.slice('branch '.length).replace('refs/heads/', '');
416
+ }
417
+ else if (cur && line === 'detached') {
418
+ cur.detached = true;
419
+ }
420
+ }
421
+ if (cur)
422
+ worktrees.push(cur);
423
+ return worktrees;
424
+ }
425
+ /**
426
+ * The path of the linked worktree that has `branch` checked out, wherever it
427
+ * is: also one made before worktrees moved into the repo (`<repo>-worktrees/`).
428
+ * The main checkout (the first entry) never counts.
429
+ */
430
+ export async function findWorktreeFor(repo, branch) {
431
+ const linked = (await listWorktrees(repo)).slice(1);
432
+ return linked.find(w => w.branch === branch)?.path ?? null;
433
+ }
434
+ /** Make sure `.worktrees/` is in the repo's `info/exclude`, so it never shows up as untracked. */
435
+ async function excludeWorktreesDir(repo) {
436
+ const { stdout } = await runGit(repo, ['rev-parse', '--git-common-dir']);
437
+ const commonDir = stdout.trim();
438
+ const exclude = join(isAbsolute(commonDir) ? commonDir : join(repo, commonDir), 'info', 'exclude');
439
+ const line = `${WORKTREES_DIR}/`;
440
+ const current = existsSync(exclude) ? readFileSync(exclude, 'utf-8') : '';
441
+ if (current.split('\n').some(l => l.trim() === line || l.trim() === `/${line}`))
442
+ return;
443
+ mkdirSync(dirname(exclude), { recursive: true });
444
+ appendFileSync(exclude, `${current && !current.endsWith('\n') ? '\n' : ''}${line}\n`);
445
+ }
446
+ /**
447
+ * Add the worktree of `branch` at `wtPath`: on the branch when it exists, else
448
+ * on a new branch from the repo's HEAD. Returns whether the branch is new. The
449
+ * caller checks the jail, the path and the naming rule; this only runs git.
450
+ */
451
+ export async function addWorktree(repo, branch, wtPath) {
452
+ let branchExists;
453
+ try {
454
+ await runGit(repo, ['rev-parse', '--verify', `refs/heads/${branch}`]);
455
+ branchExists = true;
456
+ }
457
+ catch {
458
+ branchExists = false;
459
+ }
460
+ await excludeWorktreesDir(repo);
461
+ await runGit(repo, branchExists ? ['worktree', 'add', wtPath, branch] : ['worktree', 'add', '-b', branch, wtPath]);
462
+ return { newBranch: !branchExists };
463
+ }
464
+ export async function executeWorktree(params, context) {
465
+ const resolved = await resolveRepo(params, context);
466
+ if ('error' in resolved)
467
+ return resolved.error;
468
+ const { repo } = resolved;
469
+ const action = params.action;
470
+ try {
471
+ if (action === 'list') {
472
+ return JSON.stringify({ repo: params.repo ?? '.', worktrees: await listWorktrees(repo) });
473
+ }
474
+ const branch = typeof params.branch === 'string' ? params.branch : '';
475
+ const invalid = validateRefName(branch);
476
+ if (invalid)
477
+ return invalid;
478
+ if (action === 'create') {
479
+ const existing = await findWorktreeFor(repo, branch);
480
+ if (existing)
481
+ return `Error: branch "${branch}" already has a worktree at ${existing}`;
482
+ const wtPath = worktreePathFor(repo, branch);
483
+ // Belt and braces: the worktree is inside the repo, so inside the jail.
484
+ try {
485
+ resolveInJail(wtPath, context);
486
+ }
487
+ catch (err) {
488
+ return `Error: ${err.message}`;
489
+ }
490
+ if (existsSync(wtPath))
491
+ return `Error: worktree path already exists: ${wtPath}`;
492
+ if (!BRANCH_NAMING.test(branch)) {
493
+ try {
494
+ await runGit(repo, ['rev-parse', '--verify', `refs/heads/${branch}`]);
495
+ }
496
+ catch {
497
+ return `Error: new branch "${branch}" must match ${BRANCH_NAMING} (feat/, fix/, chore/, test/, task/). Use runner_git_branch with allowAnyName for exceptions.`;
498
+ }
499
+ }
500
+ const { newBranch } = await addWorktree(repo, branch, wtPath);
501
+ const setup = params.setup === false ? null : await runWorktreeSetup(repo, wtPath, context);
502
+ return JSON.stringify({ success: true, action: 'created', branch, path: wtPath, newBranch, ...(setup ? { setup } : {}) });
503
+ }
504
+ if (action === 'remove') {
505
+ const wtPath = await findWorktreeFor(repo, branch);
506
+ if (!wtPath)
507
+ return `Error: no worktree found for branch "${branch}"`;
508
+ if (params.force !== true) {
509
+ const clean = await isClean(wtPath);
510
+ if (!clean) {
511
+ return `Error: worktree at ${wtPath} has uncommitted changes. Commit them first or pass force: true to discard.`;
512
+ }
513
+ }
514
+ const removeArgs = ['worktree', 'remove'];
515
+ if (params.force === true)
516
+ removeArgs.push('--force');
517
+ removeArgs.push(wtPath);
518
+ await runGit(repo, removeArgs);
519
+ await runGit(repo, ['worktree', 'prune']);
520
+ return JSON.stringify({ success: true, action: 'removed', branch, path: wtPath });
521
+ }
522
+ return `Error: unknown action "${action}". Use create, list or remove.`;
523
+ }
524
+ catch (err) {
525
+ return `Error: ${gitErrorMessage(err)}`;
526
+ }
527
+ }
528
+ // ─── runner_git_branch ──────────────────────
529
+ const branchDefinition = {
530
+ name: 'runner_git_branch',
531
+ description: 'Manage branches: list, create (optionally switch when the tree is clean), switch to an existing branch (clean tree only), delete (refused for main/master and the current branch).',
532
+ parameters: {
533
+ type: 'object',
534
+ properties: {
535
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
536
+ action: { type: 'string', enum: ['list', 'create', 'switch', 'delete'], description: 'What to do.' },
537
+ branch: { type: 'string', description: 'Branch name (required for create/switch/delete).' },
538
+ switch: { type: 'boolean', description: 'create only: also switch to the new branch. Only allowed when the working tree is clean. Default: false.' },
539
+ allowAnyName: { type: 'boolean', description: 'create only: skip the feat/|fix/|chore/|test/ naming rule. Default: false.' },
540
+ },
541
+ required: ['action'],
542
+ },
543
+ };
544
+ export async function executeBranch(params, context) {
545
+ const resolved = await resolveRepo(params, context, { changesTree: params.action === 'switch' || params.switch === true });
546
+ if ('error' in resolved)
547
+ return resolved.error;
548
+ const { repo } = resolved;
549
+ const action = params.action;
550
+ try {
551
+ if (action === 'list') {
552
+ const { stdout } = await runGit(repo, ['branch', '--format=%(refname:short)%09%(objectname:short)%09%(HEAD)']);
553
+ const branches = stdout
554
+ .split('\n')
555
+ .filter(l => l.trim().length > 0)
556
+ .map(l => {
557
+ const [name, hash, head] = l.split('\t');
558
+ return { name, hash, current: head === '*' };
559
+ });
560
+ return JSON.stringify({ repo: params.repo ?? '.', branches });
561
+ }
562
+ const branch = typeof params.branch === 'string' ? params.branch : '';
563
+ const invalid = validateRefName(branch);
564
+ if (invalid)
565
+ return invalid;
566
+ if (action === 'create') {
567
+ if (params.allowAnyName !== true && !BRANCH_NAMING.test(branch)) {
568
+ return `Error: branch "${branch}" must match ${BRANCH_NAMING} (feat/, fix/, chore/, test/, task/). Pass allowAnyName: true for a deliberate exception.`;
569
+ }
570
+ let exists = false;
571
+ try {
572
+ await runGit(repo, ['rev-parse', '--verify', `refs/heads/${branch}`]);
573
+ exists = true;
574
+ }
575
+ catch {
576
+ exists = false;
577
+ }
578
+ if (exists)
579
+ return `Error: branch "${branch}" already exists.`;
580
+ if (params.switch === true) {
581
+ const clean = await isClean(repo);
582
+ if (!clean) {
583
+ return 'Error: refusing to switch branches with uncommitted changes. Commit first, or create the branch without switch and use runner_git_worktree to work on it.';
584
+ }
585
+ await runGit(repo, ['switch', '-c', branch]);
586
+ return JSON.stringify({ success: true, action: 'created', branch, switched: true });
587
+ }
588
+ await runGit(repo, ['branch', branch]);
589
+ return JSON.stringify({ success: true, action: 'created', branch, switched: false });
590
+ }
591
+ if (action === 'switch') {
592
+ let exists = false;
593
+ try {
594
+ await runGit(repo, ['rev-parse', '--verify', `refs/heads/${branch}`]);
595
+ exists = true;
596
+ }
597
+ catch {
598
+ exists = false;
599
+ }
600
+ if (!exists) {
601
+ return `Error: branch "${branch}" does not exist. Create it first (action: "create") or use runner_git_worktree.`;
602
+ }
603
+ const current = await currentBranch(repo);
604
+ if (current === branch) {
605
+ return JSON.stringify({ success: true, action: 'switched', branch, alreadyOn: true });
606
+ }
607
+ if (!(await isClean(repo))) {
608
+ return 'Error: refusing to switch branches with uncommitted changes. Commit them, stash them (runner_git_stash), or use runner_git_worktree to work on the other branch without switching.';
609
+ }
610
+ await runGit(repo, ['switch', branch]);
611
+ return JSON.stringify({ success: true, action: 'switched', branch });
612
+ }
613
+ if (action === 'delete') {
614
+ if (PROTECTED_BRANCHES.includes(branch)) {
615
+ return `Error: refusing to delete protected branch "${branch}".`;
616
+ }
617
+ const current = await currentBranch(repo);
618
+ if (current === branch) {
619
+ return `Error: refusing to delete the current branch "${branch}".`;
620
+ }
621
+ // -d only: git itself refuses when the branch is not fully merged.
622
+ await runGit(repo, ['branch', '-d', branch]);
623
+ return JSON.stringify({ success: true, action: 'deleted', branch });
624
+ }
625
+ return `Error: unknown action "${action}". Use list, create, switch or delete.`;
626
+ }
627
+ catch (err) {
628
+ return `Error: ${gitErrorMessage(err)}`;
629
+ }
630
+ }
631
+ // ─── runner_git_commit ──────────────────────
632
+ const commitDefinition = {
633
+ name: 'runner_git_commit',
634
+ description: 'Stage files (specific paths or all changes) and commit. Uses the agent identity when the repo has none configured; in a chat whose person connected their git relay the commit is in THEIR name, with you added as `Co-authored-by` (do not add that line yourself). Refuses empty commits. In a session with a scope it commits only changes inside the scope: `all` stages just the scope, and paths (or staged files) outside it are refused. Refuses a commit that would leave an import behind: a committed source file (ts, tsx, js, mjs, cjs, jsx, vue, astro) that imports a relative path (`./x`, `../x`) git does not track and the commit does not take, as that builds here and breaks every build of what is pushed. It then commits nothing, unstages what it staged and answers `{ success: false, error, missing: [{ file, imports }] }` (paths from the repo\'s top level): add those files to paths, or pass allowMissingImports: true when they are meant to stay out. In a task run the message always starts with its task: `Task #<uid> ` is put in front when the message does not start with it already.',
635
+ parameters: {
636
+ type: 'object',
637
+ properties: {
638
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
639
+ message: { type: 'string', description: 'Commit message. Prefer conventional commits (feat:, fix:, chore:, test:, docs:, refactor:). Start it with the task the work is for: `Task #<uid> fix: ...`. In a task run that prefix is added for you when you leave it out.' },
640
+ paths: { type: 'array', items: { type: 'string' }, description: 'Files to stage before committing (relative to the repo). Omit and set all: true to stage everything.' },
641
+ all: { type: 'boolean', description: 'Stage all changes (git add -A) before committing. Default: false.' },
642
+ mine: { type: 'boolean', description: 'Stage exactly the files this chat or task changed itself (`yours` in runner_git_status) and commit those: the safe choice in a shared checkout. Instead of paths or all. Default: false.' },
643
+ allowMissingImports: { type: 'boolean', description: 'Commit even when a committed file imports an untracked file the commit leaves out (`missing`). Only when that file is meant to stay out of git. Default: false.' },
644
+ },
645
+ required: ['message'],
646
+ },
647
+ };
648
+ /** A commit in a task run always STARTS with its task (`Task #ABC12345 fix: ...`),
649
+ * so the first thing `git log --oneline` shows is which task a commit was for,
650
+ * and `git log --grep` finds a task's work. Left alone when the message
651
+ * already starts with it, so an agent that wrote it itself does not get it twice. */
652
+ function withTaskPrefix(message, context) {
653
+ const taskUid = context?.taskUid;
654
+ if (!taskUid)
655
+ return message;
656
+ const prefix = `Task #${taskUid}`;
657
+ return message.startsWith(prefix) ? message : `${prefix} ${message}`;
658
+ }
659
+ /** No line breaks or angle brackets from outside in a trailer. */
660
+ function trailerPart(text) {
661
+ return text.replace(/[\r\n<>]/g, ' ').trim();
662
+ }
663
+ /** The agent's own address on a co-authored commit: the one the studio sends,
664
+ * else built from the dispatch's agent slug (an older studio sends none). */
665
+ function coAuthorEmail(relay, context) {
666
+ return trailerPart(relay.agent.email ?? '') || agentEmail(context);
667
+ }
668
+ /** In a chat whose person connected a git relay the commit is theirs: their
669
+ * name, the agent named in a `Co-authored-by` trailer (once, however often
670
+ * the agent wrote it itself). Otherwise the message as it is. */
671
+ function withCoAuthor(message, context) {
672
+ const relay = context?.gitRelay;
673
+ if (!relay)
674
+ return message;
675
+ const trailer = `Co-authored-by: ${trailerPart(relay.agent.name) || agentAuthorName(context)} <${coAuthorEmail(relay, context)}>`;
676
+ const lines = message.split('\n');
677
+ if (lines.some(l => l.trim().toLowerCase() === trailer.toLowerCase()))
678
+ return message;
679
+ // Trailers go in the last paragraph: join one that is already there.
680
+ const last = message.slice(message.lastIndexOf('\n\n') + 2);
681
+ const inTrailers = message.includes('\n\n') && last.split('\n').every(l => /^[A-Za-z][A-Za-z-]*: /.test(l));
682
+ return `${message}${inTrailers ? '\n' : '\n\n'}${trailer}`;
683
+ }
684
+ /** Who a commit is by: the person behind the chat when they connected a git
685
+ * relay, else the repo's own identity or the agent's. */
686
+ export async function commitIdentity(repo, context) {
687
+ const as = context?.gitRelay?.commitAs;
688
+ if (as)
689
+ return ['-c', `user.name=${trailerPart(as.name)}`, '-c', `user.email=${trailerPart(as.email)}`];
690
+ return identityArgs(repo, context);
691
+ }
692
+ /**
693
+ * Stage what the commit takes: the given paths, everything (`all`), or exactly
694
+ * the run's own files (`mine`). With `mine` the commit takes only those, so what
695
+ * another run staged stays staged and out of it.
696
+ */
697
+ async function stageForCommit(repo, opts, context) {
698
+ if (opts.mine) {
699
+ const { stdout } = await runGit(repo, ['status', '--porcelain=v2']);
700
+ const split = await ownSplit(repo, parseStatus(stdout), context);
701
+ if (!split)
702
+ return { error: 'Error: mine: true needs a project checkout this chat or task works in. Pass paths instead.' };
703
+ if (split.yours.length === 0)
704
+ return { error: 'Error: none of the changed files are yours (runner_git_status). Pass paths when you mean files you changed another way.' };
705
+ const { stdout: top } = await runGit(repo, ['rev-parse', '--show-toplevel']);
706
+ const outside = outOfScopePaths(top.trim(), split.yours, context);
707
+ if (outside.length)
708
+ return { error: outOfScopeError(outside, context) };
709
+ const only = { cwd: top.trim(), paths: split.yours };
710
+ await runGit(only.cwd, ['add', '--', ...only.paths]);
711
+ return { only };
712
+ }
713
+ if (opts.all) {
714
+ // In a scoped session `all` means all changes inside the scope.
715
+ const top = await repoTop(repo);
716
+ const spec = scopePathspec(top, context);
717
+ if (spec === null)
718
+ return { error: outOfScopeError([relative(repo, top) || '.'], context) };
719
+ await runGit(top, spec ? ['add', '-A', '--', spec] : ['add', '-A']);
720
+ return { only: null };
721
+ }
722
+ const bad = opts.paths.find(p => p.startsWith('-'));
723
+ if (bad)
724
+ return { error: `Error: path "${bad}" must not start with "-"` };
725
+ const outside = outOfScopePaths(repo, opts.paths, context);
726
+ if (outside.length)
727
+ return { error: outOfScopeError(outside, context) };
728
+ if (opts.paths.length > 0)
729
+ await runGit(repo, ['add', '--', ...opts.paths]);
730
+ return { only: null };
731
+ }
732
+ /** Does the index hold anything to commit? */
733
+ async function hasStagedChanges(repo) {
734
+ try {
735
+ await runGit(repo, ['diff', '--staged', '--quiet']);
736
+ }
737
+ catch {
738
+ return true; // non-zero exit = there ARE staged changes
739
+ }
740
+ // A repo without any commit yet: diff --staged fails differently; double-check.
741
+ try {
742
+ const { stdout } = await runGit(repo, ['status', '--porcelain']);
743
+ return stdout.split('\n').some(l => l.length > 0 && l[0] !== ' ' && l[0] !== '?');
744
+ }
745
+ catch {
746
+ return false;
747
+ }
748
+ }
749
+ /** The refusal of a commit that would leave an import behind (commit-guard.ts),
750
+ * with what this call staged unstaged again; null when nothing is missing. */
751
+ async function refuseMissingImports(repo, only, snapshot) {
752
+ const top = await repoTop(repo);
753
+ const missing = await findMissingImports(top, only ? only.paths : await stagedFiles(top));
754
+ if (!missing.length)
755
+ return null;
756
+ await restoreIndex(top, snapshot);
757
+ return JSON.stringify({ success: false, error: missingImportsMessage(missing), missing });
758
+ }
759
+ /** The commit's own params, or the error to answer with. */
760
+ function parseCommitParams(params) {
761
+ const message = typeof params.message === 'string' ? params.message.trim() : '';
762
+ if (!message)
763
+ return { error: 'Error: message is required' };
764
+ if (message.startsWith('-'))
765
+ return { error: 'Error: message must not start with "-"' };
766
+ const paths = Array.isArray(params.paths) ? params.paths.filter((p) => typeof p === 'string') : [];
767
+ const all = params.all === true;
768
+ const mine = params.mine === true;
769
+ if ([paths.length > 0, all, mine].filter(Boolean).length > 1)
770
+ return { error: 'Error: pass one of paths, all: true or mine: true' };
771
+ return { message, paths, all, mine, guard: params.allowMissingImports !== true };
772
+ }
773
+ /** In a scoped session: the error for staged files outside the scope (the index restored), else null. */
774
+ async function refuseOutsideScope(repo, only, snapshot, context) {
775
+ const top = await repoTop(repo);
776
+ const outside = await commitOutsideScope(top, only ? only.paths : null, context);
777
+ if (!outside.length)
778
+ return null;
779
+ await restoreIndex(top, snapshot);
780
+ return outOfScopeError(outside, context);
781
+ }
782
+ export async function executeCommit(params, context) {
783
+ const resolved = await resolveRepo(params, context);
784
+ if ('error' in resolved)
785
+ return resolved.error;
786
+ const { repo } = resolved;
787
+ const parsed = parseCommitParams(params);
788
+ if ('error' in parsed)
789
+ return parsed.error;
790
+ const { message, paths, all, mine, guard } = parsed;
791
+ const missingScope = missingWriteScope(context);
792
+ if (missingScope)
793
+ return `Error: ${missingScopeError(missingScope)}`;
794
+ try {
795
+ const scoped = hasWriteScope(context);
796
+ const snapshot = guard || scoped ? await snapshotIndex(await repoTop(repo)) : null;
797
+ const staged = await stageForCommit(repo, { paths, all, mine }, context);
798
+ if ('error' in staged)
799
+ return staged.error;
800
+ const { only } = staged;
801
+ // Refuse empty commits: check the index against HEAD.
802
+ if (!(await hasStagedChanges(repo))) {
803
+ return 'Error: nothing staged to commit. Pass paths or all: true to stage changes first.';
804
+ }
805
+ const refused = guard ? await refuseMissingImports(repo, only, snapshot) : null;
806
+ if (refused)
807
+ return refused;
808
+ const outside = scoped ? await refuseOutsideScope(repo, only, snapshot, context) : null;
809
+ if (outside)
810
+ return outside;
811
+ const identity = await commitIdentity(repo, context);
812
+ const commitArgs = [...identity, 'commit', '-m', withCoAuthor(withTaskPrefix(message, context), context)];
813
+ const { stdout } = only
814
+ ? await runGit(only.cwd, [...commitArgs, '--', ...only.paths])
815
+ : await runGit(repo, commitArgs);
816
+ const { stdout: hashOut } = await runGit(repo, ['rev-parse', 'HEAD']);
817
+ const hash = hashOut.trim();
818
+ const { stdout: messageOut } = await runGit(repo, ['log', '-1', '--format=%B']);
819
+ return JSON.stringify({
820
+ success: true,
821
+ hash,
822
+ shortHash: hash.slice(0, 7),
823
+ message: messageOut.trim(),
824
+ summary: stdout.trim().split('\n')[0],
825
+ });
826
+ }
827
+ catch (err) {
828
+ return `Error: ${gitErrorMessage(err)}`;
829
+ }
830
+ }
831
+ // ─── runner_git_push ────────────────────────
832
+ const pushDefinition = {
833
+ name: 'runner_git_push',
834
+ description: 'Push a branch to a remote (publish local commits). This is the ONLY way to push - the shell blocks `git push`. ' +
835
+ 'USER-INITIATED ONLY: call this only when the user asked you to push in this session. Never offer, suggest or ' +
836
+ 'ask about a push yourself, not even at the end of a job: publishing commits is the user\'s call, never your own initiative. ' +
837
+ 'Only works when a user is present (chat/companion); in a task run it is refused because nobody can confirm. ' +
838
+ 'Force-push is not supported. Pushes with --follow-tags: the annotated tags on the commits it pushes (runner_git_tag) ' +
839
+ 'go along, listed in `tags`. In a chat whose person connected their git relay, a push to GitHub goes out through ' +
840
+ 'THEIR machine, with their key, after they confirm it there: it can take a few minutes, and when their machine is ' +
841
+ 'offline it waits for it (you are told so; carry on with your work). Tags do not go through the relay.',
842
+ parameters: {
843
+ type: 'object',
844
+ properties: {
845
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
846
+ remote: { type: 'string', description: 'Remote to push to. Default: "origin".' },
847
+ branch: { type: 'string', description: 'Branch to push. Default: the current branch.' },
848
+ setUpstream: { type: 'boolean', description: 'Set the branch\'s upstream (-u). Applied automatically when the branch has none. Default: false.' },
849
+ },
850
+ required: [],
851
+ },
852
+ };
853
+ /** Agents push their own branch and open a pull request: never main or
854
+ * master, however it is spelled (`refs/heads/main`, `heads/main`). */
855
+ function refuseProtectedPush(branch) {
856
+ if (!PROTECTED_BRANCHES.includes(branch.replace(/^(refs\/)?heads\//, '')))
857
+ return null;
858
+ return `Blocked: agents never push to "${branch}". Push your own branch (feat/, fix/, chore/...) and open a pull request; merging stays with a person.`;
859
+ }
860
+ // ─── Through the person's git relay ─────────
861
+ //
862
+ // In a chat whose person connected a git relay on ANOTHER runner (their
863
+ // machine), a push does not go out from here: the branch goes to the studio
864
+ // as a git bundle, and their machine pushes it with their key after their
865
+ // click there. That machine checks everything again from the bundle itself.
866
+ /** How long a push waits on the studio: the person's click (two minutes),
867
+ * git on their machine, and a margin past the studio's own wait. */
868
+ const RELAY_PUSH_WAIT_MS = 5 * 60_000;
869
+ /** The URL of `remote`, or null. */
870
+ async function remoteUrlOf(repo, remote) {
871
+ try {
872
+ return (await runGit(repo, ['remote', 'get-url', remote])).stdout.trim() || null;
873
+ }
874
+ catch {
875
+ return null;
876
+ }
877
+ }
878
+ function isGithubRemote(url) {
879
+ try {
880
+ githubRepo(url);
881
+ return true;
882
+ }
883
+ catch {
884
+ return false;
885
+ }
886
+ }
887
+ /** `branch` as a git bundle in `file`: the commits `remote` does not have yet
888
+ * when git can tell (what the relay builds on), else the whole branch. */
889
+ async function bundleBranch(repo, remote, branch, file) {
890
+ const ref = `refs/heads/${branch}`;
891
+ try {
892
+ await runGit(repo, ['bundle', 'create', file, ref, '--not', `--remotes=${remote}`]);
893
+ }
894
+ catch {
895
+ await runGit(repo, ['bundle', 'create', file, ref]);
896
+ }
897
+ }
898
+ /** What the answer says about tags a relay push leaves behind. */
899
+ function tagsLeftBehind(tags) {
900
+ if (!tags.length)
901
+ return {};
902
+ return { tagsNotPushed: tags, tagsNote: `The git relay pushes the branch only: ${tags.join(', ')} stayed here. A person pushes tags from their own machine.` };
903
+ }
904
+ /** The studio's answer to a push for the agent, in plain words. */
905
+ function relayPushResult(reply, branch, tags) {
906
+ switch (reply.status) {
907
+ case 'pushed':
908
+ return JSON.stringify({ success: true, via: 'git relay', runner: reply.runner, branch, sha: reply.sha, output: reply.output || 'pushed', ...tagsLeftBehind(tags) });
909
+ case 'waiting':
910
+ return JSON.stringify({
911
+ success: true,
912
+ pushed: false,
913
+ waiting: true,
914
+ message: `The push waits for ${reply.person}'s tunnel; the commits are on ${branch} here. Carry on: it goes out once their machine is back and they confirm it there.`,
915
+ });
916
+ case 'refused':
917
+ return `Error: the push through the git relay did not go out: ${reply.reason} The commits stay on ${branch} here; ask the person before you try again.`;
918
+ }
919
+ }
920
+ async function pushViaRelay(repo, remote, branch, repoUrl, context) {
921
+ if (!context.studioUrl || !context.agentToken || !context.queueUid) {
922
+ return 'Error: the git relay needs the studio connection of this chat, and it is missing.';
923
+ }
924
+ try {
925
+ relayBranch(branch);
926
+ }
927
+ catch (err) {
928
+ return `Blocked: ${err.message}. Commit on a branch of your own and push that.`;
929
+ }
930
+ const { stdout: ahead } = await runGit(repo, ['rev-list', '--count', `refs/heads/${branch}`, '--not', `--remotes=${remote}`]);
931
+ if (ahead.trim() === '0') {
932
+ return JSON.stringify({ success: true, via: 'git relay', branch, output: `Nothing to push: every commit on ${branch} is already on ${remote}.` });
933
+ }
934
+ const dir = mkdtempSync(join(tmpdir(), 'relay-push-'));
935
+ let bundle;
936
+ try {
937
+ const file = join(dir, 'branch.bundle');
938
+ await bundleBranch(repo, remote, branch, file);
939
+ const bytes = readFileSync(file);
940
+ if (bytes.length > RELAY_BUNDLE_MAX_BYTES) {
941
+ return `Error: ${branch} is too big to push through the git relay (${Math.round(bytes.length / 1024 / 1024)} MB, at most ${RELAY_BUNDLE_MAX_BYTES / 1024 / 1024} MB).`;
942
+ }
943
+ bundle = bytes.toString('base64');
944
+ }
945
+ finally {
946
+ rmSync(dir, { recursive: true, force: true });
947
+ }
948
+ const timeout = AbortSignal.timeout(RELAY_PUSH_WAIT_MS);
949
+ try {
950
+ const res = await fetch(`${context.studioUrl}/api/agents/git-relay/push`, {
951
+ method: 'POST',
952
+ headers: { 'Authorization': `Bearer ${context.agentToken}`, 'Content-Type': 'application/json' },
953
+ body: JSON.stringify({ queueUid: context.queueUid, repoUrl, branch, bundle }),
954
+ signal: context.signal ? AbortSignal.any([context.signal, timeout]) : timeout,
955
+ });
956
+ if (!res.ok) {
957
+ const text = await res.text();
958
+ let message = text;
959
+ try {
960
+ message = JSON.parse(text).message ?? text;
961
+ }
962
+ catch { /* plain text */ }
963
+ return `Error: the studio did not take the push (${res.status}): ${message.slice(0, 500)}`;
964
+ }
965
+ const tags = await unpushedAnnotatedTags(repo, `refs/heads/${branch}`, remote);
966
+ return relayPushResult(await res.json(), branch, tags);
967
+ }
968
+ catch (err) {
969
+ return `Error: the push through the git relay did not finish: ${err.message}. The commits stay on ${branch} here.`;
970
+ }
971
+ }
972
+ /** Exported for tests. */
973
+ export async function executePush(params, context) {
974
+ if (!userPresent(context)) {
975
+ return 'Blocked: pushing needs a person to confirm, and no user is present in a task run. Leave the work committed on its branch and report the branch and the commit - a person can push it from a chat/companion session. runner_git_push is only available when a user is present.';
976
+ }
977
+ if (typeof params.branch === 'string' && params.branch) {
978
+ const refused = refuseProtectedPush(params.branch);
979
+ if (refused)
980
+ return refused;
981
+ }
982
+ const resolved = await resolveRepo(params, context);
983
+ if ('error' in resolved)
984
+ return resolved.error;
985
+ const { repo } = resolved;
986
+ const remote = typeof params.remote === 'string' && params.remote.length > 0 ? params.remote : 'origin';
987
+ const remoteInvalid = validateRefName(remote, 'remote');
988
+ if (remoteInvalid)
989
+ return remoteInvalid;
990
+ let branch = typeof params.branch === 'string' && params.branch.length > 0 ? params.branch : '';
991
+ if (!branch) {
992
+ const current = await currentBranch(repo);
993
+ if (!current)
994
+ return 'Error: detached HEAD - pass an explicit "branch" to push.';
995
+ branch = current;
996
+ }
997
+ const branchInvalid = validateRefName(branch);
998
+ if (branchInvalid)
999
+ return branchInvalid;
1000
+ const protectedRefused = refuseProtectedPush(branch);
1001
+ if (protectedRefused)
1002
+ return protectedRefused;
1003
+ // The person behind this chat pushes through their own machine, unless
1004
+ // that machine is this one. Only GitHub goes through the relay.
1005
+ if (context?.gitRelay && !context.gitRelay.local) {
1006
+ const url = await remoteUrlOf(repo, remote);
1007
+ if (url && isGithubRemote(url))
1008
+ return pushViaRelay(repo, remote, branch, url, context);
1009
+ }
1010
+ try {
1011
+ const needsUpstream = params.setUpstream === true || !(await hasUpstream(repo, branch));
1012
+ // What --follow-tags takes along, read before the push moves the remote refs.
1013
+ const tags = await unpushedAnnotatedTags(repo, `refs/heads/${branch}`, remote);
1014
+ const args = ['push', '--follow-tags'];
1015
+ if (needsUpstream)
1016
+ args.push('-u');
1017
+ args.push(remote, branch);
1018
+ // git push reports progress and result on stderr; keep both for the model.
1019
+ const { stdout, stderr } = await runGit(repo, args);
1020
+ const output = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
1021
+ return JSON.stringify({
1022
+ success: true,
1023
+ remote,
1024
+ branch,
1025
+ setUpstream: needsUpstream,
1026
+ tags,
1027
+ output: output || 'Everything up-to-date',
1028
+ });
1029
+ }
1030
+ catch (err) {
1031
+ return `Error: ${gitErrorMessage(err)}`;
1032
+ }
1033
+ }
1034
+ // ─── runner_git_fetch ───────────────────────
1035
+ const fetchDefinition = {
1036
+ name: 'runner_git_fetch',
1037
+ description: 'Fetch refs from a remote to update remote-tracking branches. Read-only: never touches the working tree or the current branch - it only refreshes what the repo knows about the remote.',
1038
+ parameters: {
1039
+ type: 'object',
1040
+ properties: {
1041
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
1042
+ remote: { type: 'string', description: 'Remote to fetch from. Default: "origin".' },
1043
+ prune: { type: 'boolean', description: 'Also delete local remote-tracking refs that no longer exist on the remote (--prune). Default: false.' },
1044
+ },
1045
+ required: [],
1046
+ },
1047
+ };
1048
+ export async function executeFetch(params, context) {
1049
+ const resolved = await resolveRepo(params, context);
1050
+ if ('error' in resolved)
1051
+ return resolved.error;
1052
+ const { repo } = resolved;
1053
+ const remote = typeof params.remote === 'string' && params.remote.length > 0 ? params.remote : 'origin';
1054
+ const remoteInvalid = validateRefName(remote, 'remote');
1055
+ if (remoteInvalid)
1056
+ return remoteInvalid;
1057
+ const args = ['fetch', remote];
1058
+ if (params.prune === true)
1059
+ args.push('--prune');
1060
+ try {
1061
+ const { stdout, stderr } = await runGit(repo, args);
1062
+ const output = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
1063
+ return JSON.stringify({
1064
+ success: true,
1065
+ remote,
1066
+ prune: params.prune === true,
1067
+ output: output || 'Already up to date.',
1068
+ });
1069
+ }
1070
+ catch (err) {
1071
+ return `Error: ${gitErrorMessage(err)}`;
1072
+ }
1073
+ }
1074
+ // ─── runner_git_pull ────────────────────────
1075
+ const pullDefinition = {
1076
+ name: 'runner_git_pull',
1077
+ description: 'Pull a branch from a remote (fetch + integrate) into a clean working tree. Defaults to --ff-only (fast-forward only, never a merge commit); pass strategy "rebase" or "merge" for diverged branches. Aborts cleanly on conflict, leaving the branch unchanged.',
1078
+ parameters: {
1079
+ type: 'object',
1080
+ properties: {
1081
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
1082
+ remote: { type: 'string', description: 'Remote to pull from. Default: "origin".' },
1083
+ branch: { type: 'string', description: 'Branch to pull. Default: the current branch.' },
1084
+ strategy: { type: 'string', enum: ['ff-only', 'rebase', 'merge'], description: 'How to integrate remote commits. "ff-only" (default) fast-forwards or fails; "rebase" replays local commits on top; "merge" creates a merge commit.' },
1085
+ },
1086
+ required: [],
1087
+ },
1088
+ };
1089
+ export async function executePull(params, context) {
1090
+ const resolved = await resolveRepo(params, context, { changesTree: true });
1091
+ if ('error' in resolved)
1092
+ return resolved.error;
1093
+ const { repo } = resolved;
1094
+ const remote = typeof params.remote === 'string' && params.remote.length > 0 ? params.remote : 'origin';
1095
+ const remoteInvalid = validateRefName(remote, 'remote');
1096
+ if (remoteInvalid)
1097
+ return remoteInvalid;
1098
+ const strategy = params.strategy === 'rebase' || params.strategy === 'merge' ? params.strategy : 'ff-only';
1099
+ let branch = typeof params.branch === 'string' && params.branch.length > 0 ? params.branch : '';
1100
+ if (!branch) {
1101
+ const current = await currentBranch(repo);
1102
+ if (!current)
1103
+ return 'Error: detached HEAD - pass an explicit "branch" to pull.';
1104
+ branch = current;
1105
+ }
1106
+ const branchInvalid = validateRefName(branch);
1107
+ if (branchInvalid)
1108
+ return branchInvalid;
1109
+ if (!(await isClean(repo))) {
1110
+ return 'Error: refusing to pull into a dirty working tree. Commit your changes or stash them (runner_git_stash) first, then pull.';
1111
+ }
1112
+ const flag = strategy === 'rebase' ? '--rebase' : strategy === 'merge' ? '--no-rebase' : '--ff-only';
1113
+ try {
1114
+ const identity = await identityArgs(repo, context);
1115
+ const { stdout, stderr } = await runGit(repo, [...identity, 'pull', flag, remote, branch]);
1116
+ const output = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
1117
+ return JSON.stringify({
1118
+ success: true,
1119
+ remote,
1120
+ branch,
1121
+ strategy,
1122
+ output: output || 'Already up to date.',
1123
+ });
1124
+ }
1125
+ catch (err) {
1126
+ // Leave the tree clean: unwind any half-applied rebase/merge so the agent
1127
+ // is not stranded in a conflicted state (there is no reset tool to escape).
1128
+ if (strategy === 'rebase')
1129
+ await runGit(repo, ['rebase', '--abort']).catch(() => { });
1130
+ else if (strategy === 'merge')
1131
+ await runGit(repo, ['merge', '--abort']).catch(() => { });
1132
+ const hint = strategy === 'ff-only'
1133
+ ? ' The branches have diverged, so a fast-forward is impossible. Re-run with strategy "rebase" or "merge".'
1134
+ : ' The pull hit conflicts and was aborted; your branch is unchanged. Resolve by pulling in a worktree or ask the user for guidance.';
1135
+ return `Error: ${gitErrorMessage(err)}${hint}`;
1136
+ }
1137
+ }
1138
+ // ─── runner_git_merge ───────────────────────
1139
+ const mergeDefinition = {
1140
+ name: 'runner_git_merge',
1141
+ description: 'Merge another branch into the current branch on a clean working tree. Aborts cleanly on conflict, leaving the current branch unchanged. Never force-merges or resets.',
1142
+ parameters: {
1143
+ type: 'object',
1144
+ properties: {
1145
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
1146
+ branch: { type: 'string', description: 'Branch (or ref, e.g. "origin/main") to merge INTO the current branch.' },
1147
+ noFf: { type: 'boolean', description: 'Always create a merge commit even when a fast-forward is possible (--no-ff). Default: false.' },
1148
+ },
1149
+ required: ['branch'],
1150
+ },
1151
+ };
1152
+ export async function executeMerge(params, context) {
1153
+ const resolved = await resolveRepo(params, context, { changesTree: true });
1154
+ if ('error' in resolved)
1155
+ return resolved.error;
1156
+ const { repo } = resolved;
1157
+ const branch = typeof params.branch === 'string' ? params.branch : '';
1158
+ const branchInvalid = validateRefName(branch, 'ref');
1159
+ if (branchInvalid)
1160
+ return branchInvalid;
1161
+ const current = await currentBranch(repo);
1162
+ if (!current)
1163
+ return 'Error: detached HEAD - switch to a branch before merging.';
1164
+ if (!(await isClean(repo))) {
1165
+ return 'Error: refusing to merge into a dirty working tree. Commit your changes or stash them (runner_git_stash) first.';
1166
+ }
1167
+ const args = ['merge'];
1168
+ if (params.noFf === true)
1169
+ args.push('--no-ff');
1170
+ args.push(branch);
1171
+ try {
1172
+ const identity = await identityArgs(repo, context);
1173
+ const { stdout, stderr } = await runGit(repo, [...identity, ...args]);
1174
+ const output = [stdout.trim(), stderr.trim()].filter(Boolean).join('\n');
1175
+ return JSON.stringify({
1176
+ success: true,
1177
+ into: current,
1178
+ branch,
1179
+ noFf: params.noFf === true,
1180
+ output: output || 'Already up to date.',
1181
+ });
1182
+ }
1183
+ catch (err) {
1184
+ await runGit(repo, ['merge', '--abort']).catch(() => { });
1185
+ return `Error: ${gitErrorMessage(err)} The merge hit conflicts and was aborted; "${current}" is unchanged. Resolve in a worktree or ask the user for guidance.`;
1186
+ }
1187
+ }
1188
+ // ─── runner_git_stash ───────────────────────
1189
+ const stashDefinition = {
1190
+ name: 'runner_git_stash',
1191
+ description: 'Set aside uncommitted changes so you can switch or pull, then restore them later. Actions: save (stash current changes), pop (re-apply the most recent stash and drop it), list, drop.',
1192
+ parameters: {
1193
+ type: 'object',
1194
+ properties: {
1195
+ repo: { type: 'string', description: 'Repo path relative to the project root. Default: ".".' },
1196
+ action: { type: 'string', enum: ['save', 'pop', 'list', 'drop'], description: 'What to do.' },
1197
+ message: { type: 'string', description: 'save only: optional label for the stash entry.' },
1198
+ includeUntracked: { type: 'boolean', description: 'save only: also stash untracked files (-u). Default: false.' },
1199
+ ref: { type: 'string', description: 'drop only: which stash entry to drop, e.g. "stash@{1}". Default: the most recent.' },
1200
+ },
1201
+ required: ['action'],
1202
+ },
1203
+ };
1204
+ export async function executeStash(params, context) {
1205
+ const resolved = await resolveRepo(params, context, { changesTree: params.action !== 'list' });
1206
+ if ('error' in resolved)
1207
+ return resolved.error;
1208
+ const { repo } = resolved;
1209
+ const action = params.action;
1210
+ try {
1211
+ if (action === 'save') {
1212
+ const args = ['stash', 'push'];
1213
+ if (params.includeUntracked === true)
1214
+ args.push('-u');
1215
+ if (typeof params.message === 'string' && params.message.length > 0) {
1216
+ const message = params.message.trim();
1217
+ if (message.startsWith('-'))
1218
+ return 'Error: message must not start with "-"';
1219
+ args.push('-m', message);
1220
+ }
1221
+ const { stdout } = await runGit(repo, args);
1222
+ const out = stdout.trim();
1223
+ const saved = !/no local changes to save/i.test(out);
1224
+ return JSON.stringify({ success: true, action: 'save', saved, output: out || 'Saved working directory.' });
1225
+ }
1226
+ if (action === 'list') {
1227
+ const { stdout } = await runGit(repo, ['stash', 'list']);
1228
+ const entries = stdout.split('\n').map(l => l.trim()).filter(l => l.length > 0);
1229
+ return JSON.stringify({ repo: params.repo ?? '.', count: entries.length, entries });
1230
+ }
1231
+ if (action === 'pop') {
1232
+ try {
1233
+ const { stdout } = await runGit(repo, ['stash', 'pop']);
1234
+ return JSON.stringify({ success: true, action: 'pop', output: stdout.trim() });
1235
+ }
1236
+ catch (err) {
1237
+ // A conflicting pop keeps the stash entry but leaves conflicts in the
1238
+ // tree; there is no clean auto-abort, so report and let the agent resolve.
1239
+ return `Error: ${gitErrorMessage(err)} The stash could not be applied cleanly (conflicts). The stash entry is preserved; resolve the conflicts or drop it once handled.`;
1240
+ }
1241
+ }
1242
+ if (action === 'drop') {
1243
+ const args = ['stash', 'drop'];
1244
+ if (typeof params.ref === 'string' && params.ref.length > 0) {
1245
+ const ref = params.ref;
1246
+ if (!/^stash@\{\d+\}$/.test(ref))
1247
+ return `Error: invalid stash ref "${ref}". Use e.g. "stash@{0}".`;
1248
+ args.push(ref);
1249
+ }
1250
+ const { stdout } = await runGit(repo, args);
1251
+ return JSON.stringify({ success: true, action: 'drop', output: stdout.trim() });
1252
+ }
1253
+ return `Error: unknown action "${action}". Use save, pop, list or drop.`;
1254
+ }
1255
+ catch (err) {
1256
+ return `Error: ${gitErrorMessage(err)}`;
1257
+ }
1258
+ }
1259
+ // ─── Exports ────────────────────────────────
1260
+ export const gitTools = [
1261
+ { definition: statusDefinition, execute: executeStatus },
1262
+ { definition: logDefinition, execute: executeLog },
1263
+ { definition: diffDefinition, execute: executeDiff },
1264
+ { definition: worktreeDefinition, execute: executeWorktree },
1265
+ { definition: branchDefinition, execute: executeBranch },
1266
+ { definition: fetchDefinition, execute: executeFetch },
1267
+ { definition: pullDefinition, execute: executePull },
1268
+ { definition: mergeDefinition, execute: executeMerge },
1269
+ { definition: stashDefinition, execute: executeStash },
1270
+ { definition: commitDefinition, execute: executeCommit },
1271
+ { definition: pushDefinition, execute: executePush },
1272
+ ];