rookery-agent 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (670) hide show
  1. package/README.md +467 -367
  2. package/docs/migration.md +88 -88
  3. package/docs/updates.md +112 -0
  4. package/package.json +13 -3
  5. package/packages/cli/dist/commands/config.js +2 -2
  6. package/packages/cli/dist/commands/doctor.d.ts.map +1 -1
  7. package/packages/cli/dist/commands/doctor.js +13 -9
  8. package/packages/cli/dist/commands/doctor.js.map +1 -1
  9. package/packages/cli/dist/commands/memory.js +1 -1
  10. package/packages/cli/dist/commands/org.d.ts +2 -2
  11. package/packages/cli/dist/commands/org.d.ts.map +1 -1
  12. package/packages/cli/dist/commands/org.js +19 -17
  13. package/packages/cli/dist/commands/org.js.map +1 -1
  14. package/packages/cli/dist/commands/serve.js +1 -1
  15. package/packages/cli/dist/commands/serve.js.map +1 -1
  16. package/packages/cli/dist/commands/shared.d.ts.map +1 -1
  17. package/packages/cli/dist/commands/shared.js +2 -1
  18. package/packages/cli/dist/commands/shared.js.map +1 -1
  19. package/packages/cli/dist/commands/tasks.d.ts.map +1 -1
  20. package/packages/cli/dist/commands/tasks.js +25 -11
  21. package/packages/cli/dist/commands/tasks.js.map +1 -1
  22. package/packages/cli/dist/commands/tools.js +1 -1
  23. package/packages/cli/dist/commands/tools.js.map +1 -1
  24. package/packages/cli/dist/index.js +13 -13
  25. package/packages/cli/dist/index.js.map +1 -1
  26. package/packages/cli/dist/repl.d.ts +12 -0
  27. package/packages/cli/dist/repl.d.ts.map +1 -1
  28. package/packages/cli/dist/repl.js +170 -16
  29. package/packages/cli/dist/repl.js.map +1 -1
  30. package/packages/cli/dist/tui/App.d.ts +7 -3
  31. package/packages/cli/dist/tui/App.d.ts.map +1 -1
  32. package/packages/cli/dist/tui/App.js +182 -16
  33. package/packages/cli/dist/tui/App.js.map +1 -1
  34. package/packages/cli/dist/tui/commands.d.ts +7 -0
  35. package/packages/cli/dist/tui/commands.d.ts.map +1 -1
  36. package/packages/cli/dist/tui/commands.js +70 -8
  37. package/packages/cli/dist/tui/commands.js.map +1 -1
  38. package/packages/cli/dist/tui/components/AssignmentsView.js +4 -4
  39. package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -1
  40. package/packages/cli/dist/tui/components/Banner.d.ts +11 -2
  41. package/packages/cli/dist/tui/components/Banner.d.ts.map +1 -1
  42. package/packages/cli/dist/tui/components/Banner.js +7 -10
  43. package/packages/cli/dist/tui/components/Banner.js.map +1 -1
  44. package/packages/cli/dist/tui/components/CodeBlock.js +2 -2
  45. package/packages/cli/dist/tui/components/CodeBlock.js.map +1 -1
  46. package/packages/cli/dist/tui/components/InputBox.d.ts.map +1 -1
  47. package/packages/cli/dist/tui/components/InputBox.js +4 -4
  48. package/packages/cli/dist/tui/components/InputBox.js.map +1 -1
  49. package/packages/cli/dist/tui/components/Logo.d.ts +56 -0
  50. package/packages/cli/dist/tui/components/Logo.d.ts.map +1 -0
  51. package/packages/cli/dist/tui/components/Logo.js +50 -0
  52. package/packages/cli/dist/tui/components/Logo.js.map +1 -0
  53. package/packages/cli/dist/tui/components/Markdown.js +8 -8
  54. package/packages/cli/dist/tui/components/Markdown.js.map +1 -1
  55. package/packages/cli/dist/tui/components/Message.d.ts +1 -1
  56. package/packages/cli/dist/tui/components/Message.d.ts.map +1 -1
  57. package/packages/cli/dist/tui/components/Message.js +5 -4
  58. package/packages/cli/dist/tui/components/Message.js.map +1 -1
  59. package/packages/cli/dist/tui/components/QuestionView.d.ts +29 -0
  60. package/packages/cli/dist/tui/components/QuestionView.d.ts.map +1 -0
  61. package/packages/cli/dist/tui/components/QuestionView.js +53 -0
  62. package/packages/cli/dist/tui/components/QuestionView.js.map +1 -0
  63. package/packages/cli/dist/tui/components/SlashPalette.d.ts +5 -2
  64. package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -1
  65. package/packages/cli/dist/tui/components/SlashPalette.js +2 -2
  66. package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -1
  67. package/packages/cli/dist/tui/components/StatusLine.d.ts +0 -2
  68. package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -1
  69. package/packages/cli/dist/tui/components/StatusLine.js +8 -5
  70. package/packages/cli/dist/tui/components/StatusLine.js.map +1 -1
  71. package/packages/cli/dist/tui/components/ToolGroup.js +2 -2
  72. package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -1
  73. package/packages/cli/dist/tui/components/WatchView.d.ts +21 -0
  74. package/packages/cli/dist/tui/components/WatchView.d.ts.map +1 -0
  75. package/packages/cli/dist/tui/components/WatchView.js +36 -0
  76. package/packages/cli/dist/tui/components/WatchView.js.map +1 -0
  77. package/packages/cli/dist/tui/history.d.ts +20 -0
  78. package/packages/cli/dist/tui/history.d.ts.map +1 -0
  79. package/packages/cli/dist/tui/history.js +105 -0
  80. package/packages/cli/dist/tui/history.js.map +1 -0
  81. package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -1
  82. package/packages/cli/dist/tui/hooks/useSlash.js +3 -2
  83. package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -1
  84. package/packages/cli/dist/tui/hooks/useTurn.d.ts +58 -1
  85. package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -1
  86. package/packages/cli/dist/tui/hooks/useTurn.js +214 -36
  87. package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -1
  88. package/packages/cli/dist/tui/hooks/useWatch.d.ts +52 -0
  89. package/packages/cli/dist/tui/hooks/useWatch.d.ts.map +1 -0
  90. package/packages/cli/dist/tui/hooks/useWatch.js +145 -0
  91. package/packages/cli/dist/tui/hooks/useWatch.js.map +1 -0
  92. package/packages/cli/dist/tui/inkTheme.d.ts +19 -0
  93. package/packages/cli/dist/tui/inkTheme.d.ts.map +1 -0
  94. package/packages/cli/dist/tui/inkTheme.js +81 -0
  95. package/packages/cli/dist/tui/inkTheme.js.map +1 -0
  96. package/packages/cli/dist/tui/theme.d.ts +39 -29
  97. package/packages/cli/dist/tui/theme.d.ts.map +1 -1
  98. package/packages/cli/dist/tui/theme.js +35 -25
  99. package/packages/cli/dist/tui/theme.js.map +1 -1
  100. package/packages/cli/dist/tui/types.d.ts +56 -3
  101. package/packages/cli/dist/tui/types.d.ts.map +1 -1
  102. package/packages/cli/dist/tui/types.js +85 -0
  103. package/packages/cli/dist/tui/types.js.map +1 -1
  104. package/packages/cli/dist/ui/modelNames.d.ts +51 -0
  105. package/packages/cli/dist/ui/modelNames.d.ts.map +1 -0
  106. package/packages/cli/dist/ui/modelNames.js +134 -0
  107. package/packages/cli/dist/ui/modelNames.js.map +1 -0
  108. package/packages/cli/dist/ui/render.d.ts.map +1 -1
  109. package/packages/cli/dist/ui/render.js +17 -8
  110. package/packages/cli/dist/ui/render.js.map +1 -1
  111. package/packages/cli/dist/ui/speech.js +5 -0
  112. package/packages/cli/dist/ui/speech.js.map +1 -1
  113. package/packages/cli/dist/ui/theme.d.ts +33 -9
  114. package/packages/cli/dist/ui/theme.d.ts.map +1 -1
  115. package/packages/cli/dist/ui/theme.js +33 -9
  116. package/packages/cli/dist/ui/theme.js.map +1 -1
  117. package/packages/cli/package.json +1 -1
  118. package/packages/core/dist/agents/persona.d.ts.map +1 -1
  119. package/packages/core/dist/agents/persona.js +5 -2
  120. package/packages/core/dist/agents/persona.js.map +1 -1
  121. package/packages/core/dist/computer/accessibility.d.ts +78 -0
  122. package/packages/core/dist/computer/accessibility.d.ts.map +1 -0
  123. package/packages/core/dist/computer/accessibility.js +270 -0
  124. package/packages/core/dist/computer/accessibility.js.map +1 -0
  125. package/packages/core/dist/computer/assemblies.d.ts +17 -0
  126. package/packages/core/dist/computer/assemblies.d.ts.map +1 -0
  127. package/packages/core/dist/computer/assemblies.js +55 -0
  128. package/packages/core/dist/computer/assemblies.js.map +1 -0
  129. package/packages/core/dist/computer/browser-init.d.ts +9 -0
  130. package/packages/core/dist/computer/browser-init.d.ts.map +1 -0
  131. package/packages/core/dist/computer/browser-init.js +133 -0
  132. package/packages/core/dist/computer/browser-init.js.map +1 -0
  133. package/packages/core/dist/computer/cursor.d.ts +30 -0
  134. package/packages/core/dist/computer/cursor.d.ts.map +1 -0
  135. package/packages/core/dist/computer/cursor.js +30 -0
  136. package/packages/core/dist/computer/cursor.js.map +1 -0
  137. package/packages/core/dist/computer/mcp-server.js +524 -82
  138. package/packages/core/dist/computer/mcp-server.js.map +1 -1
  139. package/packages/core/dist/computer/powershell.d.ts +4 -0
  140. package/packages/core/dist/computer/powershell.d.ts.map +1 -1
  141. package/packages/core/dist/computer/powershell.js +471 -81
  142. package/packages/core/dist/computer/powershell.js.map +1 -1
  143. package/packages/core/dist/computer/screen-text.d.ts +82 -0
  144. package/packages/core/dist/computer/screen-text.d.ts.map +1 -0
  145. package/packages/core/dist/computer/screen-text.js +243 -0
  146. package/packages/core/dist/computer/screen-text.js.map +1 -0
  147. package/packages/core/dist/computer/sketch.d.ts +66 -0
  148. package/packages/core/dist/computer/sketch.d.ts.map +1 -0
  149. package/packages/core/dist/computer/sketch.js +540 -0
  150. package/packages/core/dist/computer/sketch.js.map +1 -0
  151. package/packages/core/dist/computer/tools.d.ts +8 -8
  152. package/packages/core/dist/computer/tools.d.ts.map +1 -1
  153. package/packages/core/dist/computer/tools.js +186 -31
  154. package/packages/core/dist/computer/tools.js.map +1 -1
  155. package/packages/core/dist/computer/validation.d.ts +555 -0
  156. package/packages/core/dist/computer/validation.d.ts.map +1 -0
  157. package/packages/core/dist/computer/validation.js +111 -0
  158. package/packages/core/dist/computer/validation.js.map +1 -0
  159. package/packages/core/dist/computer/windows-cursor.d.ts +14 -0
  160. package/packages/core/dist/computer/windows-cursor.d.ts.map +1 -0
  161. package/packages/core/dist/computer/windows-cursor.js +713 -0
  162. package/packages/core/dist/computer/windows-cursor.js.map +1 -0
  163. package/packages/core/dist/config.d.ts +34 -1
  164. package/packages/core/dist/config.d.ts.map +1 -1
  165. package/packages/core/dist/config.js +362 -11
  166. package/packages/core/dist/config.js.map +1 -1
  167. package/packages/core/dist/cron/scheduler.d.ts +59 -6
  168. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  169. package/packages/core/dist/cron/scheduler.js +295 -27
  170. package/packages/core/dist/cron/scheduler.js.map +1 -1
  171. package/packages/core/dist/cron/store.d.ts +19 -1
  172. package/packages/core/dist/cron/store.d.ts.map +1 -1
  173. package/packages/core/dist/cron/store.js +36 -8
  174. package/packages/core/dist/cron/store.js.map +1 -1
  175. package/packages/core/dist/external/claude-code.d.ts +4 -0
  176. package/packages/core/dist/external/claude-code.d.ts.map +1 -0
  177. package/packages/core/dist/external/claude-code.js +111 -0
  178. package/packages/core/dist/external/claude-code.js.map +1 -0
  179. package/packages/core/dist/external/discovery.d.ts +33 -0
  180. package/packages/core/dist/external/discovery.d.ts.map +1 -0
  181. package/packages/core/dist/external/discovery.js +144 -0
  182. package/packages/core/dist/external/discovery.js.map +1 -0
  183. package/packages/core/dist/external/homes.d.ts +26 -0
  184. package/packages/core/dist/external/homes.d.ts.map +1 -0
  185. package/packages/core/dist/external/homes.js +49 -0
  186. package/packages/core/dist/external/homes.js.map +1 -0
  187. package/packages/core/dist/external/shared.d.ts +201 -0
  188. package/packages/core/dist/external/shared.d.ts.map +1 -0
  189. package/packages/core/dist/external/shared.js +308 -0
  190. package/packages/core/dist/external/shared.js.map +1 -0
  191. package/packages/core/dist/gateway/policy.d.ts +117 -2
  192. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  193. package/packages/core/dist/gateway/policy.js +286 -6
  194. package/packages/core/dist/gateway/policy.js.map +1 -1
  195. package/packages/core/dist/index.d.ts +38 -12
  196. package/packages/core/dist/index.d.ts.map +1 -1
  197. package/packages/core/dist/index.js +66 -12
  198. package/packages/core/dist/index.js.map +1 -1
  199. package/packages/core/dist/memory/db.d.ts +1 -1
  200. package/packages/core/dist/memory/db.d.ts.map +1 -1
  201. package/packages/core/dist/memory/db.js +878 -1
  202. package/packages/core/dist/memory/db.js.map +1 -1
  203. package/packages/core/dist/memory/dream/admission.d.ts +124 -0
  204. package/packages/core/dist/memory/dream/admission.d.ts.map +1 -0
  205. package/packages/core/dist/memory/dream/admission.js +116 -0
  206. package/packages/core/dist/memory/dream/admission.js.map +1 -0
  207. package/packages/core/dist/memory/dream/candidate.d.ts +152 -0
  208. package/packages/core/dist/memory/dream/candidate.d.ts.map +1 -0
  209. package/packages/core/dist/memory/dream/candidate.js +547 -0
  210. package/packages/core/dist/memory/dream/candidate.js.map +1 -0
  211. package/packages/core/dist/memory/dream/evaluate.d.ts +394 -0
  212. package/packages/core/dist/memory/dream/evaluate.d.ts.map +1 -0
  213. package/packages/core/dist/memory/dream/evaluate.js +1032 -0
  214. package/packages/core/dist/memory/dream/evaluate.js.map +1 -0
  215. package/packages/core/dist/memory/dream/frame.d.ts +61 -0
  216. package/packages/core/dist/memory/dream/frame.d.ts.map +1 -0
  217. package/packages/core/dist/memory/dream/frame.js +292 -0
  218. package/packages/core/dist/memory/dream/frame.js.map +1 -0
  219. package/packages/core/dist/memory/dream/label.d.ts +370 -0
  220. package/packages/core/dist/memory/dream/label.d.ts.map +1 -0
  221. package/packages/core/dist/memory/dream/label.js +439 -0
  222. package/packages/core/dist/memory/dream/label.js.map +1 -0
  223. package/packages/core/dist/memory/dream/measure.d.ts +114 -0
  224. package/packages/core/dist/memory/dream/measure.d.ts.map +1 -0
  225. package/packages/core/dist/memory/dream/measure.js +205 -0
  226. package/packages/core/dist/memory/dream/measure.js.map +1 -0
  227. package/packages/core/dist/memory/dream/policy.d.ts +21 -0
  228. package/packages/core/dist/memory/dream/policy.d.ts.map +1 -0
  229. package/packages/core/dist/memory/dream/policy.js +157 -0
  230. package/packages/core/dist/memory/dream/policy.js.map +1 -0
  231. package/packages/core/dist/memory/dream/probe.d.ts +202 -0
  232. package/packages/core/dist/memory/dream/probe.d.ts.map +1 -0
  233. package/packages/core/dist/memory/dream/probe.js +671 -0
  234. package/packages/core/dist/memory/dream/probe.js.map +1 -0
  235. package/packages/core/dist/memory/dream/promote.d.ts +312 -0
  236. package/packages/core/dist/memory/dream/promote.d.ts.map +1 -0
  237. package/packages/core/dist/memory/dream/promote.js +528 -0
  238. package/packages/core/dist/memory/dream/promote.js.map +1 -0
  239. package/packages/core/dist/memory/dream/score.d.ts +103 -0
  240. package/packages/core/dist/memory/dream/score.d.ts.map +1 -0
  241. package/packages/core/dist/memory/dream/score.js +334 -0
  242. package/packages/core/dist/memory/dream/score.js.map +1 -0
  243. package/packages/core/dist/memory/dream/slots.d.ts +193 -0
  244. package/packages/core/dist/memory/dream/slots.d.ts.map +1 -0
  245. package/packages/core/dist/memory/dream/slots.js +0 -0
  246. package/packages/core/dist/memory/dream/slots.js.map +1 -0
  247. package/packages/core/dist/memory/dream/trajectory.d.ts +262 -0
  248. package/packages/core/dist/memory/dream/trajectory.d.ts.map +1 -0
  249. package/packages/core/dist/memory/dream/trajectory.js +366 -0
  250. package/packages/core/dist/memory/dream/trajectory.js.map +1 -0
  251. package/packages/core/dist/memory/extractor.d.ts +7 -0
  252. package/packages/core/dist/memory/extractor.d.ts.map +1 -1
  253. package/packages/core/dist/memory/extractor.js +35 -12
  254. package/packages/core/dist/memory/extractor.js.map +1 -1
  255. package/packages/core/dist/memory/gate.d.ts +43 -7
  256. package/packages/core/dist/memory/gate.d.ts.map +1 -1
  257. package/packages/core/dist/memory/gate.js +91 -4
  258. package/packages/core/dist/memory/gate.js.map +1 -1
  259. package/packages/core/dist/memory/recall.d.ts +57 -0
  260. package/packages/core/dist/memory/recall.d.ts.map +1 -1
  261. package/packages/core/dist/memory/recall.js +60 -123
  262. package/packages/core/dist/memory/recall.js.map +1 -1
  263. package/packages/core/dist/memory/sleep.d.ts +131 -4
  264. package/packages/core/dist/memory/sleep.d.ts.map +1 -1
  265. package/packages/core/dist/memory/sleep.js +2384 -65
  266. package/packages/core/dist/memory/sleep.js.map +1 -1
  267. package/packages/core/dist/memory/store.d.ts +564 -10
  268. package/packages/core/dist/memory/store.d.ts.map +1 -1
  269. package/packages/core/dist/memory/store.js +1673 -102
  270. package/packages/core/dist/memory/store.js.map +1 -1
  271. package/packages/core/dist/org/controller.d.ts +268 -4
  272. package/packages/core/dist/org/controller.d.ts.map +1 -1
  273. package/packages/core/dist/org/controller.js +2298 -248
  274. package/packages/core/dist/org/controller.js.map +1 -1
  275. package/packages/core/dist/org/ponytail.d.ts +1 -1
  276. package/packages/core/dist/org/ponytail.js +1 -1
  277. package/packages/core/dist/org/project-mcp.d.ts +3 -3
  278. package/packages/core/dist/org/prompts.d.ts +44 -30
  279. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  280. package/packages/core/dist/org/prompts.js +209 -92
  281. package/packages/core/dist/org/prompts.js.map +1 -1
  282. package/packages/core/dist/org/questions.d.ts +104 -0
  283. package/packages/core/dist/org/questions.d.ts.map +1 -0
  284. package/packages/core/dist/org/questions.js +136 -0
  285. package/packages/core/dist/org/questions.js.map +1 -0
  286. package/packages/core/dist/org/review.d.ts +100 -0
  287. package/packages/core/dist/org/review.d.ts.map +1 -0
  288. package/packages/core/dist/org/review.js +256 -0
  289. package/packages/core/dist/org/review.js.map +1 -0
  290. package/packages/core/dist/org/store.d.ts +311 -2
  291. package/packages/core/dist/org/store.d.ts.map +1 -1
  292. package/packages/core/dist/org/store.js +981 -13
  293. package/packages/core/dist/org/store.js.map +1 -1
  294. package/packages/core/dist/org/tools.d.ts +33 -3
  295. package/packages/core/dist/org/tools.d.ts.map +1 -1
  296. package/packages/core/dist/org/tools.js +380 -67
  297. package/packages/core/dist/org/tools.js.map +1 -1
  298. package/packages/core/dist/providers/catalogue.d.ts +1 -1
  299. package/packages/core/dist/providers/catalogue.d.ts.map +1 -1
  300. package/packages/core/dist/providers/catalogue.js +2 -2
  301. package/packages/core/dist/providers/catalogue.js.map +1 -1
  302. package/packages/core/dist/providers/claude-code.d.ts +19 -3
  303. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  304. package/packages/core/dist/providers/claude-code.js +501 -40
  305. package/packages/core/dist/providers/claude-code.js.map +1 -1
  306. package/packages/core/dist/providers/claude-tui.d.ts +288 -0
  307. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -0
  308. package/packages/core/dist/providers/claude-tui.js +1118 -0
  309. package/packages/core/dist/providers/claude-tui.js.map +1 -0
  310. package/packages/core/dist/providers/codex-auth.d.ts +15 -0
  311. package/packages/core/dist/providers/codex-auth.d.ts.map +1 -0
  312. package/packages/core/dist/providers/codex-auth.js +127 -0
  313. package/packages/core/dist/providers/codex-auth.js.map +1 -0
  314. package/packages/core/dist/providers/codex-bridge.d.ts +58 -0
  315. package/packages/core/dist/providers/codex-bridge.d.ts.map +1 -0
  316. package/packages/core/dist/providers/codex-bridge.js +375 -0
  317. package/packages/core/dist/providers/codex-bridge.js.map +1 -0
  318. package/packages/core/dist/providers/codex-translate.d.ts +75 -0
  319. package/packages/core/dist/providers/codex-translate.d.ts.map +1 -0
  320. package/packages/core/dist/providers/codex-translate.js +383 -0
  321. package/packages/core/dist/providers/codex-translate.js.map +1 -0
  322. package/packages/core/dist/providers/model-gateway.d.ts +56 -0
  323. package/packages/core/dist/providers/model-gateway.d.ts.map +1 -0
  324. package/packages/core/dist/providers/model-gateway.js +119 -0
  325. package/packages/core/dist/providers/model-gateway.js.map +1 -0
  326. package/packages/core/dist/providers/process.d.ts +3 -1
  327. package/packages/core/dist/providers/process.d.ts.map +1 -1
  328. package/packages/core/dist/providers/process.js +3 -3
  329. package/packages/core/dist/providers/process.js.map +1 -1
  330. package/packages/core/dist/providers/profiles.d.ts +11 -0
  331. package/packages/core/dist/providers/profiles.d.ts.map +1 -0
  332. package/packages/core/dist/providers/profiles.js +28 -0
  333. package/packages/core/dist/providers/profiles.js.map +1 -0
  334. package/packages/core/dist/providers/provider-catalog.d.ts +72 -0
  335. package/packages/core/dist/providers/provider-catalog.d.ts.map +1 -0
  336. package/packages/core/dist/providers/provider-catalog.js +144 -0
  337. package/packages/core/dist/providers/provider-catalog.js.map +1 -0
  338. package/packages/core/dist/providers/quota.d.ts +40 -1
  339. package/packages/core/dist/providers/quota.d.ts.map +1 -1
  340. package/packages/core/dist/providers/quota.js +288 -25
  341. package/packages/core/dist/providers/quota.js.map +1 -1
  342. package/packages/core/dist/providers/registry.d.ts +46 -3
  343. package/packages/core/dist/providers/registry.d.ts.map +1 -1
  344. package/packages/core/dist/providers/registry.js +148 -13
  345. package/packages/core/dist/providers/registry.js.map +1 -1
  346. package/packages/core/dist/providers/router.d.ts +28 -0
  347. package/packages/core/dist/providers/router.d.ts.map +1 -0
  348. package/packages/core/dist/providers/router.js +88 -0
  349. package/packages/core/dist/providers/router.js.map +1 -0
  350. package/packages/core/dist/providers/user-settings-guard.d.ts +12 -0
  351. package/packages/core/dist/providers/user-settings-guard.d.ts.map +1 -0
  352. package/packages/core/dist/providers/user-settings-guard.js +130 -0
  353. package/packages/core/dist/providers/user-settings-guard.js.map +1 -0
  354. package/packages/core/dist/runtime.d.ts +193 -7
  355. package/packages/core/dist/runtime.d.ts.map +1 -1
  356. package/packages/core/dist/runtime.js +1676 -219
  357. package/packages/core/dist/runtime.js.map +1 -1
  358. package/packages/core/dist/skills/builtin.d.ts +34 -0
  359. package/packages/core/dist/skills/builtin.d.ts.map +1 -0
  360. package/packages/core/dist/skills/builtin.js +305 -0
  361. package/packages/core/dist/skills/builtin.js.map +1 -0
  362. package/packages/core/dist/skills/shelf.d.ts +30 -0
  363. package/packages/core/dist/skills/shelf.d.ts.map +1 -0
  364. package/packages/core/dist/skills/shelf.js +159 -0
  365. package/packages/core/dist/skills/shelf.js.map +1 -0
  366. package/packages/core/dist/skills/store.d.ts +66 -4
  367. package/packages/core/dist/skills/store.d.ts.map +1 -1
  368. package/packages/core/dist/skills/store.js +105 -18
  369. package/packages/core/dist/skills/store.js.map +1 -1
  370. package/packages/core/dist/skills/suggest.d.ts +21 -0
  371. package/packages/core/dist/skills/suggest.d.ts.map +1 -0
  372. package/packages/core/dist/skills/suggest.js +150 -0
  373. package/packages/core/dist/skills/suggest.js.map +1 -0
  374. package/packages/core/dist/tools/catalog.d.ts +1 -3
  375. package/packages/core/dist/tools/catalog.d.ts.map +1 -1
  376. package/packages/core/dist/tools/catalog.js +38 -26
  377. package/packages/core/dist/tools/catalog.js.map +1 -1
  378. package/packages/core/dist/tools/hub.d.ts +136 -10
  379. package/packages/core/dist/tools/hub.d.ts.map +1 -1
  380. package/packages/core/dist/tools/hub.js +418 -24
  381. package/packages/core/dist/tools/hub.js.map +1 -1
  382. package/packages/core/dist/turns/journal.d.ts +78 -0
  383. package/packages/core/dist/turns/journal.d.ts.map +1 -0
  384. package/packages/core/dist/turns/journal.js +104 -0
  385. package/packages/core/dist/turns/journal.js.map +1 -0
  386. package/packages/core/dist/types.d.ts +1776 -12
  387. package/packages/core/dist/types.d.ts.map +1 -1
  388. package/packages/core/dist/types.js.map +1 -1
  389. package/packages/core/dist/util/blocks.d.ts +41 -0
  390. package/packages/core/dist/util/blocks.d.ts.map +1 -0
  391. package/packages/core/dist/util/blocks.js +175 -0
  392. package/packages/core/dist/util/blocks.js.map +1 -0
  393. package/packages/core/dist/util/queue.d.ts +12 -0
  394. package/packages/core/dist/util/queue.d.ts.map +1 -1
  395. package/packages/core/dist/util/queue.js +16 -0
  396. package/packages/core/dist/util/queue.js.map +1 -1
  397. package/packages/core/dist/util/time.d.ts +39 -0
  398. package/packages/core/dist/util/time.d.ts.map +1 -0
  399. package/packages/core/dist/util/time.js +71 -0
  400. package/packages/core/dist/util/time.js.map +1 -0
  401. package/packages/core/package.json +1 -1
  402. package/packages/server/dist/auth.d.ts +14 -1
  403. package/packages/server/dist/auth.d.ts.map +1 -1
  404. package/packages/server/dist/auth.js +19 -0
  405. package/packages/server/dist/auth.js.map +1 -1
  406. package/packages/server/dist/context.d.ts +35 -1
  407. package/packages/server/dist/context.d.ts.map +1 -1
  408. package/packages/server/dist/context.js +39 -10
  409. package/packages/server/dist/context.js.map +1 -1
  410. package/packages/server/dist/gateways/attachments.d.ts +32 -0
  411. package/packages/server/dist/gateways/attachments.d.ts.map +1 -0
  412. package/packages/server/dist/gateways/attachments.js +167 -0
  413. package/packages/server/dist/gateways/attachments.js.map +1 -0
  414. package/packages/server/dist/gateways/markdown.d.ts +9 -0
  415. package/packages/server/dist/gateways/markdown.d.ts.map +1 -0
  416. package/packages/server/dist/gateways/markdown.js +170 -0
  417. package/packages/server/dist/gateways/markdown.js.map +1 -0
  418. package/packages/server/dist/gateways/push.d.ts +1 -1
  419. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  420. package/packages/server/dist/gateways/push.js +420 -13
  421. package/packages/server/dist/gateways/push.js.map +1 -1
  422. package/packages/server/dist/gateways/telegram-api.d.ts +70 -1
  423. package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -1
  424. package/packages/server/dist/gateways/telegram-api.js +140 -1
  425. package/packages/server/dist/gateways/telegram-api.js.map +1 -1
  426. package/packages/server/dist/gateways/telegram.d.ts +181 -1
  427. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  428. package/packages/server/dist/gateways/telegram.js +1572 -78
  429. package/packages/server/dist/gateways/telegram.js.map +1 -1
  430. package/packages/server/dist/gateways/threads.d.ts +84 -0
  431. package/packages/server/dist/gateways/threads.d.ts.map +1 -0
  432. package/packages/server/dist/gateways/threads.js +289 -0
  433. package/packages/server/dist/gateways/threads.js.map +1 -0
  434. package/packages/server/dist/index.d.ts +2 -1
  435. package/packages/server/dist/index.d.ts.map +1 -1
  436. package/packages/server/dist/index.js +2 -1
  437. package/packages/server/dist/index.js.map +1 -1
  438. package/packages/server/dist/listeners/imap.d.ts +13 -0
  439. package/packages/server/dist/listeners/imap.d.ts.map +1 -0
  440. package/packages/server/dist/listeners/imap.js +0 -0
  441. package/packages/server/dist/listeners/imap.js.map +1 -0
  442. package/packages/server/dist/listeners/registry.d.ts +18 -0
  443. package/packages/server/dist/listeners/registry.d.ts.map +1 -0
  444. package/packages/server/dist/listeners/registry.js +88 -0
  445. package/packages/server/dist/listeners/registry.js.map +1 -0
  446. package/packages/server/dist/listeners/types.d.ts +55 -0
  447. package/packages/server/dist/listeners/types.d.ts.map +1 -0
  448. package/packages/server/dist/listeners/types.js +2 -0
  449. package/packages/server/dist/listeners/types.js.map +1 -0
  450. package/packages/server/dist/main.js +15 -1
  451. package/packages/server/dist/main.js.map +1 -1
  452. package/packages/server/dist/routes/chat.d.ts +7 -3
  453. package/packages/server/dist/routes/chat.d.ts.map +1 -1
  454. package/packages/server/dist/routes/chat.js +8 -17
  455. package/packages/server/dist/routes/chat.js.map +1 -1
  456. package/packages/server/dist/routes/config.d.ts.map +1 -1
  457. package/packages/server/dist/routes/config.js +66 -7
  458. package/packages/server/dist/routes/config.js.map +1 -1
  459. package/packages/server/dist/routes/cron.d.ts.map +1 -1
  460. package/packages/server/dist/routes/cron.js +65 -8
  461. package/packages/server/dist/routes/cron.js.map +1 -1
  462. package/packages/server/dist/routes/dream.d.ts +22 -0
  463. package/packages/server/dist/routes/dream.d.ts.map +1 -0
  464. package/packages/server/dist/routes/dream.js +152 -0
  465. package/packages/server/dist/routes/dream.js.map +1 -0
  466. package/packages/server/dist/routes/hooks.d.ts +18 -0
  467. package/packages/server/dist/routes/hooks.d.ts.map +1 -0
  468. package/packages/server/dist/routes/hooks.js +62 -0
  469. package/packages/server/dist/routes/hooks.js.map +1 -0
  470. package/packages/server/dist/routes/listeners.d.ts +10 -0
  471. package/packages/server/dist/routes/listeners.d.ts.map +1 -0
  472. package/packages/server/dist/routes/listeners.js +12 -0
  473. package/packages/server/dist/routes/listeners.js.map +1 -0
  474. package/packages/server/dist/routes/memories.d.ts.map +1 -1
  475. package/packages/server/dist/routes/memories.js +55 -3
  476. package/packages/server/dist/routes/memories.js.map +1 -1
  477. package/packages/server/dist/routes/org.d.ts.map +1 -1
  478. package/packages/server/dist/routes/org.js +289 -49
  479. package/packages/server/dist/routes/org.js.map +1 -1
  480. package/packages/server/dist/routes/profile.d.ts.map +1 -1
  481. package/packages/server/dist/routes/profile.js +6 -3
  482. package/packages/server/dist/routes/profile.js.map +1 -1
  483. package/packages/server/dist/routes/providers.d.ts.map +1 -1
  484. package/packages/server/dist/routes/providers.js +66 -7
  485. package/packages/server/dist/routes/providers.js.map +1 -1
  486. package/packages/server/dist/routes/questions.d.ts +45 -0
  487. package/packages/server/dist/routes/questions.d.ts.map +1 -0
  488. package/packages/server/dist/routes/questions.js +73 -0
  489. package/packages/server/dist/routes/questions.js.map +1 -0
  490. package/packages/server/dist/routes/sessions.d.ts.map +1 -1
  491. package/packages/server/dist/routes/sessions.js +26 -6
  492. package/packages/server/dist/routes/sessions.js.map +1 -1
  493. package/packages/server/dist/routes/sleep.d.ts.map +1 -1
  494. package/packages/server/dist/routes/sleep.js +71 -2
  495. package/packages/server/dist/routes/sleep.js.map +1 -1
  496. package/packages/server/dist/routes/terminals.d.ts +25 -0
  497. package/packages/server/dist/routes/terminals.d.ts.map +1 -0
  498. package/packages/server/dist/routes/terminals.js +35 -0
  499. package/packages/server/dist/routes/terminals.js.map +1 -0
  500. package/packages/server/dist/routes/tools.d.ts.map +1 -1
  501. package/packages/server/dist/routes/tools.js +140 -6
  502. package/packages/server/dist/routes/tools.js.map +1 -1
  503. package/packages/server/dist/routes/updates.d.ts +10 -0
  504. package/packages/server/dist/routes/updates.d.ts.map +1 -0
  505. package/packages/server/dist/routes/updates.js +22 -0
  506. package/packages/server/dist/routes/updates.js.map +1 -0
  507. package/packages/server/dist/routes/ws.d.ts +11 -5
  508. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  509. package/packages/server/dist/routes/ws.js +168 -28
  510. package/packages/server/dist/routes/ws.js.map +1 -1
  511. package/packages/server/dist/schemas.d.ts +1177 -215
  512. package/packages/server/dist/schemas.d.ts.map +1 -1
  513. package/packages/server/dist/schemas.js +317 -12
  514. package/packages/server/dist/schemas.js.map +1 -1
  515. package/packages/server/dist/server.d.ts +7 -1
  516. package/packages/server/dist/server.d.ts.map +1 -1
  517. package/packages/server/dist/server.js +210 -3
  518. package/packages/server/dist/server.js.map +1 -1
  519. package/packages/server/dist/services/stream.d.ts +94 -5
  520. package/packages/server/dist/services/stream.d.ts.map +1 -1
  521. package/packages/server/dist/services/stream.js +9 -20
  522. package/packages/server/dist/services/stream.js.map +1 -1
  523. package/packages/server/dist/services/stt.d.ts +65 -0
  524. package/packages/server/dist/services/stt.d.ts.map +1 -0
  525. package/packages/server/dist/services/stt.js +306 -0
  526. package/packages/server/dist/services/stt.js.map +1 -0
  527. package/packages/server/dist/services/turns.d.ts +54 -0
  528. package/packages/server/dist/services/turns.d.ts.map +1 -0
  529. package/packages/server/dist/services/turns.js +186 -0
  530. package/packages/server/dist/services/turns.js.map +1 -0
  531. package/packages/server/dist/services/updates.d.ts +99 -0
  532. package/packages/server/dist/services/updates.d.ts.map +1 -0
  533. package/packages/server/dist/services/updates.js +316 -0
  534. package/packages/server/dist/services/updates.js.map +1 -0
  535. package/packages/server/package.json +1 -1
  536. package/packages/web/dist/app-icon.svg +2 -0
  537. package/packages/web/dist/apple-touch-icon.png +0 -0
  538. package/packages/web/dist/assets/abnfDiagram-O67JEVCF-D7YyFndQ.js +1 -0
  539. package/packages/web/dist/assets/arc-C_Zgk2dJ.js +1 -0
  540. package/packages/web/dist/assets/architectureDiagram-NJMV4G6O-eI0adu1B.js +36 -0
  541. package/packages/web/dist/assets/blockDiagram-BEXU5L5S-WAoOFUA9.js +140 -0
  542. package/packages/web/dist/assets/c4Diagram-YGBWAQC7-DE8Zyhng.js +38 -0
  543. package/packages/web/dist/assets/channel-egZxcyUK.js +1 -0
  544. package/packages/web/dist/assets/chunk-2Q5K7J3B-bnqLP2XD.js +1 -0
  545. package/packages/web/dist/assets/chunk-3FUC2YCW-Ck1_SVe0.js +2 -0
  546. package/packages/web/dist/assets/chunk-5VM5RSS4-hDmC41gD.js +15 -0
  547. package/packages/web/dist/assets/chunk-GTNCS2PH-PoWvfCrT.js +88 -0
  548. package/packages/web/dist/assets/chunk-GWA4HPMP-D3V0IG43.js +1 -0
  549. package/packages/web/dist/assets/chunk-JWPE2WC7-BryfpHM5.js +1 -0
  550. package/packages/web/dist/assets/chunk-NETBCI7D-8ic1iEdT.js +1 -0
  551. package/packages/web/dist/assets/chunk-WEXAMYUT-nM8tmQT2.js +1 -0
  552. package/packages/web/dist/assets/chunk-XXDRQBXY-Do28F482.js +1 -0
  553. package/packages/web/dist/assets/classDiagram-v2-NBCMYWYE-Bop9oNNO.js +217 -0
  554. package/packages/web/dist/assets/cose-bilkent-JH36ORCC-a7f_bpnt.js +1 -0
  555. package/packages/web/dist/assets/cynefin-OW5HDTMX-DnArcis_.js +178 -0
  556. package/packages/web/dist/assets/cynefinDiagram-VND7K2PF-vEuTb1GD.js +62 -0
  557. package/packages/web/dist/assets/cytoscape.esm-Ix0LnXOy.js +331 -0
  558. package/packages/web/dist/assets/dagre-6A5THRUB-BgG4MynJ.js +4 -0
  559. package/packages/web/dist/assets/diagram-22UHCM2B-DRCQpafv.js +200 -0
  560. package/packages/web/dist/assets/diagram-3UASUU5V-BKgmAXde.js +24 -0
  561. package/packages/web/dist/assets/diagram-ATOU4E4O-B6Hsy36X.js +3 -0
  562. package/packages/web/dist/assets/diagram-CDSNMT55-JflyfyoB.js +30 -0
  563. package/packages/web/dist/assets/diagram-MLGK6HIB-Dd2QPJjT.js +24 -0
  564. package/packages/web/dist/assets/diagram-MPIPVDR6-DE5QU60x.js +41 -0
  565. package/packages/web/dist/assets/draco_decoder-C32yEggz.wasm +0 -0
  566. package/packages/web/dist/assets/draco_decoder-Z1_iN-Ht.wasm +0 -0
  567. package/packages/web/dist/assets/draco_decoder-fzg4nYZr.js +34 -0
  568. package/packages/web/dist/assets/draco_wasm_wrapper-DxJM36Ib.js +117 -0
  569. package/packages/web/dist/assets/draco_wasm_wrapper-fZCQGLGb.js +116 -0
  570. package/packages/web/dist/assets/ebnfDiagram-ZINNZB2B-D7AQ741b.js +1 -0
  571. package/packages/web/dist/assets/elk-276RUBZZ-CeewBVLF.js +27 -0
  572. package/packages/web/dist/assets/erDiagram-OPXOYQCR-mLLYkZ5c.js +99 -0
  573. package/packages/web/dist/assets/flowDiagram-KWPJA3E3-DtpSpsQN.js +213 -0
  574. package/packages/web/dist/assets/ganttDiagram-FUAMR5RP-1_lh-3ky.js +292 -0
  575. package/packages/web/dist/assets/gitGraphDiagram-X574FWY7-DoPXZuT5.js +106 -0
  576. package/packages/web/dist/assets/graph-Bn3Yngep.js +1 -0
  577. package/packages/web/dist/assets/index-Cw2Opmx7.js +648 -0
  578. package/packages/web/dist/assets/index-j0zBRCgT.css +32 -0
  579. package/packages/web/dist/assets/infoDiagram-VRGFBTTK-DQpRGGiD.js +2 -0
  580. package/packages/web/dist/assets/ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js +70 -0
  581. package/packages/web/dist/assets/journeyDiagram-ZHPQQLJL-Bg-oeFjb.js +139 -0
  582. package/packages/web/dist/assets/kanban-definition-PNTS6WVX-BnpI4VH8.js +89 -0
  583. package/packages/web/dist/assets/katex-C5jXJg4s.js +257 -0
  584. package/packages/web/dist/assets/mermaid.core-BwBKxlRA.js +313 -0
  585. package/packages/web/dist/assets/mindmap-definition-NLK3R4M7-NBnnxEoO.js +96 -0
  586. package/packages/web/dist/assets/pegDiagram-GJSIUBJH-RrXXbIvO.js +1 -0
  587. package/packages/web/dist/assets/pieDiagram-5QR66LMP-B27q6Gso.js +39 -0
  588. package/packages/web/dist/assets/quadrantDiagram-O4NWA36T-DGDsdur2.js +7 -0
  589. package/packages/web/dist/assets/railroadDiagram-XR7U4H2S-GdjkE3mI.js +1 -0
  590. package/packages/web/dist/assets/requirementDiagram-PLB6GJNP-DjK0GfgO.js +84 -0
  591. package/packages/web/dist/assets/sankeyDiagram-IPEJSGJF-BG_AIkwF.js +40 -0
  592. package/packages/web/dist/assets/scene-D4LPicHk.js +4620 -0
  593. package/packages/web/dist/assets/sequenceDiagram-PO4LG4MO-CIQwUb4y.js +169 -0
  594. package/packages/web/dist/assets/sizeCapture-INFHLROL-bpIoPxdJ.js +1 -0
  595. package/packages/web/dist/assets/stateDiagram-v2-GCMORJYK-8hYXvPPv.js +291 -0
  596. package/packages/web/dist/assets/swimlanes-2SLR337P-gfflUMF9.js +1 -0
  597. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +8 -0
  598. package/packages/web/dist/assets/timeline-definition-EJHVYXUP-PHMNoGTZ.js +120 -0
  599. package/packages/web/dist/assets/usecaseDiagram-POWQR4AR-B2j5iteO.js +370 -0
  600. package/packages/web/dist/assets/vennDiagram-UO4OBE2U-BzxtZ-_2.js +34 -0
  601. package/packages/web/dist/assets/wardleyDiagram-VNRHLVJA-DL7YbMpY.js +78 -0
  602. package/packages/web/dist/assets/xychartDiagram-PMCCYNJV-CisgP1cT.js +7 -0
  603. package/packages/web/dist/draco/draco_decoder.js +33 -0
  604. package/packages/web/dist/draco/draco_decoder.wasm +0 -0
  605. package/packages/web/dist/draco/draco_wasm_wrapper.js +116 -0
  606. package/packages/web/dist/favicon-16.png +0 -0
  607. package/packages/web/dist/favicon-32.png +0 -0
  608. package/packages/web/dist/favicon-48.png +0 -0
  609. package/packages/web/dist/favicon.ico +0 -0
  610. package/packages/web/dist/favicon.svg +1 -1
  611. package/packages/web/dist/icon-192.png +0 -0
  612. package/packages/web/dist/icon-512.png +0 -0
  613. package/packages/web/dist/index.html +12 -4
  614. package/packages/web/dist/logo-light.svg +1 -1
  615. package/packages/web/dist/logo-mono.svg +2 -0
  616. package/packages/web/dist/logo-stacked-light.svg +2 -0
  617. package/packages/web/dist/logo-stacked.svg +2 -0
  618. package/packages/web/dist/logo-white.svg +2 -0
  619. package/packages/web/dist/logo.svg +1 -1
  620. package/packages/web/dist/mark-light.svg +1 -1
  621. package/packages/web/dist/mark-mono.svg +2 -0
  622. package/packages/web/dist/mark-small-light.svg +2 -0
  623. package/packages/web/dist/mark-small.svg +2 -0
  624. package/packages/web/dist/mark-white.svg +2 -0
  625. package/packages/web/dist/mark.svg +1 -1
  626. package/packages/web/dist/models/LICENSE.txt +5 -0
  627. package/packages/web/dist/models/brain.glb +0 -0
  628. package/packages/web/dist/site.webmanifest +23 -0
  629. package/packages/web/dist/wordmark-light.svg +2 -0
  630. package/packages/web/dist/wordmark.svg +2 -0
  631. package/packages/web/package.json +1 -1
  632. package/scripts/rookery.mjs +204 -122
  633. package/scripts/updater.mjs +227 -0
  634. package/packages/cli/dist/tui/components/Wordmark.d.ts +0 -35
  635. package/packages/cli/dist/tui/components/Wordmark.d.ts.map +0 -1
  636. package/packages/cli/dist/tui/components/Wordmark.js +0 -81
  637. package/packages/cli/dist/tui/components/Wordmark.js.map +0 -1
  638. package/packages/core/dist/agents/orchestrator.d.ts +0 -24
  639. package/packages/core/dist/agents/orchestrator.d.ts.map +0 -1
  640. package/packages/core/dist/agents/orchestrator.js +0 -88
  641. package/packages/core/dist/agents/orchestrator.js.map +0 -1
  642. package/packages/core/dist/agents/roles.d.ts +0 -21
  643. package/packages/core/dist/agents/roles.d.ts.map +0 -1
  644. package/packages/core/dist/agents/roles.js +0 -81
  645. package/packages/core/dist/agents/roles.js.map +0 -1
  646. package/packages/core/dist/agents/team.d.ts +0 -105
  647. package/packages/core/dist/agents/team.d.ts.map +0 -1
  648. package/packages/core/dist/agents/team.js +0 -623
  649. package/packages/core/dist/agents/team.js.map +0 -1
  650. package/packages/core/dist/providers/codex.d.ts +0 -10
  651. package/packages/core/dist/providers/codex.d.ts.map +0 -1
  652. package/packages/core/dist/providers/codex.js +0 -375
  653. package/packages/core/dist/providers/codex.js.map +0 -1
  654. package/packages/core/dist/tools/browser.d.ts +0 -20
  655. package/packages/core/dist/tools/browser.d.ts.map +0 -1
  656. package/packages/core/dist/tools/browser.js +0 -72
  657. package/packages/core/dist/tools/browser.js.map +0 -1
  658. package/packages/server/dist/routes/agents.d.ts +0 -5
  659. package/packages/server/dist/routes/agents.d.ts.map +0 -1
  660. package/packages/server/dist/routes/agents.js +0 -6
  661. package/packages/server/dist/routes/agents.js.map +0 -1
  662. package/packages/server/dist/routes/team.d.ts +0 -11
  663. package/packages/server/dist/routes/team.d.ts.map +0 -1
  664. package/packages/server/dist/routes/team.js +0 -36
  665. package/packages/server/dist/routes/team.js.map +0 -1
  666. package/packages/web/dist/assets/3d-force-graph-BPZmoydi.js +0 -1163
  667. package/packages/web/dist/assets/index-IBSTzK7-.js +0 -1255
  668. package/packages/web/dist/assets/index-qUXUui7W.css +0 -1
  669. package/packages/web/dist/assets/three-spritetext-B9ZIW7c-.js +0 -4
  670. package/packages/web/dist/assets/three.module-cmFfBtHS.js +0 -4228
@@ -1,4 +1,9 @@
1
- import { ASSISTANT_MEMORY_OWNER, classifyUpdate, escapeHtml, missingGatewaySettings, nextGatewayAction, providerQuota, splitMessage, } from '../../../core/dist/index.js';
1
+ import { ASSISTANT_MEMORY_OWNER, classifyCallback, classifyUpdate, isAudible, missingGatewaySettings, nextGatewayAction, notificationReadCallbackData, notificationReadDoneCallbackData, providerQuota, questionCallbackData, questionDoneCallbackData, readCallbackData, splitMessage, } from '../../../core/dist/index.js';
2
+ import { localModelReady, transcribe, SttError } from '../services/stt.js';
3
+ import { voiceKeys } from '../services/voice-keys.js';
4
+ import { humanDuration, humanSize, pruneInbox, saveAttachment } from './attachments.js';
5
+ import { toTelegramHtml } from './markdown.js';
6
+ import { findOrigin, noteMessages, openThread, originContext, rememberOrigin, takeMessages, } from './threads.js';
2
7
  import { createTelegramApi, TelegramApiError, } from './telegram-api.js';
3
8
  /**
4
9
  * The Telegram transport: the part that actually talks to api.telegram.org.
@@ -14,16 +19,247 @@ import { createTelegramApi, TelegramApiError, } from './telegram-api.js';
14
19
  */
15
20
  /** Seconds we ask Telegram to hold a poll open. */
16
21
  const POLL_SECONDS = 50;
17
- /** Only messages. Edits, callback queries and channel posts never arrive. */
18
- const ALLOWED_UPDATES = ['message'];
22
+ /**
23
+ * Messages, and taps on the buttons the bot drew itself. Edits, channel
24
+ * posts and everything else never arrive.
25
+ */
26
+ const ALLOWED_UPDATES = ['message', 'callback_query'];
27
+ /**
28
+ * The two things this channel draws buttons for, and nothing else.
29
+ *
30
+ * What goes *on* a button - the prefixes and how they read back - lives in
31
+ * `@rookery/core`'s gateway policy, next to the guard that decides whether a
32
+ * tap counts at all. What is left here is the drawing: labels, rows, and the
33
+ * wording a spent button carries. Notification ids and question ids are
34
+ * opaque to the phone either way; a tap is believed because the guard chain
35
+ * proved who pressed it, never because of what the data says.
36
+ */
37
+ /**
38
+ * The button as it is drawn under a fresh notification push.
39
+ *
40
+ * The label is an *invitation*, not a state, and the difference is the whole
41
+ * point: the first version read "✓ Read" both before and after the tap, so
42
+ * the button did change and nobody could see it. A button says what tapping
43
+ * it will do; what it did belongs to `notificationReadDone` below.
44
+ *
45
+ * Exported so `push.ts` can ask for it without knowing what goes on a
46
+ * button: the wording stays in the one file that also draws the rest.
47
+ */
48
+ export function notificationReadKeyboard(notificationId) {
49
+ return [[{ text: 'Mark as read', callbackData: notificationReadCallbackData(notificationId) }]];
50
+ }
51
+ /**
52
+ * The same button, spent: a statement, with the time it happened.
53
+ *
54
+ * The clock is the server's own, because that is the room the user is in -
55
+ * Telegram tells a bot nothing about the phone's time zone.
56
+ */
57
+ export function notificationReadDone(at) {
58
+ const stamp = new Date(at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
59
+ return [[{ text: '✓ Read at ' + stamp, callbackData: notificationReadDoneCallbackData() }]];
60
+ }
61
+ /** Longest an option reads on a button before the phone wraps it badly. */
62
+ const OPTION_LABEL = 48;
63
+ /**
64
+ * The options of an open question, one per row.
65
+ *
66
+ * Numbered, and numbered the same way the message above them is, because
67
+ * there are two ways to answer on this channel and they have to agree: a tap
68
+ * on "2." and the typed reply "2" must mean the same option. One option per
69
+ * row rather than two side by side - a label long enough to be worth reading
70
+ * is a label that gets cut in half in a two-column keyboard.
71
+ */
72
+ export function questionKeyboard(question) {
73
+ return question.options.map((option, index) => [
74
+ {
75
+ text: String(index + 1) + '. ' + oneLine(option.label, OPTION_LABEL),
76
+ callbackData: questionCallbackData(question.id, index),
77
+ },
78
+ ]);
79
+ }
80
+ /**
81
+ * What is left standing once a question is over.
82
+ *
83
+ * The same reasoning as the read button: Telegram has no disabled state, so
84
+ * the spent keyboard is a keyboard too, and its one job is to say what
85
+ * happened - including when the answer came from the web app or the terminal
86
+ * rather than from here, which is the case this exists for.
87
+ */
88
+ export function questionClosedKeyboard(reason, chosen) {
89
+ const text = reason === 'answered'
90
+ ? '✓ ' + oneLine(chosen || 'Answered', OPTION_LABEL)
91
+ : reason === 'expired'
92
+ ? '⏳ No answer in time'
93
+ : reason === 'cancelled'
94
+ ? '✕ Withdrawn'
95
+ : // Closed between drawing the buttons and pressing one, and this
96
+ // channel was not told which way. Saying that is better than
97
+ // picking the likelier of two wordings and being wrong.
98
+ '• No longer open';
99
+ return [[{ text, callbackData: questionDoneCallbackData() }]];
100
+ }
101
+ /**
102
+ * The question as a message.
103
+ *
104
+ * The options are written out above the buttons even though the buttons
105
+ * carry them too, and that is deliberate: a button holds a label and nothing
106
+ * more, while an option that needs a sentence of explanation only has room
107
+ * for it here. The numbering is the bridge between the two answers this
108
+ * channel takes - tapping "2." and writing "2" are the same act.
109
+ *
110
+ * The deadline is named rather than implied. A question that quietly stops
111
+ * mattering while the phone is in a pocket is worse than one that said when
112
+ * it would.
113
+ */
114
+ export function questionText(question) {
115
+ const lines = [
116
+ '❓ ' + oneLine(question.header, 80),
117
+ '',
118
+ question.question.trim(),
119
+ '',
120
+ ...question.options.map((option, index) => String(index + 1) + '. ' + option.label + (option.description ? ' – ' + option.description : '')),
121
+ '',
122
+ question.multiSelect
123
+ ? 'Tap one, or write the numbers you mean ("1 3"), or answer in your own words.'
124
+ : 'Tap one, write its number, or answer in your own words.',
125
+ ];
126
+ if (Number.isFinite(question.expiresAt) && question.expiresAt > 0) {
127
+ const stamp = new Date(question.expiresAt).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
128
+ lines.push('If nothing comes back by ' + stamp + ' I carry on without it.');
129
+ }
130
+ return lines.join('\n');
131
+ }
132
+ /**
133
+ * A typed reply, read as an answer to the question that is open.
134
+ *
135
+ * Three shapes, in the order a person is likely to mean them: the numbers
136
+ * printed next to the options, the wording of an option itself, and anything
137
+ * else, which is a free answer and goes through whole. Nothing is rejected -
138
+ * the registry takes free text on purpose, and a reply this cannot classify
139
+ * is still the user talking to the question, not a new turn.
140
+ *
141
+ * Exported for its own test: "1" meaning the first option and "1" meaning
142
+ * the literal word are the same three characters, and only the open question
143
+ * tells them apart.
144
+ */
145
+ export function readTypedAnswer(text, question) {
146
+ const at = Date.now();
147
+ const written = text.trim();
148
+ const source = 'telegram';
149
+ const tokens = written.split(/[\s,;]+/).filter(Boolean);
150
+ const numbers = tokens.map((token) => Number(token));
151
+ const inRange = (value) => Number.isInteger(value) && value >= 1 && value <= question.options.length;
152
+ if (tokens.length > 0 && numbers.every(inRange)) {
153
+ const picked = [...new Set(numbers.map((value) => value - 1))];
154
+ return { selected: question.multiSelect ? picked : picked.slice(0, 1), source, at };
155
+ }
156
+ const flat = written.toLowerCase();
157
+ const labelled = question.options.findIndex((option) => option.label.trim().toLowerCase() === flat);
158
+ if (labelled >= 0)
159
+ return { selected: [labelled], source, at };
160
+ return { selected: [], text: written, source, at };
161
+ }
162
+ /** The labels behind an answer, for the button that says what was chosen. */
163
+ function chosenLabels(question, answer) {
164
+ if (!answer)
165
+ return undefined;
166
+ const labels = answer.selected
167
+ .map((index) => question.options[index]?.label)
168
+ .filter((label) => Boolean(label));
169
+ if (labels.length > 0)
170
+ return labels.join(', ');
171
+ return answer.text?.trim() || undefined;
172
+ }
173
+ /**
174
+ * How long an album is waited for.
175
+ *
176
+ * Several photos sent at once arrive as several updates that share a
177
+ * `media_group_id`, one per picture, a few hundred milliseconds apart. One
178
+ * turn per picture would answer the first one before the third has landed,
179
+ * so the group is collected and handed over as a single message. The window
180
+ * restarts with every further item, and one and a half seconds is well past
181
+ * what Telegram needs to deliver them.
182
+ */
183
+ const ALBUM_WINDOW_MS = 1500;
184
+ /** Most files one message (or one album) may carry into a single turn. */
185
+ const MAX_ATTACHMENTS = 10;
186
+ /** How much of a transcript is echoed back so the sender can check it. */
187
+ const TRANSCRIPT_ECHO = 600;
188
+ /** Smallest gap between two rewrites of the live progress line. */
189
+ const PROGRESS_EDIT_MS = 12_000;
190
+ /**
191
+ * How soon the first words of a streamed answer go out, and how far apart
192
+ * every rewrite after them is.
193
+ *
194
+ * Telegram rate limits edits per chat, and a turn that produces a page of
195
+ * text would otherwise ask for a hundred of them. Half a second to first
196
+ * sight, then one and a half between updates: fast enough to read as typing,
197
+ * slow enough that a long answer costs tens of calls rather than hundreds.
198
+ */
199
+ const STREAM_FIRST_MS = 500;
200
+ const STREAM_EDIT_MS = 1500;
201
+ /** How many rows a list command shows before it says "and more". */
202
+ const LIST_LIMIT = 8;
203
+ /**
204
+ * How far back `/clear` counts from the newest message.
205
+ *
206
+ * Message ids are a per-chat counter, so this is "the last thousand
207
+ * messages", not a thousand deletions: Telegram is handed the ids a hundred
208
+ * at a time and skips whatever is not there or too old to delete. A
209
+ * thousand covers a very talkative 48 hours - which is all Telegram will
210
+ * delete anyway - at ten API calls per `/clear`.
211
+ */
212
+ const CLEAR_SWEEP = 1000;
213
+ /**
214
+ * The commands, in the order Telegram's menu shows them.
215
+ *
216
+ * One table, three uses: `/help` prints it, `setMyCommands` hands it to
217
+ * Telegram so the app draws its own menu, and the switch in `handleCommand`
218
+ * answers it. A command that is added in one place and forgotten in another
219
+ * is the usual way a bot ends up lying about itself, so there is only the
220
+ * one place. The German aliases (`/neu`, `/aus`) are still accepted and
221
+ * deliberately not listed - they are history, not a second interface.
222
+ *
223
+ * Exported for the test that holds it against Telegram's own rules: the
224
+ * whole list is refused if a single entry breaks them, and a refused list
225
+ * is a menu that silently never appears.
226
+ */
227
+ export const COMMANDS = [
228
+ { command: 'help', description: 'Every command, with what it does' },
229
+ { command: 'new', description: 'Start a new conversation, keep the old one' },
230
+ { command: 'clear', description: 'Empty this chat and start fresh' },
231
+ { command: 'stop', description: 'Cancel the turn that is running' },
232
+ { command: 'status', description: 'Provider, usage limits, running work, last sleep' },
233
+ { command: 'tasks', description: 'Open tasks on the board' },
234
+ { command: 'inbox', description: 'Unread notifications: schedules, tasks, questions' },
235
+ { command: 'agents', description: 'Who works in the company' },
236
+ { command: 'schedules', description: 'What runs on a schedule, and when' },
237
+ { command: 'id', description: 'Your numeric Telegram ID' },
238
+ { command: 'off', description: 'Silence the gateway until the server restarts' },
239
+ ];
240
+ /** Reactions the bot puts on the sender's own message while it works. */
241
+ const REACTION = {
242
+ /** Taken in, working on it. */
243
+ working: '👀',
244
+ /** Answered. */
245
+ done: '👍',
246
+ /** Something went wrong; the error itself still arrives as a message. */
247
+ failed: '😢',
248
+ };
19
249
  const BACKOFF_START_MS = 1000;
20
250
  const BACKOFF_MAX_MS = 60_000;
251
+ /**
252
+ * How long after a start that failed on something transient before trying
253
+ * again, doubling up to the ceiling. Five seconds so a laptop whose network
254
+ * arrives a moment late is back within one, a minute so a Telegram outage is
255
+ * not hammered.
256
+ */
257
+ const RETRY_START_MS = 5000;
258
+ const RETRY_MAX_MS = 60_000;
21
259
  /** Telegram's typing bubble fades after a few seconds, so it is refreshed. */
22
260
  const TYPING_INTERVAL_MS = 4000;
23
- /** Silence a turn may spend before the first "still working" line goes out. */
261
+ /** Silence a turn may spend before the live progress line appears. */
24
262
  const FIRST_NOTE_MS = 20_000;
25
- /** Minimum distance between two progress lines after that first one. */
26
- const NOTE_INTERVAL_MS = 60_000;
27
263
  /** Messages one sender may have waiting. Beyond it, the rest is refused. */
28
264
  const MAX_QUEUE_DEPTH = 3;
29
265
  /** How often the same stranger can learn their own id. */
@@ -32,35 +268,70 @@ const ID_REPLY_INTERVAL_MS = 60 * 60 * 1000;
32
268
  const AUDIT_TEXT = 120;
33
269
  const REJECT_TEXT = 80;
34
270
  /**
35
- * Markdown fences to Telegram HTML.
271
+ * One piece of Markdown as Telegram HTML.
36
272
  *
37
- * `splitMessage` guarantees every piece carries balanced fences, so a piece
38
- * can be converted on its own. Everything outside a block is escaped text;
39
- * inside, the block is escaped in one go and wrapped in `<pre>`, which is the
40
- * only tag Telegram renders as a code block.
273
+ * The conversion itself lives in `markdown.ts`; what matters here is that it
274
+ * is applied piece by piece. `splitMessage` guarantees every piece carries
275
+ * balanced code fences, so each one converts on its own without the fence
276
+ * state of its neighbours.
41
277
  */
42
278
  function toHtml(piece) {
43
- const out = [];
44
- let code;
45
- for (const line of piece.split('\n')) {
46
- if (line.trimStart().startsWith('```')) {
47
- if (code) {
48
- out.push(`<pre>${escapeHtml(code.join('\n'))}</pre>`);
49
- code = undefined;
50
- }
51
- else {
52
- code = [];
53
- }
54
- continue;
55
- }
56
- if (code)
57
- code.push(line);
58
- else
59
- out.push(escapeHtml(line));
279
+ return toTelegramHtml(piece);
280
+ }
281
+ /** What Telegram accepts in one message, counted after escaping. */
282
+ const TELEGRAM_LIMIT = 4096;
283
+ /**
284
+ * One message's worth of HTML at a time, each piece guaranteed to fit.
285
+ *
286
+ * `splitMessage` counts the text as written, but what goes on the wire is
287
+ * escaped: a line of `&` grows fivefold, and a piece cut at exactly 4096
288
+ * characters then arrives at the API as 20 000 and is refused - which reads,
289
+ * from the phone, as a message that simply never came. So the pieces are
290
+ * measured after conversion and cut again against a smaller budget until
291
+ * they fit. The floor of 400 cannot overflow: the longest escape here is
292
+ * `&quot;` at six characters, so 400 can become at most 2400.
293
+ *
294
+ * Exported for the test that feeds it a body of nothing but `&`.
295
+ */
296
+ export function htmlPieces(text) {
297
+ let budget = TELEGRAM_LIMIT;
298
+ for (let attempt = 0; attempt < 4; attempt += 1) {
299
+ const pieces = splitMessage(text, budget);
300
+ const html = pieces.map(toHtml);
301
+ if (html.every((piece) => piece.length <= TELEGRAM_LIMIT))
302
+ return html;
303
+ // Re-cut against the worst growth actually seen, not a guess about it.
304
+ const growth = Math.max(...html.map((piece, index) => piece.length / Math.max(1, pieces[index]?.length ?? 1)));
305
+ budget = Math.max(400, Math.floor(TELEGRAM_LIMIT / growth));
60
306
  }
61
- if (code)
62
- out.push(`<pre>${escapeHtml(code.join('\n'))}</pre>`);
63
- return out.join('\n');
307
+ return splitMessage(text, 400).map(toHtml);
308
+ }
309
+ /**
310
+ * What a streamed message should say once the turn is over.
311
+ *
312
+ * Two texts describe the same turn and neither is the whole truth. The
313
+ * deltas are what the user actually watched being written, thinking out loud
314
+ * between tool calls included. The provider's `done` text is narrower:
315
+ * Claude Code reports its *result*, the closing answer alone, so taking it as
316
+ * the final state - which this used to do - wiped every intermediate step the
317
+ * moment the turn finished.
318
+ *
319
+ * So the streamed text stands, and the final answer is added only when it is
320
+ * not already in it. The comparison ignores whitespace, because the two
321
+ * renderings differ in line breaks far more often than in words.
322
+ *
323
+ * Exported for its own test: this is a one-line decision that costs a visible
324
+ * half of the conversation when it goes the wrong way.
325
+ */
326
+ export function mergeFinalText(streamed, finalText) {
327
+ const flat = (value) => value.replace(/\s+/g, ' ').trim();
328
+ const final = finalText.trim();
329
+ const shown = streamed.trim();
330
+ if (!final)
331
+ return shown;
332
+ if (!shown)
333
+ return final;
334
+ return flat(shown).includes(flat(final)) ? shown : shown + '\n\n' + final;
64
335
  }
65
336
  /** A sleep that neither keeps the process alive nor outlives a stop(). */
66
337
  function delay(ms, signal) {
@@ -76,12 +347,56 @@ function delay(ms, signal) {
76
347
  function errorText(error) {
77
348
  return error instanceof Error ? error.message : String(error);
78
349
  }
350
+ /** One row of a list: no line breaks, and short enough to read on a phone. */
351
+ function oneLine(text, max) {
352
+ const flat = text.replace(/\s+/g, ' ').trim();
353
+ return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
354
+ }
355
+ /** Narrow foreign JSON to an object without claiming anything about its fields. */
356
+ function asRecord(value) {
357
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
358
+ return undefined;
359
+ return value;
360
+ }
79
361
  /** The sender's username, straight out of the raw update, for the log only. */
80
362
  function usernameOf(update) {
81
363
  const message = update.message;
82
364
  const from = message?.from;
83
365
  return typeof from?.username === 'string' ? from.username : undefined;
84
366
  }
367
+ /**
368
+ * The task question a pushed message asked, if it asked one: a `question`
369
+ * notification that points at a card. Read from the store, so the registry
370
+ * only has to remember the notification's id.
371
+ */
372
+ export function questionForOrigin(context, origin) {
373
+ if ((origin.kind !== 'notification' && origin.kind !== 'mail') || !origin.ref)
374
+ return undefined;
375
+ const notification = context.assistant.store.org.getNotification(origin.ref);
376
+ if (!notification || notification.kind !== 'question' || !notification.taskId)
377
+ return undefined;
378
+ return { taskId: notification.taskId, orgId: notification.orgId };
379
+ }
380
+ /**
381
+ * Answer a waiting card as the user. Only a card that is still waiting is
382
+ * answered: a reply to a question somebody already answered in the web
383
+ * app must not start the task over.
384
+ */
385
+ export async function answerTaskQuestion(context, asked, answer) {
386
+ const task = context.assistant.store.org.getTask(asked.taskId);
387
+ if (!task)
388
+ return { ok: false, reason: 'that task no longer exists.' };
389
+ if (task.status !== 'blocked') {
390
+ return { ok: false, reason: `the task is no longer waiting for an answer (it is ${task.status}).` };
391
+ }
392
+ try {
393
+ const result = await context.assistant.org.answerTask({ taskId: task.id, answer, orgId: asked.orgId });
394
+ return result.ok ? { ok: true } : { ok: false, reason: result.reason };
395
+ }
396
+ catch (error) {
397
+ return { ok: false, reason: errorText(error) };
398
+ }
399
+ }
85
400
  export function createTelegramGateway(context) {
86
401
  const log = context.log.child('telegram');
87
402
  let api;
@@ -110,11 +425,44 @@ export function createTelegramGateway(context) {
110
425
  /** `/aus` silences the channel until the process is restarted, not until the next config write. */
111
426
  let silenced = false;
112
427
  const queues = new Map();
428
+ /** Albums still being collected, by Telegram's `media_group_id`. */
429
+ const albums = new Map();
113
430
  /** One running turn per sender, so `/stop` knows what to abort. */
114
431
  const turns = new Map();
432
+ /**
433
+ * A turn in one of this chat's conversations that nobody here typed - a
434
+ * report-back from work handed off from the phone (R3). The conversation
435
+ * remembers which chat it belongs to; its answer goes there, filed as an
436
+ * answer of that conversation so a reply to it continues it.
437
+ */
438
+ const sessionChatKey = (sessionId) => 'telegram:session:' + sessionId;
439
+ context.assistant.on('follow-up', (event) => {
440
+ if (!running || !api)
441
+ return;
442
+ const raw = context.assistant.store.getMeta(sessionChatKey(event.sessionId));
443
+ const chatId = raw ? Number(raw) : NaN;
444
+ if (!Number.isFinite(chatId))
445
+ return;
446
+ const text = event.text.trim() || (event.error ? 'Error: ' + event.error : '');
447
+ if (!text)
448
+ return;
449
+ say(chatId, text, { origin: { kind: 'answer', sessionId: event.sessionId } });
450
+ });
115
451
  /** Per chat, so two answers never race each other onto the wire. */
116
452
  const outbox = new Map();
117
453
  const idReplies = new Map();
454
+ /**
455
+ * The questions standing on this phone, keyed by question *and* chat.
456
+ *
457
+ * One question can be drawn in several chats (push has a recipient list),
458
+ * and one chat can hold more than one at a time (a scheduled turn and a
459
+ * web turn can both stop to ask). So the key is the pair, the entry
460
+ * carries the message the buttons sit under, and an entry exists exactly
461
+ * as long as the question is worth answering from here: it is written when
462
+ * the question is drawn and deleted the moment it is answered, withdrawn
463
+ * or expired.
464
+ */
465
+ const questionPosts = new Map();
118
466
  const settings = () => context.config.gateways.telegram;
119
467
  // The config is the source: `loadConfig` has already let TELEGRAM_BOT_TOKEN
120
468
  // override the stored value, so reading one place reads both.
@@ -132,23 +480,364 @@ export function createTelegramGateway(context) {
132
480
  outbox.set(chatId, next.catch(() => { }));
133
481
  return next;
134
482
  }
135
- async function deliver(chatId, text) {
483
+ async function deliver(chatId, text, options = {}) {
136
484
  const client = api;
137
485
  if (!client)
138
486
  throw new Error('The Telegram gateway is not running.');
139
- for (const piece of splitMessage(text)) {
140
- await client.sendMessage(chatId, toHtml(piece), {
487
+ const ids = [];
488
+ // Materialised, because the last piece is the one that carries the
489
+ // buttons and a generator cannot say which one that is.
490
+ const pieces = [...htmlPieces(text)];
491
+ for (const [index, piece] of pieces.entries()) {
492
+ const id = await client.sendMessage(chatId, piece, {
141
493
  parseMode: 'HTML',
142
494
  disablePreview: true,
495
+ ...(options.silent ? { silent: true } : {}),
496
+ // Only the first piece quotes the original: Telegram would otherwise
497
+ // draw the same quoted block above every part of a long answer.
498
+ ...(ids.length === 0 && options.replyTo !== undefined ? { replyTo: options.replyTo } : {}),
499
+ // And only the last one carries the buttons, so they sit at the
500
+ // bottom of the whole message rather than in the middle of it.
501
+ ...(index === pieces.length - 1 && options.keyboard ? { replyMarkup: options.keyboard } : {}),
143
502
  });
503
+ if (id !== undefined)
504
+ ids.push(id);
144
505
  }
506
+ if (options.origin)
507
+ rememberOrigin(context, chatId, ids, options.origin);
508
+ // Everything standing in the chat is written down, because `/clear`
509
+ // deletes by id and Telegram has no "delete everything".
510
+ noteMessages(context, chatId, ids);
511
+ return ids;
145
512
  }
146
513
  /** Fire-and-forget delivery: used where a failed line must not break a turn. */
147
- function say(chatId, text) {
148
- void chain(chatId, () => deliver(chatId, text)).catch((error) => {
514
+ function say(chatId, text, options = {}) {
515
+ void chain(chatId, async () => {
516
+ await deliver(chatId, text, options);
517
+ }).catch((error) => {
149
518
  log.warn('Telegram send failed', { chatId, error: errorText(error) });
150
519
  });
151
520
  }
521
+ /**
522
+ * Put a reaction on the sender's own message.
523
+ *
524
+ * Decoration, and treated as such: a Telegram that refuses the emoji, or
525
+ * an older Bot API that has never heard of reactions, must not cost the
526
+ * answer. Failures are swallowed at debug level and nothing waits for it.
527
+ */
528
+ function react(chatId, messageId, emoji) {
529
+ if (messageId === undefined)
530
+ return;
531
+ void api?.setMessageReaction(chatId, messageId, emoji).catch((error) => {
532
+ log.debug('Telegram reaction not accepted', { chatId, error: errorText(error) });
533
+ });
534
+ }
535
+ /* ---------------------------- questions ---------------------------- */
536
+ /**
537
+ * The assistant asking the person something, carried to the phone.
538
+ *
539
+ * A turn that asks is a turn that has stopped, and until now this channel
540
+ * had no way to show that - the question was raised somewhere in core and
541
+ * the phone saw a typing bubble until the question gave up. Two things make
542
+ * it answerable from here: buttons, which are the second and last exception
543
+ * to this channel's "no buttons" rule (see
544
+ * `docs/concepts/telegram-channel.md`), and a plain typed reply, which is
545
+ * what a phone is actually good at.
546
+ *
547
+ * The typed path is the one with the trap in it. A message normally becomes
548
+ * a turn and turns are serialised per sender, so an answer typed while the
549
+ * asking turn is still running would queue up *behind the very turn it
550
+ * would release*, and both would sit there until the question expired. So a
551
+ * message that answers an open question never reaches the queue. A tap has
552
+ * the same property for free: a `callback_query` is not a message and never
553
+ * was queued.
554
+ */
555
+ const postKey = (questionId, chatId) => questionId + '@' + String(chatId);
556
+ /** Is somebody being asked something in this chat right now? */
557
+ function openQuestion(chatId) {
558
+ let newest;
559
+ for (const post of questionPosts.values()) {
560
+ if (post.chatId !== chatId)
561
+ continue;
562
+ // Expired questions are cleaned up by the closing event, but a clock
563
+ // that has already passed the deadline is reason enough not to answer
564
+ // into it - core has moved the turn on by then.
565
+ if (post.question.expiresAt > 0 && post.question.expiresAt <= Date.now())
566
+ continue;
567
+ if (!newest || post.at > newest.at)
568
+ newest = post;
569
+ }
570
+ return newest;
571
+ }
572
+ /** Draw the question in one chat, unless it is already standing there. */
573
+ function offerQuestion(chatId, question, origin) {
574
+ const key = postKey(question.id, chatId);
575
+ // Claimed before anything is awaited: the turn that asked and the push
576
+ // listener both arrive within the same tick. A Telegram turn claims the
577
+ // post first, so the push that follows a heartbeat later does not
578
+ // overwrite where the card came from.
579
+ if (questionPosts.has(key))
580
+ return;
581
+ const post = { question, chatId, origin, at: Date.now() };
582
+ questionPosts.set(key, post);
583
+ void chain(chatId, async () => {
584
+ const ids = await deliver(chatId, questionText(question), { keyboard: questionKeyboard(question) });
585
+ // The buttons sit under the last piece, so that is the message a
586
+ // closing event has to rewrite.
587
+ post.messageId = ids[ids.length - 1];
588
+ }).catch((error) => {
589
+ // Undrawn means unanswerable from here: dropping the entry lets a
590
+ // later attempt try again, and keeps a typed reply from being taken
591
+ // as the answer to a question nobody ever saw.
592
+ questionPosts.delete(key);
593
+ log.warn('Telegram question could not be delivered', { chatId, error: errorText(error) });
594
+ });
595
+ }
596
+ /** Rewrite one standing question's buttons to say how it ended. */
597
+ function settlePost(post, reason, answer) {
598
+ const client = api;
599
+ if (!client || post.messageId === undefined)
600
+ return;
601
+ const keyboard = questionClosedKeyboard(reason, chosenLabels(post.question, answer));
602
+ void client.editMessageReplyMarkup(post.chatId, post.messageId, keyboard).catch((error) => {
603
+ // A stale keyboard is a cosmetic loss; the answer itself was recorded
604
+ // by the registry long before this ran.
605
+ log.debug('Telegram question buttons could not be redrawn', { error: errorText(error) });
606
+ });
607
+ }
608
+ /**
609
+ * The question is over, wherever that happened. Every chat it was drawn in
610
+ * gets its buttons rewritten - including the ones that did not answer,
611
+ * which is the whole reason the closing event exists.
612
+ */
613
+ function closeQuestion(id, reason, answer) {
614
+ for (const [key, post] of questionPosts) {
615
+ if (post.question.id !== id)
616
+ continue;
617
+ questionPosts.delete(key);
618
+ settlePost(post, reason, answer);
619
+ }
620
+ }
621
+ /**
622
+ * Hand an answer to the registry that is holding the turn. `false` when
623
+ * the registry no longer has that question - answered at another screen, or
624
+ * given up on - which is normal rather than an error.
625
+ *
626
+ * The entry is dropped first, so the closing event that follows finds
627
+ * nothing left to redraw here and this chat is not asked to rewrite the
628
+ * same buttons twice; Telegram answers a second identical edit with a 400.
629
+ */
630
+ function submitAnswer(post, answer) {
631
+ questionPosts.delete(postKey(post.question.id, post.chatId));
632
+ const taken = context.assistant.questions.answer(post.question.id, answer);
633
+ settlePost(post, taken ? 'answered' : 'gone', taken ? answer : undefined);
634
+ if (taken) {
635
+ log.info('Question answered from Telegram', {
636
+ chat: post.chatId,
637
+ question: post.question.id,
638
+ selected: answer.selected,
639
+ free: answer.text !== undefined,
640
+ });
641
+ }
642
+ return taken;
643
+ }
644
+ /**
645
+ * The single line that says what a long turn is doing.
646
+ *
647
+ * One message, rewritten in place, rather than a column of "still working"
648
+ * notes: on a phone the stack of them *is* the noise. It appears only when
649
+ * the turn has been silent for a while, is rewritten at a distance that
650
+ * stays well clear of Telegram's edit limit, and is taken away entirely
651
+ * once the answer is there - it was scaffolding, and scaffolding comes
652
+ * down.
653
+ */
654
+ function startProgress(chatId) {
655
+ let messageId;
656
+ let shown = '';
657
+ let shownAt = 0;
658
+ let closed = false;
659
+ const show = (line) => {
660
+ const text = line.trim();
661
+ if (closed || !text || text === shown)
662
+ return;
663
+ const now = Date.now();
664
+ if (messageId !== undefined && now - shownAt < PROGRESS_EDIT_MS)
665
+ return;
666
+ shown = text;
667
+ shownAt = now;
668
+ void chain(chatId, async () => {
669
+ if (closed)
670
+ return;
671
+ const client = api;
672
+ if (!client)
673
+ return;
674
+ if (messageId === undefined) {
675
+ const [id] = await deliver(chatId, text);
676
+ messageId = id;
677
+ return;
678
+ }
679
+ await client.editMessageText(chatId, messageId, toHtml(text), {
680
+ parseMode: 'HTML',
681
+ disablePreview: true,
682
+ });
683
+ }).catch((error) => {
684
+ log.debug('Telegram progress line failed', { chatId, error: errorText(error) });
685
+ });
686
+ };
687
+ const clear = () => {
688
+ closed = true;
689
+ const id = messageId;
690
+ messageId = undefined;
691
+ if (id === undefined)
692
+ return;
693
+ void chain(chatId, async () => {
694
+ await api?.deleteMessages(chatId, [id]);
695
+ }).catch((error) => {
696
+ log.debug('Telegram progress line could not be removed', { chatId, error: errorText(error) });
697
+ });
698
+ };
699
+ return { show, clear };
700
+ }
701
+ /**
702
+ * The answer, written as it is produced.
703
+ *
704
+ * Telegram has no streaming. What it has is `editMessageText`, and what
705
+ * this does is rewrite one message on a timer while the deltas come in -
706
+ * which reads, on a phone, exactly like someone typing. The timer is the
707
+ * whole design constraint: edits are rate limited per chat, so the text is
708
+ * flushed at a distance rather than per token, and only when it actually
709
+ * changed.
710
+ *
711
+ * Long answers keep working because the pieces are recomputed from the
712
+ * whole text every flush. `splitMessage` is greedy from the front, so
713
+ * every piece but the last is settled once it exists: earlier messages are
714
+ * left alone, the last one is edited, and a new one is sent when the text
715
+ * grows past it. The `done` event has the last word - whatever the deltas
716
+ * added up to, the final text is what stands.
717
+ */
718
+ function startStream(chatId, replyTo) {
719
+ /** What has been sent so far, by index: message id and the text in it. */
720
+ const ids = [];
721
+ const texts = [];
722
+ let text = '';
723
+ let writtenAt = 0;
724
+ let timer;
725
+ let writing = false;
726
+ /** A delta arrived while a write was in flight; write again afterwards. */
727
+ let again = false;
728
+ let closed = false;
729
+ async function write() {
730
+ const client = api;
731
+ if (!client)
732
+ return;
733
+ const body = text.trim();
734
+ if (!body)
735
+ return;
736
+ writtenAt = Date.now();
737
+ const pieces = htmlPieces(body);
738
+ for (let index = 0; index < pieces.length; index += 1) {
739
+ const piece = pieces[index];
740
+ if (index < ids.length) {
741
+ if (texts[index] === piece)
742
+ continue;
743
+ await client.editMessageText(chatId, ids[index], piece, {
744
+ parseMode: 'HTML',
745
+ disablePreview: true,
746
+ });
747
+ // Noted as written only once it is written. Marking it first would
748
+ // make a refused edit look like a finished one, and the next pass
749
+ // would skip exactly the piece that never arrived.
750
+ texts[index] = piece;
751
+ continue;
752
+ }
753
+ const id = await client.sendMessage(chatId, piece, {
754
+ parseMode: 'HTML',
755
+ disablePreview: true,
756
+ // Only the first message quotes what is being answered.
757
+ ...(ids.length === 0 && replyTo !== undefined ? { replyTo } : {}),
758
+ });
759
+ if (id === undefined)
760
+ return;
761
+ ids.push(id);
762
+ texts.push(piece);
763
+ noteMessages(context, chatId, [id]);
764
+ }
765
+ }
766
+ /** One writer at a time, in the chat's own order. */
767
+ function run() {
768
+ if (writing) {
769
+ // Whatever arrived during this write is not lost: it is written by
770
+ // the pass that follows it.
771
+ again = true;
772
+ return;
773
+ }
774
+ writing = true;
775
+ void chain(chatId, async () => {
776
+ await write();
777
+ })
778
+ .catch((error) => {
779
+ // A refused edit is not worth the turn: the next pass rewrites the
780
+ // same text anyway, and the answer still arrives.
781
+ log.debug('Telegram stream update failed', { chatId, error: errorText(error) });
782
+ })
783
+ .finally(() => {
784
+ writing = false;
785
+ if (again) {
786
+ again = false;
787
+ arm();
788
+ }
789
+ });
790
+ }
791
+ /**
792
+ * Make sure what has arrived gets written, and soon.
793
+ *
794
+ * The first version of this dropped a delta that arrived inside the
795
+ * throttle window and waited for the next one to carry it - which is
796
+ * fine while text keeps coming and wrong the moment it stops. A model
797
+ * that writes a sentence and then reaches for a tool falls silent for
798
+ * seconds, and the sentence sat there half-written. So the wait is a
799
+ * timer rather than a test: every delta is followed by a write, at the
800
+ * earliest the throttle allows.
801
+ */
802
+ function arm() {
803
+ if (timer || closed)
804
+ return;
805
+ // The first words go out quickly - that is the point of streaming -
806
+ // and everything after them at the slower, rate-limit-safe pace.
807
+ const wait = ids.length === 0 ? STREAM_FIRST_MS : STREAM_EDIT_MS;
808
+ const due = Math.max(0, writtenAt + wait - Date.now());
809
+ timer = setTimeout(() => {
810
+ timer = undefined;
811
+ run();
812
+ }, due);
813
+ timer.unref?.();
814
+ }
815
+ return {
816
+ started: () => ids.length > 0,
817
+ push(delta) {
818
+ if (closed)
819
+ return;
820
+ text += delta;
821
+ arm();
822
+ },
823
+ async finish(finalText) {
824
+ closed = true;
825
+ if (timer)
826
+ clearTimeout(timer);
827
+ timer = undefined;
828
+ // The streamed text stands, and the provider's closing answer is
829
+ // added only when it is not already part of it. The reasoning, and
830
+ // the bug it repairs, are with `mergeFinalText`.
831
+ text = mergeFinalText(text, finalText);
832
+ await chain(chatId, async () => {
833
+ await write();
834
+ }).catch((error) => {
835
+ log.warn('Telegram stream could not be finished', { chatId, error: errorText(error) });
836
+ });
837
+ return ids;
838
+ },
839
+ };
840
+ }
152
841
  /* --------------------------- sessions --------------------------- */
153
842
  /**
154
843
  * The conversation behind a chat. Deliberately an ordinary `chat` session
@@ -201,6 +890,169 @@ export function createTelegramGateway(context) {
201
890
  : 'Last sleep run: none yet');
202
891
  return lines.join('\n');
203
892
  }
893
+ /** The command list as `/help` prints it, out of the one table above. */
894
+ function helpText() {
895
+ const rows = COMMANDS.map((entry) => `/${entry.command} – ${entry.description}`);
896
+ return ['What I answer to:', '', ...rows].join('\n');
897
+ }
898
+ /** One organisation, or nothing to report from. */
899
+ function orgId() {
900
+ try {
901
+ return context.assistant.org.activeOrganization().id;
902
+ }
903
+ catch {
904
+ return undefined;
905
+ }
906
+ }
907
+ /** "in 3 h 20 min", "12 min ago" - a clock reading nobody has to subtract. */
908
+ function relativeTime(at) {
909
+ if (!at)
910
+ return '';
911
+ const delta = at - Date.now();
912
+ const minutes = Math.round(Math.abs(delta) / 60_000);
913
+ const text = minutes < 60
914
+ ? `${minutes} min`
915
+ : minutes < 60 * 48
916
+ ? `${Math.round(minutes / 60)} h`
917
+ : `${Math.round(minutes / (60 * 24))} d`;
918
+ return delta >= 0 ? `in ${text}` : `${text} ago`;
919
+ }
920
+ /** A list command's body, with the same shape for all four of them. */
921
+ function listText(title, rows, empty, total = rows.length) {
922
+ if (rows.length === 0)
923
+ return empty;
924
+ const shown = rows.slice(0, LIST_LIMIT);
925
+ const rest = total - shown.length;
926
+ return [title, '', ...shown, ...(rest > 0 ? ['', `… and ${rest} more. The web app has the rest.`] : [])].join('\n');
927
+ }
928
+ function tasksText() {
929
+ const id = orgId();
930
+ if (!id)
931
+ return 'No company is configured yet.';
932
+ const open = context.assistant.store.org.listTasks(id, {
933
+ status: ['running', 'planned', 'open', 'failed'],
934
+ limit: 40,
935
+ });
936
+ // Running first, then what is planned, then the rest: the order someone
937
+ // looking at a phone actually wants.
938
+ const rank = { running: 0, failed: 1, planned: 2, open: 3 };
939
+ const sorted = [...open].sort((a, b) => (rank[a.status] ?? 9) - (rank[b.status] ?? 9));
940
+ const rows = sorted.map((task) => {
941
+ const who = task.assigneeId ? context.assistant.store.org.getAgent(task.assigneeId)?.name : undefined;
942
+ const mark = task.priority === 'high' ? '❗ ' : '';
943
+ return `• ${mark}${oneLine(task.title, 70)} – ${task.status}${who ? `, ${who}` : ''}`;
944
+ });
945
+ // "Unfinished" rather than "open": a failed task is on this list too,
946
+ // and it is the one most worth seeing from a phone.
947
+ return listText(`Board: ${open.length} unfinished`, rows, 'Nothing open on the board.', open.length);
948
+ }
949
+ function inboxText() {
950
+ const id = orgId();
951
+ if (!id)
952
+ return 'No company is configured yet.';
953
+ // Read without marking read: this is a glance at the inbox, not the act
954
+ // of reading a notification, and the web inbox must not go quiet because
955
+ // of it.
956
+ const store = context.assistant.store.org;
957
+ const total = store.unreadNotificationCount(id);
958
+ const unread = store.listNotifications({ orgId: id, unread: true, limit: LIST_LIMIT });
959
+ const rows = unread.map((notification) => `• ${oneLine(notification.title, 70)} – ${notification.kind} (${relativeTime(notification.createdAt)})`);
960
+ return listText(`Inbox: ${total} unread`, rows, 'No unread notifications.', total);
961
+ }
962
+ function agentsText() {
963
+ const id = orgId();
964
+ if (!id)
965
+ return 'No company is configured yet.';
966
+ const agents = context.assistant.store.org.listAgents(id);
967
+ const running = context.assistant.store.org.listAssignments(id, { status: ['running'], limit: 50 });
968
+ const busy = new Map();
969
+ for (const assignment of running)
970
+ busy.set(assignment.agentId, (busy.get(assignment.agentId) ?? 0) + 1);
971
+ const rows = agents.map((agent) => {
972
+ const load = busy.get(agent.id);
973
+ return `• ${agent.name} – ${oneLine(agent.title, 50)}${load ? ` (busy: ${load})` : ''}`;
974
+ });
975
+ return listText(`Company: ${agents.length} agents`, rows, 'Nobody works here yet.', agents.length);
976
+ }
977
+ function schedulesText() {
978
+ const id = orgId();
979
+ if (!id)
980
+ return 'No company is configured yet.';
981
+ const jobs = context.assistant.cron.list(id);
982
+ const upcoming = [...jobs].sort((a, b) => (a.nextRunAt ?? Infinity) - (b.nextRunAt ?? Infinity));
983
+ const rows = upcoming.map((job) => {
984
+ const when = job.enabled ? (job.nextRunAt ? relativeTime(job.nextRunAt) : 'not scheduled') : 'off';
985
+ const last = job.lastStatus ? `, last ${job.lastStatus}` : '';
986
+ return `• ${oneLine(job.name, 50)} – ${job.schedule}, ${when}${last}`;
987
+ });
988
+ return listText(`Schedules: ${jobs.length}`, rows, 'No schedules are set up.', jobs.length);
989
+ }
990
+ /**
991
+ * Empty the chat and start over.
992
+ *
993
+ * "As if writing the bot for the first time" is the whole point, so this
994
+ * deletes the messages themselves rather than only opening a new
995
+ * conversation.
996
+ *
997
+ * It does not delete only what the gateway happens to remember. That was
998
+ * the first attempt, and it cleared two messages out of a full chat: the
999
+ * ledger starts at the last restart, while the chat goes back as far as it
1000
+ * goes. Message ids are a per-chat counter, so the way to reach a message
1001
+ * nobody wrote down is to count backwards from the newest one and hand
1002
+ * Telegram the whole range - it skips every id that is not there, already
1003
+ * gone, or past its 48-hour deletion window. The ledger is still read, for
1004
+ * the one thing a range cannot supply: where to start counting when the
1005
+ * newest id is unknown.
1006
+ *
1007
+ * What stays is what Telegram will not part with: anything older than 48
1008
+ * hours. The answer says so rather than claiming an empty chat.
1009
+ *
1010
+ * The conversation itself is kept. It stays in the web app's sidebar with
1011
+ * everything that was said in it - the chat is cleared, the memory of it
1012
+ * is not.
1013
+ */
1014
+ async function clearChat(chatId, commandMessageId) {
1015
+ const client = api;
1016
+ const known = takeMessages(context, chatId);
1017
+ const newest = Math.max(commandMessageId ?? 0, ...known, 0);
1018
+ let swept = 0;
1019
+ if (client && newest > 0) {
1020
+ // Downwards from the newest, so a flood limit that cuts this short
1021
+ // takes what is on screen first.
1022
+ for (let top = newest; top > 0 && newest - top < CLEAR_SWEEP; top -= 100) {
1023
+ const batch = [];
1024
+ for (let id = top; id > 0 && id > top - 100 && newest - id < CLEAR_SWEEP; id -= 1)
1025
+ batch.push(id);
1026
+ if (batch.length === 0)
1027
+ break;
1028
+ try {
1029
+ await client.deleteMessages(chatId, batch);
1030
+ swept += batch.length;
1031
+ }
1032
+ catch (error) {
1033
+ // A batch Telegram refuses outright - every id in it too old - is
1034
+ // not a reason to stop: further down is only older, but further up
1035
+ // may still hold something deletable in a chat with gaps.
1036
+ log.debug('Telegram delete batch refused', { chatId, error: errorText(error) });
1037
+ }
1038
+ }
1039
+ }
1040
+ const session = resolveSession(chatId, true);
1041
+ log.info('Telegram chat cleared', { chatId, swept, newest, sessionId: session.id });
1042
+ // One line on an empty screen, which is the whole point of the command.
1043
+ // The footnote about Telegram's 48 hours is true every time and worth
1044
+ // reading once, so it comes with the first clear in a chat and never
1045
+ // again - an explanation repeated on every use stops being read and
1046
+ // starts being clutter.
1047
+ const noticeKey = `telegram:clear-notice:${chatId}`;
1048
+ const explained = context.assistant.store.getMeta(noticeKey) !== null;
1049
+ if (!explained)
1050
+ context.assistant.store.setMeta(noticeKey, String(Date.now()));
1051
+ say(chatId, explained
1052
+ ? '✨ Fresh start.'
1053
+ : '✨ Fresh start — the old conversation is kept in the web app.\n' +
1054
+ 'Telegram lets me delete only the last 48 hours; for anything older: hold the chat → Clear History.');
1055
+ }
204
1056
  /** Returns true when the message was a command and is fully dealt with. */
205
1057
  async function handleCommand(verdict) {
206
1058
  const chatId = verdict.chatId;
@@ -211,8 +1063,14 @@ export function createTelegramGateway(context) {
211
1063
  case 'start':
212
1064
  say(chatId, `Hello, this is ${context.config.assistantName}. Send a message and I will reply in ` +
213
1065
  'the same conversation you can access in the browser.\n\n' +
214
- '/new new conversation, /stop cancel the current turn, /status current state, ' +
215
- '/id your user ID, /off silence the gateway until restart.');
1066
+ 'Voice messages are transcribed, and photos and documents are read. ' +
1067
+ 'Reply to one of my notifications and I will answer about that notification, ' +
1068
+ 'in a conversation of its own, rather than about whatever we last discussed.\n\n' +
1069
+ helpText());
1070
+ return true;
1071
+ case 'help':
1072
+ case 'hilfe':
1073
+ say(chatId, helpText());
216
1074
  return true;
217
1075
  case 'new':
218
1076
  case 'neu': {
@@ -221,6 +1079,27 @@ export function createTelegramGateway(context) {
221
1079
  say(chatId, 'New conversation created. The previous one is preserved.');
222
1080
  return true;
223
1081
  }
1082
+ case 'clear':
1083
+ await clearChat(chatId, verdict.messageId);
1084
+ return true;
1085
+ case 'tasks':
1086
+ say(chatId, tasksText());
1087
+ return true;
1088
+ case 'inbox':
1089
+ say(chatId, inboxText());
1090
+ return true;
1091
+ // Mail was folded into notifications; the old command still works and
1092
+ // says where it went.
1093
+ case 'mail':
1094
+ say(chatId, '/mail is now /inbox.\n\n' + inboxText());
1095
+ return true;
1096
+ case 'agents':
1097
+ say(chatId, agentsText());
1098
+ return true;
1099
+ case 'schedules':
1100
+ case 'cron':
1101
+ say(chatId, schedulesText());
1102
+ return true;
224
1103
  case 'stop': {
225
1104
  const turn = turns.get(userId);
226
1105
  // The turn itself reports "Cancelled." on its way out, so this
@@ -247,67 +1126,314 @@ export function createTelegramGateway(context) {
247
1126
  });
248
1127
  return true;
249
1128
  default:
250
- say(chatId, 'Unknown command. Available commands: /start, /new, /stop, /status, /id and /off.');
1129
+ say(chatId, 'I do not know that one.\n\n' + helpText());
251
1130
  return true;
252
1131
  }
253
1132
  }
1133
+ /** How a file is named in the line the assistant is handed. */
1134
+ const KIND_LABEL = {
1135
+ photo: 'A photo',
1136
+ voice: 'A voice message',
1137
+ audio: 'An audio file',
1138
+ video: 'A video',
1139
+ video_note: 'A video note',
1140
+ animation: 'An animation',
1141
+ document: 'A document',
1142
+ sticker: 'A sticker',
1143
+ };
1144
+ /**
1145
+ * Whether a turn would end up listening locally, and so might have to wait
1146
+ * for a model to be fetched. Read fresh: a key added on the voice page
1147
+ * takes effect on the next voice note, not on the next restart.
1148
+ */
1149
+ function listensLocally(config) {
1150
+ if (config.transcribe === 'local')
1151
+ return true;
1152
+ if (config.transcribe !== 'auto')
1153
+ return false;
1154
+ const keys = voiceKeys(context.config.home);
1155
+ return !keys.openai && !keys.elevenlabs;
1156
+ }
1157
+ /**
1158
+ * Fetch, store and, where there is something to hear, transcribe.
1159
+ *
1160
+ * Every failure here is reported rather than thrown: one unreadable file
1161
+ * out of three must not cost the other two, and a photo that could not be
1162
+ * downloaded is something the assistant should be able to say out loud
1163
+ * instead of answering a question it never saw.
1164
+ */
1165
+ async function takeIn(job, signal) {
1166
+ const config = settings();
1167
+ const intake = { lines: [], transcripts: [], saved: 0 };
1168
+ const client = api;
1169
+ if (!client || job.attachments.length === 0)
1170
+ return intake;
1171
+ const maxBytes = Math.min(Math.max(1, config.maxAttachmentMb), 20) * 1024 * 1024;
1172
+ let announcedColdStart = false;
1173
+ for (const attachment of job.attachments.slice(0, MAX_ATTACHMENTS)) {
1174
+ const label = KIND_LABEL[attachment.kind] ?? 'A file';
1175
+ try {
1176
+ const file = await client.getFile(attachment.fileId, signal);
1177
+ if (!file.path) {
1178
+ intake.lines.push(`${label} was sent, but Telegram would not hand the file over.`);
1179
+ continue;
1180
+ }
1181
+ const bytes = await client.downloadFile(file.path, { maxBytes, signal });
1182
+ const stored = saveAttachment(context.config.workspace, attachment, bytes);
1183
+ intake.saved += 1;
1184
+ const size = humanSize(stored.bytes);
1185
+ const named = attachment.fileName ? ` named “${attachment.fileName}”` : '';
1186
+ if (isAudible(attachment) && config.transcribe !== 'off') {
1187
+ const length = humanDuration(attachment.duration);
1188
+ // The local model is fetched once, and that once takes about a
1189
+ // minute on a normal line. Saying so beats a silence that looks
1190
+ // like a bot which stopped working.
1191
+ if (!announcedColdStart && listensLocally(config) && !localModelReady(config.transcribeModel)) {
1192
+ announcedColdStart = true;
1193
+ say(job.chatId, 'Listening. The speech model is being downloaded once, which takes a minute.');
1194
+ }
1195
+ try {
1196
+ const result = await transcribe({
1197
+ audio: bytes,
1198
+ mime: attachment.mime,
1199
+ fileName: attachment.fileName,
1200
+ engine: config.transcribe,
1201
+ model: config.transcribeModel,
1202
+ lang: context.config.voice.lang,
1203
+ home: context.config.home,
1204
+ signal,
1205
+ });
1206
+ intake.transcripts.push(result.text);
1207
+ intake.lines.push(`${label}${length ? ` (${length})` : ''}, transcribed by ${result.engine}; the wording may be` +
1208
+ ` imperfect. The audio itself is at ${stored.path}.`);
1209
+ // Echoed back, because a transcript nobody can check is a
1210
+ // misheard sentence the assistant answers with a straight face.
1211
+ const echo = result.text.length > TRANSCRIPT_ECHO ? result.text.slice(0, TRANSCRIPT_ECHO) + ' …' : result.text;
1212
+ say(job.chatId, '🎤 ' + echo);
1213
+ log.info('Telegram voice note transcribed', {
1214
+ from: job.userId,
1215
+ engine: result.engine,
1216
+ ms: result.ms,
1217
+ chars: result.text.length,
1218
+ });
1219
+ }
1220
+ catch (error) {
1221
+ const reason = error instanceof SttError ? error.message : errorText(error);
1222
+ intake.lines.push(`${label}${length ? ` (${length})` : ''} could not be transcribed: ${reason} The audio is at ${stored.path}.`);
1223
+ log.warn('Telegram transcription failed', { from: job.userId, error: reason });
1224
+ }
1225
+ continue;
1226
+ }
1227
+ switch (attachment.kind) {
1228
+ case 'photo':
1229
+ case 'sticker':
1230
+ intake.lines.push(`${label} (${size}) is at ${stored.path}. Open it with your file-reading tool before you answer; you can see images.`);
1231
+ break;
1232
+ case 'video':
1233
+ case 'video_note':
1234
+ case 'animation':
1235
+ intake.lines.push(`${label} (${size}) is at ${stored.path}.`);
1236
+ break;
1237
+ default:
1238
+ intake.lines.push(`${label}${named} (${size}) is at ${stored.path}. Open it before you answer.`);
1239
+ }
1240
+ }
1241
+ catch (error) {
1242
+ const reason = error instanceof TelegramApiError ? error.message : errorText(error);
1243
+ intake.lines.push(`${label} could not be taken in: ${reason}`);
1244
+ log.warn('Telegram attachment failed', { from: job.userId, kind: attachment.kind, error: reason });
1245
+ }
1246
+ }
1247
+ if (job.attachments.length > MAX_ATTACHMENTS) {
1248
+ intake.lines.push(`${job.attachments.length - MAX_ATTACHMENTS} further file(s) in this batch were not taken in.`);
1249
+ }
1250
+ return intake;
1251
+ }
1252
+ /**
1253
+ * The prompt for a turn that arrived with files, a quoted notification, or
1254
+ * both.
1255
+ *
1256
+ * Everything the assistant did not write itself is introduced as what it
1257
+ * is: the user's own words stand as they are, a transcript says that it is
1258
+ * a transcript, and a quoted notification is fenced off with a line saying
1259
+ * where it ends. None of it is trusted less for that - it is all the
1260
+ * owner's own material - but a turn that cannot tell a notification apart from an
1261
+ * instruction is a turn that will eventually follow the notification.
1262
+ */
1263
+ function buildPrompt(job, intake, quoted) {
1264
+ const parts = [];
1265
+ if (quoted) {
1266
+ parts.push('The user is replying on Telegram to this notification from Rookery:\n\n' +
1267
+ quoted +
1268
+ '\n\n--- end of the notification; their reply follows ---');
1269
+ }
1270
+ if (intake.lines.length > 0) {
1271
+ parts.push('Sent from Telegram:\n' + intake.lines.map((line) => '- ' + line).join('\n'));
1272
+ }
1273
+ for (const transcript of intake.transcripts) {
1274
+ parts.push('What they said:\n"' + transcript + '"');
1275
+ }
1276
+ const written = job.text?.trim();
1277
+ if (written)
1278
+ parts.push(intake.transcripts.length > 0 || intake.lines.length > 0 ? 'What they wrote with it:\n' + written : written);
1279
+ // A file with nothing said about it is still a request: look at this.
1280
+ if (parts.length === 0 || (!written && intake.transcripts.length === 0)) {
1281
+ parts.push('They sent this without saying anything. Look at it and say what you make of it.');
1282
+ }
1283
+ return parts.join('\n\n');
1284
+ }
254
1285
  /* ----------------------------- turns ----------------------------- */
255
- async function runTurn(userId, chatId, text) {
1286
+ async function runTurn(job) {
256
1287
  const config = settings();
257
- const session = resolveSession(chatId);
258
- log.info('Telegram message accepted', {
259
- from: userId,
260
- sessionId: session.id,
261
- permission: config.permission,
262
- text: text.slice(0, AUDIT_TEXT),
263
- });
1288
+ const { userId, chatId } = job;
264
1289
  const turn = new AbortController();
265
1290
  turns.set(userId, turn);
266
1291
  const typing = setInterval(() => {
1292
+ // Not while the turn is waiting on an answer: a typing bubble over an
1293
+ // open question claims the machine is busy when it is the person who
1294
+ // is being waited for.
1295
+ if (openQuestion(chatId))
1296
+ return;
267
1297
  void api?.sendChatAction(chatId, 'typing').catch(() => { });
268
1298
  }, TYPING_INTERVAL_MS);
269
1299
  typing.unref?.();
270
1300
  void api?.sendChatAction(chatId, 'typing').catch(() => { });
271
- let noteAt = 0;
272
- const note = (line) => {
273
- noteAt = Date.now();
274
- say(chatId, line);
275
- };
1301
+ // Seen, and being worked on. A reaction says that without adding a
1302
+ // message to a chat the answer is about to land in anyway.
1303
+ react(chatId, job.messageId, REACTION.working);
276
1304
  // Nothing to show yet is the normal state of a long turn; without a sign
277
- // of life the phone looks broken. Only when the turn has said nothing at
278
- // all so far - an error line is a sign of life too.
279
- const firstNote = setTimeout(() => {
280
- if (noteAt === 0)
281
- note('Still working on it ...');
282
- }, FIRST_NOTE_MS);
1305
+ // of life the phone looks broken. One line, rewritten as the turn moves
1306
+ // on, and gone once the answer is there.
1307
+ const openedAt = Date.now();
1308
+ const progress = startProgress(chatId);
1309
+ const firstNote = setTimeout(() => progress.show('Working on it …'), FIRST_NOTE_MS);
283
1310
  firstNote.unref?.();
284
1311
  let answer = '';
1312
+ let failed = false;
1313
+ // Set inside the try, so a failure on the way in still runs through the
1314
+ // one `finally` that stops the typing bubble and the progress timer.
1315
+ let session;
1316
+ let origin;
1317
+ let stream;
1318
+ // Set when the message turned out to be the answer to a task's question
1319
+ // and was handed to the card instead of a turn.
1320
+ let answeredTask = false;
285
1321
  try {
1322
+ // Files first: downloading and listening is part of the turn, and the
1323
+ // typing bubble and the progress note above already cover the wait.
1324
+ const intake = await takeIn(job, turn.signal);
1325
+ // Where this belongs. A reply to something the bot sent goes back to
1326
+ // whatever that message was about; everything else is the running
1327
+ // Telegram conversation, exactly as before.
1328
+ origin = job.replyTo?.fromBot === true ? findOrigin(context, chatId, job.replyTo.messageId) : undefined;
1329
+ // A reply to an agent's question is the answer, not a conversation:
1330
+ // it goes onto the card and the task carries on, and no chat turn is
1331
+ // started about it.
1332
+ const asked = origin ? questionForOrigin(context, origin) : undefined;
1333
+ if (asked) {
1334
+ answeredTask = true;
1335
+ const text = [job.text?.trim() ?? '', ...intake.transcripts].filter((part) => part.length > 0).join('\n\n');
1336
+ if (!text) {
1337
+ say(chatId, 'Write the answer as text (or say it in a voice message) to answer that question.', {
1338
+ ...(job.messageId !== undefined ? { replyTo: job.messageId } : {}),
1339
+ });
1340
+ failed = true;
1341
+ }
1342
+ else {
1343
+ const result = await answerTaskQuestion(context, asked, text);
1344
+ failed = !result.ok;
1345
+ log.info('Telegram reply answered a task question', {
1346
+ from: userId,
1347
+ task: asked.taskId,
1348
+ ok: result.ok,
1349
+ });
1350
+ say(chatId, result.ok ? 'Answered — the task continues.' : `Could not answer: ${result.reason}`, {
1351
+ ...(job.messageId !== undefined ? { replyTo: job.messageId } : {}),
1352
+ });
1353
+ }
1354
+ return;
1355
+ }
1356
+ const thread = origin
1357
+ ? openThread(context, origin, () => resolveSession(chatId))
1358
+ : { session: resolveSession(chatId), fresh: false };
1359
+ session = thread.session;
1360
+ // Whatever answers in this conversation later without being asked
1361
+ // here - a report-back - knows where to find this chat.
1362
+ context.assistant.store.setMeta(sessionChatKey(session.id), String(chatId));
1363
+ // The notification itself goes in front of the turn only when this
1364
+ // conversation has not seen it yet. A thread being continued already
1365
+ // holds it in its history, and repeating it every time would push the
1366
+ // actual exchange out of the window. A notice that never had a record
1367
+ // is the exception: there is nothing to read back, so its own text is
1368
+ // all the context there will ever be.
1369
+ const quoted = origin
1370
+ ? thread.fresh
1371
+ ? originContext(context, origin)
1372
+ : origin.ref
1373
+ ? undefined
1374
+ : origin.snippet
1375
+ : undefined;
1376
+ const prompt = buildPrompt(job, intake, quoted);
1377
+ log.info('Telegram message accepted', {
1378
+ from: userId,
1379
+ sessionId: session.id,
1380
+ permission: config.permission,
1381
+ attachments: intake.saved,
1382
+ spoken: intake.transcripts.length,
1383
+ replyingTo: origin?.kind,
1384
+ thread: thread.fresh ? 'new' : 'continued',
1385
+ text: prompt.slice(0, AUDIT_TEXT),
1386
+ });
1387
+ // A streamed answer quotes what it answers on its first message, the
1388
+ // way a whole one would.
1389
+ stream = config.stream
1390
+ ? startStream(chatId, origin && job.messageId !== undefined ? job.messageId : undefined)
1391
+ : undefined;
286
1392
  for await (const event of context.assistant.chat({
287
- text,
1393
+ text: prompt,
288
1394
  sessionId: session.id,
289
1395
  permission: config.permission,
290
1396
  model: config.model,
291
1397
  signal: turn.signal,
292
1398
  })) {
293
- if (event.type === 'done') {
1399
+ if (event.type === 'text') {
1400
+ if (!stream)
1401
+ continue;
1402
+ // The progress line was standing in for an answer that had not
1403
+ // started. It has started.
1404
+ progress.clear();
1405
+ stream.push(event.delta);
1406
+ }
1407
+ else if (event.type === 'done') {
294
1408
  answer = event.text;
295
1409
  }
296
1410
  else if (event.type === 'error') {
297
1411
  // Never swallowed: an error the user does not see is an answer that
298
1412
  // simply never arrives.
1413
+ failed = true;
299
1414
  say(chatId, `Error: ${event.message}`);
300
- noteAt = Date.now();
301
1415
  }
302
- else if (event.type === 'status' && noteAt > 0) {
303
- if (Date.now() - noteAt >= NOTE_INTERVAL_MS) {
304
- note(event.detail ? `${event.label} – ${event.detail}` : event.label);
305
- }
1416
+ else if (event.type === 'question') {
1417
+ // The turn has stopped and is waiting on a person. Whatever the
1418
+ // progress line last claimed it was doing, it is not doing that.
1419
+ progress.clear();
1420
+ // Idempotent: push may put the same question here in the same tick,
1421
+ // because it cannot know this turn came from the phone.
1422
+ offerQuestion(chatId, event, 'turn');
1423
+ }
1424
+ else if (event.type === 'question-closed') {
1425
+ closeQuestion(event.id, event.reason, event.answer);
1426
+ }
1427
+ else if (event.type === 'status' && Date.now() - openedAt >= FIRST_NOTE_MS) {
1428
+ // Only once the turn has been quiet long enough to worry about;
1429
+ // the line itself then rewrites at its own pace.
1430
+ progress.show(event.detail ? `${event.label} – ${event.detail}` : event.label);
306
1431
  }
307
1432
  }
308
1433
  }
309
1434
  catch (error) {
310
1435
  if (!turn.signal.aborted) {
1436
+ failed = true;
311
1437
  log.error('Telegram turn failed', { from: userId, error: errorText(error) });
312
1438
  say(chatId, `Error: ${errorText(error)}`);
313
1439
  }
@@ -315,15 +1441,51 @@ export function createTelegramGateway(context) {
315
1441
  finally {
316
1442
  clearTimeout(firstNote);
317
1443
  clearInterval(typing);
1444
+ progress.clear();
318
1445
  if (turns.get(userId) === turn)
319
1446
  turns.delete(userId);
320
1447
  }
321
- if (turn.signal.aborted)
1448
+ if (answeredTask) {
1449
+ react(chatId, job.messageId, failed ? REACTION.failed : REACTION.done);
1450
+ return;
1451
+ }
1452
+ // Whatever was streamed is written out one last time, cancelled turns
1453
+ // included: half an answer that stands is better than half an answer
1454
+ // that is quietly wound back.
1455
+ const streamed = stream ? await stream.finish(answer) : [];
1456
+ if (turn.signal.aborted) {
1457
+ react(chatId, job.messageId, REACTION.failed);
322
1458
  say(chatId, 'Cancelled.');
323
- else if (answer.trim().length > 0)
324
- say(chatId, answer);
325
- else
326
- say(chatId, 'No answer was returned.');
1459
+ return;
1460
+ }
1461
+ react(chatId, job.messageId, failed ? REACTION.failed : REACTION.done);
1462
+ // The answer carries its own origin: replying to it comes back to this
1463
+ // conversation, whichever one it turned out to be. That is what lets a
1464
+ // thread continue days later, and what keeps a reply to an old answer
1465
+ // out of today's chat.
1466
+ const answered = {
1467
+ origin: {
1468
+ kind: 'answer',
1469
+ ...(session ? { sessionId: session.id } : {}),
1470
+ ...(origin?.title ? { title: origin.title } : {}),
1471
+ },
1472
+ // Quote the message being answered when this turn belongs to a thread
1473
+ // of its own, so the phone shows which of the day's notifications it
1474
+ // is about. In the plain chat the quoted line would only be noise.
1475
+ ...(origin && job.messageId !== undefined ? { replyTo: job.messageId } : {}),
1476
+ };
1477
+ if (streamed.length > 0) {
1478
+ // The answer is already on the screen. What is left is filing it, so
1479
+ // that a reply to it finds its way back to this conversation.
1480
+ if (answered.origin)
1481
+ rememberOrigin(context, chatId, streamed, answered.origin);
1482
+ }
1483
+ else if (answer.trim().length > 0) {
1484
+ say(chatId, answer, answered);
1485
+ }
1486
+ else {
1487
+ say(chatId, 'No answer was returned.', answered);
1488
+ }
327
1489
  }
328
1490
  /* ---------------------------- dispatch ---------------------------- */
329
1491
  function enqueue(userId, job) {
@@ -344,9 +1506,160 @@ export function createTelegramGateway(context) {
344
1506
  });
345
1507
  return true;
346
1508
  }
1509
+ /**
1510
+ * What an allowed sender is told when their own message was refused.
1511
+ *
1512
+ * Every reason in here is one the guard can only reach *after* the
1513
+ * allowlist has said yes, in the sender's own private chat - so the
1514
+ * silence that protects the bot from strangers buys nothing here, and
1515
+ * costs the owner a message that seems to vanish. Everything else stays
1516
+ * silent, `not_private` included: a word in a group chat is exactly what
1517
+ * the guard refused to allow.
1518
+ */
1519
+ const REJECTION_NOTE = {
1520
+ forwarded: 'Forwarded messages are not accepted - they carry someone else\'s words. Send the text or the file yourself.',
1521
+ media_off: 'Attachments are switched off for this gateway. You can turn them on in the gateway settings.',
1522
+ unsupported_media: 'Animated and video stickers cannot be read.',
1523
+ too_large: 'That file is larger than this gateway accepts.',
1524
+ too_long: 'That message is too long. Shorten it, or send it as a file.',
1525
+ no_content: 'There was nothing in that message I can work with.',
1526
+ };
1527
+ /**
1528
+ * A tap on one of a question's options.
1529
+ *
1530
+ * The button is only trusted as far as the entry behind it: the index has
1531
+ * to name an option of a question this chat is actually holding open. A
1532
+ * question that has since been answered elsewhere, or expired, has no entry
1533
+ * any more - and says so, rather than writing into a turn that has long
1534
+ * since moved on.
1535
+ */
1536
+ async function answerFromTap(questionId, option, chatId, acknowledge) {
1537
+ const post = chatId === undefined ? undefined : questionPosts.get(postKey(questionId, chatId));
1538
+ if (!post) {
1539
+ await acknowledge('That question is no longer open.');
1540
+ return;
1541
+ }
1542
+ const chosen = post.question.options[option];
1543
+ if (!chosen) {
1544
+ await acknowledge('That option is gone.');
1545
+ return;
1546
+ }
1547
+ const taken = submitAnswer(post, { selected: [option], source: 'telegram', at: Date.now() });
1548
+ await acknowledge(taken ? '✓ ' + oneLine(chosen.label, 60) : 'That question is no longer open.');
1549
+ }
1550
+ /**
1551
+ * A tapped button: the one gesture on Telegram that means "I have read
1552
+ * this", and the only one there can be.
1553
+ *
1554
+ * The Bot API has no read receipts - a bot never learns that its message
1555
+ * was looked at. So being read is not observed here, it is *declared*, by
1556
+ * a deliberate tap, and only that tap marks the notification read in the
1557
+ * store the web inbox reads from. Anything softer (the push having been
1558
+ * delivered, a glance at `/inbox`) would empty the unread list without
1559
+ * anybody having read a word, which is the failure mode `/inbox` already
1560
+ * avoids on purpose.
1561
+ *
1562
+ * No turn is started and no model is called: this is a database write and
1563
+ * an acknowledgement, the same weight as the four reading commands.
1564
+ */
1565
+ async function handleCallback(update) {
1566
+ const verdict = classifyCallback(update, settings());
1567
+ lastEventAt = Date.now();
1568
+ const client = api;
1569
+ const { callbackId, chatId, messageId, data } = verdict;
1570
+ // Acknowledged even when refused: an unanswered tap spins on the phone
1571
+ // for a minute, and a stranger learns nothing from a silent button.
1572
+ const acknowledge = async (text) => {
1573
+ if (!client || !callbackId)
1574
+ return;
1575
+ try {
1576
+ await client.answerCallbackQuery(callbackId, text);
1577
+ }
1578
+ catch (error) {
1579
+ log.debug('Telegram callback could not be acknowledged', { error: errorText(error) });
1580
+ }
1581
+ };
1582
+ if (!verdict.ok) {
1583
+ log.warn('Telegram callback rejected', { from: verdict.userId, reason: verdict.reason });
1584
+ await acknowledge();
1585
+ return;
1586
+ }
1587
+ // What the tap meant, read back through the one vocabulary in core. The
1588
+ // data is never believed because of what it says - the guard above has
1589
+ // already proved who pressed it.
1590
+ const action = readCallbackData(data);
1591
+ if (action.kind === 'notification-read-done' || action.kind === 'mail-read-done') {
1592
+ await acknowledge('Already marked as read.');
1593
+ return;
1594
+ }
1595
+ if (action.kind === 'question-done') {
1596
+ await acknowledge('That question is already settled.');
1597
+ return;
1598
+ }
1599
+ if (action.kind === 'question') {
1600
+ await answerFromTap(action.questionId, action.option, chatId, acknowledge);
1601
+ return;
1602
+ }
1603
+ const store = context.assistant.store.org;
1604
+ if (action.kind === 'mail-read') {
1605
+ // A button under a mail pushed before mail was removed. The migration
1606
+ // kept the mail's id for the notification it became, so the tap still
1607
+ // lands where it should when that notification is there; otherwise
1608
+ // there is nothing left to mark.
1609
+ const migrated = action.mailId ? store.getNotification(action.mailId) : null;
1610
+ if (migrated && !migrated.readAt) {
1611
+ store.markNotificationsRead([migrated.id]);
1612
+ context.assistant.emit('changed', { kind: 'notifications', id: 'all' });
1613
+ }
1614
+ await acknowledge('Already handled.');
1615
+ return;
1616
+ }
1617
+ if (action.kind !== 'notification-read') {
1618
+ // A button from an older version of this code, or one we no longer
1619
+ // draw. Saying so beats leaving the phone to guess.
1620
+ await acknowledge('This button no longer does anything.');
1621
+ return;
1622
+ }
1623
+ const notification = action.notificationId ? store.getNotification(action.notificationId) : null;
1624
+ if (!notification) {
1625
+ await acknowledge('That notification is gone.');
1626
+ return;
1627
+ }
1628
+ store.markNotificationsRead([notification.id]);
1629
+ // The web inbox follows the socket, so it has to hear about this - on
1630
+ // `changed`, never on `notification`: push listens to that one and would
1631
+ // send the very notification that was just marked read straight back.
1632
+ context.assistant.emit('changed', { kind: 'notifications', id: 'all' });
1633
+ log.info('Notification marked read from Telegram', { from: verdict.userId, notification: notification.id });
1634
+ await acknowledge('✓ Marked as read.');
1635
+ // The button has done its work; what is left in the chat should say so
1636
+ // rather than invite a second tap. A failure here costs a stale button,
1637
+ // never the read state that was already written.
1638
+ if (client && chatId !== undefined && messageId !== undefined) {
1639
+ try {
1640
+ await client.editMessageReplyMarkup(chatId, messageId, notificationReadDone(Date.now()));
1641
+ }
1642
+ catch (error) {
1643
+ log.debug('Telegram read button could not be redrawn', { error: errorText(error) });
1644
+ }
1645
+ }
1646
+ }
347
1647
  function handleUpdate(update) {
1648
+ // A tap is not a message and never becomes a turn, so it leaves before
1649
+ // `classifyUpdate` - which would only ever call it "not a message".
1650
+ if (asRecord(update.callback_query) !== undefined) {
1651
+ void handleCallback(update).catch((error) => {
1652
+ log.warn('Telegram callback failed', { error: errorText(error) });
1653
+ });
1654
+ return;
1655
+ }
348
1656
  const verdict = classifyUpdate(update, settings());
349
1657
  lastEventAt = Date.now();
1658
+ // Noted before anything is decided about it: `/clear` empties the chat,
1659
+ // and a message that was refused is standing in it just the same.
1660
+ if (verdict.chatId !== undefined && verdict.chatId === verdict.userId) {
1661
+ noteMessages(context, verdict.chatId, [verdict.messageId]);
1662
+ }
350
1663
  if (!verdict.ok) {
351
1664
  log.warn('Telegram update rejected', {
352
1665
  from: verdict.userId,
@@ -354,6 +1667,13 @@ export function createTelegramGateway(context) {
354
1667
  reason: verdict.reason,
355
1668
  text: verdict.text?.slice(0, REJECT_TEXT),
356
1669
  });
1670
+ // An allowed sender in their own chat hears why. Which is not a leak:
1671
+ // they already know the bot answers them.
1672
+ const note = verdict.reason ? REJECTION_NOTE[verdict.reason] : undefined;
1673
+ if (note && verdict.chatId !== undefined && verdict.chatId === verdict.userId) {
1674
+ say(verdict.chatId, note);
1675
+ return;
1676
+ }
357
1677
  // The one and only answer a rejected update ever gets: the number the
358
1678
  // sender already carries. Without it nobody can put themselves on the
359
1679
  // allowlist; with it they learn nothing new. Once an hour, so it cannot
@@ -384,14 +1704,93 @@ export function createTelegramGateway(context) {
384
1704
  });
385
1705
  return;
386
1706
  }
387
- // An accepted verdict always carries all three, but they are checked
1707
+ // An accepted verdict always carries the ids, but they are checked
388
1708
  // rather than asserted - nothing here narrows foreign input by claim.
389
- const { userId, chatId, text } = verdict;
390
- if (userId === undefined || chatId === undefined || text === undefined)
1709
+ const { userId, chatId } = verdict;
1710
+ if (userId === undefined || chatId === undefined)
391
1711
  return;
392
- if (!enqueue(userId, () => runTurn(userId, chatId, text))) {
393
- say(chatId, 'The queue is full. Please wait until I have answered the previous messages.');
1712
+ // A question is standing in this chat, so a written message may be its
1713
+ // answer and not a new turn.
1714
+ //
1715
+ // This is the branch the whole typed path depends on. Turns are
1716
+ // serialised per sender, and the turn that asked is still holding that
1717
+ // queue while it waits - so an answer that went in as a turn would be
1718
+ // queued behind the very turn it releases, and the two would deadlock
1719
+ // until the question expired. A tap never had this problem: a
1720
+ // `callback_query` is not a message and bypasses the queue by nature.
1721
+ //
1722
+ // But "the turn that asked" is the condition, not "a question exists
1723
+ // somewhere". A card the phone only received as a push - the question
1724
+ // came from a browser tab - leaves an ordinary message alone: swallowing
1725
+ // it would eat the user's next request and hand the blocked turn an
1726
+ // answer nobody gave. Such a card is answered by its buttons, or by a
1727
+ // reply addressed to the card itself.
1728
+ //
1729
+ // Only plain text, though. A photo is content in its own right, and
1730
+ // "here, look at this" is a new turn even mid-question.
1731
+ const candidate = (verdict.text ?? '').trim() && (verdict.attachments ?? []).length === 0 ? openQuestion(chatId) : undefined;
1732
+ const asked = candidate &&
1733
+ (candidate.origin === 'turn' ||
1734
+ (verdict.replyTo?.fromBot === true && verdict.replyTo.messageId === candidate.messageId))
1735
+ ? candidate
1736
+ : undefined;
1737
+ if (asked) {
1738
+ if (submitAnswer(asked, readTypedAnswer(verdict.text ?? '', asked.question))) {
1739
+ // No message back: the reaction says it arrived, and the turn that
1740
+ // was waiting is about to say the rest.
1741
+ react(chatId, verdict.messageId, REACTION.done);
1742
+ return;
1743
+ }
1744
+ // The question was already over by the time this got here. Then it was
1745
+ // never an answer, and it goes on as what it looks like: a message.
394
1746
  }
1747
+ const job = {
1748
+ userId,
1749
+ chatId,
1750
+ attachments: verdict.attachments ?? [],
1751
+ ...(verdict.text !== undefined ? { text: verdict.text } : {}),
1752
+ ...(verdict.messageId !== undefined ? { messageId: verdict.messageId } : {}),
1753
+ ...(verdict.replyTo ? { replyTo: verdict.replyTo } : {}),
1754
+ };
1755
+ // Several pictures sent at once are one message to the person who sent
1756
+ // them, and have to be one turn here too.
1757
+ if (verdict.mediaGroupId) {
1758
+ collectAlbum(verdict.mediaGroupId, job);
1759
+ return;
1760
+ }
1761
+ dispatch(job);
1762
+ }
1763
+ /** Hand one message to the queue, or say why it is not being taken. */
1764
+ function dispatch(job) {
1765
+ if (!enqueue(job.userId, () => runTurn(job))) {
1766
+ say(job.chatId, 'The queue is full. Please wait until I have answered the previous messages.');
1767
+ }
1768
+ }
1769
+ /**
1770
+ * Gather the items of an album, then send them on as one message.
1771
+ *
1772
+ * The caption sits on whichever item the sender wrote it under - usually
1773
+ * the first, but not always - so the first caption seen wins and the rest
1774
+ * only add their files. The timer restarts with every item, because
1775
+ * Telegram delivers an album across several polls.
1776
+ */
1777
+ function collectAlbum(groupId, job) {
1778
+ const pending = albums.get(groupId);
1779
+ if (pending) {
1780
+ clearTimeout(pending.timer);
1781
+ pending.job.attachments.push(...job.attachments);
1782
+ if (!pending.job.text && job.text)
1783
+ pending.job.text = job.text;
1784
+ if (!pending.job.replyTo && job.replyTo)
1785
+ pending.job.replyTo = job.replyTo;
1786
+ }
1787
+ const collected = pending?.job ?? job;
1788
+ const timer = setTimeout(() => {
1789
+ albums.delete(groupId);
1790
+ dispatch(collected);
1791
+ }, ALBUM_WINDOW_MS);
1792
+ timer.unref?.();
1793
+ albums.set(groupId, { job: collected, timer });
395
1794
  }
396
1795
  /* ----------------------------- polling ----------------------------- */
397
1796
  async function poll(client, signal) {
@@ -450,6 +1849,38 @@ export function createTelegramGateway(context) {
450
1849
  running = false;
451
1850
  }
452
1851
  /* ---------------------------- lifecycle ---------------------------- */
1852
+ /** Pending retry after a start that failed for a reason that may pass. */
1853
+ let retryTimer;
1854
+ let retryDelay = RETRY_START_MS;
1855
+ function clearRetry() {
1856
+ if (retryTimer)
1857
+ clearTimeout(retryTimer);
1858
+ retryTimer = undefined;
1859
+ retryDelay = RETRY_START_MS;
1860
+ }
1861
+ /**
1862
+ * Try again later, further apart each time.
1863
+ *
1864
+ * Only from the transient branch of `start`: a rejected token and a second
1865
+ * poller on the same bot are handled by `blocked`, which this must never
1866
+ * paper over. The timer is unref'd, so a process with nothing else to do
1867
+ * still exits.
1868
+ */
1869
+ function scheduleRetry() {
1870
+ if (retryTimer || silenced)
1871
+ return;
1872
+ const wait = retryDelay;
1873
+ retryDelay = Math.min(retryDelay * 2, RETRY_MAX_MS);
1874
+ retryTimer = setTimeout(() => {
1875
+ retryTimer = undefined;
1876
+ if (running || blocked)
1877
+ return;
1878
+ void start().catch((error) => {
1879
+ log.warn('Telegram gateway retry failed', { error: errorText(error) });
1880
+ });
1881
+ }, wait);
1882
+ retryTimer.unref?.();
1883
+ }
453
1884
  async function start() {
454
1885
  if (running)
455
1886
  return;
@@ -486,17 +1917,51 @@ export function createTelegramGateway(context) {
486
1917
  ? 'Telegram rejected this bot token (401). Gateway stopped.'
487
1918
  : 'Another process is polling the same bot (409). Gateway stopped.';
488
1919
  blocked = { reason: lastError, token: secret };
1920
+ clearRetry();
489
1921
  log.error('Telegram gateway cannot run with these settings', { reason: lastError });
490
1922
  return;
491
1923
  }
1924
+ // Everything else is weather: a DNS hiccup, a laptop whose network
1925
+ // came up a second after the server did, Telegram having a moment.
1926
+ // The first version gave up here and stayed down until somebody
1927
+ // noticed and restarted - which is how a channel that exists to be
1928
+ // reachable ends up silently unreachable for a day. So it tries
1929
+ // again, further apart each time, for as long as the config still
1930
+ // wants it running.
492
1931
  lastError = error instanceof TelegramApiError ? error.message : errorText(error);
493
- log.error('Telegram gateway failed to start', { error: lastError });
1932
+ log.error('Telegram gateway failed to start', { error: lastError, retryInMs: retryDelay });
1933
+ scheduleRetry();
494
1934
  return;
495
1935
  }
1936
+ // Yesterday's photos are not worth keeping for ever. Best-effort, and
1937
+ // never a reason not to start.
1938
+ try {
1939
+ const removed = pruneInbox(context.config.workspace);
1940
+ if (removed > 0)
1941
+ log.info('Telegram inbox swept', { folders: removed });
1942
+ }
1943
+ catch (error) {
1944
+ log.warn('Telegram inbox could not be swept', { error: errorText(error) });
1945
+ }
1946
+ // What draws the blue menu button in the app. Best-effort: a bot whose
1947
+ // menu is a day out of date still answers every one of its commands.
1948
+ void client.setMyCommands(COMMANDS).catch((error) => {
1949
+ log.warn('Telegram command menu could not be published', { error: errorText(error) });
1950
+ });
1951
+ // What an empty chat shows above the Start button - which is exactly
1952
+ // what a chat looks like after `/clear`.
1953
+ void client
1954
+ .setMyDescription(`${context.config.assistantName}, your assistant. Write, send a photo or a document, or ` +
1955
+ 'record a voice message. Replies to my notifications are answered about that ' +
1956
+ 'notification. /help lists everything.', `${context.config.assistantName} · your assistant, on your own machine`)
1957
+ .catch((error) => {
1958
+ log.debug('Telegram description could not be set', { error: errorText(error) });
1959
+ });
496
1960
  api = client;
497
1961
  activeToken = secret;
498
1962
  lastError = undefined;
499
1963
  running = true;
1964
+ clearRetry();
500
1965
  controller = new AbortController();
501
1966
  log.info('Telegram gateway started', {
502
1967
  bot: botUsername,
@@ -506,10 +1971,15 @@ export function createTelegramGateway(context) {
506
1971
  loop = poll(client, controller.signal);
507
1972
  }
508
1973
  async function stop() {
1974
+ clearRetry();
509
1975
  controller?.abort();
510
1976
  for (const turn of turns.values())
511
1977
  turn.abort();
512
1978
  turns.clear();
1979
+ // A half-collected album belongs to a connection that is going away.
1980
+ for (const album of albums.values())
1981
+ clearTimeout(album.timer);
1982
+ albums.clear();
513
1983
  const pending = loop;
514
1984
  controller = undefined;
515
1985
  loop = undefined;
@@ -574,9 +2044,33 @@ export function createTelegramGateway(context) {
574
2044
  * id, so no lookup is needed. A 403 (the user blocked the bot) arrives at
575
2045
  * the caller as a `TelegramApiError` with `forbidden`, because whoever
576
2046
  * sends notifications has to be able to stop sending them.
2047
+ *
2048
+ * The ids of the messages that went out come back, because a
2049
+ * notification is only half sent until replying to it leads somewhere:
2050
+ * push hands them straight to the origin registry.
2051
+ */
2052
+ async send(userId, text, options = {}) {
2053
+ let ids = [];
2054
+ await chain(userId, async () => {
2055
+ ids = await deliver(userId, text, options);
2056
+ });
2057
+ return ids;
2058
+ },
2059
+ /**
2060
+ * A question, put where somebody can answer it. The chat id of a private
2061
+ * chat is the user id, so there is nothing to look up.
2062
+ *
2063
+ * Nothing is returned and nothing is awaited: whether this phone answers
2064
+ * is the person's business, and the turn waiting on it is held by the
2065
+ * registry in core, not by this call.
577
2066
  */
578
- async send(userId, text) {
579
- await chain(userId, () => deliver(userId, text));
2067
+ ask(userId, question) {
2068
+ if (!running)
2069
+ return;
2070
+ offerQuestion(userId, question, 'push');
2071
+ },
2072
+ closeQuestion(id, reason, answer) {
2073
+ closeQuestion(id, reason, answer);
580
2074
  },
581
2075
  };
582
2076
  }