@nordhavnhq/runner 0.0.0-stage → 0.95.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 +80 -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 +42 -0
  13. package/dist/cli/link.js +314 -0
  14. package/dist/cli/logs.d.ts +2 -0
  15. package/dist/cli/logs.js +147 -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 +81 -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 +145 -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 +1325 -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,765 @@
1
+ import { streamInference } from '../inference.js';
2
+ import { sendWsTaskDone, sendWsTaskToolUse, sendWsTaskMessage, sendWsTaskSteerApplied, } from '../connection.js';
3
+ import { steerBody, steerIds } from './pending-steers.js';
4
+ import { buildUserMessage } from './messages.js';
5
+ import { buildScratchPromptNote } from './scratch-prompt.js';
6
+ import { buildProjectInstructionsNote } from './project-instructions.js';
7
+ import { writeScopeContext } from './write-scope.js';
8
+ import { executeMcpTool } from '../tools/mcp.js';
9
+ import { autoLoadToolDef, appendAutoLoadInstructions } from './auto-load.js';
10
+ import { applyUnloadToolset } from './unload-toolset.js';
11
+ import { postStudioLog } from '../mcp.js';
12
+ import { dispatchScratchKey } from '../contract/calls.js';
13
+ import { MAX_TASK_TOOL_ROUNDS } from '../constants.js';
14
+ import { extractValidationFromUpdateTaskOutput, formatValidationFeedback, } from './task-validation.js';
15
+ import { pendingActionInReply, pendingActionNudge, deliversTaskWork, isRunEndingTaskStatus, runEndingReply, TOOL_RESULT_MAX_CHARS } from '../contract/loop.js';
16
+ import { buildUnknownToolError } from '../contract/tool-names.js';
17
+ import { runTaskLoop } from './phased-loop.js';
18
+ import { emitEvent } from './events.js';
19
+ import { backgroundWaitMs, formatBackgroundCommandsNote, formatBackgroundWaitMessage, } from './background-commands.js';
20
+ // Reserved task-memory key holding the agent's pinned-notes working set, so the
21
+ // `studio_pin` facts survive a task interruption / resume (a fresh dispatch of the
22
+ // same task starts a new in-memory loop with empty pins otherwise). Mirrors the
23
+ // studio-side run-task.ts. Persisted via the studio memory endpoint; task-scoped
24
+ // so it is NOT loaded into the `## Memory` prompt block.
25
+ const PINNED_NOTES_MEMORY_KEY = '__task_pins';
26
+ /** Restore the pinned-notes working set from task-scoped studio memory. */
27
+ async function loadPinnedNotes(studioUrl, token, taskUid) {
28
+ if (!taskUid)
29
+ return [];
30
+ try {
31
+ const url = `${studioUrl}/api/agents/memory?scope=task&taskUid=${encodeURIComponent(taskUid)}`;
32
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
33
+ if (!res.ok)
34
+ return [];
35
+ const body = (await res.json());
36
+ const row = body.memories?.find(m => m.key === PINNED_NOTES_MEMORY_KEY);
37
+ if (!row?.value)
38
+ return [];
39
+ const parsed = JSON.parse(row.value);
40
+ if (!Array.isArray(parsed))
41
+ return [];
42
+ return parsed.filter((e) => Array.isArray(e) && e.length === 2 && typeof e[0] === 'string' && typeof e[1] === 'string');
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ }
48
+ /** Persist the pinned notes to task-scoped studio memory (fire-and-forget). */
49
+ function persistPinnedNotes(studioUrl, token, taskUid, notes) {
50
+ if (!taskUid)
51
+ return;
52
+ void fetch(`${studioUrl}/api/agents/memory`, {
53
+ method: 'POST',
54
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
55
+ body: JSON.stringify({
56
+ key: PINNED_NOTES_MEMORY_KEY,
57
+ value: JSON.stringify(notes),
58
+ scope: 'task',
59
+ taskUid,
60
+ isEditable: false,
61
+ }),
62
+ }).catch(() => { });
63
+ }
64
+ // ─── Result-reply extraction ──────────────────────────────────────────
65
+ /**
66
+ * Pull a human-readable reply out of the resultJson the agent submitted via
67
+ * studio_update_task. Used when we short-circuit the loop after a terminal
68
+ * status update - the resultJson IS the deliverable.
69
+ */
70
+ function extractReplyFromResultJson(resultJson) {
71
+ if (!resultJson || typeof resultJson !== 'object')
72
+ return null;
73
+ const r = resultJson;
74
+ if (typeof r.output === 'string' && r.output.trim())
75
+ return r.output;
76
+ if (r.structured && typeof r.structured === 'object') {
77
+ const s = r.structured;
78
+ const keys = Object.keys(s);
79
+ const only = keys.length === 1 ? s[keys[0]] : undefined;
80
+ if (typeof only === 'string')
81
+ return only;
82
+ }
83
+ if (typeof r.summary === 'string' && r.summary.trim())
84
+ return r.summary;
85
+ return null;
86
+ }
87
+ // ─── Background commands at run end ───────────────────────────────────
88
+ /**
89
+ * Wait for the background commands of this dispatch and return the reply with
90
+ * a note for each one that still runs or exited non-zero. The wait is shown on
91
+ * the run's timeline (which also keeps the run's slot alive meanwhile). An
92
+ * empty reply (a stop on a question without a line) stays empty: the note then
93
+ * only goes to the event log.
94
+ */
95
+ async function addBackgroundCommandsNote(wait, opts) {
96
+ const outcome = await wait(opts.queueUid, {
97
+ timeoutMs: opts.timeoutMs,
98
+ signal: opts.signal,
99
+ onWait: running => sendWsTaskMessage(opts.socket, opts.queueId, formatBackgroundWaitMessage(running, opts.timeoutMs)),
100
+ });
101
+ const note = opts.signal.aborted ? null : formatBackgroundCommandsNote(outcome);
102
+ if (!note)
103
+ return opts.reply;
104
+ emitEvent({ kind: 'note', level: 'warn', channel: 'task', agentSlug: opts.agentSlug, queueUid: opts.queueUid, message: note });
105
+ return opts.reply.trim() ? `${opts.reply}\n\n${note}` : opts.reply;
106
+ }
107
+ // ─── Main handler ─────────────────────────────────────────────────────
108
+ export function createHandleTask(deps) {
109
+ const { agent, agentName, config, agentHome, resolveProject, resolveWorkspaceFolders, resolveScratch, resolveCallerScratch, findProjectInstructions, inspectScratch, spillToolOutput, prepareWorktree, resolveWriteScope, waitForBackgroundCommands, activeTaskAborts, pendingTaskSteers, toolProvider, debug } = deps;
110
+ return async function handleTask(socket, task) {
111
+ const taskInput = task.input;
112
+ const isDelegation = !!taskInput?.requestingAgent && !taskInput?.taskUid;
113
+ const taskLabel = taskInput?.taskUid
114
+ ? `Task ${taskInput.taskUid}`
115
+ : isDelegation
116
+ ? `Call from ${taskInput.requestingAgent}`
117
+ : `Queue #${task.queueId}`;
118
+ emitEvent({
119
+ kind: 'dispatch.received',
120
+ channel: 'task',
121
+ agentSlug: agent.slug,
122
+ queueUid: task.queueUid,
123
+ messageCount: 1,
124
+ preview: (taskInput?.task || task.action || 'delegated task').slice(0, 80),
125
+ });
126
+ if (debug) {
127
+ postStudioLog(config.studioUrl, agent.token, {
128
+ level: 'debug',
129
+ type: 'task.dispatch',
130
+ message: `Task dispatch received - ${taskLabel}`,
131
+ data: { input: task.input, action: task.action, queueId: task.queueId },
132
+ queueUid: task.queueUid,
133
+ });
134
+ }
135
+ const abortController = new AbortController();
136
+ activeTaskAborts.set(task.queueId, abortController);
137
+ const signal = abortController.signal;
138
+ const taskStart = Date.now();
139
+ let totalInputTokens;
140
+ let totalOutputTokens;
141
+ let totalCostMicros;
142
+ // Last round's input size = real context occupancy. Reported as
143
+ // `contextTokens` so the task meter (which reads the LAST non-zero
144
+ // context_tokens across the task's dispatches) shows true current occupancy
145
+ // instead of 0. Without it external tasks never populate context_tokens and
146
+ // the meter shows 0%. Deliberately a point-in-time reading, not a peak: the
147
+ // loop's rolling summary shrinks the transcript and the meter must follow it
148
+ // down. See getTasksUsageStats in apps/server/server/utils/task/task.ts.
149
+ let totalContextTokens;
150
+ let finalReply;
151
+ let finalModel;
152
+ try {
153
+ // Mutable per-dispatch tool registry. Seeded from the studio's bootstrap
154
+ // set; the model expands it mid-loop via `studio_load_toolset`, which
155
+ // streams new defs back through `ctx.loadTools` (defined below) and into
156
+ // this map. The agentic loop re-reads it at the top of every round.
157
+ const registry = new Map();
158
+ for (const def of task.agentConfig?.toolDefs ?? []) {
159
+ registry.set(def.name, def);
160
+ }
161
+ const toolGroups = task.agentConfig?.toolGroups ?? [];
162
+ const groupForToolName = new Map();
163
+ for (const g of toolGroups) {
164
+ for (const t of g.tools ?? [])
165
+ groupForToolName.set(t.name, g);
166
+ }
167
+ // This dispatch's throwaway scratch dir - jailed like the agent home, but
168
+ // reaped on a TTL so temp files never accumulate in the project checkout.
169
+ // Keyed by the task/queue uid so a resumed dispatch reuses the same dir.
170
+ const scratchRoot = resolveScratch(dispatchScratchKey({ kind: 'task', taskUid: taskInput?.taskUid, queueUid: task.queueUid, queueId: task.queueId }));
171
+ // A call may READ its caller's scratch: a caller hands its copies work
172
+ // in files there, and a copy that cannot open them only fails.
173
+ const caller = isDelegation ? taskInput?.caller : undefined;
174
+ const callerScratch = caller?.agentSlug && caller.scratchKey && resolveCallerScratch
175
+ ? resolveCallerScratch(caller.agentSlug, caller.scratchKey)
176
+ : null;
177
+ // System prompt + task instruction are fully assembled studio-side; we
178
+ // only append the concrete scratch path (the studio can't know this
179
+ // machine's local paths) so the agent knows where to put temp files.
180
+ // Relative tool paths resolve against the project THIS task is bound to -
181
+ // the dispatch carries the project, and the agent is cross-project, so
182
+ // this differs per task. Falls back to the agent's home when that
183
+ // project isn't available on this machine.
184
+ const checkout = resolveProject(task.project?.folder);
185
+ // A project that gives every code run its own worktree: the run works in
186
+ // it, on its branch, and never sees the shared checkout. When it cannot
187
+ // be made the run says so and works in the checkout, as before.
188
+ const worktree = task.project?.worktreeBranch && checkout !== agentHome && prepareWorktree
189
+ ? await prepareWorktree(checkout, task.project.worktreeBranch)
190
+ : null;
191
+ const projectRoot = worktree && 'path' in worktree ? worktree.path : checkout;
192
+ // The project's unmuted workspace folders: extra jail roots, checked against
193
+ // the checkout (a worktree lives under the checkout's own folder).
194
+ const workspaceRoots = checkout !== agentHome && resolveWorkspaceFolders
195
+ ? resolveWorkspaceFolders(task.project?.workspaceFolders, checkout)
196
+ : [];
197
+ // The session's scope applies to the root the run works in (its own
198
+ // worktree when it has one), never to an unlinked project's home.
199
+ const writeScope = task.project?.scope && projectRoot !== agentHome && resolveWriteScope
200
+ ? resolveWriteScope(projectRoot, task.project.scope)
201
+ : null;
202
+ const worktreeNote = worktree && 'error' in worktree
203
+ ? `\n\nThe own worktree for this run could not be made (${worktree.error}). You work in the shared checkout instead: never switch branches there, and commit only the files you changed.`
204
+ : '';
205
+ const systemPrompt = `${task.systemPrompt}${worktreeNote}${buildScratchPromptNote(scratchRoot, callerScratch)}${buildProjectInstructionsNote(findProjectInstructions, projectRoot, agentHome)}`;
206
+ const initialMessages = [
207
+ buildUserMessage({ text: task.userPrompt, attachments: taskInput?.files ?? [] }),
208
+ ];
209
+ const attachments = [];
210
+ // Per-call sink for inline image bytes (capture tools with `keep:false`).
211
+ // Drained inside `executeTool` and threaded into the agentic loop via
212
+ // `ToolOutcome.images`, which `buildToolResultMessage` embeds as a v6
213
+ // `content` output so the model sees the bytes without an extra round.
214
+ const pendingToolImages = [];
215
+ const ctx = {
216
+ agentSlug: agent.slug,
217
+ agentName: agentName?.(),
218
+ organisationSlug: agent.organisationSlug,
219
+ projectRoot,
220
+ ...(workspaceRoots.length ? { workspaceRoots } : {}),
221
+ agentHome,
222
+ scratchRoot,
223
+ ...(callerScratch && callerScratch !== scratchRoot ? { readOnlyRoots: [callerScratch] } : {}),
224
+ ...writeScopeContext(writeScope),
225
+ projectSlug: task.project?.slug,
226
+ conversationId: taskInput?.originConversation?.uid,
227
+ queueUid: task.queueUid,
228
+ taskUid: taskInput?.taskUid,
229
+ // The files of the checkout this task (or a call's caller) changed itself
230
+ // and has not committed: `runner_git_status` names them `yours`. Only in a checkout.
231
+ ...(task.project && projectRoot !== agentHome ? { ownFiles: new Set(task.project.ownFiles ?? []), touchedFiles: new WeakMap() } : {}),
232
+ signal,
233
+ delegateTimeoutMs: task.agentConfig?.delegateTimeoutMs,
234
+ // Only a budget the studio set: a task without one has no clock to
235
+ // hold a call to (see `maxLoopMs` below).
236
+ runDeadlineAt: task.agentConfig?.maxLoopMs != null ? Date.now() + task.agentConfig.maxLoopMs : undefined,
237
+ studioUrl: config.studioUrl,
238
+ agentToken: agent.token,
239
+ socket,
240
+ attachments,
241
+ pendingToolImages,
242
+ loadTools: (defs) => {
243
+ for (const def of defs)
244
+ registry.set(def.name, def);
245
+ },
246
+ hasTool: (name) => registry.has(name),
247
+ };
248
+ // Inference adapter. Tasks don't stream to the studio mid-token (no live
249
+ // "typing" UI on the activity feed), so no streaming callbacks are
250
+ // passed - mid-round narration is surfaced via `task:message` frames
251
+ // through the `onAssistantNarration` hook below.
252
+ // On a model slot when the run says so: an explore copy on its explore
253
+ // model, a phase of a run that plans first on that phase's (`inferenceFor`).
254
+ const inferenceOn = (slot, phase) => (req, sig) => streamInference({
255
+ studioUrl: config.studioUrl,
256
+ connectionToken: agent.token,
257
+ messages: req.messages,
258
+ tools: req.tools,
259
+ ...(req.toolChoice ? { toolChoice: req.toolChoice } : {}),
260
+ queueUid: task.queueUid,
261
+ signal: sig,
262
+ agentSlug: agent.slug,
263
+ inference: task.inference,
264
+ ...(slot ? { slot, phase } : {}),
265
+ ...(req.purpose ? { purpose: req.purpose } : {}),
266
+ });
267
+ const inferenceSlot = task.agentConfig?.inferenceSlot;
268
+ const callInference = inferenceOn(inferenceSlot, inferenceSlot);
269
+ // Rolling-summary transport. Bound to the agent's configured compaction
270
+ // model when set, so a fold runs on a cheap/fast model instead of the
271
+ // agent's reasoning model. Undefined when not configured -> the loop
272
+ // reuses `callInference`.
273
+ //
274
+ // The `inference` hint is deliberately NOT forwarded here: it switches the
275
+ // runner to direct-mode against the AGENT's provider/baseUrl, which would
276
+ // silently ignore `modelOverride` and bill the expensive model anyway. The
277
+ // compaction call always goes through the studio proxy, which is what
278
+ // resolves the compaction provider.
279
+ const compactionOverride = task.agentConfig?.compactionModelOverride;
280
+ const callSummaryInference = compactionOverride
281
+ ? (req, sig) => streamInference({
282
+ studioUrl: config.studioUrl,
283
+ connectionToken: agent.token,
284
+ messages: req.messages,
285
+ tools: req.tools,
286
+ ...(req.toolChoice ? { toolChoice: req.toolChoice } : {}),
287
+ queueUid: task.queueUid,
288
+ signal: sig,
289
+ agentSlug: agent.slug,
290
+ modelOverride: compactionOverride,
291
+ })
292
+ : undefined;
293
+ // Validation + terminal-status state. Closed over by the executeTool
294
+ // adapter (which writes) and the onAfterRound hook (which reads it to
295
+ // decide whether to stop the loop / inject feedback).
296
+ let structuredResultSubmitted = false;
297
+ const validationRetriesConfigured = task.agentConfig?.validationRetries;
298
+ let validationRetriesLeft = typeof validationRetriesConfigured === 'number' && validationRetriesConfigured >= 0
299
+ ? Math.floor(validationRetriesConfigured)
300
+ : 2;
301
+ let pendingValidationFeedback = null;
302
+ let lastValidationErrors = null;
303
+ let terminalStatusSubmitted = null;
304
+ let terminalReplyOverride = null;
305
+ // Whether this run pushed anything durable to the studio (an asset upload
306
+ // or a file save). Gates the end-of-run scratch heads-up: a run that
307
+ // persisted is assumed to have handled its own output, so we stay quiet.
308
+ let persistedToStudio = false;
309
+ // Tool-execution adapter - owns local-vs-MCP routing, WS
310
+ // `task:tool-use` framing, per-tool stdout logging, event emission, and
311
+ // the schema-validation + terminal-status detection that fires when the
312
+ // agent calls `studio_update_task` on the current task. Mirrors the
313
+ // OS-side `runInternalTask` decision matrix; keep them aligned.
314
+ const executeTool = async (call, toolDef) => {
315
+ // `studio_unload_toolset` carries `mcpPath: null` and is not a local
316
+ // tool: it only mutates this dispatch's registry, which the provider
317
+ // cannot see. Routed BEFORE the auto-load and unknown-tool branches
318
+ // below, which would otherwise reject it for having no path at all.
319
+ // Mirrors the studio-side interception in internal-runtime/adapters.ts.
320
+ if (toolDef && call.name === 'studio_unload_toolset') {
321
+ const unloadStart = Date.now();
322
+ sendWsTaskToolUse(socket, task.queueId, call.name, 'running', call.arguments);
323
+ emitEvent({
324
+ kind: 'tool.start',
325
+ agentSlug: agent.slug,
326
+ tool: call.name,
327
+ queueUid: task.queueUid,
328
+ argsBytes: JSON.stringify(call.arguments ?? {}).length,
329
+ });
330
+ const { result, isError } = applyUnloadToolset(call.arguments, registry, groupForToolName);
331
+ const durationMs = Date.now() - unloadStart;
332
+ sendWsTaskToolUse(socket, task.queueId, call.name, isError ? 'error' : 'done', call.arguments, result, durationMs);
333
+ emitEvent({
334
+ kind: 'tool.end',
335
+ agentSlug: agent.slug,
336
+ tool: call.name,
337
+ queueUid: task.queueUid,
338
+ durMs: durationMs,
339
+ ...(isError ? { error: result } : {}),
340
+ });
341
+ return { result, isError, durationMs };
342
+ }
343
+ // First-use auto-load: a real, granted tool the model called before
344
+ // its schema landed in this dispatch's registry. Pull it in-band and
345
+ // run the call this same step instead of bouncing with "load and
346
+ // retry". Mirrors the studio-side path in internal-runtime/adapters.ts.
347
+ let resolvedDef = toolDef;
348
+ let autoLoaded = false;
349
+ if (!resolvedDef && groupForToolName.has(call.name)) {
350
+ resolvedDef = await autoLoadToolDef(call.name, registry, ctx);
351
+ autoLoaded = resolvedDef !== undefined;
352
+ }
353
+ // Unknown tool - auto-load couldn't resolve it. Surface a helpful
354
+ // "load the toolset" hint and short-circuit.
355
+ if (!resolvedDef || (!resolvedDef.mcpPath && !toolProvider.isLocalTool(call.name))) {
356
+ const errMsg = buildUnknownToolError(call.name, groupForToolName);
357
+ sendWsTaskToolUse(socket, task.queueId, call.name, 'error', call.arguments, errMsg, 0);
358
+ return { result: errMsg, isError: true, durationMs: 0 };
359
+ }
360
+ sendWsTaskToolUse(socket, task.queueId, call.name, 'running', call.arguments);
361
+ const toolStart = Date.now();
362
+ emitEvent({
363
+ kind: 'tool.start',
364
+ agentSlug: agent.slug,
365
+ tool: call.name,
366
+ queueUid: task.queueUid,
367
+ argsBytes: JSON.stringify(call.arguments ?? {}).length,
368
+ });
369
+ let result;
370
+ let isError;
371
+ // Reset before exec so only this call's pushes are captured. Only
372
+ // local capture tools push (keep:false mode); MCP tools never do.
373
+ pendingToolImages.length = 0;
374
+ try {
375
+ if (resolvedDef.mcpPath) {
376
+ result = await executeMcpTool(resolvedDef, call.arguments, ctx);
377
+ }
378
+ else {
379
+ result = await toolProvider.executeLocalTool(call.name, call.arguments, ctx);
380
+ }
381
+ isError = result.startsWith('Error:');
382
+ }
383
+ catch (err) {
384
+ result = `Error: ${err.message}`;
385
+ isError = true;
386
+ }
387
+ // Note a successful durable persist so the scratch heads-up can stay
388
+ // quiet for runs that clearly moved their output out of scratch.
389
+ if (!isError && (call.name === 'runner_upload_file' || call.name === 'studio_save_file')) {
390
+ persistedToStudio = true;
391
+ }
392
+ // Rich first-use fallback: the call errored on a tool we just
393
+ // auto-loaded, so the model formed its args blind. Append the tool's
394
+ // full instructions so the next round can correct instead of guessing.
395
+ if (autoLoaded && isError) {
396
+ result = await appendAutoLoadInstructions(call.name, result, ctx);
397
+ }
398
+ const durationMs = Date.now() - toolStart;
399
+ sendWsTaskToolUse(socket, task.queueId, call.name, isError ? 'error' : 'done', call.arguments, result, durationMs, ctx.touchedFiles?.get(call.arguments));
400
+ emitEvent({
401
+ kind: 'tool.end',
402
+ agentSlug: agent.slug,
403
+ tool: call.name,
404
+ queueUid: task.queueUid,
405
+ durMs: durationMs,
406
+ ...(isError ? { error: result } : {}),
407
+ });
408
+ // studio_update_task: validate the structured result and detect
409
+ // terminal status. Only react when the underlying MCP call succeeded
410
+ // - errored calls leave state untouched.
411
+ if (call.name === 'studio_update_task' && !isError) {
412
+ const args = call.arguments;
413
+ if (args?.resultJson) {
414
+ const validation = extractValidationFromUpdateTaskOutput(result);
415
+ if (validation && validation.valid === false) {
416
+ lastValidationErrors = validation.errors ?? [];
417
+ if (validationRetriesLeft > 0) {
418
+ validationRetriesLeft--;
419
+ pendingValidationFeedback = formatValidationFeedback(validation.errors ?? [], validationRetriesLeft);
420
+ emitEvent({ kind: 'note', level: 'info', channel: 'task', agentSlug: agent.slug, queueUid: task.queueUid, message: `schema validation failed (${validation.errors?.length ?? 0} errors): retrying (${validationRetriesLeft} left)` });
421
+ }
422
+ else {
423
+ emitEvent({ kind: 'note', level: 'warn', channel: 'task', agentSlug: agent.slug, queueUid: task.queueUid, message: `schema validation failed (${validation.errors?.length ?? 0} errors): no retries left` });
424
+ }
425
+ }
426
+ else {
427
+ lastValidationErrors = null;
428
+ structuredResultSubmitted = true;
429
+ }
430
+ }
431
+ const statusArg = args?.status;
432
+ const targetUidArg = (args?.taskUid ?? args?.uid);
433
+ const targetsCurrentTask = !targetUidArg || targetUidArg === taskInput?.taskUid;
434
+ // `in_review` and `waiting` end the run like `done`: the work is
435
+ // delivered, and a sign-off or an answer from outside is not another
436
+ // round. The rule is the agent contract's (RUN_ENDING_TASK_STATUSES).
437
+ const doneOnInvalidSchema = deliversTaskWork(statusArg)
438
+ && !!task.schemaReminder && !!lastValidationErrors;
439
+ if (targetsCurrentTask
440
+ && isRunEndingTaskStatus(statusArg)
441
+ && !doneOnInvalidSchema) {
442
+ terminalStatusSubmitted = statusArg;
443
+ const replyFromResult = extractReplyFromResultJson(args?.resultJson);
444
+ if (replyFromResult)
445
+ terminalReplyOverride = replyFromResult;
446
+ }
447
+ else if (doneOnInvalidSchema && targetsCurrentTask && validationRetriesLeft === 0) {
448
+ pendingValidationFeedback =
449
+ 'Your `done` call was rejected: the structured result has failed schema validation on every retry, and there are no retries remaining. The task will be marked failed. Do not call `studio_update_task` again; end your turn.';
450
+ terminalStatusSubmitted = 'failed';
451
+ terminalReplyOverride = `Schema validation failed after all retries - ${(lastValidationErrors ?? []).map(e => `${e.path}: ${e.message}`).join('; ')}`;
452
+ }
453
+ }
454
+ const inlineImages = pendingToolImages.splice(0);
455
+ return inlineImages.length > 0
456
+ ? { result, isError, durationMs, images: inlineImages }
457
+ : { result, isError, durationMs };
458
+ };
459
+ // Hooks wired:
460
+ // - `onRoundStart` drains any `task:steer` messages queued by the
461
+ // studio between rounds and injects them as a user message.
462
+ // - `hasPendingSteer` lets the loop cut a tool round short once a steer
463
+ // is queued, so it lands after one tool instead of all of them.
464
+ // - `onEmptyToolCalls` first drains a steer that came in during the
465
+ // round that ended with a plain reply: the loop breaks before the
466
+ // next `onRoundStart`, so without this the steer was dropped.
467
+ // - `onAssistantNarration` streams the assistant's mid-loop narration
468
+ // via `task:message` frames so the activity log shows reasoning
469
+ // between tool rounds.
470
+ // - `onEmptyToolCalls` replays the studio-supplied `schemaReminder`
471
+ // when the task carries a result schema and the agent ended its
472
+ // turn without submitting a valid structured result. Skipped once
473
+ // `structuredResultSubmitted` is true, because the reminder text
474
+ // ("you still need to save the result") becomes a lie post-submit
475
+ // and would prod the model to overwrite a clean result. Mirrors
476
+ // the same guard in OS-side run-task.ts.
477
+ // - `onAfterRound` flushes pending validation feedback and stops the
478
+ // loop once a terminal `studio_update_task` has been observed.
479
+ // - `onInferenceInput`/`Output` mirror the verbose `--debug` logs the
480
+ // old inlined loop emitted, only attached when debug is on.
481
+ const drainSteerInstruction = () => {
482
+ const steers = pendingTaskSteers.get(task.queueId);
483
+ if (!steers || steers.length === 0)
484
+ return null;
485
+ pendingTaskSteers.delete(task.queueId);
486
+ const body = steerBody(steers);
487
+ // The lines waiting above the input move into the log here.
488
+ sendWsTaskSteerApplied(socket, task.queueId, steerIds(steers));
489
+ emitEvent({ kind: 'note', level: 'info', channel: 'task', agentSlug: agent.slug, queueUid: task.queueUid, message: `applied ${steers.length} steer(s)` });
490
+ return `[User steer]\n${body}\n\nAcknowledge briefly and adjust your approach accordingly. Continue working on the task.`;
491
+ };
492
+ const schemaReminder = task.schemaReminder;
493
+ let pendingActionNudged = false;
494
+ const hooks = {
495
+ onRoundStart: () => {
496
+ const instruction = drainSteerInstruction();
497
+ return instruction ? { injectUserMessage: instruction } : undefined;
498
+ },
499
+ hasPendingSteer: () => (pendingTaskSteers.get(task.queueId)?.length ?? 0) > 0,
500
+ onEmptyToolCalls: (round, reply) => {
501
+ // The reply this round wrote is replaced by the next one: sent first,
502
+ // so it stands above the steer it did not see.
503
+ const kept = reply.trim();
504
+ if (kept && (pendingTaskSteers.get(task.queueId)?.length ?? 0) > 0) {
505
+ sendWsTaskMessage(socket, task.queueId, kept, undefined, round);
506
+ }
507
+ const instruction = drainSteerInstruction();
508
+ if (instruction)
509
+ return { continueWithUserMessage: instruction };
510
+ if (schemaReminder && !structuredResultSubmitted)
511
+ return { continueWithUserMessage: schemaReminder };
512
+ // A reply that ends announcing a step it never took: once per run.
513
+ if (!pendingActionNudged) {
514
+ const action = pendingActionInReply(reply);
515
+ if (action) {
516
+ pendingActionNudged = true;
517
+ return { continueWithUserMessage: pendingActionNudge(action) };
518
+ }
519
+ }
520
+ },
521
+ onAssistantNarration: (round, narration, thoughts) => {
522
+ sendWsTaskMessage(socket, task.queueId, narration, thoughts ?? undefined, round);
523
+ },
524
+ onAfterRound: () => {
525
+ const feedback = pendingValidationFeedback;
526
+ pendingValidationFeedback = null;
527
+ if (terminalStatusSubmitted) {
528
+ emitEvent({ kind: 'note', level: 'info', channel: 'task', agentSlug: agent.slug, queueUid: task.queueUid, message: `terminal '${terminalStatusSubmitted}' submitted` });
529
+ const base = terminalReplyOverride
530
+ ? { stop: true, overrideFinalReply: terminalReplyOverride }
531
+ : { stop: true };
532
+ return feedback ? { ...base, injectUserMessage: feedback } : base;
533
+ }
534
+ if (feedback)
535
+ return { injectUserMessage: feedback };
536
+ },
537
+ };
538
+ if (debug) {
539
+ hooks.onInferenceInput = (round, messages, tools) => {
540
+ postStudioLog(config.studioUrl, agent.token, {
541
+ level: 'debug',
542
+ type: 'task.inference.input',
543
+ message: `Inference input - round ${round}, ${messages.length} message(s), ${tools.length} tool(s)`,
544
+ data: { round, messages, tools },
545
+ queueUid: task.queueUid,
546
+ });
547
+ };
548
+ hooks.onInferenceOutput = (round, result) => {
549
+ postStudioLog(config.studioUrl, agent.token, {
550
+ level: 'debug',
551
+ type: 'task.inference.output',
552
+ message: `Inference output - round ${round}${result.toolCalls?.length ? `, ${result.toolCalls.length} tool call(s)` : ''}`,
553
+ data: {
554
+ round,
555
+ message: result.message,
556
+ toolCalls: result.toolCalls,
557
+ usage: result.usage,
558
+ model: result.model,
559
+ },
560
+ queueUid: task.queueUid,
561
+ });
562
+ };
563
+ }
564
+ const maxRounds = task.agentConfig?.maxToolRounds ?? MAX_TASK_TOOL_ROUNDS;
565
+ // Per-tool-result cap, the same as a chat's: a task's results are resent
566
+ // just as often, and a task runs for far more rounds. Studio can override
567
+ // it via agentConfig.toolResultTruncateChars.
568
+ const toolResultTruncateChars = task.agentConfig?.toolResultTruncateChars ?? TOOL_RESULT_MAX_CHARS;
569
+ // The inlined loop had no wall-clock cap; preserve that unless the
570
+ // studio ships an explicit `maxLoopMs` (opt-in per agent).
571
+ const maxLoopMs = task.agentConfig?.maxLoopMs ?? Number.MAX_SAFE_INTEGER;
572
+ // Studio ships `maxCostPerTurn` in dollars; the loop counts micros.
573
+ // Same field governs chat turns and task runs - name is overloaded but
574
+ // the intent ("circuit-breaker for runaway spend") is the same.
575
+ const maxCostMicros = task.agentConfig?.maxCostPerTurn !== undefined
576
+ ? Math.round(task.agentConfig.maxCostPerTurn * 1_000_000)
577
+ : undefined;
578
+ // Restore the pinned-notes working set saved by a prior dispatch of this
579
+ // task (resume after interrupt/restart), and persist it on every change so
580
+ // the next dispatch picks up where this one left off.
581
+ const initialPinnedNotes = await loadPinnedNotes(config.studioUrl, agent.token, taskInput?.taskUid);
582
+ const loopResult = await runTaskLoop({
583
+ systemPrompt,
584
+ initialMessages,
585
+ registry,
586
+ callInference,
587
+ ...(callSummaryInference ? { callSummaryInference } : {}),
588
+ executeTool,
589
+ ...(spillToolOutput ? { spillToolOutput: (callId, toolName, text) => spillToolOutput(scratchRoot, callId, toolName, text) } : {}),
590
+ limits: {
591
+ maxRounds,
592
+ maxLoopMs,
593
+ toolResultTruncateChars,
594
+ maxCostMicros,
595
+ contextWindowTokens: task.agentConfig?.contextWindowTokens,
596
+ },
597
+ signal,
598
+ initialPinnedNotes,
599
+ onPinnedNotesChanged: notes => persistPinnedNotes(config.studioUrl, agent.token, taskInput?.taskUid, notes),
600
+ // A task has no persisted conversation to archive - handle
601
+ // studio_compact by folding the in-memory transcript.
602
+ compactInMemory: true,
603
+ // Notes for whoever picks the task up next: full ones when the run
604
+ // stops before it is done, short ones for the reviewer when it handed
605
+ // its work for review or set it waiting. Keep in sync with the studio's
606
+ // run-task.ts.
607
+ writeHandoff: stopReason => stopReason === 'hook-stop'
608
+ ? (terminalStatusSubmitted === 'in_review' || terminalStatusSubmitted === 'waiting') && !isDelegation ? 'review' : false
609
+ : true,
610
+ // A task (not a call) that goes in circles gets one closing round, and
611
+ // is reminded once to pin what it found.
612
+ closeOnLoop: !isDelegation,
613
+ nudgePins: !isDelegation,
614
+ // A call has no todo list on screen; a task does.
615
+ nudgeTodos: !isDelegation,
616
+ hooks,
617
+ }, {
618
+ // A run that plans first: each phase on its own slot (contract/phases.ts).
619
+ phases: task.agentConfig?.phases,
620
+ inferenceFor: (slot, phase) => inferenceOn(slot, phase),
621
+ onPhase: (phase, why) => emitEvent({ kind: 'note', agentSlug: agent.slug, channel: 'task', queueUid: task.queueUid, level: 'info', message: `${phase} phase (${why})` }),
622
+ });
623
+ totalInputTokens = loopResult.totalUsage.inputTokens;
624
+ totalOutputTokens = loopResult.totalUsage.outputTokens;
625
+ totalCostMicros = loopResult.totalUsage.costMicros;
626
+ totalContextTokens = loopResult.totalUsage.contextTokens;
627
+ finalModel = loopResult.finalModel;
628
+ // A run that stopped without the agent closing it out - an empty final
629
+ // turn (forced synthesis included) or a tripped wall-clock/cost circuit
630
+ // breaker - must NOT be recorded as a successful completion: the
631
+ // deliverable was never produced. Surface it as a task error so the
632
+ // studio fails the queue entry (and the linked Task) instead of
633
+ // silently marking it done. The salvaged narration (if any) still
634
+ // ships as the output, so the timeline shows what the agent last said.
635
+ const prematureStopError = !terminalStatusSubmitted
636
+ ? loopResult.stopReason === 'empty'
637
+ ? 'Agent stopped without completing the task: its final turn produced no reply, so the run likely ended before the work was finished.'
638
+ : loopResult.stopReason === 'max-loop-ms'
639
+ ? 'Task run stopped before completion: the wall-clock limit (maxLoopMs) was reached.'
640
+ : loopResult.stopReason === 'max-cost'
641
+ ? `Task run stopped before completion: the cost cap (maxCostPerTurn) was reached (spent $${(totalCostMicros / 1_000_000).toFixed(2)}${maxCostMicros !== undefined ? ` of the $${(maxCostMicros / 1_000_000).toFixed(2)} cap` : ''}).`
642
+ : loopResult.stopReason === 'loop' || loopResult.stopReason === 'stopped'
643
+ ? `Task run stopped before completion. ${loopResult.finalReply}`
644
+ : loopResult.stopReason === 'budget'
645
+ ? `Task run stopped at its budget. ${loopResult.finalReply}`
646
+ : undefined
647
+ : undefined;
648
+ finalReply = loopResult.finalReply;
649
+ // A stop on a question is the exception below: the agent's own line
650
+ // (`askedRunReply`) or nothing, never a canned one.
651
+ if (!finalReply && loopResult.stopReason !== 'awaiting-user') {
652
+ // The visible timeline entry must always say something real. Preserve
653
+ // the fallback messaging the inlined loop used: a terminal submission
654
+ // with no extractable reply still reads as completion; a terminal
655
+ // `failed` submission needs its own wording (surfacing "Task
656
+ // completed." on a failed task is misleading). When neither applies,
657
+ // describe what actually happened - the premature-stop reason if we
658
+ // have one, then the exhausted round-budget string.
659
+ if (terminalStatusSubmitted)
660
+ finalReply = runEndingReply(terminalStatusSubmitted);
661
+ else if (prematureStopError)
662
+ finalReply = prematureStopError;
663
+ else if (loopResult.rounds >= maxRounds)
664
+ finalReply = 'Task reached maximum tool rounds.';
665
+ else
666
+ finalReply = 'The agent ended its run without writing a summary.';
667
+ }
668
+ // Background commands this run started and that may still run: wait for
669
+ // them (capped, cancel ends it) so the result says when they did not end
670
+ // well. A run that stops on a question parks on a person: no wait.
671
+ if (waitForBackgroundCommands && !signal.aborted) {
672
+ finalReply = await addBackgroundCommandsNote(waitForBackgroundCommands, {
673
+ socket,
674
+ queueId: task.queueId,
675
+ queueUid: task.queueUid,
676
+ agentSlug: agent.slug,
677
+ signal,
678
+ timeoutMs: loopResult.stopReason === 'awaiting-user' ? 0 : backgroundWaitMs(Date.now(), ctx.runDeadlineAt),
679
+ reply: finalReply,
680
+ });
681
+ }
682
+ const elapsed = Date.now() - taskStart;
683
+ if (signal.aborted) {
684
+ sendWsTaskDone(socket, task.queueId, 'Cancelled by user.', {
685
+ inputTokens: totalInputTokens,
686
+ outputTokens: totalOutputTokens,
687
+ costMicros: totalCostMicros,
688
+ contextTokens: totalContextTokens,
689
+ model: finalModel,
690
+ }, 'Cancelled by user');
691
+ emitEvent({ kind: 'dispatch.cancelled', channel: 'task', agentSlug: agent.slug, queueUid: task.queueUid });
692
+ return;
693
+ }
694
+ // If the agent had a structured schema to satisfy but every attempt
695
+ // failed validation, mark the queue entry as failed. Same when the
696
+ // agent itself submitted a terminal `failed` status.
697
+ // The cast widens past TS's closure-blind narrowing: `lastValidationErrors`
698
+ // is only ever assigned inside `executeTool`, so at this read site TS
699
+ // still thinks it's `null` and would otherwise treat the truthy branch
700
+ // as dead.
701
+ // Scratch heads-up: if the agent left files in this dispatch's scratch dir
702
+ // and never pushed anything durable to the studio, warn - scratch is reaped
703
+ // on a TTL, so that content is about to be silently lost. Gated on
704
+ // `!persistedToStudio` to stay quiet for runs that clearly saved their
705
+ // output. Informational only (a `note`, no extra loop round); it surfaces
706
+ // to the operator's timeline, not back into the agent.
707
+ if (inspectScratch) {
708
+ const leftInScratch = inspectScratch(scratchRoot);
709
+ if (leftInScratch > 0 && !persistedToStudio) {
710
+ emitEvent({
711
+ kind: 'note',
712
+ level: 'warn',
713
+ channel: 'task',
714
+ agentSlug: agent.slug,
715
+ queueUid: task.queueUid,
716
+ message: `${leftInScratch} file(s) left in scratch and nothing was persisted to the studio. Scratch is auto-deleted on a TTL, so this content will be lost - commit deliverables to the project or upload assets with runner_upload_file / studio_save_file.`,
717
+ });
718
+ }
719
+ }
720
+ const errs = lastValidationErrors;
721
+ const taskError = (task.schemaReminder && errs)
722
+ ? `Schema validation failed: ${errs.map(e => `${e.path} - ${e.message}`).join('; ')}`
723
+ : terminalStatusSubmitted === 'failed'
724
+ ? (terminalReplyOverride || 'Task marked failed by agent')
725
+ : prematureStopError;
726
+ sendWsTaskDone(socket, task.queueId, finalReply, {
727
+ inputTokens: totalInputTokens,
728
+ outputTokens: totalOutputTokens,
729
+ costMicros: totalCostMicros,
730
+ contextTokens: totalContextTokens,
731
+ cachedInputTokens: loopResult.totalUsage.cacheReadTokens,
732
+ cacheCreationTokens: loopResult.totalUsage.cacheCreationTokens,
733
+ model: finalModel,
734
+ }, taskError, taskError || loopResult.stopReason === 'awaiting-user' ? loopResult.handoff : null, loopResult.stopReason);
735
+ emitEvent({
736
+ kind: 'dispatch.finished',
737
+ channel: 'task',
738
+ agentSlug: agent.slug,
739
+ queueUid: task.queueUid,
740
+ durMs: elapsed,
741
+ inputTokens: totalInputTokens,
742
+ outputTokens: totalOutputTokens,
743
+ costMicros: totalCostMicros,
744
+ model: finalModel,
745
+ });
746
+ }
747
+ catch (err) {
748
+ const errMsg = err instanceof Error ? err.message : String(err);
749
+ if (signal.aborted) {
750
+ emitEvent({ kind: 'dispatch.cancelled', channel: 'task', agentSlug: agent.slug, queueUid: task.queueUid });
751
+ sendWsTaskDone(socket, task.queueId, 'Cancelled by user.', undefined, 'Cancelled by user');
752
+ return;
753
+ }
754
+ emitEvent({ kind: 'dispatch.failed', channel: 'task', agentSlug: agent.slug, queueUid: task.queueUid, error: errMsg });
755
+ sendWsTaskDone(socket, task.queueId, `Error: ${errMsg}`, undefined, errMsg);
756
+ }
757
+ finally {
758
+ // Only while this run is still the row's: a re-dispatch owns the key now.
759
+ if (activeTaskAborts.get(task.queueId) === abortController) {
760
+ activeTaskAborts.delete(task.queueId);
761
+ pendingTaskSteers.delete(task.queueId);
762
+ }
763
+ }
764
+ };
765
+ }