rookery-agent 0.3.0 → 0.4.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 (745) hide show
  1. package/README.md +5 -3
  2. package/docs/updates.md +12 -0
  3. package/package.json +1 -1
  4. package/packages/cli/dist/commands/chat.d.ts.map +1 -1
  5. package/packages/cli/dist/commands/chat.js +37 -74
  6. package/packages/cli/dist/commands/chat.js.map +1 -1
  7. package/packages/cli/dist/commands/config.js +4 -4
  8. package/packages/cli/dist/commands/config.js.map +1 -1
  9. package/packages/cli/dist/commands/doctor.d.ts.map +1 -1
  10. package/packages/cli/dist/commands/doctor.js +113 -91
  11. package/packages/cli/dist/commands/doctor.js.map +1 -1
  12. package/packages/cli/dist/commands/memory.d.ts.map +1 -1
  13. package/packages/cli/dist/commands/memory.js +28 -31
  14. package/packages/cli/dist/commands/memory.js.map +1 -1
  15. package/packages/cli/dist/commands/org.d.ts.map +1 -1
  16. package/packages/cli/dist/commands/org.js +36 -103
  17. package/packages/cli/dist/commands/org.js.map +1 -1
  18. package/packages/cli/dist/commands/serve.d.ts.map +1 -1
  19. package/packages/cli/dist/commands/serve.js +8 -6
  20. package/packages/cli/dist/commands/serve.js.map +1 -1
  21. package/packages/cli/dist/commands/sessions.d.ts.map +1 -1
  22. package/packages/cli/dist/commands/sessions.js +18 -17
  23. package/packages/cli/dist/commands/sessions.js.map +1 -1
  24. package/packages/cli/dist/commands/shared.d.ts +26 -5
  25. package/packages/cli/dist/commands/shared.d.ts.map +1 -1
  26. package/packages/cli/dist/commands/shared.js +85 -63
  27. package/packages/cli/dist/commands/shared.js.map +1 -1
  28. package/packages/cli/dist/commands/slash.d.ts +51 -0
  29. package/packages/cli/dist/commands/slash.d.ts.map +1 -0
  30. package/packages/cli/dist/commands/slash.js +110 -0
  31. package/packages/cli/dist/commands/slash.js.map +1 -0
  32. package/packages/cli/dist/commands/tasks.d.ts.map +1 -1
  33. package/packages/cli/dist/commands/tasks.js +74 -115
  34. package/packages/cli/dist/commands/tasks.js.map +1 -1
  35. package/packages/cli/dist/commands/tools.d.ts.map +1 -1
  36. package/packages/cli/dist/commands/tools.js +51 -34
  37. package/packages/cli/dist/commands/tools.js.map +1 -1
  38. package/packages/cli/dist/index.js +42 -52
  39. package/packages/cli/dist/index.js.map +1 -1
  40. package/packages/cli/dist/repl.d.ts +1 -25
  41. package/packages/cli/dist/repl.d.ts.map +1 -1
  42. package/packages/cli/dist/repl.js +165 -726
  43. package/packages/cli/dist/repl.js.map +1 -1
  44. package/packages/cli/dist/replInput.d.ts +33 -0
  45. package/packages/cli/dist/replInput.d.ts.map +1 -0
  46. package/packages/cli/dist/replInput.js +97 -0
  47. package/packages/cli/dist/replInput.js.map +1 -0
  48. package/packages/cli/dist/replOutput.d.ts +11 -0
  49. package/packages/cli/dist/replOutput.d.ts.map +1 -0
  50. package/packages/cli/dist/replOutput.js +22 -0
  51. package/packages/cli/dist/replOutput.js.map +1 -0
  52. package/packages/cli/dist/replQuestions.d.ts +32 -0
  53. package/packages/cli/dist/replQuestions.d.ts.map +1 -0
  54. package/packages/cli/dist/replQuestions.js +122 -0
  55. package/packages/cli/dist/replQuestions.js.map +1 -0
  56. package/packages/cli/dist/replSlash.d.ts +24 -0
  57. package/packages/cli/dist/replSlash.d.ts.map +1 -0
  58. package/packages/cli/dist/replSlash.js +311 -0
  59. package/packages/cli/dist/replSlash.js.map +1 -0
  60. package/packages/cli/dist/replState.d.ts +56 -0
  61. package/packages/cli/dist/replState.d.ts.map +1 -0
  62. package/packages/cli/dist/replState.js +89 -0
  63. package/packages/cli/dist/replState.js.map +1 -0
  64. package/packages/cli/dist/tui/App.d.ts +7 -24
  65. package/packages/cli/dist/tui/App.d.ts.map +1 -1
  66. package/packages/cli/dist/tui/App.js +139 -513
  67. package/packages/cli/dist/tui/App.js.map +1 -1
  68. package/packages/cli/dist/tui/LiveRegion.d.ts +16 -0
  69. package/packages/cli/dist/tui/LiveRegion.d.ts.map +1 -0
  70. package/packages/cli/dist/tui/LiveRegion.js +37 -0
  71. package/packages/cli/dist/tui/LiveRegion.js.map +1 -0
  72. package/packages/cli/dist/tui/boot.d.ts +34 -0
  73. package/packages/cli/dist/tui/boot.d.ts.map +1 -0
  74. package/packages/cli/dist/tui/boot.js +133 -0
  75. package/packages/cli/dist/tui/boot.js.map +1 -0
  76. package/packages/cli/dist/tui/commands.d.ts +3 -4
  77. package/packages/cli/dist/tui/commands.d.ts.map +1 -1
  78. package/packages/cli/dist/tui/commands.js +339 -405
  79. package/packages/cli/dist/tui/commands.js.map +1 -1
  80. package/packages/cli/dist/tui/components/ActivityLine.d.ts +1 -1
  81. package/packages/cli/dist/tui/components/ActivityLine.d.ts.map +1 -1
  82. package/packages/cli/dist/tui/components/ActivityLine.js +2 -2
  83. package/packages/cli/dist/tui/components/ActivityLine.js.map +1 -1
  84. package/packages/cli/dist/tui/components/AssignmentsView.d.ts.map +1 -1
  85. package/packages/cli/dist/tui/components/AssignmentsView.js +34 -20
  86. package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -1
  87. package/packages/cli/dist/tui/components/Logo.d.ts +3 -19
  88. package/packages/cli/dist/tui/components/Logo.d.ts.map +1 -1
  89. package/packages/cli/dist/tui/components/Logo.js +13 -13
  90. package/packages/cli/dist/tui/components/Logo.js.map +1 -1
  91. package/packages/cli/dist/tui/components/Markdown.d.ts.map +1 -1
  92. package/packages/cli/dist/tui/components/Markdown.js +201 -146
  93. package/packages/cli/dist/tui/components/Markdown.js.map +1 -1
  94. package/packages/cli/dist/tui/components/QuestionView.d.ts +0 -2
  95. package/packages/cli/dist/tui/components/QuestionView.d.ts.map +1 -1
  96. package/packages/cli/dist/tui/components/QuestionView.js +21 -12
  97. package/packages/cli/dist/tui/components/QuestionView.js.map +1 -1
  98. package/packages/cli/dist/tui/components/Scrollback.d.ts.map +1 -1
  99. package/packages/cli/dist/tui/components/Scrollback.js +6 -3
  100. package/packages/cli/dist/tui/components/Scrollback.js.map +1 -1
  101. package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -1
  102. package/packages/cli/dist/tui/components/SlashPalette.js +14 -9
  103. package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -1
  104. package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -1
  105. package/packages/cli/dist/tui/components/StatusLine.js +45 -22
  106. package/packages/cli/dist/tui/components/StatusLine.js.map +1 -1
  107. package/packages/cli/dist/tui/components/ToolGroup.d.ts.map +1 -1
  108. package/packages/cli/dist/tui/components/ToolGroup.js +12 -7
  109. package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -1
  110. package/packages/cli/dist/tui/components/WatchView.d.ts.map +1 -1
  111. package/packages/cli/dist/tui/components/WatchView.js +28 -17
  112. package/packages/cli/dist/tui/components/WatchView.js.map +1 -1
  113. package/packages/cli/dist/tui/highlight.d.ts +0 -2
  114. package/packages/cli/dist/tui/highlight.d.ts.map +1 -1
  115. package/packages/cli/dist/tui/highlight.js +8 -6
  116. package/packages/cli/dist/tui/highlight.js.map +1 -1
  117. package/packages/cli/dist/tui/history.d.ts +30 -4
  118. package/packages/cli/dist/tui/history.d.ts.map +1 -1
  119. package/packages/cli/dist/tui/history.js +100 -75
  120. package/packages/cli/dist/tui/history.js.map +1 -1
  121. package/packages/cli/dist/tui/hooks/coalescer.d.ts +18 -0
  122. package/packages/cli/dist/tui/hooks/coalescer.d.ts.map +1 -0
  123. package/packages/cli/dist/tui/hooks/coalescer.js +36 -0
  124. package/packages/cli/dist/tui/hooks/coalescer.js.map +1 -0
  125. package/packages/cli/dist/tui/hooks/useColumns.d.ts +2 -7
  126. package/packages/cli/dist/tui/hooks/useColumns.d.ts.map +1 -1
  127. package/packages/cli/dist/tui/hooks/useColumns.js +6 -11
  128. package/packages/cli/dist/tui/hooks/useColumns.js.map +1 -1
  129. package/packages/cli/dist/tui/hooks/useHistory.d.ts +7 -4
  130. package/packages/cli/dist/tui/hooks/useHistory.d.ts.map +1 -1
  131. package/packages/cli/dist/tui/hooks/useHistory.js +21 -18
  132. package/packages/cli/dist/tui/hooks/useHistory.js.map +1 -1
  133. package/packages/cli/dist/tui/hooks/usePrompt.d.ts +27 -0
  134. package/packages/cli/dist/tui/hooks/usePrompt.d.ts.map +1 -0
  135. package/packages/cli/dist/tui/hooks/usePrompt.js +169 -0
  136. package/packages/cli/dist/tui/hooks/usePrompt.js.map +1 -0
  137. package/packages/cli/dist/tui/hooks/useQuestion.d.ts +23 -0
  138. package/packages/cli/dist/tui/hooks/useQuestion.d.ts.map +1 -0
  139. package/packages/cli/dist/tui/hooks/useQuestion.js +43 -0
  140. package/packages/cli/dist/tui/hooks/useQuestion.js.map +1 -0
  141. package/packages/cli/dist/tui/hooks/useScrollback.d.ts +18 -0
  142. package/packages/cli/dist/tui/hooks/useScrollback.d.ts.map +1 -0
  143. package/packages/cli/dist/tui/hooks/useScrollback.js +29 -0
  144. package/packages/cli/dist/tui/hooks/useScrollback.js.map +1 -0
  145. package/packages/cli/dist/tui/hooks/useSession.d.ts +25 -0
  146. package/packages/cli/dist/tui/hooks/useSession.d.ts.map +1 -0
  147. package/packages/cli/dist/tui/hooks/useSession.js +36 -0
  148. package/packages/cli/dist/tui/hooks/useSession.js.map +1 -0
  149. package/packages/cli/dist/tui/hooks/useSlash.d.ts +0 -2
  150. package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -1
  151. package/packages/cli/dist/tui/hooks/useSlash.js +0 -1
  152. package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -1
  153. package/packages/cli/dist/tui/hooks/useSpeech.d.ts +19 -0
  154. package/packages/cli/dist/tui/hooks/useSpeech.d.ts.map +1 -0
  155. package/packages/cli/dist/tui/hooks/useSpeech.js +33 -0
  156. package/packages/cli/dist/tui/hooks/useSpeech.js.map +1 -0
  157. package/packages/cli/dist/tui/hooks/useTicker.d.ts +13 -0
  158. package/packages/cli/dist/tui/hooks/useTicker.d.ts.map +1 -0
  159. package/packages/cli/dist/tui/hooks/useTicker.js +24 -0
  160. package/packages/cli/dist/tui/hooks/useTicker.js.map +1 -0
  161. package/packages/cli/dist/tui/hooks/useTurn.d.ts +4 -4
  162. package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -1
  163. package/packages/cli/dist/tui/hooks/useTurn.js +167 -289
  164. package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -1
  165. package/packages/cli/dist/tui/hooks/useWatch.d.ts.map +1 -1
  166. package/packages/cli/dist/tui/hooks/useWatch.js +15 -48
  167. package/packages/cli/dist/tui/hooks/useWatch.js.map +1 -1
  168. package/packages/cli/dist/tui/inkTheme.d.ts.map +1 -1
  169. package/packages/cli/dist/tui/inkTheme.js +9 -11
  170. package/packages/cli/dist/tui/inkTheme.js.map +1 -1
  171. package/packages/cli/dist/tui/theme.d.ts +7 -13
  172. package/packages/cli/dist/tui/theme.d.ts.map +1 -1
  173. package/packages/cli/dist/tui/theme.js +18 -15
  174. package/packages/cli/dist/tui/theme.js.map +1 -1
  175. package/packages/cli/dist/tui/types.d.ts +10 -23
  176. package/packages/cli/dist/tui/types.d.ts.map +1 -1
  177. package/packages/cli/dist/tui/types.js +13 -31
  178. package/packages/cli/dist/tui/types.js.map +1 -1
  179. package/packages/cli/dist/ui/modelNames.d.ts.map +1 -1
  180. package/packages/cli/dist/ui/modelNames.js +45 -37
  181. package/packages/cli/dist/ui/modelNames.js.map +1 -1
  182. package/packages/cli/dist/ui/render.d.ts +32 -14
  183. package/packages/cli/dist/ui/render.d.ts.map +1 -1
  184. package/packages/cli/dist/ui/render.js +155 -98
  185. package/packages/cli/dist/ui/render.js.map +1 -1
  186. package/packages/cli/dist/ui/speech.d.ts +4 -7
  187. package/packages/cli/dist/ui/speech.d.ts.map +1 -1
  188. package/packages/cli/dist/ui/speech.js +37 -51
  189. package/packages/cli/dist/ui/speech.js.map +1 -1
  190. package/packages/cli/dist/ui/spinner.d.ts +1 -4
  191. package/packages/cli/dist/ui/spinner.d.ts.map +1 -1
  192. package/packages/cli/dist/ui/spinner.js +1 -12
  193. package/packages/cli/dist/ui/spinner.js.map +1 -1
  194. package/packages/cli/package.json +1 -1
  195. package/packages/core/dist/agents/persona.d.ts.map +1 -1
  196. package/packages/core/dist/agents/persona.js +27 -11
  197. package/packages/core/dist/agents/persona.js.map +1 -1
  198. package/packages/core/dist/assistant/board-watch.d.ts +72 -0
  199. package/packages/core/dist/assistant/board-watch.d.ts.map +1 -0
  200. package/packages/core/dist/assistant/board-watch.js +224 -0
  201. package/packages/core/dist/assistant/board-watch.js.map +1 -0
  202. package/packages/core/dist/assistant/chat-turn.d.ts +14 -0
  203. package/packages/core/dist/assistant/chat-turn.d.ts.map +1 -0
  204. package/packages/core/dist/assistant/chat-turn.js +159 -0
  205. package/packages/core/dist/assistant/chat-turn.js.map +1 -0
  206. package/packages/core/dist/assistant/dream-recorder.d.ts +74 -0
  207. package/packages/core/dist/assistant/dream-recorder.d.ts.map +1 -0
  208. package/packages/core/dist/assistant/dream-recorder.js +282 -0
  209. package/packages/core/dist/assistant/dream-recorder.js.map +1 -0
  210. package/packages/core/dist/assistant/headless-turn.d.ts +17 -0
  211. package/packages/core/dist/assistant/headless-turn.d.ts.map +1 -0
  212. package/packages/core/dist/assistant/headless-turn.js +330 -0
  213. package/packages/core/dist/assistant/headless-turn.js.map +1 -0
  214. package/packages/core/dist/assistant/journalled-turn.d.ts +39 -0
  215. package/packages/core/dist/assistant/journalled-turn.d.ts.map +1 -0
  216. package/packages/core/dist/assistant/journalled-turn.js +75 -0
  217. package/packages/core/dist/assistant/journalled-turn.js.map +1 -0
  218. package/packages/core/dist/assistant/memory-learning.d.ts +27 -0
  219. package/packages/core/dist/assistant/memory-learning.d.ts.map +1 -0
  220. package/packages/core/dist/assistant/memory-learning.js +82 -0
  221. package/packages/core/dist/assistant/memory-learning.js.map +1 -0
  222. package/packages/core/dist/assistant/promotion-notice.d.ts +14 -0
  223. package/packages/core/dist/assistant/promotion-notice.d.ts.map +1 -0
  224. package/packages/core/dist/assistant/promotion-notice.js +33 -0
  225. package/packages/core/dist/assistant/promotion-notice.js.map +1 -0
  226. package/packages/core/dist/assistant/scheduled-runs.d.ts +30 -0
  227. package/packages/core/dist/assistant/scheduled-runs.d.ts.map +1 -0
  228. package/packages/core/dist/assistant/scheduled-runs.js +184 -0
  229. package/packages/core/dist/assistant/scheduled-runs.js.map +1 -0
  230. package/packages/core/dist/assistant/sessions.d.ts +44 -0
  231. package/packages/core/dist/assistant/sessions.d.ts.map +1 -0
  232. package/packages/core/dist/assistant/sessions.js +75 -0
  233. package/packages/core/dist/assistant/sessions.js.map +1 -0
  234. package/packages/core/dist/assistant/terminal-turn.d.ts +18 -0
  235. package/packages/core/dist/assistant/terminal-turn.d.ts.map +1 -0
  236. package/packages/core/dist/assistant/terminal-turn.js +228 -0
  237. package/packages/core/dist/assistant/terminal-turn.js.map +1 -0
  238. package/packages/core/dist/assistant/terminals.d.ts +91 -0
  239. package/packages/core/dist/assistant/terminals.d.ts.map +1 -0
  240. package/packages/core/dist/assistant/terminals.js +266 -0
  241. package/packages/core/dist/assistant/terminals.js.map +1 -0
  242. package/packages/core/dist/assistant/turn-support.d.ts +109 -0
  243. package/packages/core/dist/assistant/turn-support.d.ts.map +1 -0
  244. package/packages/core/dist/assistant/turn-support.js +80 -0
  245. package/packages/core/dist/assistant/turn-support.js.map +1 -0
  246. package/packages/core/dist/assistant/turn-transcript.d.ts +44 -0
  247. package/packages/core/dist/assistant/turn-transcript.d.ts.map +1 -0
  248. package/packages/core/dist/assistant/turn-transcript.js +82 -0
  249. package/packages/core/dist/assistant/turn-transcript.js.map +1 -0
  250. package/packages/core/dist/assistant/types.d.ts +120 -0
  251. package/packages/core/dist/assistant/types.d.ts.map +1 -0
  252. package/packages/core/dist/assistant/types.js +2 -0
  253. package/packages/core/dist/assistant/types.js.map +1 -0
  254. package/packages/core/dist/computer/accessibility.d.ts.map +1 -1
  255. package/packages/core/dist/computer/accessibility.js +40 -35
  256. package/packages/core/dist/computer/accessibility.js.map +1 -1
  257. package/packages/core/dist/computer/mcp-server.js +426 -364
  258. package/packages/core/dist/computer/mcp-server.js.map +1 -1
  259. package/packages/core/dist/computer/powershell.d.ts.map +1 -1
  260. package/packages/core/dist/computer/powershell.js +25 -16
  261. package/packages/core/dist/computer/powershell.js.map +1 -1
  262. package/packages/core/dist/computer/screen-text.d.ts.map +1 -1
  263. package/packages/core/dist/computer/screen-text.js +54 -34
  264. package/packages/core/dist/computer/screen-text.js.map +1 -1
  265. package/packages/core/dist/computer/sketch.d.ts.map +1 -1
  266. package/packages/core/dist/computer/sketch.js +185 -128
  267. package/packages/core/dist/computer/sketch.js.map +1 -1
  268. package/packages/core/dist/computer/tools.d.ts +2 -0
  269. package/packages/core/dist/computer/tools.d.ts.map +1 -1
  270. package/packages/core/dist/computer/tools.js +31 -27
  271. package/packages/core/dist/computer/tools.js.map +1 -1
  272. package/packages/core/dist/computer/validation.d.ts +16 -16
  273. package/packages/core/dist/computer/validation.d.ts.map +1 -1
  274. package/packages/core/dist/computer/validation.js +28 -20
  275. package/packages/core/dist/computer/validation.js.map +1 -1
  276. package/packages/core/dist/config.d.ts +10 -1
  277. package/packages/core/dist/config.d.ts.map +1 -1
  278. package/packages/core/dist/config.js +64 -23
  279. package/packages/core/dist/config.js.map +1 -1
  280. package/packages/core/dist/cron/parse.d.ts.map +1 -1
  281. package/packages/core/dist/cron/parse.js +90 -77
  282. package/packages/core/dist/cron/parse.js.map +1 -1
  283. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  284. package/packages/core/dist/cron/scheduler.js +99 -65
  285. package/packages/core/dist/cron/scheduler.js.map +1 -1
  286. package/packages/core/dist/cron/script.d.ts.map +1 -1
  287. package/packages/core/dist/cron/script.js +72 -42
  288. package/packages/core/dist/cron/script.js.map +1 -1
  289. package/packages/core/dist/external/claude-code.d.ts.map +1 -1
  290. package/packages/core/dist/external/claude-code.js +41 -28
  291. package/packages/core/dist/external/claude-code.js.map +1 -1
  292. package/packages/core/dist/external/discovery.d.ts.map +1 -1
  293. package/packages/core/dist/external/discovery.js +14 -11
  294. package/packages/core/dist/external/discovery.js.map +1 -1
  295. package/packages/core/dist/external/shared.d.ts.map +1 -1
  296. package/packages/core/dist/external/shared.js +55 -74
  297. package/packages/core/dist/external/shared.js.map +1 -1
  298. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  299. package/packages/core/dist/gateway/policy.js +5 -2
  300. package/packages/core/dist/gateway/policy.js.map +1 -1
  301. package/packages/core/dist/index.d.ts +1 -1
  302. package/packages/core/dist/index.d.ts.map +1 -1
  303. package/packages/core/dist/index.js +1 -1
  304. package/packages/core/dist/index.js.map +1 -1
  305. package/packages/core/dist/logger.d.ts.map +1 -1
  306. package/packages/core/dist/logger.js +11 -11
  307. package/packages/core/dist/logger.js.map +1 -1
  308. package/packages/core/dist/memory/db.d.ts.map +1 -1
  309. package/packages/core/dist/memory/db.js +175 -226
  310. package/packages/core/dist/memory/db.js.map +1 -1
  311. package/packages/core/dist/memory/dream/admission.d.ts +5 -0
  312. package/packages/core/dist/memory/dream/admission.d.ts.map +1 -1
  313. package/packages/core/dist/memory/dream/admission.js +8 -14
  314. package/packages/core/dist/memory/dream/admission.js.map +1 -1
  315. package/packages/core/dist/memory/dream/candidate.d.ts.map +1 -1
  316. package/packages/core/dist/memory/dream/candidate.js +119 -92
  317. package/packages/core/dist/memory/dream/candidate.js.map +1 -1
  318. package/packages/core/dist/memory/dream/evaluate.d.ts +13 -4
  319. package/packages/core/dist/memory/dream/evaluate.d.ts.map +1 -1
  320. package/packages/core/dist/memory/dream/evaluate.js +264 -288
  321. package/packages/core/dist/memory/dream/evaluate.js.map +1 -1
  322. package/packages/core/dist/memory/dream/frame.d.ts +6 -0
  323. package/packages/core/dist/memory/dream/frame.d.ts.map +1 -1
  324. package/packages/core/dist/memory/dream/frame.js +137 -91
  325. package/packages/core/dist/memory/dream/frame.js.map +1 -1
  326. package/packages/core/dist/memory/dream/label.d.ts.map +1 -1
  327. package/packages/core/dist/memory/dream/label.js +6 -9
  328. package/packages/core/dist/memory/dream/label.js.map +1 -1
  329. package/packages/core/dist/memory/dream/measure.d.ts +4 -0
  330. package/packages/core/dist/memory/dream/measure.d.ts.map +1 -1
  331. package/packages/core/dist/memory/dream/measure.js +13 -58
  332. package/packages/core/dist/memory/dream/measure.js.map +1 -1
  333. package/packages/core/dist/memory/dream/policy.d.ts.map +1 -1
  334. package/packages/core/dist/memory/dream/policy.js +4 -2
  335. package/packages/core/dist/memory/dream/policy.js.map +1 -1
  336. package/packages/core/dist/memory/dream/probe.d.ts +31 -4
  337. package/packages/core/dist/memory/dream/probe.d.ts.map +1 -1
  338. package/packages/core/dist/memory/dream/probe.js +290 -289
  339. package/packages/core/dist/memory/dream/probe.js.map +1 -1
  340. package/packages/core/dist/memory/dream/promote.d.ts.map +1 -1
  341. package/packages/core/dist/memory/dream/promote.js +10 -11
  342. package/packages/core/dist/memory/dream/promote.js.map +1 -1
  343. package/packages/core/dist/memory/dream/score.d.ts +9 -0
  344. package/packages/core/dist/memory/dream/score.d.ts.map +1 -1
  345. package/packages/core/dist/memory/dream/score.js +6 -7
  346. package/packages/core/dist/memory/dream/score.js.map +1 -1
  347. package/packages/core/dist/memory/dream/slots.d.ts.map +1 -1
  348. package/packages/core/dist/memory/dream/slots.js +0 -0
  349. package/packages/core/dist/memory/dream/slots.js.map +1 -1
  350. package/packages/core/dist/memory/dream/trajectory.d.ts.map +1 -1
  351. package/packages/core/dist/memory/dream/trajectory.js +76 -53
  352. package/packages/core/dist/memory/dream/trajectory.js.map +1 -1
  353. package/packages/core/dist/memory/dream/util.d.ts +44 -0
  354. package/packages/core/dist/memory/dream/util.d.ts.map +1 -0
  355. package/packages/core/dist/memory/dream/util.js +83 -0
  356. package/packages/core/dist/memory/dream/util.js.map +1 -0
  357. package/packages/core/dist/memory/extractor.d.ts.map +1 -1
  358. package/packages/core/dist/memory/extractor.js +67 -46
  359. package/packages/core/dist/memory/extractor.js.map +1 -1
  360. package/packages/core/dist/memory/gate.d.ts.map +1 -1
  361. package/packages/core/dist/memory/gate.js +55 -44
  362. package/packages/core/dist/memory/gate.js.map +1 -1
  363. package/packages/core/dist/memory/recall.d.ts +1 -1
  364. package/packages/core/dist/memory/recall.d.ts.map +1 -1
  365. package/packages/core/dist/memory/recall.js +42 -39
  366. package/packages/core/dist/memory/recall.js.map +1 -1
  367. package/packages/core/dist/memory/sleep-dream.d.ts +210 -0
  368. package/packages/core/dist/memory/sleep-dream.d.ts.map +1 -0
  369. package/packages/core/dist/memory/sleep-dream.js +1109 -0
  370. package/packages/core/dist/memory/sleep-dream.js.map +1 -0
  371. package/packages/core/dist/memory/sleep-frames.d.ts +40 -0
  372. package/packages/core/dist/memory/sleep-frames.d.ts.map +1 -0
  373. package/packages/core/dist/memory/sleep-frames.js +127 -0
  374. package/packages/core/dist/memory/sleep-frames.js.map +1 -0
  375. package/packages/core/dist/memory/sleep-limits.d.ts +18 -0
  376. package/packages/core/dist/memory/sleep-limits.d.ts.map +1 -0
  377. package/packages/core/dist/memory/sleep-limits.js +34 -0
  378. package/packages/core/dist/memory/sleep-limits.js.map +1 -0
  379. package/packages/core/dist/memory/sleep-model.d.ts +36 -0
  380. package/packages/core/dist/memory/sleep-model.d.ts.map +1 -0
  381. package/packages/core/dist/memory/sleep-model.js +80 -0
  382. package/packages/core/dist/memory/sleep-model.js.map +1 -0
  383. package/packages/core/dist/memory/sleep-policy.d.ts +19 -0
  384. package/packages/core/dist/memory/sleep-policy.d.ts.map +1 -0
  385. package/packages/core/dist/memory/sleep-policy.js +79 -0
  386. package/packages/core/dist/memory/sleep-policy.js.map +1 -0
  387. package/packages/core/dist/memory/sleep-prompts.d.ts +15 -0
  388. package/packages/core/dist/memory/sleep-prompts.d.ts.map +1 -0
  389. package/packages/core/dist/memory/sleep-prompts.js +212 -0
  390. package/packages/core/dist/memory/sleep-prompts.js.map +1 -0
  391. package/packages/core/dist/memory/sleep-report.d.ts +63 -0
  392. package/packages/core/dist/memory/sleep-report.d.ts.map +1 -0
  393. package/packages/core/dist/memory/sleep-report.js +97 -0
  394. package/packages/core/dist/memory/sleep-report.js.map +1 -0
  395. package/packages/core/dist/memory/sleep-verdicts.d.ts +77 -0
  396. package/packages/core/dist/memory/sleep-verdicts.d.ts.map +1 -0
  397. package/packages/core/dist/memory/sleep-verdicts.js +198 -0
  398. package/packages/core/dist/memory/sleep-verdicts.js.map +1 -0
  399. package/packages/core/dist/memory/sleep.d.ts +6 -61
  400. package/packages/core/dist/memory/sleep.d.ts.map +1 -1
  401. package/packages/core/dist/memory/sleep.js +1099 -2458
  402. package/packages/core/dist/memory/sleep.js.map +1 -1
  403. package/packages/core/dist/memory/store-rows.d.ts +43 -0
  404. package/packages/core/dist/memory/store-rows.d.ts.map +1 -0
  405. package/packages/core/dist/memory/store-rows.js +330 -0
  406. package/packages/core/dist/memory/store-rows.js.map +1 -0
  407. package/packages/core/dist/memory/store.d.ts +34 -20
  408. package/packages/core/dist/memory/store.d.ts.map +1 -1
  409. package/packages/core/dist/memory/store.js +634 -861
  410. package/packages/core/dist/memory/store.js.map +1 -1
  411. package/packages/core/dist/migration-cron.d.ts +2 -1
  412. package/packages/core/dist/migration-cron.d.ts.map +1 -1
  413. package/packages/core/dist/migration-cron.js +197 -154
  414. package/packages/core/dist/migration-cron.js.map +1 -1
  415. package/packages/core/dist/migration-scripts.d.ts +11 -3
  416. package/packages/core/dist/migration-scripts.d.ts.map +1 -1
  417. package/packages/core/dist/migration-scripts.js +81 -61
  418. package/packages/core/dist/migration-scripts.js.map +1 -1
  419. package/packages/core/dist/migration-shared.d.ts +9 -0
  420. package/packages/core/dist/migration-shared.d.ts.map +1 -0
  421. package/packages/core/dist/migration-shared.js +16 -0
  422. package/packages/core/dist/migration-shared.js.map +1 -0
  423. package/packages/core/dist/migration.d.ts.map +1 -1
  424. package/packages/core/dist/migration.js +150 -111
  425. package/packages/core/dist/migration.js.map +1 -1
  426. package/packages/core/dist/org/assignment-log.d.ts +28 -0
  427. package/packages/core/dist/org/assignment-log.d.ts.map +1 -0
  428. package/packages/core/dist/org/assignment-log.js +86 -0
  429. package/packages/core/dist/org/assignment-log.js.map +1 -0
  430. package/packages/core/dist/org/bridge.d.ts.map +1 -1
  431. package/packages/core/dist/org/bridge.js +32 -30
  432. package/packages/core/dist/org/bridge.js.map +1 -1
  433. package/packages/core/dist/org/controller.d.ts +18 -21
  434. package/packages/core/dist/org/controller.d.ts.map +1 -1
  435. package/packages/core/dist/org/controller.js +2042 -1848
  436. package/packages/core/dist/org/controller.js.map +1 -1
  437. package/packages/core/dist/org/json-reply.d.ts +6 -0
  438. package/packages/core/dist/org/json-reply.d.ts.map +1 -0
  439. package/packages/core/dist/org/json-reply.js +23 -0
  440. package/packages/core/dist/org/json-reply.js.map +1 -0
  441. package/packages/core/dist/org/mcp-bridge.js +34 -26
  442. package/packages/core/dist/org/mcp-bridge.js.map +1 -1
  443. package/packages/core/dist/org/planner.d.ts.map +1 -1
  444. package/packages/core/dist/org/planner.js +38 -42
  445. package/packages/core/dist/org/planner.js.map +1 -1
  446. package/packages/core/dist/org/project-mcp.d.ts.map +1 -1
  447. package/packages/core/dist/org/project-mcp.js +2 -5
  448. package/packages/core/dist/org/project-mcp.js.map +1 -1
  449. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  450. package/packages/core/dist/org/prompts.js +176 -156
  451. package/packages/core/dist/org/prompts.js.map +1 -1
  452. package/packages/core/dist/org/questions.d.ts.map +1 -1
  453. package/packages/core/dist/org/questions.js +19 -14
  454. package/packages/core/dist/org/questions.js.map +1 -1
  455. package/packages/core/dist/org/review.d.ts.map +1 -1
  456. package/packages/core/dist/org/review.js +27 -43
  457. package/packages/core/dist/org/review.js.map +1 -1
  458. package/packages/core/dist/org/store.d.ts +19 -32
  459. package/packages/core/dist/org/store.d.ts.map +1 -1
  460. package/packages/core/dist/org/store.js +250 -206
  461. package/packages/core/dist/org/store.js.map +1 -1
  462. package/packages/core/dist/org/tool-args.d.ts +54 -0
  463. package/packages/core/dist/org/tool-args.d.ts.map +1 -0
  464. package/packages/core/dist/org/tool-args.js +104 -0
  465. package/packages/core/dist/org/tool-args.js.map +1 -0
  466. package/packages/core/dist/org/tools.d.ts.map +1 -1
  467. package/packages/core/dist/org/tools.js +238 -443
  468. package/packages/core/dist/org/tools.js.map +1 -1
  469. package/packages/core/dist/profile.d.ts.map +1 -1
  470. package/packages/core/dist/profile.js +114 -57
  471. package/packages/core/dist/profile.js.map +1 -1
  472. package/packages/core/dist/providers/catalogue.d.ts.map +1 -1
  473. package/packages/core/dist/providers/catalogue.js +89 -60
  474. package/packages/core/dist/providers/catalogue.js.map +1 -1
  475. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  476. package/packages/core/dist/providers/claude-code.js +425 -366
  477. package/packages/core/dist/providers/claude-code.js.map +1 -1
  478. package/packages/core/dist/providers/claude-tui.d.ts +13 -9
  479. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -1
  480. package/packages/core/dist/providers/claude-tui.js +568 -396
  481. package/packages/core/dist/providers/claude-tui.js.map +1 -1
  482. package/packages/core/dist/providers/codex-auth.d.ts +3 -0
  483. package/packages/core/dist/providers/codex-auth.d.ts.map +1 -1
  484. package/packages/core/dist/providers/codex-auth.js +9 -7
  485. package/packages/core/dist/providers/codex-auth.js.map +1 -1
  486. package/packages/core/dist/providers/codex-bridge.d.ts +24 -7
  487. package/packages/core/dist/providers/codex-bridge.d.ts.map +1 -1
  488. package/packages/core/dist/providers/codex-bridge.js +128 -168
  489. package/packages/core/dist/providers/codex-bridge.js.map +1 -1
  490. package/packages/core/dist/providers/codex-translate.d.ts.map +1 -1
  491. package/packages/core/dist/providers/codex-translate.js +195 -197
  492. package/packages/core/dist/providers/codex-translate.js.map +1 -1
  493. package/packages/core/dist/providers/loopback-server.d.ts +33 -0
  494. package/packages/core/dist/providers/loopback-server.d.ts.map +1 -0
  495. package/packages/core/dist/providers/loopback-server.js +104 -0
  496. package/packages/core/dist/providers/loopback-server.js.map +1 -0
  497. package/packages/core/dist/providers/model-gateway.d.ts +2 -4
  498. package/packages/core/dist/providers/model-gateway.d.ts.map +1 -1
  499. package/packages/core/dist/providers/model-gateway.js +39 -75
  500. package/packages/core/dist/providers/model-gateway.js.map +1 -1
  501. package/packages/core/dist/providers/process.d.ts.map +1 -1
  502. package/packages/core/dist/providers/process.js +32 -23
  503. package/packages/core/dist/providers/process.js.map +1 -1
  504. package/packages/core/dist/providers/provider-catalog.d.ts +5 -3
  505. package/packages/core/dist/providers/provider-catalog.d.ts.map +1 -1
  506. package/packages/core/dist/providers/provider-catalog.js +33 -25
  507. package/packages/core/dist/providers/provider-catalog.js.map +1 -1
  508. package/packages/core/dist/providers/quota.d.ts.map +1 -1
  509. package/packages/core/dist/providers/quota.js +37 -37
  510. package/packages/core/dist/providers/quota.js.map +1 -1
  511. package/packages/core/dist/providers/registry.d.ts.map +1 -1
  512. package/packages/core/dist/providers/registry.js +3 -1
  513. package/packages/core/dist/providers/registry.js.map +1 -1
  514. package/packages/core/dist/providers/user-settings-guard.d.ts.map +1 -1
  515. package/packages/core/dist/providers/user-settings-guard.js +7 -2
  516. package/packages/core/dist/providers/user-settings-guard.js.map +1 -1
  517. package/packages/core/dist/runtime.d.ts +45 -158
  518. package/packages/core/dist/runtime.d.ts.map +1 -1
  519. package/packages/core/dist/runtime.js +184 -1701
  520. package/packages/core/dist/runtime.js.map +1 -1
  521. package/packages/core/dist/skills/import.d.ts.map +1 -1
  522. package/packages/core/dist/skills/import.js +52 -36
  523. package/packages/core/dist/skills/import.js.map +1 -1
  524. package/packages/core/dist/skills/shelf.d.ts +14 -0
  525. package/packages/core/dist/skills/shelf.d.ts.map +1 -1
  526. package/packages/core/dist/skills/shelf.js +2 -3
  527. package/packages/core/dist/skills/shelf.js.map +1 -1
  528. package/packages/core/dist/skills/store.d.ts +2 -0
  529. package/packages/core/dist/skills/store.d.ts.map +1 -1
  530. package/packages/core/dist/skills/store.js +17 -12
  531. package/packages/core/dist/skills/store.js.map +1 -1
  532. package/packages/core/dist/tools/catalog.d.ts.map +1 -1
  533. package/packages/core/dist/tools/catalog.js +6 -2
  534. package/packages/core/dist/tools/catalog.js.map +1 -1
  535. package/packages/core/dist/tools/hub.d.ts.map +1 -1
  536. package/packages/core/dist/tools/hub.js +97 -79
  537. package/packages/core/dist/tools/hub.js.map +1 -1
  538. package/packages/core/dist/turns/journal.d.ts.map +1 -1
  539. package/packages/core/dist/turns/journal.js +12 -18
  540. package/packages/core/dist/turns/journal.js.map +1 -1
  541. package/packages/core/dist/types.d.ts +12 -3
  542. package/packages/core/dist/types.d.ts.map +1 -1
  543. package/packages/core/dist/types.js.map +1 -1
  544. package/packages/core/dist/util/blocks.d.ts.map +1 -1
  545. package/packages/core/dist/util/blocks.js +14 -22
  546. package/packages/core/dist/util/blocks.js.map +1 -1
  547. package/packages/core/dist/util/queue.d.ts +0 -2
  548. package/packages/core/dist/util/queue.d.ts.map +1 -1
  549. package/packages/core/dist/util/queue.js +0 -6
  550. package/packages/core/dist/util/queue.js.map +1 -1
  551. package/packages/core/package.json +1 -1
  552. package/packages/server/dist/auth.d.ts +8 -0
  553. package/packages/server/dist/auth.d.ts.map +1 -1
  554. package/packages/server/dist/auth.js +8 -8
  555. package/packages/server/dist/auth.js.map +1 -1
  556. package/packages/server/dist/env.d.ts.map +1 -1
  557. package/packages/server/dist/env.js +18 -15
  558. package/packages/server/dist/env.js.map +1 -1
  559. package/packages/server/dist/errors.d.ts +3 -0
  560. package/packages/server/dist/errors.d.ts.map +1 -0
  561. package/packages/server/dist/errors.js +5 -0
  562. package/packages/server/dist/errors.js.map +1 -0
  563. package/packages/server/dist/gateways/attachments.d.ts.map +1 -1
  564. package/packages/server/dist/gateways/attachments.js +38 -21
  565. package/packages/server/dist/gateways/attachments.js.map +1 -1
  566. package/packages/server/dist/gateways/markdown.d.ts.map +1 -1
  567. package/packages/server/dist/gateways/markdown.js +30 -12
  568. package/packages/server/dist/gateways/markdown.js.map +1 -1
  569. package/packages/server/dist/gateways/push.d.ts +6 -6
  570. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  571. package/packages/server/dist/gateways/push.js +101 -74
  572. package/packages/server/dist/gateways/push.js.map +1 -1
  573. package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -1
  574. package/packages/server/dist/gateways/telegram-api.js +61 -44
  575. package/packages/server/dist/gateways/telegram-api.js.map +1 -1
  576. package/packages/server/dist/gateways/telegram.d.ts +5 -0
  577. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  578. package/packages/server/dist/gateways/telegram.js +985 -753
  579. package/packages/server/dist/gateways/telegram.js.map +1 -1
  580. package/packages/server/dist/gateways/threads.d.ts.map +1 -1
  581. package/packages/server/dist/gateways/threads.js +144 -130
  582. package/packages/server/dist/gateways/threads.js.map +1 -1
  583. package/packages/server/dist/listeners/imap.d.ts.map +1 -1
  584. package/packages/server/dist/listeners/imap.js +0 -0
  585. package/packages/server/dist/listeners/imap.js.map +1 -1
  586. package/packages/server/dist/listeners/registry.d.ts.map +1 -1
  587. package/packages/server/dist/listeners/registry.js +15 -15
  588. package/packages/server/dist/listeners/registry.js.map +1 -1
  589. package/packages/server/dist/main.js +3 -2
  590. package/packages/server/dist/main.js.map +1 -1
  591. package/packages/server/dist/routes/chat.d.ts.map +1 -1
  592. package/packages/server/dist/routes/chat.js +5 -8
  593. package/packages/server/dist/routes/chat.js.map +1 -1
  594. package/packages/server/dist/routes/config.d.ts +6 -0
  595. package/packages/server/dist/routes/config.d.ts.map +1 -1
  596. package/packages/server/dist/routes/config.js +34 -31
  597. package/packages/server/dist/routes/config.js.map +1 -1
  598. package/packages/server/dist/routes/cron.d.ts.map +1 -1
  599. package/packages/server/dist/routes/cron.js +33 -23
  600. package/packages/server/dist/routes/cron.js.map +1 -1
  601. package/packages/server/dist/routes/dream.d.ts +1 -1
  602. package/packages/server/dist/routes/dream.d.ts.map +1 -1
  603. package/packages/server/dist/routes/dream.js +16 -34
  604. package/packages/server/dist/routes/dream.js.map +1 -1
  605. package/packages/server/dist/routes/gateways.d.ts.map +1 -1
  606. package/packages/server/dist/routes/gateways.js +8 -13
  607. package/packages/server/dist/routes/gateways.js.map +1 -1
  608. package/packages/server/dist/routes/memories.d.ts.map +1 -1
  609. package/packages/server/dist/routes/memories.js +16 -29
  610. package/packages/server/dist/routes/memories.js.map +1 -1
  611. package/packages/server/dist/routes/night.d.ts +31 -0
  612. package/packages/server/dist/routes/night.d.ts.map +1 -0
  613. package/packages/server/dist/routes/night.js +28 -0
  614. package/packages/server/dist/routes/night.js.map +1 -0
  615. package/packages/server/dist/routes/org.d.ts.map +1 -1
  616. package/packages/server/dist/routes/org.js +125 -119
  617. package/packages/server/dist/routes/org.js.map +1 -1
  618. package/packages/server/dist/routes/profile.d.ts.map +1 -1
  619. package/packages/server/dist/routes/profile.js +5 -6
  620. package/packages/server/dist/routes/profile.js.map +1 -1
  621. package/packages/server/dist/routes/providers.d.ts.map +1 -1
  622. package/packages/server/dist/routes/providers.js +1 -3
  623. package/packages/server/dist/routes/providers.js.map +1 -1
  624. package/packages/server/dist/routes/query.d.ts +10 -0
  625. package/packages/server/dist/routes/query.d.ts.map +1 -0
  626. package/packages/server/dist/routes/query.js +17 -0
  627. package/packages/server/dist/routes/query.js.map +1 -0
  628. package/packages/server/dist/routes/questions.d.ts.map +1 -1
  629. package/packages/server/dist/routes/questions.js +5 -11
  630. package/packages/server/dist/routes/questions.js.map +1 -1
  631. package/packages/server/dist/routes/sessions.d.ts.map +1 -1
  632. package/packages/server/dist/routes/sessions.js +20 -28
  633. package/packages/server/dist/routes/sessions.js.map +1 -1
  634. package/packages/server/dist/routes/sleep.d.ts.map +1 -1
  635. package/packages/server/dist/routes/sleep.js +21 -36
  636. package/packages/server/dist/routes/sleep.js.map +1 -1
  637. package/packages/server/dist/routes/stats.d.ts.map +1 -1
  638. package/packages/server/dist/routes/stats.js +2 -7
  639. package/packages/server/dist/routes/stats.js.map +1 -1
  640. package/packages/server/dist/routes/terminals.d.ts.map +1 -1
  641. package/packages/server/dist/routes/terminals.js +19 -14
  642. package/packages/server/dist/routes/terminals.js.map +1 -1
  643. package/packages/server/dist/routes/tools.d.ts.map +1 -1
  644. package/packages/server/dist/routes/tools.js +7 -5
  645. package/packages/server/dist/routes/tools.js.map +1 -1
  646. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  647. package/packages/server/dist/routes/ws.js +235 -207
  648. package/packages/server/dist/routes/ws.js.map +1 -1
  649. package/packages/server/dist/schemas.d.ts +30 -21
  650. package/packages/server/dist/schemas.d.ts.map +1 -1
  651. package/packages/server/dist/schemas.js +3 -2
  652. package/packages/server/dist/schemas.js.map +1 -1
  653. package/packages/server/dist/server.d.ts.map +1 -1
  654. package/packages/server/dist/server.js +250 -230
  655. package/packages/server/dist/server.js.map +1 -1
  656. package/packages/server/dist/services/stream.d.ts.map +1 -1
  657. package/packages/server/dist/services/stream.js +6 -4
  658. package/packages/server/dist/services/stream.js.map +1 -1
  659. package/packages/server/dist/services/stt.d.ts +1 -1
  660. package/packages/server/dist/services/stt.d.ts.map +1 -1
  661. package/packages/server/dist/services/stt.js +175 -124
  662. package/packages/server/dist/services/stt.js.map +1 -1
  663. package/packages/server/dist/services/tts.d.ts.map +1 -1
  664. package/packages/server/dist/services/tts.js +82 -54
  665. package/packages/server/dist/services/tts.js.map +1 -1
  666. package/packages/server/dist/services/turns.d.ts +8 -6
  667. package/packages/server/dist/services/turns.d.ts.map +1 -1
  668. package/packages/server/dist/services/turns.js +36 -32
  669. package/packages/server/dist/services/turns.js.map +1 -1
  670. package/packages/server/dist/services/updates.d.ts +1 -0
  671. package/packages/server/dist/services/updates.d.ts.map +1 -1
  672. package/packages/server/dist/services/updates.js +150 -91
  673. package/packages/server/dist/services/updates.js.map +1 -1
  674. package/packages/server/dist/services/voice-keys.d.ts.map +1 -1
  675. package/packages/server/dist/services/voice-keys.js +4 -2
  676. package/packages/server/dist/services/voice-keys.js.map +1 -1
  677. package/packages/server/dist/static.d.ts +1 -1
  678. package/packages/server/dist/static.d.ts.map +1 -1
  679. package/packages/server/dist/static.js +7 -7
  680. package/packages/server/dist/static.js.map +1 -1
  681. package/packages/server/package.json +1 -1
  682. package/packages/web/dist/assets/{abnfDiagram-O67JEVCF-D7YyFndQ.js → abnfDiagram-O67JEVCF-c90Gs7pG.js} +1 -1
  683. package/packages/web/dist/assets/{arc-C_Zgk2dJ.js → arc-C28-SQX8.js} +1 -1
  684. package/packages/web/dist/assets/{architectureDiagram-NJMV4G6O-eI0adu1B.js → architectureDiagram-NJMV4G6O-CBPhVAKx.js} +1 -1
  685. package/packages/web/dist/assets/{blockDiagram-BEXU5L5S-WAoOFUA9.js → blockDiagram-BEXU5L5S-CwKMvCbh.js} +1 -1
  686. package/packages/web/dist/assets/{c4Diagram-YGBWAQC7-DE8Zyhng.js → c4Diagram-YGBWAQC7-CsL4YtmG.js} +1 -1
  687. package/packages/web/dist/assets/channel-gYp6Rt3b.js +1 -0
  688. package/packages/web/dist/assets/{chunk-2Q5K7J3B-bnqLP2XD.js → chunk-2Q5K7J3B-C9Bji_Nr.js} +1 -1
  689. package/packages/web/dist/assets/{chunk-3FUC2YCW-Ck1_SVe0.js → chunk-3FUC2YCW-BUnPWClf.js} +2 -2
  690. package/packages/web/dist/assets/{chunk-5VM5RSS4-hDmC41gD.js → chunk-5VM5RSS4-CdfpfDTC.js} +1 -1
  691. package/packages/web/dist/assets/{chunk-GTNCS2PH-PoWvfCrT.js → chunk-GTNCS2PH-BZrKT8Ne.js} +1 -1
  692. package/packages/web/dist/assets/{chunk-GWA4HPMP-D3V0IG43.js → chunk-GWA4HPMP-C0jEzDJu.js} +1 -1
  693. package/packages/web/dist/assets/{chunk-JWPE2WC7-BryfpHM5.js → chunk-JWPE2WC7-CkLRmEro.js} +1 -1
  694. package/packages/web/dist/assets/{chunk-NETBCI7D-8ic1iEdT.js → chunk-NETBCI7D-BBeWMDmk.js} +1 -1
  695. package/packages/web/dist/assets/{chunk-WEXAMYUT-nM8tmQT2.js → chunk-WEXAMYUT-B6IqsBxs.js} +1 -1
  696. package/packages/web/dist/assets/{chunk-XXDRQBXY-Do28F482.js → chunk-XXDRQBXY-BPXeDnB2.js} +1 -1
  697. package/packages/web/dist/assets/{classDiagram-v2-NBCMYWYE-Bop9oNNO.js → classDiagram-v2-NBCMYWYE-2kqq2mJ8.js} +1 -1
  698. package/packages/web/dist/assets/{cose-bilkent-JH36ORCC-a7f_bpnt.js → cose-bilkent-JH36ORCC-G49FKtk6.js} +1 -1
  699. package/packages/web/dist/assets/{cynefin-OW5HDTMX-DnArcis_.js → cynefin-OW5HDTMX-98M_mPg9.js} +1 -1
  700. package/packages/web/dist/assets/{cynefinDiagram-VND7K2PF-vEuTb1GD.js → cynefinDiagram-VND7K2PF-BYJTAxOT.js} +1 -1
  701. package/packages/web/dist/assets/{dagre-6A5THRUB-BgG4MynJ.js → dagre-6A5THRUB-Bxcb5kkl.js} +1 -1
  702. package/packages/web/dist/assets/{diagram-22UHCM2B-DRCQpafv.js → diagram-22UHCM2B-DK7wAztC.js} +1 -1
  703. package/packages/web/dist/assets/{diagram-3UASUU5V-BKgmAXde.js → diagram-3UASUU5V-BMRz0ele.js} +1 -1
  704. package/packages/web/dist/assets/{diagram-ATOU4E4O-B6Hsy36X.js → diagram-ATOU4E4O-O23sdVpm.js} +1 -1
  705. package/packages/web/dist/assets/{diagram-CDSNMT55-JflyfyoB.js → diagram-CDSNMT55-CGxai-zV.js} +1 -1
  706. package/packages/web/dist/assets/{diagram-MLGK6HIB-Dd2QPJjT.js → diagram-MLGK6HIB-B_29W-sW.js} +1 -1
  707. package/packages/web/dist/assets/{diagram-MPIPVDR6-DE5QU60x.js → diagram-MPIPVDR6-OSt1qPU_.js} +1 -1
  708. package/packages/web/dist/assets/{ebnfDiagram-ZINNZB2B-D7AQ741b.js → ebnfDiagram-ZINNZB2B-DnZcwiew.js} +1 -1
  709. package/packages/web/dist/assets/{elk-276RUBZZ-CeewBVLF.js → elk-276RUBZZ-BP6-xQAF.js} +1 -1
  710. package/packages/web/dist/assets/{erDiagram-OPXOYQCR-mLLYkZ5c.js → erDiagram-OPXOYQCR-DhG7UZtA.js} +1 -1
  711. package/packages/web/dist/assets/{flowDiagram-KWPJA3E3-DtpSpsQN.js → flowDiagram-KWPJA3E3-CNTS1YPA.js} +1 -1
  712. package/packages/web/dist/assets/{ganttDiagram-FUAMR5RP-1_lh-3ky.js → ganttDiagram-FUAMR5RP-_eKkbUxc.js} +1 -1
  713. package/packages/web/dist/assets/{gitGraphDiagram-X574FWY7-DoPXZuT5.js → gitGraphDiagram-X574FWY7-N_PXNE-o.js} +1 -1
  714. package/packages/web/dist/assets/index-DGq8BOVF.js +646 -0
  715. package/packages/web/dist/assets/index-DgMuFFt3.css +32 -0
  716. package/packages/web/dist/assets/{infoDiagram-VRGFBTTK-DQpRGGiD.js → infoDiagram-VRGFBTTK-vj_EDhft.js} +1 -1
  717. package/packages/web/dist/assets/{ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js → ishikawaDiagram-OU5B5YK6-Dr0BodVq.js} +1 -1
  718. package/packages/web/dist/assets/{journeyDiagram-ZHPQQLJL-Bg-oeFjb.js → journeyDiagram-ZHPQQLJL-DykOPAu9.js} +1 -1
  719. package/packages/web/dist/assets/{kanban-definition-PNTS6WVX-BnpI4VH8.js → kanban-definition-PNTS6WVX-zslQcJnX.js} +1 -1
  720. package/packages/web/dist/assets/{mermaid.core-BwBKxlRA.js → mermaid.core-C888eQE1.js} +4 -4
  721. package/packages/web/dist/assets/{mindmap-definition-NLK3R4M7-NBnnxEoO.js → mindmap-definition-NLK3R4M7-CpdltDoL.js} +1 -1
  722. package/packages/web/dist/assets/{pegDiagram-GJSIUBJH-RrXXbIvO.js → pegDiagram-GJSIUBJH-Dsx3NmVN.js} +1 -1
  723. package/packages/web/dist/assets/{pieDiagram-5QR66LMP-B27q6Gso.js → pieDiagram-5QR66LMP-D_4DJLkr.js} +1 -1
  724. package/packages/web/dist/assets/{quadrantDiagram-O4NWA36T-DGDsdur2.js → quadrantDiagram-O4NWA36T-BXgGWrJ1.js} +1 -1
  725. package/packages/web/dist/assets/{railroadDiagram-XR7U4H2S-GdjkE3mI.js → railroadDiagram-XR7U4H2S-WMsrl4TR.js} +1 -1
  726. package/packages/web/dist/assets/{requirementDiagram-PLB6GJNP-DjK0GfgO.js → requirementDiagram-PLB6GJNP-m2PpXDpq.js} +1 -1
  727. package/packages/web/dist/assets/{sankeyDiagram-IPEJSGJF-BG_AIkwF.js → sankeyDiagram-IPEJSGJF-DfcxNy3C.js} +1 -1
  728. package/packages/web/dist/assets/scene-BA1PRRU7.js +4620 -0
  729. package/packages/web/dist/assets/{sequenceDiagram-PO4LG4MO-CIQwUb4y.js → sequenceDiagram-PO4LG4MO-B8yIKbJ8.js} +1 -1
  730. package/packages/web/dist/assets/{sizeCapture-INFHLROL-bpIoPxdJ.js → sizeCapture-INFHLROL-Cic9nV7h.js} +1 -1
  731. package/packages/web/dist/assets/{stateDiagram-v2-GCMORJYK-8hYXvPPv.js → stateDiagram-v2-GCMORJYK-oOFJPdg1.js} +1 -1
  732. package/packages/web/dist/assets/{swimlanes-2SLR337P-gfflUMF9.js → swimlanes-2SLR337P-UCvVVk9j.js} +1 -1
  733. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-B8q2Z_Nb.js +8 -0
  734. package/packages/web/dist/assets/{timeline-definition-EJHVYXUP-PHMNoGTZ.js → timeline-definition-EJHVYXUP-BLgviPCi.js} +1 -1
  735. package/packages/web/dist/assets/{usecaseDiagram-POWQR4AR-B2j5iteO.js → usecaseDiagram-POWQR4AR-CV7U5Y4h.js} +1 -1
  736. package/packages/web/dist/assets/{vennDiagram-UO4OBE2U-BzxtZ-_2.js → vennDiagram-UO4OBE2U-C8OA0JqM.js} +1 -1
  737. package/packages/web/dist/assets/{wardleyDiagram-VNRHLVJA-DL7YbMpY.js → wardleyDiagram-VNRHLVJA-F55WtNqt.js} +1 -1
  738. package/packages/web/dist/assets/{xychartDiagram-PMCCYNJV-CisgP1cT.js → xychartDiagram-PMCCYNJV-C93Bzul9.js} +1 -1
  739. package/packages/web/dist/index.html +2 -2
  740. package/packages/web/package.json +1 -1
  741. package/packages/web/dist/assets/channel-egZxcyUK.js +0 -1
  742. package/packages/web/dist/assets/index-Cw2Opmx7.js +0 -648
  743. package/packages/web/dist/assets/index-j0zBRCgT.css +0 -32
  744. package/packages/web/dist/assets/scene-D4LPicHk.js +0 -4620
  745. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +0 -8
@@ -15,6 +15,8 @@ import { formatAge, formatDay, formatWhen } from '../util/time.js';
15
15
  import { buildAgentPrompt, renderBoard, renderOrgOverview, renderSchedules, renderTaskActivity, } from './prompts.js';
16
16
  import { draftHandover, draftNote, draftReconfig, draftReplacementProposal, judgeAssignment, } from './review.js';
17
17
  import { buildTaskWaves, planTask } from './planner.js';
18
+ import { AssignmentLogBuffer } from './assignment-log.js';
19
+ import { ToolArgs, asMemoryKind, asPermission, asPriority, asQuestionOptions, resolveClearable, resolveOptional, toolError, } from './tool-args.js';
18
20
  import { toolsFor } from './tools.js';
19
21
  import { externalTurnExtras, renderToolServers, toolServerStates, toolServersFor, withToolServer, } from '../tools/hub.js';
20
22
  import { SkillStore, projectSkillsDir, renderSkill, renderSkillsIndex, skillSlug, } from '../skills/store.js';
@@ -27,6 +29,14 @@ import { fingerprintMcpFile, projectMcpStatus, readProjectMcpFile, renderProject
27
29
  const PROGRESS_EVERY = 700;
28
30
  /** How much of a result travels back into the caller's tool response. */
29
31
  const RESULT_BUDGET = 24000;
32
+ /** How much of a result a task's note, a card line or a notification carries. */
33
+ const NOTE_RESULT_BUDGET = 4000;
34
+ /** The same for a failure notification, which also states the error. */
35
+ const NOTIFICATION_PARTIAL_BUDGET = 2000;
36
+ /** How much of one child's report a handed-off task's parent reads back. */
37
+ const CHILD_REPORT_BUDGET = 6000;
38
+ /** The port a watched mailbox gets when none is given: IMAP over TLS. */
39
+ const DEFAULT_IMAP_PORT = 993;
30
40
  /**
31
41
  * How many providers one assignment may run on. The second only happens when
32
42
  * the first died on its usage limit before producing anything, so a switch
@@ -40,6 +50,22 @@ const MAX_PROVIDER_ATTEMPTS = 2;
40
50
  * applies on top of it.
41
51
  */
42
52
  const MAX_DELEGATION_ROUNDS = 2;
53
+ /** How many recent records a lookup by id prefix, or by project, looks through. */
54
+ const LOOKUP_SCAN_LIMIT = 500;
55
+ /** How many of the assistant's memories `forget` searches for an id prefix. */
56
+ const MEMORY_PREFIX_SCAN_LIMIT = 1000;
57
+ /** How much of a profile document one `read_profile` call returns unless asked otherwise. */
58
+ const PROFILE_EXCERPT_CHARS = 12000;
59
+ /** What fits an `ask_user` card on a phone. */
60
+ const MIN_QUESTION_OPTIONS = 2;
61
+ const MAX_QUESTION_OPTIONS = 4;
62
+ /** How many core-profile memories an agent's turn always carries. */
63
+ const AGENT_PROFILE_LIMIT = 3;
64
+ /** What `#learn` recalls to tell the extractor what the agent already knows. */
65
+ const KNOWN_MEMORIES_LIMIT = 20;
66
+ const KNOWN_MEMORIES_THRESHOLD = 0.05;
67
+ const NO_SUCH_RUN = 'No run with that id.';
68
+ const NO_PROJECT_MCP_SERVERS = "No MCP servers in this project's .mcp.json.";
43
69
  /**
44
70
  * The notice for one ended task, in the words the assistant reads. `question`
45
71
  * is what the agent asked with `ask_requester`, for a task that is waiting.
@@ -48,7 +74,7 @@ export function reportBackNotice(task, agent, question) {
48
74
  const who = agent ? agent.name + ' (' + agent.slug + ')' : 'the agent';
49
75
  const ended = task.finishedAt ?? task.updatedAt;
50
76
  const took = task.startedAt && ended > task.startedAt ? ' after ' + formatAge(task.startedAt, ended, 'second') : '';
51
- const head = '[Rookery] Background task ' + task.id.slice(0, 8) + ' "' + task.title + '", handed to ' + who + ', ';
77
+ const head = '[Rookery] Background task ' + shortId(task.id) + ' "' + task.title + '", handed to ' + who + ', ';
52
78
  const system = 'This message comes from the system, not from your user - do not answer it as if they wrote it. ' +
53
79
  'You handed this work off earlier in this conversation; this is the follow-up you owe them.';
54
80
  switch (task.status) {
@@ -62,13 +88,13 @@ export function reportBackNotice(task, agent, question) {
62
88
  (question ? 'The question:\n' + clip(question, RESULT_BUDGET) + '\n\n' : '') +
63
89
  (task.result ? 'What it said:\n' + clip(task.result, RESULT_BUDGET) + '\n\n' : '') + system + ' ' +
64
90
  'Put the question to the user. Once they answer, pass the answer on with answer_task("' +
65
- task.id.slice(0, 8) + '", ...) and the task picks up again, as the same task. Answer it yourself only ' +
91
+ shortId(task.id) + '", ...) and the task picks up again, as the same task. Answer it yourself only ' +
66
92
  'if you know the answer for certain.');
67
93
  case 'cancelled':
68
94
  return head + 'was cancelled' + took + '.\n\n' + system + ' Tell the user briefly, unless they cancelled it themselves just now.';
69
95
  default:
70
96
  return (head + 'failed' + took + ': ' + (task.error ?? 'no reason given').replace(/[.\s]+$/, '') + '.' +
71
- (task.result ? '\n\nWhat it had so far:\n' + clip(task.result, 4000) : '') + '\n\n' + system + ' ' +
97
+ (task.result ? '\n\nWhat it had so far:\n' + clip(task.result, NOTE_RESULT_BUDGET) : '') + '\n\n' + system + ' ' +
72
98
  'Tell the user what went wrong and what you suggest - retrying, handing it to someone else, or dropping it.');
73
99
  }
74
100
  }
@@ -85,7 +111,7 @@ export function taskNotification(task, agent, question) {
85
111
  return {
86
112
  kind: 'question',
87
113
  title: (agent ? agent.name : 'An agent') + ' has a question about ' + name,
88
- body: clip(question ?? task.result ?? 'The task is waiting for an answer.', 4000),
114
+ body: clip(question ?? task.result ?? 'The task is waiting for an answer.', NOTE_RESULT_BUDGET),
89
115
  fromKind: agent ? 'agent' : 'system',
90
116
  fromAgentId: agent?.id,
91
117
  taskId: task.id,
@@ -97,92 +123,91 @@ export function taskNotification(task, agent, question) {
97
123
  ? 'Task ' + name + ' was cancelled'
98
124
  : 'Task ' + name + ' failed';
99
125
  const body = task.status === 'done'
100
- ? clip(task.result?.trim() || '', 4000) + (task.error ? (task.result ? '\n\n' : '') + 'Note: ' + task.error : '')
126
+ ? clip(task.result?.trim() || '', NOTE_RESULT_BUDGET) + (task.error ? (task.result ? '\n\n' : '') + 'Note: ' + task.error : '')
101
127
  : task.status === 'cancelled'
102
128
  ? ''
103
- : (task.error ?? 'No reason given.') + (task.result ? '\n\nWhat it had so far:\n' + clip(task.result, 2000) : '');
129
+ : (task.error ?? 'No reason given.') +
130
+ (task.result ? '\n\nWhat it had so far:\n' + clip(task.result, NOTIFICATION_PARTIAL_BUDGET) : '');
104
131
  return { kind: 'task', title, body, fromKind: 'system', taskId: task.id };
105
132
  }
106
- /** How much of one assignment's live log is kept, in JSON bytes. */
107
- const ASSIGNMENT_LOG_BYTES = 256 * 1024;
108
133
  /**
109
- * The live log of one running assignment: a ring buffer capped in bytes and
110
- * the watchers following it. It exists only while the run does - once the
111
- * assignment ends, watchers learn it from the `assignment` broadcast and the
112
- * buffer goes away, so watching never grows anything on disk.
134
+ * What one provider attempt produced so far: the report text, and the fatal
135
+ * error that ended it, if one did.
113
136
  */
114
- class AssignmentLogBuffer {
115
- /** Buffered entries in arrival order; the oldest go when the cap is hit. */
116
- entries = [];
117
- /** Set once whole entries were dropped to stay under the cap. */
118
- overflowed = false;
119
- listeners = new Set();
120
- #seq = 0;
121
- #bytes = 0;
122
- #done = false;
123
- #waiters = [];
124
- /** Append one event; returns the numbered entry the watchers receive. */
125
- push(event) {
126
- const entry = { seq: (this.#seq += 1), event };
127
- this.entries.push(entry);
128
- this.#bytes += byteSize(entry);
129
- // Over the cap, whole entries go, oldest first - but never the one just
130
- // pushed: a single huge line is better kept than silently dropped.
131
- while (this.#bytes > ASSIGNMENT_LOG_BYTES && this.entries.length > 1) {
132
- const dropped = this.entries.shift();
133
- if (!dropped)
134
- break;
135
- this.#bytes -= byteSize(dropped);
136
- this.overflowed = true;
137
- }
138
- for (const listener of [...this.listeners])
139
- listener(entry);
140
- this.#wake();
141
- return entry;
137
+ class AttemptOutput {
138
+ text = '';
139
+ fatal = null;
140
+ #sinceProgress = 0;
141
+ /** Take in a streamed delta; true when enough has come in since the last progress line. */
142
+ append(delta) {
143
+ this.text += delta;
144
+ this.#sinceProgress += delta.length;
145
+ if (this.#sinceProgress < PROGRESS_EVERY)
146
+ return false;
147
+ this.#sinceProgress = 0;
148
+ return true;
142
149
  }
143
- /**
144
- * A provider switch starts the transcript over: the dead attempt's half
145
- * output would only read as a broken restart. `seq` keeps counting, so a
146
- * client ordering by it stays whole across the gap.
147
- */
148
- reset() {
149
- this.entries.length = 0;
150
- this.#bytes = 0;
151
- this.overflowed = false;
152
- }
153
- /** The run is over: generators drain what is left and then end. */
154
- end() {
155
- this.#done = true;
156
- this.#wake();
157
- }
158
- /** Replay the buffer, then follow it live until the run ends. */
159
- async *stream() {
160
- let lastSeq = 0;
161
- for (;;) {
162
- // The cap shifts the oldest entries out from under any index, and a
163
- // reset empties the list entirely - the cursor is the last seq
164
- // yielded, never a position.
165
- const next = this.entries.find((entry) => entry.seq > lastSeq);
166
- if (next) {
167
- lastSeq = next.seq;
168
- yield next;
169
- continue;
170
- }
171
- if (this.#done)
172
- return;
173
- await new Promise((resolve) => this.#waiters.push(resolve));
150
+ }
151
+ /**
152
+ * The row of one running assignment, kept honest: every change is written,
153
+ * read back and announced in one step.
154
+ */
155
+ class AssignmentRecord {
156
+ #assignment;
157
+ #org;
158
+ #agent;
159
+ #publish;
160
+ #log;
161
+ constructor(org, agent, assignment, publish, log) {
162
+ this.#org = org;
163
+ this.#agent = agent;
164
+ this.#assignment = assignment;
165
+ this.#publish = publish;
166
+ this.#log = log;
167
+ }
168
+ get id() {
169
+ return this.#assignment.id;
170
+ }
171
+ /** The row as last read back. */
172
+ get assignment() {
173
+ return this.#assignment;
174
+ }
175
+ /** Say how the run stands, to the turn that started it and to everyone listening; `extra` carries live-only fields. */
176
+ announce(extra = {}) {
177
+ this.#publish({ type: 'assignment', assignment: toView(this.#assignment, this.#agent, extra) });
178
+ }
179
+ finish(patch, extra = {}) {
180
+ this.#org.updateAssignment(this.id, patch);
181
+ this.#assignment = this.#org.getAssignment(this.id) ?? this.#assignment;
182
+ this.announce(extra);
183
+ return this.#assignment;
184
+ }
185
+ fail(error, started) {
186
+ const failed = this.finish({ status: 'failed', error, finishedAt: Date.now(), durationMs: Date.now() - started }, { error });
187
+ // Every fail() path is a hard signal (timeout, no provider, empty
188
+ // output, a fatal provider error) - no model call, and it marks the run
189
+ // as a technical failure rather than a quality judgement (see
190
+ // docs/concepts/agent-performance-management.md). A write that cannot
191
+ // land must never take the assignment result down with it.
192
+ try {
193
+ this.#org.upsertReview({
194
+ orgId: failed.orgId,
195
+ agentId: this.#agent.id,
196
+ assignmentId: failed.id,
197
+ source: 'system',
198
+ overall: 1,
199
+ failedRun: true,
200
+ });
174
201
  }
175
- }
176
- #wake() {
177
- // splice, never length = 0 before the loop: both names point at the
178
- // same array here, and emptying it first would leave nothing to iterate.
179
- for (const waiter of this.#waiters.splice(0))
180
- waiter();
202
+ catch (reviewError) {
203
+ this.#log.warn('System review failed to write', {
204
+ assignment: failed.id,
205
+ error: reviewError.message,
206
+ });
207
+ }
208
+ return failed;
181
209
  }
182
210
  }
183
- function byteSize(entry) {
184
- return Buffer.byteLength(JSON.stringify(entry));
185
- }
186
211
  export class OrgController extends EventEmitter {
187
212
  #store;
188
213
  #registry;
@@ -292,839 +317,894 @@ export class OrgController extends EventEmitter {
292
317
  return (name, args) => this.handle(context, name, args);
293
318
  }
294
319
  /* -------------------------------- tools -------------------------------- */
295
- async handle(context, name, args) {
296
- const text = (key) => (typeof args[key] === 'string' ? args[key].trim() : '');
297
- const fail = (message) => ({ text: message, isError: true });
320
+ async handle(context, name, rawArgs) {
321
+ const args = new ToolArgs(rawArgs);
298
322
  switch (name) {
299
323
  case 'org_overview':
300
324
  return { text: renderOrgOverview(this.snapshot(context.orgId), this.#store.org) };
301
325
  case 'assign':
302
- return this.#assign(context, text('agent'), text('title'), text('task'), text('project'), args.wait !== false);
303
- case 'assignment_status': {
304
- const assignment = this.findAssignment(context.orgId, text('id'));
305
- if (!assignment)
306
- return fail('No run with that id.');
307
- return {
308
- text: describeAssignment(assignment, this.#store.org.getAgent(assignment.agentId), this.#store.org.taskRunNumber(assignment.id)),
309
- };
310
- }
311
- case 'review_assignment': {
312
- if (context.audience !== 'assistant')
313
- return fail('Only the assistant records reviews.');
314
- const assignment = this.findAssignment(context.orgId, text('id'));
315
- if (!assignment)
316
- return fail('No run with that id.');
317
- const overall = clampNumber(args.overall, 1, 5, 3);
318
- const review = this.#store.org.upsertReview({
319
- orgId: context.orgId,
320
- agentId: assignment.agentId,
321
- assignmentId: assignment.id,
322
- taskId: this.#store.org.getTaskIdForAssignment(assignment.id) ?? undefined,
323
- source: 'assistant',
324
- overall,
325
- comment: text('comment') || undefined,
326
- });
327
- this.emit('changed', { kind: 'agent', id: assignment.agentId });
328
- return { text: 'Review recorded (overall ' + review.overall + ').' };
329
- }
330
- case 'agent_performance': {
331
- if (context.audience !== 'assistant')
332
- return fail('Only the assistant sees the personnel record.');
333
- const agent = this.#store.org.findAgent(context.orgId, text('agent'));
334
- if (!agent)
335
- return fail('No agent "' + text('agent') + '".');
336
- return { text: describeAgentPerformance(agent, this.#store.org) };
337
- }
338
- case 'cancel_assignment': {
339
- if (context.audience !== 'assistant')
340
- return fail('Only the assistant can call off a running task.');
341
- const assignment = this.findAssignment(context.orgId, text('id'));
342
- if (!assignment)
343
- return fail('No run with that id.');
344
- if (!this.cancel(assignment.id, 'the assistant')) {
345
- return fail('Run ' + assignment.id.slice(0, 8) + ' is not running; it is ' + assignment.status + '.');
346
- }
347
- return { text: 'Calling off run ' + assignment.id.slice(0, 8) + '. It ends as cancelled within a moment.' };
348
- }
349
- case 'list_assignments': {
350
- if (context.audience !== 'assistant')
351
- return fail('Only the assistant can read the history.');
352
- const agent = text('agent') ? this.#store.org.findAgent(context.orgId, text('agent')) : null;
353
- if (text('agent') && !agent)
354
- return fail('No agent "' + text('agent') + '".');
355
- const project = text('project') ? this.#store.org.findProject(context.orgId, text('project')) : null;
356
- if (text('project') && !project)
357
- return fail('No project "' + text('project') + '".');
358
- const wanted = text('status').split(',').map((v) => v.trim()).filter(Boolean);
359
- const limit = clampNumber(args.limit, 1, 200, 20);
360
- const rows = this.#store.org
361
- .listAssignments(context.orgId, {
362
- agentId: agent?.id,
363
- status: wanted.length ? wanted : undefined,
364
- limit: project ? 500 : limit,
365
- })
366
- .filter((entry) => !project || entry.projectId === project.id)
367
- .slice(0, limit);
368
- if (!rows.length)
369
- return { text: 'No runs match.' };
370
- const byId = new Map(this.#store.org.listAgents(context.orgId, { includeArchived: true }).map((entry) => [entry.id, entry]));
371
- return {
372
- text: rows
373
- .map((entry) => {
374
- const who = byId.get(entry.agentId)?.slug ?? '?';
375
- // Local wall clock, and for anything still going the elapsed
376
- // span as well: "has this run too long" is the question the
377
- // board watcher asks, and a span cannot be read in the wrong
378
- // timezone the way a stamp can.
379
- const when = formatWhen(entry.createdAt);
380
- const took = entry.durationMs
381
- ? ' ' + Math.round(entry.durationMs / 1000) + 's'
382
- : entry.status === 'running'
383
- ? ' running ' + formatAge(entry.createdAt)
384
- : '';
385
- // The name, never the brief: three runs of the same errand open
386
- // with the same twenty words, and a list of those tells nobody
387
- // which is which (concept 7.1).
388
- const run = this.#store.org.taskRunNumber(entry.id);
389
- return '- ' + entry.id.slice(0, 8) + ' ' + when + ' ' + entry.status + took + ' ' + who + ': ' +
390
- shorten(entry.title, 100) + (run && run > 1 ? ' (run ' + run + ')' : '') +
391
- (entry.error ? ' [' + shorten(entry.error, 60) + ']' : '');
392
- })
393
- .join('\n'),
394
- };
395
- }
396
- case 'update_project': {
397
- if (context.audience !== 'assistant')
398
- return fail('Only the assistant can change projects.');
399
- const project = this.#store.org.findProject(context.orgId, text('project'));
400
- if (!project)
401
- return fail('No project "' + text('project') + '".');
402
- const patch = {};
403
- if (text('name'))
404
- patch.name = text('name');
405
- if (text('description'))
406
- patch.description = text('description');
407
- if (text('path')) {
408
- if (text('path').toLowerCase() === 'none')
409
- patch.path = null;
410
- else if (!existsSync(text('path')))
411
- return fail('The directory ' + text('path') + ' does not exist.');
412
- else
413
- patch.path = text('path');
414
- }
415
- if (typeof args.archived === 'boolean')
416
- patch.archived = args.archived;
417
- if (!Object.keys(patch).length)
418
- return fail('Nothing to change.');
419
- this.#store.org.updateProject(project.id, patch);
420
- this.emit('changed', { kind: 'project', id: project.id });
421
- return { text: 'Updated project "' + (patch.name ?? project.name) + '": ' + Object.keys(patch).join(', ') + '.' };
422
- }
423
- case 'sleep_now': {
424
- if (context.audience !== 'assistant')
425
- return fail('Only the assistant has this memory.');
426
- if (!this.#sleep)
427
- return fail('The nightly memory run is not available here.');
428
- if (this.#sleep.isRunning(ASSISTANT_MEMORY_OWNER))
429
- return { text: 'The memory is already asleep.' };
430
- // Started, not awaited: a night takes minutes and the turn must not
431
- // sit and wait for it. The memory page follows it live.
432
- void this.#sleep.run({ owner: ASSISTANT_MEMORY_OWNER, trigger: 'manual' });
433
- return {
434
- text: 'The memory is going to sleep now. It condenses, files and connects; nothing is deleted, ' +
435
- 'and the run can be undone on the memory page.',
436
- };
437
- }
438
- case 'read_profile': {
439
- if (context.audience !== 'assistant')
440
- return fail('Only the assistant has this profile.');
441
- return { text: readProfileExcerpt(this.#config, text('name'), args.offset === undefined ? 0 : Number(args.offset), args.limit === undefined ? 12000 : Number(args.limit)) };
442
- }
443
- case 'search_profile': {
444
- if (context.audience !== 'assistant')
445
- return fail('Only the assistant has this profile.');
446
- return { text: searchProfile(this.#config, text('query')) };
447
- }
448
- case 'remember': {
449
- // The assistant keeps facts about the user; an agent keeps facts
450
- // about its own work. Either way the write lands in the caller's own
451
- // bank and nowhere else - there is no path here that writes across
452
- // the owner boundary.
453
- const owner = context.audience === 'agent' && context.agentId ? context.agentId : ASSISTANT_MEMORY_OWNER;
454
- // Same rule as write_skill below: a scheduled run has nobody present
455
- // to confirm anything, and a memory it pinned would even carry
456
- // origin 'user' - protected from the very night that should weigh it.
457
- if (context.scheduled) {
458
- return fail('This run was started by a schedule. Automated runs leave no memories - if this ' +
459
- 'belongs in memory, bring it up in a conversation.');
460
- }
461
- if (!text('content'))
462
- return fail('A memory needs content.');
463
- const tags = text('tags').split(',').map((v) => v.trim()).filter(Boolean);
464
- const record = this.#store.upsertMemory({
465
- kind: asMemoryKind(text('kind')),
466
- content: text('content'),
467
- tags,
468
- importance: clampNumber(args.importance, 0, 1, 0.7),
469
- owner,
470
- sourceSessionId: context.sessionId,
471
- // Asked for explicitly, so the night never merges it away.
472
- origin: 'user',
473
- });
474
- linkEntities(this.#store, owner, record.id, tags);
475
- this.emit('changed', { kind: 'memory', id: record.id });
476
- return { text: 'Remembered (' + record.id.slice(0, 8) + '): ' + record.content };
477
- }
478
- case 'forget': {
479
- if (context.audience !== 'assistant')
480
- return fail('Only the assistant has this memory.');
481
- // Forgetting is a deletion, and E1 of the memory concept says a
482
- // deletion happens only on the user's explicit word - a schedule has
483
- // nobody behind it to give that word.
484
- if (context.scheduled) {
485
- return fail('This run was started by a schedule. Nothing is forgotten on an automated run - ask ' +
486
- 'in a conversation instead.');
487
- }
488
- const ref = text('id');
489
- if (!ref)
490
- return fail('Which memory? Give its id.');
491
- const record = this.#store.getMemory(ref) ??
492
- this.#store.listMemories({ owner: ASSISTANT_MEMORY_OWNER, limit: 1000 }).find((m) => m.id.startsWith(ref));
493
- if (!record || record.owner !== ASSISTANT_MEMORY_OWNER)
494
- return fail('No memory ' + ref + '.');
495
- this.#store.forgetMemory(record.id);
496
- this.emit('changed', { kind: 'memory', id: record.id });
497
- return { text: 'Forgotten: ' + record.content };
498
- }
499
- case 'search_memory': {
500
- // Read-only, and strictly inside the caller's own bank: the
501
- // assistant searches what it knows about the user, an agent searches
502
- // its own working memory. One owner in, one owner out.
503
- const owner = context.audience === 'agent' && context.agentId ? context.agentId : ASSISTANT_MEMORY_OWNER;
504
- const limit = clampNumber(args.limit, 1, 100, 20);
505
- const query = text('query');
506
- const rows = query
507
- ? recall(this.#store, { text: query, limit, owner, touch: false })
508
- : this.#store.listMemories({ owner, limit });
509
- if (!rows.length)
510
- return { text: query ? 'Nothing in memory matches.' : 'Memory is empty.' };
511
- return {
512
- text: rows
513
- .map((m) => '- ' + m.id.slice(0, 8) + ' [' + m.kind + ', ' + m.importance.toFixed(2) + '] ' + m.content)
514
- .join('\n'),
515
- };
516
- }
326
+ return this.#toolAssign(context, args);
327
+ case 'assignment_status':
328
+ return this.#toolAssignmentStatus(context, args);
329
+ case 'review_assignment':
330
+ return this.#toolReviewAssignment(context, args);
331
+ case 'agent_performance':
332
+ return this.#toolAgentPerformance(context, args);
333
+ case 'cancel_assignment':
334
+ return this.#toolCancelAssignment(context, args);
335
+ case 'list_assignments':
336
+ return this.#toolListAssignments(context, args);
337
+ case 'update_project':
338
+ return this.#toolUpdateProject(context, args);
339
+ case 'sleep_now':
340
+ return this.#toolSleepNow(context);
341
+ case 'read_profile':
342
+ return this.#toolReadProfile(context, args);
343
+ case 'search_profile':
344
+ return this.#toolSearchProfile(context, args);
345
+ case 'remember':
346
+ return this.#toolRemember(context, args);
347
+ case 'forget':
348
+ return this.#toolForget(context, args);
349
+ case 'search_memory':
350
+ return this.#toolSearchMemory(context, args);
517
351
  case 'get_settings':
518
352
  if (context.audience !== 'assistant')
519
- return fail('Only the assistant can read settings.');
353
+ return toolError('Only the assistant can read settings.');
520
354
  return { text: describeSettings(this.#config) };
521
355
  case 'update_settings':
522
- return this.#updateSettings(context, args);
356
+ return this.#toolUpdateSettings(context, args);
523
357
  case 'ask_requester':
524
- return this.#askRequester(context, text('question'));
525
- case 'answer_task': {
526
- const task = this.findTask(context.orgId, text('id'));
527
- if (!task)
528
- return fail('No task ' + text('id') + '.');
529
- const answerer = context.audience === 'agent' ? { kind: 'agent', agentId: context.agentId } : { kind: 'assistant' };
530
- const answered = await this.#answer(task, text('answer'), answerer, context);
531
- if (!answered.ok)
532
- return fail(answered.reason);
533
- const where = context.taskId && task.parentId === context.taskId
534
- ? 'Your own task stays open until it is back: when your run ends, you are started again with its result.'
535
- : task.requesterSessionId && !task.parentId
536
- ? 'When it ends, a message arrives in the conversation it came from.'
537
- : 'How it ends is recorded on its card.';
538
- return {
539
- text: 'Answered task ' + task.id.slice(0, 8) + ' "' + task.title + '"; it runs again with your answer. ' + where,
540
- };
541
- }
542
- case 'report_to_user': {
543
- // Agents, and the one assistant run that has no conversation to speak
544
- // in: the board watcher. An ordinary assistant turn answers the user
545
- // directly, and `notify` is its line for what cannot wait.
546
- if (context.audience !== 'agent' && !context.watching) {
547
- return fail('Reach the user through your answer, or with notify for something that has to arrive now.');
548
- }
549
- if (!text('title') || !text('body'))
550
- return fail('A report needs a title and a body.');
551
- const notification = this.notifyUser({
552
- orgId: context.orgId,
553
- kind: context.watching ? 'watch' : 'agent',
554
- title: text('title'),
555
- body: text('body'),
556
- fromKind: context.audience === 'agent' ? 'agent' : 'assistant',
557
- fromAgentId: context.audience === 'agent' ? context.agentId : undefined,
558
- taskId: context.taskId,
559
- // The watcher's own run is where a reply to its report continues;
560
- // an agent's run has no conversation of its own to point at.
561
- sessionId: context.watching ? context.sessionId : undefined,
562
- });
563
- if (context.taskId && this.#store.org.getTask(context.taskId)) {
564
- this.#taskEvent({
565
- taskId: context.taskId,
566
- kind: 'note',
567
- actorKind: context.audience === 'agent' ? 'agent' : 'assistant',
568
- actorAgentId: context.agentId,
569
- text: 'Reported to the user: ' + notification.title + '\n\n' + notification.body,
570
- assignmentId: context.parentAssignmentId,
571
- });
572
- }
573
- return { text: 'Left the user a notification: "' + notification.title + '".' };
574
- }
575
- case 'task_activity': {
576
- const task = this.findTask(context.orgId, text('id'));
577
- if (!task)
578
- return fail('No task ' + text('id') + '.');
579
- return {
580
- text: clip(renderTaskActivity(task, this.#store.org.listTaskEvents(task.id), this.snapshot(context.orgId)), RESULT_BUDGET),
581
- };
582
- }
583
- case 'notify': {
584
- if (context.audience !== 'assistant')
585
- return fail('Only the assistant can send notifications.');
586
- if (!text('text'))
587
- return fail('A notification needs text.');
588
- const urgency = args.urgency === 'high' ? 'high' : 'normal';
589
- // Kept as well as pushed: a push is gone once it is swiped away, and
590
- // the web should be able to show what the assistant said on its own.
591
- // The push itself still travels on the `notify` event - the
592
- // notification is the record, so a channel must not push it twice.
593
- const firstLine = text('text').split('\n', 1)[0] ?? '';
594
- this.notifyUser({
595
- orgId: context.orgId,
596
- kind: 'system',
597
- title: shorten(firstLine, 80),
598
- body: text('text'),
599
- fromKind: 'assistant',
600
- sessionId: context.sessionId,
601
- });
602
- if (!this.#canNotify || !this.#canNotify()) {
603
- return {
604
- text: 'No push channel can reach the user right now - none is set up, it is switched off, or it has ' +
605
- 'no recipient. The message is saved in their notifications and waits there.',
606
- };
607
- }
608
- const event = { text: text('text'), urgency, at: Date.now() };
609
- this.emit('notify', event);
610
- return { text: 'Sent' + (urgency === 'high' ? ' (high urgency)' : '') + ': ' + event.text };
611
- }
612
- case 'ask_user': {
613
- // Only the assistant asks. An agent runs unattended by design and
614
- // asks whoever gave it the work (`ask_requester`); letting one block
615
- // on a person would stall a whole delegation chain behind them.
616
- if (context.audience !== 'assistant') {
617
- return fail('Only the assistant can ask the user. Inside a task, ask whoever gave you the work with ' +
618
- 'ask_requester; otherwise say what you need in your result.');
619
- }
620
- // Belt and braces: a scheduled run is not offered the tool at all
621
- // (see `register`), so getting here means the list was built for a
622
- // conversation and the run turned out to be automated.
623
- if (context.scheduled) {
624
- return fail('This run was started by a schedule and nobody is there to answer. Decide it yourself ' +
625
- 'and say in your result what you assumed.');
626
- }
627
- if (!this.#questions)
628
- return fail('Asking the user is not available here.');
629
- const header = text('header');
630
- const question = text('question');
631
- if (!question)
632
- return fail('A question needs its text.');
633
- const options = asQuestionOptions(args.options);
634
- if (options.length < 2)
635
- return fail('Offer at least two options to choose from.');
636
- if (options.length > 4)
637
- return fail('Offer at most four options; more does not fit a phone.');
638
- const timeoutMs = this.#config.questions.timeoutMs;
639
- // The close event carries why it closed, and the turn wants to know:
640
- // "nobody was there" and "somebody waved it away" are different
641
- // things to carry on from.
642
- let closedBecause;
643
- const emit = (event) => {
644
- if (event.type === 'question-closed')
645
- closedBecause = event.reason;
646
- context.emit(event);
647
- };
648
- const answer = await this.#questions.ask({
649
- header: header || 'Question',
650
- question,
651
- options,
652
- multiSelect: args.multiSelect === true,
653
- sessionId: context.sessionId,
654
- },
655
- // `emit` puts the card on the asking turn's own stream; `signal` is
656
- // the half no other tool handler has: an aborted turn kills the
657
- // provider process, and without this the question would stay open
658
- // for its full timeout with nobody left to receive the answer.
659
- // `owner` widens that to every way a turn can end.
660
- { signal: context.signal, timeoutMs, emit, ...(context.questionOwner ? { owner: context.questionOwner } : {}) });
661
- if (!answer) {
662
- if (closedBecause === 'cancelled' || context.signal?.aborted) {
663
- return { text: 'The question was cancelled before anybody answered it.' };
664
- }
665
- const minutes = Math.max(1, Math.round(timeoutMs / 60000));
666
- return {
667
- text: 'No answer within ' + minutes + ' minute' + (minutes === 1 ? '' : 's') + '. Carry on with ' +
668
- 'your own best judgement and say which way you went and why.',
669
- };
670
- }
671
- const chosen = answer.selected
672
- .map((index) => options[index]?.label)
673
- .filter((label) => Boolean(label));
674
- const parts = [];
675
- if (chosen.length)
676
- parts.push('The user chose: ' + chosen.join(', ') + '.');
677
- if (answer.text)
678
- parts.push((chosen.length ? 'They added: ' : 'The user answered: ') + answer.text);
679
- return { text: parts.join('\n') };
680
- }
681
- case 'use_skill': {
682
- // An agent's own instructions carry its project's skills too (Befund
683
- // 4 in the concept doc): the tool must resolve against the running
684
- // assignment's project, not only the one long-lived home store.
685
- const project = context.audience === 'agent' && context.projectId ? this.#store.org.getProject(context.projectId) : null;
686
- const who = context.audience === 'agent' ? 'agent' : 'assistant';
687
- const skills = context.audience === 'agent' ? this.#agentSkills(project) : this.#skills.for('assistant');
688
- // Rookery's own shelf first, then the one installed in Claude Code -
689
- // a skill a person wrote here outranks a plugin's.
690
- const skill = skills.find((entry) => entry.name === text('name').toLowerCase()) ??
691
- openExternalSkill(this.#config, who, text('name'));
692
- if (!skill) {
693
- return fail('No skill "' + text('name') + '". The list in your instructions is authoritative for ' +
694
- "Rookery's own skills; for the ones installed on this machine, search with find_skill first.");
695
- }
696
- // Noted, not just answered. Which run had a skill open is the only
697
- // way the night can later tell a procedure that still holds from one
698
- // that is quietly sending every run that follows it into a wall.
699
- this.#store.recordSkillUse({
700
- skill: skill.name,
701
- owner: context.audience === 'agent' && context.agentId ? context.agentId : ASSISTANT_MEMORY_OWNER,
702
- assignmentId: context.audience === 'agent' ? context.parentAssignmentId : undefined,
703
- sessionId: context.sessionId,
704
- });
705
- return { text: renderSkill(skill) };
706
- }
707
- case 'find_skill': {
708
- const who = context.audience === 'agent' ? 'agent' : 'assistant';
709
- const hits = findExternalSkills(this.#config, who, text('query'));
710
- return { text: renderSkillHits(hits) };
711
- }
712
- case 'write_skill': {
713
- // A scheduled run has a person's trust but not a person present:
714
- // what it writes down would echo its own job prompt, and nothing
715
- // standing behind it would ever be read by anyone. It says so and
716
- // carries on without the skill.
717
- if (context.scheduled) {
718
- return fail('This run was started by a schedule. Automated runs leave no memories and write no ' +
719
- 'skills - if this procedure matters, ask for it in a conversation or write it yourself.');
720
- }
721
- // Always the home store, never the project one: a skill written in
722
- // the middle of an assignment must not land in somebody's repository.
723
- const audience = args.audience === 'assistant' || args.audience === 'agents' || args.audience === 'both'
724
- ? args.audience
725
- : 'both';
726
- try {
727
- // Keep the previous wording before replacing it. Revising a skill
728
- // is the point of this tool, and a revision that turns out worse
729
- // than what it replaced has to leave a way back.
730
- const name = skillSlug(text('name'));
731
- this.#store.snapshotSkill({ skill: name, content: this.#skills.raw(name) });
732
- const skill = this.#skills.save({
733
- name: text('name'),
734
- description: text('description'),
735
- body: text('body'),
736
- audience,
737
- origin: 'agent',
738
- });
739
- this.emit('changed', { kind: 'skill', id: skill.name });
740
- return {
741
- text: 'Skill "' + skill.name + '" written to ' + skill.path + '. It is in the index from ' +
742
- 'the next turn on; open it with use_skill.',
743
- };
744
- }
745
- catch (cause) {
746
- return fail(cause.message);
747
- }
748
- }
749
- case 'project_mcp_servers': {
750
- if (context.audience !== 'assistant')
751
- return fail('Only the assistant reviews project MCP servers.');
752
- const project = this.#store.org.findProject(context.orgId, text('project'));
753
- if (!project)
754
- return fail('No project "' + text('project') + '".');
755
- if (!project.path)
756
- return fail('Project "' + project.name + '" has no directory.');
757
- const file = readProjectMcpFile(project.path);
758
- if (!file || !file.servers.length)
759
- return { text: "No MCP servers in this project's .mcp.json." };
760
- const status = projectMcpStatus(file, project.mcpTrust);
761
- return {
762
- text: 'Status: ' + status + '.\n' +
763
- renderProjectMcpServers(file.servers) +
764
- (status === 'trusted' ? '' : '\nUse trust_project_mcp to approve before these start for a run.'),
765
- };
766
- }
767
- case 'trust_project_mcp': {
768
- if (context.audience !== 'assistant')
769
- return fail('Only the assistant decides project trust.');
770
- const project = this.#store.org.findProject(context.orgId, text('project'));
771
- if (!project)
772
- return fail('No project "' + text('project') + '".');
773
- const decision = text('decision');
774
- if (decision !== 'approve' && decision !== 'revoke')
775
- return fail('decision must be approve or revoke.');
776
- if (decision === 'revoke') {
777
- this.#store.org.updateProject(project.id, { mcpTrust: null });
778
- this.emit('changed', { kind: 'project', id: project.id });
779
- return { text: 'Revoked trust for "' + project.name + '"; its MCP servers no longer start for its runs.' };
780
- }
781
- if (!project.path)
782
- return fail('Project "' + project.name + '" has no directory.');
783
- const file = readProjectMcpFile(project.path);
784
- if (!file || !file.servers.length)
785
- return fail("No MCP servers in this project's .mcp.json.");
786
- this.#store.org.updateProject(project.id, {
787
- mcpTrust: { fingerprint: fingerprintMcpFile(file.raw), approvedAt: Date.now() },
788
- });
789
- this.emit('changed', { kind: 'project', id: project.id });
790
- return {
791
- text: 'Trusted "' + project.name + '": ' + file.servers.length +
792
- ' MCP server(s) start for its runs from now on.',
793
- };
794
- }
358
+ return this.#toolAskRequester(context, args.text('question'));
359
+ case 'answer_task':
360
+ return this.#toolAnswerTask(context, args);
361
+ case 'report_to_user':
362
+ return this.#toolReportToUser(context, args);
363
+ case 'task_activity':
364
+ return this.#toolTaskActivity(context, args);
365
+ case 'notify':
366
+ return this.#toolNotify(context, args);
367
+ case 'ask_user':
368
+ return this.#toolAskUser(context, args);
369
+ case 'use_skill':
370
+ return this.#toolUseSkill(context, args);
371
+ case 'find_skill':
372
+ return { text: renderSkillHits(findExternalSkills(this.#config, callerKind(context), args.text('query'))) };
373
+ case 'write_skill':
374
+ return this.#toolWriteSkill(context, args);
375
+ case 'project_mcp_servers':
376
+ return this.#toolProjectMcpServers(context, args);
377
+ case 'trust_project_mcp':
378
+ return this.#toolTrustProjectMcp(context, args);
795
379
  case 'tool_servers':
796
380
  if (context.audience !== 'assistant')
797
- return fail('Only the assistant sees the hub.');
381
+ return toolError('Only the assistant sees the hub.');
798
382
  return { text: renderToolServers(toolServerStates(this.#config)) };
799
- case 'set_tool_server': {
800
- if (context.audience !== 'assistant')
801
- return fail('Only the assistant can switch tools.');
802
- const state = toolServerStates(this.#config).find((entry) => entry.id === text('id'));
803
- if (!state)
804
- return fail('No tool server "' + text('id') + '".');
805
- if (typeof args.enabled !== 'boolean')
806
- return fail('enabled must be true or false.');
807
- // A server read out of Claude Code belongs to somebody else's
808
- // installation. Starting it is the user's call, made on the Tools page.
809
- if (state.approvalRequired) {
810
- return fail(state.name + ' comes from ' + (state.source || 'another installation') + ' and only the user can ' +
811
- 'switch it on, on the Tools page. Say that you need it and why.');
812
- }
813
- if (args.enabled && !state.installed)
814
- return fail(state.name + ' is not installed on this machine.');
815
- if (args.enabled && state.missingEnv.length) {
816
- return fail(state.name + ' needs ' + state.missingEnv.join(', ') + ' first; the user sets that on the Tools page.');
817
- }
818
- const audience = text('audience');
819
- applyConfig(this.#config, withToolServer(this.#config, state.id, {
820
- enabled: args.enabled,
821
- ...(audience === 'assistant' || audience === 'agents' || audience === 'both' ? { audience } : {}),
822
- }));
823
- this.emit('changed', { kind: 'tools', id: state.id });
824
- return {
825
- text: state.name + ' is now ' + (args.enabled ? 'on' : 'off') + ' for ' + (audience || state.audience) + '. ' +
826
- (args.enabled
827
- ? 'Finish this answer and it is attached; the turn then carries on and you can use it.'
828
- : 'It is gone from the next turn on.'),
829
- };
830
- }
831
- case 'hire_agent': {
832
- if (context.audience !== 'assistant')
833
- return fail('Only the assistant can hire.');
834
- const replaces = text('replaces') ? this.#store.org.findAgent(context.orgId, text('replaces')) : null;
835
- if (text('replaces') && !replaces)
836
- return fail('No agent "' + text('replaces') + '" to replace.');
837
- if (replaces) {
838
- // Stage 4 (docs/concepts/agent-performance-management.md, section
839
- // 4): archiving, the handover and the hire happen together in
840
- // #replaceAgent, never as three separate steps a half-finished
841
- // call could leave inconsistent.
842
- if (!text('name') || !text('title') || !text('instructions')) {
843
- return fail('Replacing an agent still needs a name, a title and instructions for the successor.');
844
- }
845
- if (text('name').trim().toLowerCase() === replaces.name.trim().toLowerCase()) {
846
- return fail('The successor needs a different name from ' + replaces.name + " - decision E4: a new identity, not a reused one.");
847
- }
848
- const successor = await this.replaceAgent(context.orgId, replaces.id, {
849
- name: text('name'),
850
- slug: text('slug') || undefined,
851
- title: text('title'),
852
- instructions: text('instructions'),
853
- voice: text('voice') || undefined,
854
- handover: text('handover') || undefined,
855
- }, this.#asProvider(text('provider')) ?? replaces.provider);
856
- return {
857
- text: 'Archived ' + replaces.name + ' (' + replaces.slug + ') and hired ' + successor.name + ' as ' +
858
- successor.title + ' (slug: ' + successor.slug + ') in their place.',
859
- };
860
- }
861
- const team = text('team') ? this.#store.org.findTeam(context.orgId, text('team')) : null;
862
- if (text('team') && !team)
863
- return fail('No team "' + text('team') + '". Create it first.');
864
- const manager = text('manager') ? this.#store.org.findAgent(context.orgId, text('manager')) : null;
865
- if (text('manager') && !manager)
866
- return fail('No agent "' + text('manager') + '" to report to.');
867
- const agent = this.#store.org.createAgent({
868
- orgId: context.orgId,
869
- slug: text('slug') || undefined,
870
- name: text('name'),
871
- title: text('title'),
872
- instructions: text('instructions'),
873
- voice: text('voice') || undefined,
874
- teamId: team?.id,
875
- managerId: manager?.id,
876
- provider: this.#asProvider(text('provider')),
877
- model: text('model') || undefined,
878
- permission: asPermission(text('permission')),
879
- });
880
- this.emit('changed', { kind: 'agent', id: agent.id });
881
- return { text: 'Hired ' + agent.name + ' as ' + agent.title + ' (slug: ' + agent.slug + ').' };
882
- }
883
- case 'create_team': {
884
- if (context.audience !== 'assistant')
885
- return fail('Only the assistant can create teams.');
886
- const lead = text('lead') ? this.#store.org.findAgent(context.orgId, text('lead')) : null;
887
- if (text('lead') && !lead)
888
- return fail('No agent "' + text('lead') + '" to lead the team.');
889
- const team = this.#store.org.createTeam({
890
- orgId: context.orgId,
891
- name: text('name'),
892
- purpose: text('purpose') || undefined,
893
- leadId: lead?.id,
894
- });
895
- this.emit('changed', { kind: 'team', id: team.id });
896
- return { text: 'Created team "' + team.name + '" (id: ' + team.id + ').' };
897
- }
898
- case 'create_project': {
899
- if (context.audience !== 'assistant')
900
- return fail('Only the assistant can create projects.');
901
- const path = text('path') || undefined;
902
- if (path && !existsSync(path))
903
- return fail('The directory ' + path + ' does not exist.');
904
- const project = this.#store.org.createProject({
905
- orgId: context.orgId,
906
- name: text('name'),
907
- description: text('description') || undefined,
908
- path,
909
- });
910
- this.emit('changed', { kind: 'project', id: project.id });
911
- return { text: 'Created project "' + project.name + '" (id: ' + project.id + ').' };
912
- }
383
+ case 'set_tool_server':
384
+ return this.#toolSetToolServer(context, args);
385
+ case 'hire_agent':
386
+ return this.#toolHireAgent(context, args);
387
+ case 'create_team':
388
+ return this.#toolCreateTeam(context, args);
389
+ case 'create_project':
390
+ return this.#toolCreateProject(context, args);
913
391
  case 'update_agent':
914
- return this.#updateAgent(context, args);
392
+ return this.#toolUpdateAgent(context, args);
915
393
  case 'update_team':
916
- return this.#updateTeam(context, args);
917
- case 'create_task': {
918
- if (!text('title') || !text('description'))
919
- return fail('A task needs a title and a description.');
920
- const project = text('project') ? this.#store.org.findProject(context.orgId, text('project')) : null;
921
- if (text('project') && !project)
922
- return fail('No project "' + text('project') + '".');
923
- const assignee = text('assignee') ? this.#store.org.findAgent(context.orgId, text('assignee')) : null;
924
- if (text('assignee') && !assignee)
925
- return fail('No agent "' + text('assignee') + '".');
926
- const task = this.#store.org.createTask({
927
- orgId: context.orgId,
928
- title: text('title'),
929
- description: text('description'),
930
- projectId: project?.id ?? context.projectId,
931
- priority: asPriority(text('priority')),
932
- assigneeId: assignee?.id,
933
- createdBy: context.audience === 'agent' ? 'agent' : 'assistant',
934
- createdByAgentId: context.agentId,
935
- // Whenever it runs, the conversation that asked for it hears how it
936
- // ended. Inside a task there is a parent to report to instead.
937
- requesterSessionId: context.taskId ? undefined : context.sessionId,
938
- });
939
- // The card opens its own activity with the brief (`createTask`), so
940
- // there is nothing more to write before anybody presses start.
941
- this.#announceTask(task, context.emit);
942
- return { text: 'Task ' + task.id.slice(0, 8) + ' "' + task.title + '" is on the board.' };
943
- }
944
- case 'list_tasks': {
945
- const wanted = text('status').split(',').map((v) => v.trim()).filter(Boolean);
946
- // Without a filter this is the board, and the board is its top row.
947
- // With one it is a search, and delegated work sits under a parent
948
- // (decision E9) - a blocked subtask under a finished parent is
949
- // exactly what the board watcher is woken for.
950
- const tasks = this.#store.org.listTasks(context.orgId, wanted.length ? { status: wanted, anyLevel: true } : {});
951
- return { text: renderBoard(tasks, this.snapshot(context.orgId), this.#store.org) };
952
- }
394
+ return this.#toolUpdateTeam(context, args);
395
+ case 'create_task':
396
+ return this.#toolCreateTask(context, args);
397
+ case 'list_tasks':
398
+ return this.#toolListTasks(context, args);
953
399
  case 'update_task':
954
- return this.#updateTask(context, args);
955
- case 'plan_task': {
956
- const task = this.findTask(context.orgId, text('id'));
957
- if (!task)
958
- return fail('No task ' + text('id') + '.');
959
- const plan = await this.planTask(context, task, text('hint') || undefined);
960
- return { text: describePlan(plan, this.#store.org.listTasks(context.orgId, { parentId: task.id })) };
961
- }
962
- case 'run_task': {
963
- const task = this.findTask(context.orgId, text('id'));
964
- if (!task)
965
- return fail('No task ' + text('id') + '.');
966
- const finished = await this.#runAwaited(context, task);
967
- if (finished.status === 'blocked')
968
- return { text: this.#waitingText(finished) };
969
- if (finished.status !== 'done') {
970
- return fail('Task "' + finished.title + '" ' + finished.status + (finished.error ? ': ' + finished.error : '.'));
971
- }
972
- return { text: 'Task "' + finished.title + '" is done.\n\n' + clip(finished.result ?? '', RESULT_BUDGET) };
973
- }
400
+ return this.#toolUpdateTask(context, args);
401
+ case 'plan_task':
402
+ return this.#toolPlanTask(context, args);
403
+ case 'run_task':
404
+ return this.#toolRunTask(context, args);
974
405
  case 'list_schedules':
975
406
  case 'create_schedule':
976
407
  case 'update_schedule':
977
408
  case 'delete_schedule':
978
409
  case 'run_schedule':
979
410
  case 'set_webhook':
980
- return this.#schedules(context, name, args);
411
+ return this.#toolSchedules(context, name, args);
981
412
  case 'list_listeners':
982
413
  case 'set_listener':
983
414
  case 'remove_listener':
984
- return this.#listeners(context, name, args);
415
+ return this.#toolListeners(context, name, args);
985
416
  default:
986
- return fail('Unknown tool ' + name + '.');
417
+ return toolError('Unknown tool ' + name + '.');
418
+ }
419
+ }
420
+ #toolAssignmentStatus(context, args) {
421
+ const assignment = this.findAssignment(context.orgId, args.text('id'));
422
+ if (!assignment)
423
+ return toolError(NO_SUCH_RUN);
424
+ return {
425
+ text: describeAssignment(assignment, this.#store.org.getAgent(assignment.agentId), this.#store.org.taskRunNumber(assignment.id)),
426
+ };
427
+ }
428
+ #toolReviewAssignment(context, args) {
429
+ if (context.audience !== 'assistant')
430
+ return toolError('Only the assistant records reviews.');
431
+ const assignment = this.findAssignment(context.orgId, args.text('id'));
432
+ if (!assignment)
433
+ return toolError(NO_SUCH_RUN);
434
+ const review = this.#store.org.upsertReview({
435
+ orgId: context.orgId,
436
+ agentId: assignment.agentId,
437
+ assignmentId: assignment.id,
438
+ taskId: this.#store.org.getTaskIdForAssignment(assignment.id) ?? undefined,
439
+ source: 'assistant',
440
+ overall: args.number('overall', 1, 5, 3),
441
+ comment: args.text('comment') || undefined,
442
+ });
443
+ this.emit('changed', { kind: 'agent', id: assignment.agentId });
444
+ return { text: 'Review recorded (overall ' + review.overall + ').' };
445
+ }
446
+ #toolAgentPerformance(context, args) {
447
+ if (context.audience !== 'assistant')
448
+ return toolError('Only the assistant sees the personnel record.');
449
+ const agent = this.#store.org.findAgent(context.orgId, args.text('agent'));
450
+ if (!agent)
451
+ return toolError(noAgent(args.text('agent')));
452
+ return { text: describeAgentPerformance(agent, this.#store.org) };
453
+ }
454
+ #toolCancelAssignment(context, args) {
455
+ if (context.audience !== 'assistant')
456
+ return toolError('Only the assistant can call off a running task.');
457
+ const assignment = this.findAssignment(context.orgId, args.text('id'));
458
+ if (!assignment)
459
+ return toolError(NO_SUCH_RUN);
460
+ if (!this.cancel(assignment.id, 'the assistant')) {
461
+ return toolError('Run ' + shortId(assignment.id) + ' is not running; it is ' + assignment.status + '.');
462
+ }
463
+ return { text: 'Calling off run ' + shortId(assignment.id) + '. It ends as cancelled within a moment.' };
464
+ }
465
+ #toolListAssignments(context, args) {
466
+ if (context.audience !== 'assistant')
467
+ return toolError('Only the assistant can read the history.');
468
+ const org = this.#store.org;
469
+ const agent = resolveOptional(args.text('agent'), (ref) => org.findAgent(context.orgId, ref), noAgent);
470
+ if (!agent.ok)
471
+ return agent.error;
472
+ const project = resolveOptional(args.text('project'), (ref) => org.findProject(context.orgId, ref), noProject);
473
+ if (!project.ok)
474
+ return project.error;
475
+ const wanted = args.list('status');
476
+ const limit = args.number('limit', 1, 200, 20);
477
+ // The store cannot filter by project, so a project filter scans further
478
+ // back and cuts afterwards.
479
+ const rows = org
480
+ .listAssignments(context.orgId, {
481
+ agentId: agent.value?.id,
482
+ status: wanted.length ? wanted : undefined,
483
+ limit: project.value ? LOOKUP_SCAN_LIMIT : limit,
484
+ })
485
+ .filter((entry) => !project.value || entry.projectId === project.value.id)
486
+ .slice(0, limit);
487
+ if (!rows.length)
488
+ return { text: 'No runs match.' };
489
+ const slugs = new Map(org.listAgents(context.orgId, { includeArchived: true }).map((entry) => [entry.id, entry.slug]));
490
+ return { text: rows.map((entry) => this.#assignmentListLine(entry, slugs.get(entry.agentId) ?? '?')).join('\n') };
491
+ }
492
+ #assignmentListLine(entry, agentSlug) {
493
+ // Local wall clock, and for anything still going the elapsed
494
+ // span as well: "has this run too long" is the question the
495
+ // board watcher asks, and a span cannot be read in the wrong
496
+ // timezone the way a stamp can.
497
+ const took = entry.durationMs
498
+ ? ' ' + toSeconds(entry.durationMs) + 's'
499
+ : entry.status === 'running'
500
+ ? ' running ' + formatAge(entry.createdAt)
501
+ : '';
502
+ // The name, never the brief: three runs of the same errand open
503
+ // with the same twenty words, and a list of those tells nobody
504
+ // which is which (concept 7.1).
505
+ const run = this.#store.org.taskRunNumber(entry.id);
506
+ return '- ' + shortId(entry.id) + ' ' + formatWhen(entry.createdAt) + ' ' + entry.status + took + ' ' + agentSlug + ': ' +
507
+ shorten(entry.title, 100) + (run && run > 1 ? ' (run ' + run + ')' : '') +
508
+ (entry.error ? ' [' + shorten(entry.error, 60) + ']' : '');
509
+ }
510
+ #toolUpdateProject(context, args) {
511
+ if (context.audience !== 'assistant')
512
+ return toolError('Only the assistant can change projects.');
513
+ const project = this.#store.org.findProject(context.orgId, args.text('project'));
514
+ if (!project)
515
+ return toolError(noProject(args.text('project')));
516
+ const patch = {};
517
+ if (args.text('name'))
518
+ patch.name = args.text('name');
519
+ if (args.text('description'))
520
+ patch.description = args.text('description');
521
+ const path = args.text('path');
522
+ if (path) {
523
+ if (path.toLowerCase() === 'none')
524
+ patch.path = null;
525
+ else if (!existsSync(path))
526
+ return toolError('The directory ' + path + ' does not exist.');
527
+ else
528
+ patch.path = path;
529
+ }
530
+ const archived = args.flag('archived');
531
+ if (archived !== undefined)
532
+ patch.archived = archived;
533
+ if (!Object.keys(patch).length)
534
+ return toolError('Nothing to change.');
535
+ this.#store.org.updateProject(project.id, patch);
536
+ this.emit('changed', { kind: 'project', id: project.id });
537
+ return { text: 'Updated project "' + (patch.name ?? project.name) + '": ' + Object.keys(patch).join(', ') + '.' };
538
+ }
539
+ #toolSleepNow(context) {
540
+ if (context.audience !== 'assistant')
541
+ return toolError('Only the assistant has this memory.');
542
+ if (!this.#sleep)
543
+ return toolError('The nightly memory run is not available here.');
544
+ if (this.#sleep.isRunning(ASSISTANT_MEMORY_OWNER))
545
+ return { text: 'The memory is already asleep.' };
546
+ // Started, not awaited: a night takes minutes and the turn must not
547
+ // sit and wait for it. The memory page follows it live.
548
+ void this.#sleep.run({ owner: ASSISTANT_MEMORY_OWNER, trigger: 'manual' });
549
+ return {
550
+ text: 'The memory is going to sleep now. It condenses, files and connects; nothing is deleted, ' +
551
+ 'and the run can be undone on the memory page.',
552
+ };
553
+ }
554
+ #toolReadProfile(context, args) {
555
+ if (context.audience !== 'assistant')
556
+ return toolError('Only the assistant has this profile.');
557
+ const offset = args.has('offset') ? Number(args.raw('offset')) : 0;
558
+ const limit = args.has('limit') ? Number(args.raw('limit')) : PROFILE_EXCERPT_CHARS;
559
+ return { text: readProfileExcerpt(this.#config, args.text('name'), offset, limit) };
560
+ }
561
+ #toolSearchProfile(context, args) {
562
+ if (context.audience !== 'assistant')
563
+ return toolError('Only the assistant has this profile.');
564
+ return { text: searchProfile(this.#config, args.text('query')) };
565
+ }
566
+ #toolRemember(context, args) {
567
+ // The assistant keeps facts about the user; an agent keeps facts
568
+ // about its own work. Either way the write lands in the caller's own
569
+ // bank and nowhere else - there is no path here that writes across
570
+ // the owner boundary.
571
+ const owner = memoryOwnerOf(context);
572
+ // Same rule as write_skill below: a scheduled run has nobody present
573
+ // to confirm anything, and a memory it pinned would even carry
574
+ // origin 'user' - protected from the very night that should weigh it.
575
+ if (context.scheduled) {
576
+ return toolError('This run was started by a schedule. Automated runs leave no memories - if this ' +
577
+ 'belongs in memory, bring it up in a conversation.');
578
+ }
579
+ if (!args.text('content'))
580
+ return toolError('A memory needs content.');
581
+ const tags = args.list('tags');
582
+ const record = this.#store.upsertMemory({
583
+ kind: asMemoryKind(args.text('kind')),
584
+ content: args.text('content'),
585
+ tags,
586
+ importance: args.number('importance', 0, 1, 0.7),
587
+ owner,
588
+ sourceSessionId: context.sessionId,
589
+ // Asked for explicitly, so the night never merges it away.
590
+ origin: 'user',
591
+ });
592
+ linkEntities(this.#store, owner, record.id, tags);
593
+ this.emit('changed', { kind: 'memory', id: record.id });
594
+ return { text: 'Remembered (' + shortId(record.id) + '): ' + record.content };
595
+ }
596
+ #toolForget(context, args) {
597
+ if (context.audience !== 'assistant')
598
+ return toolError('Only the assistant has this memory.');
599
+ // Forgetting is a deletion, and E1 of the memory concept says a
600
+ // deletion happens only on the user's explicit word - a schedule has
601
+ // nobody behind it to give that word.
602
+ if (context.scheduled) {
603
+ return toolError('This run was started by a schedule. Nothing is forgotten on an automated run - ask ' +
604
+ 'in a conversation instead.');
605
+ }
606
+ const ref = args.text('id');
607
+ if (!ref)
608
+ return toolError('Which memory? Give its id.');
609
+ const record = this.#store.getMemory(ref) ??
610
+ this.#store
611
+ .listMemories({ owner: ASSISTANT_MEMORY_OWNER, limit: MEMORY_PREFIX_SCAN_LIMIT })
612
+ .find((memory) => memory.id.startsWith(ref));
613
+ if (!record || record.owner !== ASSISTANT_MEMORY_OWNER)
614
+ return toolError('No memory ' + ref + '.');
615
+ this.#store.forgetMemory(record.id);
616
+ this.emit('changed', { kind: 'memory', id: record.id });
617
+ return { text: 'Forgotten: ' + record.content };
618
+ }
619
+ #toolSearchMemory(context, args) {
620
+ // Read-only, and strictly inside the caller's own bank: the
621
+ // assistant searches what it knows about the user, an agent searches
622
+ // its own working memory. One owner in, one owner out.
623
+ const owner = memoryOwnerOf(context);
624
+ const limit = args.number('limit', 1, 100, 20);
625
+ const query = args.text('query');
626
+ const rows = query
627
+ ? recall(this.#store, { text: query, limit, owner, touch: false })
628
+ : this.#store.listMemories({ owner, limit });
629
+ if (!rows.length)
630
+ return { text: query ? 'Nothing in memory matches.' : 'Memory is empty.' };
631
+ return {
632
+ text: rows
633
+ .map((memory) => '- ' + shortId(memory.id) + ' [' + memory.kind + ', ' + memory.importance.toFixed(2) + '] ' + memory.content)
634
+ .join('\n'),
635
+ };
636
+ }
637
+ async #toolAnswerTask(context, args) {
638
+ const task = this.findTask(context.orgId, args.text('id'));
639
+ if (!task)
640
+ return toolError('No task ' + args.text('id') + '.');
641
+ const answerer = context.audience === 'agent' ? { kind: 'agent', agentId: context.agentId } : { kind: 'assistant' };
642
+ const answered = await this.#answer(task, args.text('answer'), answerer, context);
643
+ if (!answered.ok)
644
+ return toolError(answered.reason);
645
+ const where = context.taskId && task.parentId === context.taskId
646
+ ? 'Your own task stays open until it is back: when your run ends, you are started again with its result.'
647
+ : task.requesterSessionId && !task.parentId
648
+ ? 'When it ends, a message arrives in the conversation it came from.'
649
+ : 'How it ends is recorded on its card.';
650
+ return {
651
+ text: 'Answered task ' + shortId(task.id) + ' "' + task.title + '"; it runs again with your answer. ' + where,
652
+ };
653
+ }
654
+ #toolReportToUser(context, args) {
655
+ // Agents, and the one assistant run that has no conversation to speak
656
+ // in: the board watcher. An ordinary assistant turn answers the user
657
+ // directly, and `notify` is its line for what cannot wait.
658
+ if (context.audience !== 'agent' && !context.watching) {
659
+ return toolError('Reach the user through your answer, or with notify for something that has to arrive now.');
660
+ }
661
+ if (!args.text('title') || !args.text('body'))
662
+ return toolError('A report needs a title and a body.');
663
+ const isAgent = context.audience === 'agent';
664
+ const notification = this.notifyUser({
665
+ orgId: context.orgId,
666
+ kind: context.watching ? 'watch' : 'agent',
667
+ title: args.text('title'),
668
+ body: args.text('body'),
669
+ fromKind: callerKind(context),
670
+ fromAgentId: isAgent ? context.agentId : undefined,
671
+ taskId: context.taskId,
672
+ // The watcher's own run is where a reply to its report continues;
673
+ // an agent's run has no conversation of its own to point at.
674
+ sessionId: context.watching ? context.sessionId : undefined,
675
+ });
676
+ if (context.taskId && this.#store.org.getTask(context.taskId)) {
677
+ this.#taskEvent({
678
+ taskId: context.taskId,
679
+ kind: 'note',
680
+ actorKind: callerKind(context),
681
+ actorAgentId: context.agentId,
682
+ text: 'Reported to the user: ' + notification.title + '\n\n' + notification.body,
683
+ assignmentId: context.parentAssignmentId,
684
+ });
685
+ }
686
+ return { text: 'Left the user a notification: "' + notification.title + '".' };
687
+ }
688
+ #toolTaskActivity(context, args) {
689
+ const task = this.findTask(context.orgId, args.text('id'));
690
+ if (!task)
691
+ return toolError('No task ' + args.text('id') + '.');
692
+ return {
693
+ text: clip(renderTaskActivity(task, this.#store.org.listTaskEvents(task.id), this.snapshot(context.orgId)), RESULT_BUDGET),
694
+ };
695
+ }
696
+ #toolNotify(context, args) {
697
+ if (context.audience !== 'assistant')
698
+ return toolError('Only the assistant can send notifications.');
699
+ const text = args.text('text');
700
+ if (!text)
701
+ return toolError('A notification needs text.');
702
+ const urgency = args.raw('urgency') === 'high' ? 'high' : 'normal';
703
+ // Kept as well as pushed: a push is gone once it is swiped away, and
704
+ // the web should be able to show what the assistant said on its own.
705
+ // The push itself still travels on the `notify` event - the
706
+ // notification is the record, so a channel must not push it twice.
707
+ this.notifyUser({
708
+ orgId: context.orgId,
709
+ kind: 'system',
710
+ title: shorten(text.split('\n', 1)[0] ?? '', 80),
711
+ body: text,
712
+ fromKind: 'assistant',
713
+ sessionId: context.sessionId,
714
+ });
715
+ if (!this.#canNotify || !this.#canNotify()) {
716
+ return {
717
+ text: 'No push channel can reach the user right now - none is set up, it is switched off, or it has ' +
718
+ 'no recipient. The message is saved in their notifications and waits there.',
719
+ };
720
+ }
721
+ const event = { text, urgency, at: Date.now() };
722
+ this.emit('notify', event);
723
+ return { text: 'Sent' + (urgency === 'high' ? ' (high urgency)' : '') + ': ' + event.text };
724
+ }
725
+ async #toolAskUser(context, args) {
726
+ // Only the assistant asks. An agent runs unattended by design and
727
+ // asks whoever gave it the work (`ask_requester`); letting one block
728
+ // on a person would stall a whole delegation chain behind them.
729
+ if (context.audience !== 'assistant') {
730
+ return toolError('Only the assistant can ask the user. Inside a task, ask whoever gave you the work with ' +
731
+ 'ask_requester; otherwise say what you need in your result.');
732
+ }
733
+ // Belt and braces: a scheduled run is not offered the tool at all
734
+ // (see `register`), so getting here means the list was built for a
735
+ // conversation and the run turned out to be automated.
736
+ if (context.scheduled) {
737
+ return toolError('This run was started by a schedule and nobody is there to answer. Decide it yourself ' +
738
+ 'and say in your result what you assumed.');
739
+ }
740
+ if (!this.#questions)
741
+ return toolError('Asking the user is not available here.');
742
+ const question = args.text('question');
743
+ if (!question)
744
+ return toolError('A question needs its text.');
745
+ const options = asQuestionOptions(args.raw('options'));
746
+ if (options.length < MIN_QUESTION_OPTIONS)
747
+ return toolError('Offer at least two options to choose from.');
748
+ if (options.length > MAX_QUESTION_OPTIONS)
749
+ return toolError('Offer at most four options; more does not fit a phone.');
750
+ const timeoutMs = this.#config.questions.timeoutMs;
751
+ // The close event carries why it closed, and the turn wants to know:
752
+ // "nobody was there" and "somebody waved it away" are different
753
+ // things to carry on from.
754
+ let closedBecause;
755
+ const emit = (event) => {
756
+ if (event.type === 'question-closed')
757
+ closedBecause = event.reason;
758
+ context.emit(event);
759
+ };
760
+ const answer = await this.#questions.ask({
761
+ header: args.text('header') || 'Question',
762
+ question,
763
+ options,
764
+ multiSelect: args.raw('multiSelect') === true,
765
+ sessionId: context.sessionId,
766
+ },
767
+ // `emit` puts the card on the asking turn's own stream; `signal` is
768
+ // the half no other tool handler has: an aborted turn kills the
769
+ // provider process, and without this the question would stay open
770
+ // for its full timeout with nobody left to receive the answer.
771
+ // `owner` widens that to every way a turn can end.
772
+ { signal: context.signal, timeoutMs, emit, ...(context.questionOwner ? { owner: context.questionOwner } : {}) });
773
+ if (!answer) {
774
+ const cancelled = closedBecause === 'cancelled' || context.signal?.aborted;
775
+ return { text: cancelled ? 'The question was cancelled before anybody answered it.' : noAnswerText(timeoutMs) };
776
+ }
777
+ return { text: answerText(answer, options) };
778
+ }
779
+ #toolUseSkill(context, args) {
780
+ // An agent's own instructions carry its project's skills too (Befund
781
+ // 4 in the concept doc): the tool must resolve against the running
782
+ // assignment's project, not only the one long-lived home store.
783
+ const isAgent = context.audience === 'agent';
784
+ const project = isAgent && context.projectId ? this.#store.org.getProject(context.projectId) : null;
785
+ const skills = isAgent ? this.#agentSkills(project) : this.#skills.for('assistant');
786
+ const name = args.text('name');
787
+ // Rookery's own shelf first, then the one installed in Claude Code -
788
+ // a skill a person wrote here outranks a plugin's.
789
+ const skill = skills.find((entry) => entry.name === name.toLowerCase()) ?? openExternalSkill(this.#config, callerKind(context), name);
790
+ if (!skill) {
791
+ return toolError('No skill "' + name + '". The list in your instructions is authoritative for ' +
792
+ "Rookery's own skills; for the ones installed on this machine, search with find_skill first.");
793
+ }
794
+ // Noted, not just answered. Which run had a skill open is the only
795
+ // way the night can later tell a procedure that still holds from one
796
+ // that is quietly sending every run that follows it into a wall.
797
+ this.#store.recordSkillUse({
798
+ skill: skill.name,
799
+ owner: memoryOwnerOf(context),
800
+ assignmentId: isAgent ? context.parentAssignmentId : undefined,
801
+ sessionId: context.sessionId,
802
+ });
803
+ return { text: renderSkill(skill) };
804
+ }
805
+ #toolWriteSkill(context, args) {
806
+ // A scheduled run has a person's trust but not a person present:
807
+ // what it writes down would echo its own job prompt, and nothing
808
+ // standing behind it would ever be read by anyone. It says so and
809
+ // carries on without the skill.
810
+ if (context.scheduled) {
811
+ return toolError('This run was started by a schedule. Automated runs leave no memories and write no ' +
812
+ 'skills - if this procedure matters, ask for it in a conversation or write it yourself.');
813
+ }
814
+ // Always the home store, never the project one: a skill written in
815
+ // the middle of an assignment must not land in somebody's repository.
816
+ const audience = asServerAudience(args.raw('audience')) ?? 'both';
817
+ try {
818
+ // Keep the previous wording before replacing it. Revising a skill
819
+ // is the point of this tool, and a revision that turns out worse
820
+ // than what it replaced has to leave a way back.
821
+ const name = skillSlug(args.text('name'));
822
+ this.#store.snapshotSkill({ skill: name, content: this.#skills.raw(name) });
823
+ const skill = this.#skills.save({
824
+ name: args.text('name'),
825
+ description: args.text('description'),
826
+ body: args.text('body'),
827
+ audience,
828
+ origin: 'agent',
829
+ });
830
+ this.emit('changed', { kind: 'skill', id: skill.name });
831
+ return {
832
+ text: 'Skill "' + skill.name + '" written to ' + skill.path + '. It is in the index from ' +
833
+ 'the next turn on; open it with use_skill.',
834
+ };
987
835
  }
836
+ catch (cause) {
837
+ return toolError(cause.message);
838
+ }
839
+ }
840
+ #toolProjectMcpServers(context, args) {
841
+ if (context.audience !== 'assistant')
842
+ return toolError('Only the assistant reviews project MCP servers.');
843
+ const project = this.#store.org.findProject(context.orgId, args.text('project'));
844
+ if (!project)
845
+ return toolError(noProject(args.text('project')));
846
+ if (!project.path)
847
+ return toolError('Project "' + project.name + '" has no directory.');
848
+ const file = readProjectMcpFile(project.path);
849
+ if (!file || !file.servers.length)
850
+ return { text: NO_PROJECT_MCP_SERVERS };
851
+ const status = projectMcpStatus(file, project.mcpTrust);
852
+ return {
853
+ text: 'Status: ' + status + '.\n' +
854
+ renderProjectMcpServers(file.servers) +
855
+ (status === 'trusted' ? '' : '\nUse trust_project_mcp to approve before these start for a run.'),
856
+ };
857
+ }
858
+ #toolTrustProjectMcp(context, args) {
859
+ if (context.audience !== 'assistant')
860
+ return toolError('Only the assistant decides project trust.');
861
+ const project = this.#store.org.findProject(context.orgId, args.text('project'));
862
+ if (!project)
863
+ return toolError(noProject(args.text('project')));
864
+ const decision = args.text('decision');
865
+ if (decision !== 'approve' && decision !== 'revoke')
866
+ return toolError('decision must be approve or revoke.');
867
+ if (decision === 'revoke') {
868
+ this.#store.org.updateProject(project.id, { mcpTrust: null });
869
+ this.emit('changed', { kind: 'project', id: project.id });
870
+ return { text: 'Revoked trust for "' + project.name + '"; its MCP servers no longer start for its runs.' };
871
+ }
872
+ if (!project.path)
873
+ return toolError('Project "' + project.name + '" has no directory.');
874
+ const file = readProjectMcpFile(project.path);
875
+ if (!file || !file.servers.length)
876
+ return toolError(NO_PROJECT_MCP_SERVERS);
877
+ this.#store.org.updateProject(project.id, {
878
+ mcpTrust: { fingerprint: fingerprintMcpFile(file.raw), approvedAt: Date.now() },
879
+ });
880
+ this.emit('changed', { kind: 'project', id: project.id });
881
+ return {
882
+ text: 'Trusted "' + project.name + '": ' + file.servers.length +
883
+ ' MCP server(s) start for its runs from now on.',
884
+ };
885
+ }
886
+ #toolSetToolServer(context, args) {
887
+ if (context.audience !== 'assistant')
888
+ return toolError('Only the assistant can switch tools.');
889
+ const state = toolServerStates(this.#config).find((entry) => entry.id === args.text('id'));
890
+ if (!state)
891
+ return toolError('No tool server "' + args.text('id') + '".');
892
+ const enabled = args.flag('enabled');
893
+ if (enabled === undefined)
894
+ return toolError('enabled must be true or false.');
895
+ // A server read out of Claude Code belongs to somebody else's
896
+ // installation. Starting it is the user's call, made on the Tools page.
897
+ if (state.approvalRequired) {
898
+ return toolError(state.name + ' comes from ' + (state.source || 'another installation') + ' and only the user can ' +
899
+ 'switch it on, on the Tools page. Say that you need it and why.');
900
+ }
901
+ if (enabled && !state.installed)
902
+ return toolError(state.name + ' is not installed on this machine.');
903
+ if (enabled && state.missingEnv.length) {
904
+ return toolError(state.name + ' needs ' + state.missingEnv.join(', ') + ' first; the user sets that on the Tools page.');
905
+ }
906
+ const audienceText = args.text('audience');
907
+ const audience = asServerAudience(audienceText);
908
+ applyConfig(this.#config, withToolServer(this.#config, state.id, { enabled, ...(audience ? { audience } : {}) }));
909
+ this.emit('changed', { kind: 'tools', id: state.id });
910
+ return {
911
+ text: state.name + ' is now ' + (enabled ? 'on' : 'off') + ' for ' + (audienceText || state.audience) + '. ' +
912
+ (enabled
913
+ ? 'Finish this answer and it is attached; the turn then carries on and you can use it.'
914
+ : 'It is gone from the next turn on.'),
915
+ };
916
+ }
917
+ async #toolHireAgent(context, args) {
918
+ if (context.audience !== 'assistant')
919
+ return toolError('Only the assistant can hire.');
920
+ const org = this.#store.org;
921
+ const replaces = resolveOptional(args.text('replaces'), (ref) => org.findAgent(context.orgId, ref), (ref) => 'No agent "' + ref + '" to replace.');
922
+ if (!replaces.ok)
923
+ return replaces.error;
924
+ // Stage 4 (docs/concepts/agent-performance-management.md, section
925
+ // 4): archiving, the handover and the hire happen together in
926
+ // #replaceAgent, never as three separate steps a half-finished
927
+ // call could leave inconsistent.
928
+ if (replaces.value)
929
+ return this.#replaceAgentViaTool(context, replaces.value, args);
930
+ const team = resolveOptional(args.text('team'), (ref) => org.findTeam(context.orgId, ref), (ref) => 'No team "' + ref + '". Create it first.');
931
+ if (!team.ok)
932
+ return team.error;
933
+ const manager = resolveOptional(args.text('manager'), (ref) => org.findAgent(context.orgId, ref), (ref) => 'No agent "' + ref + '" to report to.');
934
+ if (!manager.ok)
935
+ return manager.error;
936
+ const agent = org.createAgent({
937
+ orgId: context.orgId,
938
+ slug: args.text('slug') || undefined,
939
+ name: args.text('name'),
940
+ title: args.text('title'),
941
+ instructions: args.text('instructions'),
942
+ voice: args.text('voice') || undefined,
943
+ teamId: team.value?.id,
944
+ managerId: manager.value?.id,
945
+ provider: this.#asProvider(args.text('provider')),
946
+ model: args.text('model') || undefined,
947
+ permission: asPermission(args.text('permission')),
948
+ });
949
+ this.emit('changed', { kind: 'agent', id: agent.id });
950
+ return { text: 'Hired ' + agent.name + ' as ' + agent.title + ' (slug: ' + agent.slug + ').' };
951
+ }
952
+ async #replaceAgentViaTool(context, replaces, args) {
953
+ if (!args.text('name') || !args.text('title') || !args.text('instructions')) {
954
+ return toolError('Replacing an agent still needs a name, a title and instructions for the successor.');
955
+ }
956
+ if (args.text('name').toLowerCase() === replaces.name.trim().toLowerCase()) {
957
+ return toolError('The successor needs a different name from ' + replaces.name + " - decision E4: a new identity, not a reused one.");
958
+ }
959
+ const successor = await this.replaceAgent(context.orgId, replaces.id, {
960
+ name: args.text('name'),
961
+ slug: args.text('slug') || undefined,
962
+ title: args.text('title'),
963
+ instructions: args.text('instructions'),
964
+ voice: args.text('voice') || undefined,
965
+ handover: args.text('handover') || undefined,
966
+ }, this.#asProvider(args.text('provider')) ?? replaces.provider);
967
+ return {
968
+ text: 'Archived ' + replaces.name + ' (' + replaces.slug + ') and hired ' + successor.name + ' as ' +
969
+ successor.title + ' (slug: ' + successor.slug + ') in their place.',
970
+ };
971
+ }
972
+ #toolCreateTeam(context, args) {
973
+ if (context.audience !== 'assistant')
974
+ return toolError('Only the assistant can create teams.');
975
+ const lead = resolveOptional(args.text('lead'), (ref) => this.#store.org.findAgent(context.orgId, ref), (ref) => 'No agent "' + ref + '" to lead the team.');
976
+ if (!lead.ok)
977
+ return lead.error;
978
+ const team = this.#store.org.createTeam({
979
+ orgId: context.orgId,
980
+ name: args.text('name'),
981
+ purpose: args.text('purpose') || undefined,
982
+ leadId: lead.value?.id,
983
+ });
984
+ this.emit('changed', { kind: 'team', id: team.id });
985
+ return { text: 'Created team "' + team.name + '" (id: ' + team.id + ').' };
986
+ }
987
+ #toolCreateProject(context, args) {
988
+ if (context.audience !== 'assistant')
989
+ return toolError('Only the assistant can create projects.');
990
+ const path = args.text('path') || undefined;
991
+ if (path && !existsSync(path))
992
+ return toolError('The directory ' + path + ' does not exist.');
993
+ const project = this.#store.org.createProject({
994
+ orgId: context.orgId,
995
+ name: args.text('name'),
996
+ description: args.text('description') || undefined,
997
+ path,
998
+ });
999
+ this.emit('changed', { kind: 'project', id: project.id });
1000
+ return { text: 'Created project "' + project.name + '" (id: ' + project.id + ').' };
1001
+ }
1002
+ #toolCreateTask(context, args) {
1003
+ if (!args.text('title') || !args.text('description'))
1004
+ return toolError('A task needs a title and a description.');
1005
+ const project = resolveOptional(args.text('project'), (ref) => this.#store.org.findProject(context.orgId, ref), noProject);
1006
+ if (!project.ok)
1007
+ return project.error;
1008
+ const assignee = resolveOptional(args.text('assignee'), (ref) => this.#store.org.findAgent(context.orgId, ref), noAgent);
1009
+ if (!assignee.ok)
1010
+ return assignee.error;
1011
+ const task = this.#store.org.createTask({
1012
+ orgId: context.orgId,
1013
+ title: args.text('title'),
1014
+ description: args.text('description'),
1015
+ projectId: project.value?.id ?? context.projectId,
1016
+ priority: asPriority(args.text('priority')),
1017
+ assigneeId: assignee.value?.id,
1018
+ createdBy: callerKind(context),
1019
+ createdByAgentId: context.agentId,
1020
+ // Whenever it runs, the conversation that asked for it hears how it
1021
+ // ended. Inside a task there is a parent to report to instead.
1022
+ requesterSessionId: context.taskId ? undefined : context.sessionId,
1023
+ });
1024
+ // The card opens its own activity with the brief (`createTask`), so
1025
+ // there is nothing more to write before anybody presses start.
1026
+ this.#announceTask(task, context.emit);
1027
+ return { text: 'Task ' + shortId(task.id) + ' "' + task.title + '" is on the board.' };
1028
+ }
1029
+ #toolListTasks(context, args) {
1030
+ const wanted = args.list('status');
1031
+ // Without a filter this is the board, and the board is its top row.
1032
+ // With one it is a search, and delegated work sits under a parent
1033
+ // (decision E9) - a blocked subtask under a finished parent is
1034
+ // exactly what the board watcher is woken for.
1035
+ const tasks = this.#store.org.listTasks(context.orgId, wanted.length ? { status: wanted, anyLevel: true } : {});
1036
+ return { text: renderBoard(tasks, this.snapshot(context.orgId), this.#store.org) };
1037
+ }
1038
+ async #toolPlanTask(context, args) {
1039
+ const task = this.findTask(context.orgId, args.text('id'));
1040
+ if (!task)
1041
+ return toolError('No task ' + args.text('id') + '.');
1042
+ const plan = await this.planTask(context, task, args.text('hint') || undefined);
1043
+ return { text: describePlan(plan, this.#store.org.listTasks(context.orgId, { parentId: task.id })) };
1044
+ }
1045
+ async #toolRunTask(context, args) {
1046
+ const task = this.findTask(context.orgId, args.text('id'));
1047
+ if (!task)
1048
+ return toolError('No task ' + args.text('id') + '.');
1049
+ const finished = await this.#runAwaited(context, task);
1050
+ if (finished.status === 'blocked')
1051
+ return { text: this.#waitingText(finished) };
1052
+ if (finished.status !== 'done') {
1053
+ return toolError('Task "' + finished.title + '" ' + finished.status + (finished.error ? ': ' + finished.error : '.'));
1054
+ }
1055
+ return { text: 'Task "' + finished.title + '" is done.\n\n' + clip(finished.result ?? '', RESULT_BUDGET) };
988
1056
  }
989
1057
  /* ------------------------------- schedules ------------------------------ */
990
- /** The schedule tools: thin validation around the clock, with agents and projects resolved by name. */
991
- #schedules(context, name, args) {
992
- const text = (key) => (typeof args[key] === 'string' ? args[key].trim() : '');
993
- const flag = (key) => (typeof args[key] === 'boolean' ? args[key] : undefined);
994
- const fail = (message) => ({ text: message, isError: true });
1058
+ #toolSchedules(context, name, args) {
995
1059
  const cron = this.#cron;
996
1060
  if (!cron)
997
- return fail('Schedules are not available in this session.');
1061
+ return toolError('Schedules are not available in this session.');
998
1062
  const snapshot = this.snapshot(context.orgId);
999
- const bySlug = new Map(snapshot.agents.map((agent) => [agent.id, agent.slug]));
1000
- const line = (job) => describeCronJob(job, job.agentId ? bySlug.get(job.agentId) : undefined);
1001
- if (name === 'list_schedules') {
1063
+ if (name === 'list_schedules')
1002
1064
  return { text: renderSchedules(cron.list(context.orgId), snapshot) };
1003
- }
1004
- // "event" takes a schedule off the clock, and then it needs no expression
1005
- // at all; anything else keeps the old rule that one is required.
1006
- const triggerMode = text('triggerMode').toLowerCase() === 'event' ? 'event' : text('triggerMode') ? 'schedule' : undefined;
1007
- const cooldownMs = args.cooldownSeconds === undefined ? undefined : clampNumber(args.cooldownSeconds, 0, 86_400, 60) * 1000;
1008
- if (name === 'create_schedule') {
1009
- if (!text('name') || !text('prompt'))
1010
- return fail('A schedule needs a name and a prompt.');
1011
- if (!text('schedule') && triggerMode !== 'event') {
1012
- return fail('A schedule needs a cron expression, or triggerMode "event" to take it off the clock.');
1013
- }
1014
- const agent = text('agent') ? this.#store.org.findAgent(context.orgId, text('agent')) : null;
1015
- if (text('agent') && !agent)
1016
- return fail('No agent "' + text('agent') + '".');
1017
- const project = text('project') ? this.#store.org.findProject(context.orgId, text('project')) : null;
1018
- if (text('project') && !project)
1019
- return fail('No project "' + text('project') + '".');
1020
- // A one-off follow-up ("I'll get back to you here") should land back
1021
- // in the conversation it was promised in, not in a brand-new one.
1022
- // Only for the assistant's own runs - a recurring job, or one handed
1023
- // to an agent, keeps creating its own dedicated conversation.
1024
- const replyHere = !agent && flag('once') === true ? context.sessionId : undefined;
1025
- try {
1026
- const job = cron.create({
1027
- orgId: context.orgId,
1028
- name: text('name'),
1029
- schedule: text('schedule'),
1030
- triggerMode,
1031
- eventCooldownMs: cooldownMs,
1032
- prompt: text('prompt'),
1033
- kind: agent ? 'agent' : 'assistant',
1034
- agentId: agent?.id,
1035
- projectId: project?.id ?? context.projectId,
1036
- sessionId: replyHere,
1037
- once: flag('once'),
1038
- enabled: flag('enabled'),
1039
- createdBy: 'assistant',
1040
- });
1041
- const when = job.schedule ? describeCron(job.schedule) : 'on events only, no timetable';
1042
- return { text: 'Schedule created: ' + when + '.\n' + line(job) };
1043
- }
1044
- catch (error) {
1045
- return fail(error.message);
1046
- }
1047
- }
1048
- const job = cron.find(context.orgId, text('id'));
1065
+ const bySlug = new Map(snapshot.agents.map((agent) => [agent.id, agent.slug]));
1066
+ const call = {
1067
+ context,
1068
+ cron,
1069
+ args,
1070
+ describe: (job) => describeCronJob(job, job.agentId ? bySlug.get(job.agentId) : undefined),
1071
+ };
1072
+ if (name === 'create_schedule')
1073
+ return this.#createSchedule(call);
1074
+ const job = cron.find(context.orgId, args.text('id'));
1049
1075
  if (!job)
1050
- return fail('No schedule "' + text('id') + '". list_schedules shows the ids.');
1076
+ return toolError('No schedule "' + args.text('id') + '". list_schedules shows the ids.');
1051
1077
  // The nightly memory run is Rookery's internal clockwork: it is not on
1052
1078
  // the list, and it is not the assistant's to delete, fire or reschedule.
1053
1079
  // The memory page owns it.
1054
1080
  if (job.kind === 'sleep') {
1055
- return fail('"' + job.name + '" is the memory\'s own nightly run, not a schedule of yours. It is managed on the memory page.');
1081
+ return toolError('"' + job.name + '" is the memory\'s own nightly run, not a schedule of yours. It is managed on the memory page.');
1056
1082
  }
1057
- if (name === 'set_webhook') {
1058
- if (text('action').toLowerCase() === 'remove') {
1059
- cron.disableWebhook(job.id);
1060
- return { text: 'The webhook for "' + job.name + '" is gone; the URL opens nothing now.' };
1061
- }
1062
- const rotated = Boolean(job.webhookToken);
1063
- const updated = cron.enableWebhook(job.id);
1064
- const url = 'http://' + this.#config.host + ':' + this.#config.port + '/hooks/' + updated.webhookToken;
1065
- return {
1066
- text: (rotated ? 'Rotated the webhook for "' : 'Webhook for "') + job.name +
1067
- '": ' + url + '\n' +
1068
- (rotated ? 'The previous URL stopped working just now. ' : '') +
1069
- 'Anything that can send an HTTP POST to it starts this schedule.',
1070
- };
1083
+ switch (name) {
1084
+ case 'set_webhook':
1085
+ return this.#setWebhook(call, job);
1086
+ case 'delete_schedule':
1087
+ cron.remove(job.id);
1088
+ return { text: 'Deleted schedule "' + job.name + '".' };
1089
+ case 'run_schedule':
1090
+ return this.#runScheduleNow(cron, job);
1091
+ default:
1092
+ return this.#updateSchedule(call, job);
1093
+ }
1094
+ }
1095
+ #createSchedule({ context, cron, args, describe }) {
1096
+ const triggerMode = triggerModeArg(args);
1097
+ if (!args.text('name') || !args.text('prompt'))
1098
+ return toolError('A schedule needs a name and a prompt.');
1099
+ if (!args.text('schedule') && triggerMode !== 'event') {
1100
+ return toolError('A schedule needs a cron expression, or triggerMode "event" to take it off the clock.');
1101
+ }
1102
+ const agent = resolveOptional(args.text('agent'), (ref) => this.#store.org.findAgent(context.orgId, ref), noAgent);
1103
+ if (!agent.ok)
1104
+ return agent.error;
1105
+ const project = resolveOptional(args.text('project'), (ref) => this.#store.org.findProject(context.orgId, ref), noProject);
1106
+ if (!project.ok)
1107
+ return project.error;
1108
+ // A one-off follow-up ("I'll get back to you here") should land back
1109
+ // in the conversation it was promised in, not in a brand-new one.
1110
+ // Only for the assistant's own runs - a recurring job, or one handed
1111
+ // to an agent, keeps creating its own dedicated conversation.
1112
+ const once = args.flag('once');
1113
+ const replyHere = !agent.value && once === true ? context.sessionId : undefined;
1114
+ try {
1115
+ const job = cron.create({
1116
+ orgId: context.orgId,
1117
+ name: args.text('name'),
1118
+ schedule: args.text('schedule'),
1119
+ triggerMode,
1120
+ eventCooldownMs: cooldownMsArg(args),
1121
+ prompt: args.text('prompt'),
1122
+ kind: agent.value ? 'agent' : 'assistant',
1123
+ agentId: agent.value?.id,
1124
+ projectId: project.value?.id ?? context.projectId,
1125
+ sessionId: replyHere,
1126
+ once,
1127
+ enabled: args.flag('enabled'),
1128
+ createdBy: 'assistant',
1129
+ });
1130
+ const when = job.schedule ? describeCron(job.schedule) : 'on events only, no timetable';
1131
+ return { text: 'Schedule created: ' + when + '.\n' + describe(job) };
1071
1132
  }
1072
- if (name === 'delete_schedule') {
1073
- cron.remove(job.id);
1074
- return { text: 'Deleted schedule "' + job.name + '".' };
1133
+ catch (error) {
1134
+ return toolError(error.message);
1075
1135
  }
1076
- if (name === 'run_schedule') {
1077
- if (cron.isRunning(job.id))
1078
- return { text: 'Schedule "' + job.name + '" is already running.' };
1079
- void cron.runNow(job.id).catch((error) => this.#log.warn('Manual schedule run failed', { error: error.message }));
1080
- return { text: 'Schedule "' + job.name + '" is running now; the result reaches the user as a notification.' };
1136
+ }
1137
+ #setWebhook({ cron, args }, job) {
1138
+ if (args.text('action').toLowerCase() === 'remove') {
1139
+ cron.disableWebhook(job.id);
1140
+ return { text: 'The webhook for "' + job.name + '" is gone; the URL opens nothing now.' };
1081
1141
  }
1082
- // update_schedule
1083
- const patch = {};
1084
- if (text('name'))
1085
- patch.name = text('name');
1086
- if (text('schedule'))
1087
- patch.schedule = text('schedule');
1088
- if (text('prompt'))
1089
- patch.prompt = text('prompt');
1090
- if (text('agent')) {
1091
- const wanted = text('agent').toLowerCase();
1092
- if (wanted === 'assistant' || wanted === 'me' || wanted === 'none')
1093
- patch.agentId = null;
1094
- else {
1095
- const agent = this.#store.org.findAgent(context.orgId, text('agent'));
1096
- if (!agent)
1097
- return fail('No agent "' + text('agent') + '".');
1098
- patch.agentId = agent.id;
1099
- }
1142
+ const rotated = Boolean(job.webhookToken);
1143
+ const updated = cron.enableWebhook(job.id);
1144
+ const url = 'http://' + this.#config.host + ':' + this.#config.port + '/hooks/' + updated.webhookToken;
1145
+ return {
1146
+ text: (rotated ? 'Rotated the webhook for "' : 'Webhook for "') + job.name +
1147
+ '": ' + url + '\n' +
1148
+ (rotated ? 'The previous URL stopped working just now. ' : '') +
1149
+ 'Anything that can send an HTTP POST to it starts this schedule.',
1150
+ };
1151
+ }
1152
+ #runScheduleNow(cron, job) {
1153
+ if (cron.isRunning(job.id))
1154
+ return { text: 'Schedule "' + job.name + '" is already running.' };
1155
+ void cron.runNow(job.id).catch((error) => this.#log.warn('Manual schedule run failed', { error: error.message }));
1156
+ return { text: 'Schedule "' + job.name + '" is running now; the result reaches the user as a notification.' };
1157
+ }
1158
+ #updateSchedule(call, job) {
1159
+ const patch = this.#schedulePatch(call);
1160
+ if (!patch.ok)
1161
+ return patch.error;
1162
+ if (!Object.keys(patch.value).length)
1163
+ return toolError('Nothing to change; pass at least one field.');
1164
+ try {
1165
+ const updated = call.cron.update(job.id, patch.value);
1166
+ return {
1167
+ text: 'Updated schedule "' + updated.name + '": ' + Object.keys(patch.value).join(', ') + '.\n' + call.describe(updated),
1168
+ };
1100
1169
  }
1101
- if (text('project')) {
1102
- if (text('project').toLowerCase() === 'none')
1103
- patch.projectId = null;
1104
- else {
1105
- const project = this.#store.org.findProject(context.orgId, text('project'));
1106
- if (!project)
1107
- return fail('No project "' + text('project') + '".');
1108
- patch.projectId = project.id;
1109
- }
1170
+ catch (error) {
1171
+ return toolError(error.message);
1110
1172
  }
1173
+ }
1174
+ #schedulePatch({ context, args }) {
1175
+ const orgId = context.orgId;
1176
+ const patch = {};
1177
+ if (args.text('name'))
1178
+ patch.name = args.text('name');
1179
+ if (args.text('schedule'))
1180
+ patch.schedule = args.text('schedule');
1181
+ if (args.text('prompt'))
1182
+ patch.prompt = args.text('prompt');
1183
+ if (args.text('agent')) {
1184
+ const agent = resolveClearable(args.text('agent'), ['assistant', 'me', 'none'], (ref) => this.#store.org.findAgent(orgId, ref), noAgent);
1185
+ if (!agent.ok)
1186
+ return agent;
1187
+ patch.agentId = agent.value;
1188
+ }
1189
+ if (args.text('project')) {
1190
+ const project = resolveClearable(args.text('project'), ['none'], (ref) => this.#store.org.findProject(orgId, ref), noProject);
1191
+ if (!project.ok)
1192
+ return project;
1193
+ patch.projectId = project.value;
1194
+ }
1195
+ const triggerMode = triggerModeArg(args);
1111
1196
  if (triggerMode)
1112
1197
  patch.triggerMode = triggerMode;
1198
+ const cooldownMs = cooldownMsArg(args);
1113
1199
  if (cooldownMs !== undefined)
1114
1200
  patch.eventCooldownMs = cooldownMs;
1115
- if (flag('enabled') !== undefined)
1116
- patch.enabled = flag('enabled');
1117
- if (flag('once') !== undefined)
1118
- patch.once = flag('once');
1119
- if (!Object.keys(patch).length)
1120
- return fail('Nothing to change; pass at least one field.');
1121
- try {
1122
- const updated = cron.update(job.id, patch);
1123
- return { text: 'Updated schedule "' + updated.name + '": ' + Object.keys(patch).join(', ') + '.\n' + line(updated) };
1124
- }
1125
- catch (error) {
1126
- return fail(error.message);
1127
- }
1201
+ const enabled = args.flag('enabled');
1202
+ if (enabled !== undefined)
1203
+ patch.enabled = enabled;
1204
+ const once = args.flag('once');
1205
+ if (once !== undefined)
1206
+ patch.once = once;
1207
+ return { ok: true, value: patch };
1128
1208
  }
1129
1209
  /* ------------------------------- listeners ------------------------------ */
1130
1210
  /**
@@ -1136,54 +1216,46 @@ export class OrgController extends EventEmitter {
1136
1216
  * registry follows on the `changed` event. Same split as everywhere: the
1137
1217
  * decision here, the socket there.
1138
1218
  */
1139
- #listeners(context, name, args) {
1140
- const text = (key) => (typeof args[key] === 'string' ? args[key].trim() : '');
1141
- const flag = (key) => (typeof args[key] === 'boolean' ? args[key] : undefined);
1142
- const fail = (message) => ({ text: message, isError: true });
1219
+ #toolListeners(context, name, args) {
1143
1220
  if (context.audience !== 'assistant')
1144
- return fail('Only the assistant can change listeners.');
1145
- const entries = this.#config.listeners.imap;
1146
- const jobName = (jobId) => this.#cron?.get(jobId)?.name ?? '(no schedule)';
1147
- if (name === 'list_listeners') {
1148
- if (!entries.length)
1149
- return { text: 'No mailbox is being watched.' };
1150
- return {
1151
- text: entries
1152
- .map((entry) => '- ' + entry.id + ': ' + entry.user + ' / ' + entry.mailbox + ' on ' + entry.host + ':' + entry.port +
1153
- ', fires "' + jobName(entry.jobId) + '", ' + (entry.enabled ? 'on' : 'off') +
1154
- ', password ' + (entry.password ? 'set' : 'missing'))
1155
- .join('\n'),
1156
- };
1157
- }
1158
- const id = text('id');
1221
+ return toolError('Only the assistant can change listeners.');
1222
+ if (name === 'list_listeners')
1223
+ return this.#listListeners();
1224
+ const id = args.text('id');
1159
1225
  if (!id)
1160
- return fail('Name the listener.');
1226
+ return toolError('Name the listener.');
1161
1227
  // It ends up in `imap:<id>` on every run this mailbox causes, so it has to
1162
1228
  // stay a plain word.
1163
1229
  if (!/^[A-Za-z0-9._-]+$/.test(id))
1164
- return fail('A listener id is letters, digits, dot, dash or underscore.');
1165
- const existing = entries.find((entry) => entry.id === id) ?? null;
1166
- if (name === 'remove_listener') {
1167
- if (!existing)
1168
- return fail('No listener "' + id + '".');
1169
- this.#writeListeners(entries.filter((entry) => entry.id !== id));
1170
- return { text: 'Stopped watching "' + id + '" and forgot its settings, the password included.' };
1171
- }
1172
- const wantedJob = text('schedule') ? this.#cron?.find(context.orgId, text('schedule')) ?? null : null;
1173
- if (text('schedule') && !wantedJob) {
1174
- return fail('No schedule "' + text('schedule') + '". list_schedules shows the names.');
1175
- }
1176
- const merged = {
1177
- id,
1178
- enabled: flag('enabled') ?? existing?.enabled ?? false,
1179
- host: text('host') || existing?.host || '',
1180
- port: args.port === undefined ? existing?.port ?? 993 : clampNumber(args.port, 1, 65535, 993),
1181
- secure: flag('secure') ?? existing?.secure ?? true,
1182
- user: text('user') || existing?.user || '',
1183
- password: text('password') || existing?.password || '',
1184
- mailbox: text('mailbox') || existing?.mailbox || 'INBOX',
1185
- jobId: wantedJob?.id ?? existing?.jobId ?? '',
1230
+ return toolError('A listener id is letters, digits, dot, dash or underscore.');
1231
+ const existing = this.#config.listeners.imap.find((entry) => entry.id === id) ?? null;
1232
+ if (name === 'remove_listener')
1233
+ return this.#removeListener(id, existing);
1234
+ return this.#setListener(context, id, existing, args);
1235
+ }
1236
+ #listListeners() {
1237
+ const entries = this.#config.listeners.imap;
1238
+ if (!entries.length)
1239
+ return { text: 'No mailbox is being watched.' };
1240
+ return {
1241
+ text: entries
1242
+ .map((entry) => '- ' + entry.id + ': ' + entry.user + ' / ' + entry.mailbox + ' on ' + entry.host + ':' + entry.port +
1243
+ ', fires "' + this.#listenerJobName(entry.jobId) + '", ' + (entry.enabled ? 'on' : 'off') +
1244
+ ', password ' + (entry.password ? 'set' : 'missing'))
1245
+ .join('\n'),
1186
1246
  };
1247
+ }
1248
+ #removeListener(id, existing) {
1249
+ if (!existing)
1250
+ return toolError('No listener "' + id + '".');
1251
+ this.#writeListeners(this.#config.listeners.imap.filter((entry) => entry.id !== id));
1252
+ return { text: 'Stopped watching "' + id + '" and forgot its settings, the password included.' };
1253
+ }
1254
+ #setListener(context, id, existing, args) {
1255
+ const wantedJob = resolveOptional(args.text('schedule'), (ref) => this.#cron?.find(context.orgId, ref) ?? null, (ref) => 'No schedule "' + ref + '". list_schedules shows the names.');
1256
+ if (!wantedJob.ok)
1257
+ return wantedJob.error;
1258
+ const merged = mergeListener(id, existing, args, wantedJob.value?.id);
1187
1259
  const missing = [];
1188
1260
  if (!merged.host)
1189
1261
  missing.push('a server');
@@ -1192,142 +1264,160 @@ export class OrgController extends EventEmitter {
1192
1264
  if (!merged.jobId)
1193
1265
  missing.push('a schedule to fire');
1194
1266
  if (missing.length)
1195
- return fail('This mailbox still needs ' + missing.join(', ') + '.');
1267
+ return toolError('This mailbox still needs ' + missing.join(', ') + '.');
1196
1268
  // Switched on without a password it would only produce a rejected login
1197
1269
  // and a stopped listener, which reads like a bug rather than a blank field.
1198
1270
  if (merged.enabled && !merged.password)
1199
- return fail('Set the password before switching "' + id + '" on.');
1271
+ return toolError('Set the password before switching "' + id + '" on.');
1272
+ const entries = this.#config.listeners.imap;
1200
1273
  this.#writeListeners(existing ? entries.map((entry) => (entry.id === id ? merged : entry)) : [...entries, merged]);
1201
1274
  // The password is never repeated back, not even to the person who just
1202
1275
  // said it: a tool result is transcript too, and one copy is enough.
1203
1276
  return {
1204
1277
  text: (existing ? 'Updated mailbox "' : 'Now watching "') + id + '": ' + merged.user + ' / ' + merged.mailbox +
1205
- ' on ' + merged.host + ':' + merged.port + ', firing "' + jobName(merged.jobId) + '", ' +
1278
+ ' on ' + merged.host + ':' + merged.port + ', firing "' + this.#listenerJobName(merged.jobId) + '", ' +
1206
1279
  (merged.enabled ? 'on.' : 'off - switch it on once the details are right.'),
1207
1280
  };
1208
1281
  }
1282
+ #listenerJobName(jobId) {
1283
+ return this.#cron?.get(jobId)?.name ?? '(no schedule)';
1284
+ }
1209
1285
  /** Write the list back; the server's registry follows on the event. */
1210
1286
  #writeListeners(imap) {
1211
1287
  applyConfig(this.#config, { listeners: { imap } });
1212
1288
  this.emit('changed', { kind: 'listeners', id: 'listeners' });
1213
1289
  }
1214
- async #assign(context, agentRef, titleRaw, task, projectRef, wait = true) {
1215
- const fail = (message) => ({ text: message, isError: true });
1290
+ async #toolAssign(context, args) {
1291
+ const agentRef = args.text('agent');
1292
+ const task = args.text('task');
1293
+ const wait = args.raw('wait') !== false;
1216
1294
  if (!agentRef)
1217
- return fail('Name the agent to assign to.');
1295
+ return toolError('Name the agent to assign to.');
1218
1296
  if (!task)
1219
- return fail('The task is empty.');
1297
+ return toolError('The task is empty.');
1220
1298
  const agent = this.#store.org.findAgent(context.orgId, agentRef);
1221
1299
  if (!agent) {
1222
1300
  const known = this.#store.org.listAgents(context.orgId).map((entry) => entry.slug);
1223
- return fail('No agent "' + agentRef + '". ' +
1224
- (known.length ? 'Known agents: ' + known.join(', ') + '.' : 'Nobody is hired yet.'));
1225
- }
1226
- if (context.audience === 'agent') {
1227
- if (agent.id === context.agentId) {
1228
- // A self-assignment only makes sense detached: waiting on it would
1229
- // just be the same process blocking on itself for no reason, and in
1230
- // a chat turn there is no coding tool to do the work with anyway.
1231
- if (wait)
1232
- return fail('Taking work on yourself has to run in the background - call assign with wait=false.');
1233
- }
1234
- else if (agent.managerId !== context.agentId) {
1235
- const reports = this.#store.org.listAgents(context.orgId, { managerId: context.agentId }).map((r) => r.slug);
1236
- return fail('You may only assign work to your direct reports' +
1237
- (reports.length ? ': ' + reports.join(', ') : ', and you have none') + '.');
1238
- }
1239
- }
1240
- const depth = context.depth + 1;
1241
- if (depth >= this.#config.org.maxDelegationDepth) {
1242
- return fail('Delegation is nested too deep already. Do this part of the work yourself.');
1301
+ return toolError(noAgent(agentRef) + ' ' + (known.length ? 'Known agents: ' + known.join(', ') + '.' : 'Nobody is hired yet.'));
1243
1302
  }
1303
+ const refusal = this.#assignmentRefusal(context, agent, wait);
1304
+ if (refusal)
1305
+ return toolError(refusal);
1244
1306
  let projectId = context.projectId;
1245
- if (projectRef) {
1246
- const project = this.#store.org.findProject(context.orgId, projectRef);
1307
+ if (args.text('project')) {
1308
+ const project = this.#store.org.findProject(context.orgId, args.text('project'));
1247
1309
  if (!project)
1248
- return fail('No project "' + projectRef + '".');
1310
+ return toolError(noProject(args.text('project')));
1249
1311
  projectId = project.id;
1250
1312
  }
1251
1313
  // Handing work to somebody puts it on the board like every other way in
1252
1314
  // (decision E9). This was the fourth entrance, and the only one that left
1253
1315
  // a run nobody could find on a card. Inside a task, the new one becomes a
1254
1316
  // child of it, so a delegation chain reads as a tree.
1255
- const title = titleRaw.trim() || titleFromBrief(task);
1256
- const board = this.#store.org.createTask({
1317
+ const card = this.#store.org.createTask({
1257
1318
  orgId: context.orgId,
1258
1319
  parentId: context.taskId,
1259
- title,
1320
+ title: args.text('title') || titleFromBrief(task),
1260
1321
  description: task,
1261
1322
  projectId,
1262
1323
  assigneeId: agent.id,
1263
- createdBy: context.audience === 'agent' ? 'agent' : 'assistant',
1324
+ createdBy: callerKind(context),
1264
1325
  createdByAgentId: context.agentId,
1265
1326
  // Where the ending is reported (R1): the conversation for top-level
1266
1327
  // work, the parent task for work handed on from inside one.
1267
1328
  requesterSessionId: context.taskId ? undefined : context.sessionId,
1268
1329
  });
1269
- this.#announceTask(board, context.emit);
1270
- const shortId = board.id.slice(0, 8);
1330
+ this.#announceTask(card, context.emit);
1271
1331
  // The new task is its own errand: the note that continued the caller's
1272
1332
  // task is not part of this brief.
1273
1333
  const runContext = {
1274
1334
  ...context,
1275
1335
  projectId,
1276
- taskId: board.id,
1336
+ taskId: card.id,
1277
1337
  taskNote: undefined,
1278
- emit: wait ? context.emit : () => undefined,
1338
+ emit: wait ? context.emit : ignoreEvent,
1279
1339
  signal: wait ? context.signal : undefined,
1280
1340
  };
1281
- if (!wait) {
1282
- // Detached: the turn ends while the agent works. Its progress reaches
1283
- // every socket through the org-level run events; the turn's own stream
1284
- // and abort signal must not be tied to it.
1285
- //
1286
- // Nobody waits on the promise here, and nobody has to: how the task
1287
- // ends is reported back by `runTask` itself - to the conversation for
1288
- // top-level work, to the parent task (which waits for it, R4) for work
1289
- // handed on from inside one. It used to be dropped on the floor unless
1290
- // an agent had assigned itself, while the tool text promised otherwise.
1291
- const running = this.runTask(runContext, board).catch((error) => {
1292
- this.#log.warn('Detached task failed', { agent: agent.slug, error: String(error) });
1293
- return this.#store.org.getTask(board.id) ?? board;
1294
- });
1295
- if (context.taskId) {
1296
- let pending = this.#detached.get(context.taskId);
1297
- if (!pending) {
1298
- pending = new Map();
1299
- this.#detached.set(context.taskId, pending);
1300
- }
1301
- pending.set(board.id, running);
1341
+ return wait
1342
+ ? this.#assignAndWait(runContext, card, agent)
1343
+ : this.#assignDetached(context, runContext, card, agent);
1344
+ }
1345
+ /** Why the caller may not hand work to this agent now, or null when it may. */
1346
+ #assignmentRefusal(context, agent, wait) {
1347
+ if (context.audience === 'agent') {
1348
+ if (agent.id === context.agentId) {
1349
+ // A self-assignment only makes sense detached: waiting on it would
1350
+ // just be the same process blocking on itself for no reason, and in
1351
+ // a chat turn there is no coding tool to do the work with anyway.
1352
+ if (wait)
1353
+ return 'Taking work on yourself has to run in the background - call assign with wait=false.';
1302
1354
  }
1303
- const whereBack = context.taskId
1304
- ? 'Your own task stays open until it is finished: when your run ends, you are started again with its result.'
1305
- : context.sessionId
1306
- ? 'When it ends - done, failed or with a question - a message arrives in this conversation, and you tell the user then.'
1307
- : 'It is on the board; how it ends is recorded on its card.';
1308
- return {
1309
- text: (agent.id === context.agentId ? 'Started in the background' : 'Handed to ' + agent.name + ' (' + agent.slug + ')') +
1310
- ' as task ' + shortId + ' "' + title + '". ' + whereBack,
1311
- };
1355
+ else if (agent.managerId !== context.agentId) {
1356
+ const reports = this.#store.org.listAgents(context.orgId, { managerId: context.agentId }).map((r) => r.slug);
1357
+ return 'You may only assign work to your direct reports' +
1358
+ (reports.length ? ': ' + reports.join(', ') : ', and you have none') + '.';
1359
+ }
1360
+ }
1361
+ if (context.depth + 1 >= this.#config.org.maxDelegationDepth) {
1362
+ return 'Delegation is nested too deep already. Do this part of the work yourself.';
1312
1363
  }
1313
- const finished = await this.#runAwaited(runContext, board);
1314
- const duration = finished.startedAt && finished.finishedAt
1315
- ? ', ' + Math.round((finished.finishedAt - finished.startedAt) / 1000) + ' s'
1316
- : '';
1364
+ return null;
1365
+ }
1366
+ /**
1367
+ * Detached: the turn ends while the agent works. Its progress reaches
1368
+ * every socket through the org-level run events; the turn's own stream
1369
+ * and abort signal must not be tied to it.
1370
+ *
1371
+ * Nobody waits on the promise here, and nobody has to: how the task
1372
+ * ends is reported back by `runTask` itself - to the conversation for
1373
+ * top-level work, to the parent task (which waits for it, R4) for work
1374
+ * handed on from inside one. It used to be dropped on the floor unless
1375
+ * an agent had assigned itself, while the tool text promised otherwise.
1376
+ */
1377
+ #assignDetached(context, runContext, card, agent) {
1378
+ const running = this.runTask(runContext, card).catch((error) => {
1379
+ this.#log.warn('Detached task failed', { agent: agent.slug, error: String(error) });
1380
+ return this.#current(card);
1381
+ });
1382
+ if (context.taskId)
1383
+ this.#trackDetached(context.taskId, card.id, running);
1384
+ const whereBack = context.taskId
1385
+ ? 'Your own task stays open until it is finished: when your run ends, you are started again with its result.'
1386
+ : context.sessionId
1387
+ ? 'When it ends - done, failed or with a question - a message arrives in this conversation, and you tell the user then.'
1388
+ : 'It is on the board; how it ends is recorded on its card.';
1389
+ return {
1390
+ text: (agent.id === context.agentId ? 'Started in the background' : 'Handed to ' + agent.name + ' (' + agent.slug + ')') +
1391
+ ' as task ' + shortId(card.id) + ' "' + card.title + '". ' + whereBack,
1392
+ };
1393
+ }
1394
+ async #assignAndWait(runContext, card, agent) {
1395
+ const finished = await this.#runAwaited(runContext, card);
1396
+ const label = 'task ' + shortId(card.id) + ' "' + card.title + '"';
1317
1397
  if (finished.status === 'blocked') {
1318
1398
  // Not a failure: the agent asked whoever wanted the work a question,
1319
1399
  // and the card stays open until it is answered.
1320
1400
  return { text: this.#waitingText(finished) };
1321
1401
  }
1322
1402
  if (finished.status !== 'done') {
1323
- return fail('Task ' + shortId + ' "' + title + '" with ' + agent.slug + ' ' + finished.status +
1403
+ return toolError('Task ' + shortId(card.id) + ' "' + card.title + '" with ' + agent.slug + ' ' + finished.status +
1324
1404
  (finished.error ? ': ' + finished.error : '.'));
1325
1405
  }
1406
+ const duration = finished.startedAt && finished.finishedAt ? ', ' + toSeconds(finished.finishedAt - finished.startedAt) + ' s' : '';
1326
1407
  return {
1327
- text: 'Report from ' + agent.name + ' (' + agent.slug + ') on task ' + shortId + ' "' + title + '"' +
1328
- duration + ':\n\n' + clip(finished.result ?? '', RESULT_BUDGET),
1408
+ text: 'Report from ' + agent.name + ' (' + agent.slug + ') on ' + label + duration + ':\n\n' +
1409
+ clip(finished.result ?? '', RESULT_BUDGET),
1329
1410
  };
1330
1411
  }
1412
+ /** Note work a task handed off in the background: the task does not end while any of it is out (R4). */
1413
+ #trackDetached(parentTaskId, taskId, running) {
1414
+ let pending = this.#detached.get(parentTaskId);
1415
+ if (!pending) {
1416
+ pending = new Map();
1417
+ this.#detached.set(parentTaskId, pending);
1418
+ }
1419
+ pending.set(taskId, running);
1420
+ }
1331
1421
  /* ------------------------ questions, answers, notices ----------------------- */
1332
1422
  /**
1333
1423
  * What a caller that waited on a task hears when the task stopped on a
@@ -1338,11 +1428,11 @@ export class OrgController extends EventEmitter {
1338
1428
  const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
1339
1429
  const who = agent ? agent.name + ' (' + agent.slug + ')' : 'The agent';
1340
1430
  const question = this.#questionFor(task);
1341
- return (who + ' has a question about task ' + task.id.slice(0, 8) + ' "' + task.title + '" and the task waits for ' +
1431
+ return (who + ' has a question about task ' + shortId(task.id) + ' "' + task.title + '" and the task waits for ' +
1342
1432
  'the answer.' +
1343
1433
  (question ? '\n\nThe question:\n' + clip(question, RESULT_BUDGET) : '') +
1344
1434
  (task.result ? '\n\nWhat it said:\n' + clip(task.result, RESULT_BUDGET) : '') +
1345
- '\n\nAnswer it with answer_task("' + task.id.slice(0, 8) + '", ...) once you know the answer; the task ' +
1435
+ '\n\nAnswer it with answer_task("' + shortId(task.id) + '", ...) once you know the answer; the task ' +
1346
1436
  'then runs again with it.');
1347
1437
  }
1348
1438
  /** The last question asked on a card, if any - what a waiting task waits on. */
@@ -1359,20 +1449,19 @@ export class OrgController extends EventEmitter {
1359
1449
  * or a notification). This replaces a mail on the requester's To line, and
1360
1450
  * the outbox scan that used to recognise one.
1361
1451
  */
1362
- #askRequester(context, question) {
1363
- const fail = (message) => ({ text: message, isError: true });
1452
+ #toolAskRequester(context, question) {
1364
1453
  if (context.audience !== 'agent') {
1365
- return fail('Only an agent working on a task asks its requester. You can ask the user with ask_user.');
1454
+ return toolError('Only an agent working on a task asks its requester. You can ask the user with ask_user.');
1366
1455
  }
1367
1456
  if (!context.taskId) {
1368
- return fail('You are not working on a task, so nobody is waiting to be asked. Put the question in your result, ' +
1457
+ return toolError('You are not working on a task, so nobody is waiting to be asked. Put the question in your result, ' +
1369
1458
  'with what you assumed in the meantime.');
1370
1459
  }
1371
1460
  const task = this.#store.org.getTask(context.taskId);
1372
1461
  if (!task)
1373
- return fail('The task you are working on no longer exists.');
1462
+ return toolError('The task you are working on no longer exists.');
1374
1463
  if (!question)
1375
- return fail('A question needs its text.');
1464
+ return toolError('A question needs its text.');
1376
1465
  this.#taskEvent({
1377
1466
  taskId: task.id,
1378
1467
  kind: 'question',
@@ -1384,7 +1473,7 @@ export class OrgController extends EventEmitter {
1384
1473
  if (context.parentAssignmentId)
1385
1474
  this.#askedRequester.add(context.parentAssignmentId);
1386
1475
  return {
1387
- text: 'Your question is on the card of task ' + task.id.slice(0, 8) + '. End your run now with a short ' +
1476
+ text: 'Your question is on the card of task ' + shortId(task.id) + '. End your run now with a short ' +
1388
1477
  'summary of where the work stands and what you would do with each likely answer. The task waits ' +
1389
1478
  'for the answer, and you are started again with it.',
1390
1479
  };
@@ -1442,7 +1531,7 @@ export class OrgController extends EventEmitter {
1442
1531
  const answered = await this.#answer(task, input.answer.trim(), input.by ?? { kind: 'user' });
1443
1532
  if (!answered.ok)
1444
1533
  return answered;
1445
- return { ok: true, task: this.#store.org.getTask(task.id) ?? task };
1534
+ return { ok: true, task: this.#current(task) };
1446
1535
  }
1447
1536
  /**
1448
1537
  * Answer a task and carry it on. The answer goes on the card first, whatever
@@ -1479,7 +1568,7 @@ export class OrgController extends EventEmitter {
1479
1568
  ? 'The user'
1480
1569
  : 'The assistant';
1481
1570
  const question = this.#questionFor(task);
1482
- const note = (question ? 'You asked:\n' + clip(question, 4000) + '\n\n' : '') +
1571
+ const note = (question ? 'You asked:\n' + clip(question, NOTE_RESULT_BUDGET) + '\n\n' : '') +
1483
1572
  label + ' answered:\n\n' + answer;
1484
1573
  return this.#continueTask(task, by, note, context);
1485
1574
  }
@@ -1514,7 +1603,7 @@ export class OrgController extends EventEmitter {
1514
1603
  'without the user. It stays as it is until they pick it up.',
1515
1604
  };
1516
1605
  }
1517
- const depth = context ? context.depth : -1;
1606
+ const depth = context?.depth ?? -1;
1518
1607
  if (depth + 1 >= this.#config.org.maxDelegationDepth) {
1519
1608
  return { ok: false, reason: 'The answer is on the card, but delegation is nested too deep to run it from here.' };
1520
1609
  }
@@ -1525,20 +1614,14 @@ export class OrgController extends EventEmitter {
1525
1614
  depth,
1526
1615
  projectId: task.projectId,
1527
1616
  parentAssignmentId: context?.parentAssignmentId,
1528
- emit: () => undefined,
1617
+ emit: ignoreEvent,
1529
1618
  taskNote: note,
1530
1619
  }, task).catch((error) => {
1531
1620
  this.#log.warn('Task continuation failed', { task: task.id, error: String(error) });
1532
- return this.#store.org.getTask(task.id) ?? task;
1621
+ return this.#current(task);
1533
1622
  });
1534
- if (context?.taskId && task.parentId === context.taskId) {
1535
- let pending = this.#detached.get(context.taskId);
1536
- if (!pending) {
1537
- pending = new Map();
1538
- this.#detached.set(context.taskId, pending);
1539
- }
1540
- pending.set(task.id, running);
1541
- }
1623
+ if (context?.taskId && task.parentId === context.taskId)
1624
+ this.#trackDetached(context.taskId, task.id, running);
1542
1625
  return { ok: true };
1543
1626
  }
1544
1627
  /** Append one line to a card's activity and tell everyone listening. Never throws. */
@@ -1573,44 +1656,46 @@ export class OrgController extends EventEmitter {
1573
1656
  * cancellation the person just performed themselves.
1574
1657
  */
1575
1658
  #deliverEnding(task, status, how) {
1576
- const userCard = task.createdBy === 'user' && !task.requesterSessionId && !task.parentId;
1577
- const reportsBack = Boolean(task.requesterSessionId) && !task.parentId;
1578
- const awaited = this.#awaited.has(task.id);
1579
1659
  if (status === 'blocked') {
1580
1660
  // Only a run's own ending asks anything; a card set to `blocked` by
1581
1661
  // hand carries no new question.
1582
- if (!how.fromRun)
1583
- return;
1584
- if (!userCard) {
1585
- if (awaited || reportsBack)
1586
- return;
1587
- // A lead's own report asked it: the lead's task waits for its
1588
- // children and is started again with the question (R4), and
1589
- // `#awaitDelegated` escalates it when it cannot be.
1590
- if (task.createdBy === 'agent' && task.parentId)
1591
- return;
1592
- }
1593
- this.#escalateQuestion(task);
1662
+ if (how.fromRun && this.#questionFallsToUser(task))
1663
+ this.#escalateQuestion(task);
1594
1664
  return;
1595
1665
  }
1596
- if (task.scheduleId)
1666
+ if (!this.#userHearsEnding(task, status, how))
1597
1667
  return;
1668
+ const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
1669
+ this.notifyUser({ orgId: task.orgId, ...taskNotification(task, agent) });
1670
+ }
1671
+ /** Whether a waiting card's question falls to the user: nobody else in the chain will carry it. */
1672
+ #questionFallsToUser(task) {
1673
+ if (isUserCard(task))
1674
+ return true;
1675
+ if (this.#awaited.has(task.id) || reportsBackToConversation(task))
1676
+ return false;
1677
+ // A lead's own report asked it: the lead's task waits for its
1678
+ // children and is started again with the question (R4), and
1679
+ // `#awaitDelegated` escalates it when it cannot be.
1680
+ return !(task.createdBy === 'agent' && task.parentId);
1681
+ }
1682
+ /** Whether the user is owed a notification for an ending that is not a question. */
1683
+ #userHearsEnding(task, status, how) {
1684
+ if (task.scheduleId)
1685
+ return false;
1598
1686
  if (status === 'cancelled' && how.by === 'user' && !how.fromRun)
1599
- return;
1687
+ return false;
1600
1688
  // The user's own card tells them, even when the assistant happened to be
1601
1689
  // waiting on the run: they put it up, and the card is theirs to follow.
1602
- if (!userCard) {
1603
- if (awaited || reportsBack || task.parentId)
1604
- return;
1605
- if (task.createdBy !== 'assistant')
1606
- return;
1607
- }
1608
- const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
1609
- this.notifyUser({ orgId: task.orgId, ...taskNotification(task, agent) });
1690
+ if (isUserCard(task))
1691
+ return true;
1692
+ if (this.#awaited.has(task.id) || reportsBackToConversation(task) || task.parentId)
1693
+ return false;
1694
+ return task.createdBy === 'assistant';
1610
1695
  }
1611
1696
  /** Put a waiting card's question to the user, in the asking agent's name. */
1612
1697
  #escalateQuestion(task) {
1613
- const current = this.#store.org.getTask(task.id) ?? task;
1698
+ const current = this.#current(task);
1614
1699
  const asked = this.#store.org.lastTaskEvent(current.id, 'question');
1615
1700
  const agentId = asked?.actorAgentId ?? current.assigneeId;
1616
1701
  const agent = agentId ? this.#store.org.getAgent(agentId) : null;
@@ -1648,12 +1733,28 @@ export class OrgController extends EventEmitter {
1648
1733
  * record says how it ended. Events flow to `input.emit` as they happen.
1649
1734
  */
1650
1735
  async run(input) {
1651
- const { agent } = input;
1736
+ const run = this.#openRun(input);
1737
+ run.record.announce();
1738
+ await this.#acquire(run.abort.signal);
1739
+ const started = Date.now();
1740
+ try {
1741
+ return await this.#execute(run, started);
1742
+ }
1743
+ catch (error) {
1744
+ this.#log.warn('Assignment failed', { id: run.record.id, error: error.message });
1745
+ return run.record.fail(error.message, started);
1746
+ }
1747
+ finally {
1748
+ this.#closeRun(run);
1749
+ }
1750
+ }
1751
+ /** Create the assignment's record and everything that lives from the moment it is queued. */
1752
+ #openRun(input) {
1652
1753
  const org = this.#store.org;
1653
1754
  const project = input.projectId ? org.getProject(input.projectId) : null;
1654
- let assignment = org.createAssignment({
1755
+ const assignment = org.createAssignment({
1655
1756
  orgId: input.orgId,
1656
- agentId: agent.id,
1757
+ agentId: input.agent.id,
1657
1758
  title: input.title,
1658
1759
  task: input.task,
1659
1760
  projectId: project?.id,
@@ -1664,48 +1765,16 @@ export class OrgController extends EventEmitter {
1664
1765
  depth: input.depth,
1665
1766
  });
1666
1767
  input.onStarted?.(assignment);
1667
- const view = (extra = {}) => toView(assignment, agent, extra);
1668
- const announce = (extra = {}) => this.#announce({ type: 'assignment', assignment: view(extra) }, input.emit);
1669
- const finish = (patch, extra = {}) => {
1670
- org.updateAssignment(assignment.id, patch);
1671
- assignment = org.getAssignment(assignment.id) ?? assignment;
1672
- announce(extra);
1673
- return assignment;
1674
- };
1675
- const fail = (error, started) => {
1676
- const failed = finish({ status: 'failed', error, finishedAt: Date.now(), durationMs: Date.now() - started }, { error });
1677
- // Every fail() path is a hard signal (timeout, no provider, empty
1678
- // output, a fatal provider error) - no model call, and it marks the run
1679
- // as a technical failure rather than a quality judgement (see
1680
- // docs/concepts/agent-performance-management.md). A write that cannot
1681
- // land must never take the assignment result down with it.
1682
- try {
1683
- org.upsertReview({
1684
- orgId: input.orgId,
1685
- agentId: agent.id,
1686
- assignmentId: assignment.id,
1687
- source: 'system',
1688
- overall: 1,
1689
- failedRun: true,
1690
- });
1691
- }
1692
- catch (reviewError) {
1693
- this.#log.warn('System review failed to write', {
1694
- assignment: assignment.id,
1695
- error: reviewError.message,
1696
- });
1697
- }
1698
- return failed;
1699
- };
1768
+ const record = new AssignmentRecord(org, input.agent, assignment, (event) => this.#announce(event, input.emit), this.#log);
1700
1769
  // One abort controller per assignment, live from the moment it is queued:
1701
1770
  // the caller going away, a cancel() by id and the timeout all end in it.
1702
- const controller = new AbortController();
1703
- const onAbort = () => controller.abort();
1771
+ const abort = new AbortController();
1772
+ const onAbort = () => abort.abort();
1704
1773
  input.signal?.addEventListener('abort', onAbort, { once: true });
1705
1774
  let cancelledBy = null;
1706
1775
  this.#active.set(assignment.id, (by) => {
1707
1776
  cancelledBy = by;
1708
- controller.abort();
1777
+ abort.abort();
1709
1778
  });
1710
1779
  // The live log lives from the moment the run is queued: watching a
1711
1780
  // pending assignment is legal, it simply has nothing to show yet. Its
@@ -1718,289 +1787,360 @@ export class OrgController extends EventEmitter {
1718
1787
  // messages of its own and opens no recall trace, and the one label its
1719
1788
  // runs can earn - the review (4.2d) - is keyed on this same id.
1720
1789
  this.#store.turns.beginAssignment(assignment.id, input.sessionId, Date.now());
1721
- const cancelled = () => cancelledBy !== null || Boolean(input.signal?.aborted);
1722
- announce();
1723
- await this.#acquire(controller.signal);
1724
- const started = Date.now();
1790
+ return {
1791
+ input,
1792
+ project,
1793
+ record,
1794
+ abort,
1795
+ onAbort,
1796
+ cancelled: () => cancelledBy !== null || Boolean(input.signal?.aborted),
1797
+ };
1798
+ }
1799
+ /** Everything between being granted a slot and having an ending to write. */
1800
+ async #execute(run, started) {
1801
+ const { input, project, record, abort } = run;
1802
+ const { agent } = input;
1803
+ if (abort.signal.aborted)
1804
+ return record.finish({ status: 'cancelled', finishedAt: started, durationMs: 0 });
1805
+ const preferred = agent.provider ?? this.#config.defaultProvider;
1806
+ const providerId = await this.#registry.resolveUsable(preferred);
1807
+ if (!providerId)
1808
+ return record.fail(await this.#noProviderReason(), started);
1809
+ const cwd = project?.path || agentWorkspace(this.#config, agent.id);
1810
+ if (!existsSync(cwd))
1811
+ return record.fail('The project directory ' + cwd + ' does not exist.', started);
1812
+ const shared = this.#prepareRun(run, cwd, preferred);
1813
+ // The timeout and the bridge token span every provider attempt: a
1814
+ // switch does not buy a second timeout, and the bridge serves whichever
1815
+ // process is currently running.
1816
+ const timer = setTimeout(() => abort.abort(), this.#config.org.assignmentTimeoutMs);
1817
+ timer.unref?.();
1818
+ const token = this.register({
1819
+ orgId: input.orgId,
1820
+ audience: 'agent',
1821
+ agentId: agent.id,
1822
+ sessionId: input.sessionId,
1823
+ projectId: project?.id,
1824
+ parentAssignmentId: record.id,
1825
+ // What this run is carrying out, so anything it hands on lands under
1826
+ // the same card instead of starting a second one (decision E9).
1827
+ taskId: input.taskId,
1828
+ depth: input.depth,
1829
+ emit: input.emit,
1830
+ signal: abort.signal,
1831
+ scheduled: input.scheduled,
1832
+ });
1833
+ let outcome;
1725
1834
  try {
1726
- if (controller.signal.aborted)
1727
- return finish({ status: 'cancelled', finishedAt: started, durationMs: 0 });
1728
- const preferred = agent.provider ?? this.#config.defaultProvider;
1729
- const providerId = await this.#registry.resolveUsable(preferred);
1730
- if (!providerId) {
1731
- // A company parked entirely for quota says so: there is nothing to
1732
- // log in to, only windows to wait out.
1733
- const ready = (await this.#registry.statuses()).filter((status) => status.available && status.authenticated);
1734
- return fail(ready.length > 0 && ready.every((status) => providerBlocked(status.id))
1735
- ? 'Every provider is out of quota.'
1736
- : 'No provider is logged in.', started);
1737
- }
1738
- const cwd = project?.path || agentWorkspace(this.#config, agent.id);
1739
- if (!existsSync(cwd))
1740
- return fail('The project directory ' + cwd + ' does not exist.', started);
1741
- // Everything below is shared by every provider attempt of this
1742
- // assignment: the company, the memory and the skills are the agent's,
1743
- // not the backend's.
1744
- const snapshot = this.snapshot(input.orgId);
1745
- const memories = this.#memoriesFor(agent.id, input.task);
1746
- const requester = input.requesterKind === 'agent'
1747
- ? (org.getAgent(input.requesterAgentId ?? '')?.name ?? 'your manager')
1748
- : input.requesterKind === 'user'
1749
- ? 'the user, directly'
1750
- : 'the assistant';
1751
- // The project's own MCP servers - read from its `.mcp.json`, the same
1752
- // file a person's own session in that folder would read - only start
1753
- // once the assistant has approved this exact file (see
1754
- // trust_project_mcp). Untrusted or changed, they stay off and the
1755
- // agent is told why instead of silently missing tools it expects.
1756
- const projectMcp = project?.path ? readProjectMcpFile(project.path) : null;
1757
- const projectMcpState = projectMcpStatus(projectMcp, project?.mcpTrust);
1758
- const projectMcpSpecs = projectMcpState === 'trusted' && projectMcp ? projectMcp.servers : [];
1759
- // Rookery searches its own shelf rather than trusting the agent to
1760
- // remember: the index says what exists, the hint says how much more is
1761
- // installed, and the third line is the two or three that look like this
1762
- // assignment - put there the way a recalled memory is, not left to a
1763
- // tool call somebody has to think of.
1764
- const agentSkills = this.#agentSkills(project);
1765
- const skillsIndex = [
1766
- renderSkillsIndex(agentSkills),
1767
- renderExternalSkillsHint(this.#config, 'agent'),
1768
- renderSkillMatches(matchSkills(this.#config, 'agent', agentSkills, input.task)),
1769
- ]
1770
- .filter(Boolean)
1771
- .join('\n\n');
1772
- // The timeout and the bridge token span every provider attempt: a
1773
- // switch does not buy a second timeout, and the bridge serves whichever
1774
- // process is currently running.
1775
- const timer = setTimeout(() => controller.abort(), this.#config.org.assignmentTimeoutMs);
1776
- timer.unref?.();
1777
- const token = this.register({
1778
- orgId: input.orgId,
1779
- audience: 'agent',
1780
- agentId: agent.id,
1781
- sessionId: input.sessionId,
1782
- projectId: project?.id,
1783
- parentAssignmentId: assignment.id,
1784
- // What this run is carrying out, so anything it hands on lands under
1785
- // the same card instead of starting a second one (decision E9).
1835
+ outcome = await this.#runAttempts(run, { ...shared, token, started, firstProvider: providerId });
1836
+ }
1837
+ finally {
1838
+ clearTimeout(timer);
1839
+ this.unregister(token);
1840
+ }
1841
+ if (run.cancelled()) {
1842
+ return record.finish({ status: 'cancelled', finishedAt: Date.now(), durationMs: Date.now() - started });
1843
+ }
1844
+ if (abort.signal.aborted)
1845
+ return record.fail('Timed out.', started);
1846
+ if (outcome.fatal)
1847
+ return record.fail(outcome.fatal, started);
1848
+ if (!outcome.text.trim())
1849
+ return record.fail('The agent produced no output.', started);
1850
+ return this.#complete(run, outcome, started);
1851
+ }
1852
+ /**
1853
+ * Why no provider could take the run. A company parked entirely for quota
1854
+ * says so: there is nothing to log in to, only windows to wait out.
1855
+ */
1856
+ async #noProviderReason() {
1857
+ const ready = (await this.#registry.statuses()).filter((status) => status.available && status.authenticated);
1858
+ return ready.length > 0 && ready.every((status) => providerBlocked(status.id))
1859
+ ? 'Every provider is out of quota.'
1860
+ : 'No provider is logged in.';
1861
+ }
1862
+ /**
1863
+ * Everything shared by every provider attempt of this assignment: the
1864
+ * company, the memory and the skills are the agent's, not the backend's.
1865
+ */
1866
+ #prepareRun(run, cwd, preferred) {
1867
+ const { input, project, record } = run;
1868
+ return {
1869
+ project,
1870
+ cwd,
1871
+ preferred,
1872
+ projectMcp: this.#projectMcpSetup(project),
1873
+ promptBase: {
1874
+ config: this.#config,
1875
+ agent: input.agent,
1876
+ snapshot: this.snapshot(input.orgId),
1877
+ project: project ?? undefined,
1878
+ memories: this.#memoriesFor(input.agent.id, input.task),
1879
+ assignmentId: record.id,
1880
+ requestedBy: this.#requesterLabel(input),
1786
1881
  taskId: input.taskId,
1787
- depth: input.depth,
1788
- emit: input.emit,
1789
- signal: controller.signal,
1790
- scheduled: input.scheduled,
1791
- });
1792
- let text = '';
1793
- let fatal = null;
1794
- /** The provider and model the assignment ends up having run with. */
1795
- let usedProvider = providerId;
1796
- let usedModel = agent.model;
1797
- const tried = new Set([providerId]);
1798
- try {
1799
- for (let attempt = 1; attempt <= MAX_PROVIDER_ATTEMPTS; attempt += 1) {
1800
- const pid = usedProvider;
1801
- // A different backend serves different names; the fallback
1802
- // provider's own default stands in for a model it has never
1803
- // heard of.
1804
- usedModel = attempt === 1 && pid === preferred ? agent.model : remapModel(pid, agent.model);
1805
- finish({ status: 'running', provider: pid, model: usedModel, startedAt: started });
1806
- const extra = toolServersFor(this.#config, 'agent', pid, project?.id);
1807
- const toolHints = [...extra.hints];
1808
- if (projectMcp?.servers.length && projectMcpState !== 'trusted') {
1809
- toolHints.push("This project's .mcp.json lists " + projectMcp.servers.length + ' MCP server(s) not yet trusted' +
1810
- (projectMcpState === 'changed' ? ' (the file changed since it was approved)' : '') +
1811
- '; the assistant can review them with project_mcp_servers and trust_project_mcp.');
1812
- }
1813
- const systemPrompt = buildAgentPrompt({
1814
- config: this.#config,
1815
- agent,
1816
- snapshot,
1817
- project: project ?? undefined,
1818
- memories,
1819
- assignmentId: assignment.id,
1820
- requestedBy: requester,
1821
- taskId: input.taskId,
1822
- toolHints,
1823
- skillsIndex,
1824
- agentNotes: org.agentNotesSince(agent.id).slice(0, 2),
1825
- handoverFrom: this.#handoverFor(agent),
1826
- });
1827
- // A switch discards the dead attempt's partial text: an assignment
1828
- // has no resume, so it starts over rather than stitching. The live
1829
- // log is cleared at the switch itself, below, so the switch notice
1830
- // is pushed after the reset and no watcher can lose it.
1831
- text = '';
1832
- let sinceProgress = 0;
1833
- fatal = null;
1834
- try {
1835
- const mcp = await this.#bridge.spec(token);
1836
- const mcpExtra = [...extra.specs, ...projectMcpSpecs];
1837
- for await (const event of this.#registry.get(pid).run({
1838
- prompt: input.task,
1839
- systemPrompt,
1840
- model: usedModel,
1841
- effort: this.#config.defaultEffort,
1842
- cwd,
1843
- permission: agent.permission ?? this.#config.defaultPermission,
1844
- mcp,
1845
- mcpExtra: mcpExtra.length ? mcpExtra : undefined,
1846
- // Approved subagents and hooks out of the Claude Code
1847
- // installation, plus Rookery's own permission floor.
1848
- ...externalTurnExtras(this.#config, 'agent'),
1849
- // A visible Claude Code terminal per run, keyed by the run so
1850
- // the server can stream it to whoever opens the run's page.
1851
- ...(this.#config.org.interactiveRuns
1852
- ? {
1853
- tui: {
1854
- key: assignment.id,
1855
- // A person typing into the finished run's terminal
1856
- // belongs in its transcript, not only on the screen.
1857
- // The live buffer is gone once the run finished, so
1858
- // these go straight into the journal the transcript
1859
- // is read from.
1860
- onLateEvent: (event) => this.#store.turns.append(assignment.id, event),
1861
- },
1862
- }
1863
- : {}),
1864
- signal: controller.signal,
1865
- })) {
1866
- if (event.type === 'text') {
1867
- this.#logPush(assignment.id, event);
1868
- text += event.delta;
1869
- sinceProgress += event.delta.length;
1870
- if (sinceProgress >= PROGRESS_EVERY) {
1871
- sinceProgress = 0;
1872
- org.updateAssignment(assignment.id, { chars: text.length });
1873
- announce({ chars: text.length, preview: shorten(tail(text, 160), 110) });
1874
- }
1875
- }
1876
- else if (event.type === 'thinking') {
1877
- this.#logPush(assignment.id, event);
1878
- }
1879
- else if (event.type === 'tool') {
1880
- // The live log keeps the raw event: the `[slug]` prefix below
1881
- // is for the parent turn's stream, not this run's own log.
1882
- this.#logPush(assignment.id, event);
1883
- input.emit({ ...event, detail: '[' + agent.slug + '] ' + (event.detail ?? '') });
1884
- // A tool starting is the one moment worth telling everyone about,
1885
- // not just the turn that started this run - the same `announce`
1886
- // that already carries `chars`/`preview` org-wide, extended with
1887
- // what the run is doing right now. Not persisted, same as
1888
- // `preview`: a live-only field, gone once the run finishes.
1889
- if (event.status === 'start') {
1890
- announce({ lastActivity: { kind: 'tool', label: event.name, at: Date.now() } });
1891
- }
1892
- }
1893
- else if (event.type === 'done') {
1894
- text = event.text || text;
1895
- }
1896
- else if (event.type === 'error' && event.fatal) {
1897
- this.#logPush(assignment.id, event);
1898
- fatal = event.message;
1899
- }
1900
- }
1901
- }
1902
- catch (error) {
1903
- fatal = error.message;
1904
- }
1905
- // Only a usage-limit death goes around once more, on a provider
1906
- // that has not been tried yet; anything else falls through to the
1907
- // ordinary ending below. Cancelled and timed-out runs are never
1908
- // retried on another backend.
1909
- if (fatal === null ||
1910
- !isUsageLimitError(fatal) ||
1911
- attempt >= MAX_PROVIDER_ATTEMPTS ||
1912
- cancelled() ||
1913
- controller.signal.aborted ||
1914
- !this.#config.providerFallback.enabled) {
1915
- break;
1916
- }
1917
- rememberUsageFailure(pid);
1918
- const alternate = await this.#registry.resolveUsable(preferred, { exclude: [...tried] });
1919
- if (!alternate)
1920
- break;
1921
- const switchEvent = {
1922
- type: 'status',
1923
- label: 'provider',
1924
- detail: pid + ' hit its usage limit, continuing on ' + alternate,
1925
- };
1926
- this.#logReset(assignment.id);
1927
- this.#logPush(assignment.id, switchEvent);
1928
- input.emit(switchEvent);
1929
- announce({ lastActivity: { kind: 'status', label: 'provider', at: Date.now() } });
1930
- usedProvider = alternate;
1931
- tried.add(alternate);
1932
- }
1933
- }
1934
- finally {
1935
- clearTimeout(timer);
1936
- this.unregister(token);
1937
- }
1938
- if (cancelled()) {
1939
- return finish({ status: 'cancelled', finishedAt: Date.now(), durationMs: Date.now() - started });
1940
- }
1941
- if (controller.signal.aborted)
1942
- return fail('Timed out.', started);
1943
- if (fatal)
1944
- return fail(fatal, started);
1945
- if (!text.trim())
1946
- return fail('The agent produced no output.', started);
1947
- const done = finish({ status: 'done', result: text, chars: text.length, finishedAt: Date.now(), durationMs: Date.now() - started }, { chars: text.length, preview: shorten(tail(text, 160), 110) });
1948
- // A scheduled assignment does not learn: its "task" is the job's own
1949
- // prompt, written once when the schedule was created, and every firing
1950
- // would otherwise quote it back into the bank as if it were news.
1951
- if (this.#config.memory.enabled && this.#config.memory.autoExtract && !input.scheduled) {
1952
- void this.#learn(agent, input.task, text, usedProvider);
1882
+ skillsIndex: this.#skillsIndexFor(project, input.task),
1883
+ },
1884
+ };
1885
+ }
1886
+ /** Who asked for the work, in the words the agent's prompt uses. */
1887
+ #requesterLabel(input) {
1888
+ if (input.requesterKind === 'agent') {
1889
+ return this.#store.org.getAgent(input.requesterAgentId ?? '')?.name ?? 'your manager';
1890
+ }
1891
+ return input.requesterKind === 'user' ? 'the user, directly' : 'the assistant';
1892
+ }
1893
+ /**
1894
+ * The project's own MCP servers - read from its `.mcp.json`, the same
1895
+ * file a person's own session in that folder would read - only start
1896
+ * once the assistant has approved this exact file (see
1897
+ * trust_project_mcp). Untrusted or changed, they stay off and the
1898
+ * agent is told why instead of silently missing tools it expects.
1899
+ */
1900
+ #projectMcpSetup(project) {
1901
+ const file = project?.path ? readProjectMcpFile(project.path) : null;
1902
+ const state = projectMcpStatus(file, project?.mcpTrust);
1903
+ if (state === 'trusted' && file)
1904
+ return { specs: file.servers, hints: [] };
1905
+ if (!file?.servers.length)
1906
+ return { specs: [], hints: [] };
1907
+ const changed = state === 'changed' ? ' (the file changed since it was approved)' : '';
1908
+ return {
1909
+ specs: [],
1910
+ hints: [
1911
+ "This project's .mcp.json lists " + file.servers.length + ' MCP server(s) not yet trusted' + changed +
1912
+ '; the assistant can review them with project_mcp_servers and trust_project_mcp.',
1913
+ ],
1914
+ };
1915
+ }
1916
+ /**
1917
+ * Rookery searches its own shelf rather than trusting the agent to
1918
+ * remember: the index says what exists, the hint says how much more is
1919
+ * installed, and the third line is the two or three that look like this
1920
+ * assignment - put there the way a recalled memory is, not left to a
1921
+ * tool call somebody has to think of.
1922
+ */
1923
+ #skillsIndexFor(project, task) {
1924
+ const skills = this.#agentSkills(project);
1925
+ return [
1926
+ renderSkillsIndex(skills),
1927
+ renderExternalSkillsHint(this.#config, 'agent'),
1928
+ renderSkillMatches(matchSkills(this.#config, 'agent', skills, task)),
1929
+ ]
1930
+ .filter(Boolean)
1931
+ .join('\n\n');
1932
+ }
1933
+ /** Run the provider attempts: the first on the chosen backend, and at most one more after a usage-limit death. */
1934
+ async #runAttempts(run, setup) {
1935
+ const { agent } = run.input;
1936
+ let provider = setup.firstProvider;
1937
+ const tried = new Set([provider]);
1938
+ let output = new AttemptOutput();
1939
+ for (let attempt = 1; attempt <= MAX_PROVIDER_ATTEMPTS; attempt += 1) {
1940
+ // A different backend serves different names; the fallback
1941
+ // provider's own default stands in for a model it has never
1942
+ // heard of.
1943
+ const model = attempt === 1 && provider === setup.preferred ? agent.model : remapModel(provider, agent.model);
1944
+ run.record.finish({ status: 'running', provider, model, startedAt: setup.started });
1945
+ // A switch discards the dead attempt's partial text: an assignment
1946
+ // has no resume, so it starts over rather than stitching. The live
1947
+ // log is cleared at the switch itself, below, so the switch notice
1948
+ // is pushed after the reset and no watcher can lose it.
1949
+ output = await this.#streamAttempt(run, setup, provider, model);
1950
+ const alternate = await this.#alternateProvider(run, setup, { attempt, provider, tried, fatal: output.fatal });
1951
+ if (!alternate)
1952
+ break;
1953
+ this.#announceProviderSwitch(run, provider, alternate);
1954
+ provider = alternate;
1955
+ tried.add(alternate);
1956
+ }
1957
+ return { text: output.text, fatal: output.fatal, provider };
1958
+ }
1959
+ /**
1960
+ * Only a usage-limit death goes around once more, on a provider
1961
+ * that has not been tried yet; anything else falls through to the
1962
+ * ordinary ending. Cancelled and timed-out runs are never
1963
+ * retried on another backend.
1964
+ */
1965
+ async #alternateProvider(run, setup, failed) {
1966
+ const retryable = failed.fatal !== null &&
1967
+ isUsageLimitError(failed.fatal) &&
1968
+ failed.attempt < MAX_PROVIDER_ATTEMPTS &&
1969
+ !run.cancelled() &&
1970
+ !run.abort.signal.aborted &&
1971
+ this.#config.providerFallback.enabled;
1972
+ if (!retryable)
1973
+ return undefined;
1974
+ rememberUsageFailure(failed.provider);
1975
+ return (await this.#registry.resolveUsable(setup.preferred, { exclude: [...failed.tried] })) ?? undefined;
1976
+ }
1977
+ #announceProviderSwitch(run, from, to) {
1978
+ const id = run.record.id;
1979
+ const switchEvent = {
1980
+ type: 'status',
1981
+ label: 'provider',
1982
+ detail: from + ' hit its usage limit, continuing on ' + to,
1983
+ };
1984
+ this.#logReset(id);
1985
+ this.#logPush(id, switchEvent);
1986
+ run.input.emit(switchEvent);
1987
+ run.record.announce({ lastActivity: { kind: 'status', label: 'provider', at: Date.now() } });
1988
+ }
1989
+ /** One provider process, from prompt to last event; never throws, a failure ends in `fatal`. */
1990
+ async #streamAttempt(run, setup, provider, model) {
1991
+ const { input, record, abort } = run;
1992
+ const { agent } = input;
1993
+ const output = new AttemptOutput();
1994
+ const extra = toolServersFor(this.#config, 'agent', provider, setup.project?.id);
1995
+ const systemPrompt = buildAgentPrompt({
1996
+ ...setup.promptBase,
1997
+ toolHints: [...extra.hints, ...setup.projectMcp.hints],
1998
+ agentNotes: this.#store.org.agentNotesSince(agent.id).slice(0, 2),
1999
+ handoverFrom: this.#handoverFor(agent),
2000
+ });
2001
+ try {
2002
+ const mcp = await this.#bridge.spec(setup.token);
2003
+ const mcpExtra = [...extra.specs, ...setup.projectMcp.specs];
2004
+ for await (const event of this.#registry.get(provider).run({
2005
+ prompt: input.task,
2006
+ systemPrompt,
2007
+ model,
2008
+ effort: this.#config.defaultEffort,
2009
+ cwd: setup.cwd,
2010
+ permission: agent.permission ?? this.#config.defaultPermission,
2011
+ mcp,
2012
+ mcpExtra: mcpExtra.length ? mcpExtra : undefined,
2013
+ // Approved subagents and hooks out of the Claude Code
2014
+ // installation, plus Rookery's own permission floor.
2015
+ ...externalTurnExtras(this.#config, 'agent'),
2016
+ ...this.#interactiveRunOptions(record.id),
2017
+ signal: abort.signal,
2018
+ })) {
2019
+ this.#absorbProviderEvent(run, event, output);
1953
2020
  }
1954
- if (this.#config.org.autoReview)
1955
- void this.#review(agent, done, input.task, text, usedProvider);
1956
- // Asked by the run itself, through `ask_requester` - nothing to infer.
1957
- input.onAskedRequester?.(this.#askedRequester.has(assignment.id));
1958
- return done;
1959
2021
  }
1960
2022
  catch (error) {
1961
- this.#log.warn('Assignment failed', { id: assignment.id, error: error.message });
1962
- return fail(error.message, started);
2023
+ output.fatal = error.message;
1963
2024
  }
1964
- finally {
1965
- // How it ended, written into the transcript itself.
1966
- //
1967
- // The journal used to stop at the last streamed line, so a run that
1968
- // timed out, found no provider, produced nothing or died on an
1969
- // exception left a transcript that simply broke off - and the reason
1970
- // existed only in `assignments.error`, which the log view does not
1971
- // read. Anyone opening the transcript afterwards saw an account that
1972
- // ends mid-sentence with no explanation. Now the last thing in the
1973
- // record is what happened.
1974
- const outcome = this.#store.org.getAssignment(assignment.id) ?? assignment;
1975
- this.#logPush(assignment.id, outcome.status === 'done'
1976
- ? {
1977
- type: 'status',
1978
- label: 'Done',
1979
- ...(outcome.durationMs ? { detail: Math.round(outcome.durationMs / 1000) + ' s' } : {}),
2025
+ return output;
2026
+ }
2027
+ /**
2028
+ * A visible Claude Code terminal per run, keyed by the run so the server
2029
+ * can stream it to whoever opens the run's page.
2030
+ */
2031
+ #interactiveRunOptions(assignmentId) {
2032
+ if (!this.#config.org.interactiveRuns)
2033
+ return {};
2034
+ return {
2035
+ tui: {
2036
+ key: assignmentId,
2037
+ // A person typing into the finished run's terminal
2038
+ // belongs in its transcript, not only on the screen.
2039
+ // The live buffer is gone once the run finished, so
2040
+ // these go straight into the journal the transcript
2041
+ // is read from.
2042
+ onLateEvent: (event) => this.#store.turns.append(assignmentId, event),
2043
+ },
2044
+ };
2045
+ }
2046
+ /** Route one provider event: into the live log, the parent turn's stream, the progress line, or the attempt's result. */
2047
+ #absorbProviderEvent(run, event, output) {
2048
+ const { input, record } = run;
2049
+ switch (event.type) {
2050
+ case 'text':
2051
+ this.#logPush(record.id, event);
2052
+ if (output.append(event.delta)) {
2053
+ this.#store.org.updateAssignment(record.id, { chars: output.text.length });
2054
+ record.announce({ chars: output.text.length, preview: shorten(tail(output.text, 160), 110) });
1980
2055
  }
1981
- : { type: 'error', message: outcome.status + (outcome.error ? ': ' + outcome.error : ''), fatal: true });
1982
- const log = this.#logs.get(assignment.id);
1983
- if (log) {
1984
- // The run is over: live watchers hear it from the `assignment`
1985
- // broadcast `finish()` already sent, generators end here, and the
1986
- // buffer itself is gone. The journal stays - after a run, its
1987
- // transcript remains readable instead of only the result.
1988
- log.end();
1989
- this.#logs.delete(assignment.id);
1990
- }
1991
- // What the journal says has to match what happened. It used to write
1992
- // `done` for every run that reached this line - a run that timed out,
1993
- // was cancelled or died on a fatal provider error settled as an
1994
- // orderly end, so a client rebuilding the run from the journal after
1995
- // a reload saw a clean finish where the assignment row said `failed`.
1996
- // `done` is reserved for a run that actually ended in `done`.
1997
- const settled = this.#store.org.getAssignment(assignment.id) ?? assignment;
1998
- this.#store.turns.settle(assignment.id, settled.status === 'done' ? 'done' : 'interrupted', Date.now());
1999
- this.#askedRequester.delete(assignment.id);
2000
- this.#active.delete(assignment.id);
2001
- input.signal?.removeEventListener('abort', onAbort);
2002
- this.#release();
2056
+ break;
2057
+ case 'thinking':
2058
+ this.#logPush(record.id, event);
2059
+ break;
2060
+ case 'tool':
2061
+ // The live log keeps the raw event: the `[slug]` prefix below
2062
+ // is for the parent turn's stream, not this run's own log.
2063
+ this.#logPush(record.id, event);
2064
+ input.emit({ ...event, detail: '[' + input.agent.slug + '] ' + (event.detail ?? '') });
2065
+ // A tool starting is the one moment worth telling everyone about,
2066
+ // not just the turn that started this run - the same `announce`
2067
+ // that already carries `chars`/`preview` org-wide, extended with
2068
+ // what the run is doing right now. Not persisted, same as
2069
+ // `preview`: a live-only field, gone once the run finishes.
2070
+ if (event.status === 'start') {
2071
+ record.announce({ lastActivity: { kind: 'tool', label: event.name, at: Date.now() } });
2072
+ }
2073
+ break;
2074
+ case 'done':
2075
+ output.text = event.text || output.text;
2076
+ break;
2077
+ case 'error':
2078
+ if (event.fatal) {
2079
+ this.#logPush(record.id, event);
2080
+ output.fatal = event.message;
2081
+ }
2082
+ break;
2083
+ }
2084
+ }
2085
+ /** A run that produced a report: record it, and let the agent learn from it and be judged on it. */
2086
+ #complete(run, outcome, started) {
2087
+ const { input, record } = run;
2088
+ const { text } = outcome;
2089
+ const done = record.finish({ status: 'done', result: text, chars: text.length, finishedAt: Date.now(), durationMs: Date.now() - started }, { chars: text.length, preview: shorten(tail(text, 160), 110) });
2090
+ // A scheduled assignment does not learn: its "task" is the job's own
2091
+ // prompt, written once when the schedule was created, and every firing
2092
+ // would otherwise quote it back into the bank as if it were news.
2093
+ if (this.#config.memory.enabled && this.#config.memory.autoExtract && !input.scheduled) {
2094
+ void this.#learn(input.agent, input.task, text, outcome.provider);
2003
2095
  }
2096
+ if (this.#config.org.autoReview)
2097
+ void this.#review(input.agent, done, input.task, text, outcome.provider);
2098
+ // Asked by the run itself, through `ask_requester` - nothing to infer.
2099
+ input.onAskedRequester?.(this.#askedRequester.has(record.id));
2100
+ return done;
2101
+ }
2102
+ /**
2103
+ * How it ended, written into the transcript itself.
2104
+ *
2105
+ * The journal used to stop at the last streamed line, so a run that
2106
+ * timed out, found no provider, produced nothing or died on an
2107
+ * exception left a transcript that simply broke off - and the reason
2108
+ * existed only in `assignments.error`, which the log view does not
2109
+ * read. Anyone opening the transcript afterwards saw an account that
2110
+ * ends mid-sentence with no explanation. Now the last thing in the
2111
+ * record is what happened.
2112
+ */
2113
+ #closeRun(run) {
2114
+ const { input, record } = run;
2115
+ const id = record.id;
2116
+ const outcome = this.#store.org.getAssignment(id) ?? record.assignment;
2117
+ this.#logPush(id, outcome.status === 'done'
2118
+ ? {
2119
+ type: 'status',
2120
+ label: 'Done',
2121
+ ...(outcome.durationMs ? { detail: toSeconds(outcome.durationMs) + ' s' } : {}),
2122
+ }
2123
+ : { type: 'error', message: outcome.status + (outcome.error ? ': ' + outcome.error : ''), fatal: true });
2124
+ const log = this.#logs.get(id);
2125
+ if (log) {
2126
+ // The run is over: live watchers hear it from the `assignment`
2127
+ // broadcast `finish()` already sent, generators end here, and the
2128
+ // buffer itself is gone. The journal stays - after a run, its
2129
+ // transcript remains readable instead of only the result.
2130
+ log.end();
2131
+ this.#logs.delete(id);
2132
+ }
2133
+ // What the journal says has to match what happened. It used to write
2134
+ // `done` for every run that reached this line - a run that timed out,
2135
+ // was cancelled or died on a fatal provider error settled as an
2136
+ // orderly end, so a client rebuilding the run from the journal after
2137
+ // a reload saw a clean finish where the assignment row said `failed`.
2138
+ // `done` is reserved for a run that actually ended in `done`.
2139
+ this.#store.turns.settle(id, outcome.status === 'done' ? 'done' : 'interrupted', Date.now());
2140
+ this.#askedRequester.delete(id);
2141
+ this.#active.delete(id);
2142
+ input.signal?.removeEventListener('abort', run.onAbort);
2143
+ this.#release();
2004
2144
  }
2005
2145
  /**
2006
2146
  * Stop a queued or running assignment. Returns false when nothing by that
@@ -2030,7 +2170,7 @@ export class OrgController extends EventEmitter {
2030
2170
  if (ref.length < 4)
2031
2171
  return null;
2032
2172
  const matches = this.#store.org
2033
- .listAssignments(orgId, { limit: 500 })
2173
+ .listAssignments(orgId, { limit: LOOKUP_SCAN_LIMIT })
2034
2174
  .filter((entry) => entry.id.startsWith(ref));
2035
2175
  return matches.length === 1 ? (matches[0] ?? null) : null;
2036
2176
  }
@@ -2084,44 +2224,36 @@ export class OrgController extends EventEmitter {
2084
2224
  yield* buffer.stream();
2085
2225
  }
2086
2226
  /* ------------------------------- settings ------------------------------- */
2087
- #updateSettings(context, args) {
2088
- const text = (key) => (typeof args[key] === 'string' ? args[key].trim() : '');
2089
- const fail = (message) => ({ text: message, isError: true });
2227
+ #toolUpdateSettings(context, args) {
2090
2228
  if (context.audience !== 'assistant')
2091
- return fail('Only the assistant can change settings.');
2229
+ return toolError('Only the assistant can change settings.');
2092
2230
  const patch = {};
2093
- if (text('defaultProvider')) {
2094
- const provider = this.#asProvider(text('defaultProvider'));
2231
+ const defaultProvider = args.text('defaultProvider');
2232
+ if (defaultProvider) {
2233
+ const provider = this.#asProvider(defaultProvider);
2095
2234
  if (!provider)
2096
- return fail('No provider "' + text('defaultProvider') + '". Configured: ' + this.#providerIds() + '.');
2235
+ return toolError('No provider "' + defaultProvider + '". Configured: ' + this.#providerIds() + '.');
2097
2236
  patch.defaultProvider = provider;
2098
2237
  }
2099
2238
  // An empty string clears a setting: the merge skips undefined, and
2100
2239
  // loadConfig turns '' back into "unset".
2101
- if (text('defaultModel'))
2102
- patch.defaultModel = text('defaultModel') === 'default' ? '' : text('defaultModel');
2103
- if (text('defaultEffort')) {
2104
- const effort = text('defaultEffort');
2240
+ const defaultModel = args.text('defaultModel');
2241
+ if (defaultModel)
2242
+ patch.defaultModel = defaultModel === 'default' ? '' : defaultModel;
2243
+ const effort = args.text('defaultEffort');
2244
+ if (effort) {
2105
2245
  if (effort === 'default')
2106
2246
  patch.defaultEffort = '';
2107
2247
  else if (EFFORT_LEVELS.includes(effort))
2108
2248
  patch.defaultEffort = effort;
2109
2249
  else
2110
- return fail('Effort must be one of ' + EFFORT_LEVELS.join(', ') + ', or default.');
2111
- }
2112
- const org = {};
2113
- if (args.maxConcurrentAssignments !== undefined) {
2114
- org.maxConcurrentAssignments = clampNumber(args.maxConcurrentAssignments, 1, 16, 4);
2115
- }
2116
- if (args.maxDelegationDepth !== undefined)
2117
- org.maxDelegationDepth = clampNumber(args.maxDelegationDepth, 1, 6, 3);
2118
- if (args.assignmentTimeoutMinutes !== undefined) {
2119
- org.assignmentTimeoutMs = clampNumber(args.assignmentTimeoutMinutes, 1, 600, 45) * 60 * 1000;
2250
+ return toolError('Effort must be one of ' + EFFORT_LEVELS.join(', ') + ', or default.');
2120
2251
  }
2252
+ const org = orgSettingsPatch(args);
2121
2253
  if (Object.keys(org).length)
2122
2254
  patch.org = org;
2123
2255
  if (!Object.keys(patch).length)
2124
- return fail('Nothing to change.');
2256
+ return toolError('Nothing to change.');
2125
2257
  // applyConfig writes ~/.rookery/config.json and refreshes the one config
2126
2258
  // object the runtime and the server share, dropping the keys a cleared
2127
2259
  // setting leaves behind.
@@ -2130,108 +2262,100 @@ export class OrgController extends EventEmitter {
2130
2262
  return { text: 'Settings updated.\n' + describeSettings(this.#config) };
2131
2263
  }
2132
2264
  /* ------------------------------- structure ------------------------------ */
2133
- async #updateAgent(context, args) {
2134
- const text = (key) => (typeof args[key] === 'string' ? args[key].trim() : '');
2135
- const fail = (message) => ({ text: message, isError: true });
2265
+ #toolUpdateAgent(context, args) {
2136
2266
  if (context.audience !== 'assistant')
2137
- return fail('Only the assistant can change staff.');
2138
- const agent = this.#store.org.findAgent(context.orgId, text('agent'));
2267
+ return toolError('Only the assistant can change staff.');
2268
+ const agent = this.#store.org.findAgent(context.orgId, args.text('agent'));
2139
2269
  if (!agent)
2140
- return fail('No agent "' + text('agent') + '".');
2141
- const newInstructions = text('instructions');
2270
+ return toolError(noAgent(args.text('agent')));
2271
+ const newInstructions = args.text('instructions');
2272
+ const reason = args.text('reason');
2142
2273
  // Once an agent is flagged (stage >= 1), a silent instruction change is
2143
2274
  // the exact failure `agent_actions` exists to prevent - "protocol before
2144
2275
  // effect", decision E1. Below stage 1 this is unchanged: a free
2145
2276
  // restructuring of the company is not a personnel action.
2146
2277
  if (newInstructions && newInstructions !== agent.instructions) {
2147
2278
  const stage = this.#store.org.performance(agent.id).stage;
2148
- if (stage >= 1 && !text('reason')) {
2149
- return fail(agent.name + ' is at escalation stage ' + stage + '; changing standing instructions needs a "reason" ' +
2279
+ if (stage >= 1 && !reason) {
2280
+ return toolError(agent.name + ' is at escalation stage ' + stage + '; changing standing instructions needs a "reason" ' +
2150
2281
  '(it is written to the personnel record as a reconfig). Use agent_performance to see why.');
2151
2282
  }
2152
2283
  }
2153
- const patch = {};
2154
- if (text('name'))
2155
- patch.name = text('name');
2156
- if (text('title'))
2157
- patch.title = text('title');
2158
- if (newInstructions)
2159
- patch.instructions = newInstructions;
2160
- if (text('team')) {
2161
- if (text('team').toLowerCase() === 'none')
2162
- patch.teamId = null;
2163
- else {
2164
- const team = this.#store.org.findTeam(context.orgId, text('team'));
2165
- if (!team)
2166
- return fail('No team "' + text('team') + '".');
2167
- patch.teamId = team.id;
2168
- }
2169
- }
2170
- if (text('manager')) {
2171
- if (text('manager').toLowerCase() === 'assistant')
2172
- patch.managerId = null;
2173
- else {
2174
- const manager = this.#store.org.findAgent(context.orgId, text('manager'));
2175
- if (!manager)
2176
- return fail('No agent "' + text('manager') + '".');
2177
- if (manager.id === agent.id)
2178
- return fail('An agent cannot be its own manager.');
2179
- patch.managerId = manager.id;
2180
- }
2181
- }
2182
- // An id the registry does not serve clears the preference back to the
2183
- // company default, the same way an unknown permission does below.
2184
- if (text('provider'))
2185
- patch.provider = this.#asProvider(text('provider')) ?? null;
2186
- if (text('model'))
2187
- patch.model = text('model');
2188
- if (text('permission'))
2189
- patch.permission = asPermission(text('permission')) ?? null;
2190
- if (typeof args.archived === 'boolean')
2191
- patch.archived = args.archived;
2192
- this.#store.org.updateAgent(agent.id, patch);
2284
+ const patch = this.#agentPatch(context.orgId, args, agent);
2285
+ if (!patch.ok)
2286
+ return patch.error;
2287
+ this.#store.org.updateAgent(agent.id, patch.value);
2193
2288
  // A `reason` on an instructions change is a personnel action by hand,
2194
2289
  // same rule as the automatic one in #develop: the record and the change
2195
2290
  // land together (decision E1). `stage` here is the one this reconfig
2196
2291
  // responds to, not necessarily still current a moment later.
2197
- if (patch.instructions && text('reason')) {
2292
+ if (patch.value.instructions && reason) {
2198
2293
  const stage = this.#store.org.performance(agent.id).stage;
2199
2294
  this.#store.org.createAction({
2200
2295
  orgId: context.orgId,
2201
2296
  agentId: agent.id,
2202
2297
  kind: 'reconfig',
2203
2298
  stage: Math.max(stage, 1),
2204
- reason: text('reason'),
2299
+ reason,
2205
2300
  beforeText: agent.instructions,
2206
- afterText: patch.instructions,
2301
+ afterText: patch.value.instructions,
2207
2302
  decidedBy: 'assistant',
2208
2303
  });
2209
2304
  }
2210
2305
  this.emit('changed', { kind: 'agent', id: agent.id });
2211
- return { text: 'Updated ' + agent.name + ' (' + agent.slug + '): ' + Object.keys(patch).join(', ') + '.' };
2306
+ return { text: 'Updated ' + agent.name + ' (' + agent.slug + '): ' + Object.keys(patch.value).join(', ') + '.' };
2212
2307
  }
2213
- async #updateTeam(context, args) {
2214
- const text = (key) => (typeof args[key] === 'string' ? args[key].trim() : '');
2215
- const fail = (message) => ({ text: message, isError: true });
2308
+ #agentPatch(orgId, args, agent) {
2309
+ const patch = {};
2310
+ if (args.text('name'))
2311
+ patch.name = args.text('name');
2312
+ if (args.text('title'))
2313
+ patch.title = args.text('title');
2314
+ if (args.text('instructions'))
2315
+ patch.instructions = args.text('instructions');
2316
+ if (args.text('team')) {
2317
+ const team = resolveClearable(args.text('team'), ['none'], (ref) => this.#store.org.findTeam(orgId, ref), noTeam);
2318
+ if (!team.ok)
2319
+ return team;
2320
+ patch.teamId = team.value;
2321
+ }
2322
+ if (args.text('manager')) {
2323
+ const manager = resolveClearable(args.text('manager'), ['assistant'], (ref) => this.#store.org.findAgent(orgId, ref), noAgent);
2324
+ if (!manager.ok)
2325
+ return manager;
2326
+ if (manager.value === agent.id)
2327
+ return { ok: false, error: toolError('An agent cannot be its own manager.') };
2328
+ patch.managerId = manager.value;
2329
+ }
2330
+ // An id the registry does not serve clears the preference back to the
2331
+ // company default, the same way an unknown permission does below.
2332
+ if (args.text('provider'))
2333
+ patch.provider = this.#asProvider(args.text('provider')) ?? null;
2334
+ if (args.text('model'))
2335
+ patch.model = args.text('model');
2336
+ if (args.text('permission'))
2337
+ patch.permission = asPermission(args.text('permission')) ?? null;
2338
+ const archived = args.flag('archived');
2339
+ if (archived !== undefined)
2340
+ patch.archived = archived;
2341
+ return { ok: true, value: patch };
2342
+ }
2343
+ #toolUpdateTeam(context, args) {
2216
2344
  if (context.audience !== 'assistant')
2217
- return fail('Only the assistant can change teams.');
2218
- const team = this.#store.org.findTeam(context.orgId, text('team'));
2345
+ return toolError('Only the assistant can change teams.');
2346
+ const team = this.#store.org.findTeam(context.orgId, args.text('team'));
2219
2347
  if (!team)
2220
- return fail('No team "' + text('team') + '".');
2348
+ return toolError(noTeam(args.text('team')));
2221
2349
  const patch = {};
2222
- if (text('name'))
2223
- patch.name = text('name');
2224
- if (text('purpose'))
2225
- patch.purpose = text('purpose');
2226
- if (text('lead')) {
2227
- if (text('lead').toLowerCase() === 'none')
2228
- patch.leadId = null;
2229
- else {
2230
- const lead = this.#store.org.findAgent(context.orgId, text('lead'));
2231
- if (!lead)
2232
- return fail('No agent "' + text('lead') + '".');
2233
- patch.leadId = lead.id;
2234
- }
2350
+ if (args.text('name'))
2351
+ patch.name = args.text('name');
2352
+ if (args.text('purpose'))
2353
+ patch.purpose = args.text('purpose');
2354
+ if (args.text('lead')) {
2355
+ const lead = resolveClearable(args.text('lead'), ['none'], (ref) => this.#store.org.findAgent(context.orgId, ref), noAgent);
2356
+ if (!lead.ok)
2357
+ return lead.error;
2358
+ patch.leadId = lead.value;
2235
2359
  }
2236
2360
  this.#store.org.updateTeam(team.id, patch);
2237
2361
  this.emit('changed', { kind: 'team', id: team.id });
@@ -2246,40 +2370,24 @@ export class OrgController extends EventEmitter {
2246
2370
  const exact = this.#store.org.getTask(wanted);
2247
2371
  if (exact && exact.orgId === orgId)
2248
2372
  return exact;
2249
- const matches = this.#store.org.listAllTasks(orgId, 500).filter((task) => task.id.startsWith(wanted));
2373
+ const matches = this.#store.org.listAllTasks(orgId, LOOKUP_SCAN_LIMIT).filter((task) => task.id.startsWith(wanted));
2250
2374
  return matches.length === 1 ? (matches[0] ?? null) : null;
2251
2375
  }
2252
- async #updateTask(context, args) {
2253
- const text = (key) => (typeof args[key] === 'string' ? args[key].trim() : '');
2254
- const fail = (message) => ({ text: message, isError: true });
2255
- const task = this.findTask(context.orgId, text('id'));
2376
+ async #toolUpdateTask(context, args) {
2377
+ const task = this.findTask(context.orgId, args.text('id'));
2256
2378
  if (!task)
2257
- return fail('No task ' + text('id') + '.');
2379
+ return toolError('No task ' + args.text('id') + '.');
2258
2380
  if (task.status === 'running') {
2259
2381
  // The one edit allowed mid-run: pulling the plug. The run loop writes
2260
2382
  // the final status itself once its assignments have stopped.
2261
- if (text('status') === 'cancelled' && this.cancelTask(task.id)) {
2383
+ if (args.text('status') === 'cancelled' && this.cancelTask(task.id)) {
2262
2384
  return { text: 'Cancelling task "' + task.title + '" and everything it started.' };
2263
2385
  }
2264
- return fail('The task is running; wait for it to finish, or cancel it with status "cancelled".');
2265
- }
2266
- const patch = {};
2267
- if (text('title'))
2268
- patch.title = text('title');
2269
- if (text('description'))
2270
- patch.description = text('description');
2271
- if (text('priority'))
2272
- patch.priority = asPriority(text('priority'));
2273
- if (text('assignee')) {
2274
- if (text('assignee').toLowerCase() === 'none')
2275
- patch.assigneeId = null;
2276
- else {
2277
- const agent = this.#store.org.findAgent(context.orgId, text('assignee'));
2278
- if (!agent)
2279
- return fail('No agent "' + text('assignee') + '".');
2280
- patch.assigneeId = agent.id;
2281
- }
2386
+ return toolError('The task is running; wait for it to finish, or cancel it with status "cancelled".');
2282
2387
  }
2388
+ const patch = this.#taskPatch(context.orgId, args);
2389
+ if (!patch.ok)
2390
+ return patch.error;
2283
2391
  // The status goes through `setTaskStatus`, which is what makes this tool
2284
2392
  // record on the card what it did and tell whoever is owed the ending -
2285
2393
  // closing a task from here used to leave whoever was waiting waiting for
@@ -2289,31 +2397,48 @@ export class OrgController extends EventEmitter {
2289
2397
  // the other edits standing and unannounced: the caller read "that is not
2290
2398
  // allowed", believed nothing had happened, and the card had quietly lost
2291
2399
  // its assignee in an open browser that was never told.
2292
- const fields = Object.keys(patch);
2293
- const status = text('status');
2400
+ const fields = Object.keys(patch.value);
2401
+ const status = args.text('status');
2294
2402
  const settable = status === 'open' || status === 'done' || status === 'cancelled' || status === 'blocked';
2295
2403
  if (!settable && !fields.length)
2296
- return fail('Nothing to change.');
2404
+ return toolError('Nothing to change.');
2297
2405
  if (settable) {
2406
+ const result = args.text('result');
2298
2407
  const moved = await this.setTaskStatus({
2299
2408
  task,
2300
2409
  to: status,
2301
- by: context.audience === 'agent' ? 'agent' : 'assistant',
2302
- ...(text('result') ? { result: text('result') } : {}),
2410
+ by: callerKind(context),
2411
+ ...(result ? { result } : {}),
2303
2412
  emit: context.emit,
2304
2413
  });
2305
2414
  if (!moved.ok)
2306
- return fail(moved.reason);
2415
+ return toolError(moved.reason);
2307
2416
  }
2308
2417
  if (fields.length)
2309
- this.#store.org.updateTask(task.id, patch);
2310
- const edited = this.#store.org.getTask(task.id) ?? task;
2418
+ this.#store.org.updateTask(task.id, patch.value);
2419
+ const edited = this.#current(task);
2311
2420
  this.#announceTask(edited, context.emit);
2312
2421
  return {
2313
2422
  text: 'Updated task "' + edited.title + '": ' +
2314
2423
  [...fields, ...(settable ? ['status'] : [])].join(', ') + '.',
2315
2424
  };
2316
2425
  }
2426
+ #taskPatch(orgId, args) {
2427
+ const patch = {};
2428
+ if (args.text('title'))
2429
+ patch.title = args.text('title');
2430
+ if (args.text('description'))
2431
+ patch.description = args.text('description');
2432
+ if (args.text('priority'))
2433
+ patch.priority = asPriority(args.text('priority'));
2434
+ if (args.text('assignee')) {
2435
+ const assignee = resolveClearable(args.text('assignee'), ['none'], (ref) => this.#store.org.findAgent(orgId, ref), noAgent);
2436
+ if (!assignee.ok)
2437
+ return assignee;
2438
+ patch.assigneeId = assignee.value;
2439
+ }
2440
+ return { ok: true, value: patch };
2441
+ }
2317
2442
  /**
2318
2443
  * Plan a task: ask the planner, then write the decision to the board as an
2319
2444
  * assignee or as subtasks. Existing unfinished subtasks are cancelled first,
@@ -2331,41 +2456,47 @@ export class OrgController extends EventEmitter {
2331
2456
  hint,
2332
2457
  signal: context.signal,
2333
2458
  });
2334
- for (const child of this.#store.org.listTasks(context.orgId, { parentId: task.id })) {
2459
+ this.#cancelUnfinishedSubtasks(context.orgId, task.id);
2460
+ this.#applyPlan(context, task, plan, snapshot.agents);
2461
+ this.#announceTask(this.#current(task), context.emit);
2462
+ return plan;
2463
+ }
2464
+ #cancelUnfinishedSubtasks(orgId, parentId) {
2465
+ for (const child of this.#store.org.listTasks(orgId, { parentId })) {
2335
2466
  if (child.status === 'open' || child.status === 'planned') {
2336
2467
  this.#store.org.updateTask(child.id, { status: 'cancelled', finishedAt: Date.now() });
2337
2468
  }
2338
2469
  }
2339
- const bySlug = new Map(snapshot.agents.map((agent) => [agent.slug, agent]));
2340
- if (plan.mode === 'split') {
2341
- const created = [];
2342
- for (const subtask of plan.subtasks) {
2343
- const child = this.#store.org.createTask({
2344
- orgId: context.orgId,
2345
- parentId: task.id,
2346
- projectId: task.projectId,
2347
- title: subtask.title,
2348
- description: subtask.description,
2349
- priority: task.priority,
2350
- assigneeId: bySlug.get(subtask.agent)?.id,
2351
- createdBy: 'assistant',
2352
- dependsOn: subtask.dependsOn.map((index) => created[index]?.id ?? '').filter(Boolean),
2353
- status: 'planned',
2354
- });
2355
- created.push(child);
2356
- this.#announceTask(child, context.emit);
2357
- }
2358
- this.#store.org.updateTask(task.id, { status: 'planned', planNote: plan.reason, assigneeId: null });
2359
- }
2360
- else {
2470
+ }
2471
+ /** Write the planner's decision to the board: subtasks for a split, an assignee for a single task. */
2472
+ #applyPlan(context, task, plan, agents) {
2473
+ const bySlug = new Map(agents.map((agent) => [agent.slug, agent]));
2474
+ if (plan.mode !== 'split') {
2361
2475
  this.#store.org.updateTask(task.id, {
2362
2476
  status: 'planned',
2363
2477
  planNote: plan.reason,
2364
2478
  assigneeId: plan.assignee ? (bySlug.get(plan.assignee)?.id ?? null) : null,
2365
2479
  });
2480
+ return;
2366
2481
  }
2367
- this.#announceTask(this.#store.org.getTask(task.id) ?? task, context.emit);
2368
- return plan;
2482
+ const created = [];
2483
+ for (const subtask of plan.subtasks) {
2484
+ const child = this.#store.org.createTask({
2485
+ orgId: context.orgId,
2486
+ parentId: task.id,
2487
+ projectId: task.projectId,
2488
+ title: subtask.title,
2489
+ description: subtask.description,
2490
+ priority: task.priority,
2491
+ assigneeId: bySlug.get(subtask.agent)?.id,
2492
+ createdBy: 'assistant',
2493
+ dependsOn: subtask.dependsOn.map((index) => created[index]?.id ?? '').filter(Boolean),
2494
+ status: 'planned',
2495
+ });
2496
+ created.push(child);
2497
+ this.#announceTask(child, context.emit);
2498
+ }
2499
+ this.#store.org.updateTask(task.id, { status: 'planned', planNote: plan.reason, assigneeId: null });
2369
2500
  }
2370
2501
  /**
2371
2502
  * Run a task to completion. Unplanned tasks are planned first. Subtasks
@@ -2373,15 +2504,13 @@ export class OrgController extends EventEmitter {
2373
2504
  * reports. Never throws; the returned task says how it ended.
2374
2505
  */
2375
2506
  async runTask(outer, task) {
2376
- const org = this.#store.org;
2377
- const reload = () => org.getTask(task.id) ?? task;
2378
2507
  // A task's row only says `running` once planning has finished, and
2379
2508
  // planning awaits - so two first invocations (a double-click before the
2380
2509
  // first scheduling) both read a not-yet-running row and both plan. The
2381
2510
  // claim on `#activeTasks` below is written before the first await, which
2382
2511
  // makes it the one check a concurrent invocation cannot slip past.
2383
- if (this.#activeTasks.has(task.id) || reload().status === 'running')
2384
- return reload();
2512
+ if (this.#activeTasks.has(task.id) || this.#current(task).status === 'running')
2513
+ return this.#current(task);
2385
2514
  // The run gets its own abort controller so cancelTask() can stop it
2386
2515
  // without touching the caller's turn; the caller's signal feeds into it.
2387
2516
  const controller = new AbortController();
@@ -2398,7 +2527,7 @@ export class OrgController extends EventEmitter {
2398
2527
  // Every ending of every run passes here, thrown or not, so this is the
2399
2528
  // one place a report-back can be neither forgotten nor sent twice.
2400
2529
  this.#detached.delete(task.id);
2401
- this.#reportBack(reload());
2530
+ this.#reportBack(this.#current(task));
2402
2531
  }
2403
2532
  }
2404
2533
  /**
@@ -2436,11 +2565,8 @@ export class OrgController extends EventEmitter {
2436
2565
  * runtime's to fall back from: it turns the event into a notification.
2437
2566
  */
2438
2567
  #reportBack(task) {
2439
- if (!task.requesterSessionId || task.parentId || this.#awaited.has(task.id))
2440
- return;
2441
- if (task.status !== 'done' && task.status !== 'failed' && task.status !== 'cancelled' && task.status !== 'blocked') {
2568
+ if (!task.requesterSessionId || task.parentId || this.#awaited.has(task.id) || !isEnding(task.status))
2442
2569
  return;
2443
- }
2444
2570
  const agent = task.assigneeId ? this.#store.org.getAgent(task.assigneeId) : null;
2445
2571
  const event = {
2446
2572
  sessionId: task.requesterSessionId,
@@ -2465,25 +2591,15 @@ export class OrgController extends EventEmitter {
2465
2591
  this.#detached.delete(task.id);
2466
2592
  return outcome;
2467
2593
  }
2468
- const entries = [...pending.entries()];
2594
+ const handedOff = [...pending.entries()];
2469
2595
  pending.clear();
2470
- const cancelAll = () => {
2471
- for (const [id] of entries)
2472
- this.cancelTask(id);
2473
- };
2474
2596
  if (context.signal?.aborted || outcome.status === 'cancelled') {
2475
- cancelAll();
2597
+ for (const [id] of handedOff)
2598
+ this.cancelTask(id);
2476
2599
  this.#detached.delete(task.id);
2477
2600
  return outcome;
2478
2601
  }
2479
- context.signal?.addEventListener('abort', cancelAll, { once: true });
2480
- let children;
2481
- try {
2482
- children = await Promise.all(entries.map(([, promise]) => promise));
2483
- }
2484
- finally {
2485
- context.signal?.removeEventListener('abort', cancelAll);
2486
- }
2602
+ const children = await this.#awaitHandedOff(context.signal, handedOff);
2487
2603
  // Cancelled while it waited: the task ends cancelled, not with the
2488
2604
  // interim report it had written before the work came back.
2489
2605
  if (context.signal?.aborted) {
@@ -2495,42 +2611,56 @@ export class OrgController extends EventEmitter {
2495
2611
  // over the question or the failure. Nor is one past either ceiling.
2496
2612
  // A child that came back with a question then has nobody left to ask
2497
2613
  // it of, and a question is never silent: it goes to the user.
2498
- const current = children.map((child) => this.#store.org.getTask(child.id) ?? child);
2499
- if (outcome.status !== 'done' ||
2500
- outcome.askedRequester ||
2501
- round >= MAX_DELEGATION_ROUNDS ||
2502
- this.#store.org.taskRunCount(task.id) >= this.#config.org.maxTaskRuns) {
2614
+ const current = children.map((child) => this.#current(child));
2615
+ const mayPickUp = outcome.status === 'done' &&
2616
+ !outcome.askedRequester &&
2617
+ round < MAX_DELEGATION_ROUNDS &&
2618
+ this.#store.org.taskRunCount(task.id) < this.#config.org.maxTaskRuns;
2619
+ if (!mayPickUp) {
2503
2620
  for (const child of current)
2504
2621
  if (child.status === 'blocked')
2505
2622
  this.#escalateQuestion(child);
2506
2623
  continue;
2507
2624
  }
2508
- const results = current
2509
- .map((child) => {
2510
- const who = child.assigneeId ? (this.#store.org.getAgent(child.assigneeId)?.slug ?? 'agent') : 'agent';
2511
- const head = '### ' + child.title + ' (' + who + ', ' + child.status + ', task ' + child.id.slice(0, 8) + ')\n';
2512
- if (child.status === 'blocked') {
2513
- // R4 meets ask_requester: the child asked its requester, and the
2514
- // requester is this run. The question comes back here with the
2515
- // results, and answering it carries the child on.
2516
- const question = this.#questionFor(child);
2517
- return (head + 'It stopped with a question for you:\n' + clip(question ?? child.result ?? '(no text)', 6000) +
2518
- '\nAnswer it with answer_task("' + child.id.slice(0, 8) + '", ...) - it then carries on in the ' +
2519
- 'background, and you are started again once it is back. If you cannot answer it, say so in your ' +
2520
- 'report instead.');
2521
- }
2522
- return head + clip(child.result ?? (child.error ? 'FAILED: ' + child.error : 'no output'), 6000);
2523
- })
2524
- .join('\n\n');
2525
- const note = 'The work you handed off in the background while doing this task has come back:\n\n' + results +
2526
- '\n\nYour own report from before it came back:\n' + clip(outcome.result ?? '', 6000) +
2625
+ const note = 'The work you handed off in the background while doing this task has come back:\n\n' +
2626
+ current.map((child) => this.#handedOffReport(child)).join('\n\n') +
2627
+ '\n\nYour own report from before it came back:\n' + clip(outcome.result ?? '', CHILD_REPORT_BUDGET) +
2527
2628
  '\n\nPick the task back up with these results and finish it. What you answer now is the final report.';
2528
- outcome = await this.#runTaskLeaf({ ...context, taskNote: note }, this.#store.org.getTask(task.id) ?? task, agent);
2629
+ outcome = await this.#runTaskLeaf({ ...context, taskNote: note }, this.#current(task), agent);
2630
+ }
2631
+ }
2632
+ /** Wait for work handed off in the background; an abort of the waiter calls all of it off. */
2633
+ async #awaitHandedOff(signal, handedOff) {
2634
+ const cancelAll = () => {
2635
+ for (const [id] of handedOff)
2636
+ this.cancelTask(id);
2637
+ };
2638
+ signal?.addEventListener('abort', cancelAll, { once: true });
2639
+ try {
2640
+ return await Promise.all(handedOff.map(([, promise]) => promise));
2641
+ }
2642
+ finally {
2643
+ signal?.removeEventListener('abort', cancelAll);
2644
+ }
2645
+ }
2646
+ /** One handed-off child as its parent reads it when the work is back. */
2647
+ #handedOffReport(child) {
2648
+ const who = child.assigneeId ? (this.#store.org.getAgent(child.assigneeId)?.slug ?? 'agent') : 'agent';
2649
+ const head = '### ' + child.title + ' (' + who + ', ' + child.status + ', task ' + shortId(child.id) + ')\n';
2650
+ if (child.status === 'blocked') {
2651
+ // R4 meets ask_requester: the child asked its requester, and the
2652
+ // requester is this run. The question comes back here with the
2653
+ // results, and answering it carries the child on.
2654
+ const question = this.#questionFor(child);
2655
+ return (head + 'It stopped with a question for you:\n' + clip(question ?? child.result ?? '(no text)', CHILD_REPORT_BUDGET) +
2656
+ '\nAnswer it with answer_task("' + shortId(child.id) + '", ...) - it then carries on in the ' +
2657
+ 'background, and you are started again once it is back. If you cannot answer it, say so in your ' +
2658
+ 'report instead.');
2529
2659
  }
2660
+ return head + clip(child.result ?? (child.error ? 'FAILED: ' + child.error : 'no output'), CHILD_REPORT_BUDGET);
2530
2661
  }
2531
2662
  async #runTask(context, task) {
2532
2663
  const org = this.#store.org;
2533
- const reload = () => org.getTask(task.id) ?? task;
2534
2664
  const started = Date.now();
2535
2665
  // How a run ends is the card's business, not an HTTP route's: every
2536
2666
  // ending passes here, and `setTaskStatus` records it and decides who is
@@ -2541,15 +2671,14 @@ export class OrgController extends EventEmitter {
2541
2671
  // inside rather than having to cancel first.
2542
2672
  const finish = async (status, patch) => {
2543
2673
  const moved = await this.setTaskStatus({
2544
- task: reload(),
2674
+ task: this.#current(task),
2545
2675
  to: status,
2546
2676
  by: task.createdBy,
2547
2677
  fromRun: true,
2548
- since: started,
2549
2678
  emit: context.emit,
2550
2679
  ...patch,
2551
2680
  });
2552
- return moved.ok ? moved.task : reload();
2681
+ return moved.ok ? moved.task : this.#current(task);
2553
2682
  };
2554
2683
  try {
2555
2684
  // Planning belongs inside the guard. It ran before it once, so a
@@ -2559,17 +2688,17 @@ export class OrgController extends EventEmitter {
2559
2688
  // explanation. The claim below is what makes the card `running`, and
2560
2689
  // it is atomic: a status write that slips in between the read above
2561
2690
  // and this line loses, rather than being silently overwritten.
2562
- let children = org.listTasks(context.orgId, { parentId: task.id }).filter((c) => c.status !== 'cancelled');
2563
- if (!children.length && !reload().assigneeId) {
2564
- await this.planTask(context, reload());
2565
- children = org.listTasks(context.orgId, { parentId: task.id }).filter((c) => c.status !== 'cancelled');
2691
+ let children = this.#liveSubtasks(context.orgId, task.id);
2692
+ if (!children.length && !this.#current(task).assigneeId) {
2693
+ await this.planTask(context, this.#current(task));
2694
+ children = this.#liveSubtasks(context.orgId, task.id);
2566
2695
  }
2567
2696
  if (!org.claimTaskForRun(task.id, started)) {
2568
2697
  // Somebody finished or cancelled it while this was getting ready.
2569
- return reload();
2698
+ return this.#current(task);
2570
2699
  }
2571
- this.#announceTask(reload(), context.emit);
2572
- return await this.#runTaskBody(context, task, children, finish, started);
2700
+ this.#announceTask(this.#current(task), context.emit);
2701
+ return await this.#runTaskBody(context, task, children, finish);
2573
2702
  }
2574
2703
  catch (error) {
2575
2704
  // The card claims to be running and nothing is. Left like that it can
@@ -2585,60 +2714,66 @@ export class OrgController extends EventEmitter {
2585
2714
  catch {
2586
2715
  // Even the status write failed. The column is the last thing that
2587
2716
  // can still be made true, so it is written directly.
2588
- org.updateTask(task.id, { status: 'failed', error: message, finishedAt: Date.now() });
2589
- return reload();
2717
+ this.#markEnded(task.id, { status: 'failed', error: message });
2718
+ return this.#current(task);
2590
2719
  }
2591
2720
  }
2592
2721
  }
2722
+ /** The subtasks of a task that still count: everything but the cancelled. */
2723
+ #liveSubtasks(orgId, parentId) {
2724
+ return this.#store.org.listTasks(orgId, { parentId }).filter((child) => child.status !== 'cancelled');
2725
+ }
2593
2726
  /**
2594
2727
  * The body of one task run, split out only so `#runTask` can wrap the
2595
2728
  * whole of it - planning, waves and all - in a single catch.
2596
2729
  */
2597
- async #runTaskBody(context, task, children, finish, started) {
2598
- const org = this.#store.org;
2599
- const reload = () => org.getTask(task.id) ?? task;
2600
- if (!children.length) {
2601
- const current = reload();
2602
- const agent = current.assigneeId ? org.getAgent(current.assigneeId) : null;
2603
- if (!agent)
2604
- return await finish('failed', { error: 'Nobody is assigned and nobody could be found to do it.' });
2605
- const leaf = await this.#runTaskLeaf(context, current, agent);
2606
- const outcome = await this.#awaitDelegated(context, current, agent, leaf);
2607
- return await finish(taskStatusFor(outcome), { result: outcome.result, error: outcome.error });
2608
- }
2609
- const waves = buildTaskWaves(children.filter((c) => c.status !== 'done'));
2730
+ async #runTaskBody(context, task, children, finish) {
2731
+ if (!children.length)
2732
+ return await this.#runUnsplitTask(context, task, finish);
2610
2733
  // The note that continued the parent is the parent's; each subtask runs
2611
2734
  // on its own brief. The parent speaks for the split once, below, with
2612
2735
  // the combined result.
2613
2736
  const waveContext = { ...context, taskNote: undefined };
2614
- for (const wave of waves) {
2737
+ for (const wave of buildTaskWaves(children.filter((child) => child.status !== 'done'))) {
2615
2738
  if (waveContext.signal?.aborted)
2616
2739
  break;
2617
2740
  await Promise.all(wave.map((child) => this.#runSubtask(waveContext, child)));
2618
2741
  }
2619
- const all = org.listTasks(context.orgId, { parentId: task.id }).filter((c) => c.status !== 'cancelled');
2620
- const failed = all.filter((c) => c.status === 'failed');
2621
- const combined = all
2622
- .map((c) => {
2623
- const agent = c.assigneeId ? org.getAgent(c.assigneeId) : null;
2624
- const head = '### ' + c.title + ' (' + (agent?.slug ?? 'unassigned') + ', ' + c.status + ')';
2625
- return head + '\n' + (c.result ?? (c.error ? 'FAILED: ' + c.error : 'no output'));
2742
+ const outcome = this.#splitOutcome(this.#liveSubtasks(context.orgId, task.id), Boolean(context.signal?.aborted));
2743
+ return await finish(outcome.status, { result: outcome.result, error: outcome.error });
2744
+ }
2745
+ /** A task that was not split: its assignee does the whole of it. */
2746
+ async #runUnsplitTask(context, task, finish) {
2747
+ const current = this.#current(task);
2748
+ const agent = current.assigneeId ? this.#store.org.getAgent(current.assigneeId) : null;
2749
+ if (!agent)
2750
+ return await finish('failed', { error: 'Nobody is assigned and nobody could be found to do it.' });
2751
+ const leaf = await this.#runTaskLeaf(context, current, agent);
2752
+ const outcome = await this.#awaitDelegated(context, current, agent, leaf);
2753
+ return await finish(taskStatusFor(outcome), { result: outcome.result, error: outcome.error });
2754
+ }
2755
+ /** How a split task ended, from where its subtasks ended up, with their reports side by side. */
2756
+ #splitOutcome(subtasks, aborted) {
2757
+ const failed = subtasks.filter((child) => child.status === 'failed');
2758
+ const result = subtasks
2759
+ .map((child) => {
2760
+ const agent = child.assigneeId ? this.#store.org.getAgent(child.assigneeId) : null;
2761
+ const head = '### ' + child.title + ' (' + (agent?.slug ?? 'unassigned') + ', ' + child.status + ')';
2762
+ return head + '\n' + (child.result ?? (child.error ? 'FAILED: ' + child.error : 'no output'));
2626
2763
  })
2627
2764
  .join('\n\n');
2628
- const outcome = context.signal?.aborted
2629
- ? { status: 'cancelled', result: combined }
2630
- : failed.length === all.length
2631
- ? { status: 'failed', error: 'Every subtask failed.', result: combined }
2632
- : {
2633
- status: 'done',
2634
- result: combined,
2635
- error: failed.length ? failed.length + ' of ' + all.length + ' subtasks failed.' : undefined,
2636
- };
2637
- return await finish(outcome.status, { result: outcome.result, error: outcome.error });
2765
+ if (aborted)
2766
+ return { status: 'cancelled', result };
2767
+ if (failed.length === subtasks.length)
2768
+ return { status: 'failed', error: 'Every subtask failed.', result };
2769
+ return {
2770
+ status: 'done',
2771
+ result,
2772
+ error: failed.length ? failed.length + ' of ' + subtasks.length + ' subtasks failed.' : undefined,
2773
+ };
2638
2774
  }
2639
2775
  /** One subtask inside a wave: mark it, run its leaf, record the outcome. */
2640
2776
  async #runSubtask(outer, child) {
2641
- const org = this.#store.org;
2642
2777
  // A subtask gets its own controller in `#activeTasks`, exactly like the
2643
2778
  // task above it. Without one, `cancelTask(childId)` found nothing and
2644
2779
  // returned false, so a single stuck child of a five-way split could not
@@ -2656,8 +2791,8 @@ export class OrgController extends EventEmitter {
2656
2791
  // Same rule as the parent: a child must never be left claiming to run.
2657
2792
  const message = error.message;
2658
2793
  this.#log.warn('Subtask run failed', { task: child.id, error: message });
2659
- org.updateTask(child.id, { status: 'failed', error: message, finishedAt: Date.now() });
2660
- this.#announceTask(org.getTask(child.id) ?? child, context.emit);
2794
+ this.#markEnded(child.id, { status: 'failed', error: message });
2795
+ this.#announceTask(this.#current(child), context.emit);
2661
2796
  }
2662
2797
  finally {
2663
2798
  this.#activeTasks.delete(child.id);
@@ -2666,69 +2801,63 @@ export class OrgController extends EventEmitter {
2666
2801
  }
2667
2802
  }
2668
2803
  async #runSubtaskBody(context, child) {
2669
- const org = this.#store.org;
2670
- const agent = child.assigneeId ? org.getAgent(child.assigneeId) : null;
2671
- org.updateTask(child.id, { status: 'running', startedAt: Date.now() });
2672
- this.#announceTask(org.getTask(child.id) ?? child, context.emit);
2673
- if (context.signal?.aborted) {
2674
- org.updateTask(child.id, { status: 'cancelled', finishedAt: Date.now() });
2675
- }
2676
- else if (!agent) {
2677
- org.updateTask(child.id, { status: 'failed', error: 'No assignee.', finishedAt: Date.now() });
2678
- }
2679
- else {
2680
- const deps = child.dependsOn.map((id) => org.getTask(id)).filter((t) => Boolean(t));
2681
- // A dependency that ended failed or cancelled used to be silently
2682
- // dropped (no result), and this subtask ran on a basis it never saw.
2683
- // It fails with the reason instead, the way a missing assignee does;
2684
- // the parent's summary then carries the failure. A dependency that is
2685
- // merely not finished yet (a cycle released in one wave) is not broken
2686
- // here - it stays dropped from the inputs, as before.
2687
- const broken = deps.filter((t) => t.status === 'failed' || t.status === 'cancelled');
2688
- if (broken.length) {
2689
- org.updateTask(child.id, {
2690
- status: 'failed',
2691
- error: 'Dependency did not finish: ' + broken.map((t) => t.title).join(', ') + '.',
2692
- finishedAt: Date.now(),
2693
- });
2694
- }
2695
- else {
2696
- // A subtask's agent may hand work on in the background as well; the
2697
- // subtask is not done before that work is back (R4).
2698
- const leaf = await this.#runTaskLeaf(context, child, agent, deps.filter((t) => t.result));
2699
- const outcome = await this.#awaitDelegated(context, child, agent, leaf);
2700
- org.updateTask(child.id, {
2701
- status: taskStatusFor(outcome),
2702
- result: outcome.result,
2703
- error: outcome.error,
2704
- finishedAt: Date.now(),
2705
- });
2706
- }
2707
- }
2708
- const ended = org.getTask(child.id) ?? child;
2804
+ this.#store.org.updateTask(child.id, { status: 'running', startedAt: Date.now() });
2805
+ this.#announceTask(this.#current(child), context.emit);
2806
+ await this.#carryOutSubtask(context, child);
2807
+ const ended = this.#current(child);
2709
2808
  this.#announceTask(ended, context.emit);
2710
2809
  // A subtask's ending is written straight to its row above - the parent's
2711
2810
  // loop owns it - but it still goes on the card, and a question on it
2712
2811
  // still has to reach somebody: the split's parent only collects results.
2713
- if (ended.status === 'done' || ended.status === 'failed' || ended.status === 'cancelled' || ended.status === 'blocked') {
2812
+ if (isEnding(ended.status)) {
2714
2813
  this.#recordStatus(ended, 'system');
2715
2814
  this.#deliverEnding(ended, ended.status, { by: 'assistant', fromRun: true });
2716
2815
  }
2717
2816
  }
2817
+ /** Run the subtask's leaf - or refuse it - and write how that ended onto its row. */
2818
+ async #carryOutSubtask(context, child) {
2819
+ const org = this.#store.org;
2820
+ if (context.signal?.aborted)
2821
+ return this.#markEnded(child.id, { status: 'cancelled' });
2822
+ const agent = child.assigneeId ? org.getAgent(child.assigneeId) : null;
2823
+ if (!agent)
2824
+ return this.#markEnded(child.id, { status: 'failed', error: 'No assignee.' });
2825
+ const deps = child.dependsOn.map((id) => org.getTask(id)).filter((dep) => Boolean(dep));
2826
+ // A dependency that ended failed or cancelled used to be silently
2827
+ // dropped (no result), and this subtask ran on a basis it never saw.
2828
+ // It fails with the reason instead, the way a missing assignee does;
2829
+ // the parent's summary then carries the failure. A dependency that is
2830
+ // merely not finished yet (a cycle released in one wave) is not broken
2831
+ // here - it stays dropped from the inputs, as before.
2832
+ const broken = deps.filter((dep) => dep.status === 'failed' || dep.status === 'cancelled');
2833
+ if (broken.length) {
2834
+ return this.#markEnded(child.id, {
2835
+ status: 'failed',
2836
+ error: 'Dependency did not finish: ' + broken.map((dep) => dep.title).join(', ') + '.',
2837
+ });
2838
+ }
2839
+ // A subtask's agent may hand work on in the background as well; the
2840
+ // subtask is not done before that work is back (R4).
2841
+ const leaf = await this.#runTaskLeaf(context, child, agent, deps.filter((dep) => dep.result));
2842
+ const outcome = await this.#awaitDelegated(context, child, agent, leaf);
2843
+ this.#markEnded(child.id, { status: taskStatusFor(outcome), result: outcome.result, error: outcome.error });
2844
+ }
2845
+ /** Write a task's final status straight onto its row, stamped as finished now. */
2846
+ #markEnded(taskId, patch) {
2847
+ this.#store.org.updateTask(taskId, { ...patch, finishedAt: Date.now() });
2848
+ }
2849
+ /** The task as the store has it now; the one passed in when it has gone. */
2850
+ #current(task) {
2851
+ return this.#store.org.getTask(task.id) ?? task;
2852
+ }
2718
2853
  /** The card's own line about where it now stands. */
2719
2854
  #recordStatus(task, actor) {
2720
- if (task.status !== 'done' && task.status !== 'failed' && task.status !== 'cancelled' && task.status !== 'blocked') {
2855
+ if (!isEnding(task.status))
2721
2856
  return;
2722
- }
2723
2857
  this.#taskEvent({ taskId: task.id, kind: 'status', actorKind: actor, text: statusNote(task, task.status) });
2724
2858
  }
2725
2859
  /** One task, one agent, one assignment. */
2726
2860
  async #runTaskLeaf(context, task, agent, deps = []) {
2727
- const prior = deps.length
2728
- ? 'Results of the subtasks this one depends on:\n\n' +
2729
- deps.map((dep) => '### ' + dep.title + '\n' + clip(dep.result ?? '', 6000)).join('\n\n') +
2730
- '\n\n---\n\n'
2731
- : '';
2732
2861
  // What continued the task comes after the work order: the order is what
2733
2862
  // the task is, the note is what changed about it.
2734
2863
  const note = context.taskNote ? '\n\n---\n\n' + context.taskNote : '';
@@ -2745,7 +2874,7 @@ export class OrgController extends EventEmitter {
2745
2874
  // line, so heading the brief with it says the same thing twice - and
2746
2875
  // the agent reads the repetition as emphasis that was never meant.
2747
2876
  // Only a title that adds something gets a heading.
2748
- task: prior + briefFor(task) + note,
2877
+ task: dependencyResults(deps) + briefFor(task) + note,
2749
2878
  projectId: task.projectId ?? context.projectId,
2750
2879
  sessionId: context.sessionId,
2751
2880
  parentId: context.parentAssignmentId,
@@ -2782,10 +2911,7 @@ export class OrgController extends EventEmitter {
2782
2911
  kind: 'run-ended',
2783
2912
  actorKind: 'agent',
2784
2913
  actorAgentId: agent.id,
2785
- text: 'Run ' + runNumber + ' ' + (askedRequester && assignment.status === 'done' ? 'ended with a question' : assignment.status) +
2786
- (assignment.durationMs !== undefined ? ' after ' + Math.round(assignment.durationMs / 1000) + ' s' : '') +
2787
- (assignment.error ? ': ' + assignment.error : '.') +
2788
- (assignment.result ? '\n\n' + clip(assignment.result, 4000) : ''),
2914
+ text: runEndedNote(runNumber, assignment, askedRequester),
2789
2915
  assignmentId: assignment.id,
2790
2916
  });
2791
2917
  return {
@@ -2826,64 +2952,17 @@ export class OrgController extends EventEmitter {
2826
2952
  if (current.status === input.to && !input.fromRun) {
2827
2953
  return { ok: true, task: current };
2828
2954
  }
2829
- // A run in flight owns its card. Cancelling is the way to interrupt it;
2830
- // anything else would have two writers deciding the same outcome.
2831
- if (current.status === 'running' && !input.fromRun && input.to !== 'cancelled') {
2832
- return { ok: false, reason: 'The task is running. Cancel it first, or wait for it to finish.' };
2833
- }
2834
- // An agent reports; the person who asked decides it is finished
2835
- // (decision O3). `update_task` is offered to agents and checked nothing,
2836
- // so an agent could close or drop a card the user had put on the board
2837
- // themselves - and the user found out by noticing it was gone. Marking
2838
- // it `blocked` or handing back a result stays open to them, and a run
2839
- // recording its own outcome passes `fromRun`.
2840
- if (input.by === 'agent' &&
2841
- !input.fromRun &&
2842
- current.createdBy === 'user' &&
2843
- (input.to === 'done' || input.to === 'cancelled')) {
2844
- return {
2845
- ok: false,
2846
- reason: 'This task belongs to the user. Report what you found and let them close it.',
2847
- };
2848
- }
2849
- const now = Date.now();
2850
- const terminal = input.to === 'done' || input.to === 'failed' || input.to === 'cancelled';
2851
- const patch = { status: input.to };
2852
- if (terminal) {
2853
- patch.finishedAt = now;
2854
- if (input.result !== undefined)
2855
- patch.result = input.result;
2856
- if (input.error !== undefined)
2857
- patch.error = input.error;
2858
- }
2859
- else if (input.to === 'blocked') {
2860
- // Waiting is not a new life. A blocked card is mid-question: it
2861
- // carries what the run produced so far and the reason it stopped,
2862
- // and clearing those - as "back into play" does - threw away the
2863
- // very thing the person is being asked about.
2864
- patch.finishedAt = null;
2865
- if (input.result !== undefined)
2866
- patch.result = input.result;
2867
- if (input.error !== undefined)
2868
- patch.error = input.error;
2869
- }
2870
- else {
2871
- // Back into play: nothing from the last attempt may survive as if it
2872
- // described this one.
2873
- patch.finishedAt = null;
2874
- patch.result = input.result ?? null;
2875
- patch.error = input.error ?? null;
2876
- if (input.to === 'running')
2877
- patch.startedAt = now;
2878
- }
2879
- org.updateTask(current.id, patch);
2880
- const updated = org.getTask(current.id) ?? current;
2881
- this.#announceTask(updated, input.emit ?? (() => undefined));
2955
+ const refusal = statusChangeRefusal(current, input);
2956
+ if (refusal)
2957
+ return { ok: false, reason: refusal };
2958
+ org.updateTask(current.id, statusPatch(input, Date.now()));
2959
+ const updated = this.#current(current);
2960
+ this.#announceTask(updated, input.emit ?? ignoreEvent);
2882
2961
  // Every ending and every wait goes on the card, whoever moved it; then
2883
2962
  // whoever is owed the news gets it (`#deliverEnding` has the rules - who
2884
2963
  // hears, and the old silences: a schedule's card, the person's own
2885
2964
  // cancel).
2886
- if (input.to === 'done' || input.to === 'failed' || input.to === 'cancelled' || input.to === 'blocked') {
2965
+ if (isEnding(input.to)) {
2887
2966
  this.#recordStatus(updated, input.fromRun ? 'system' : input.by);
2888
2967
  this.#deliverEnding(updated, input.to, { by: input.by, fromRun: Boolean(input.fromRun) });
2889
2968
  }
@@ -2895,7 +2974,7 @@ export class OrgController extends EventEmitter {
2895
2974
  * card the moment the work is handed over, not once planning is done.
2896
2975
  */
2897
2976
  announceTask(task) {
2898
- this.#announceTask(task, () => undefined);
2977
+ this.#announceTask(task, ignoreEvent);
2899
2978
  }
2900
2979
  #announceTask(task, emit) {
2901
2980
  const event = { type: 'task', task };
@@ -2960,7 +3039,7 @@ export class OrgController extends EventEmitter {
2960
3039
  hopEntity: policy.hopEntity,
2961
3040
  hopEdge: policy.hopEdge,
2962
3041
  });
2963
- const profile = coreProfile(this.#store, { owner: agentId, limit: 3 });
3042
+ const profile = coreProfile(this.#store, { owner: agentId, limit: AGENT_PROFILE_LIMIT });
2964
3043
  const byId = new Map(profile.map((memory) => [memory.id, memory]));
2965
3044
  for (const memory of matched)
2966
3045
  byId.set(memory.id, memory);
@@ -2978,8 +3057,8 @@ export class OrgController extends EventEmitter {
2978
3057
  const known = recall(this.#store, {
2979
3058
  text: task + '\n' + report,
2980
3059
  owner: agent.id,
2981
- limit: 20,
2982
- threshold: 0.05,
3060
+ limit: KNOWN_MEMORIES_LIMIT,
3061
+ threshold: KNOWN_MEMORIES_THRESHOLD,
2983
3062
  touch: false,
2984
3063
  expand: false,
2985
3064
  }).map((memory) => memory.content);
@@ -3058,8 +3137,7 @@ export class OrgController extends EventEmitter {
3058
3137
  */
3059
3138
  async #develop(agent, orgId, providerId) {
3060
3139
  const performance = this.#store.org.performance(agent.id);
3061
- const actions = this.#store.org.listActions(agent.id, { limit: 1 });
3062
- const lastStage = actions[0]?.stage ?? 0;
3140
+ const lastStage = this.#store.org.listActions(agent.id, { limit: 1 })[0]?.stage ?? 0;
3063
3141
  if (performance.stage <= lastStage)
3064
3142
  return;
3065
3143
  const reviews = this.#store.org.effectiveReviews(agent.id, 10).filter((review) => !review.failedRun);
@@ -3070,80 +3148,84 @@ export class OrgController extends EventEmitter {
3070
3148
  tags: review.tags,
3071
3149
  createdAt: review.createdAt,
3072
3150
  }));
3073
- const provider = this.#registry.get(providerId);
3074
- if (performance.stage === 1) {
3075
- const drafted = await draftNote(provider, { roleTitle: agent.title, instructions: agent.instructions, reviews: weak });
3076
- if (!drafted)
3077
- return;
3078
- this.#store.org.createAction({
3079
- orgId,
3080
- agentId: agent.id,
3081
- kind: 'note',
3082
- stage: 1,
3083
- reason: drafted.reason,
3084
- agentNote: drafted.agentNote,
3085
- reviewIds: reviews.slice(0, 3).map((review) => review.id),
3086
- decidedBy: 'assistant',
3087
- });
3088
- this.emit('changed', { kind: 'agent', id: agent.id });
3151
+ const subject = { agent, orgId, provider: this.#registry.get(providerId), reviews, weak };
3152
+ if (performance.stage === 1)
3153
+ await this.#fileNote(subject);
3154
+ else if (performance.stage === 2)
3155
+ await this.#fileReconfig(subject);
3156
+ else if (performance.stage === 3)
3157
+ await this.#fileReplacementProposal(subject);
3158
+ }
3159
+ async #fileNote({ agent, orgId, provider, reviews, weak }) {
3160
+ const drafted = await draftNote(provider, { roleTitle: agent.title, instructions: agent.instructions, reviews: weak });
3161
+ if (!drafted)
3089
3162
  return;
3090
- }
3091
- if (performance.stage === 2) {
3092
- const drafted = await draftReconfig(provider, { roleTitle: agent.title, instructions: agent.instructions, reviews: weak });
3093
- if (!drafted)
3094
- return;
3095
- // Propose by default, apply only where the user has said it may
3096
- // (`org.autoReconfig`). Standing instructions are something a person
3097
- // wrote, and stage 2 is reached by one model's judgment of another
3098
- // model's output - a chain with nobody in it. Filed as a proposal,
3099
- // the same text is one click away on the agent's page and the agent
3100
- // keeps working to its current instructions until then.
3101
- const applying = this.#config.org.autoReconfig;
3102
- // Protocol before effect (decision E1): the action and the instruction
3103
- // change happen together, or not at all - `updateAgent` never runs
3104
- // ahead of a personnel-file entry that justifies it.
3105
- this.#store.org.createAction({
3106
- orgId,
3107
- agentId: agent.id,
3108
- kind: applying ? 'reconfig' : 'reconfig-proposal',
3109
- stage: 2,
3110
- reason: drafted.reason,
3111
- beforeText: agent.instructions,
3112
- afterText: drafted.newInstructions,
3113
- agentNote: drafted.agentNote,
3114
- reviewIds: reviews.slice(0, 5).map((review) => review.id),
3115
- decidedBy: 'assistant',
3116
- });
3117
- if (applying)
3118
- this.#store.org.updateAgent(agent.id, { instructions: drafted.newInstructions });
3119
- this.emit('changed', { kind: 'agent', id: agent.id });
3163
+ this.#store.org.createAction({
3164
+ orgId,
3165
+ agentId: agent.id,
3166
+ kind: 'note',
3167
+ stage: 1,
3168
+ reason: drafted.reason,
3169
+ agentNote: drafted.agentNote,
3170
+ reviewIds: reviews.slice(0, 3).map((review) => review.id),
3171
+ decidedBy: 'assistant',
3172
+ });
3173
+ this.emit('changed', { kind: 'agent', id: agent.id });
3174
+ }
3175
+ async #fileReconfig({ agent, orgId, provider, reviews, weak }) {
3176
+ const drafted = await draftReconfig(provider, { roleTitle: agent.title, instructions: agent.instructions, reviews: weak });
3177
+ if (!drafted)
3120
3178
  return;
3121
- }
3122
- if (performance.stage === 3) {
3123
- const drafted = await draftReplacementProposal(provider, {
3124
- currentName: agent.name,
3125
- roleTitle: agent.title,
3126
- instructions: agent.instructions,
3127
- reviews: weak,
3128
- });
3129
- if (!drafted)
3130
- return;
3131
- // Only a proposal (section 4, stage 3): logged so the agent page can
3132
- // show it as a pending action item, nothing about the agent changes
3133
- // until the user approves the replacement.
3134
- this.#store.org.createAction({
3135
- orgId,
3136
- agentId: agent.id,
3137
- kind: 'probation',
3138
- stage: 3,
3139
- reason: drafted.reason +
3140
- '\n\nProposed successor: ' + drafted.successorName + ' (' + drafted.successorSlug + '), ' +
3141
- drafted.successorTitle + '.\n\n' + drafted.successorInstructions,
3142
- reviewIds: reviews.slice(0, 5).map((review) => review.id),
3143
- decidedBy: 'assistant',
3144
- });
3145
- this.emit('changed', { kind: 'agent', id: agent.id });
3146
- }
3179
+ // Propose by default, apply only where the user has said it may
3180
+ // (`org.autoReconfig`). Standing instructions are something a person
3181
+ // wrote, and stage 2 is reached by one model's judgment of another
3182
+ // model's output - a chain with nobody in it. Filed as a proposal,
3183
+ // the same text is one click away on the agent's page and the agent
3184
+ // keeps working to its current instructions until then.
3185
+ const applying = this.#config.org.autoReconfig;
3186
+ // Protocol before effect (decision E1): the action and the instruction
3187
+ // change happen together, or not at all - `updateAgent` never runs
3188
+ // ahead of a personnel-file entry that justifies it.
3189
+ this.#store.org.createAction({
3190
+ orgId,
3191
+ agentId: agent.id,
3192
+ kind: applying ? 'reconfig' : 'reconfig-proposal',
3193
+ stage: 2,
3194
+ reason: drafted.reason,
3195
+ beforeText: agent.instructions,
3196
+ afterText: drafted.newInstructions,
3197
+ agentNote: drafted.agentNote,
3198
+ reviewIds: reviews.slice(0, 5).map((review) => review.id),
3199
+ decidedBy: 'assistant',
3200
+ });
3201
+ if (applying)
3202
+ this.#store.org.updateAgent(agent.id, { instructions: drafted.newInstructions });
3203
+ this.emit('changed', { kind: 'agent', id: agent.id });
3204
+ }
3205
+ async #fileReplacementProposal({ agent, orgId, provider, reviews, weak }) {
3206
+ const drafted = await draftReplacementProposal(provider, {
3207
+ currentName: agent.name,
3208
+ roleTitle: agent.title,
3209
+ instructions: agent.instructions,
3210
+ reviews: weak,
3211
+ });
3212
+ if (!drafted)
3213
+ return;
3214
+ // Only a proposal (section 4, stage 3): logged so the agent page can
3215
+ // show it as a pending action item, nothing about the agent changes
3216
+ // until the user approves the replacement.
3217
+ this.#store.org.createAction({
3218
+ orgId,
3219
+ agentId: agent.id,
3220
+ kind: 'probation',
3221
+ stage: 3,
3222
+ reason: drafted.reason +
3223
+ '\n\nProposed successor: ' + drafted.successorName + ' (' + drafted.successorSlug + '), ' +
3224
+ drafted.successorTitle + '.\n\n' + drafted.successorInstructions,
3225
+ reviewIds: reviews.slice(0, 5).map((review) => review.id),
3226
+ decidedBy: 'assistant',
3227
+ });
3228
+ this.emit('changed', { kind: 'agent', id: agent.id });
3147
3229
  }
3148
3230
  /**
3149
3231
  * Stage 2, the half the machine does not do: the user accepts a drafted
@@ -3195,29 +3277,7 @@ export class OrgController extends EventEmitter {
3195
3277
  const predecessor = this.#store.org.getAgent(predecessorId);
3196
3278
  if (!predecessor)
3197
3279
  throw new Error('No agent ' + predecessorId + '.');
3198
- let handover = successor.handover?.trim();
3199
- if (!handover) {
3200
- const resolvedProvider = await this.#registry.resolveUsable(providerId ?? this.#config.defaultProvider);
3201
- if (resolvedProvider) {
3202
- try {
3203
- const memories = this.#store.listMemories({ owner: predecessor.id, limit: 300, includeDormant: false });
3204
- handover =
3205
- (await draftHandover(this.#registry.get(resolvedProvider), {
3206
- predecessorName: predecessor.name,
3207
- roleTitle: predecessor.title,
3208
- instructions: predecessor.instructions,
3209
- memories: memories.map((memory) => ({
3210
- content: memory.content,
3211
- importance: memory.importance,
3212
- createdAt: memory.createdAt,
3213
- })),
3214
- })) ?? undefined;
3215
- }
3216
- catch (error) {
3217
- this.#log.warn('Handover draft failed', { agent: predecessor.slug, error: error.message });
3218
- }
3219
- }
3220
- }
3280
+ const handover = successor.handover?.trim() || (await this.#condenseHandover(predecessor, providerId));
3221
3281
  const newAgent = this.#store.org.createAgent({
3222
3282
  orgId,
3223
3283
  slug: successor.slug,
@@ -3254,6 +3314,30 @@ export class OrgController extends EventEmitter {
3254
3314
  this.emit('changed', { kind: 'agent', id: newAgent.id });
3255
3315
  return newAgent;
3256
3316
  }
3317
+ /** A handover condensed from the predecessor's memory; undefined without a usable provider or when drafting fails. */
3318
+ async #condenseHandover(predecessor, providerId) {
3319
+ const resolvedProvider = await this.#registry.resolveUsable(providerId ?? this.#config.defaultProvider);
3320
+ if (!resolvedProvider)
3321
+ return undefined;
3322
+ try {
3323
+ const memories = this.#store.listMemories({ owner: predecessor.id, limit: 300, includeDormant: false });
3324
+ const handover = await draftHandover(this.#registry.get(resolvedProvider), {
3325
+ predecessorName: predecessor.name,
3326
+ roleTitle: predecessor.title,
3327
+ instructions: predecessor.instructions,
3328
+ memories: memories.map((memory) => ({
3329
+ content: memory.content,
3330
+ importance: memory.importance,
3331
+ createdAt: memory.createdAt,
3332
+ })),
3333
+ });
3334
+ return handover ?? undefined;
3335
+ }
3336
+ catch (error) {
3337
+ this.#log.warn('Handover draft failed', { agent: predecessor.slug, error: error.message });
3338
+ return undefined;
3339
+ }
3340
+ }
3257
3341
  /** Concurrency gate: at most `maxConcurrentAssignments` provider processes at once. */
3258
3342
  #acquire(signal) {
3259
3343
  if (this.#running < this.#config.org.maxConcurrentAssignments) {
@@ -3315,7 +3399,7 @@ export function describeAssignment(assignment, agent, runNumber) {
3315
3399
  'Brief: ' + clip(assignment.task, 400),
3316
3400
  ];
3317
3401
  if (assignment.durationMs !== undefined)
3318
- lines.push('Duration: ' + Math.round(assignment.durationMs / 1000) + ' s');
3402
+ lines.push('Duration: ' + toSeconds(assignment.durationMs) + ' s');
3319
3403
  if (assignment.error)
3320
3404
  lines.push('Error: ' + assignment.error);
3321
3405
  if (assignment.result)
@@ -3346,44 +3430,6 @@ export function describeAgentPerformance(agent, org) {
3346
3430
  }
3347
3431
  return lines.join('\n');
3348
3432
  }
3349
- function asMemoryKind(value) {
3350
- return value === 'preference' || value === 'project' || value === 'event' ? value : 'fact';
3351
- }
3352
- /**
3353
- * The `ask_user` options, read defensively. The schema says objects with a
3354
- * label, but a model that answers a list of strings is asking the same
3355
- * question and should not be sent back round for a formality; anything
3356
- * without readable text is dropped rather than shown as an empty button.
3357
- */
3358
- function asQuestionOptions(value) {
3359
- if (!Array.isArray(value))
3360
- return [];
3361
- const options = [];
3362
- for (const entry of value) {
3363
- if (typeof entry === 'string') {
3364
- const label = entry.trim();
3365
- if (label)
3366
- options.push({ label });
3367
- continue;
3368
- }
3369
- if (!entry || typeof entry !== 'object')
3370
- continue;
3371
- const record = entry;
3372
- const label = typeof record.label === 'string' ? record.label.trim() : '';
3373
- if (!label)
3374
- continue;
3375
- const description = typeof record.description === 'string' ? record.description.trim() : '';
3376
- options.push(description ? { label, description } : { label });
3377
- }
3378
- return options;
3379
- }
3380
- /** A number argument within bounds; the fallback when it is missing or not a number. */
3381
- function clampNumber(value, min, max, fallback) {
3382
- const parsed = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN;
3383
- if (!Number.isFinite(parsed))
3384
- return fallback;
3385
- return Math.min(max, Math.max(min, parsed));
3386
- }
3387
3433
  /** The settings the assistant may see and change, as plain lines. */
3388
3434
  export function describeSettings(config) {
3389
3435
  return [
@@ -3395,10 +3441,6 @@ export function describeSettings(config) {
3395
3441
  'Run timeout: ' + Math.round(config.org.assignmentTimeoutMs / 60000) + ' min',
3396
3442
  ].join('\n');
3397
3443
  }
3398
- function asPriority(value) {
3399
- return value === 'low' || value === 'normal' || value === 'high' ? value : undefined;
3400
- }
3401
- /** The status note itself: one sentence a person can read without the board. */
3402
3444
  /**
3403
3445
  * The work order an agent reads for one task.
3404
3446
  *
@@ -3435,7 +3477,7 @@ function statusNote(task, status) {
3435
3477
  const name = 'The task "' + task.title + '"';
3436
3478
  if (status === 'done') {
3437
3479
  const result = task.result?.trim();
3438
- return result ? name + ' is done.\n\n' + clip(result, 4000) : name + ' is done.';
3480
+ return result ? name + ' is done.\n\n' + clip(result, NOTE_RESULT_BUDGET) : name + ' is done.';
3439
3481
  }
3440
3482
  if (status === 'cancelled')
3441
3483
  return name + ' was cancelled.';
@@ -3467,7 +3509,7 @@ export function describePlan(plan, children) {
3467
3509
  lines.push('Subtasks:');
3468
3510
  for (const [index, subtask] of plan.subtasks.entries()) {
3469
3511
  const child = children.find((c) => c.title === subtask.title && c.status === 'planned');
3470
- lines.push('- [' + (child?.id.slice(0, 8) ?? '?') + '] ' + subtask.title + ' → ' + subtask.agent +
3512
+ lines.push('- [' + (child ? shortId(child.id) : '?') + '] ' + subtask.title + ' → ' + subtask.agent +
3471
3513
  (subtask.dependsOn.length ? ' (after ' + subtask.dependsOn.map((i) => i + 1).join(', ') + ')' : '') +
3472
3514
  ' #' + (index + 1));
3473
3515
  }
@@ -3475,7 +3517,159 @@ export function describePlan(plan, children) {
3475
3517
  lines.push('Use update_task to change assignees or wording, then run_task to execute.');
3476
3518
  return lines.join('\n');
3477
3519
  }
3478
- function asPermission(value) {
3479
- return value === 'chat' || value === 'read' || value === 'write' || value === 'full' ? value : undefined;
3520
+ /** The first characters of an id: what people and models see, and quote back. */
3521
+ function shortId(id) {
3522
+ return id.slice(0, 8);
3523
+ }
3524
+ function toSeconds(ms) {
3525
+ return Math.round(ms / 1000);
3526
+ }
3527
+ function ignoreEvent() {
3528
+ // A caller with no turn to emit into: the controller's own listeners still hear it.
3529
+ }
3530
+ const noAgent = (ref) => 'No agent "' + ref + '".';
3531
+ const noTeam = (ref) => 'No team "' + ref + '".';
3532
+ const noProject = (ref) => 'No project "' + ref + '".';
3533
+ /** Who a tool call comes from, as the cards and notifications it writes name them. */
3534
+ function callerKind(context) {
3535
+ return context.audience === 'agent' ? 'agent' : 'assistant';
3536
+ }
3537
+ /** The memory bank a caller reads and writes: an agent's own, or the assistant's. */
3538
+ function memoryOwnerOf(context) {
3539
+ return context.audience === 'agent' && context.agentId ? context.agentId : ASSISTANT_MEMORY_OWNER;
3540
+ }
3541
+ function isEnding(status) {
3542
+ return status === 'done' || status === 'failed' || status === 'cancelled' || status === 'blocked';
3543
+ }
3544
+ /** A card the user put on the board themselves, with no conversation or parent to report into. */
3545
+ function isUserCard(task) {
3546
+ return task.createdBy === 'user' && !task.requesterSessionId && !task.parentId;
3547
+ }
3548
+ /** Work a conversation handed off: its ending travels back to that conversation as a turn of its own. */
3549
+ function reportsBackToConversation(task) {
3550
+ return Boolean(task.requesterSessionId) && !task.parentId;
3551
+ }
3552
+ /** Why `change` may not move `current`, or null when it may. */
3553
+ function statusChangeRefusal(current, change) {
3554
+ // A run in flight owns its card. Cancelling is the way to interrupt it;
3555
+ // anything else would have two writers deciding the same outcome.
3556
+ if (current.status === 'running' && !change.fromRun && change.to !== 'cancelled') {
3557
+ return 'The task is running. Cancel it first, or wait for it to finish.';
3558
+ }
3559
+ // An agent reports; the person who asked decides it is finished
3560
+ // (decision O3). `update_task` is offered to agents and checked nothing,
3561
+ // so an agent could close or drop a card the user had put on the board
3562
+ // themselves - and the user found out by noticing it was gone. Marking
3563
+ // it `blocked` or handing back a result stays open to them, and a run
3564
+ // recording its own outcome passes `fromRun`.
3565
+ if (change.by === 'agent' &&
3566
+ !change.fromRun &&
3567
+ current.createdBy === 'user' &&
3568
+ (change.to === 'done' || change.to === 'cancelled')) {
3569
+ return 'This task belongs to the user. Report what you found and let them close it.';
3570
+ }
3571
+ return null;
3572
+ }
3573
+ /** The columns a move to `change.to` writes. */
3574
+ function statusPatch(change, now) {
3575
+ const patch = { status: change.to };
3576
+ if (isEnding(change.to)) {
3577
+ // Waiting is not a new life. A blocked card is mid-question: it
3578
+ // carries what the run produced so far and the reason it stopped,
3579
+ // and clearing those - as "back into play" does - threw away the
3580
+ // very thing the person is being asked about.
3581
+ patch.finishedAt = change.to === 'blocked' ? null : now;
3582
+ if (change.result !== undefined)
3583
+ patch.result = change.result;
3584
+ if (change.error !== undefined)
3585
+ patch.error = change.error;
3586
+ return patch;
3587
+ }
3588
+ // Back into play: nothing from the last attempt may survive as if it
3589
+ // described this one.
3590
+ patch.finishedAt = null;
3591
+ patch.result = change.result ?? null;
3592
+ patch.error = change.error ?? null;
3593
+ if (change.to === 'running')
3594
+ patch.startedAt = now;
3595
+ return patch;
3596
+ }
3597
+ /** The results of the subtasks a task depends on, ahead of its own work order. */
3598
+ function dependencyResults(deps) {
3599
+ if (!deps.length)
3600
+ return '';
3601
+ return ('Results of the subtasks this one depends on:\n\n' +
3602
+ deps.map((dep) => '### ' + dep.title + '\n' + clip(dep.result ?? '', CHILD_REPORT_BUDGET)).join('\n\n') +
3603
+ '\n\n---\n\n');
3604
+ }
3605
+ /** The card's line about one run of it ending. */
3606
+ function runEndedNote(runNumber, assignment, askedRequester) {
3607
+ const outcome = askedRequester && assignment.status === 'done' ? 'ended with a question' : assignment.status;
3608
+ return ('Run ' + runNumber + ' ' + outcome +
3609
+ (assignment.durationMs !== undefined ? ' after ' + toSeconds(assignment.durationMs) + ' s' : '') +
3610
+ (assignment.error ? ': ' + assignment.error : '.') +
3611
+ (assignment.result ? '\n\n' + clip(assignment.result, NOTE_RESULT_BUDGET) : ''));
3612
+ }
3613
+ /** The org settings `update_settings` was asked to change, each within its bounds. */
3614
+ function orgSettingsPatch(args) {
3615
+ const org = {};
3616
+ if (args.has('maxConcurrentAssignments')) {
3617
+ org.maxConcurrentAssignments = args.number('maxConcurrentAssignments', 1, 16, 4);
3618
+ }
3619
+ if (args.has('maxDelegationDepth'))
3620
+ org.maxDelegationDepth = args.number('maxDelegationDepth', 1, 6, 3);
3621
+ if (args.has('assignmentTimeoutMinutes')) {
3622
+ org.assignmentTimeoutMs = args.number('assignmentTimeoutMinutes', 1, 600, 45) * 60 * 1000;
3623
+ }
3624
+ return org;
3625
+ }
3626
+ /** "event" takes a schedule off the clock, and then it needs no expression at all; anything else keeps the old rule that one is required. */
3627
+ function triggerModeArg(args) {
3628
+ const mode = args.text('triggerMode');
3629
+ if (mode.toLowerCase() === 'event')
3630
+ return 'event';
3631
+ return mode ? 'schedule' : undefined;
3632
+ }
3633
+ function cooldownMsArg(args) {
3634
+ if (!args.has('cooldownSeconds'))
3635
+ return undefined;
3636
+ return args.number('cooldownSeconds', 0, 86_400, 60) * 1000;
3637
+ }
3638
+ /** The mailbox settings as they stand after this call: what it names, over what was there, over the defaults. */
3639
+ function mergeListener(id, existing, args, jobId) {
3640
+ return {
3641
+ id,
3642
+ enabled: args.flag('enabled') ?? existing?.enabled ?? false,
3643
+ host: args.text('host') || existing?.host || '',
3644
+ port: args.has('port')
3645
+ ? args.number('port', 1, 65535, DEFAULT_IMAP_PORT)
3646
+ : existing?.port ?? DEFAULT_IMAP_PORT,
3647
+ secure: args.flag('secure') ?? existing?.secure ?? true,
3648
+ user: args.text('user') || existing?.user || '',
3649
+ password: args.text('password') || existing?.password || '',
3650
+ mailbox: args.text('mailbox') || existing?.mailbox || 'INBOX',
3651
+ jobId: jobId ?? existing?.jobId ?? '',
3652
+ };
3653
+ }
3654
+ function asServerAudience(value) {
3655
+ return value === 'assistant' || value === 'agents' || value === 'both' ? value : undefined;
3656
+ }
3657
+ /** What a turn is told when its question went unanswered until the timeout. */
3658
+ function noAnswerText(timeoutMs) {
3659
+ const minutes = Math.max(1, Math.round(timeoutMs / 60000));
3660
+ return ('No answer within ' + minutes + ' minute' + (minutes === 1 ? '' : 's') + '. Carry on with ' +
3661
+ 'your own best judgement and say which way you went and why.');
3662
+ }
3663
+ /** What a turn is told when the user answered its question: the options they chose, and what they added. */
3664
+ function answerText(answer, options) {
3665
+ const chosen = answer.selected
3666
+ .map((index) => options[index]?.label)
3667
+ .filter((label) => Boolean(label));
3668
+ const parts = [];
3669
+ if (chosen.length)
3670
+ parts.push('The user chose: ' + chosen.join(', ') + '.');
3671
+ if (answer.text)
3672
+ parts.push((chosen.length ? 'They added: ' : 'The user answered: ') + answer.text);
3673
+ return parts.join('\n');
3480
3674
  }
3481
3675
  //# sourceMappingURL=controller.js.map