rookery-agent 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (743) hide show
  1. package/README.md +9 -3
  2. package/docs/updates.md +12 -0
  3. package/package.json +1 -2
  4. package/packages/cli/dist/commands/chat.d.ts.map +1 -1
  5. package/packages/cli/dist/commands/chat.js +37 -74
  6. package/packages/cli/dist/commands/chat.js.map +1 -1
  7. package/packages/cli/dist/commands/config.js +4 -4
  8. package/packages/cli/dist/commands/config.js.map +1 -1
  9. package/packages/cli/dist/commands/doctor.d.ts.map +1 -1
  10. package/packages/cli/dist/commands/doctor.js +113 -91
  11. package/packages/cli/dist/commands/doctor.js.map +1 -1
  12. package/packages/cli/dist/commands/memory.d.ts.map +1 -1
  13. package/packages/cli/dist/commands/memory.js +28 -31
  14. package/packages/cli/dist/commands/memory.js.map +1 -1
  15. package/packages/cli/dist/commands/org.d.ts.map +1 -1
  16. package/packages/cli/dist/commands/org.js +36 -103
  17. package/packages/cli/dist/commands/org.js.map +1 -1
  18. package/packages/cli/dist/commands/serve.d.ts.map +1 -1
  19. package/packages/cli/dist/commands/serve.js +8 -6
  20. package/packages/cli/dist/commands/serve.js.map +1 -1
  21. package/packages/cli/dist/commands/sessions.d.ts.map +1 -1
  22. package/packages/cli/dist/commands/sessions.js +18 -17
  23. package/packages/cli/dist/commands/sessions.js.map +1 -1
  24. package/packages/cli/dist/commands/shared.d.ts +26 -5
  25. package/packages/cli/dist/commands/shared.d.ts.map +1 -1
  26. package/packages/cli/dist/commands/shared.js +85 -63
  27. package/packages/cli/dist/commands/shared.js.map +1 -1
  28. package/packages/cli/dist/commands/slash.d.ts +51 -0
  29. package/packages/cli/dist/commands/slash.d.ts.map +1 -0
  30. package/packages/cli/dist/commands/slash.js +110 -0
  31. package/packages/cli/dist/commands/slash.js.map +1 -0
  32. package/packages/cli/dist/commands/tasks.d.ts.map +1 -1
  33. package/packages/cli/dist/commands/tasks.js +74 -115
  34. package/packages/cli/dist/commands/tasks.js.map +1 -1
  35. package/packages/cli/dist/commands/tools.d.ts.map +1 -1
  36. package/packages/cli/dist/commands/tools.js +51 -34
  37. package/packages/cli/dist/commands/tools.js.map +1 -1
  38. package/packages/cli/dist/index.js +42 -52
  39. package/packages/cli/dist/index.js.map +1 -1
  40. package/packages/cli/dist/repl.d.ts +1 -25
  41. package/packages/cli/dist/repl.d.ts.map +1 -1
  42. package/packages/cli/dist/repl.js +165 -726
  43. package/packages/cli/dist/repl.js.map +1 -1
  44. package/packages/cli/dist/replInput.d.ts +33 -0
  45. package/packages/cli/dist/replInput.d.ts.map +1 -0
  46. package/packages/cli/dist/replInput.js +97 -0
  47. package/packages/cli/dist/replInput.js.map +1 -0
  48. package/packages/cli/dist/replOutput.d.ts +11 -0
  49. package/packages/cli/dist/replOutput.d.ts.map +1 -0
  50. package/packages/cli/dist/replOutput.js +22 -0
  51. package/packages/cli/dist/replOutput.js.map +1 -0
  52. package/packages/cli/dist/replQuestions.d.ts +32 -0
  53. package/packages/cli/dist/replQuestions.d.ts.map +1 -0
  54. package/packages/cli/dist/replQuestions.js +122 -0
  55. package/packages/cli/dist/replQuestions.js.map +1 -0
  56. package/packages/cli/dist/replSlash.d.ts +24 -0
  57. package/packages/cli/dist/replSlash.d.ts.map +1 -0
  58. package/packages/cli/dist/replSlash.js +311 -0
  59. package/packages/cli/dist/replSlash.js.map +1 -0
  60. package/packages/cli/dist/replState.d.ts +56 -0
  61. package/packages/cli/dist/replState.d.ts.map +1 -0
  62. package/packages/cli/dist/replState.js +89 -0
  63. package/packages/cli/dist/replState.js.map +1 -0
  64. package/packages/cli/dist/tui/App.d.ts +7 -24
  65. package/packages/cli/dist/tui/App.d.ts.map +1 -1
  66. package/packages/cli/dist/tui/App.js +139 -513
  67. package/packages/cli/dist/tui/App.js.map +1 -1
  68. package/packages/cli/dist/tui/LiveRegion.d.ts +16 -0
  69. package/packages/cli/dist/tui/LiveRegion.d.ts.map +1 -0
  70. package/packages/cli/dist/tui/LiveRegion.js +37 -0
  71. package/packages/cli/dist/tui/LiveRegion.js.map +1 -0
  72. package/packages/cli/dist/tui/boot.d.ts +34 -0
  73. package/packages/cli/dist/tui/boot.d.ts.map +1 -0
  74. package/packages/cli/dist/tui/boot.js +133 -0
  75. package/packages/cli/dist/tui/boot.js.map +1 -0
  76. package/packages/cli/dist/tui/commands.d.ts +3 -4
  77. package/packages/cli/dist/tui/commands.d.ts.map +1 -1
  78. package/packages/cli/dist/tui/commands.js +339 -405
  79. package/packages/cli/dist/tui/commands.js.map +1 -1
  80. package/packages/cli/dist/tui/components/ActivityLine.d.ts +1 -1
  81. package/packages/cli/dist/tui/components/ActivityLine.d.ts.map +1 -1
  82. package/packages/cli/dist/tui/components/ActivityLine.js +2 -2
  83. package/packages/cli/dist/tui/components/ActivityLine.js.map +1 -1
  84. package/packages/cli/dist/tui/components/AssignmentsView.d.ts.map +1 -1
  85. package/packages/cli/dist/tui/components/AssignmentsView.js +34 -20
  86. package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -1
  87. package/packages/cli/dist/tui/components/Logo.d.ts +3 -19
  88. package/packages/cli/dist/tui/components/Logo.d.ts.map +1 -1
  89. package/packages/cli/dist/tui/components/Logo.js +13 -13
  90. package/packages/cli/dist/tui/components/Logo.js.map +1 -1
  91. package/packages/cli/dist/tui/components/Markdown.d.ts.map +1 -1
  92. package/packages/cli/dist/tui/components/Markdown.js +201 -146
  93. package/packages/cli/dist/tui/components/Markdown.js.map +1 -1
  94. package/packages/cli/dist/tui/components/QuestionView.d.ts +0 -2
  95. package/packages/cli/dist/tui/components/QuestionView.d.ts.map +1 -1
  96. package/packages/cli/dist/tui/components/QuestionView.js +21 -12
  97. package/packages/cli/dist/tui/components/QuestionView.js.map +1 -1
  98. package/packages/cli/dist/tui/components/Scrollback.d.ts.map +1 -1
  99. package/packages/cli/dist/tui/components/Scrollback.js +6 -3
  100. package/packages/cli/dist/tui/components/Scrollback.js.map +1 -1
  101. package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -1
  102. package/packages/cli/dist/tui/components/SlashPalette.js +14 -9
  103. package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -1
  104. package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -1
  105. package/packages/cli/dist/tui/components/StatusLine.js +45 -22
  106. package/packages/cli/dist/tui/components/StatusLine.js.map +1 -1
  107. package/packages/cli/dist/tui/components/ToolGroup.d.ts.map +1 -1
  108. package/packages/cli/dist/tui/components/ToolGroup.js +12 -7
  109. package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -1
  110. package/packages/cli/dist/tui/components/WatchView.d.ts.map +1 -1
  111. package/packages/cli/dist/tui/components/WatchView.js +28 -17
  112. package/packages/cli/dist/tui/components/WatchView.js.map +1 -1
  113. package/packages/cli/dist/tui/highlight.d.ts +0 -2
  114. package/packages/cli/dist/tui/highlight.d.ts.map +1 -1
  115. package/packages/cli/dist/tui/highlight.js +8 -6
  116. package/packages/cli/dist/tui/highlight.js.map +1 -1
  117. package/packages/cli/dist/tui/history.d.ts +30 -4
  118. package/packages/cli/dist/tui/history.d.ts.map +1 -1
  119. package/packages/cli/dist/tui/history.js +100 -75
  120. package/packages/cli/dist/tui/history.js.map +1 -1
  121. package/packages/cli/dist/tui/hooks/coalescer.d.ts +18 -0
  122. package/packages/cli/dist/tui/hooks/coalescer.d.ts.map +1 -0
  123. package/packages/cli/dist/tui/hooks/coalescer.js +36 -0
  124. package/packages/cli/dist/tui/hooks/coalescer.js.map +1 -0
  125. package/packages/cli/dist/tui/hooks/useColumns.d.ts +2 -7
  126. package/packages/cli/dist/tui/hooks/useColumns.d.ts.map +1 -1
  127. package/packages/cli/dist/tui/hooks/useColumns.js +6 -11
  128. package/packages/cli/dist/tui/hooks/useColumns.js.map +1 -1
  129. package/packages/cli/dist/tui/hooks/useHistory.d.ts +7 -4
  130. package/packages/cli/dist/tui/hooks/useHistory.d.ts.map +1 -1
  131. package/packages/cli/dist/tui/hooks/useHistory.js +21 -18
  132. package/packages/cli/dist/tui/hooks/useHistory.js.map +1 -1
  133. package/packages/cli/dist/tui/hooks/usePrompt.d.ts +27 -0
  134. package/packages/cli/dist/tui/hooks/usePrompt.d.ts.map +1 -0
  135. package/packages/cli/dist/tui/hooks/usePrompt.js +169 -0
  136. package/packages/cli/dist/tui/hooks/usePrompt.js.map +1 -0
  137. package/packages/cli/dist/tui/hooks/useQuestion.d.ts +23 -0
  138. package/packages/cli/dist/tui/hooks/useQuestion.d.ts.map +1 -0
  139. package/packages/cli/dist/tui/hooks/useQuestion.js +43 -0
  140. package/packages/cli/dist/tui/hooks/useQuestion.js.map +1 -0
  141. package/packages/cli/dist/tui/hooks/useScrollback.d.ts +18 -0
  142. package/packages/cli/dist/tui/hooks/useScrollback.d.ts.map +1 -0
  143. package/packages/cli/dist/tui/hooks/useScrollback.js +29 -0
  144. package/packages/cli/dist/tui/hooks/useScrollback.js.map +1 -0
  145. package/packages/cli/dist/tui/hooks/useSession.d.ts +25 -0
  146. package/packages/cli/dist/tui/hooks/useSession.d.ts.map +1 -0
  147. package/packages/cli/dist/tui/hooks/useSession.js +36 -0
  148. package/packages/cli/dist/tui/hooks/useSession.js.map +1 -0
  149. package/packages/cli/dist/tui/hooks/useSlash.d.ts +0 -2
  150. package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -1
  151. package/packages/cli/dist/tui/hooks/useSlash.js +0 -1
  152. package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -1
  153. package/packages/cli/dist/tui/hooks/useSpeech.d.ts +19 -0
  154. package/packages/cli/dist/tui/hooks/useSpeech.d.ts.map +1 -0
  155. package/packages/cli/dist/tui/hooks/useSpeech.js +33 -0
  156. package/packages/cli/dist/tui/hooks/useSpeech.js.map +1 -0
  157. package/packages/cli/dist/tui/hooks/useTicker.d.ts +13 -0
  158. package/packages/cli/dist/tui/hooks/useTicker.d.ts.map +1 -0
  159. package/packages/cli/dist/tui/hooks/useTicker.js +24 -0
  160. package/packages/cli/dist/tui/hooks/useTicker.js.map +1 -0
  161. package/packages/cli/dist/tui/hooks/useTurn.d.ts +4 -4
  162. package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -1
  163. package/packages/cli/dist/tui/hooks/useTurn.js +167 -289
  164. package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -1
  165. package/packages/cli/dist/tui/hooks/useWatch.d.ts.map +1 -1
  166. package/packages/cli/dist/tui/hooks/useWatch.js +15 -48
  167. package/packages/cli/dist/tui/hooks/useWatch.js.map +1 -1
  168. package/packages/cli/dist/tui/inkTheme.d.ts.map +1 -1
  169. package/packages/cli/dist/tui/inkTheme.js +9 -11
  170. package/packages/cli/dist/tui/inkTheme.js.map +1 -1
  171. package/packages/cli/dist/tui/theme.d.ts +7 -13
  172. package/packages/cli/dist/tui/theme.d.ts.map +1 -1
  173. package/packages/cli/dist/tui/theme.js +18 -15
  174. package/packages/cli/dist/tui/theme.js.map +1 -1
  175. package/packages/cli/dist/tui/types.d.ts +10 -23
  176. package/packages/cli/dist/tui/types.d.ts.map +1 -1
  177. package/packages/cli/dist/tui/types.js +13 -31
  178. package/packages/cli/dist/tui/types.js.map +1 -1
  179. package/packages/cli/dist/ui/modelNames.d.ts.map +1 -1
  180. package/packages/cli/dist/ui/modelNames.js +45 -37
  181. package/packages/cli/dist/ui/modelNames.js.map +1 -1
  182. package/packages/cli/dist/ui/render.d.ts +32 -14
  183. package/packages/cli/dist/ui/render.d.ts.map +1 -1
  184. package/packages/cli/dist/ui/render.js +155 -98
  185. package/packages/cli/dist/ui/render.js.map +1 -1
  186. package/packages/cli/dist/ui/speech.d.ts +4 -7
  187. package/packages/cli/dist/ui/speech.d.ts.map +1 -1
  188. package/packages/cli/dist/ui/speech.js +37 -51
  189. package/packages/cli/dist/ui/speech.js.map +1 -1
  190. package/packages/cli/dist/ui/spinner.d.ts +1 -4
  191. package/packages/cli/dist/ui/spinner.d.ts.map +1 -1
  192. package/packages/cli/dist/ui/spinner.js +1 -12
  193. package/packages/cli/dist/ui/spinner.js.map +1 -1
  194. package/packages/cli/package.json +1 -1
  195. package/packages/core/dist/agents/persona.d.ts.map +1 -1
  196. package/packages/core/dist/agents/persona.js +27 -11
  197. package/packages/core/dist/agents/persona.js.map +1 -1
  198. package/packages/core/dist/assistant/board-watch.d.ts +72 -0
  199. package/packages/core/dist/assistant/board-watch.d.ts.map +1 -0
  200. package/packages/core/dist/assistant/board-watch.js +224 -0
  201. package/packages/core/dist/assistant/board-watch.js.map +1 -0
  202. package/packages/core/dist/assistant/chat-turn.d.ts +14 -0
  203. package/packages/core/dist/assistant/chat-turn.d.ts.map +1 -0
  204. package/packages/core/dist/assistant/chat-turn.js +159 -0
  205. package/packages/core/dist/assistant/chat-turn.js.map +1 -0
  206. package/packages/core/dist/assistant/dream-recorder.d.ts +74 -0
  207. package/packages/core/dist/assistant/dream-recorder.d.ts.map +1 -0
  208. package/packages/core/dist/assistant/dream-recorder.js +282 -0
  209. package/packages/core/dist/assistant/dream-recorder.js.map +1 -0
  210. package/packages/core/dist/assistant/headless-turn.d.ts +17 -0
  211. package/packages/core/dist/assistant/headless-turn.d.ts.map +1 -0
  212. package/packages/core/dist/assistant/headless-turn.js +330 -0
  213. package/packages/core/dist/assistant/headless-turn.js.map +1 -0
  214. package/packages/core/dist/assistant/journalled-turn.d.ts +39 -0
  215. package/packages/core/dist/assistant/journalled-turn.d.ts.map +1 -0
  216. package/packages/core/dist/assistant/journalled-turn.js +75 -0
  217. package/packages/core/dist/assistant/journalled-turn.js.map +1 -0
  218. package/packages/core/dist/assistant/memory-learning.d.ts +27 -0
  219. package/packages/core/dist/assistant/memory-learning.d.ts.map +1 -0
  220. package/packages/core/dist/assistant/memory-learning.js +82 -0
  221. package/packages/core/dist/assistant/memory-learning.js.map +1 -0
  222. package/packages/core/dist/assistant/promotion-notice.d.ts +14 -0
  223. package/packages/core/dist/assistant/promotion-notice.d.ts.map +1 -0
  224. package/packages/core/dist/assistant/promotion-notice.js +33 -0
  225. package/packages/core/dist/assistant/promotion-notice.js.map +1 -0
  226. package/packages/core/dist/assistant/scheduled-runs.d.ts +30 -0
  227. package/packages/core/dist/assistant/scheduled-runs.d.ts.map +1 -0
  228. package/packages/core/dist/assistant/scheduled-runs.js +184 -0
  229. package/packages/core/dist/assistant/scheduled-runs.js.map +1 -0
  230. package/packages/core/dist/assistant/sessions.d.ts +44 -0
  231. package/packages/core/dist/assistant/sessions.d.ts.map +1 -0
  232. package/packages/core/dist/assistant/sessions.js +75 -0
  233. package/packages/core/dist/assistant/sessions.js.map +1 -0
  234. package/packages/core/dist/assistant/terminal-turn.d.ts +18 -0
  235. package/packages/core/dist/assistant/terminal-turn.d.ts.map +1 -0
  236. package/packages/core/dist/assistant/terminal-turn.js +228 -0
  237. package/packages/core/dist/assistant/terminal-turn.js.map +1 -0
  238. package/packages/core/dist/assistant/terminals.d.ts +91 -0
  239. package/packages/core/dist/assistant/terminals.d.ts.map +1 -0
  240. package/packages/core/dist/assistant/terminals.js +266 -0
  241. package/packages/core/dist/assistant/terminals.js.map +1 -0
  242. package/packages/core/dist/assistant/turn-support.d.ts +109 -0
  243. package/packages/core/dist/assistant/turn-support.d.ts.map +1 -0
  244. package/packages/core/dist/assistant/turn-support.js +80 -0
  245. package/packages/core/dist/assistant/turn-support.js.map +1 -0
  246. package/packages/core/dist/assistant/turn-transcript.d.ts +44 -0
  247. package/packages/core/dist/assistant/turn-transcript.d.ts.map +1 -0
  248. package/packages/core/dist/assistant/turn-transcript.js +82 -0
  249. package/packages/core/dist/assistant/turn-transcript.js.map +1 -0
  250. package/packages/core/dist/assistant/types.d.ts +120 -0
  251. package/packages/core/dist/assistant/types.d.ts.map +1 -0
  252. package/packages/core/dist/assistant/types.js +2 -0
  253. package/packages/core/dist/assistant/types.js.map +1 -0
  254. package/packages/core/dist/computer/accessibility.d.ts.map +1 -1
  255. package/packages/core/dist/computer/accessibility.js +40 -35
  256. package/packages/core/dist/computer/accessibility.js.map +1 -1
  257. package/packages/core/dist/computer/mcp-server.js +426 -364
  258. package/packages/core/dist/computer/mcp-server.js.map +1 -1
  259. package/packages/core/dist/computer/powershell.d.ts.map +1 -1
  260. package/packages/core/dist/computer/powershell.js +25 -16
  261. package/packages/core/dist/computer/powershell.js.map +1 -1
  262. package/packages/core/dist/computer/screen-text.d.ts.map +1 -1
  263. package/packages/core/dist/computer/screen-text.js +54 -34
  264. package/packages/core/dist/computer/screen-text.js.map +1 -1
  265. package/packages/core/dist/computer/sketch.d.ts.map +1 -1
  266. package/packages/core/dist/computer/sketch.js +185 -128
  267. package/packages/core/dist/computer/sketch.js.map +1 -1
  268. package/packages/core/dist/computer/tools.d.ts +2 -0
  269. package/packages/core/dist/computer/tools.d.ts.map +1 -1
  270. package/packages/core/dist/computer/tools.js +31 -27
  271. package/packages/core/dist/computer/tools.js.map +1 -1
  272. package/packages/core/dist/computer/validation.d.ts +16 -16
  273. package/packages/core/dist/computer/validation.d.ts.map +1 -1
  274. package/packages/core/dist/computer/validation.js +28 -20
  275. package/packages/core/dist/computer/validation.js.map +1 -1
  276. package/packages/core/dist/config.d.ts +10 -1
  277. package/packages/core/dist/config.d.ts.map +1 -1
  278. package/packages/core/dist/config.js +81 -26
  279. package/packages/core/dist/config.js.map +1 -1
  280. package/packages/core/dist/cron/parse.d.ts.map +1 -1
  281. package/packages/core/dist/cron/parse.js +90 -77
  282. package/packages/core/dist/cron/parse.js.map +1 -1
  283. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  284. package/packages/core/dist/cron/scheduler.js +99 -65
  285. package/packages/core/dist/cron/scheduler.js.map +1 -1
  286. package/packages/core/dist/cron/script.d.ts.map +1 -1
  287. package/packages/core/dist/cron/script.js +72 -42
  288. package/packages/core/dist/cron/script.js.map +1 -1
  289. package/packages/core/dist/external/claude-code.d.ts.map +1 -1
  290. package/packages/core/dist/external/claude-code.js +41 -28
  291. package/packages/core/dist/external/claude-code.js.map +1 -1
  292. package/packages/core/dist/external/discovery.d.ts.map +1 -1
  293. package/packages/core/dist/external/discovery.js +14 -11
  294. package/packages/core/dist/external/discovery.js.map +1 -1
  295. package/packages/core/dist/external/shared.d.ts +20 -0
  296. package/packages/core/dist/external/shared.d.ts.map +1 -1
  297. package/packages/core/dist/external/shared.js +97 -81
  298. package/packages/core/dist/external/shared.js.map +1 -1
  299. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  300. package/packages/core/dist/gateway/policy.js +5 -2
  301. package/packages/core/dist/gateway/policy.js.map +1 -1
  302. package/packages/core/dist/logger.d.ts.map +1 -1
  303. package/packages/core/dist/logger.js +11 -11
  304. package/packages/core/dist/logger.js.map +1 -1
  305. package/packages/core/dist/memory/db.d.ts.map +1 -1
  306. package/packages/core/dist/memory/db.js +175 -226
  307. package/packages/core/dist/memory/db.js.map +1 -1
  308. package/packages/core/dist/memory/dream/admission.d.ts +5 -0
  309. package/packages/core/dist/memory/dream/admission.d.ts.map +1 -1
  310. package/packages/core/dist/memory/dream/admission.js +8 -14
  311. package/packages/core/dist/memory/dream/admission.js.map +1 -1
  312. package/packages/core/dist/memory/dream/candidate.d.ts.map +1 -1
  313. package/packages/core/dist/memory/dream/candidate.js +119 -92
  314. package/packages/core/dist/memory/dream/candidate.js.map +1 -1
  315. package/packages/core/dist/memory/dream/evaluate.d.ts +13 -4
  316. package/packages/core/dist/memory/dream/evaluate.d.ts.map +1 -1
  317. package/packages/core/dist/memory/dream/evaluate.js +264 -288
  318. package/packages/core/dist/memory/dream/evaluate.js.map +1 -1
  319. package/packages/core/dist/memory/dream/frame.d.ts +6 -0
  320. package/packages/core/dist/memory/dream/frame.d.ts.map +1 -1
  321. package/packages/core/dist/memory/dream/frame.js +137 -91
  322. package/packages/core/dist/memory/dream/frame.js.map +1 -1
  323. package/packages/core/dist/memory/dream/label.d.ts.map +1 -1
  324. package/packages/core/dist/memory/dream/label.js +6 -9
  325. package/packages/core/dist/memory/dream/label.js.map +1 -1
  326. package/packages/core/dist/memory/dream/measure.d.ts +4 -0
  327. package/packages/core/dist/memory/dream/measure.d.ts.map +1 -1
  328. package/packages/core/dist/memory/dream/measure.js +13 -58
  329. package/packages/core/dist/memory/dream/measure.js.map +1 -1
  330. package/packages/core/dist/memory/dream/policy.d.ts.map +1 -1
  331. package/packages/core/dist/memory/dream/policy.js +4 -2
  332. package/packages/core/dist/memory/dream/policy.js.map +1 -1
  333. package/packages/core/dist/memory/dream/probe.d.ts +31 -4
  334. package/packages/core/dist/memory/dream/probe.d.ts.map +1 -1
  335. package/packages/core/dist/memory/dream/probe.js +290 -289
  336. package/packages/core/dist/memory/dream/probe.js.map +1 -1
  337. package/packages/core/dist/memory/dream/promote.d.ts.map +1 -1
  338. package/packages/core/dist/memory/dream/promote.js +10 -11
  339. package/packages/core/dist/memory/dream/promote.js.map +1 -1
  340. package/packages/core/dist/memory/dream/score.d.ts +9 -0
  341. package/packages/core/dist/memory/dream/score.d.ts.map +1 -1
  342. package/packages/core/dist/memory/dream/score.js +6 -7
  343. package/packages/core/dist/memory/dream/score.js.map +1 -1
  344. package/packages/core/dist/memory/dream/slots.d.ts.map +1 -1
  345. package/packages/core/dist/memory/dream/slots.js +0 -0
  346. package/packages/core/dist/memory/dream/slots.js.map +1 -1
  347. package/packages/core/dist/memory/dream/trajectory.d.ts.map +1 -1
  348. package/packages/core/dist/memory/dream/trajectory.js +76 -53
  349. package/packages/core/dist/memory/dream/trajectory.js.map +1 -1
  350. package/packages/core/dist/memory/dream/util.d.ts +44 -0
  351. package/packages/core/dist/memory/dream/util.d.ts.map +1 -0
  352. package/packages/core/dist/memory/dream/util.js +83 -0
  353. package/packages/core/dist/memory/dream/util.js.map +1 -0
  354. package/packages/core/dist/memory/extractor.d.ts.map +1 -1
  355. package/packages/core/dist/memory/extractor.js +67 -46
  356. package/packages/core/dist/memory/extractor.js.map +1 -1
  357. package/packages/core/dist/memory/gate.d.ts.map +1 -1
  358. package/packages/core/dist/memory/gate.js +55 -44
  359. package/packages/core/dist/memory/gate.js.map +1 -1
  360. package/packages/core/dist/memory/recall.d.ts +1 -1
  361. package/packages/core/dist/memory/recall.d.ts.map +1 -1
  362. package/packages/core/dist/memory/recall.js +55 -43
  363. package/packages/core/dist/memory/recall.js.map +1 -1
  364. package/packages/core/dist/memory/sleep-dream.d.ts +210 -0
  365. package/packages/core/dist/memory/sleep-dream.d.ts.map +1 -0
  366. package/packages/core/dist/memory/sleep-dream.js +1109 -0
  367. package/packages/core/dist/memory/sleep-dream.js.map +1 -0
  368. package/packages/core/dist/memory/sleep-frames.d.ts +40 -0
  369. package/packages/core/dist/memory/sleep-frames.d.ts.map +1 -0
  370. package/packages/core/dist/memory/sleep-frames.js +127 -0
  371. package/packages/core/dist/memory/sleep-frames.js.map +1 -0
  372. package/packages/core/dist/memory/sleep-limits.d.ts +18 -0
  373. package/packages/core/dist/memory/sleep-limits.d.ts.map +1 -0
  374. package/packages/core/dist/memory/sleep-limits.js +34 -0
  375. package/packages/core/dist/memory/sleep-limits.js.map +1 -0
  376. package/packages/core/dist/memory/sleep-model.d.ts +36 -0
  377. package/packages/core/dist/memory/sleep-model.d.ts.map +1 -0
  378. package/packages/core/dist/memory/sleep-model.js +80 -0
  379. package/packages/core/dist/memory/sleep-model.js.map +1 -0
  380. package/packages/core/dist/memory/sleep-policy.d.ts +19 -0
  381. package/packages/core/dist/memory/sleep-policy.d.ts.map +1 -0
  382. package/packages/core/dist/memory/sleep-policy.js +79 -0
  383. package/packages/core/dist/memory/sleep-policy.js.map +1 -0
  384. package/packages/core/dist/memory/sleep-prompts.d.ts +15 -0
  385. package/packages/core/dist/memory/sleep-prompts.d.ts.map +1 -0
  386. package/packages/core/dist/memory/sleep-prompts.js +212 -0
  387. package/packages/core/dist/memory/sleep-prompts.js.map +1 -0
  388. package/packages/core/dist/memory/sleep-report.d.ts +63 -0
  389. package/packages/core/dist/memory/sleep-report.d.ts.map +1 -0
  390. package/packages/core/dist/memory/sleep-report.js +97 -0
  391. package/packages/core/dist/memory/sleep-report.js.map +1 -0
  392. package/packages/core/dist/memory/sleep-verdicts.d.ts +77 -0
  393. package/packages/core/dist/memory/sleep-verdicts.d.ts.map +1 -0
  394. package/packages/core/dist/memory/sleep-verdicts.js +198 -0
  395. package/packages/core/dist/memory/sleep-verdicts.js.map +1 -0
  396. package/packages/core/dist/memory/sleep.d.ts +6 -61
  397. package/packages/core/dist/memory/sleep.d.ts.map +1 -1
  398. package/packages/core/dist/memory/sleep.js +1099 -2458
  399. package/packages/core/dist/memory/sleep.js.map +1 -1
  400. package/packages/core/dist/memory/store-rows.d.ts +43 -0
  401. package/packages/core/dist/memory/store-rows.d.ts.map +1 -0
  402. package/packages/core/dist/memory/store-rows.js +330 -0
  403. package/packages/core/dist/memory/store-rows.js.map +1 -0
  404. package/packages/core/dist/memory/store.d.ts +34 -20
  405. package/packages/core/dist/memory/store.d.ts.map +1 -1
  406. package/packages/core/dist/memory/store.js +634 -861
  407. package/packages/core/dist/memory/store.js.map +1 -1
  408. package/packages/core/dist/migration-cron.d.ts +2 -1
  409. package/packages/core/dist/migration-cron.d.ts.map +1 -1
  410. package/packages/core/dist/migration-cron.js +197 -154
  411. package/packages/core/dist/migration-cron.js.map +1 -1
  412. package/packages/core/dist/migration-scripts.d.ts +11 -3
  413. package/packages/core/dist/migration-scripts.d.ts.map +1 -1
  414. package/packages/core/dist/migration-scripts.js +81 -61
  415. package/packages/core/dist/migration-scripts.js.map +1 -1
  416. package/packages/core/dist/migration-shared.d.ts +9 -0
  417. package/packages/core/dist/migration-shared.d.ts.map +1 -0
  418. package/packages/core/dist/migration-shared.js +16 -0
  419. package/packages/core/dist/migration-shared.js.map +1 -0
  420. package/packages/core/dist/migration.d.ts.map +1 -1
  421. package/packages/core/dist/migration.js +150 -111
  422. package/packages/core/dist/migration.js.map +1 -1
  423. package/packages/core/dist/org/assignment-log.d.ts +28 -0
  424. package/packages/core/dist/org/assignment-log.d.ts.map +1 -0
  425. package/packages/core/dist/org/assignment-log.js +86 -0
  426. package/packages/core/dist/org/assignment-log.js.map +1 -0
  427. package/packages/core/dist/org/bridge.d.ts.map +1 -1
  428. package/packages/core/dist/org/bridge.js +32 -30
  429. package/packages/core/dist/org/bridge.js.map +1 -1
  430. package/packages/core/dist/org/controller.d.ts +18 -21
  431. package/packages/core/dist/org/controller.d.ts.map +1 -1
  432. package/packages/core/dist/org/controller.js +2042 -1848
  433. package/packages/core/dist/org/controller.js.map +1 -1
  434. package/packages/core/dist/org/json-reply.d.ts +6 -0
  435. package/packages/core/dist/org/json-reply.d.ts.map +1 -0
  436. package/packages/core/dist/org/json-reply.js +23 -0
  437. package/packages/core/dist/org/json-reply.js.map +1 -0
  438. package/packages/core/dist/org/mcp-bridge.js +34 -26
  439. package/packages/core/dist/org/mcp-bridge.js.map +1 -1
  440. package/packages/core/dist/org/planner.d.ts.map +1 -1
  441. package/packages/core/dist/org/planner.js +38 -42
  442. package/packages/core/dist/org/planner.js.map +1 -1
  443. package/packages/core/dist/org/project-mcp.d.ts.map +1 -1
  444. package/packages/core/dist/org/project-mcp.js +2 -5
  445. package/packages/core/dist/org/project-mcp.js.map +1 -1
  446. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  447. package/packages/core/dist/org/prompts.js +176 -156
  448. package/packages/core/dist/org/prompts.js.map +1 -1
  449. package/packages/core/dist/org/questions.d.ts.map +1 -1
  450. package/packages/core/dist/org/questions.js +19 -14
  451. package/packages/core/dist/org/questions.js.map +1 -1
  452. package/packages/core/dist/org/review.d.ts.map +1 -1
  453. package/packages/core/dist/org/review.js +27 -43
  454. package/packages/core/dist/org/review.js.map +1 -1
  455. package/packages/core/dist/org/store.d.ts +19 -32
  456. package/packages/core/dist/org/store.d.ts.map +1 -1
  457. package/packages/core/dist/org/store.js +250 -206
  458. package/packages/core/dist/org/store.js.map +1 -1
  459. package/packages/core/dist/org/tool-args.d.ts +54 -0
  460. package/packages/core/dist/org/tool-args.d.ts.map +1 -0
  461. package/packages/core/dist/org/tool-args.js +104 -0
  462. package/packages/core/dist/org/tool-args.js.map +1 -0
  463. package/packages/core/dist/org/tools.d.ts.map +1 -1
  464. package/packages/core/dist/org/tools.js +238 -443
  465. package/packages/core/dist/org/tools.js.map +1 -1
  466. package/packages/core/dist/profile.d.ts.map +1 -1
  467. package/packages/core/dist/profile.js +114 -57
  468. package/packages/core/dist/profile.js.map +1 -1
  469. package/packages/core/dist/providers/catalogue.d.ts.map +1 -1
  470. package/packages/core/dist/providers/catalogue.js +89 -60
  471. package/packages/core/dist/providers/catalogue.js.map +1 -1
  472. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  473. package/packages/core/dist/providers/claude-code.js +418 -357
  474. package/packages/core/dist/providers/claude-code.js.map +1 -1
  475. package/packages/core/dist/providers/claude-tui.d.ts +13 -9
  476. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -1
  477. package/packages/core/dist/providers/claude-tui.js +568 -396
  478. package/packages/core/dist/providers/claude-tui.js.map +1 -1
  479. package/packages/core/dist/providers/codex-auth.d.ts +3 -0
  480. package/packages/core/dist/providers/codex-auth.d.ts.map +1 -1
  481. package/packages/core/dist/providers/codex-auth.js +9 -7
  482. package/packages/core/dist/providers/codex-auth.js.map +1 -1
  483. package/packages/core/dist/providers/codex-bridge.d.ts +24 -7
  484. package/packages/core/dist/providers/codex-bridge.d.ts.map +1 -1
  485. package/packages/core/dist/providers/codex-bridge.js +128 -168
  486. package/packages/core/dist/providers/codex-bridge.js.map +1 -1
  487. package/packages/core/dist/providers/codex-translate.d.ts.map +1 -1
  488. package/packages/core/dist/providers/codex-translate.js +195 -197
  489. package/packages/core/dist/providers/codex-translate.js.map +1 -1
  490. package/packages/core/dist/providers/loopback-server.d.ts +33 -0
  491. package/packages/core/dist/providers/loopback-server.d.ts.map +1 -0
  492. package/packages/core/dist/providers/loopback-server.js +104 -0
  493. package/packages/core/dist/providers/loopback-server.js.map +1 -0
  494. package/packages/core/dist/providers/model-gateway.d.ts +2 -4
  495. package/packages/core/dist/providers/model-gateway.d.ts.map +1 -1
  496. package/packages/core/dist/providers/model-gateway.js +39 -75
  497. package/packages/core/dist/providers/model-gateway.js.map +1 -1
  498. package/packages/core/dist/providers/process.d.ts.map +1 -1
  499. package/packages/core/dist/providers/process.js +32 -23
  500. package/packages/core/dist/providers/process.js.map +1 -1
  501. package/packages/core/dist/providers/provider-catalog.d.ts.map +1 -1
  502. package/packages/core/dist/providers/provider-catalog.js +21 -23
  503. package/packages/core/dist/providers/provider-catalog.js.map +1 -1
  504. package/packages/core/dist/providers/quota.d.ts.map +1 -1
  505. package/packages/core/dist/providers/quota.js +37 -37
  506. package/packages/core/dist/providers/quota.js.map +1 -1
  507. package/packages/core/dist/providers/registry.d.ts.map +1 -1
  508. package/packages/core/dist/providers/registry.js +3 -1
  509. package/packages/core/dist/providers/registry.js.map +1 -1
  510. package/packages/core/dist/providers/user-settings-guard.d.ts.map +1 -1
  511. package/packages/core/dist/providers/user-settings-guard.js +7 -2
  512. package/packages/core/dist/providers/user-settings-guard.js.map +1 -1
  513. package/packages/core/dist/runtime.d.ts +45 -158
  514. package/packages/core/dist/runtime.d.ts.map +1 -1
  515. package/packages/core/dist/runtime.js +184 -1701
  516. package/packages/core/dist/runtime.js.map +1 -1
  517. package/packages/core/dist/skills/import.d.ts.map +1 -1
  518. package/packages/core/dist/skills/import.js +52 -36
  519. package/packages/core/dist/skills/import.js.map +1 -1
  520. package/packages/core/dist/skills/shelf.d.ts +14 -0
  521. package/packages/core/dist/skills/shelf.d.ts.map +1 -1
  522. package/packages/core/dist/skills/shelf.js +2 -3
  523. package/packages/core/dist/skills/shelf.js.map +1 -1
  524. package/packages/core/dist/skills/store.d.ts +2 -0
  525. package/packages/core/dist/skills/store.d.ts.map +1 -1
  526. package/packages/core/dist/skills/store.js +17 -12
  527. package/packages/core/dist/skills/store.js.map +1 -1
  528. package/packages/core/dist/tools/catalog.d.ts +13 -0
  529. package/packages/core/dist/tools/catalog.d.ts.map +1 -1
  530. package/packages/core/dist/tools/catalog.js +20 -5
  531. package/packages/core/dist/tools/catalog.js.map +1 -1
  532. package/packages/core/dist/tools/hub.d.ts +4 -1
  533. package/packages/core/dist/tools/hub.d.ts.map +1 -1
  534. package/packages/core/dist/tools/hub.js +114 -83
  535. package/packages/core/dist/tools/hub.js.map +1 -1
  536. package/packages/core/dist/turns/journal.d.ts.map +1 -1
  537. package/packages/core/dist/turns/journal.js +12 -18
  538. package/packages/core/dist/turns/journal.js.map +1 -1
  539. package/packages/core/dist/types.d.ts +25 -3
  540. package/packages/core/dist/types.d.ts.map +1 -1
  541. package/packages/core/dist/types.js.map +1 -1
  542. package/packages/core/dist/util/blocks.d.ts.map +1 -1
  543. package/packages/core/dist/util/blocks.js +14 -22
  544. package/packages/core/dist/util/blocks.js.map +1 -1
  545. package/packages/core/dist/util/queue.d.ts +0 -2
  546. package/packages/core/dist/util/queue.d.ts.map +1 -1
  547. package/packages/core/dist/util/queue.js +0 -6
  548. package/packages/core/dist/util/queue.js.map +1 -1
  549. package/packages/core/package.json +1 -1
  550. package/packages/server/dist/auth.d.ts +27 -9
  551. package/packages/server/dist/auth.d.ts.map +1 -1
  552. package/packages/server/dist/auth.js +73 -15
  553. package/packages/server/dist/auth.js.map +1 -1
  554. package/packages/server/dist/env.d.ts.map +1 -1
  555. package/packages/server/dist/env.js +18 -15
  556. package/packages/server/dist/env.js.map +1 -1
  557. package/packages/server/dist/errors.d.ts +3 -0
  558. package/packages/server/dist/errors.d.ts.map +1 -0
  559. package/packages/server/dist/errors.js +5 -0
  560. package/packages/server/dist/errors.js.map +1 -0
  561. package/packages/server/dist/gateways/attachments.d.ts.map +1 -1
  562. package/packages/server/dist/gateways/attachments.js +38 -21
  563. package/packages/server/dist/gateways/attachments.js.map +1 -1
  564. package/packages/server/dist/gateways/markdown.d.ts.map +1 -1
  565. package/packages/server/dist/gateways/markdown.js +30 -12
  566. package/packages/server/dist/gateways/markdown.js.map +1 -1
  567. package/packages/server/dist/gateways/push.d.ts +6 -6
  568. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  569. package/packages/server/dist/gateways/push.js +101 -74
  570. package/packages/server/dist/gateways/push.js.map +1 -1
  571. package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -1
  572. package/packages/server/dist/gateways/telegram-api.js +61 -44
  573. package/packages/server/dist/gateways/telegram-api.js.map +1 -1
  574. package/packages/server/dist/gateways/telegram.d.ts +5 -0
  575. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  576. package/packages/server/dist/gateways/telegram.js +985 -753
  577. package/packages/server/dist/gateways/telegram.js.map +1 -1
  578. package/packages/server/dist/gateways/threads.d.ts.map +1 -1
  579. package/packages/server/dist/gateways/threads.js +144 -130
  580. package/packages/server/dist/gateways/threads.js.map +1 -1
  581. package/packages/server/dist/listeners/imap.d.ts.map +1 -1
  582. package/packages/server/dist/listeners/imap.js +0 -0
  583. package/packages/server/dist/listeners/imap.js.map +1 -1
  584. package/packages/server/dist/listeners/registry.d.ts.map +1 -1
  585. package/packages/server/dist/listeners/registry.js +15 -15
  586. package/packages/server/dist/listeners/registry.js.map +1 -1
  587. package/packages/server/dist/main.js +3 -2
  588. package/packages/server/dist/main.js.map +1 -1
  589. package/packages/server/dist/routes/chat.d.ts.map +1 -1
  590. package/packages/server/dist/routes/chat.js +5 -8
  591. package/packages/server/dist/routes/chat.js.map +1 -1
  592. package/packages/server/dist/routes/config.d.ts +6 -0
  593. package/packages/server/dist/routes/config.d.ts.map +1 -1
  594. package/packages/server/dist/routes/config.js +34 -31
  595. package/packages/server/dist/routes/config.js.map +1 -1
  596. package/packages/server/dist/routes/cron.d.ts.map +1 -1
  597. package/packages/server/dist/routes/cron.js +33 -23
  598. package/packages/server/dist/routes/cron.js.map +1 -1
  599. package/packages/server/dist/routes/dream.d.ts +1 -1
  600. package/packages/server/dist/routes/dream.d.ts.map +1 -1
  601. package/packages/server/dist/routes/dream.js +16 -34
  602. package/packages/server/dist/routes/dream.js.map +1 -1
  603. package/packages/server/dist/routes/gateways.d.ts.map +1 -1
  604. package/packages/server/dist/routes/gateways.js +8 -13
  605. package/packages/server/dist/routes/gateways.js.map +1 -1
  606. package/packages/server/dist/routes/memories.d.ts.map +1 -1
  607. package/packages/server/dist/routes/memories.js +16 -29
  608. package/packages/server/dist/routes/memories.js.map +1 -1
  609. package/packages/server/dist/routes/night.d.ts +31 -0
  610. package/packages/server/dist/routes/night.d.ts.map +1 -0
  611. package/packages/server/dist/routes/night.js +28 -0
  612. package/packages/server/dist/routes/night.js.map +1 -0
  613. package/packages/server/dist/routes/org.d.ts.map +1 -1
  614. package/packages/server/dist/routes/org.js +125 -119
  615. package/packages/server/dist/routes/org.js.map +1 -1
  616. package/packages/server/dist/routes/profile.d.ts.map +1 -1
  617. package/packages/server/dist/routes/profile.js +5 -6
  618. package/packages/server/dist/routes/profile.js.map +1 -1
  619. package/packages/server/dist/routes/providers.d.ts.map +1 -1
  620. package/packages/server/dist/routes/providers.js +1 -3
  621. package/packages/server/dist/routes/providers.js.map +1 -1
  622. package/packages/server/dist/routes/query.d.ts +10 -0
  623. package/packages/server/dist/routes/query.d.ts.map +1 -0
  624. package/packages/server/dist/routes/query.js +17 -0
  625. package/packages/server/dist/routes/query.js.map +1 -0
  626. package/packages/server/dist/routes/questions.d.ts.map +1 -1
  627. package/packages/server/dist/routes/questions.js +5 -11
  628. package/packages/server/dist/routes/questions.js.map +1 -1
  629. package/packages/server/dist/routes/sessions.d.ts.map +1 -1
  630. package/packages/server/dist/routes/sessions.js +20 -28
  631. package/packages/server/dist/routes/sessions.js.map +1 -1
  632. package/packages/server/dist/routes/sleep.d.ts.map +1 -1
  633. package/packages/server/dist/routes/sleep.js +21 -36
  634. package/packages/server/dist/routes/sleep.js.map +1 -1
  635. package/packages/server/dist/routes/stats.d.ts.map +1 -1
  636. package/packages/server/dist/routes/stats.js +2 -7
  637. package/packages/server/dist/routes/stats.js.map +1 -1
  638. package/packages/server/dist/routes/terminals.d.ts.map +1 -1
  639. package/packages/server/dist/routes/terminals.js +19 -14
  640. package/packages/server/dist/routes/terminals.js.map +1 -1
  641. package/packages/server/dist/routes/tools.d.ts.map +1 -1
  642. package/packages/server/dist/routes/tools.js +9 -5
  643. package/packages/server/dist/routes/tools.js.map +1 -1
  644. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  645. package/packages/server/dist/routes/ws.js +235 -207
  646. package/packages/server/dist/routes/ws.js.map +1 -1
  647. package/packages/server/dist/schemas.d.ts +30 -21
  648. package/packages/server/dist/schemas.d.ts.map +1 -1
  649. package/packages/server/dist/schemas.js +3 -2
  650. package/packages/server/dist/schemas.js.map +1 -1
  651. package/packages/server/dist/server.d.ts.map +1 -1
  652. package/packages/server/dist/server.js +257 -238
  653. package/packages/server/dist/server.js.map +1 -1
  654. package/packages/server/dist/services/stream.d.ts.map +1 -1
  655. package/packages/server/dist/services/stream.js +6 -4
  656. package/packages/server/dist/services/stream.js.map +1 -1
  657. package/packages/server/dist/services/stt.d.ts +1 -1
  658. package/packages/server/dist/services/stt.d.ts.map +1 -1
  659. package/packages/server/dist/services/stt.js +175 -124
  660. package/packages/server/dist/services/stt.js.map +1 -1
  661. package/packages/server/dist/services/tts.d.ts.map +1 -1
  662. package/packages/server/dist/services/tts.js +82 -54
  663. package/packages/server/dist/services/tts.js.map +1 -1
  664. package/packages/server/dist/services/turns.d.ts +8 -6
  665. package/packages/server/dist/services/turns.d.ts.map +1 -1
  666. package/packages/server/dist/services/turns.js +36 -32
  667. package/packages/server/dist/services/turns.js.map +1 -1
  668. package/packages/server/dist/services/updates.d.ts +1 -0
  669. package/packages/server/dist/services/updates.d.ts.map +1 -1
  670. package/packages/server/dist/services/updates.js +150 -91
  671. package/packages/server/dist/services/updates.js.map +1 -1
  672. package/packages/server/dist/services/voice-keys.d.ts.map +1 -1
  673. package/packages/server/dist/services/voice-keys.js +4 -2
  674. package/packages/server/dist/services/voice-keys.js.map +1 -1
  675. package/packages/server/dist/static.d.ts +1 -1
  676. package/packages/server/dist/static.d.ts.map +1 -1
  677. package/packages/server/dist/static.js +7 -7
  678. package/packages/server/dist/static.js.map +1 -1
  679. package/packages/server/package.json +1 -1
  680. package/packages/web/dist/assets/{abnfDiagram-O67JEVCF-D7YyFndQ.js → abnfDiagram-O67JEVCF-BmjzYusK.js} +1 -1
  681. package/packages/web/dist/assets/{arc-C_Zgk2dJ.js → arc-n9TPu3wY.js} +1 -1
  682. package/packages/web/dist/assets/{architectureDiagram-NJMV4G6O-eI0adu1B.js → architectureDiagram-NJMV4G6O-Cx9TKHMG.js} +1 -1
  683. package/packages/web/dist/assets/{blockDiagram-BEXU5L5S-WAoOFUA9.js → blockDiagram-BEXU5L5S-Cu2lqO0u.js} +1 -1
  684. package/packages/web/dist/assets/{c4Diagram-YGBWAQC7-DE8Zyhng.js → c4Diagram-YGBWAQC7-C0lage7M.js} +1 -1
  685. package/packages/web/dist/assets/channel-Cx64mAod.js +1 -0
  686. package/packages/web/dist/assets/{chunk-2Q5K7J3B-bnqLP2XD.js → chunk-2Q5K7J3B-D3aVQoie.js} +1 -1
  687. package/packages/web/dist/assets/{chunk-3FUC2YCW-Ck1_SVe0.js → chunk-3FUC2YCW-Cmrvpp5I.js} +2 -2
  688. package/packages/web/dist/assets/{chunk-5VM5RSS4-hDmC41gD.js → chunk-5VM5RSS4-Bk7nd1Or.js} +1 -1
  689. package/packages/web/dist/assets/{chunk-GTNCS2PH-PoWvfCrT.js → chunk-GTNCS2PH--_-V13S9.js} +1 -1
  690. package/packages/web/dist/assets/{chunk-GWA4HPMP-D3V0IG43.js → chunk-GWA4HPMP-B2iN_iAC.js} +1 -1
  691. package/packages/web/dist/assets/{chunk-JWPE2WC7-BryfpHM5.js → chunk-JWPE2WC7-BCQEdHBw.js} +1 -1
  692. package/packages/web/dist/assets/{chunk-NETBCI7D-8ic1iEdT.js → chunk-NETBCI7D-lKrFsR6g.js} +1 -1
  693. package/packages/web/dist/assets/{chunk-WEXAMYUT-nM8tmQT2.js → chunk-WEXAMYUT-Bl4c2a1n.js} +1 -1
  694. package/packages/web/dist/assets/{chunk-XXDRQBXY-Do28F482.js → chunk-XXDRQBXY-xvPIGObD.js} +1 -1
  695. package/packages/web/dist/assets/{classDiagram-v2-NBCMYWYE-Bop9oNNO.js → classDiagram-v2-NBCMYWYE-DjX85RUY.js} +1 -1
  696. package/packages/web/dist/assets/{cose-bilkent-JH36ORCC-a7f_bpnt.js → cose-bilkent-JH36ORCC-Dn5oYBNs.js} +1 -1
  697. package/packages/web/dist/assets/{cynefin-OW5HDTMX-DnArcis_.js → cynefin-OW5HDTMX-D1zN_crx.js} +1 -1
  698. package/packages/web/dist/assets/{cynefinDiagram-VND7K2PF-vEuTb1GD.js → cynefinDiagram-VND7K2PF-B-GwPS_J.js} +1 -1
  699. package/packages/web/dist/assets/{dagre-6A5THRUB-BgG4MynJ.js → dagre-6A5THRUB-C2wUvKaS.js} +1 -1
  700. package/packages/web/dist/assets/{diagram-22UHCM2B-DRCQpafv.js → diagram-22UHCM2B-DnZ3T6JG.js} +1 -1
  701. package/packages/web/dist/assets/{diagram-3UASUU5V-BKgmAXde.js → diagram-3UASUU5V-DR8pK0Yb.js} +1 -1
  702. package/packages/web/dist/assets/{diagram-ATOU4E4O-B6Hsy36X.js → diagram-ATOU4E4O-olswvjNy.js} +1 -1
  703. package/packages/web/dist/assets/{diagram-CDSNMT55-JflyfyoB.js → diagram-CDSNMT55-CkbrgFGH.js} +1 -1
  704. package/packages/web/dist/assets/{diagram-MLGK6HIB-Dd2QPJjT.js → diagram-MLGK6HIB-DiNLsh9k.js} +1 -1
  705. package/packages/web/dist/assets/{diagram-MPIPVDR6-DE5QU60x.js → diagram-MPIPVDR6-DY0eRCo8.js} +1 -1
  706. package/packages/web/dist/assets/{ebnfDiagram-ZINNZB2B-D7AQ741b.js → ebnfDiagram-ZINNZB2B-BwyYBste.js} +1 -1
  707. package/packages/web/dist/assets/{elk-276RUBZZ-CeewBVLF.js → elk-276RUBZZ-BOkb2Unt.js} +1 -1
  708. package/packages/web/dist/assets/{erDiagram-OPXOYQCR-mLLYkZ5c.js → erDiagram-OPXOYQCR-Bopm0hOe.js} +1 -1
  709. package/packages/web/dist/assets/{flowDiagram-KWPJA3E3-DtpSpsQN.js → flowDiagram-KWPJA3E3-CB8O7Rey.js} +1 -1
  710. package/packages/web/dist/assets/{ganttDiagram-FUAMR5RP-1_lh-3ky.js → ganttDiagram-FUAMR5RP-BMoBwxn3.js} +1 -1
  711. package/packages/web/dist/assets/{gitGraphDiagram-X574FWY7-DoPXZuT5.js → gitGraphDiagram-X574FWY7-r9EVynuW.js} +1 -1
  712. package/packages/web/dist/assets/index-BJFGaq8t.js +646 -0
  713. package/packages/web/dist/assets/index-BMYKZrup.css +32 -0
  714. package/packages/web/dist/assets/{infoDiagram-VRGFBTTK-DQpRGGiD.js → infoDiagram-VRGFBTTK-4NICTzD4.js} +1 -1
  715. package/packages/web/dist/assets/{ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js → ishikawaDiagram-OU5B5YK6-qmYHkSam.js} +1 -1
  716. package/packages/web/dist/assets/{journeyDiagram-ZHPQQLJL-Bg-oeFjb.js → journeyDiagram-ZHPQQLJL-BSb6Qa2c.js} +1 -1
  717. package/packages/web/dist/assets/{kanban-definition-PNTS6WVX-BnpI4VH8.js → kanban-definition-PNTS6WVX-B0cwMsip.js} +1 -1
  718. package/packages/web/dist/assets/{mermaid.core-BwBKxlRA.js → mermaid.core-CTl4Qse1.js} +4 -4
  719. package/packages/web/dist/assets/{mindmap-definition-NLK3R4M7-NBnnxEoO.js → mindmap-definition-NLK3R4M7-tbJ4AKr2.js} +1 -1
  720. package/packages/web/dist/assets/{pegDiagram-GJSIUBJH-RrXXbIvO.js → pegDiagram-GJSIUBJH-BD50Xatx.js} +1 -1
  721. package/packages/web/dist/assets/{pieDiagram-5QR66LMP-B27q6Gso.js → pieDiagram-5QR66LMP-C52DU0dU.js} +1 -1
  722. package/packages/web/dist/assets/{quadrantDiagram-O4NWA36T-DGDsdur2.js → quadrantDiagram-O4NWA36T-Dmf0Relz.js} +1 -1
  723. package/packages/web/dist/assets/{railroadDiagram-XR7U4H2S-GdjkE3mI.js → railroadDiagram-XR7U4H2S-q1rW0LBx.js} +1 -1
  724. package/packages/web/dist/assets/{requirementDiagram-PLB6GJNP-DjK0GfgO.js → requirementDiagram-PLB6GJNP-ChTty00B.js} +1 -1
  725. package/packages/web/dist/assets/{sankeyDiagram-IPEJSGJF-BG_AIkwF.js → sankeyDiagram-IPEJSGJF-vRhUUtR0.js} +1 -1
  726. package/packages/web/dist/assets/scene-DUzELcJR.js +4620 -0
  727. package/packages/web/dist/assets/{sequenceDiagram-PO4LG4MO-CIQwUb4y.js → sequenceDiagram-PO4LG4MO-CJ37i6X7.js} +1 -1
  728. package/packages/web/dist/assets/{sizeCapture-INFHLROL-bpIoPxdJ.js → sizeCapture-INFHLROL-CUwB5IU5.js} +1 -1
  729. package/packages/web/dist/assets/{stateDiagram-v2-GCMORJYK-8hYXvPPv.js → stateDiagram-v2-GCMORJYK-CbmUCHZz.js} +1 -1
  730. package/packages/web/dist/assets/{swimlanes-2SLR337P-gfflUMF9.js → swimlanes-2SLR337P-BH1ix14-.js} +1 -1
  731. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-D1P54_6D.js +8 -0
  732. package/packages/web/dist/assets/{timeline-definition-EJHVYXUP-PHMNoGTZ.js → timeline-definition-EJHVYXUP-h73o8wo_.js} +1 -1
  733. package/packages/web/dist/assets/{usecaseDiagram-POWQR4AR-B2j5iteO.js → usecaseDiagram-POWQR4AR-BmrG9VWs.js} +1 -1
  734. package/packages/web/dist/assets/{vennDiagram-UO4OBE2U-BzxtZ-_2.js → vennDiagram-UO4OBE2U-Bax-03xB.js} +1 -1
  735. package/packages/web/dist/assets/{wardleyDiagram-VNRHLVJA-DL7YbMpY.js → wardleyDiagram-VNRHLVJA-A2y6258q.js} +1 -1
  736. package/packages/web/dist/assets/{xychartDiagram-PMCCYNJV-CisgP1cT.js → xychartDiagram-PMCCYNJV-BSiMaGgj.js} +1 -1
  737. package/packages/web/dist/index.html +2 -2
  738. package/packages/web/package.json +1 -1
  739. package/packages/web/dist/assets/channel-egZxcyUK.js +0 -1
  740. package/packages/web/dist/assets/index-Cw2Opmx7.js +0 -648
  741. package/packages/web/dist/assets/index-j0zBRCgT.css +0 -32
  742. package/packages/web/dist/assets/scene-D4LPicHk.js +0 -4620
  743. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +0 -8
@@ -5,37 +5,29 @@ import { ASSISTANT_MEMORY_OWNER } from './types.js';
5
5
  import { databasePath, loadConfig } from './config.js';
6
6
  import { createLogger, silentLogger } from './logger.js';
7
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
8
  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';
15
9
  import { Store } from './memory/store.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';
21
- import { extractMemories, smallModelFor } from './memory/extractor.js';
22
- import { admitCandidates, linkEntities } from './memory/gate.js';
10
+ import { linkEntities } from './memory/gate.js';
11
+ import { recall } from './memory/recall.js';
23
12
  import { SleepRunner } from './memory/sleep.js';
24
- import { buildSystemPrompt, deriveTitle } from './agents/persona.js';
25
13
  import { BridgeServer } from './org/bridge.js';
26
14
  import { OrgController, taskNotification } from './org/controller.js';
27
15
  import { QuestionRegistry } from './org/questions.js';
28
- import { assistantOrgBlock } from './org/prompts.js';
29
- import { dormantToolsHint, externalTurnExtras, toolServersFor } from './tools/hub.js';
30
- import { SkillStore, renderSkillsIndex } from './skills/store.js';
31
- import { renderExternalSkillsHint } from './skills/shelf.js';
32
- import { matchSkills, renderSkillMatches } from './skills/suggest.js';
16
+ import { SkillStore } from './skills/store.js';
33
17
  import { CronScheduler } from './cron/scheduler.js';
34
- import { describeCron } from './cron/parse.js';
35
- import { runCronScript } from './cron/script.js';
36
18
  import { EventQueue, titleFromBrief } from './util/queue.js';
37
- import { formatAge, formatNow } from './util/time.js';
38
- import { TurnBlocks } from './util/blocks.js';
19
+ import { BoardWatch } from './assistant/board-watch.js';
20
+ import { chatTurn } from './assistant/chat-turn.js';
21
+ import { DreamRecorder } from './assistant/dream-recorder.js';
22
+ import { journalledTurn } from './assistant/journalled-turn.js';
23
+ import { learnFromExchange } from './assistant/memory-learning.js';
24
+ import { promotionMessage } from './assistant/promotion-notice.js';
25
+ import { ScheduledRuns } from './assistant/scheduled-runs.js';
26
+ import { createSession, pinProject, resolveSession, sessionPermissionKey, SessionTurnQueue, } from './assistant/sessions.js';
27
+ import { ConversationTerminals, conversationTerminalKey } from './assistant/terminals.js';
28
+ import { storeTypedTurn } from './assistant/terminal-turn.js';
29
+ import { reportIfRejected } from './assistant/turn-support.js';
30
+ export { conversationTerminalKey } from './assistant/terminals.js';
39
31
  /**
40
32
  * The assistant runtime.
41
33
  *
@@ -58,138 +50,10 @@ import { TurnBlocks } from './util/blocks.js';
58
50
  * The assistant's own process always runs in the workspace. It never sees
59
51
  * the directory Rookery was started from; only agents work in project
60
52
  * directories, and only when the project names one.
61
- */
62
- /**
63
- * How many provider processes one turn may use. Two, because a turn that
64
- * attaches a tool server needs a second process to actually get it, and
65
- * because a third would let the assistant loop over its own switches.
66
- */
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
53
  *
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.';
104
- /** Add up what two passes of one turn cost; the last pass owns the context gauge. */
105
- function mergeUsage(base, next) {
106
- if (!base)
107
- return next;
108
- if (!next)
109
- return base;
110
- const sum = (a, b) => (a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0));
111
- return {
112
- inputTokens: sum(base.inputTokens, next.inputTokens),
113
- outputTokens: sum(base.outputTokens, next.outputTokens),
114
- cachedInputTokens: sum(base.cachedInputTokens, next.cachedInputTokens),
115
- reasoningTokens: sum(base.reasoningTokens, next.reasoningTokens),
116
- costUsd: sum(base.costUsd, next.costUsd),
117
- contextTokens: next.contextTokens ?? base.contextTokens,
118
- contextWindow: next.contextWindow ?? base.contextWindow,
119
- };
120
- }
121
- /**
122
- * What the second pass is asked. It is not the user talking, and it says so:
123
- * the assistant should pick the work back up, not answer this sentence.
124
- */
125
- function continuePrompt(servers) {
126
- return [
127
- '[Rookery] The tool servers you just switched on are attached now: ' + servers.join(', ') + '.',
128
- 'This message is from the system, not from your user, so do not address it and do not greet.',
129
- 'Carry on with what you stopped for, using the new tools, and finish the answer without',
130
- 'repeating what you already said.',
131
- ].join(' ');
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.
54
+ * The turn itself lives in `assistant/`: this class owns the collaborators,
55
+ * the public surface and the events it re-broadcasts.
167
56
  */
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
- }
193
57
  export class Assistant extends EventEmitter {
194
58
  config;
195
59
  store;
@@ -228,29 +92,13 @@ export class Assistant extends EventEmitter {
228
92
  notifyProbe;
229
93
  /** Takes over report-back turns so people can watch them; see `TurnRunner`. */
230
94
  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();
95
+ #sessionTurns = new SessionTurnQueue();
96
+ #boardWatch;
97
+ #recorder;
98
+ #terminals;
99
+ #turnServices;
100
+ #journalContext;
101
+ #scheduledRuns;
254
102
  constructor(options = {}) {
255
103
  super();
256
104
  this.config = loadConfig(options.config ?? {});
@@ -267,7 +115,7 @@ export class Assistant extends EventEmitter {
267
115
  this.skills = new SkillStore(this.config.skillsDir);
268
116
  this.cron = new CronScheduler({
269
117
  store: this.store,
270
- runner: (job, run, signal) => this.#runScheduled(job, run, signal),
118
+ runner: (job, _run, signal) => this.#scheduledRuns.run(job, signal),
271
119
  logger: this.log,
272
120
  timeoutMs: this.config.org.assignmentTimeoutMs,
273
121
  // A run's outcome goes the one road to the user. A closure, because
@@ -313,6 +161,53 @@ export class Assistant extends EventEmitter {
313
161
  // `notifyProbe` to the honest test.
314
162
  canNotify: () => (this.notifyProbe ? this.notifyProbe() : this.listenerCount('notify') > 0),
315
163
  });
164
+ this.#boardWatch = new BoardWatch({
165
+ store: this.store,
166
+ cron: this.cron,
167
+ org: this.org,
168
+ config: this.config,
169
+ log: this.log,
170
+ });
171
+ this.#recorder = new DreamRecorder({ store: this.store, config: this.config, log: this.log });
172
+ const collaborators = {
173
+ config: this.config,
174
+ store: this.store,
175
+ log: this.log,
176
+ providers: this.providers,
177
+ org: this.org,
178
+ skills: this.skills,
179
+ cron: this.cron,
180
+ questions: this.questions,
181
+ };
182
+ this.#terminals = new ConversationTerminals({
183
+ ...collaborators,
184
+ onTypedTurn: (sessionId, turn, openedWith) => storeTypedTurn(this.#turnServices, sessionId, turn, openedWith),
185
+ onChanged: (sessionId) => this.#announceSessionChanged(sessionId),
186
+ });
187
+ this.#turnServices = {
188
+ ...collaborators,
189
+ terminals: this.#terminals,
190
+ recorder: this.#recorder,
191
+ announceTool: (event) => {
192
+ this.emit('tool', event);
193
+ },
194
+ announceChanged: (sessionId) => this.#announceSessionChanged(sessionId),
195
+ learn: (sessionId, userText, assistantText, providerId) => this.#learn(sessionId, userText, assistantText, providerId),
196
+ };
197
+ this.#journalContext = { store: this.store, config: this.config, recorder: this.#recorder };
198
+ this.#scheduledRuns = new ScheduledRuns({
199
+ config: this.config,
200
+ store: this.store,
201
+ sleep: this.sleep,
202
+ boardWatch: this.#boardWatch,
203
+ chat: (input) => this.chat(input),
204
+ assign: (input) => this.assign(input),
205
+ createSession: (input) => this.createSession(input),
206
+ });
207
+ this.#relayEvents();
208
+ }
209
+ /** What every client hears about, from the clock, the night shift and the company. */
210
+ #relayEvents() {
316
211
  this.cron.on('cron', (event) => this.emit('cron', event));
317
212
  this.cron.on('message', (event) => this.emit('message', event));
318
213
  // Only a scheduler without the `notify` hook emits this itself; wired
@@ -337,7 +232,7 @@ export class Assistant extends EventEmitter {
337
232
  // The watcher's fast path (section 5): a task landing in `failed` or
338
233
  // `blocked` wakes it through the same event machinery a webhook or an
339
234
  // IMAP listener uses, no different from any other schedule.
340
- this.org.on('task', (event) => this.#onTaskEvent(event));
235
+ this.org.on('task', (event) => this.#boardWatch.onTaskEvent(event));
341
236
  this.org.on('changed', (change) => this.emit('changed', change));
342
237
  // The assistant reaching out on its own initiative - no HTTP, no
343
238
  // Telegram here, just an event a channel in another package can listen
@@ -347,6 +242,21 @@ export class Assistant extends EventEmitter {
347
242
  // handed it off hears about it as a turn of its own (R2/R3).
348
243
  this.org.on('report-back', (event) => this.#onReportBack(event));
349
244
  }
245
+ #announceSessionChanged(sessionId) {
246
+ this.emit('changed', { kind: 'session', id: sessionId });
247
+ }
248
+ close() {
249
+ // Anything still waiting on a person is settled first: an open question
250
+ // holds a promise inside a tool call, and shutting down around it would
251
+ // leave that call to time out long after there is anybody to answer.
252
+ this.questions.cancelAll();
253
+ this.cron.stop();
254
+ // No terminal or gateway outlives the runtime that owns it.
255
+ this.#terminals.shutdown();
256
+ reportIfRejected(this.org.bridge.close(), this.log, 'Closing the MCP bridge');
257
+ reportIfRejected(sharedCodexBridge.close(), this.log, 'Closing the Codex bridge');
258
+ this.store.close();
259
+ }
350
260
  /* --------------------------- report-back --------------------------- */
351
261
  #onReportBack(event) {
352
262
  const session = this.store.getSession(event.sessionId);
@@ -355,16 +265,7 @@ export class Assistant extends EventEmitter {
355
265
  // the only one left is the user: it goes to them as a notification
356
266
  // instead of a turn nobody would see - a question most of all.
357
267
  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
- });
268
+ this.#notifyReportBack(event, session);
368
269
  return;
369
270
  }
370
271
  // Archived while the work ran: bringing it back is better than burying
@@ -373,6 +274,18 @@ export class Assistant extends EventEmitter {
373
274
  this.store.updateSession(session.id, { archived: false });
374
275
  this.followUp({ sessionId: session.id, text: event.notice, taskId: event.taskId });
375
276
  }
277
+ #notifyReportBack(event, session) {
278
+ const task = this.store.org.getTask(event.taskId);
279
+ if (!task)
280
+ return;
281
+ const agent = task.assigneeId ? this.store.org.getAgent(task.assigneeId) : null;
282
+ const question = task.status === 'blocked' ? this.store.org.lastTaskEvent(task.id, 'question') : null;
283
+ this.org.notifyUser({
284
+ orgId: task.orgId,
285
+ ...taskNotification(task, agent, question?.text),
286
+ ...(session ? { sessionId: session.id } : {}),
287
+ });
288
+ }
376
289
  /**
377
290
  * A turn in a conversation that nobody typed: Rookery telling the
378
291
  * assistant something it has to pass on - today, how work it handed off
@@ -430,46 +343,9 @@ export class Assistant extends EventEmitter {
430
343
  this.emit('follow-up', done);
431
344
  }
432
345
  }
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
- };
448
- }
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();
454
- this.cron.stop();
455
- void this.org.bridge.close();
456
- void sharedCodexBridge.close();
457
- this.store.close();
458
- }
459
346
  /* ---------------------------- sessions ---------------------------- */
460
347
  createSession(input = {}) {
461
- const agent = input.agentId ? this.store.org.getAgent(input.agentId) : null;
462
- if (input.agentId && !agent)
463
- throw new Error('No agent ' + input.agentId + '.');
464
- return this.store.createSession({
465
- title: input.title,
466
- kind: input.kind,
467
- provider: input.provider ?? agent?.provider ?? this.config.defaultProvider,
468
- model: input.model ?? agent?.model ?? this.config.defaultModel,
469
- cwd: this.config.workspace,
470
- projectId: input.projectId,
471
- agentId: agent?.id,
472
- });
348
+ return createSession(this, input);
473
349
  }
474
350
  getSession(id) {
475
351
  return this.store.getSession(id);
@@ -483,6 +359,9 @@ export class Assistant extends EventEmitter {
483
359
  return this.store.listSessions({ limit, agentId, kind, includeArchived });
484
360
  }
485
361
  deleteSession(id) {
362
+ // Its terminal goes first: a process left running would go on writing a
363
+ // transcript into a conversation that no longer exists.
364
+ this.#terminals.closeNow(id);
486
365
  // A frame is a verbatim store of what was said in this session, so it
487
366
  // may never outlive the session it quotes (R17). Dropped before the
488
367
  // session row goes, the same safe direction the memory-retiring store
@@ -492,7 +371,8 @@ export class Assistant extends EventEmitter {
492
371
  }
493
372
  /** Forget the provider-side thread so the next turn starts cold. */
494
373
  resetSessionContext(id) {
495
- this.store.updateSession(id, { providerSessionId: undefined });
374
+ // `updateSession` leaves an undefined field alone, so clearing a column
375
+ // takes the statement itself.
496
376
  this.store.db
497
377
  .prepare('UPDATE sessions SET provider_session_id = NULL WHERE id = ?')
498
378
  .run(id);
@@ -533,6 +413,13 @@ export class Assistant extends EventEmitter {
533
413
  linkEntities(this.store, ASSISTANT_MEMORY_OWNER, record.id, input.tags ?? []);
534
414
  return record;
535
415
  }
416
+ /** Extract and store durable memories from a finished exchange, when learning is on. */
417
+ #learn(sessionId, userText, assistantText, providerId) {
418
+ const { memory } = this.config;
419
+ if (!memory.enabled || !memory.autoExtract)
420
+ return;
421
+ void learnFromExchange(this, { sessionId, userText, assistantText, providerId, owner: ASSISTANT_MEMORY_OWNER }, (event) => this.emit('memory', event));
422
+ }
536
423
  /* ------------------------------- sleep ---------------------------- */
537
424
  /** Run a night by hand, for one bank. The memory page's "sleep now". */
538
425
  async sleepNow(owner = ASSISTANT_MEMORY_OWNER, signal) {
@@ -583,808 +470,62 @@ export class Assistant extends EventEmitter {
583
470
  return null;
584
471
  }
585
472
  }
586
- /* ------------------------------- board watch ----------------------------- */
587
473
  /**
588
- * Make sure the board has a watcher. Called once when the clock starts.
474
+ * A retrieval policy went in force, so the user hears about it (S26,
475
+ * concept 9.6). This is the one place that can say so: the night owns the
476
+ * promotion and knows nothing about notifications, the controller owns them and
477
+ * knows nothing about the night, and the runtime holds both.
589
478
  *
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.
479
+ * A failing send costs the message, never the night: `#announcePromotion`
480
+ * in sleep.ts catches whatever comes back out of here, and this catches
481
+ * first so the warning names the notice rather than the hook.
597
482
  */
598
- ensureBoardWatchSchedule() {
483
+ async announcePromotion(notice) {
484
+ const { title, body } = promotionMessage(notice);
599
485
  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',
486
+ // A `sleep` notification, from Rookery itself. It used to be a mail
487
+ // from the user to the user, which no push filter ever let through -
488
+ // the promotion reached the web inbox and never the phone.
489
+ this.org.notifyUser({
490
+ orgId: this.org.activeOrganization().id,
491
+ kind: 'sleep',
492
+ title,
493
+ body,
494
+ fromKind: 'system',
625
495
  });
626
496
  }
627
497
  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');
498
+ this.log.warn('Could not post the promotion notice', {
499
+ owner: notice.owner,
500
+ slot: notice.slot,
501
+ policy: notice.version.id,
502
+ error: error.message,
503
+ });
692
504
  }
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
505
  }
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
- });
506
+ /* ------------------------------- board watch ----------------------------- */
507
+ /** Make sure the board has a watcher. Called once when the clock starts. */
508
+ ensureBoardWatchSchedule() {
509
+ return this.#boardWatch.ensureSchedule();
726
510
  }
727
511
  /* ------------------------------- chat ----------------------------- */
728
512
  /**
729
- * One conversational turn, streamed - and journalled while it runs.
513
+ * One conversational turn, streamed - and journalled while it runs (see
514
+ * `journalledTurn`).
730
515
  *
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.
516
+ * One conversation answers one message at a time: a turn in a known
517
+ * conversation waits for the one before it. A new conversation has nothing
518
+ * to wait for - nobody else can know its id yet.
740
519
  */
741
520
  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;
521
+ const release = input.sessionId ? await this.#sessionTurns.take(input.sessionId) : undefined;
745
522
  try {
746
- yield* this.#journalledChat(input);
523
+ yield* journalledTurn(this.#journalContext, input, (guarded, turnId, journal) => chatTurn(this.#turnServices, guarded, turnId, journal));
747
524
  }
748
525
  finally {
749
526
  release?.();
750
527
  }
751
528
  }
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) {
801
- const prompt = input.text.trim();
802
- if (!prompt) {
803
- yield { type: 'error', message: 'Nothing to send.', fatal: true };
804
- return;
805
- }
806
- const session = this.#resolveSession(input);
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;
813
- if (input.projectId && input.projectId !== session.projectId) {
814
- this.store.updateSession(session.id, { projectId: input.projectId });
815
- session.projectId = input.projectId;
816
- }
817
- const wanted = input.provider ?? session.provider;
818
- const providerId = await this.providers.resolveUsable(wanted);
819
- if (!providerId) {
820
- const statuses = await this.providers.statuses();
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(' | ');
826
- yield { type: 'error', message: 'No AI provider is ready. ' + detail, fatal: true };
827
- return;
828
- }
829
- if (providerId !== wanted) {
830
- yield { type: 'status', label: 'provider', detail: this.#switchReason(wanted, providerId) };
831
- }
832
- // Resuming the provider's own thread only works on the same provider.
833
- const resumed = Boolean(session.providerSessionId) && session.provider === providerId;
834
- const model = input.model ?? session.model ?? this.config.defaultModel;
835
- const effort = input.effort ?? this.config.defaultEffort;
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;
843
- if (this.config.memory.enabled) {
844
- yield { type: 'status', label: 'recalling', detail: 'searching memory' };
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);
851
- if (memories.length) {
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;
857
- }
858
- }
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.
864
- const organization = this.org.activeOrganization();
865
- const snapshot = this.org.snapshot(organization.id);
866
- const project = session.projectId ? (this.store.org.getProject(session.projectId) ?? undefined) : undefined;
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({
949
- config: this.config,
950
- query: prompt,
951
- memories,
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,
956
- // A voice session speaks whichever surface the turn came from.
957
- voice: input.voice ?? session.kind === 'voice',
958
- orgBlock: assistantOrgBlock(this.config, snapshot, project, this.cron.list(organization.id), this.store),
959
- toolHints,
960
- skillsIndex,
961
- // Lets the memory block group itself by entity.
962
- store: this.store,
963
- });
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;
1202
- }
1203
- return (await loadPty()) !== null;
1204
- }
1205
- async *#terminalTurn(turn) {
1206
- const { session, input } = turn;
1207
- const started = Date.now();
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');
1242
- const toolCalls = [];
1243
- const turnBlocks = new TurnBlocks();
1244
- if (turn.recall)
1245
- turnBlocks.apply(turn.recall);
1246
- let answer = '';
1247
- let failure;
1248
- let usage;
1249
- let answeredBy = terminal.model;
1250
- let prompt = turn.prompt;
1251
- let promptContext = context;
1252
- for (let pass = 1; pass <= MAX_PROVIDER_PASSES; pass += 1) {
1253
- yield {
1254
- type: 'session',
1255
- sessionId: session.id,
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());
1269
- try {
1270
- for await (const event of queue.drain()) {
1271
- if (event.type === 'tool') {
1272
- toolCalls.push(event);
1273
- turnBlocks.apply(event);
1274
- this.emit('tool', event);
1275
- }
1276
- else if (event.type === 'text' || event.type === 'thinking') {
1277
- turnBlocks.apply(event);
1278
- }
1279
- yield event;
1280
- }
1281
- }
1282
- finally {
1283
- terminal.context.emit = () => undefined;
1284
- terminal.context.signal = undefined;
1285
- }
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;
1295
- break;
1296
- }
1297
- if (result.interrupted || input.signal?.aborted || pass === MAX_PROVIDER_PASSES)
1298
- break;
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));
1304
- if (!fresh.length)
1305
- break;
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;
1321
- }
1322
- if (failure)
1323
- yield { type: 'error', message: failure, fatal: !answer };
1324
- turnBlocks.reconcile(answer);
1325
- const turnUsage = { ...usage, durationMs: Date.now() - started };
1326
- const answeredOn = this.#gatewayOwner(answeredBy, turn.providerId);
1327
- this.store.addMessage({
1328
- sessionId: session.id,
1329
- role: 'assistant',
1330
- content: answer,
1331
- turnId: turn.turnId,
1332
- provider: answeredOn,
1333
- ...(answeredBy ? { model: answeredBy } : {}),
1334
- usage: turnUsage,
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,
1342
- });
1343
- if (failure && !answer)
1344
- return;
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';
1385
- }
1386
- return wanted + ' is not logged in, using ' + chosen;
1387
- }
1388
529
  /* ------------------------------ assign ---------------------------- */
1389
530
  /**
1390
531
  * Give one agent a task directly, outside a conversation. Streams the
@@ -1431,9 +572,7 @@ export class Assistant extends EventEmitter {
1431
572
  scheduleId: input.scheduleId,
1432
573
  });
1433
574
  this.org.announceTask(card);
1434
- const queue = new EventQueue();
1435
- const run = this.org
1436
- .runTask({
575
+ const finished = yield* this.#streamRun({
1437
576
  orgId: organization.id,
1438
577
  audience: 'assistant',
1439
578
  depth: -1,
@@ -1444,13 +583,8 @@ export class Assistant extends EventEmitter {
1444
583
  // conversation that asked for it.
1445
584
  sessionId: input.sessionId,
1446
585
  scheduled: input.scheduled,
1447
- emit: (event) => queue.push(event),
1448
586
  signal: input.signal,
1449
- }, card)
1450
- .finally(() => queue.close());
1451
- for await (const event of queue.drain())
1452
- yield event;
1453
- const finished = await run;
587
+ }, card);
1454
588
  if (finished.status === 'done') {
1455
589
  yield { type: 'done', text: finished.result ?? '' };
1456
590
  }
@@ -1468,6 +602,29 @@ export class Assistant extends EventEmitter {
1468
602
  };
1469
603
  }
1470
604
  }
605
+ /**
606
+ * Runs a card and streams what the run emits - the provider's events and
607
+ * everything its tool calls cause in the company - then hands back the
608
+ * card as it ended.
609
+ */
610
+ async *#streamRun(context, card) {
611
+ const queue = new EventQueue();
612
+ const run = this.org
613
+ .runTask({ ...context, emit: (event) => queue.push(event) }, card)
614
+ .finally(() => queue.close());
615
+ let drained = false;
616
+ try {
617
+ for await (const event of queue.drain())
618
+ yield event;
619
+ drained = true;
620
+ }
621
+ finally {
622
+ // A consumer that walked away never awaits the run.
623
+ if (!drained)
624
+ reportIfRejected(run, this.log, 'Task run, after its stream ended,');
625
+ }
626
+ return await run;
627
+ }
1471
628
  /* ---------------------------- assignment log ---------------------------- */
1472
629
  /**
1473
630
  * The live log of a running assignment so far; an unknown or finished id
@@ -1510,20 +667,13 @@ export class Assistant extends EventEmitter {
1510
667
  yield { type: 'error', message: 'No task ' + input.taskId + '.', fatal: true };
1511
668
  return;
1512
669
  }
1513
- const queue = new EventQueue();
1514
- const run = this.org
1515
- .runTask({
670
+ const finished = yield* this.#streamRun({
1516
671
  orgId: organization.id,
1517
672
  audience: 'assistant',
1518
673
  depth: -1,
1519
674
  projectId: task.projectId,
1520
- emit: (event) => queue.push(event),
1521
675
  signal: input.signal,
1522
- }, task)
1523
- .finally(() => queue.close());
1524
- for await (const event of queue.drain())
1525
- yield event;
1526
- const finished = await run;
676
+ }, task);
1527
677
  if (finished.status === 'done') {
1528
678
  yield { type: 'done', text: finished.result ?? '' };
1529
679
  }
@@ -1535,381 +685,6 @@ export class Assistant extends EventEmitter {
1535
685
  };
1536
686
  }
1537
687
  }
1538
- /* ----------------------------- schedules -------------------------- */
1539
- /**
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.
1545
- */
1546
- async #runScheduled(job, run, signal) {
1547
- void run;
1548
- if (job.kind === 'script') {
1549
- const result = await runCronScript(this.config.home, job, signal);
1550
- if (result.silent)
1551
- return { status: 'done', result: '', silent: true };
1552
- if (job.script?.noAgent)
1553
- return { status: 'done', result: result.output };
1554
- job = { ...job, prompt: job.prompt + '\n\nThe imported pre-check script produced this data:\n' + result.output };
1555
- }
1556
- if (job.kind === 'sleep') {
1557
- // The night shift. `prompt` carries the scope, not an instruction:
1558
- // "assistant", "all", or one agent id.
1559
- const scope = job.prompt.trim() || 'assistant';
1560
- const owners = scope === 'all' ? this.sleep.dueOwners() : scope === 'assistant' ? [ASSISTANT_MEMORY_OWNER] : [scope];
1561
- const lines = [];
1562
- let failed;
1563
- for (const owner of owners) {
1564
- const result = await this.sleep.run({ owner, trigger: 'schedule', signal });
1565
- lines.push(labelForOwner(this, owner) + ': ' + (result.report ?? '-'));
1566
- if (result.status === 'failed')
1567
- failed = result.error ?? 'The sleep run failed.';
1568
- }
1569
- if (failed && lines.length <= 1)
1570
- return { status: 'failed', error: failed };
1571
- return { status: 'done', result: lines.join('\n') };
1572
- }
1573
- if (job.kind === 'agent') {
1574
- const agent = job.agentId ? this.store.org.getAgent(job.agentId) : null;
1575
- if (!agent || agent.archived)
1576
- return { status: 'failed', error: 'The agent for this schedule no longer exists.' };
1577
- let assignmentId;
1578
- let text = '';
1579
- let error;
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
- })) {
1593
- if (event.type === 'assignment' && !assignmentId)
1594
- assignmentId = event.assignment.id;
1595
- else if (event.type === 'done')
1596
- text = event.text;
1597
- else if (event.type === 'error' && event.fatal)
1598
- error = event.message;
1599
- }
1600
- return error ? { status: 'failed', error, assignmentId } : { status: 'done', result: text, assignmentId };
1601
- }
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;
1624
- }
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 + '. ' +
1629
- 'Nobody is following live: carry out the assignment now and finish with a short report ' +
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
- : '');
1641
- let text = '';
1642
- let error;
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
- })) {
1656
- if (event.type === 'done')
1657
- text = event.text;
1658
- else if (event.type === 'error' && event.fatal)
1659
- error = event.message;
1660
- }
1661
- if (error && !text)
1662
- return { status: 'failed', error, sessionId };
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))
1671
- return { status: 'done', result: '', silent: true, sessionId };
1672
- return { status: 'done', result: text, sessionId };
1673
- }
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
688
  /* ------------------------- conversation terminal ------------------------ */
1914
689
  /**
1915
690
  * The terminal view of a conversation: the same Claude Code process every
@@ -1919,317 +694,25 @@ export class Assistant extends EventEmitter {
1919
694
  * person types into it lands in the conversation like any other message.
1920
695
  */
1921
696
  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
- }
697
+ const session = resolveSession(this, input);
698
+ const opened = { sessionId: session.id, key: conversationTerminalKey(session.id) };
699
+ if (this.#terminals.running(session.id)?.handle.alive())
700
+ return opened;
701
+ pinProject(this.store, session, input.projectId);
1937
702
  const providerId = await this.providers.resolveUsable(input.provider ?? session.provider);
1938
703
  if (!providerId)
1939
704
  throw new Error('No AI provider is ready.');
1940
- await this.#chatTerminal(session, {
705
+ await this.#terminals.ensure(session, {
1941
706
  providerId,
1942
707
  model: input.model ?? session.model ?? this.config.defaultModel,
1943
708
  effort: input.effort ?? this.config.defaultEffort,
1944
709
  permission: input.permission ?? this.config.defaultPermission,
1945
710
  });
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;
711
+ return opened;
2094
712
  }
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
713
  /** Ends the conversation's terminal. False when it had none. */
2143
714
  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
- }
2149
- #resolveSession(input) {
2150
- if (input.sessionId) {
2151
- const existing = this.store.getSession(input.sessionId);
2152
- if (existing)
2153
- return existing;
2154
- this.log.warn('Unknown session, starting a new one', { sessionId: input.sessionId });
2155
- }
2156
- return this.createSession({
2157
- // A spoken first turn opens a voice session, so the hands-free screen
2158
- // never has to create one by hand.
2159
- kind: input.voice ? 'voice' : 'chat',
2160
- provider: input.provider,
2161
- model: input.model,
2162
- projectId: input.projectId,
2163
- agentId: input.agentId,
2164
- });
2165
- }
2166
- /** Extract and store durable memories from a finished exchange. */
2167
- async #learn(sessionId, userText, assistantText, providerId, owner) {
2168
- try {
2169
- // What the model must not repeat is what is RELEVANT here, not what
2170
- // happens to rank highest overall. Listing the forty most important
2171
- // memories was the single biggest reason the bank kept growing: the
2172
- // sentence about to be written again was almost never in that list.
2173
- const known = relevantKnown(this.store, owner, userText + '\n' + assistantText);
2174
- const candidates = await extractMemories(this.providers.get(providerId), {
2175
- userText,
2176
- assistantText,
2177
- known,
2178
- sessionId,
2179
- model: smallModelFor(providerId),
2180
- });
2181
- const admitted = admitCandidates(this.store, {
2182
- candidates,
2183
- owner,
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],
2190
- sourceSessionId: sessionId,
2191
- });
2192
- if (admitted.rejected.length) {
2193
- this.log.debug('Memory gate rejected candidates', {
2194
- count: admitted.rejected.length,
2195
- reasons: admitted.rejected.map((entry) => entry.reason).join(','),
2196
- });
2197
- }
2198
- const event = { sessionId, stored: admitted.stored };
2199
- this.emit('memory', event);
2200
- }
2201
- catch (error) {
2202
- this.log.warn('Memory extraction failed', { error: error.message });
2203
- }
2204
- }
2205
- }
2206
- /** "The assistant" or the agent's name, for the schedule's report line. */
2207
- function labelForOwner(assistant, owner) {
2208
- if (owner === ASSISTANT_MEMORY_OWNER)
2209
- return 'Assistant';
2210
- return assistant.store.org.getAgent(owner)?.name ?? owner.slice(0, 8);
2211
- }
2212
- /**
2213
- * The memories the extractor needs to see so it does not write them again:
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.
2221
- */
2222
- function relevantKnown(store, owner, text) {
2223
- const matched = recall(store, { text, owner, limit: 20, threshold: 0.05, touch: false, expand: false });
2224
- const profile = coreProfile(store, { owner, limit: 5 });
2225
- const seen = new Set();
2226
- const out = [];
2227
- for (const memory of [...matched, ...profile]) {
2228
- if (seen.has(memory.id))
2229
- continue;
2230
- seen.add(memory.id);
2231
- out.push(memory.content);
715
+ return this.#terminals.closeNow(sessionId);
2232
716
  }
2233
- return out;
2234
717
  }
2235
718
  //# sourceMappingURL=runtime.js.map