rookery-agent 0.1.0 → 0.3.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 (670) hide show
  1. package/README.md +467 -367
  2. package/docs/migration.md +88 -88
  3. package/docs/updates.md +112 -0
  4. package/package.json +13 -3
  5. package/packages/cli/dist/commands/config.js +2 -2
  6. package/packages/cli/dist/commands/doctor.d.ts.map +1 -1
  7. package/packages/cli/dist/commands/doctor.js +13 -9
  8. package/packages/cli/dist/commands/doctor.js.map +1 -1
  9. package/packages/cli/dist/commands/memory.js +1 -1
  10. package/packages/cli/dist/commands/org.d.ts +2 -2
  11. package/packages/cli/dist/commands/org.d.ts.map +1 -1
  12. package/packages/cli/dist/commands/org.js +19 -17
  13. package/packages/cli/dist/commands/org.js.map +1 -1
  14. package/packages/cli/dist/commands/serve.js +1 -1
  15. package/packages/cli/dist/commands/serve.js.map +1 -1
  16. package/packages/cli/dist/commands/shared.d.ts.map +1 -1
  17. package/packages/cli/dist/commands/shared.js +2 -1
  18. package/packages/cli/dist/commands/shared.js.map +1 -1
  19. package/packages/cli/dist/commands/tasks.d.ts.map +1 -1
  20. package/packages/cli/dist/commands/tasks.js +25 -11
  21. package/packages/cli/dist/commands/tasks.js.map +1 -1
  22. package/packages/cli/dist/commands/tools.js +1 -1
  23. package/packages/cli/dist/commands/tools.js.map +1 -1
  24. package/packages/cli/dist/index.js +13 -13
  25. package/packages/cli/dist/index.js.map +1 -1
  26. package/packages/cli/dist/repl.d.ts +12 -0
  27. package/packages/cli/dist/repl.d.ts.map +1 -1
  28. package/packages/cli/dist/repl.js +170 -16
  29. package/packages/cli/dist/repl.js.map +1 -1
  30. package/packages/cli/dist/tui/App.d.ts +7 -3
  31. package/packages/cli/dist/tui/App.d.ts.map +1 -1
  32. package/packages/cli/dist/tui/App.js +182 -16
  33. package/packages/cli/dist/tui/App.js.map +1 -1
  34. package/packages/cli/dist/tui/commands.d.ts +7 -0
  35. package/packages/cli/dist/tui/commands.d.ts.map +1 -1
  36. package/packages/cli/dist/tui/commands.js +70 -8
  37. package/packages/cli/dist/tui/commands.js.map +1 -1
  38. package/packages/cli/dist/tui/components/AssignmentsView.js +4 -4
  39. package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -1
  40. package/packages/cli/dist/tui/components/Banner.d.ts +11 -2
  41. package/packages/cli/dist/tui/components/Banner.d.ts.map +1 -1
  42. package/packages/cli/dist/tui/components/Banner.js +7 -10
  43. package/packages/cli/dist/tui/components/Banner.js.map +1 -1
  44. package/packages/cli/dist/tui/components/CodeBlock.js +2 -2
  45. package/packages/cli/dist/tui/components/CodeBlock.js.map +1 -1
  46. package/packages/cli/dist/tui/components/InputBox.d.ts.map +1 -1
  47. package/packages/cli/dist/tui/components/InputBox.js +4 -4
  48. package/packages/cli/dist/tui/components/InputBox.js.map +1 -1
  49. package/packages/cli/dist/tui/components/Logo.d.ts +56 -0
  50. package/packages/cli/dist/tui/components/Logo.d.ts.map +1 -0
  51. package/packages/cli/dist/tui/components/Logo.js +50 -0
  52. package/packages/cli/dist/tui/components/Logo.js.map +1 -0
  53. package/packages/cli/dist/tui/components/Markdown.js +8 -8
  54. package/packages/cli/dist/tui/components/Markdown.js.map +1 -1
  55. package/packages/cli/dist/tui/components/Message.d.ts +1 -1
  56. package/packages/cli/dist/tui/components/Message.d.ts.map +1 -1
  57. package/packages/cli/dist/tui/components/Message.js +5 -4
  58. package/packages/cli/dist/tui/components/Message.js.map +1 -1
  59. package/packages/cli/dist/tui/components/QuestionView.d.ts +29 -0
  60. package/packages/cli/dist/tui/components/QuestionView.d.ts.map +1 -0
  61. package/packages/cli/dist/tui/components/QuestionView.js +53 -0
  62. package/packages/cli/dist/tui/components/QuestionView.js.map +1 -0
  63. package/packages/cli/dist/tui/components/SlashPalette.d.ts +5 -2
  64. package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -1
  65. package/packages/cli/dist/tui/components/SlashPalette.js +2 -2
  66. package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -1
  67. package/packages/cli/dist/tui/components/StatusLine.d.ts +0 -2
  68. package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -1
  69. package/packages/cli/dist/tui/components/StatusLine.js +8 -5
  70. package/packages/cli/dist/tui/components/StatusLine.js.map +1 -1
  71. package/packages/cli/dist/tui/components/ToolGroup.js +2 -2
  72. package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -1
  73. package/packages/cli/dist/tui/components/WatchView.d.ts +21 -0
  74. package/packages/cli/dist/tui/components/WatchView.d.ts.map +1 -0
  75. package/packages/cli/dist/tui/components/WatchView.js +36 -0
  76. package/packages/cli/dist/tui/components/WatchView.js.map +1 -0
  77. package/packages/cli/dist/tui/history.d.ts +20 -0
  78. package/packages/cli/dist/tui/history.d.ts.map +1 -0
  79. package/packages/cli/dist/tui/history.js +105 -0
  80. package/packages/cli/dist/tui/history.js.map +1 -0
  81. package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -1
  82. package/packages/cli/dist/tui/hooks/useSlash.js +3 -2
  83. package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -1
  84. package/packages/cli/dist/tui/hooks/useTurn.d.ts +58 -1
  85. package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -1
  86. package/packages/cli/dist/tui/hooks/useTurn.js +214 -36
  87. package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -1
  88. package/packages/cli/dist/tui/hooks/useWatch.d.ts +52 -0
  89. package/packages/cli/dist/tui/hooks/useWatch.d.ts.map +1 -0
  90. package/packages/cli/dist/tui/hooks/useWatch.js +145 -0
  91. package/packages/cli/dist/tui/hooks/useWatch.js.map +1 -0
  92. package/packages/cli/dist/tui/inkTheme.d.ts +19 -0
  93. package/packages/cli/dist/tui/inkTheme.d.ts.map +1 -0
  94. package/packages/cli/dist/tui/inkTheme.js +81 -0
  95. package/packages/cli/dist/tui/inkTheme.js.map +1 -0
  96. package/packages/cli/dist/tui/theme.d.ts +39 -29
  97. package/packages/cli/dist/tui/theme.d.ts.map +1 -1
  98. package/packages/cli/dist/tui/theme.js +35 -25
  99. package/packages/cli/dist/tui/theme.js.map +1 -1
  100. package/packages/cli/dist/tui/types.d.ts +56 -3
  101. package/packages/cli/dist/tui/types.d.ts.map +1 -1
  102. package/packages/cli/dist/tui/types.js +85 -0
  103. package/packages/cli/dist/tui/types.js.map +1 -1
  104. package/packages/cli/dist/ui/modelNames.d.ts +51 -0
  105. package/packages/cli/dist/ui/modelNames.d.ts.map +1 -0
  106. package/packages/cli/dist/ui/modelNames.js +134 -0
  107. package/packages/cli/dist/ui/modelNames.js.map +1 -0
  108. package/packages/cli/dist/ui/render.d.ts.map +1 -1
  109. package/packages/cli/dist/ui/render.js +17 -8
  110. package/packages/cli/dist/ui/render.js.map +1 -1
  111. package/packages/cli/dist/ui/speech.js +5 -0
  112. package/packages/cli/dist/ui/speech.js.map +1 -1
  113. package/packages/cli/dist/ui/theme.d.ts +33 -9
  114. package/packages/cli/dist/ui/theme.d.ts.map +1 -1
  115. package/packages/cli/dist/ui/theme.js +33 -9
  116. package/packages/cli/dist/ui/theme.js.map +1 -1
  117. package/packages/cli/package.json +1 -1
  118. package/packages/core/dist/agents/persona.d.ts.map +1 -1
  119. package/packages/core/dist/agents/persona.js +5 -2
  120. package/packages/core/dist/agents/persona.js.map +1 -1
  121. package/packages/core/dist/computer/accessibility.d.ts +78 -0
  122. package/packages/core/dist/computer/accessibility.d.ts.map +1 -0
  123. package/packages/core/dist/computer/accessibility.js +270 -0
  124. package/packages/core/dist/computer/accessibility.js.map +1 -0
  125. package/packages/core/dist/computer/assemblies.d.ts +17 -0
  126. package/packages/core/dist/computer/assemblies.d.ts.map +1 -0
  127. package/packages/core/dist/computer/assemblies.js +55 -0
  128. package/packages/core/dist/computer/assemblies.js.map +1 -0
  129. package/packages/core/dist/computer/browser-init.d.ts +9 -0
  130. package/packages/core/dist/computer/browser-init.d.ts.map +1 -0
  131. package/packages/core/dist/computer/browser-init.js +133 -0
  132. package/packages/core/dist/computer/browser-init.js.map +1 -0
  133. package/packages/core/dist/computer/cursor.d.ts +30 -0
  134. package/packages/core/dist/computer/cursor.d.ts.map +1 -0
  135. package/packages/core/dist/computer/cursor.js +30 -0
  136. package/packages/core/dist/computer/cursor.js.map +1 -0
  137. package/packages/core/dist/computer/mcp-server.js +524 -82
  138. package/packages/core/dist/computer/mcp-server.js.map +1 -1
  139. package/packages/core/dist/computer/powershell.d.ts +4 -0
  140. package/packages/core/dist/computer/powershell.d.ts.map +1 -1
  141. package/packages/core/dist/computer/powershell.js +471 -81
  142. package/packages/core/dist/computer/powershell.js.map +1 -1
  143. package/packages/core/dist/computer/screen-text.d.ts +82 -0
  144. package/packages/core/dist/computer/screen-text.d.ts.map +1 -0
  145. package/packages/core/dist/computer/screen-text.js +243 -0
  146. package/packages/core/dist/computer/screen-text.js.map +1 -0
  147. package/packages/core/dist/computer/sketch.d.ts +66 -0
  148. package/packages/core/dist/computer/sketch.d.ts.map +1 -0
  149. package/packages/core/dist/computer/sketch.js +540 -0
  150. package/packages/core/dist/computer/sketch.js.map +1 -0
  151. package/packages/core/dist/computer/tools.d.ts +8 -8
  152. package/packages/core/dist/computer/tools.d.ts.map +1 -1
  153. package/packages/core/dist/computer/tools.js +186 -31
  154. package/packages/core/dist/computer/tools.js.map +1 -1
  155. package/packages/core/dist/computer/validation.d.ts +555 -0
  156. package/packages/core/dist/computer/validation.d.ts.map +1 -0
  157. package/packages/core/dist/computer/validation.js +111 -0
  158. package/packages/core/dist/computer/validation.js.map +1 -0
  159. package/packages/core/dist/computer/windows-cursor.d.ts +14 -0
  160. package/packages/core/dist/computer/windows-cursor.d.ts.map +1 -0
  161. package/packages/core/dist/computer/windows-cursor.js +713 -0
  162. package/packages/core/dist/computer/windows-cursor.js.map +1 -0
  163. package/packages/core/dist/config.d.ts +34 -1
  164. package/packages/core/dist/config.d.ts.map +1 -1
  165. package/packages/core/dist/config.js +362 -11
  166. package/packages/core/dist/config.js.map +1 -1
  167. package/packages/core/dist/cron/scheduler.d.ts +59 -6
  168. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  169. package/packages/core/dist/cron/scheduler.js +295 -27
  170. package/packages/core/dist/cron/scheduler.js.map +1 -1
  171. package/packages/core/dist/cron/store.d.ts +19 -1
  172. package/packages/core/dist/cron/store.d.ts.map +1 -1
  173. package/packages/core/dist/cron/store.js +36 -8
  174. package/packages/core/dist/cron/store.js.map +1 -1
  175. package/packages/core/dist/external/claude-code.d.ts +4 -0
  176. package/packages/core/dist/external/claude-code.d.ts.map +1 -0
  177. package/packages/core/dist/external/claude-code.js +111 -0
  178. package/packages/core/dist/external/claude-code.js.map +1 -0
  179. package/packages/core/dist/external/discovery.d.ts +33 -0
  180. package/packages/core/dist/external/discovery.d.ts.map +1 -0
  181. package/packages/core/dist/external/discovery.js +144 -0
  182. package/packages/core/dist/external/discovery.js.map +1 -0
  183. package/packages/core/dist/external/homes.d.ts +26 -0
  184. package/packages/core/dist/external/homes.d.ts.map +1 -0
  185. package/packages/core/dist/external/homes.js +49 -0
  186. package/packages/core/dist/external/homes.js.map +1 -0
  187. package/packages/core/dist/external/shared.d.ts +201 -0
  188. package/packages/core/dist/external/shared.d.ts.map +1 -0
  189. package/packages/core/dist/external/shared.js +308 -0
  190. package/packages/core/dist/external/shared.js.map +1 -0
  191. package/packages/core/dist/gateway/policy.d.ts +117 -2
  192. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  193. package/packages/core/dist/gateway/policy.js +286 -6
  194. package/packages/core/dist/gateway/policy.js.map +1 -1
  195. package/packages/core/dist/index.d.ts +38 -12
  196. package/packages/core/dist/index.d.ts.map +1 -1
  197. package/packages/core/dist/index.js +66 -12
  198. package/packages/core/dist/index.js.map +1 -1
  199. package/packages/core/dist/memory/db.d.ts +1 -1
  200. package/packages/core/dist/memory/db.d.ts.map +1 -1
  201. package/packages/core/dist/memory/db.js +878 -1
  202. package/packages/core/dist/memory/db.js.map +1 -1
  203. package/packages/core/dist/memory/dream/admission.d.ts +124 -0
  204. package/packages/core/dist/memory/dream/admission.d.ts.map +1 -0
  205. package/packages/core/dist/memory/dream/admission.js +116 -0
  206. package/packages/core/dist/memory/dream/admission.js.map +1 -0
  207. package/packages/core/dist/memory/dream/candidate.d.ts +152 -0
  208. package/packages/core/dist/memory/dream/candidate.d.ts.map +1 -0
  209. package/packages/core/dist/memory/dream/candidate.js +547 -0
  210. package/packages/core/dist/memory/dream/candidate.js.map +1 -0
  211. package/packages/core/dist/memory/dream/evaluate.d.ts +394 -0
  212. package/packages/core/dist/memory/dream/evaluate.d.ts.map +1 -0
  213. package/packages/core/dist/memory/dream/evaluate.js +1032 -0
  214. package/packages/core/dist/memory/dream/evaluate.js.map +1 -0
  215. package/packages/core/dist/memory/dream/frame.d.ts +61 -0
  216. package/packages/core/dist/memory/dream/frame.d.ts.map +1 -0
  217. package/packages/core/dist/memory/dream/frame.js +292 -0
  218. package/packages/core/dist/memory/dream/frame.js.map +1 -0
  219. package/packages/core/dist/memory/dream/label.d.ts +370 -0
  220. package/packages/core/dist/memory/dream/label.d.ts.map +1 -0
  221. package/packages/core/dist/memory/dream/label.js +439 -0
  222. package/packages/core/dist/memory/dream/label.js.map +1 -0
  223. package/packages/core/dist/memory/dream/measure.d.ts +114 -0
  224. package/packages/core/dist/memory/dream/measure.d.ts.map +1 -0
  225. package/packages/core/dist/memory/dream/measure.js +205 -0
  226. package/packages/core/dist/memory/dream/measure.js.map +1 -0
  227. package/packages/core/dist/memory/dream/policy.d.ts +21 -0
  228. package/packages/core/dist/memory/dream/policy.d.ts.map +1 -0
  229. package/packages/core/dist/memory/dream/policy.js +157 -0
  230. package/packages/core/dist/memory/dream/policy.js.map +1 -0
  231. package/packages/core/dist/memory/dream/probe.d.ts +202 -0
  232. package/packages/core/dist/memory/dream/probe.d.ts.map +1 -0
  233. package/packages/core/dist/memory/dream/probe.js +671 -0
  234. package/packages/core/dist/memory/dream/probe.js.map +1 -0
  235. package/packages/core/dist/memory/dream/promote.d.ts +312 -0
  236. package/packages/core/dist/memory/dream/promote.d.ts.map +1 -0
  237. package/packages/core/dist/memory/dream/promote.js +528 -0
  238. package/packages/core/dist/memory/dream/promote.js.map +1 -0
  239. package/packages/core/dist/memory/dream/score.d.ts +103 -0
  240. package/packages/core/dist/memory/dream/score.d.ts.map +1 -0
  241. package/packages/core/dist/memory/dream/score.js +334 -0
  242. package/packages/core/dist/memory/dream/score.js.map +1 -0
  243. package/packages/core/dist/memory/dream/slots.d.ts +193 -0
  244. package/packages/core/dist/memory/dream/slots.d.ts.map +1 -0
  245. package/packages/core/dist/memory/dream/slots.js +0 -0
  246. package/packages/core/dist/memory/dream/slots.js.map +1 -0
  247. package/packages/core/dist/memory/dream/trajectory.d.ts +262 -0
  248. package/packages/core/dist/memory/dream/trajectory.d.ts.map +1 -0
  249. package/packages/core/dist/memory/dream/trajectory.js +366 -0
  250. package/packages/core/dist/memory/dream/trajectory.js.map +1 -0
  251. package/packages/core/dist/memory/extractor.d.ts +7 -0
  252. package/packages/core/dist/memory/extractor.d.ts.map +1 -1
  253. package/packages/core/dist/memory/extractor.js +35 -12
  254. package/packages/core/dist/memory/extractor.js.map +1 -1
  255. package/packages/core/dist/memory/gate.d.ts +43 -7
  256. package/packages/core/dist/memory/gate.d.ts.map +1 -1
  257. package/packages/core/dist/memory/gate.js +91 -4
  258. package/packages/core/dist/memory/gate.js.map +1 -1
  259. package/packages/core/dist/memory/recall.d.ts +57 -0
  260. package/packages/core/dist/memory/recall.d.ts.map +1 -1
  261. package/packages/core/dist/memory/recall.js +60 -123
  262. package/packages/core/dist/memory/recall.js.map +1 -1
  263. package/packages/core/dist/memory/sleep.d.ts +131 -4
  264. package/packages/core/dist/memory/sleep.d.ts.map +1 -1
  265. package/packages/core/dist/memory/sleep.js +2384 -65
  266. package/packages/core/dist/memory/sleep.js.map +1 -1
  267. package/packages/core/dist/memory/store.d.ts +564 -10
  268. package/packages/core/dist/memory/store.d.ts.map +1 -1
  269. package/packages/core/dist/memory/store.js +1673 -102
  270. package/packages/core/dist/memory/store.js.map +1 -1
  271. package/packages/core/dist/org/controller.d.ts +268 -4
  272. package/packages/core/dist/org/controller.d.ts.map +1 -1
  273. package/packages/core/dist/org/controller.js +2298 -248
  274. package/packages/core/dist/org/controller.js.map +1 -1
  275. package/packages/core/dist/org/ponytail.d.ts +1 -1
  276. package/packages/core/dist/org/ponytail.js +1 -1
  277. package/packages/core/dist/org/project-mcp.d.ts +3 -3
  278. package/packages/core/dist/org/prompts.d.ts +44 -30
  279. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  280. package/packages/core/dist/org/prompts.js +209 -92
  281. package/packages/core/dist/org/prompts.js.map +1 -1
  282. package/packages/core/dist/org/questions.d.ts +104 -0
  283. package/packages/core/dist/org/questions.d.ts.map +1 -0
  284. package/packages/core/dist/org/questions.js +136 -0
  285. package/packages/core/dist/org/questions.js.map +1 -0
  286. package/packages/core/dist/org/review.d.ts +100 -0
  287. package/packages/core/dist/org/review.d.ts.map +1 -0
  288. package/packages/core/dist/org/review.js +256 -0
  289. package/packages/core/dist/org/review.js.map +1 -0
  290. package/packages/core/dist/org/store.d.ts +311 -2
  291. package/packages/core/dist/org/store.d.ts.map +1 -1
  292. package/packages/core/dist/org/store.js +981 -13
  293. package/packages/core/dist/org/store.js.map +1 -1
  294. package/packages/core/dist/org/tools.d.ts +33 -3
  295. package/packages/core/dist/org/tools.d.ts.map +1 -1
  296. package/packages/core/dist/org/tools.js +380 -67
  297. package/packages/core/dist/org/tools.js.map +1 -1
  298. package/packages/core/dist/providers/catalogue.d.ts +1 -1
  299. package/packages/core/dist/providers/catalogue.d.ts.map +1 -1
  300. package/packages/core/dist/providers/catalogue.js +2 -2
  301. package/packages/core/dist/providers/catalogue.js.map +1 -1
  302. package/packages/core/dist/providers/claude-code.d.ts +19 -3
  303. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  304. package/packages/core/dist/providers/claude-code.js +501 -40
  305. package/packages/core/dist/providers/claude-code.js.map +1 -1
  306. package/packages/core/dist/providers/claude-tui.d.ts +288 -0
  307. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -0
  308. package/packages/core/dist/providers/claude-tui.js +1118 -0
  309. package/packages/core/dist/providers/claude-tui.js.map +1 -0
  310. package/packages/core/dist/providers/codex-auth.d.ts +15 -0
  311. package/packages/core/dist/providers/codex-auth.d.ts.map +1 -0
  312. package/packages/core/dist/providers/codex-auth.js +127 -0
  313. package/packages/core/dist/providers/codex-auth.js.map +1 -0
  314. package/packages/core/dist/providers/codex-bridge.d.ts +58 -0
  315. package/packages/core/dist/providers/codex-bridge.d.ts.map +1 -0
  316. package/packages/core/dist/providers/codex-bridge.js +375 -0
  317. package/packages/core/dist/providers/codex-bridge.js.map +1 -0
  318. package/packages/core/dist/providers/codex-translate.d.ts +75 -0
  319. package/packages/core/dist/providers/codex-translate.d.ts.map +1 -0
  320. package/packages/core/dist/providers/codex-translate.js +383 -0
  321. package/packages/core/dist/providers/codex-translate.js.map +1 -0
  322. package/packages/core/dist/providers/model-gateway.d.ts +56 -0
  323. package/packages/core/dist/providers/model-gateway.d.ts.map +1 -0
  324. package/packages/core/dist/providers/model-gateway.js +119 -0
  325. package/packages/core/dist/providers/model-gateway.js.map +1 -0
  326. package/packages/core/dist/providers/process.d.ts +3 -1
  327. package/packages/core/dist/providers/process.d.ts.map +1 -1
  328. package/packages/core/dist/providers/process.js +3 -3
  329. package/packages/core/dist/providers/process.js.map +1 -1
  330. package/packages/core/dist/providers/profiles.d.ts +11 -0
  331. package/packages/core/dist/providers/profiles.d.ts.map +1 -0
  332. package/packages/core/dist/providers/profiles.js +28 -0
  333. package/packages/core/dist/providers/profiles.js.map +1 -0
  334. package/packages/core/dist/providers/provider-catalog.d.ts +72 -0
  335. package/packages/core/dist/providers/provider-catalog.d.ts.map +1 -0
  336. package/packages/core/dist/providers/provider-catalog.js +144 -0
  337. package/packages/core/dist/providers/provider-catalog.js.map +1 -0
  338. package/packages/core/dist/providers/quota.d.ts +40 -1
  339. package/packages/core/dist/providers/quota.d.ts.map +1 -1
  340. package/packages/core/dist/providers/quota.js +288 -25
  341. package/packages/core/dist/providers/quota.js.map +1 -1
  342. package/packages/core/dist/providers/registry.d.ts +46 -3
  343. package/packages/core/dist/providers/registry.d.ts.map +1 -1
  344. package/packages/core/dist/providers/registry.js +148 -13
  345. package/packages/core/dist/providers/registry.js.map +1 -1
  346. package/packages/core/dist/providers/router.d.ts +28 -0
  347. package/packages/core/dist/providers/router.d.ts.map +1 -0
  348. package/packages/core/dist/providers/router.js +88 -0
  349. package/packages/core/dist/providers/router.js.map +1 -0
  350. package/packages/core/dist/providers/user-settings-guard.d.ts +12 -0
  351. package/packages/core/dist/providers/user-settings-guard.d.ts.map +1 -0
  352. package/packages/core/dist/providers/user-settings-guard.js +130 -0
  353. package/packages/core/dist/providers/user-settings-guard.js.map +1 -0
  354. package/packages/core/dist/runtime.d.ts +193 -7
  355. package/packages/core/dist/runtime.d.ts.map +1 -1
  356. package/packages/core/dist/runtime.js +1676 -219
  357. package/packages/core/dist/runtime.js.map +1 -1
  358. package/packages/core/dist/skills/builtin.d.ts +34 -0
  359. package/packages/core/dist/skills/builtin.d.ts.map +1 -0
  360. package/packages/core/dist/skills/builtin.js +305 -0
  361. package/packages/core/dist/skills/builtin.js.map +1 -0
  362. package/packages/core/dist/skills/shelf.d.ts +30 -0
  363. package/packages/core/dist/skills/shelf.d.ts.map +1 -0
  364. package/packages/core/dist/skills/shelf.js +159 -0
  365. package/packages/core/dist/skills/shelf.js.map +1 -0
  366. package/packages/core/dist/skills/store.d.ts +66 -4
  367. package/packages/core/dist/skills/store.d.ts.map +1 -1
  368. package/packages/core/dist/skills/store.js +105 -18
  369. package/packages/core/dist/skills/store.js.map +1 -1
  370. package/packages/core/dist/skills/suggest.d.ts +21 -0
  371. package/packages/core/dist/skills/suggest.d.ts.map +1 -0
  372. package/packages/core/dist/skills/suggest.js +150 -0
  373. package/packages/core/dist/skills/suggest.js.map +1 -0
  374. package/packages/core/dist/tools/catalog.d.ts +1 -3
  375. package/packages/core/dist/tools/catalog.d.ts.map +1 -1
  376. package/packages/core/dist/tools/catalog.js +38 -26
  377. package/packages/core/dist/tools/catalog.js.map +1 -1
  378. package/packages/core/dist/tools/hub.d.ts +136 -10
  379. package/packages/core/dist/tools/hub.d.ts.map +1 -1
  380. package/packages/core/dist/tools/hub.js +418 -24
  381. package/packages/core/dist/tools/hub.js.map +1 -1
  382. package/packages/core/dist/turns/journal.d.ts +78 -0
  383. package/packages/core/dist/turns/journal.d.ts.map +1 -0
  384. package/packages/core/dist/turns/journal.js +104 -0
  385. package/packages/core/dist/turns/journal.js.map +1 -0
  386. package/packages/core/dist/types.d.ts +1776 -12
  387. package/packages/core/dist/types.d.ts.map +1 -1
  388. package/packages/core/dist/types.js.map +1 -1
  389. package/packages/core/dist/util/blocks.d.ts +41 -0
  390. package/packages/core/dist/util/blocks.d.ts.map +1 -0
  391. package/packages/core/dist/util/blocks.js +175 -0
  392. package/packages/core/dist/util/blocks.js.map +1 -0
  393. package/packages/core/dist/util/queue.d.ts +12 -0
  394. package/packages/core/dist/util/queue.d.ts.map +1 -1
  395. package/packages/core/dist/util/queue.js +16 -0
  396. package/packages/core/dist/util/queue.js.map +1 -1
  397. package/packages/core/dist/util/time.d.ts +39 -0
  398. package/packages/core/dist/util/time.d.ts.map +1 -0
  399. package/packages/core/dist/util/time.js +71 -0
  400. package/packages/core/dist/util/time.js.map +1 -0
  401. package/packages/core/package.json +1 -1
  402. package/packages/server/dist/auth.d.ts +14 -1
  403. package/packages/server/dist/auth.d.ts.map +1 -1
  404. package/packages/server/dist/auth.js +19 -0
  405. package/packages/server/dist/auth.js.map +1 -1
  406. package/packages/server/dist/context.d.ts +35 -1
  407. package/packages/server/dist/context.d.ts.map +1 -1
  408. package/packages/server/dist/context.js +39 -10
  409. package/packages/server/dist/context.js.map +1 -1
  410. package/packages/server/dist/gateways/attachments.d.ts +32 -0
  411. package/packages/server/dist/gateways/attachments.d.ts.map +1 -0
  412. package/packages/server/dist/gateways/attachments.js +167 -0
  413. package/packages/server/dist/gateways/attachments.js.map +1 -0
  414. package/packages/server/dist/gateways/markdown.d.ts +9 -0
  415. package/packages/server/dist/gateways/markdown.d.ts.map +1 -0
  416. package/packages/server/dist/gateways/markdown.js +170 -0
  417. package/packages/server/dist/gateways/markdown.js.map +1 -0
  418. package/packages/server/dist/gateways/push.d.ts +1 -1
  419. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  420. package/packages/server/dist/gateways/push.js +420 -13
  421. package/packages/server/dist/gateways/push.js.map +1 -1
  422. package/packages/server/dist/gateways/telegram-api.d.ts +70 -1
  423. package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -1
  424. package/packages/server/dist/gateways/telegram-api.js +140 -1
  425. package/packages/server/dist/gateways/telegram-api.js.map +1 -1
  426. package/packages/server/dist/gateways/telegram.d.ts +181 -1
  427. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  428. package/packages/server/dist/gateways/telegram.js +1572 -78
  429. package/packages/server/dist/gateways/telegram.js.map +1 -1
  430. package/packages/server/dist/gateways/threads.d.ts +84 -0
  431. package/packages/server/dist/gateways/threads.d.ts.map +1 -0
  432. package/packages/server/dist/gateways/threads.js +289 -0
  433. package/packages/server/dist/gateways/threads.js.map +1 -0
  434. package/packages/server/dist/index.d.ts +2 -1
  435. package/packages/server/dist/index.d.ts.map +1 -1
  436. package/packages/server/dist/index.js +2 -1
  437. package/packages/server/dist/index.js.map +1 -1
  438. package/packages/server/dist/listeners/imap.d.ts +13 -0
  439. package/packages/server/dist/listeners/imap.d.ts.map +1 -0
  440. package/packages/server/dist/listeners/imap.js +0 -0
  441. package/packages/server/dist/listeners/imap.js.map +1 -0
  442. package/packages/server/dist/listeners/registry.d.ts +18 -0
  443. package/packages/server/dist/listeners/registry.d.ts.map +1 -0
  444. package/packages/server/dist/listeners/registry.js +88 -0
  445. package/packages/server/dist/listeners/registry.js.map +1 -0
  446. package/packages/server/dist/listeners/types.d.ts +55 -0
  447. package/packages/server/dist/listeners/types.d.ts.map +1 -0
  448. package/packages/server/dist/listeners/types.js +2 -0
  449. package/packages/server/dist/listeners/types.js.map +1 -0
  450. package/packages/server/dist/main.js +15 -1
  451. package/packages/server/dist/main.js.map +1 -1
  452. package/packages/server/dist/routes/chat.d.ts +7 -3
  453. package/packages/server/dist/routes/chat.d.ts.map +1 -1
  454. package/packages/server/dist/routes/chat.js +8 -17
  455. package/packages/server/dist/routes/chat.js.map +1 -1
  456. package/packages/server/dist/routes/config.d.ts.map +1 -1
  457. package/packages/server/dist/routes/config.js +66 -7
  458. package/packages/server/dist/routes/config.js.map +1 -1
  459. package/packages/server/dist/routes/cron.d.ts.map +1 -1
  460. package/packages/server/dist/routes/cron.js +65 -8
  461. package/packages/server/dist/routes/cron.js.map +1 -1
  462. package/packages/server/dist/routes/dream.d.ts +22 -0
  463. package/packages/server/dist/routes/dream.d.ts.map +1 -0
  464. package/packages/server/dist/routes/dream.js +152 -0
  465. package/packages/server/dist/routes/dream.js.map +1 -0
  466. package/packages/server/dist/routes/hooks.d.ts +18 -0
  467. package/packages/server/dist/routes/hooks.d.ts.map +1 -0
  468. package/packages/server/dist/routes/hooks.js +62 -0
  469. package/packages/server/dist/routes/hooks.js.map +1 -0
  470. package/packages/server/dist/routes/listeners.d.ts +10 -0
  471. package/packages/server/dist/routes/listeners.d.ts.map +1 -0
  472. package/packages/server/dist/routes/listeners.js +12 -0
  473. package/packages/server/dist/routes/listeners.js.map +1 -0
  474. package/packages/server/dist/routes/memories.d.ts.map +1 -1
  475. package/packages/server/dist/routes/memories.js +55 -3
  476. package/packages/server/dist/routes/memories.js.map +1 -1
  477. package/packages/server/dist/routes/org.d.ts.map +1 -1
  478. package/packages/server/dist/routes/org.js +289 -49
  479. package/packages/server/dist/routes/org.js.map +1 -1
  480. package/packages/server/dist/routes/profile.d.ts.map +1 -1
  481. package/packages/server/dist/routes/profile.js +6 -3
  482. package/packages/server/dist/routes/profile.js.map +1 -1
  483. package/packages/server/dist/routes/providers.d.ts.map +1 -1
  484. package/packages/server/dist/routes/providers.js +66 -7
  485. package/packages/server/dist/routes/providers.js.map +1 -1
  486. package/packages/server/dist/routes/questions.d.ts +45 -0
  487. package/packages/server/dist/routes/questions.d.ts.map +1 -0
  488. package/packages/server/dist/routes/questions.js +73 -0
  489. package/packages/server/dist/routes/questions.js.map +1 -0
  490. package/packages/server/dist/routes/sessions.d.ts.map +1 -1
  491. package/packages/server/dist/routes/sessions.js +26 -6
  492. package/packages/server/dist/routes/sessions.js.map +1 -1
  493. package/packages/server/dist/routes/sleep.d.ts.map +1 -1
  494. package/packages/server/dist/routes/sleep.js +71 -2
  495. package/packages/server/dist/routes/sleep.js.map +1 -1
  496. package/packages/server/dist/routes/terminals.d.ts +25 -0
  497. package/packages/server/dist/routes/terminals.d.ts.map +1 -0
  498. package/packages/server/dist/routes/terminals.js +35 -0
  499. package/packages/server/dist/routes/terminals.js.map +1 -0
  500. package/packages/server/dist/routes/tools.d.ts.map +1 -1
  501. package/packages/server/dist/routes/tools.js +140 -6
  502. package/packages/server/dist/routes/tools.js.map +1 -1
  503. package/packages/server/dist/routes/updates.d.ts +10 -0
  504. package/packages/server/dist/routes/updates.d.ts.map +1 -0
  505. package/packages/server/dist/routes/updates.js +22 -0
  506. package/packages/server/dist/routes/updates.js.map +1 -0
  507. package/packages/server/dist/routes/ws.d.ts +11 -5
  508. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  509. package/packages/server/dist/routes/ws.js +168 -28
  510. package/packages/server/dist/routes/ws.js.map +1 -1
  511. package/packages/server/dist/schemas.d.ts +1177 -215
  512. package/packages/server/dist/schemas.d.ts.map +1 -1
  513. package/packages/server/dist/schemas.js +317 -12
  514. package/packages/server/dist/schemas.js.map +1 -1
  515. package/packages/server/dist/server.d.ts +7 -1
  516. package/packages/server/dist/server.d.ts.map +1 -1
  517. package/packages/server/dist/server.js +210 -3
  518. package/packages/server/dist/server.js.map +1 -1
  519. package/packages/server/dist/services/stream.d.ts +94 -5
  520. package/packages/server/dist/services/stream.d.ts.map +1 -1
  521. package/packages/server/dist/services/stream.js +9 -20
  522. package/packages/server/dist/services/stream.js.map +1 -1
  523. package/packages/server/dist/services/stt.d.ts +65 -0
  524. package/packages/server/dist/services/stt.d.ts.map +1 -0
  525. package/packages/server/dist/services/stt.js +306 -0
  526. package/packages/server/dist/services/stt.js.map +1 -0
  527. package/packages/server/dist/services/turns.d.ts +54 -0
  528. package/packages/server/dist/services/turns.d.ts.map +1 -0
  529. package/packages/server/dist/services/turns.js +186 -0
  530. package/packages/server/dist/services/turns.js.map +1 -0
  531. package/packages/server/dist/services/updates.d.ts +99 -0
  532. package/packages/server/dist/services/updates.d.ts.map +1 -0
  533. package/packages/server/dist/services/updates.js +316 -0
  534. package/packages/server/dist/services/updates.js.map +1 -0
  535. package/packages/server/package.json +1 -1
  536. package/packages/web/dist/app-icon.svg +2 -0
  537. package/packages/web/dist/apple-touch-icon.png +0 -0
  538. package/packages/web/dist/assets/abnfDiagram-O67JEVCF-D7YyFndQ.js +1 -0
  539. package/packages/web/dist/assets/arc-C_Zgk2dJ.js +1 -0
  540. package/packages/web/dist/assets/architectureDiagram-NJMV4G6O-eI0adu1B.js +36 -0
  541. package/packages/web/dist/assets/blockDiagram-BEXU5L5S-WAoOFUA9.js +140 -0
  542. package/packages/web/dist/assets/c4Diagram-YGBWAQC7-DE8Zyhng.js +38 -0
  543. package/packages/web/dist/assets/channel-egZxcyUK.js +1 -0
  544. package/packages/web/dist/assets/chunk-2Q5K7J3B-bnqLP2XD.js +1 -0
  545. package/packages/web/dist/assets/chunk-3FUC2YCW-Ck1_SVe0.js +2 -0
  546. package/packages/web/dist/assets/chunk-5VM5RSS4-hDmC41gD.js +15 -0
  547. package/packages/web/dist/assets/chunk-GTNCS2PH-PoWvfCrT.js +88 -0
  548. package/packages/web/dist/assets/chunk-GWA4HPMP-D3V0IG43.js +1 -0
  549. package/packages/web/dist/assets/chunk-JWPE2WC7-BryfpHM5.js +1 -0
  550. package/packages/web/dist/assets/chunk-NETBCI7D-8ic1iEdT.js +1 -0
  551. package/packages/web/dist/assets/chunk-WEXAMYUT-nM8tmQT2.js +1 -0
  552. package/packages/web/dist/assets/chunk-XXDRQBXY-Do28F482.js +1 -0
  553. package/packages/web/dist/assets/classDiagram-v2-NBCMYWYE-Bop9oNNO.js +217 -0
  554. package/packages/web/dist/assets/cose-bilkent-JH36ORCC-a7f_bpnt.js +1 -0
  555. package/packages/web/dist/assets/cynefin-OW5HDTMX-DnArcis_.js +178 -0
  556. package/packages/web/dist/assets/cynefinDiagram-VND7K2PF-vEuTb1GD.js +62 -0
  557. package/packages/web/dist/assets/cytoscape.esm-Ix0LnXOy.js +331 -0
  558. package/packages/web/dist/assets/dagre-6A5THRUB-BgG4MynJ.js +4 -0
  559. package/packages/web/dist/assets/diagram-22UHCM2B-DRCQpafv.js +200 -0
  560. package/packages/web/dist/assets/diagram-3UASUU5V-BKgmAXde.js +24 -0
  561. package/packages/web/dist/assets/diagram-ATOU4E4O-B6Hsy36X.js +3 -0
  562. package/packages/web/dist/assets/diagram-CDSNMT55-JflyfyoB.js +30 -0
  563. package/packages/web/dist/assets/diagram-MLGK6HIB-Dd2QPJjT.js +24 -0
  564. package/packages/web/dist/assets/diagram-MPIPVDR6-DE5QU60x.js +41 -0
  565. package/packages/web/dist/assets/draco_decoder-C32yEggz.wasm +0 -0
  566. package/packages/web/dist/assets/draco_decoder-Z1_iN-Ht.wasm +0 -0
  567. package/packages/web/dist/assets/draco_decoder-fzg4nYZr.js +34 -0
  568. package/packages/web/dist/assets/draco_wasm_wrapper-DxJM36Ib.js +117 -0
  569. package/packages/web/dist/assets/draco_wasm_wrapper-fZCQGLGb.js +116 -0
  570. package/packages/web/dist/assets/ebnfDiagram-ZINNZB2B-D7AQ741b.js +1 -0
  571. package/packages/web/dist/assets/elk-276RUBZZ-CeewBVLF.js +27 -0
  572. package/packages/web/dist/assets/erDiagram-OPXOYQCR-mLLYkZ5c.js +99 -0
  573. package/packages/web/dist/assets/flowDiagram-KWPJA3E3-DtpSpsQN.js +213 -0
  574. package/packages/web/dist/assets/ganttDiagram-FUAMR5RP-1_lh-3ky.js +292 -0
  575. package/packages/web/dist/assets/gitGraphDiagram-X574FWY7-DoPXZuT5.js +106 -0
  576. package/packages/web/dist/assets/graph-Bn3Yngep.js +1 -0
  577. package/packages/web/dist/assets/index-Cw2Opmx7.js +648 -0
  578. package/packages/web/dist/assets/index-j0zBRCgT.css +32 -0
  579. package/packages/web/dist/assets/infoDiagram-VRGFBTTK-DQpRGGiD.js +2 -0
  580. package/packages/web/dist/assets/ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js +70 -0
  581. package/packages/web/dist/assets/journeyDiagram-ZHPQQLJL-Bg-oeFjb.js +139 -0
  582. package/packages/web/dist/assets/kanban-definition-PNTS6WVX-BnpI4VH8.js +89 -0
  583. package/packages/web/dist/assets/katex-C5jXJg4s.js +257 -0
  584. package/packages/web/dist/assets/mermaid.core-BwBKxlRA.js +313 -0
  585. package/packages/web/dist/assets/mindmap-definition-NLK3R4M7-NBnnxEoO.js +96 -0
  586. package/packages/web/dist/assets/pegDiagram-GJSIUBJH-RrXXbIvO.js +1 -0
  587. package/packages/web/dist/assets/pieDiagram-5QR66LMP-B27q6Gso.js +39 -0
  588. package/packages/web/dist/assets/quadrantDiagram-O4NWA36T-DGDsdur2.js +7 -0
  589. package/packages/web/dist/assets/railroadDiagram-XR7U4H2S-GdjkE3mI.js +1 -0
  590. package/packages/web/dist/assets/requirementDiagram-PLB6GJNP-DjK0GfgO.js +84 -0
  591. package/packages/web/dist/assets/sankeyDiagram-IPEJSGJF-BG_AIkwF.js +40 -0
  592. package/packages/web/dist/assets/scene-D4LPicHk.js +4620 -0
  593. package/packages/web/dist/assets/sequenceDiagram-PO4LG4MO-CIQwUb4y.js +169 -0
  594. package/packages/web/dist/assets/sizeCapture-INFHLROL-bpIoPxdJ.js +1 -0
  595. package/packages/web/dist/assets/stateDiagram-v2-GCMORJYK-8hYXvPPv.js +291 -0
  596. package/packages/web/dist/assets/swimlanes-2SLR337P-gfflUMF9.js +1 -0
  597. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +8 -0
  598. package/packages/web/dist/assets/timeline-definition-EJHVYXUP-PHMNoGTZ.js +120 -0
  599. package/packages/web/dist/assets/usecaseDiagram-POWQR4AR-B2j5iteO.js +370 -0
  600. package/packages/web/dist/assets/vennDiagram-UO4OBE2U-BzxtZ-_2.js +34 -0
  601. package/packages/web/dist/assets/wardleyDiagram-VNRHLVJA-DL7YbMpY.js +78 -0
  602. package/packages/web/dist/assets/xychartDiagram-PMCCYNJV-CisgP1cT.js +7 -0
  603. package/packages/web/dist/draco/draco_decoder.js +33 -0
  604. package/packages/web/dist/draco/draco_decoder.wasm +0 -0
  605. package/packages/web/dist/draco/draco_wasm_wrapper.js +116 -0
  606. package/packages/web/dist/favicon-16.png +0 -0
  607. package/packages/web/dist/favicon-32.png +0 -0
  608. package/packages/web/dist/favicon-48.png +0 -0
  609. package/packages/web/dist/favicon.ico +0 -0
  610. package/packages/web/dist/favicon.svg +1 -1
  611. package/packages/web/dist/icon-192.png +0 -0
  612. package/packages/web/dist/icon-512.png +0 -0
  613. package/packages/web/dist/index.html +12 -4
  614. package/packages/web/dist/logo-light.svg +1 -1
  615. package/packages/web/dist/logo-mono.svg +2 -0
  616. package/packages/web/dist/logo-stacked-light.svg +2 -0
  617. package/packages/web/dist/logo-stacked.svg +2 -0
  618. package/packages/web/dist/logo-white.svg +2 -0
  619. package/packages/web/dist/logo.svg +1 -1
  620. package/packages/web/dist/mark-light.svg +1 -1
  621. package/packages/web/dist/mark-mono.svg +2 -0
  622. package/packages/web/dist/mark-small-light.svg +2 -0
  623. package/packages/web/dist/mark-small.svg +2 -0
  624. package/packages/web/dist/mark-white.svg +2 -0
  625. package/packages/web/dist/mark.svg +1 -1
  626. package/packages/web/dist/models/LICENSE.txt +5 -0
  627. package/packages/web/dist/models/brain.glb +0 -0
  628. package/packages/web/dist/site.webmanifest +23 -0
  629. package/packages/web/dist/wordmark-light.svg +2 -0
  630. package/packages/web/dist/wordmark.svg +2 -0
  631. package/packages/web/package.json +1 -1
  632. package/scripts/rookery.mjs +204 -122
  633. package/scripts/updater.mjs +227 -0
  634. package/packages/cli/dist/tui/components/Wordmark.d.ts +0 -35
  635. package/packages/cli/dist/tui/components/Wordmark.d.ts.map +0 -1
  636. package/packages/cli/dist/tui/components/Wordmark.js +0 -81
  637. package/packages/cli/dist/tui/components/Wordmark.js.map +0 -1
  638. package/packages/core/dist/agents/orchestrator.d.ts +0 -24
  639. package/packages/core/dist/agents/orchestrator.d.ts.map +0 -1
  640. package/packages/core/dist/agents/orchestrator.js +0 -88
  641. package/packages/core/dist/agents/orchestrator.js.map +0 -1
  642. package/packages/core/dist/agents/roles.d.ts +0 -21
  643. package/packages/core/dist/agents/roles.d.ts.map +0 -1
  644. package/packages/core/dist/agents/roles.js +0 -81
  645. package/packages/core/dist/agents/roles.js.map +0 -1
  646. package/packages/core/dist/agents/team.d.ts +0 -105
  647. package/packages/core/dist/agents/team.d.ts.map +0 -1
  648. package/packages/core/dist/agents/team.js +0 -623
  649. package/packages/core/dist/agents/team.js.map +0 -1
  650. package/packages/core/dist/providers/codex.d.ts +0 -10
  651. package/packages/core/dist/providers/codex.d.ts.map +0 -1
  652. package/packages/core/dist/providers/codex.js +0 -375
  653. package/packages/core/dist/providers/codex.js.map +0 -1
  654. package/packages/core/dist/tools/browser.d.ts +0 -20
  655. package/packages/core/dist/tools/browser.d.ts.map +0 -1
  656. package/packages/core/dist/tools/browser.js +0 -72
  657. package/packages/core/dist/tools/browser.js.map +0 -1
  658. package/packages/server/dist/routes/agents.d.ts +0 -5
  659. package/packages/server/dist/routes/agents.d.ts.map +0 -1
  660. package/packages/server/dist/routes/agents.js +0 -6
  661. package/packages/server/dist/routes/agents.js.map +0 -1
  662. package/packages/server/dist/routes/team.d.ts +0 -11
  663. package/packages/server/dist/routes/team.d.ts.map +0 -1
  664. package/packages/server/dist/routes/team.js +0 -36
  665. package/packages/server/dist/routes/team.js.map +0 -1
  666. package/packages/web/dist/assets/3d-force-graph-BPZmoydi.js +0 -1163
  667. package/packages/web/dist/assets/index-IBSTzK7-.js +0 -1255
  668. package/packages/web/dist/assets/index-qUXUui7W.css +0 -1
  669. package/packages/web/dist/assets/three-spritetext-B9ZIW7c-.js +0 -4
  670. package/packages/web/dist/assets/three.module-cmFfBtHS.js +0 -4228
@@ -1,24 +1,41 @@
1
+ import { randomUUID } from 'node:crypto';
1
2
  import { EventEmitter } from 'node:events';
2
3
  import { join } from 'node:path';
3
4
  import { ASSISTANT_MEMORY_OWNER } from './types.js';
4
- import { agentWorkspace, databasePath, loadConfig } from './config.js';
5
+ import { databasePath, loadConfig } from './config.js';
5
6
  import { createLogger, silentLogger } from './logger.js';
6
7
  import { ProviderRegistry } from './providers/registry.js';
8
+ import { remapModel } from './providers/provider-catalog.js';
9
+ import { isUsageLimitError, providerBlocked, providerLow, rememberUsageFailure } from './providers/quota.js';
10
+ import { sharedCodexBridge } from './providers/codex-bridge.js';
11
+ import { tuiSessions } from './providers/claude-tui.js';
12
+ import { ModelGateway } from './providers/model-gateway.js';
13
+ import { loadPty } from './providers/claude-tui.js';
14
+ import { renderMemoryBlock } from './memory/recall.js';
7
15
  import { Store } from './memory/store.js';
8
- import { coreProfile, dropContradicted, recall } from './memory/recall.js';
16
+ import { byScoreThenId, coreProfile, dropContradicted, recall } from './memory/recall.js';
17
+ import { fetchFrame } from './memory/dream/frame.js';
18
+ import { resolvePolicy } from './memory/dream/policy.js';
19
+ import { DEFAULT_SPLIT_RATES, splitOf } from './memory/dream/evaluate.js';
20
+ import { episodeFromEvents } from './memory/dream/trajectory.js';
9
21
  import { extractMemories, smallModelFor } from './memory/extractor.js';
10
22
  import { admitCandidates, linkEntities } from './memory/gate.js';
11
23
  import { SleepRunner } from './memory/sleep.js';
12
24
  import { buildSystemPrompt, deriveTitle } from './agents/persona.js';
13
25
  import { BridgeServer } from './org/bridge.js';
14
- import { OrgController } from './org/controller.js';
15
- import { assistantOrgBlock, buildAgentChatPrompt } from './org/prompts.js';
16
- import { dormantToolsHint, ensureToolServers, toolServersFor } from './tools/hub.js';
26
+ import { OrgController, taskNotification } from './org/controller.js';
27
+ import { QuestionRegistry } from './org/questions.js';
28
+ import { assistantOrgBlock } from './org/prompts.js';
29
+ import { dormantToolsHint, externalTurnExtras, toolServersFor } from './tools/hub.js';
17
30
  import { SkillStore, renderSkillsIndex } from './skills/store.js';
31
+ import { renderExternalSkillsHint } from './skills/shelf.js';
32
+ import { matchSkills, renderSkillMatches } from './skills/suggest.js';
18
33
  import { CronScheduler } from './cron/scheduler.js';
19
34
  import { describeCron } from './cron/parse.js';
20
35
  import { runCronScript } from './cron/script.js';
21
- import { EventQueue } from './util/queue.js';
36
+ import { EventQueue, titleFromBrief } from './util/queue.js';
37
+ import { formatAge, formatNow } from './util/time.js';
38
+ import { TurnBlocks } from './util/blocks.js';
22
39
  /**
23
40
  * The assistant runtime.
24
41
  *
@@ -27,10 +44,11 @@ import { EventQueue } from './util/queue.js';
27
44
  *
28
45
  * There is no routing step and no agent selection. Rookery is one personal
29
46
  * assistant: the identity is fixed, and the provider only ever changes when
30
- * the caller asks for it or the current one is logged out. That matters
31
- * beyond persona - switching provider throws away `providerSessionId`, so a
32
- * router that changed its mind mid-conversation would silently drop the
33
- * thread the assistant was holding.
47
+ * the caller asks for it, when the current one is logged out, or - the one
48
+ * exception - when it runs out of quota, in which case the turn switches
49
+ * once and says so. That matters beyond persona: switching provider throws
50
+ * away `providerSessionId`, so a router that changed its mind
51
+ * mid-conversation would silently drop the thread the assistant was holding.
34
52
  *
35
53
  * What the assistant can do beyond talking is run its company: every turn
36
54
  * gets Rookery's tools through the MCP bridge, and an `assign` call from
@@ -47,6 +65,42 @@ import { EventQueue } from './util/queue.js';
47
65
  * because a third would let the assistant loop over its own switches.
48
66
  */
49
67
  const MAX_PROVIDER_PASSES = 2;
68
+ /**
69
+ * How many providers one turn may run on. The second only happens when the
70
+ * first died on its usage limit with nothing to show for it, so a switch
71
+ * costs one provider session, never the thread the turn was holding.
72
+ */
73
+ const MAX_PROVIDER_ATTEMPTS = 2;
74
+ /**
75
+ * The board watcher's schedule id, deterministic so it stays findable across a
76
+ * restart - every other schedule id is a random uuid. One per organisation.
77
+ */
78
+ function boardWatchJobId(orgId) {
79
+ return 'board-watch:' + orgId;
80
+ }
81
+ /** Wide enough that the clock rarely fires it: the event path is the fast one, this is its backstop. */
82
+ const BOARD_WATCH_SCHEDULE = '*/30 * * * *';
83
+ /**
84
+ * What the watcher is told to look at (E8, F3). It reports; it does not act.
85
+ *
86
+ * The earlier wording told it to "do whatever actually helps - reassign it,
87
+ * follow up with a fresh run on the same task, or restart it". That made the
88
+ * watcher the unattended caller with the widest reach in the system, and it
89
+ * fired hardest on `blocked` - the one status that means a person was asked
90
+ * something. The right answer to an open question is to wait for it, so the
91
+ * watcher now only says what it found. `WATCH_TOOLS` in org/tools.ts is what
92
+ * enforces that; this prompt only explains it.
93
+ */
94
+ const BOARD_WATCH_PROMPT = 'Watch the board and report what needs a person. Check list_tasks for anything failed, and for ' +
95
+ 'anything running far longer than it should. You are a backstop, not a worker: you cannot start, ' +
96
+ 'reassign, restart or close anything, and that is deliberate - deciding what to do about what you ' +
97
+ 'find belongs to the user. Leave the user one report with report_to_user at most once per pass, ' +
98
+ 'and only when something truly needs a human decision: say what you saw, how long it has been ' +
99
+ 'that way, and what you would suggest. Once you have, answer with exactly [SILENT], so the same ' +
100
+ 'thing does not reach them a second time as this run\'s outcome. A task waiting on an answer is ' +
101
+ 'working as intended, not a fault, and never a reason to write. If none of what you were shown ' +
102
+ 'is worth interrupting somebody over, do not report that everything is fine - answer with ' +
103
+ 'exactly [SILENT] instead.';
50
104
  /** Add up what two passes of one turn cost; the last pass owns the context gauge. */
51
105
  function mergeUsage(base, next) {
52
106
  if (!base)
@@ -76,6 +130,66 @@ function continuePrompt(servers) {
76
130
  'repeating what you already said.',
77
131
  ].join(' ');
78
132
  }
133
+ /* --------------------------- dream recorder --------------------------- */
134
+ /**
135
+ * Salt for the dream's session-level sample draw. A fixed literal, not a
136
+ * per-process random: the sample must survive a restart, because it is drawn
137
+ * per session - consecutive turns of one session share topic, bank cutout and
138
+ * entity neighbourhood, and a restart must not split them across the sample.
139
+ */
140
+ const DREAM_SAMPLE_SALT = 'rookery.dream.sample.v1';
141
+ /**
142
+ * The sample draw of one session as a number in [0, 1): FNV-1a over the
143
+ * session id and the salt. Cheap, stable and portable - it only has to be
144
+ * deterministic, never cryptographic.
145
+ */
146
+ function dreamSampleDraw(sessionId) {
147
+ let hash = 0x811c9dc5;
148
+ const input = sessionId + DREAM_SAMPLE_SALT;
149
+ for (let index = 0; index < input.length; index += 1) {
150
+ hash ^= input.charCodeAt(index);
151
+ hash = Math.imul(hash, 0x01000193);
152
+ }
153
+ return (hash >>> 0) / 0x1_0000_0000;
154
+ }
155
+ /** Clamp to a range, for dream keys read outside the patch schema (E21). */
156
+ function clampNumber(value, lo, hi) {
157
+ return Math.min(hi, Math.max(lo, value));
158
+ }
159
+ /**
160
+ * The declared box around one turn's realised recall policy: the parameter
161
+ * space a replay of this turn's frame may move in. The interval widths are
162
+ * the house widths the night's grid places its candidates at - weights
163
+ * +/-0.1, threshold [0.05, 0.3], hop weights +/-0.15 and +/-0.2 - always
164
+ * stretched to contain the realised point and never past the valid range,
165
+ * so a knob the user turned cannot sit outside the box that is supposed to
166
+ * close over it. `limitMax` arrives already containing the realised limit.
167
+ */
168
+ function declaredDreamBox(policy, limitMax) {
169
+ const weight = (value) => [Math.max(0, value - 0.1), Math.min(1, value + 0.1)];
170
+ return {
171
+ limitMax,
172
+ w: {
173
+ relevance: weight(policy.w.relevance),
174
+ importance: weight(policy.w.importance),
175
+ recency: weight(policy.w.recency),
176
+ usage: weight(policy.w.usage),
177
+ },
178
+ threshold: [Math.min(0.05, policy.threshold), Math.max(0.3, policy.threshold)],
179
+ hopEntity: [Math.max(0, policy.hopEntity - 0.15), Math.min(1, policy.hopEntity + 0.15)],
180
+ hopEdge: [Math.max(0, policy.hopEdge - 0.2), Math.min(1, policy.hopEdge + 0.2)],
181
+ kinds: policy.kinds,
182
+ minImportance: policy.minImportance,
183
+ };
184
+ }
185
+ /** Where the rights a conversation was last used with are kept. */
186
+ function sessionPermissionKey(sessionId) {
187
+ return 'session:permission:' + sessionId;
188
+ }
189
+ /** The terminal registry's key for a conversation - runs use their assignment id. */
190
+ export function conversationTerminalKey(sessionId) {
191
+ return 'chat:' + sessionId;
192
+ }
79
193
  export class Assistant extends EventEmitter {
80
194
  config;
81
195
  store;
@@ -97,6 +211,13 @@ export class Assistant extends EventEmitter {
97
211
  * and can be started by hand from the memory page.
98
212
  */
99
213
  sleep;
214
+ /**
215
+ * The questions the assistant has put to the user and is waiting on. Held
216
+ * here, next to the company and the clock, because a question outlives the
217
+ * surface it appeared on: whoever is at a screen may answer it, so it
218
+ * cannot belong to one socket, one terminal or one chat.
219
+ */
220
+ questions;
100
221
  /**
101
222
  * Whether a notification would actually reach the user right now. Set by
102
223
  * whoever owns the outgoing channels (the server, for its gateways); left
@@ -105,11 +226,39 @@ export class Assistant extends EventEmitter {
105
226
  * a blocked recipient or a channel that was switched off mid-session.
106
227
  */
107
228
  notifyProbe;
229
+ /** Takes over report-back turns so people can watch them; see `TurnRunner`. */
230
+ turnRunner;
231
+ /**
232
+ * The turn each conversation is running or waiting to run, chained: one
233
+ * conversation answers one message at a time. A report-back arriving while
234
+ * the user's own message is being answered waits its turn instead of
235
+ * talking over it - and a conversation's terminal could not take two at
236
+ * once anyway.
237
+ */
238
+ #sessionTurns = new Map();
239
+ /** Conversation terminals by session id (T1). */
240
+ #chatTerminals = new Map();
241
+ /**
242
+ * The last status seen for a task, by id - only so the board-watch
243
+ * subscriber can tell a fresh landing in `failed` apart from an unrelated
244
+ * edit to a task that was already sitting there. Never read for anything
245
+ * else.
246
+ *
247
+ * Filled from the board when the clock starts, not left empty: a map that
248
+ * starts empty makes every already-failed task look like a fresh landing,
249
+ * so the first harmless edit to any of them after a restart - a priority,
250
+ * a title - would wake the watcher for a state it had already reported.
251
+ * Edge-triggered has to mean edge-triggered across a restart as well.
252
+ */
253
+ #taskStatusSeen = new Map();
108
254
  constructor(options = {}) {
109
255
  super();
110
256
  this.config = loadConfig(options.config ?? {});
111
257
  this.store = options.store ?? new Store(databasePath(this.config));
112
258
  this.providers = options.registry ?? new ProviderRegistry();
259
+ // Layer in configured provider profiles (e.g. GLM). A no-op when there
260
+ // are none, and harmless for the fixed provider lists tests inject.
261
+ this.providers.sync(this.config);
113
262
  this.log =
114
263
  options.logger ??
115
264
  (this.config.logLevel === 'silent'
@@ -121,14 +270,32 @@ export class Assistant extends EventEmitter {
121
270
  runner: (job, run, signal) => this.#runScheduled(job, run, signal),
122
271
  logger: this.log,
123
272
  timeoutMs: this.config.org.assignmentTimeoutMs,
273
+ // A run's outcome goes the one road to the user. A closure, because
274
+ // the controller is built below; no run can end before it exists.
275
+ notify: (input) => {
276
+ this.org.notifyUser(input);
277
+ },
124
278
  });
125
279
  // Before the controller: the `sleep_now` tool needs it at construction.
280
+ // The promotion hook is a closure rather than `this.org.notifyUser`
281
+ // itself for exactly that reason - the controller does not exist yet
282
+ // here, and it does by the time a night can promote anything.
126
283
  this.sleep = new SleepRunner({
127
284
  store: this.store,
128
285
  registry: this.providers,
129
286
  config: this.config,
130
287
  logger: this.log,
288
+ onPromotion: (notice) => this.announcePromotion(notice),
131
289
  });
290
+ // Before the controller, like the night shift: the `ask_user` tool needs
291
+ // it at construction. Its own emitter is what the Assistant re-broadcasts:
292
+ // a question-closed can arrive after the asking turn's queue has closed -
293
+ // answered late, or cancelled when the turn's token was retired - and the
294
+ // turn stream would drop it exactly then, so the registry is the one wire
295
+ // both halves can rely on.
296
+ this.questions = new QuestionRegistry();
297
+ this.questions.on('question', (event) => this.emit('question', event));
298
+ this.questions.on('question-closed', (event) => this.emit('question-closed', event));
132
299
  this.org = new OrgController({
133
300
  store: this.store,
134
301
  registry: this.providers,
@@ -137,6 +304,7 @@ export class Assistant extends EventEmitter {
137
304
  logger: this.log,
138
305
  cron: this.cron,
139
306
  sleep: this.sleep,
307
+ questions: this.questions,
140
308
  // The `notify` tool asks this instead of a transport it cannot see. A
141
309
  // listener on `notify` is the floor, not the answer: a push service
142
310
  // attaches once at startup and stays attached while it is switched
@@ -147,22 +315,145 @@ export class Assistant extends EventEmitter {
147
315
  });
148
316
  this.cron.on('cron', (event) => this.emit('cron', event));
149
317
  this.cron.on('message', (event) => this.emit('message', event));
318
+ // Only a scheduler without the `notify` hook emits this itself; wired
319
+ // anyway so an outcome can never be written without being announced.
320
+ this.cron.on('notification', (event) => this.emit('notification', event));
150
321
  // Every client watches the brain fall asleep and wake up again.
151
322
  this.sleep.on('sleep', (event) => this.emit('sleep', event));
152
323
  // Anything an agent does is interesting to every client, not only the
153
324
  // turn that caused it: the org page shows activity live.
154
325
  this.org.on('assignment', (event) => this.emit('assignment', event));
326
+ // Live transcript lines of a running assignment, for whoever opted into
327
+ // watching that run - the TUI's watch mode and the server's watching
328
+ // sockets, never a blanket fan-out.
329
+ this.org.on('assignment-log', (frame) => this.emit('assignment-log', frame));
155
330
  this.org.on('message', (event) => this.emit('message', event));
331
+ // Everything that reaches the user outside a conversation, and every
332
+ // line added to a card's activity - the two carriers that replaced mail
333
+ // (docs/concepts/mail-removal-notifications-and-task-activity.md).
334
+ this.org.on('notification', (event) => this.emit('notification', event));
335
+ this.org.on('task-event', (event) => this.emit('task-event', event));
156
336
  this.org.on('task', (event) => this.emit('task', event));
337
+ // The watcher's fast path (section 5): a task landing in `failed` or
338
+ // `blocked` wakes it through the same event machinery a webhook or an
339
+ // IMAP listener uses, no different from any other schedule.
340
+ this.org.on('task', (event) => this.#onTaskEvent(event));
157
341
  this.org.on('changed', (change) => this.emit('changed', change));
158
342
  // The assistant reaching out on its own initiative - no HTTP, no
159
343
  // Telegram here, just an event a channel in another package can listen
160
344
  // for and act on however it likes.
161
345
  this.org.on('notify', (event) => this.emit('notify', event));
346
+ // Work handed off in the background has ended: the conversation that
347
+ // handed it off hears about it as a turn of its own (R2/R3).
348
+ this.org.on('report-back', (event) => this.#onReportBack(event));
349
+ }
350
+ /* --------------------------- report-back --------------------------- */
351
+ #onReportBack(event) {
352
+ const session = this.store.getSession(event.sessionId);
353
+ // A scheduled run has nobody reading along, and a conversation that was
354
+ // deleted has nobody at all. The ending still belongs to somebody, and
355
+ // the only one left is the user: it goes to them as a notification
356
+ // instead of a turn nobody would see - a question most of all.
357
+ if (!session || (session.kind !== 'chat' && session.kind !== 'voice')) {
358
+ const task = this.store.org.getTask(event.taskId);
359
+ if (!task)
360
+ return;
361
+ const agent = task.assigneeId ? this.store.org.getAgent(task.assigneeId) : null;
362
+ const question = task.status === 'blocked' ? this.store.org.lastTaskEvent(task.id, 'question') : null;
363
+ this.org.notifyUser({
364
+ orgId: task.orgId,
365
+ ...taskNotification(task, agent, question?.text),
366
+ ...(session ? { sessionId: session.id } : {}),
367
+ });
368
+ return;
369
+ }
370
+ // Archived while the work ran: bringing it back is better than burying
371
+ // the answer where nobody looks.
372
+ if (session.archived)
373
+ this.store.updateSession(session.id, { archived: false });
374
+ this.followUp({ sessionId: session.id, text: event.notice, taskId: event.taskId });
375
+ }
376
+ /**
377
+ * A turn in a conversation that nobody typed: Rookery telling the
378
+ * assistant something it has to pass on - today, how work it handed off
379
+ * ended. It runs like any other turn of that conversation, after whatever
380
+ * is being answered there now, and the host shows it live (`turnRunner`).
381
+ * Returns the turn id.
382
+ */
383
+ followUp(input) {
384
+ const turnId = randomUUID();
385
+ const controller = new AbortController();
386
+ const permission = this.store.getMeta(sessionPermissionKey(input.sessionId));
387
+ const events = this.#reported(this.chat({
388
+ text: input.text,
389
+ sessionId: input.sessionId,
390
+ turnId,
391
+ origin: 'system',
392
+ ...(permission ? { permission } : {}),
393
+ signal: controller.signal,
394
+ }), input);
395
+ if (this.turnRunner) {
396
+ this.turnRunner({ turnId, sessionId: input.sessionId, controller, events });
397
+ }
398
+ else {
399
+ void (async () => {
400
+ for await (const event of events)
401
+ void event;
402
+ })().catch((error) => this.log.warn('Follow-up turn failed', { error: String(error) }));
403
+ }
404
+ return turnId;
405
+ }
406
+ /** Passes a follow-up's events through and says how it ended, once, however it ends. */
407
+ async *#reported(events, input) {
408
+ let text = '';
409
+ let error;
410
+ try {
411
+ for await (const event of events) {
412
+ if (event.type === 'done')
413
+ text = event.text;
414
+ else if (event.type === 'error' && event.fatal)
415
+ error = event.message;
416
+ yield event;
417
+ }
418
+ }
419
+ catch (thrown) {
420
+ error = thrown.message;
421
+ throw thrown;
422
+ }
423
+ finally {
424
+ const done = {
425
+ sessionId: input.sessionId,
426
+ ...(input.taskId ? { taskId: input.taskId } : {}),
427
+ text,
428
+ ...(error ? { error } : {}),
429
+ };
430
+ this.emit('follow-up', done);
431
+ }
432
+ }
433
+ /** Wait for this conversation's turn; the returned function hands it on. */
434
+ async #takeTurn(sessionId) {
435
+ const previous = this.#sessionTurns.get(sessionId) ?? Promise.resolve();
436
+ let release;
437
+ const mine = new Promise((resolve) => {
438
+ release = resolve;
439
+ });
440
+ const tail = previous.then(() => mine);
441
+ this.#sessionTurns.set(sessionId, tail);
442
+ await previous;
443
+ return () => {
444
+ release();
445
+ if (this.#sessionTurns.get(sessionId) === tail)
446
+ this.#sessionTurns.delete(sessionId);
447
+ };
162
448
  }
163
449
  close() {
450
+ // Anything still waiting on a person is settled first: an open question
451
+ // holds a promise inside a tool call, and shutting down around it would
452
+ // leave that call to time out long after there is anybody to answer.
453
+ this.questions.cancelAll();
164
454
  this.cron.stop();
165
455
  void this.org.bridge.close();
456
+ void sharedCodexBridge.close();
166
457
  this.store.close();
167
458
  }
168
459
  /* ---------------------------- sessions ---------------------------- */
@@ -192,6 +483,11 @@ export class Assistant extends EventEmitter {
192
483
  return this.store.listSessions({ limit, agentId, kind, includeArchived });
193
484
  }
194
485
  deleteSession(id) {
486
+ // A frame is a verbatim store of what was said in this session, so it
487
+ // may never outlive the session it quotes (R17). Dropped before the
488
+ // session row goes, the same safe direction the memory-retiring store
489
+ // methods take for their owner's frames.
490
+ this.store.dropDreamFramesForSession(id);
195
491
  this.store.deleteSession(id);
196
492
  }
197
493
  /** Forget the provider-side thread so the next turn starts cold. */
@@ -202,6 +498,13 @@ export class Assistant extends EventEmitter {
202
498
  .run(id);
203
499
  }
204
500
  /* ------------------------------ memory ---------------------------- */
501
+ /**
502
+ * Read-only memory search for surfaces that inspect the bank. This is the
503
+ * `site: 'inspect'` population of the dream's vocabulary: never framed,
504
+ * never scored - the recorder sits at the conversational call site, never
505
+ * inside `recall` (R19), precisely so a browser search or a CLI call with a
506
+ * free-form owner cannot end up in the night's pool.
507
+ */
205
508
  recallMemories(text, limit) {
206
509
  return recall(this.store, {
207
510
  text,
@@ -244,9 +547,10 @@ export class Assistant extends EventEmitter {
244
547
  }
245
548
  /**
246
549
  * Make sure the nightly run has a schedule. Called once when the clock
247
- * starts. The job is an ordinary `cron_jobs` row, so it shows up on the
248
- * schedules page, can be edited, switched off or run by hand like any
249
- * other - there is no second, hidden timer anywhere.
550
+ * starts. The job is an ordinary `cron_jobs` row - one timer, no second
551
+ * hidden one anywhere - but it is Rookery's internal clockwork, not a
552
+ * user schedule: every list filters it out, and the memory page is the
553
+ * only place it is shown and managed.
250
554
  */
251
555
  ensureSleepSchedule() {
252
556
  const sleep = this.config.memory.sleep;
@@ -254,7 +558,9 @@ export class Assistant extends EventEmitter {
254
558
  return null;
255
559
  try {
256
560
  const organization = this.org.activeOrganization();
257
- const existing = this.cron.list(organization.id).find((job) => job.kind === 'sleep');
561
+ const existing = this.cron
562
+ .list(organization.id, { includeSystem: true })
563
+ .find((job) => job.kind === 'sleep');
258
564
  if (existing) {
259
565
  // Follow the config when the user changes it there, but never
260
566
  // re-enable a job they switched off by hand.
@@ -277,22 +583,233 @@ export class Assistant extends EventEmitter {
277
583
  return null;
278
584
  }
279
585
  }
586
+ /* ------------------------------- board watch ----------------------------- */
587
+ /**
588
+ * Make sure the board has a watcher. Called once when the clock starts.
589
+ *
590
+ * Unlike the nightly memory schedule, this row is an ordinary, visible
591
+ * `cron_jobs` entry - E8 wants it editable and switchable in the same UI as
592
+ * every other job, not hidden system clockwork. Seeding is idempotent by
593
+ * id: a second call, on a later start, finds the same row and returns it
594
+ * untouched, whatever a person did to it since - edited the schedule,
595
+ * rewritten the prompt, switched it off. Only a row that does not exist yet
596
+ * gets created.
597
+ */
598
+ ensureBoardWatchSchedule() {
599
+ try {
600
+ const organization = this.org.activeOrganization();
601
+ // Seed the edge detector before the subscriber can fire: every task
602
+ // already on the board counts as "seen in this state", so only a real
603
+ // transition from here on wakes the watcher. Without this the first
604
+ // unrelated edit to an old failed task would look like a new failure.
605
+ for (const task of this.store.org.listTasks(organization.id, { anyLevel: true, limit: 5000 })) {
606
+ this.#taskStatusSeen.set(task.id, task.status);
607
+ }
608
+ const id = boardWatchJobId(organization.id);
609
+ const existing = this.cron.get(id);
610
+ if (existing && existing.orgId === organization.id)
611
+ return existing;
612
+ return this.cron.create({
613
+ id,
614
+ orgId: organization.id,
615
+ name: 'Board watch',
616
+ schedule: BOARD_WATCH_SCHEDULE,
617
+ triggerMode: 'schedule',
618
+ // The clock is the backstop; the fast path is the task-event
619
+ // subscriber below. A minute keeps ten failures or blocks in one
620
+ // burst to one run, exactly like every other event-fed schedule.
621
+ eventCooldownMs: 60_000,
622
+ kind: 'assistant',
623
+ prompt: BOARD_WATCH_PROMPT,
624
+ createdBy: 'assistant',
625
+ });
626
+ }
627
+ catch (error) {
628
+ this.log.warn('Could not set up the board watcher', { error: error.message });
629
+ return null;
630
+ }
631
+ }
632
+ /**
633
+ * What the board watcher would have something to say about, decided in
634
+ * SQL rather than by a model.
635
+ *
636
+ * The watcher used to be a full turn every thirty minutes plus one per
637
+ * event - roughly fifty model runs a day whose usual answer was
638
+ * `[SILENT]`. "Is anything wrong" is a query; only "is this worth
639
+ * interrupting somebody over, and how do I put it" needs judgment. So the
640
+ * clock runs this first, the model is never started unless this finds
641
+ * something, and when it does the findings go into the prompt: the turn
642
+ * begins already knowing what it is there for.
643
+ *
644
+ * Nothing is reported twice. Everything that went wrong before the
645
+ * watcher last actually said something was covered by that report, so
646
+ * only what became true since then is news. That is what stops a board
647
+ * with one permanently broken task on it from mailing about it
648
+ * forty-eight times a day.
649
+ */
650
+ #boardAttention(orgId, jobId) {
651
+ const now = Date.now();
652
+ // The mark is stored, not reconstructed from the run history.
653
+ //
654
+ // Reading "the newest run that produced a result" out of the last N
655
+ // runs looked equivalent and was not, in three ways. A quiet board
656
+ // writes a silent run every half hour, so after ten hours the speaking
657
+ // run had fallen out of any fixed window and every old failure became
658
+ // news again. A pass the model ended with `[SILENT]` left no result at
659
+ // all, so a finding it had deliberately judged not worth reporting came
660
+ // back every thirty minutes for ever. And both readings confused two
661
+ // different questions: what the model chose to say, and what it was
662
+ // shown. This answers the second - the mark moves when the findings are
663
+ // handed over, whatever the model then decides to do with them.
664
+ const markKey = 'board-watch:seen:' + jobId;
665
+ const since = Number(this.store.getMeta(markKey) ?? 0);
666
+ // A run that has outlived twice its own hard stop is not slow: either
667
+ // its timer never fired or the row was orphaned by a crash.
668
+ const stuckAfter = this.config.org.assignmentTimeoutMs * 2;
669
+ const lines = [];
670
+ // An explicit ceiling, and a high one. `listTasks` defaults to 100
671
+ // ordered by priority then oldest-first, so on a board that has built up
672
+ // history the newest failure - the one that matters - is exactly the row
673
+ // that falls off the end and is never seen.
674
+ for (const task of this.store.org.listTasks(orgId, { anyLevel: true, status: ['failed', 'running'], limit: 5000 })) {
675
+ const label = '[' + task.id.slice(0, 8) + '] ' + task.title;
676
+ if (task.status === 'failed') {
677
+ const landed = task.finishedAt ?? task.updatedAt;
678
+ if (landed <= since)
679
+ continue;
680
+ const runs = this.store.org.taskRunCount(task.id);
681
+ lines.push(label + ' failed' + (runs > 1 ? ' on run ' + runs : '') +
682
+ (task.error ? ': ' + task.error : '') + ' (' + formatAge(landed, now, 'minute') + ' ago)');
683
+ continue;
684
+ }
685
+ const started = task.startedAt ?? task.updatedAt;
686
+ // The moment it became stuck, not the moment we noticed: a task that
687
+ // crossed that line before the last report was in that report.
688
+ const crossed = started + stuckAfter;
689
+ if (crossed > now || crossed <= since)
690
+ continue;
691
+ lines.push(label + ' has been running ' + formatAge(started, now, 'minute') + ' with no end');
692
+ }
693
+ // Only a pass that actually found something moves the mark: a quiet
694
+ // look must not silently swallow a failure that lands a second later.
695
+ if (lines.length)
696
+ this.store.setMeta(markKey, String(now));
697
+ return lines;
698
+ }
699
+ /**
700
+ * A task crossed into `failed` - the one transition the watcher cares
701
+ * about (E8, section 5). The clock behind it fires every thirty minutes
702
+ * regardless; this is only the fast path, and it is edge-triggered on
703
+ * purpose: a task that merely stays failed while its title or priority
704
+ * changes must not re-fire the watcher on every one of those unrelated
705
+ * edits, only on actually landing in the state.
706
+ *
707
+ * `blocked` used to wake it too, and that was backwards. Blocked means an
708
+ * agent asked a person something and the board is correctly waiting for
709
+ * the answer. Waking a watcher on it meant the system's reaction to being
710
+ * asked a question was to go and do something instead - within a minute,
711
+ * while the person was still reading it.
712
+ */
713
+ #onTaskEvent(event) {
714
+ if (event.type !== 'task')
715
+ return;
716
+ const { task } = event;
717
+ const attention = task.status === 'failed';
718
+ const before = this.#taskStatusSeen.get(task.id);
719
+ this.#taskStatusSeen.set(task.id, task.status);
720
+ if (!attention || before === task.status)
721
+ return;
722
+ const id = boardWatchJobId(task.orgId);
723
+ void this.cron.runEvent(id, 'task ' + task.id.slice(0, 8) + ' turned ' + task.status).catch((error) => {
724
+ this.log.warn('Could not wake the board watcher', { error: String(error) });
725
+ });
726
+ }
280
727
  /* ------------------------------- chat ----------------------------- */
281
- /** One conversational turn, streamed. Assignments the turn starts ride the same stream. */
728
+ /**
729
+ * One conversational turn, streamed - and journalled while it runs.
730
+ *
731
+ * The wrapper is the single place every yielded event passes through, which
732
+ * is what makes the journal faithful: whatever a live client saw, in the
733
+ * order it saw it, numbered once each. A client that arrives late - a
734
+ * reloaded tab, another browser - reads the same events back and continues
735
+ * from the same numbers, so rejoining can neither duplicate nor drop.
736
+ *
737
+ * `#chatTurn` does the work and opens the journal once its session is
738
+ * resolved; events yielded before that (a rejected empty prompt, say) are
739
+ * ephemeral by nature and stay unjournalled.
740
+ */
282
741
  async *chat(input) {
742
+ // One conversation answers one message at a time. A new conversation has
743
+ // nothing to wait for: nobody else can know its id yet.
744
+ const release = input.sessionId ? await this.#takeTurn(input.sessionId) : undefined;
745
+ try {
746
+ yield* this.#journalledChat(input);
747
+ }
748
+ finally {
749
+ release?.();
750
+ }
751
+ }
752
+ async *#journalledChat(input) {
753
+ const turnId = input.turnId ?? randomUUID();
754
+ const startedAt = Date.now();
755
+ const journal = { begun: false };
756
+ // The backstop a turn never had. A run and a schedule both stop
757
+ // themselves; a turn ran until its provider process did, and over
758
+ // `POST /api/chat` - which passes no signal - nobody could interrupt
759
+ // it. The caller's own signal still works and still wins; this only
760
+ // adds an end to turns that would otherwise not have one.
761
+ const guard = new AbortController();
762
+ const onCallerAbort = () => guard.abort();
763
+ // A signal that was already aborted never fires the event again, so
764
+ // forwarding only through the listener would start a turn the caller
765
+ // had already given up on.
766
+ if (input.signal?.aborted)
767
+ guard.abort();
768
+ else
769
+ input.signal?.addEventListener('abort', onCallerAbort, { once: true });
770
+ const timer = setTimeout(() => guard.abort(), this.config.turns.timeoutMs);
771
+ // Node keeps the process alive for a pending timer; this one must never
772
+ // be the reason a CLI command refuses to exit.
773
+ timer.unref?.();
774
+ const guarded = { ...input, signal: guard.signal };
775
+ try {
776
+ for await (const event of this.#chatTurn(guarded, turnId, journal)) {
777
+ if (journal.begun)
778
+ this.store.turns.append(turnId, event);
779
+ yield event;
780
+ }
781
+ if (journal.begun) {
782
+ this.store.turns.settle(turnId, 'done', Date.now());
783
+ // Only an orderly end is an episode: a turn that died mid-flight has
784
+ // no outcome to judge a trajectory against (concept 7.2).
785
+ this.#recordTrialEpisode(turnId, journal, startedAt);
786
+ }
787
+ }
788
+ catch (error) {
789
+ // The turn died mid-flight. Whatever reached the journal is the only
790
+ // record of it - it stays, marked, rather than vanishing whole.
791
+ if (journal.begun)
792
+ this.store.turns.settle(turnId, 'interrupted', Date.now());
793
+ throw error;
794
+ }
795
+ finally {
796
+ clearTimeout(timer);
797
+ input.signal?.removeEventListener('abort', onCallerAbort);
798
+ }
799
+ }
800
+ async *#chatTurn(input, turnId, journal) {
283
801
  const prompt = input.text.trim();
284
802
  if (!prompt) {
285
803
  yield { type: 'error', message: 'Nothing to send.', fatal: true };
286
804
  return;
287
805
  }
288
806
  const session = this.#resolveSession(input);
289
- // The counterpart: an agent for a direct chat, otherwise the assistant.
290
- const agent = session.agentId ? this.store.org.getAgent(session.agentId) : null;
291
- if (session.agentId && !agent) {
292
- yield { type: 'error', message: 'The agent this conversation belonged to no longer exists.', fatal: true };
293
- return;
294
- }
295
- const owner = agent ? agent.id : ASSISTANT_MEMORY_OWNER;
807
+ this.store.turns.begin(turnId, session.id, 'chat', Date.now());
808
+ journal.begun = true;
809
+ journal.sessionId = session.id;
810
+ // Chat is exclusively the assistant's own conversation; a stale
811
+ // `agentId` on an old session is never read here any more.
812
+ const owner = ASSISTANT_MEMORY_OWNER;
296
813
  if (input.projectId && input.projectId !== session.projectId) {
297
814
  this.store.updateSession(session.id, { projectId: input.projectId });
298
815
  session.projectId = input.projectId;
@@ -301,241 +818,585 @@ export class Assistant extends EventEmitter {
301
818
  const providerId = await this.providers.resolveUsable(wanted);
302
819
  if (!providerId) {
303
820
  const statuses = await this.providers.statuses();
304
- const detail = statuses.map((s) => s.id + ': ' + (s.detail ?? 'unavailable')).join(' | ');
821
+ // A provider parked for quota says so here rather than hiding behind
822
+ // its login state: "out of quota" tells the user what to wait for.
823
+ const detail = statuses
824
+ .map((s) => s.id + ': ' + (providerBlocked(s.id) ? 'out of quota' : (s.detail ?? 'unavailable')))
825
+ .join(' | ');
305
826
  yield { type: 'error', message: 'No AI provider is ready. ' + detail, fatal: true };
306
827
  return;
307
828
  }
308
829
  if (providerId !== wanted) {
309
- yield { type: 'status', label: 'provider', detail: wanted + ' is not logged in, using ' + providerId };
830
+ yield { type: 'status', label: 'provider', detail: this.#switchReason(wanted, providerId) };
310
831
  }
311
832
  // Resuming the provider's own thread only works on the same provider.
312
833
  const resumed = Boolean(session.providerSessionId) && session.provider === providerId;
313
834
  const model = input.model ?? session.model ?? this.config.defaultModel;
314
835
  const effort = input.effort ?? this.config.defaultEffort;
315
836
  let memories = [];
837
+ /**
838
+ * The recall as it went out on the wire, kept so the ordered transcript
839
+ * can carry it too: the recall happens before the first provider attempt,
840
+ * and `turnBlocks` below is only born once one is about to start.
841
+ */
842
+ let recall;
316
843
  if (this.config.memory.enabled) {
317
844
  yield { type: 'status', label: 'recalling', detail: 'searching memory' };
318
- const matched = recall(this.store, {
319
- text: prompt,
320
- owner,
321
- limit: this.config.memory.recallLimit,
322
- threshold: this.config.memory.recallThreshold,
323
- hopEntity: this.config.memory.graph.hopEntity,
324
- hopEdge: this.config.memory.graph.hopEdge,
325
- });
326
- const profile = coreProfile(this.store, {
327
- owner,
328
- limit: Math.max(3, Math.floor(this.config.memory.recallLimit / 2)),
329
- });
330
- const byId = new Map();
331
- for (const memory of profile)
332
- byId.set(memory.id, memory);
333
- for (const memory of matched)
334
- byId.set(memory.id, memory);
335
- // Of a contradicting pair only the newer sentence goes into the prompt;
336
- // the older one stays in the bank and stays visible in the inspector.
337
- memories = dropContradicted(this.store, [...byId.values()]).sort((a, b) => b.score - a.score);
845
+ // One truth about the recall parameters (concept 9.3): the resolver
846
+ // clamps at read time and both the turn and the recorder read it here,
847
+ // so a config change cannot leave the record and the live turn
848
+ // disagreeing about which policy produced the prompt.
849
+ const policy = resolvePolicy(this.store, this.config, owner, 'recall');
850
+ memories = this.#turnMemories(session, owner, prompt, policy, turnId);
338
851
  if (memories.length) {
339
- yield { type: 'memory', action: 'recalled', count: memories.length, items: memories };
852
+ // The turn id travels with the list the surface is about to render:
853
+ // a click on one of these rows becomes a label about THIS turn, not
854
+ // about the session it happened in (S6, concept 4.2b).
855
+ recall = { type: 'memory', action: 'recalled', count: memories.length, items: memories, turnId };
856
+ yield recall;
340
857
  }
341
858
  }
342
- const history = resumed ? [] : this.store.getMessages(session.id, this.config.memory.workingWindow);
343
- // The company block: who works here, what is running, what arrived in
344
- // the inbox. Read once per turn; the inbox is then marked as read.
859
+ // Read before the turn stores its own user message: a retry that cannot
860
+ // resume the dead provider's thread rebuilds its prompt from this.
861
+ const turnHistory = this.store.getMessages(session.id, this.config.memory.workingWindow);
862
+ const history = resumed ? [] : turnHistory;
863
+ // The company block: who works here and what is running.
345
864
  const organization = this.org.activeOrganization();
346
865
  const snapshot = this.org.snapshot(organization.id);
347
- const inbox = this.store.org.inbox(organization.id, agent?.id ?? null, { unreadOnly: true });
348
866
  const project = session.projectId ? (this.store.org.getProject(session.projectId) ?? undefined) : undefined;
349
- if (inbox.length)
350
- this.store.org.markRead(inbox.map((message) => message.id));
351
- // The hub decides which extra MCP servers this turn gets, and the prompt
352
- // carries one paragraph per server plus the index of skills to open.
353
- const who = agent ? 'agent' : 'assistant';
354
- await ensureToolServers(this.config, who, providerId, project?.id, (id, error) => this.log.warn('Tool server could not prepare', { id, error: error.message }));
355
- const extra = toolServersFor(this.config, who, providerId, project?.id);
356
- // The assistant also hears about the servers it could attach but has not:
357
- // a switch it does not know about is a wall it cannot climb.
358
- const toolHints = [...extra.hints, dormantToolsHint(this.config, who, project?.id)].filter(Boolean);
359
- const skillsIndex = renderSkillsIndex(this.skills.for(who));
360
- const systemPrompt = agent
361
- ? buildAgentChatPrompt({
362
- config: this.config, agent, snapshot, memories, inbox, history, resumed, project,
363
- toolHints, skillsIndex,
364
- })
365
- : buildSystemPrompt({
867
+ // Who is asking: the assistant. The tool servers and the prompt built on
868
+ // them are per provider attempt, because each provider attaches its own.
869
+ const who = 'assistant';
870
+ // Rookery's own shelf in full, and one paragraph for the far larger one
871
+ // installed in Claude Code: what is there, not what it says. Then the few
872
+ // that look like this turn - searched here rather than left to a tool call
873
+ // the model has to think of, the same way its memories arrive.
874
+ const ownSkills = this.skills.for(who);
875
+ const skillsIndex = [
876
+ renderSkillsIndex(ownSkills),
877
+ renderExternalSkillsHint(this.config, who),
878
+ renderSkillMatches(matchSkills(this.config, who, ownSkills, prompt)),
879
+ ]
880
+ .filter(Boolean)
881
+ .join('\n\n');
882
+ // The journal's id, on the message (concept 9.4): it is what makes a
883
+ // quote from this prompt locatable to this exact turn later, instead of
884
+ // to a position counted off the transcript.
885
+ const fromSystem = input.origin === 'system';
886
+ // The rights this conversation was last used with, so a turn nobody
887
+ // typed - a report-back - runs with them rather than with the default.
888
+ if (!fromSystem && input.permission)
889
+ this.store.setMeta(sessionPermissionKey(session.id), input.permission);
890
+ this.store.addMessage({ sessionId: session.id, role: fromSystem ? 'system' : 'user', content: prompt, turnId });
891
+ if (!fromSystem && session.messageCount === 0 && session.title === 'New conversation') {
892
+ this.store.updateSession(session.id, { title: deriveTitle(prompt) });
893
+ }
894
+ // Chat and terminal are one process (T1): an ordinary conversation is
895
+ // answered by typing into its Claude Code terminal. Everything above -
896
+ // the recall, the stored message - is shared; what follows differs.
897
+ if (await this.#answersInTerminal(session, input, providerId)) {
898
+ yield* this.#terminalTurn({
899
+ session,
900
+ prompt,
901
+ memories,
902
+ project,
903
+ snapshotOrgId: organization.id,
904
+ providerId,
905
+ model,
906
+ effort,
907
+ input,
908
+ turnId,
909
+ recall,
910
+ ownSkills,
911
+ });
912
+ return;
913
+ }
914
+ // Answered headless this time - a voice turn, say. The terminal must not
915
+ // go on writing to the same transcript in parallel.
916
+ await this.#closeChatTerminal(session.id);
917
+ const started = Date.now();
918
+ let answer = '';
919
+ const toolCalls = [];
920
+ // The same turn as an ordered transcript: text, thinking and tools in
921
+ // arrival order, kept beside the flat views. One instance spans every
922
+ // pass of every attempt; a provider fallback is the only reset.
923
+ const turnBlocks = new TurnBlocks();
924
+ // What was put in front of the answer, first in the transcript because it
925
+ // was first in the turn. It survives `clear()`, so a fallback attempt
926
+ // keeps it too.
927
+ if (recall)
928
+ turnBlocks.apply(recall);
929
+ let providerSessionId = resumed ? session.providerSessionId : undefined;
930
+ let usage;
931
+ let lastFatal = null;
932
+ /** The provider and model the turn ends up having run with. */
933
+ let usedProvider = providerId;
934
+ let usedModel = model;
935
+ const tried = new Set([providerId]);
936
+ for (let attempt = 1; attempt <= MAX_PROVIDER_ATTEMPTS; attempt += 1) {
937
+ const pid = usedProvider;
938
+ // A different backend serves different names; the fallback provider's
939
+ // own default stands in for a model it has never heard of.
940
+ usedModel = attempt === 1 && pid === wanted ? model : remapModel(pid, model);
941
+ // The hub decides which extra MCP servers this attempt gets, and the
942
+ // prompt carries one paragraph per server plus the index of skills to
943
+ // open. Provider-scoped, so a switch attaches its own set.
944
+ const extra = toolServersFor(this.config, who, pid, project?.id);
945
+ // The assistant also hears about the servers it could attach but has not:
946
+ // a switch it does not know about is a wall it cannot climb.
947
+ const toolHints = [...extra.hints, dormantToolsHint(this.config, who, project?.id)].filter(Boolean);
948
+ const systemPrompt = buildSystemPrompt({
366
949
  config: this.config,
367
950
  query: prompt,
368
951
  memories,
369
- history,
370
- resumed,
952
+ // A retry cannot resume the dead provider's thread, so it rebuilds
953
+ // its context from the history it still has.
954
+ history: attempt === 1 ? history : turnHistory,
955
+ resumed: attempt === 1 && resumed,
371
956
  // A voice session speaks whichever surface the turn came from.
372
957
  voice: input.voice ?? session.kind === 'voice',
373
- orgBlock: assistantOrgBlock(this.config, snapshot, inbox, project, this.cron.list(organization.id)),
958
+ orgBlock: assistantOrgBlock(this.config, snapshot, project, this.cron.list(organization.id), this.store),
374
959
  toolHints,
375
960
  skillsIndex,
376
961
  // Lets the memory block group itself by entity.
377
962
  store: this.store,
378
963
  });
379
- this.store.addMessage({ sessionId: session.id, role: 'user', content: prompt });
380
- if (session.messageCount === 0 && session.title === 'New conversation') {
381
- this.store.updateSession(session.id, { title: deriveTitle(prompt) });
964
+ const provider = this.providers.get(pid);
965
+ // Only the first attempt may resume the provider's own thread; a
966
+ // fallback starts a fresh one on the new backend.
967
+ providerSessionId = attempt === 1 && resumed ? session.providerSessionId : undefined;
968
+ let failed = false;
969
+ yield { type: 'session', sessionId: session.id, providerSessionId, provider: pid, model: usedModel };
970
+ // The assistant stays in the workspace, not a project directory - it is
971
+ // a person, not Claude Code's coding agent.
972
+ const cwd = this.config.workspace;
973
+ // What this pass of the provider is run with. A turn usually has exactly
974
+ // one pass; see the continuation below for why it sometimes has two.
975
+ let passPrompt = prompt;
976
+ let passSystemPrompt = systemPrompt;
977
+ let passExtra = extra;
978
+ let attached = new Set(extra.specs.map((spec) => spec.name));
979
+ for (let pass = 1; pass <= MAX_PROVIDER_PASSES; pass += 1) {
980
+ // Everything the turn produces goes through one queue: the provider's
981
+ // own events, and whatever the tool calls it makes cause in the company.
982
+ const queue = new EventQueue();
983
+ const token = this.org.register({
984
+ orgId: organization.id,
985
+ audience: 'assistant',
986
+ agentId: undefined,
987
+ sessionId: session.id,
988
+ projectId: session.projectId,
989
+ depth: -1,
990
+ // A scheduled chat run works under the same rule as a scheduled
991
+ // assignment: it may read memory and open skills, but nothing it
992
+ // does lands back in the bank - no extraction, no tools that write.
993
+ // That covers every run with nobody in front of it: a session of
994
+ // kind `schedule`, the old mail-answer turn (`kind: 'mail'`, no
995
+ // longer created), and a schedule pinned to an ordinary
996
+ // conversation, which arrives with
997
+ // `input.scheduled` set. All three are exactly the runs that must
998
+ // not be offered `ask_user` - there is no screen to answer on.
999
+ scheduled: input.scheduled === true || session.kind === 'schedule' || session.kind === 'mail',
1000
+ watching: input.watching === true,
1001
+ emit: (event) => queue.push(event),
1002
+ signal: input.signal,
1003
+ });
1004
+ const currentPrompt = passPrompt;
1005
+ const currentSystemPrompt = passSystemPrompt;
1006
+ const currentSpecs = passExtra.specs;
1007
+ const currentResume = providerSessionId;
1008
+ const pump = (async () => {
1009
+ try {
1010
+ const mcp = await this.org.bridge.spec(token);
1011
+ for await (const event of provider.run({
1012
+ prompt: currentPrompt,
1013
+ systemPrompt: currentSystemPrompt,
1014
+ systemPromptMode: 'replace',
1015
+ providerSessionId: currentResume,
1016
+ model: usedModel,
1017
+ effort,
1018
+ cwd,
1019
+ permission: input.permission ?? this.config.defaultPermission,
1020
+ mcp,
1021
+ mcpExtra: currentSpecs.length ? currentSpecs : undefined,
1022
+ // Approved subagents and hooks out of the Claude Code
1023
+ // installation, plus Rookery's own permission floor.
1024
+ ...externalTurnExtras(this.config, who),
1025
+ signal: input.signal,
1026
+ })) {
1027
+ queue.push(event);
1028
+ }
1029
+ }
1030
+ catch (error) {
1031
+ queue.push({ type: 'error', message: error.message, fatal: true });
1032
+ }
1033
+ finally {
1034
+ queue.close();
1035
+ }
1036
+ })();
1037
+ let passText = '';
1038
+ try {
1039
+ for await (const event of queue.drain()) {
1040
+ switch (event.type) {
1041
+ case 'tool':
1042
+ toolCalls.push(event);
1043
+ turnBlocks.apply(event);
1044
+ // Also on the assistant's own emitter, not just this stream:
1045
+ // a channel that is not the one that started the turn - the
1046
+ // phone, watching a schedule run - has no other way to see
1047
+ // what is being done. Nobody has to listen; the web UI reads
1048
+ // these off the turn stream it already holds.
1049
+ this.emit('tool', event);
1050
+ yield event;
1051
+ break;
1052
+ case 'question':
1053
+ case 'question-closed':
1054
+ // Into this stream only. The assistant's emitter already
1055
+ // carries both events - forwarded from the registry, which
1056
+ // fires them even when this queue is long closed - so the
1057
+ // phone and a second tab see the card without this turn's
1058
+ // help, and emitting here as well would say everything twice.
1059
+ yield event;
1060
+ break;
1061
+ case 'text':
1062
+ passText += event.delta;
1063
+ turnBlocks.apply(event);
1064
+ yield event;
1065
+ break;
1066
+ case 'thinking':
1067
+ // Explicit only so the transcript folds it in; on the wire
1068
+ // this is the same pass-through `default` already gave it.
1069
+ turnBlocks.apply(event);
1070
+ yield event;
1071
+ break;
1072
+ case 'session':
1073
+ providerSessionId = event.providerSessionId ?? providerSessionId;
1074
+ break;
1075
+ case 'done':
1076
+ providerSessionId = event.providerSessionId ?? providerSessionId;
1077
+ passText = event.text || passText;
1078
+ turnBlocks.reconcile(event.text);
1079
+ usage = mergeUsage(usage, event.usage);
1080
+ break;
1081
+ case 'error':
1082
+ if (event.fatal) {
1083
+ failed = true;
1084
+ lastFatal = event.message;
1085
+ }
1086
+ yield event;
1087
+ break;
1088
+ default:
1089
+ yield event;
1090
+ }
1091
+ }
1092
+ }
1093
+ finally {
1094
+ await pump;
1095
+ this.org.unregister(token);
1096
+ // Every exit, not only an abort: a provider crash or a fallback
1097
+ // switch ends the pass without the signal ever firing, and the
1098
+ // questions it asked would otherwise stand answerable on every
1099
+ // surface for their full timeout, reaching a tool call that is gone.
1100
+ this.questions.cancelForOwner(token);
1101
+ }
1102
+ answer = answer && passText ? answer + '\n\n' + passText : answer || passText;
1103
+ // The continuation. A tool server the assistant switched on mid-turn
1104
+ // can only be attached to a provider process that has not started yet,
1105
+ // so without this the work stalls until the user asks again - exactly
1106
+ // the dead end the assistant is told not to accept. Instead the turn
1107
+ // runs once more with the new servers attached and the provider's own
1108
+ // session resumed, and the two answers are joined.
1109
+ if (failed || pass === MAX_PROVIDER_PASSES)
1110
+ break;
1111
+ if (input.signal?.aborted)
1112
+ break;
1113
+ const next = toolServersFor(this.config, who, pid, project?.id);
1114
+ const fresh = next.specs.map((spec) => spec.name).filter((name) => !attached.has(name));
1115
+ if (!fresh.length)
1116
+ break;
1117
+ passExtra = next;
1118
+ attached = new Set(next.specs.map((spec) => spec.name));
1119
+ passSystemPrompt = buildSystemPrompt({
1120
+ config: this.config,
1121
+ query: prompt,
1122
+ memories,
1123
+ resumed: true,
1124
+ voice: input.voice ?? session.kind === 'voice',
1125
+ orgBlock: assistantOrgBlock(this.config, snapshot, project, this.cron.list(organization.id), this.store),
1126
+ toolHints: [...next.hints, dormantToolsHint(this.config, who, project?.id)].filter(Boolean),
1127
+ skillsIndex,
1128
+ store: this.store,
1129
+ });
1130
+ passPrompt = continuePrompt(fresh);
1131
+ yield { type: 'status', label: 'tools', detail: fresh.join(', ') + ' attached, carrying on' };
1132
+ }
1133
+ // A turn that died on its usage limit with nothing to show goes around
1134
+ // once more on another provider. Anything else keeps today's semantics:
1135
+ // nothing usable came back, so the session context stays untouched for
1136
+ // the next attempt to resume cleanly.
1137
+ if (!failed || answer || toolCalls.length)
1138
+ break;
1139
+ const alternate = this.config.providerFallback.enabled &&
1140
+ attempt < MAX_PROVIDER_ATTEMPTS &&
1141
+ !input.signal?.aborted &&
1142
+ lastFatal !== null &&
1143
+ isUsageLimitError(lastFatal)
1144
+ ? await this.providers.resolveUsable(wanted, { exclude: [...tried] })
1145
+ : null;
1146
+ if (!alternate)
1147
+ return;
1148
+ rememberUsageFailure(pid);
1149
+ yield { type: 'status', label: 'provider', detail: pid + ' hit its usage limit, continuing on ' + alternate };
1150
+ usedProvider = alternate;
1151
+ tried.add(alternate);
1152
+ // The dead attempt belongs to no transcript; the next one starts clean
1153
+ // rather than appending to a half-told story.
1154
+ turnBlocks.clear();
1155
+ }
1156
+ // The provider's numbers plus the wall-clock of the whole turn, so a
1157
+ // reloaded transcript can still show what the context looked like.
1158
+ const turnUsage = { ...usage, durationMs: Date.now() - started };
1159
+ this.store.addMessage({
1160
+ sessionId: session.id,
1161
+ role: 'assistant',
1162
+ content: answer,
1163
+ turnId,
1164
+ provider: usedProvider,
1165
+ model: usedModel,
1166
+ usage: turnUsage,
1167
+ toolCalls,
1168
+ blocks: turnBlocks.blocks.length ? turnBlocks.blocks : undefined,
1169
+ });
1170
+ if (lastFatal !== null && !answer)
1171
+ return;
1172
+ this.store.updateSession(session.id, { provider: usedProvider, model: usedModel, providerSessionId });
1173
+ yield { type: 'done', text: answer, providerSessionId, usage: turnUsage };
1174
+ // Scheduled runs stay out of the memory: the "user" side of that
1175
+ // exchange is Rookery's own boilerplate plus the job's prompt, not
1176
+ // something the user said today, and quoting it would file the job
1177
+ // description again on every firing.
1178
+ if (this.config.memory.enabled &&
1179
+ this.config.memory.autoExtract &&
1180
+ session.kind !== 'schedule' &&
1181
+ !fromSystem) {
1182
+ void this.#learn(session.id, prompt, answer, usedProvider, owner);
1183
+ }
1184
+ }
1185
+ /* ------------------------ chat in the terminal ------------------------ */
1186
+ /**
1187
+ * Whether this turn is typed into the conversation's terminal (T1, T5):
1188
+ * switched on, an ordinary conversation, not a spoken turn or the watcher,
1189
+ * a provider the model gateway can reach, and a pty on this machine.
1190
+ */
1191
+ async #answersInTerminal(session, input, providerId) {
1192
+ if (!this.config.turns.terminal)
1193
+ return false;
1194
+ if (session.kind !== 'chat' || input.voice || input.watching)
1195
+ return false;
1196
+ if (!this.providers.has('claude') || !this.providers.get('claude').openTerminal)
1197
+ return false;
1198
+ if (providerId !== 'claude' && providerId !== 'codex') {
1199
+ const profile = this.providers.profiles().find((entry) => entry.id === providerId);
1200
+ if (profile?.via !== 'direct')
1201
+ return false;
382
1202
  }
383
- const provider = this.providers.get(providerId);
1203
+ return (await loadPty()) !== null;
1204
+ }
1205
+ async *#terminalTurn(turn) {
1206
+ const { session, input } = turn;
384
1207
  const started = Date.now();
385
- let answer = '';
1208
+ const permission = input.permission ?? this.config.defaultPermission;
1209
+ let terminal;
1210
+ try {
1211
+ // A turn nobody typed brings no settings of its own - it takes the
1212
+ // terminal as the person left it rather than restarting it onto the
1213
+ // defaults (a different model, other rights) in the middle of their work.
1214
+ const running = this.#chatTerminals.get(session.id);
1215
+ terminal =
1216
+ input.origin === 'system' && running?.handle.alive()
1217
+ ? running
1218
+ : await this.#chatTerminal(session, {
1219
+ providerId: turn.providerId,
1220
+ model: turn.model,
1221
+ effort: turn.effort,
1222
+ permission,
1223
+ });
1224
+ }
1225
+ catch (error) {
1226
+ yield { type: 'error', message: error.message, fatal: true };
1227
+ return;
1228
+ }
1229
+ // What a headless turn rebuilds into its system prompt every time goes
1230
+ // in through the prompt hook here (T2): the recall, the company as it is
1231
+ // right now, the skills that look like this message.
1232
+ const budget = this.config.memory.contextBudget;
1233
+ const snapshot = this.org.snapshot(turn.snapshotOrgId);
1234
+ const context = [
1235
+ renderMemoryBlock(turn.memories, Math.floor(budget * 0.4), 'this user', this.store),
1236
+ assistantOrgBlock(this.config, snapshot, turn.project, this.cron.list(turn.snapshotOrgId), this.store),
1237
+ renderSkillMatches(matchSkills(this.config, 'assistant', turn.ownSkills, turn.prompt)),
1238
+ 'It is now ' + formatNow() + '.',
1239
+ ]
1240
+ .filter(Boolean)
1241
+ .join('\n\n');
386
1242
  const toolCalls = [];
387
- let providerSessionId = resumed ? session.providerSessionId : undefined;
388
- let failed = false;
1243
+ const turnBlocks = new TurnBlocks();
1244
+ if (turn.recall)
1245
+ turnBlocks.apply(turn.recall);
1246
+ let answer = '';
1247
+ let failure;
389
1248
  let usage;
390
- yield { type: 'session', sessionId: session.id, providerSessionId, provider: providerId, model };
391
- // An agent in a chat may look at its project; the assistant stays in the
392
- // workspace and is a person, not Claude Code's coding agent.
393
- const cwd = agent ? (project?.path || agentWorkspace(this.config, agent.id)) : this.config.workspace;
394
- // What this pass of the provider is run with. A turn usually has exactly
395
- // one pass; see the continuation below for why it sometimes has two.
396
- let passPrompt = prompt;
397
- let passSystemPrompt = systemPrompt;
398
- let passExtra = extra;
399
- let attached = new Set(extra.specs.map((spec) => spec.name));
1249
+ let answeredBy = terminal.model;
1250
+ let prompt = turn.prompt;
1251
+ let promptContext = context;
400
1252
  for (let pass = 1; pass <= MAX_PROVIDER_PASSES; pass += 1) {
401
- // Everything the turn produces goes through one queue: the provider's
402
- // own events, and whatever the tool calls it makes cause in the company.
403
- const queue = new EventQueue();
404
- const token = this.org.register({
405
- orgId: organization.id,
406
- audience: agent ? 'agent' : 'assistant',
407
- agentId: agent?.id,
1253
+ yield {
1254
+ type: 'session',
408
1255
  sessionId: session.id,
409
- projectId: session.projectId,
410
- depth: agent ? 0 : -1,
411
- emit: (event) => queue.push(event),
412
- signal: input.signal,
413
- });
414
- const currentPrompt = passPrompt;
415
- const currentSystemPrompt = passSystemPrompt;
416
- const currentSpecs = passExtra.specs;
417
- const currentResume = providerSessionId;
418
- const pump = (async () => {
419
- try {
420
- const mcp = await this.org.bridge.spec(token);
421
- for await (const event of provider.run({
422
- prompt: currentPrompt,
423
- systemPrompt: currentSystemPrompt,
424
- systemPromptMode: agent ? 'append' : 'replace',
425
- providerSessionId: currentResume,
426
- model,
427
- effort,
428
- cwd,
429
- permission: input.permission ?? agent?.permission ?? this.config.defaultPermission,
430
- mcp,
431
- mcpExtra: currentSpecs.length ? currentSpecs : undefined,
432
- signal: input.signal,
433
- })) {
434
- queue.push(event);
435
- }
436
- }
437
- catch (error) {
438
- queue.push({ type: 'error', message: error.message, fatal: true });
439
- }
440
- finally {
441
- queue.close();
442
- }
443
- })();
444
- let passText = '';
1256
+ providerSessionId: terminal.handle.providerSessionId,
1257
+ provider: turn.providerId,
1258
+ ...(terminal.model ? { model: terminal.model } : {}),
1259
+ };
1260
+ const queue = new EventQueue();
1261
+ // The bridge token outlives the turn; its events belong to whichever
1262
+ // turn is typing into the terminal right now.
1263
+ terminal.context.emit = (event) => queue.push(event);
1264
+ // And its signal: an `assign` this turn waits on is stopped with it.
1265
+ terminal.context.signal = input.signal;
1266
+ const submitted = terminal.handle
1267
+ .submit({ prompt, context: promptContext, onEvent: (event) => queue.push(event), signal: input.signal })
1268
+ .finally(() => queue.close());
445
1269
  try {
446
1270
  for await (const event of queue.drain()) {
447
- switch (event.type) {
448
- case 'tool':
449
- toolCalls.push(event);
450
- yield event;
451
- break;
452
- case 'text':
453
- passText += event.delta;
454
- yield event;
455
- break;
456
- case 'session':
457
- providerSessionId = event.providerSessionId ?? providerSessionId;
458
- break;
459
- case 'done':
460
- providerSessionId = event.providerSessionId ?? providerSessionId;
461
- passText = event.text || passText;
462
- usage = mergeUsage(usage, event.usage);
463
- break;
464
- case 'error':
465
- if (event.fatal)
466
- failed = true;
467
- yield event;
468
- break;
469
- default:
470
- yield event;
1271
+ if (event.type === 'tool') {
1272
+ toolCalls.push(event);
1273
+ turnBlocks.apply(event);
1274
+ this.emit('tool', event);
471
1275
  }
1276
+ else if (event.type === 'text' || event.type === 'thinking') {
1277
+ turnBlocks.apply(event);
1278
+ }
1279
+ yield event;
472
1280
  }
473
1281
  }
474
1282
  finally {
475
- await pump;
476
- this.org.unregister(token);
1283
+ terminal.context.emit = () => undefined;
1284
+ terminal.context.signal = undefined;
477
1285
  }
478
- answer = answer && passText ? answer + '\n\n' + passText : answer || passText;
479
- // The continuation. A tool server the assistant switched on mid-turn
480
- // can only be attached to a provider process that has not started yet,
481
- // so without this the work stalls until the user asks again - exactly
482
- // the dead end the assistant is told not to accept. Instead the turn
483
- // runs once more with the new servers attached and the provider's own
484
- // session resumed, and the two answers are joined.
485
- if (failed || agent || pass === MAX_PROVIDER_PASSES)
1286
+ const result = await submitted;
1287
+ answeredBy = result.model ?? answeredBy;
1288
+ if (result.model)
1289
+ terminal.models.add(result.model);
1290
+ usage = mergeUsage(usage, result.usage);
1291
+ if (result.answer)
1292
+ answer = answer ? answer + '\n\n' + result.answer : result.answer;
1293
+ if (result.error) {
1294
+ failure = result.error;
486
1295
  break;
487
- if (input.signal?.aborted)
1296
+ }
1297
+ if (result.interrupted || input.signal?.aborted || pass === MAX_PROVIDER_PASSES)
488
1298
  break;
489
- const next = toolServersFor(this.config, who, providerId, project?.id);
490
- const fresh = next.specs.map((spec) => spec.name).filter((name) => !attached.has(name));
1299
+ // The continuation (T3): a tool server switched on during the turn
1300
+ // needs a process that has it attached. The terminal restarts on the
1301
+ // same session with it, and the work carries on.
1302
+ const next = toolServersFor(this.config, 'assistant', turn.providerId, session.projectId);
1303
+ const fresh = next.specs.map((spec) => spec.name).filter((name) => !terminal.servers.includes(name));
491
1304
  if (!fresh.length)
492
1305
  break;
493
- await ensureToolServers(this.config, who, providerId, project?.id, (id, error) => this.log.warn('Tool server could not prepare', { id, error: error.message }));
494
- passExtra = next;
495
- attached = new Set(next.specs.map((spec) => spec.name));
496
- passSystemPrompt = buildSystemPrompt({
497
- config: this.config,
498
- query: prompt,
499
- memories,
500
- resumed: true,
501
- voice: input.voice ?? session.kind === 'voice',
502
- orgBlock: assistantOrgBlock(this.config, snapshot, [], project, this.cron.list(organization.id)),
503
- toolHints: [...next.hints, dormantToolsHint(this.config, who, project?.id)].filter(Boolean),
504
- skillsIndex,
505
- store: this.store,
506
- });
507
- passPrompt = continuePrompt(fresh);
508
1306
  yield { type: 'status', label: 'tools', detail: fresh.join(', ') + ' attached, carrying on' };
1307
+ try {
1308
+ terminal = await this.#chatTerminal(this.store.getSession(session.id) ?? session, {
1309
+ providerId: turn.providerId,
1310
+ model: answeredBy ?? turn.model,
1311
+ effort: turn.effort,
1312
+ permission,
1313
+ });
1314
+ }
1315
+ catch (error) {
1316
+ failure = error.message;
1317
+ break;
1318
+ }
1319
+ prompt = continuePrompt(fresh);
1320
+ promptContext = undefined;
509
1321
  }
510
- if (failed && !answer && !toolCalls.length) {
511
- // Nothing usable came back; leave the session context untouched so the
512
- // next attempt can still resume cleanly.
513
- return;
514
- }
515
- // The provider's numbers plus the wall-clock of the whole turn, so a
516
- // reloaded transcript can still show what the context looked like.
1322
+ if (failure)
1323
+ yield { type: 'error', message: failure, fatal: !answer };
1324
+ turnBlocks.reconcile(answer);
517
1325
  const turnUsage = { ...usage, durationMs: Date.now() - started };
1326
+ const answeredOn = this.#gatewayOwner(answeredBy, turn.providerId);
518
1327
  this.store.addMessage({
519
1328
  sessionId: session.id,
520
1329
  role: 'assistant',
521
1330
  content: answer,
522
- provider: providerId,
523
- model,
1331
+ turnId: turn.turnId,
1332
+ provider: answeredOn,
1333
+ ...(answeredBy ? { model: answeredBy } : {}),
524
1334
  usage: turnUsage,
525
1335
  toolCalls,
1336
+ blocks: turnBlocks.blocks.length ? turnBlocks.blocks : undefined,
1337
+ });
1338
+ this.store.updateSession(session.id, {
1339
+ provider: answeredOn,
1340
+ ...(answeredBy ? { model: answeredBy } : {}),
1341
+ providerSessionId: terminal.handle.providerSessionId,
526
1342
  });
527
- if (failed && !answer)
1343
+ if (failure && !answer)
528
1344
  return;
529
- this.store.updateSession(session.id, { provider: providerId, model, providerSessionId });
530
- yield { type: 'done', text: answer, providerSessionId, usage: turnUsage };
531
- if (this.config.memory.enabled && this.config.memory.autoExtract) {
532
- void this.#learn(session.id, prompt, answer, providerId, owner);
1345
+ yield { type: 'done', text: answer, providerSessionId: terminal.handle.providerSessionId, usage: turnUsage };
1346
+ if (this.config.memory.enabled && this.config.memory.autoExtract && input.origin !== 'system') {
1347
+ void this.#learn(session.id, turn.prompt, answer, answeredOn, ASSISTANT_MEMORY_OWNER);
1348
+ }
1349
+ }
1350
+ /** Which provider a model name belongs to, as the gateway routes it. */
1351
+ #gatewayOwner(model, fallback) {
1352
+ if (!this.#gateway || !model)
1353
+ return fallback;
1354
+ const route = this.#gateway.route(model);
1355
+ return route.kind === 'codex' ? 'codex' : route.kind === 'profile' ? route.profile.id : 'claude';
1356
+ }
1357
+ /** Ends a conversation's terminal and waits until its process is gone. */
1358
+ async #closeChatTerminal(sessionId) {
1359
+ const open = this.#chatTerminals.get(sessionId);
1360
+ if (!open)
1361
+ return;
1362
+ this.#chatTerminals.delete(sessionId);
1363
+ open.handle.close();
1364
+ const key = conversationTerminalKey(sessionId);
1365
+ for (let waited = 0; waited < 5000 && tuiSessions.info(key); waited += 100) {
1366
+ await new Promise((resolve) => setTimeout(resolve, 100));
1367
+ }
1368
+ }
1369
+ /**
1370
+ * What to say when a turn starts on a provider it did not ask for. Quota
1371
+ * reasons first - they are the ones the user cannot see anywhere else - and
1372
+ * a missing login last, which the provider list already shows.
1373
+ */
1374
+ #switchReason(wanted, chosen) {
1375
+ const blocked = providerBlocked(wanted);
1376
+ if (blocked) {
1377
+ return (wanted +
1378
+ ' is out of quota' +
1379
+ (blocked.until ? ' until ' + new Date(blocked.until).toLocaleTimeString() : '') +
1380
+ ', using ' +
1381
+ chosen);
1382
+ }
1383
+ if (this.config.providerFallback.enabled && providerLow(wanted, this.config.providerFallback.thresholdPercent)) {
1384
+ return wanted + ' is nearly out of quota, using ' + chosen + ' for now';
533
1385
  }
1386
+ return wanted + ' is not logged in, using ' + chosen;
534
1387
  }
535
1388
  /* ------------------------------ assign ---------------------------- */
536
1389
  /**
537
1390
  * Give one agent a task directly, outside a conversation. Streams the
538
- * assignment's events and ends with `done` carrying the report.
1391
+ * run's events and ends with `done` carrying the report.
1392
+ *
1393
+ * Like every other way of handing out work, this puts a card on the board
1394
+ * first (decision E9). It used to call `org.run()` straight, and it is the
1395
+ * entrance the web UI, the websocket, the CLI and every agent schedule all
1396
+ * come through - so the single biggest source of "sometimes there is a
1397
+ * card and sometimes there is only a run" was this one method. The
1398
+ * `assign` tool had already been moved onto the board; this is the same
1399
+ * move for everything that is not a tool call.
539
1400
  */
540
1401
  async *assign(input) {
541
1402
  const task = input.task.trim();
@@ -553,34 +1414,82 @@ export class Assistant extends EventEmitter {
553
1414
  yield { type: 'error', message: 'No project ' + input.projectId + '.', fatal: true };
554
1415
  return;
555
1416
  }
1417
+ // The card comes first and the run hangs off it, so this work is on the
1418
+ // board from the moment it is handed over rather than only visible as a
1419
+ // row under "runs". `createdBy: 'user'` is the truth here: every caller
1420
+ // of this method is a person acting directly, or a schedule they set up.
1421
+ const card = this.store.org.createTask({
1422
+ orgId: organization.id,
1423
+ title: input.title?.trim() || titleFromBrief(task),
1424
+ description: task,
1425
+ projectId: input.projectId,
1426
+ assigneeId: agent.id,
1427
+ createdBy: 'user',
1428
+ // A card that appeared at three in the morning can say why. The work
1429
+ // is still the user's - they set the schedule up - so `createdBy`
1430
+ // stays `user` and this only names the arrangement that fired.
1431
+ scheduleId: input.scheduleId,
1432
+ });
1433
+ this.org.announceTask(card);
556
1434
  const queue = new EventQueue();
557
1435
  const run = this.org
558
- .run({
1436
+ .runTask({
559
1437
  orgId: organization.id,
560
- agent,
561
- task,
1438
+ audience: 'assistant',
1439
+ depth: -1,
562
1440
  projectId: input.projectId,
1441
+ // The conversation this was started from, when there was one. It
1442
+ // is what links the run back into that chat's journal; dropping
1443
+ // it left `turns.session_id` null and the run unfindable from the
1444
+ // conversation that asked for it.
563
1445
  sessionId: input.sessionId,
564
- requesterKind: 'user',
565
- depth: 0,
1446
+ scheduled: input.scheduled,
566
1447
  emit: (event) => queue.push(event),
567
1448
  signal: input.signal,
568
- })
1449
+ }, card)
569
1450
  .finally(() => queue.close());
570
1451
  for await (const event of queue.drain())
571
1452
  yield event;
572
- const assignment = await run;
573
- if (assignment.status === 'done') {
574
- yield { type: 'done', text: assignment.result ?? '', usage: { durationMs: assignment.durationMs } };
1453
+ const finished = await run;
1454
+ if (finished.status === 'done') {
1455
+ yield { type: 'done', text: finished.result ?? '' };
1456
+ }
1457
+ else if (finished.status === 'blocked') {
1458
+ // Not a failure: somebody was asked something and the board is
1459
+ // waiting for them. Saying "the run blocked" as an error made a
1460
+ // perfectly good question read as a breakage.
1461
+ yield { type: 'done', text: finished.result ?? 'Waiting for an answer.' };
575
1462
  }
576
1463
  else {
577
1464
  yield {
578
1465
  type: 'error',
579
- message: 'Assignment ' + assignment.status + (assignment.error ? ': ' + assignment.error : '.'),
1466
+ message: 'The run ' + finished.status + (finished.error ? ': ' + finished.error : '.'),
580
1467
  fatal: true,
581
1468
  };
582
1469
  }
583
1470
  }
1471
+ /* ---------------------------- assignment log ---------------------------- */
1472
+ /**
1473
+ * The live log of a running assignment so far; an unknown or finished id
1474
+ * reads as inactive and empty. Delegates to the org controller.
1475
+ */
1476
+ snapshotAssignmentLog(assignmentId) {
1477
+ return this.org.snapshotAssignmentLog(assignmentId);
1478
+ }
1479
+ /**
1480
+ * Follow one running assignment's live log; the returned unsub stops the
1481
+ * listener. Delegates to the org controller.
1482
+ */
1483
+ watchAssignmentLog(assignmentId, listener) {
1484
+ return this.org.watchAssignmentLog(assignmentId, listener);
1485
+ }
1486
+ /**
1487
+ * Replay a running assignment's buffered log, then follow it live until
1488
+ * the run ends. Delegates to the org controller.
1489
+ */
1490
+ async *assignmentLog(assignmentId) {
1491
+ yield* this.org.assignmentLog(assignmentId);
1492
+ }
584
1493
  /* ------------------------------- tasks ---------------------------- */
585
1494
  /** Plan one task from the board on the user's behalf. Throws when the task is unknown. */
586
1495
  async planTask(taskId, hint) {
@@ -628,9 +1537,11 @@ export class Assistant extends EventEmitter {
628
1537
  }
629
1538
  /* ----------------------------- schedules -------------------------- */
630
1539
  /**
631
- * Execute one schedule. The assistant's own jobs run as a turn in a
632
- * conversation kept per job, so the user can open it and read along or
633
- * carry on; an agent's jobs run as an ordinary assignment.
1540
+ * Execute one schedule. The assistant's own jobs run as a turn in a fresh
1541
+ * conversation every firing - a clean rerun each time, not a diary the
1542
+ * assistant keeps adding to - unless the job was pinned to a specific
1543
+ * conversation when it was created (the "reply in this chat" case for a
1544
+ * one-off follow-up); an agent's jobs run as an ordinary assignment.
634
1545
  */
635
1546
  async #runScheduled(job, run, signal) {
636
1547
  void run;
@@ -666,7 +1577,19 @@ export class Assistant extends EventEmitter {
666
1577
  let assignmentId;
667
1578
  let text = '';
668
1579
  let error;
669
- for await (const event of this.assign({ agent: agent.id, task: job.prompt, projectId: job.projectId, signal })) {
1580
+ // `scheduled` keeps the run from learning: the assignment's words are
1581
+ // the job's own prompt, and no memory should grow out of them.
1582
+ for await (const event of this.assign({
1583
+ agent: agent.id,
1584
+ // A recurring job is called the same thing every night, and that is
1585
+ // right: the schedule's name is the third source of a run's name.
1586
+ title: job.name,
1587
+ task: job.prompt,
1588
+ projectId: job.projectId,
1589
+ signal,
1590
+ scheduled: true,
1591
+ scheduleId: job.id,
1592
+ })) {
670
1593
  if (event.type === 'assignment' && !assignmentId)
671
1594
  assignmentId = event.assignment.id;
672
1595
  else if (event.type === 'done')
@@ -676,18 +1599,60 @@ export class Assistant extends EventEmitter {
676
1599
  }
677
1600
  return error ? { status: 'failed', error, assignmentId } : { status: 'done', result: text, assignmentId };
678
1601
  }
679
- let sessionId = job.sessionId && this.store.getSession(job.sessionId) ? job.sessionId : undefined;
680
- if (!sessionId) {
681
- sessionId = this.createSession({ title: 'Schedule: ' + job.name, projectId: job.projectId }).id;
682
- this.store.cron.updateJob(job.id, { sessionId }, false);
1602
+ // The board watcher checks before it thinks. Nothing on the board that
1603
+ // needs saying means no session, no provider process and no model call -
1604
+ // which is what the overwhelming majority of its firings are.
1605
+ const watching = job.id === boardWatchJobId(job.orgId);
1606
+ const attention = watching ? this.#boardAttention(job.orgId, job.id) : [];
1607
+ if (watching && !attention.length)
1608
+ return { status: 'done', result: '', silent: true };
1609
+ // `job.sessionId` here only ever means "pinned at creation" - a one-off
1610
+ // follow-up the user asked to land in a chat they already had open.
1611
+ // Nothing below writes it back after a run, so a recurring job gets a
1612
+ // clean, unlinked conversation every single firing.
1613
+ const existing = job.sessionId ? this.store.getSession(job.sessionId) : null;
1614
+ let sessionId;
1615
+ if (existing) {
1616
+ sessionId = existing.id;
1617
+ // The user may have archived the chat while this was pending; reusing
1618
+ // it silently would bury the reply where nobody looks for it.
1619
+ if (existing.archived)
1620
+ this.store.updateSession(existing.id, { archived: false });
1621
+ }
1622
+ else {
1623
+ sessionId = this.createSession({ title: 'Schedule: ' + job.name, kind: 'schedule', projectId: job.projectId }).id;
683
1624
  }
684
- const when = new Date().toLocaleString('en-GB', { dateStyle: 'medium', timeStyle: 'short' });
685
- const prompt = 'Automatic run of schedule “' + job.name + '” (' + describeCron(job.schedule) + '), ' + when + '. ' +
1625
+ // Same clock, same zone, same wording as every other stamp a model reads.
1626
+ const when = formatNow();
1627
+ const prompt = 'Automatic run of schedule “' + job.name + '” (' +
1628
+ (job.schedule ? describeCron(job.schedule) : 'fired by an event') + '), ' + when + '. ' +
686
1629
  'Nobody is following live: carry out the assignment now and finish with a short report ' +
687
- 'for the user to read later.\n\n' + job.prompt;
1630
+ 'for the user to read later. If carrying it out already delivers the result to the user by ' +
1631
+ 'itself (for example you notify them of the thing this job exists to send), that is the ' +
1632
+ 'delivery - reply with exactly [SILENT] and nothing else, so a second "schedule completed" ' +
1633
+ 'notification is not posted on top of it.\n\n' + job.prompt +
1634
+ // The watcher arrives knowing what it was woken for, so the turn is
1635
+ // about judging those findings rather than going to look for them.
1636
+ // Everything here is new since its last report by construction.
1637
+ (attention.length
1638
+ ? '\n\nThe board was checked before this run. These are new since you last reported, ' +
1639
+ 'and they are the whole reason you were woken:\n- ' + attention.join('\n- ')
1640
+ : '');
688
1641
  let text = '';
689
1642
  let error;
690
- for await (const event of this.chat({ text: prompt, sessionId, projectId: job.projectId, permission: job.permission, signal })) {
1643
+ for await (const event of this.chat({
1644
+ text: prompt,
1645
+ sessionId,
1646
+ projectId: job.projectId,
1647
+ permission: job.permission,
1648
+ signal,
1649
+ scheduled: true,
1650
+ // The board watcher is the one schedule that gets a cut-down toolset:
1651
+ // it looks and it mails, it does not act. Keyed off the job's fixed id
1652
+ // so a user-made job that merely happens to be named "Board watch" is
1653
+ // an ordinary assistant schedule with ordinary reach.
1654
+ watching,
1655
+ })) {
691
1656
  if (event.type === 'done')
692
1657
  text = event.text;
693
1658
  else if (event.type === 'error' && event.fatal)
@@ -695,11 +1660,492 @@ export class Assistant extends EventEmitter {
695
1660
  }
696
1661
  if (error && !text)
697
1662
  return { status: 'failed', error, sessionId };
698
- if (job.kind === 'script' && text.trim() === '[SILENT]')
1663
+ // An exact-match check on the whole reply is too brittle: the model
1664
+ // sometimes reasons out loud first and tacks the sentinel on as its
1665
+ // last line instead of replying with only it, which used to defeat the
1666
+ // match and let the explanation (sentinel and all) straight into the
1667
+ // outcome notification. Matching it as a trailing token - not anywhere in the
1668
+ // text - still catches that case without firing on a report that
1669
+ // merely quotes or explains the convention somewhere in its middle.
1670
+ if (/\[SILENT\]\s*$/.test(text))
699
1671
  return { status: 'done', result: '', silent: true, sessionId };
700
1672
  return { status: 'done', result: text, sessionId };
701
1673
  }
702
1674
  /* ---------------------------- internals --------------------------- */
1675
+ /**
1676
+ * Whether this turn is framed for the dream. All conditions must hold
1677
+ * (R18): the dream and the recorder are switched on, the owner is the
1678
+ * assistant - stage 1 records nothing but the assistant's own bank, an
1679
+ * agent frame would be cost without a night that ever scores it - and the
1680
+ * session is a real conversation. A `schedule` run walks this same code
1681
+ * but can never earn a correction label, because `sessionsActiveSince`
1682
+ * filters its kind out; framing it would be pure cost. The sample itself
1683
+ * is drawn per session, never per trace, and `frameRate` is clamped here
1684
+ * because `rookery config set` bypasses the patch schema (E21).
1685
+ */
1686
+ #dreamRecords(session, owner) {
1687
+ const dream = this.config.memory.dream;
1688
+ if (!dream.enabled || !dream.record)
1689
+ return false;
1690
+ if (owner !== ASSISTANT_MEMORY_OWNER)
1691
+ return false;
1692
+ if (session.kind !== 'chat' && session.kind !== 'voice' && session.kind !== 'mail')
1693
+ return false;
1694
+ return dreamSampleDraw(session.id) < clampNumber(dream.frameRate, 0, 1);
1695
+ }
1696
+ /**
1697
+ * Index a finished turn as a trial episode (concept 7.2, Phase 6).
1698
+ *
1699
+ * `dream.trialEpisodes` gets its reader here rather than in the night,
1700
+ * for the plain reason that the night cannot reach the turn journal: the
1701
+ * episode is an INDEX over `turn_events`, and only the process that just
1702
+ * wrote those rows knows the turn is over. Zero by default, so this is a
1703
+ * single config read and a return on every turn Rookery has ever run.
1704
+ *
1705
+ * The key is a quota, not a switch: `trialEpisodes` many episodes per
1706
+ * bank, then nothing. Phase 6 is a sample to validate a mechanism on, not
1707
+ * a recorder to leave running - and a trial that never stops would keep
1708
+ * pointing at verbatim journal rows long after anybody looked at it.
1709
+ *
1710
+ * Nothing in here may cost the turn. The turn is finished and answered by
1711
+ * the time this runs; a store that refuses the write costs the episode
1712
+ * and a debug line (10.5).
1713
+ */
1714
+ #recordTrialEpisode(turnId, journal, startedAt) {
1715
+ const trial = Math.round(clampNumber(this.config.memory.dream.trialEpisodes, 0, 1000));
1716
+ if (trial <= 0)
1717
+ return;
1718
+ const owner = ASSISTANT_MEMORY_OWNER;
1719
+ try {
1720
+ // Read with the quota as the limit: the question is "are there already
1721
+ // enough", never "how many are there".
1722
+ if (this.store.dreamEpisodes(owner, { limit: trial }).length >= trial)
1723
+ return;
1724
+ const sessionId = journal.sessionId;
1725
+ // The same session-wise split the recorder stamps on a trace (E3): a
1726
+ // turn outside any conversation is its own cluster.
1727
+ const split = splitOf(sessionId ?? turnId, DEFAULT_SPLIT_RATES);
1728
+ const { episode } = episodeFromEvents(turnId, this.store.turns.events(turnId), {
1729
+ owner,
1730
+ kind: 'turn',
1731
+ slot: 'recall',
1732
+ ...(sessionId ? { sessionId } : {}),
1733
+ startedAt,
1734
+ finishedAt: Date.now(),
1735
+ holdout: split === 'holdout',
1736
+ audit: split === 'audit',
1737
+ });
1738
+ this.store.recordDreamEpisode(episode);
1739
+ }
1740
+ catch (error) {
1741
+ this.log.debug('Trial episode not recorded', { turnId, error: error.message });
1742
+ }
1743
+ }
1744
+ /**
1745
+ * A retrieval policy went in force, so the user hears about it (S26,
1746
+ * concept 9.6). This is the one place that can say so: the night owns the
1747
+ * promotion and knows nothing about notifications, the controller owns them and
1748
+ * knows nothing about the night, and the runtime holds both.
1749
+ *
1750
+ * Everything quoted is a number, an id or the promotion's own stored
1751
+ * rationale, which carries no verbatim text by construction (E19/S21), so
1752
+ * the message can outlive the memories the evaluation stood on.
1753
+ *
1754
+ * A failing send costs the message, never the night: `#announcePromotion`
1755
+ * in sleep.ts catches whatever comes back out of here, and this catches
1756
+ * first so the warning names the notice rather than the hook.
1757
+ */
1758
+ async announcePromotion(notice) {
1759
+ const version = notice.version;
1760
+ const evaluation = notice.evaluation;
1761
+ const body = [
1762
+ 'A new ' + notice.slot + ' policy is in force for ' + notice.owner +
1763
+ ' (version ' + version.version + ').',
1764
+ '',
1765
+ notice.rationale,
1766
+ '',
1767
+ 'delta ' + evaluation.delta.toFixed(4) +
1768
+ ', ci_low ' + evaluation.ciLow.toFixed(4) +
1769
+ ', over ' + evaluation.closed + ' of ' + evaluation.traces + ' traces' +
1770
+ (evaluation.auditCiLow === undefined
1771
+ ? ''
1772
+ : ', audit ci_low ' + evaluation.auditCiLow.toFixed(4)) +
1773
+ '.',
1774
+ 'No further promotion of this slot before ' + new Date(notice.cooldownUntil).toISOString() + '.',
1775
+ '',
1776
+ 'Take it back on its own: POST /api/dream/policies/' + version.id + '/revert' +
1777
+ (notice.prevActiveId ? ' (restores version ' + notice.prevActiveId + ').' : '.'),
1778
+ 'Take the whole night back: undo sleep run ' + notice.runId + '.',
1779
+ ].join('\n');
1780
+ try {
1781
+ // A `sleep` notification, from Rookery itself. It used to be a mail
1782
+ // from the user to the user, which no push filter ever let through -
1783
+ // the promotion reached the web inbox and never the phone.
1784
+ this.org.notifyUser({
1785
+ orgId: this.org.activeOrganization().id,
1786
+ kind: 'sleep',
1787
+ title: 'Retrieval policy ' + notice.slot + ' v' + version.version + ' is in force',
1788
+ body,
1789
+ fromKind: 'system',
1790
+ });
1791
+ }
1792
+ catch (error) {
1793
+ this.log.warn('Could not post the promotion notice', {
1794
+ owner: notice.owner,
1795
+ slot: notice.slot,
1796
+ policy: version.id,
1797
+ error: error.message,
1798
+ });
1799
+ }
1800
+ }
1801
+ /**
1802
+ * The turn's merged memory list: the ranking plus the profile, pairs that
1803
+ * cannot both be true reduced to the newer sentence, and the whole merge
1804
+ * totally ordered - score descending, id ascending (R11), so a tie can no
1805
+ * longer pick whichever row the Map happened to insert first. That order
1806
+ * is what the rendered block reads, and what the recorder freezes.
1807
+ *
1808
+ * A framed turn additionally records everything the night needs to replay
1809
+ * this decision: the trace, the touches the ranking causes, and the frame
1810
+ * at the permissive corner of the declared box. The live ranking inside
1811
+ * the bracket is byte for byte the ranking of an unframed turn - the
1812
+ * recorder may not change the turn it records - and everything it writes
1813
+ * sits in the store's SAVEPOINT bracket (R9), so a framed turn is one
1814
+ * transaction or nothing.
1815
+ *
1816
+ * `turnId` is the JOURNAL's id, handed down from `chat()` - not one minted
1817
+ * here. That is the whole of concept 9.4's "one turn id instead of three":
1818
+ * the trace, the message and the journal now say the same word, so a
1819
+ * correction quote found in `messages.turn_id` lands on exactly the trace
1820
+ * that produced the prompt it corrects. Minted separately, `locateTurn`
1821
+ * could never match one and every correction label fell back to session
1822
+ * scope - where, by S3, it can never contribute a gain.
1823
+ */
1824
+ #turnMemories(session, owner, prompt, policy, turnId) {
1825
+ const options = {
1826
+ text: prompt,
1827
+ owner,
1828
+ limit: policy.limit,
1829
+ threshold: policy.threshold,
1830
+ hopEntity: policy.hopEntity,
1831
+ hopEdge: policy.hopEdge,
1832
+ };
1833
+ const promptProfileLimit = Math.max(3, Math.floor(policy.limit / 2));
1834
+ const merged = (matched, profile) => {
1835
+ const byId = new Map();
1836
+ for (const memory of profile)
1837
+ byId.set(memory.id, memory);
1838
+ for (const memory of matched)
1839
+ byId.set(memory.id, memory);
1840
+ // Of a contradicting pair only the newer sentence goes into the prompt;
1841
+ // the older one stays in the bank and stays visible in the inspector.
1842
+ return dropContradicted(this.store, [...byId.values()]).sort(byScoreThenId);
1843
+ };
1844
+ if (!this.#dreamRecords(session, owner)) {
1845
+ return merged(recall(this.store, options), coreProfile(this.store, { owner, limit: promptProfileLimit }));
1846
+ }
1847
+ const dream = this.config.memory.dream;
1848
+ const limitMax = Math.max(Math.round(clampNumber(dream.limitMax, 4, 16)), policy.limit);
1849
+ const maxFrameBytes = Math.round(clampNumber(dream.maxFrameBytes, 1000, 2_000_000));
1850
+ // Which half of the evidence this turn belongs to, stamped at record
1851
+ // time (E3). The unit is the SESSION, never the trace: two traces of one
1852
+ // session can never disagree, and the rates come from the one exported
1853
+ // constant the night reads back months later - if the recorder and the
1854
+ // evaluation ever picked their rates separately, a session would change
1855
+ // sides between the stamp and the measurement and the holdout would
1856
+ // quietly stop being one.
1857
+ const split = splitOf(session.id, DEFAULT_SPLIT_RATES);
1858
+ let memories = [];
1859
+ this.store.recordDreamTurn(() => {
1860
+ const trace = this.store.beginTrace({
1861
+ // One id per turn: every traced call of this turn carries it, and
1862
+ // labels attach to it rather than to any single call (R19).
1863
+ turnId,
1864
+ owner,
1865
+ kind: 'turn',
1866
+ site: 'turn',
1867
+ pipeline: 'assistant',
1868
+ sessionId: session.id,
1869
+ sessionKind: session.kind,
1870
+ // The position of this turn in its session: the messages stored
1871
+ // before it, which is the count the session carries at recall time.
1872
+ turnIndex: session.messageCount,
1873
+ policySet: { recall: policy },
1874
+ framed: true,
1875
+ holdout: split === 'holdout',
1876
+ audit: split === 'audit',
1877
+ });
1878
+ // The record, fetched before the ranking: the frame freezes
1879
+ // `access_count`, and the values worth freezing are the ones the live
1880
+ // scores are about to read - not the ones this turn's own touch will
1881
+ // write a moment later.
1882
+ const frame = fetchFrame(this.store, {
1883
+ ...options,
1884
+ box: declaredDreamBox(policy, limitMax),
1885
+ site: 'turn',
1886
+ pipeline: 'assistant',
1887
+ budgetChars: Math.floor(this.config.memory.contextBudget * 0.4),
1888
+ subject: 'this user',
1889
+ // A meta read and nothing more; empty until the first night has
1890
+ // stamped a fingerprint, which certifies nothing yet (R10).
1891
+ corpusStampId: this.store.currentCorpusStamp(owner)?.id ?? '',
1892
+ });
1893
+ const matched = recall(this.store, { ...options, touchContext: { traceId: trace.id, owner } });
1894
+ // One profile read at the permissive corner of the box, sliced down
1895
+ // for the prompt: the SQL behind `coreProfile` is prefix-invariant
1896
+ // now that it tie-breaks on id, so the wider read costs one query and
1897
+ // changes no row the prompt sees (R12).
1898
+ const profile = coreProfile(this.store, {
1899
+ owner,
1900
+ limit: Math.max(promptProfileLimit, Math.max(3, Math.floor(limitMax / 2))),
1901
+ }).slice(0, promptProfileLimit);
1902
+ memories = merged(matched, profile);
1903
+ // A frame over the size cap is refused rather than thrown at: the
1904
+ // trace still closes, without a frame, and the night simply never
1905
+ // scores this turn.
1906
+ if (!this.store.saveFrame(trace.id, 'recall', frame, { maxFrameBytes })) {
1907
+ this.log.debug('Dream frame refused: over dream.maxFrameBytes', { sessionId: session.id, turnId });
1908
+ }
1909
+ this.store.finishTrace(trace.id, { degraded: frame.degraded });
1910
+ });
1911
+ return memories;
1912
+ }
1913
+ /* ------------------------- conversation terminal ------------------------ */
1914
+ /**
1915
+ * The terminal view of a conversation: the same Claude Code process every
1916
+ * chat message of it is typed into (T1), opened here if nothing has opened
1917
+ * it yet. Switching between chat and terminal loses nothing because there
1918
+ * is nothing to switch - it is one process with one transcript, and what a
1919
+ * person types into it lands in the conversation like any other message.
1920
+ */
1921
+ async openConversationTerminal(input) {
1922
+ const session = this.#resolveSession({
1923
+ text: '',
1924
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
1925
+ ...(input.provider ? { provider: input.provider } : {}),
1926
+ ...(input.model ? { model: input.model } : {}),
1927
+ ...(input.projectId ? { projectId: input.projectId } : {}),
1928
+ });
1929
+ const key = conversationTerminalKey(session.id);
1930
+ const open = this.#chatTerminals.get(session.id);
1931
+ if (open?.handle.alive())
1932
+ return { sessionId: session.id, key };
1933
+ if (input.projectId && input.projectId !== session.projectId) {
1934
+ this.store.updateSession(session.id, { projectId: input.projectId });
1935
+ session.projectId = input.projectId;
1936
+ }
1937
+ const providerId = await this.providers.resolveUsable(input.provider ?? session.provider);
1938
+ if (!providerId)
1939
+ throw new Error('No AI provider is ready.');
1940
+ await this.#chatTerminal(session, {
1941
+ providerId,
1942
+ model: input.model ?? session.model ?? this.config.defaultModel,
1943
+ effort: input.effort ?? this.config.defaultEffort,
1944
+ permission: input.permission ?? this.config.defaultPermission,
1945
+ });
1946
+ return { sessionId: session.id, key };
1947
+ }
1948
+ /**
1949
+ * The conversation's terminal, started as this turn needs it. A terminal
1950
+ * already running with the same model, effort, rights, project and tool
1951
+ * servers is reused; any difference ends it and starts it again on the same
1952
+ * Claude Code session (T3) - the context is in the transcript, not in the
1953
+ * process, so nothing of the conversation is lost.
1954
+ *
1955
+ * What a headless turn rebuilds every time is built once here: the system
1956
+ * prompt, the tool servers. What changes per message - the recall, the
1957
+ * company's current state - goes in through the prompt hook instead.
1958
+ */
1959
+ async #chatTerminal(session, want) {
1960
+ const provider = this.providers.get('claude');
1961
+ if (!provider.openTerminal)
1962
+ throw new Error(provider.displayName + ' has no terminal of its own.');
1963
+ // Every model Rookery can reach, for the gateway's routing and the TUI's
1964
+ // `/model` menu - Claude's own entries are already in that menu.
1965
+ const picker = [];
1966
+ const direct = [];
1967
+ for (const status of await this.providers.statuses()) {
1968
+ if (status.id === 'claude' || !status.available || !status.authenticated)
1969
+ continue;
1970
+ const profile = this.providers.profiles().find((entry) => entry.id === status.id);
1971
+ // The gateway speaks to ChatGPT and to Anthropic-compatible endpoints;
1972
+ // a router-backed profile stays reachable from headless turns only.
1973
+ if (status.id !== 'codex' && profile?.via !== 'direct')
1974
+ continue;
1975
+ const models = await this.providers.models(status.id).catch(() => []);
1976
+ if (profile)
1977
+ direct.push({ profile, models: models.map((entry) => entry.id) });
1978
+ for (const entry of models) {
1979
+ picker.push({ model: entry.id, label: entry.name || entry.id, description: status.displayName });
1980
+ }
1981
+ }
1982
+ this.#gatewayProfiles = direct;
1983
+ this.#gateway ??= new ModelGateway({ profiles: () => this.#gatewayProfiles });
1984
+ const gateway = await this.#gateway.start();
1985
+ // A name another provider owns (the chat's `sonnet` on a GPT turn)
1986
+ // becomes that provider's own default instead of silently going to Claude.
1987
+ const model = want.model && this.#gatewayOwner(want.model, 'claude') === want.providerId
1988
+ ? want.model
1989
+ : remapModel(want.providerId, want.model);
1990
+ const project = session.projectId ? (this.store.org.getProject(session.projectId) ?? undefined) : undefined;
1991
+ const who = 'assistant';
1992
+ const extra = toolServersFor(this.config, who, want.providerId, project?.id);
1993
+ const servers = extra.specs.map((spec) => spec.name).sort();
1994
+ const signature = JSON.stringify([want.effort ?? '', want.permission, project?.id ?? '', servers]);
1995
+ const open = this.#chatTerminals.get(session.id);
1996
+ const sameModel = (entry) => !model || entry.models.has(model) || (want.model !== undefined && entry.models.has(want.model));
1997
+ if (open && open.handle.alive() && open.signature === signature && sameModel(open))
1998
+ return open;
1999
+ // Whatever a person is doing in it right now finishes first; a restart
2000
+ // must not cut off a turn somebody typed into the terminal view.
2001
+ if (open?.handle.alive())
2002
+ await open.handle.whenIdle();
2003
+ await this.#closeChatTerminal(session.id);
2004
+ // Read again: a restart must resume the session the last process wrote.
2005
+ const current = this.store.getSession(session.id) ?? session;
2006
+ const resumed = Boolean(current.providerSessionId);
2007
+ const organization = this.org.activeOrganization();
2008
+ const snapshot = this.org.snapshot(organization.id);
2009
+ const ownSkills = this.skills.for(who);
2010
+ const systemPrompt = buildSystemPrompt({
2011
+ config: this.config,
2012
+ query: '',
2013
+ memories: [],
2014
+ history: resumed ? [] : this.store.getMessages(session.id, this.config.memory.workingWindow),
2015
+ resumed,
2016
+ voice: false,
2017
+ orgBlock: assistantOrgBlock(this.config, snapshot, project, this.cron.list(organization.id), this.store),
2018
+ toolHints: [...extra.hints, dormantToolsHint(this.config, who, project?.id)].filter(Boolean),
2019
+ skillsIndex: [renderSkillsIndex(ownSkills), renderExternalSkillsHint(this.config, who)].filter(Boolean).join('\n\n'),
2020
+ store: this.store,
2021
+ });
2022
+ // The token lives as long as the terminal: the MCP bridge answers the
2023
+ // assistant's own tools for exactly that long. `emit` is pointed at
2024
+ // whichever turn is typing into it at the time.
2025
+ const context = {
2026
+ orgId: organization.id,
2027
+ audience: 'assistant',
2028
+ agentId: undefined,
2029
+ sessionId: session.id,
2030
+ projectId: session.projectId,
2031
+ depth: -1,
2032
+ scheduled: false,
2033
+ watching: false,
2034
+ emit: () => undefined,
2035
+ signal: undefined,
2036
+ };
2037
+ const token = this.org.register(context);
2038
+ const release = () => {
2039
+ this.org.unregister(token);
2040
+ this.questions.cancelForOwner(token);
2041
+ };
2042
+ const key = conversationTerminalKey(session.id);
2043
+ let entry;
2044
+ try {
2045
+ const mcp = await this.org.bridge.spec(token);
2046
+ const opened = await provider.openTerminal({
2047
+ prompt: '',
2048
+ systemPrompt,
2049
+ systemPromptMode: 'replace',
2050
+ ...(resumed && current.providerSessionId ? { providerSessionId: current.providerSessionId } : {}),
2051
+ ...(model ? { model } : {}),
2052
+ ...(want.effort ? { effort: want.effort } : {}),
2053
+ cwd: this.config.workspace,
2054
+ permission: want.permission,
2055
+ mcp,
2056
+ ...(extra.specs.length ? { mcpExtra: extra.specs } : {}),
2057
+ ...externalTurnExtras(this.config, who),
2058
+ gateway: { ...gateway, picker },
2059
+ tui: { key },
2060
+ }, {
2061
+ // Something a person typed into the terminal itself. What Rookery
2062
+ // types comes back to the turn that typed it and is stored there.
2063
+ onTurn: (typed) => {
2064
+ // A model picked with `/model` in the terminal is this terminal's
2065
+ // model from now on; the chat asking for it must not restart it.
2066
+ if (entry && typed.model)
2067
+ entry.models.add(typed.model);
2068
+ this.#storeTypedTurn(session.id, typed, model);
2069
+ },
2070
+ onExit: () => {
2071
+ release();
2072
+ if (entry && this.#chatTerminals.get(session.id) === entry)
2073
+ this.#chatTerminals.delete(session.id);
2074
+ this.emit('changed', { kind: 'session', id: session.id });
2075
+ },
2076
+ });
2077
+ const models = new Set([model, want.model].filter((name) => Boolean(name)));
2078
+ entry = { handle: opened.terminal, signature, models, servers, context, model };
2079
+ this.#chatTerminals.set(session.id, entry);
2080
+ // Stored at once, so the next message - or a headless turn - resumes
2081
+ // this very session even if nothing was said in the terminal yet.
2082
+ this.store.updateSession(session.id, {
2083
+ provider: want.providerId,
2084
+ ...(model ? { model } : {}),
2085
+ providerSessionId: opened.providerSessionId,
2086
+ });
2087
+ }
2088
+ catch (error) {
2089
+ release();
2090
+ throw error;
2091
+ }
2092
+ this.emit('changed', { kind: 'session', id: session.id });
2093
+ return entry;
2094
+ }
2095
+ /** A turn a person typed straight into the terminal, stored like a chat turn. */
2096
+ #storeTypedTurn(sessionId, turn, openedWith) {
2097
+ if (turn.prompt)
2098
+ this.store.addMessage({ sessionId, role: 'user', content: turn.prompt });
2099
+ // Stored the way a chat turn stores itself: the tool calls, and the
2100
+ // ordered transcript the thread renders them from - or the chat would
2101
+ // show a terminal turn as bare text.
2102
+ const toolCalls = [];
2103
+ const turnBlocks = new TurnBlocks();
2104
+ for (const event of turn.events) {
2105
+ if (event.type === 'tool')
2106
+ toolCalls.push(event);
2107
+ turnBlocks.apply(event);
2108
+ }
2109
+ turnBlocks.reconcile(turn.answer);
2110
+ // Whoever actually answered: `/model` in the terminal may have moved
2111
+ // the conversation to another provider since it opened.
2112
+ const answeredBy = turn.model ?? openedWith;
2113
+ const answeredOn = this.#gatewayOwner(answeredBy, 'claude');
2114
+ this.store.addMessage({
2115
+ sessionId,
2116
+ role: 'assistant',
2117
+ content: turn.answer,
2118
+ provider: answeredOn,
2119
+ ...(answeredBy ? { model: answeredBy } : {}),
2120
+ usage: turn.usage,
2121
+ toolCalls,
2122
+ ...(turnBlocks.blocks.length ? { blocks: turnBlocks.blocks } : {}),
2123
+ });
2124
+ const current = this.store.getSession(sessionId);
2125
+ if (current && current.title === 'New conversation' && turn.prompt) {
2126
+ this.store.updateSession(sessionId, { title: deriveTitle(turn.prompt) });
2127
+ }
2128
+ this.store.updateSession(sessionId, {
2129
+ provider: answeredOn,
2130
+ ...(answeredBy ? { model: answeredBy } : {}),
2131
+ providerSessionId: turn.providerSessionId,
2132
+ });
2133
+ this.emit('changed', { kind: 'session', id: sessionId });
2134
+ if (this.config.memory.enabled && this.config.memory.autoExtract && turn.prompt) {
2135
+ void this.#learn(sessionId, turn.prompt, turn.answer, answeredOn, ASSISTANT_MEMORY_OWNER);
2136
+ }
2137
+ }
2138
+ /** The model gateway conversation terminals share, started with the first one. */
2139
+ #gateway;
2140
+ /** The directly reachable profiles and their models, refreshed with every terminal. */
2141
+ #gatewayProfiles = [];
2142
+ /** Ends the conversation's terminal. False when it had none. */
2143
+ closeConversationTerminal(sessionId) {
2144
+ const had = this.#chatTerminals.has(sessionId) || tuiSessions.info(conversationTerminalKey(sessionId)) !== null;
2145
+ void this.#closeChatTerminal(sessionId);
2146
+ tuiSessions.kill(conversationTerminalKey(sessionId));
2147
+ return had;
2148
+ }
703
2149
  #resolveSession(input) {
704
2150
  if (input.sessionId) {
705
2151
  const existing = this.store.getSession(input.sessionId);
@@ -736,6 +2182,11 @@ export class Assistant extends EventEmitter {
736
2182
  candidates,
737
2183
  owner,
738
2184
  config: this.config.memory,
2185
+ // The user's own message, and nothing else. The assistant's answer
2186
+ // goes to the extractor so it can tell what the exchange was about,
2187
+ // but a fact the assistant produced is not a fact the user confirmed,
2188
+ // and only the user's words may stand behind a memory about the user.
2189
+ sources: [userText],
739
2190
  sourceSessionId: sessionId,
740
2191
  });
741
2192
  if (admitted.rejected.length) {
@@ -761,6 +2212,12 @@ function labelForOwner(assistant, owner) {
761
2212
  /**
762
2213
  * The memories the extractor needs to see so it does not write them again:
763
2214
  * whatever this exchange actually touches, plus the small core profile.
2215
+ *
2216
+ * Deliberately untraced: this is the `site: 'extract'` population of the
2217
+ * dream's vocabulary - `touch: false`, `expand: false`, a wider limit and a
2218
+ * lower threshold than any conversational turn. Stage 1 scores only
2219
+ * `site = 'turn'`, so the recorder does not sit here; wiring it in would
2220
+ * fill the night's pool with calls no label can ever attach to.
764
2221
  */
765
2222
  function relevantKnown(store, owner, text) {
766
2223
  const matched = recall(store, { text, owner, limit: 20, threshold: 0.05, touch: false, expand: false });