rookery-agent 0.1.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 (508) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +367 -0
  3. package/docs/migration.md +88 -0
  4. package/package.json +39 -0
  5. package/packages/cli/dist/commands/chat.d.ts +52 -0
  6. package/packages/cli/dist/commands/chat.d.ts.map +1 -0
  7. package/packages/cli/dist/commands/chat.js +107 -0
  8. package/packages/cli/dist/commands/chat.js.map +1 -0
  9. package/packages/cli/dist/commands/config.d.ts +12 -0
  10. package/packages/cli/dist/commands/config.d.ts.map +1 -0
  11. package/packages/cli/dist/commands/config.js +156 -0
  12. package/packages/cli/dist/commands/config.js.map +1 -0
  13. package/packages/cli/dist/commands/doctor.d.ts +12 -0
  14. package/packages/cli/dist/commands/doctor.d.ts.map +1 -0
  15. package/packages/cli/dist/commands/doctor.js +137 -0
  16. package/packages/cli/dist/commands/doctor.js.map +1 -0
  17. package/packages/cli/dist/commands/memory.d.ts +34 -0
  18. package/packages/cli/dist/commands/memory.d.ts.map +1 -0
  19. package/packages/cli/dist/commands/memory.js +133 -0
  20. package/packages/cli/dist/commands/memory.js.map +1 -0
  21. package/packages/cli/dist/commands/org.d.ts +93 -0
  22. package/packages/cli/dist/commands/org.d.ts.map +1 -0
  23. package/packages/cli/dist/commands/org.js +389 -0
  24. package/packages/cli/dist/commands/org.js.map +1 -0
  25. package/packages/cli/dist/commands/serve.d.ts +13 -0
  26. package/packages/cli/dist/commands/serve.d.ts.map +1 -0
  27. package/packages/cli/dist/commands/serve.js +100 -0
  28. package/packages/cli/dist/commands/serve.js.map +1 -0
  29. package/packages/cli/dist/commands/sessions.d.ts +18 -0
  30. package/packages/cli/dist/commands/sessions.d.ts.map +1 -0
  31. package/packages/cli/dist/commands/sessions.js +88 -0
  32. package/packages/cli/dist/commands/sessions.js.map +1 -0
  33. package/packages/cli/dist/commands/shared.d.ts +59 -0
  34. package/packages/cli/dist/commands/shared.d.ts.map +1 -0
  35. package/packages/cli/dist/commands/shared.js +230 -0
  36. package/packages/cli/dist/commands/shared.js.map +1 -0
  37. package/packages/cli/dist/commands/tasks.d.ts +62 -0
  38. package/packages/cli/dist/commands/tasks.d.ts.map +1 -0
  39. package/packages/cli/dist/commands/tasks.js +262 -0
  40. package/packages/cli/dist/commands/tasks.js.map +1 -0
  41. package/packages/cli/dist/commands/tools.d.ts +8 -0
  42. package/packages/cli/dist/commands/tools.d.ts.map +1 -0
  43. package/packages/cli/dist/commands/tools.js +65 -0
  44. package/packages/cli/dist/commands/tools.js.map +1 -0
  45. package/packages/cli/dist/index.d.ts +15 -0
  46. package/packages/cli/dist/index.d.ts.map +1 -0
  47. package/packages/cli/dist/index.js +513 -0
  48. package/packages/cli/dist/index.js.map +1 -0
  49. package/packages/cli/dist/repl.d.ts +29 -0
  50. package/packages/cli/dist/repl.d.ts.map +1 -0
  51. package/packages/cli/dist/repl.js +634 -0
  52. package/packages/cli/dist/repl.js.map +1 -0
  53. package/packages/cli/dist/tui/App.d.ts +51 -0
  54. package/packages/cli/dist/tui/App.d.ts.map +1 -0
  55. package/packages/cli/dist/tui/App.js +461 -0
  56. package/packages/cli/dist/tui/App.js.map +1 -0
  57. package/packages/cli/dist/tui/commands.d.ts +34 -0
  58. package/packages/cli/dist/tui/commands.d.ts.map +1 -0
  59. package/packages/cli/dist/tui/commands.js +367 -0
  60. package/packages/cli/dist/tui/commands.js.map +1 -0
  61. package/packages/cli/dist/tui/components/ActivityLine.d.ts +16 -0
  62. package/packages/cli/dist/tui/components/ActivityLine.d.ts.map +1 -0
  63. package/packages/cli/dist/tui/components/ActivityLine.js +7 -0
  64. package/packages/cli/dist/tui/components/ActivityLine.js.map +1 -0
  65. package/packages/cli/dist/tui/components/AssignmentsView.d.ts +31 -0
  66. package/packages/cli/dist/tui/components/AssignmentsView.d.ts.map +1 -0
  67. package/packages/cli/dist/tui/components/AssignmentsView.js +79 -0
  68. package/packages/cli/dist/tui/components/AssignmentsView.js.map +1 -0
  69. package/packages/cli/dist/tui/components/Banner.d.ts +18 -0
  70. package/packages/cli/dist/tui/components/Banner.d.ts.map +1 -0
  71. package/packages/cli/dist/tui/components/Banner.js +16 -0
  72. package/packages/cli/dist/tui/components/Banner.js.map +1 -0
  73. package/packages/cli/dist/tui/components/CodeBlock.d.ts +19 -0
  74. package/packages/cli/dist/tui/components/CodeBlock.d.ts.map +1 -0
  75. package/packages/cli/dist/tui/components/CodeBlock.js +21 -0
  76. package/packages/cli/dist/tui/components/CodeBlock.js.map +1 -0
  77. package/packages/cli/dist/tui/components/InputBox.d.ts +25 -0
  78. package/packages/cli/dist/tui/components/InputBox.d.ts.map +1 -0
  79. package/packages/cli/dist/tui/components/InputBox.js +35 -0
  80. package/packages/cli/dist/tui/components/InputBox.js.map +1 -0
  81. package/packages/cli/dist/tui/components/Markdown.d.ts +74 -0
  82. package/packages/cli/dist/tui/components/Markdown.d.ts.map +1 -0
  83. package/packages/cli/dist/tui/components/Markdown.js +293 -0
  84. package/packages/cli/dist/tui/components/Markdown.js.map +1 -0
  85. package/packages/cli/dist/tui/components/Message.d.ts +29 -0
  86. package/packages/cli/dist/tui/components/Message.d.ts.map +1 -0
  87. package/packages/cli/dist/tui/components/Message.js +28 -0
  88. package/packages/cli/dist/tui/components/Message.js.map +1 -0
  89. package/packages/cli/dist/tui/components/Scrollback.d.ts +23 -0
  90. package/packages/cli/dist/tui/components/Scrollback.d.ts.map +1 -0
  91. package/packages/cli/dist/tui/components/Scrollback.js +36 -0
  92. package/packages/cli/dist/tui/components/Scrollback.js.map +1 -0
  93. package/packages/cli/dist/tui/components/SlashPalette.d.ts +17 -0
  94. package/packages/cli/dist/tui/components/SlashPalette.d.ts.map +1 -0
  95. package/packages/cli/dist/tui/components/SlashPalette.js +19 -0
  96. package/packages/cli/dist/tui/components/SlashPalette.js.map +1 -0
  97. package/packages/cli/dist/tui/components/StatusLine.d.ts +61 -0
  98. package/packages/cli/dist/tui/components/StatusLine.d.ts.map +1 -0
  99. package/packages/cli/dist/tui/components/StatusLine.js +55 -0
  100. package/packages/cli/dist/tui/components/StatusLine.js.map +1 -0
  101. package/packages/cli/dist/tui/components/ToolGroup.d.ts +33 -0
  102. package/packages/cli/dist/tui/components/ToolGroup.d.ts.map +1 -0
  103. package/packages/cli/dist/tui/components/ToolGroup.js +52 -0
  104. package/packages/cli/dist/tui/components/ToolGroup.js.map +1 -0
  105. package/packages/cli/dist/tui/components/Wordmark.d.ts +35 -0
  106. package/packages/cli/dist/tui/components/Wordmark.d.ts.map +1 -0
  107. package/packages/cli/dist/tui/components/Wordmark.js +81 -0
  108. package/packages/cli/dist/tui/components/Wordmark.js.map +1 -0
  109. package/packages/cli/dist/tui/highlight.d.ts +29 -0
  110. package/packages/cli/dist/tui/highlight.d.ts.map +1 -0
  111. package/packages/cli/dist/tui/highlight.js +137 -0
  112. package/packages/cli/dist/tui/highlight.js.map +1 -0
  113. package/packages/cli/dist/tui/hooks/useColumns.d.ts +20 -0
  114. package/packages/cli/dist/tui/hooks/useColumns.d.ts.map +1 -0
  115. package/packages/cli/dist/tui/hooks/useColumns.js +38 -0
  116. package/packages/cli/dist/tui/hooks/useColumns.js.map +1 -0
  117. package/packages/cli/dist/tui/hooks/useHistory.d.ts +21 -0
  118. package/packages/cli/dist/tui/hooks/useHistory.d.ts.map +1 -0
  119. package/packages/cli/dist/tui/hooks/useHistory.js +57 -0
  120. package/packages/cli/dist/tui/hooks/useHistory.js.map +1 -0
  121. package/packages/cli/dist/tui/hooks/useSlash.d.ts +38 -0
  122. package/packages/cli/dist/tui/hooks/useSlash.d.ts.map +1 -0
  123. package/packages/cli/dist/tui/hooks/useSlash.js +89 -0
  124. package/packages/cli/dist/tui/hooks/useSlash.js.map +1 -0
  125. package/packages/cli/dist/tui/hooks/useTurn.d.ts +75 -0
  126. package/packages/cli/dist/tui/hooks/useTurn.d.ts.map +1 -0
  127. package/packages/cli/dist/tui/hooks/useTurn.js +396 -0
  128. package/packages/cli/dist/tui/hooks/useTurn.js.map +1 -0
  129. package/packages/cli/dist/tui/theme.d.ts +126 -0
  130. package/packages/cli/dist/tui/theme.d.ts.map +1 -0
  131. package/packages/cli/dist/tui/theme.js +127 -0
  132. package/packages/cli/dist/tui/theme.js.map +1 -0
  133. package/packages/cli/dist/tui/types.d.ts +205 -0
  134. package/packages/cli/dist/tui/types.d.ts.map +1 -0
  135. package/packages/cli/dist/tui/types.js +55 -0
  136. package/packages/cli/dist/tui/types.js.map +1 -0
  137. package/packages/cli/dist/ui/render.d.ts +74 -0
  138. package/packages/cli/dist/ui/render.d.ts.map +1 -0
  139. package/packages/cli/dist/ui/render.js +349 -0
  140. package/packages/cli/dist/ui/render.js.map +1 -0
  141. package/packages/cli/dist/ui/speech.d.ts +42 -0
  142. package/packages/cli/dist/ui/speech.d.ts.map +1 -0
  143. package/packages/cli/dist/ui/speech.js +257 -0
  144. package/packages/cli/dist/ui/speech.js.map +1 -0
  145. package/packages/cli/dist/ui/spinner.d.ts +17 -0
  146. package/packages/cli/dist/ui/spinner.d.ts.map +1 -0
  147. package/packages/cli/dist/ui/spinner.js +61 -0
  148. package/packages/cli/dist/ui/spinner.js.map +1 -0
  149. package/packages/cli/dist/ui/theme.d.ts +54 -0
  150. package/packages/cli/dist/ui/theme.d.ts.map +1 -0
  151. package/packages/cli/dist/ui/theme.js +74 -0
  152. package/packages/cli/dist/ui/theme.js.map +1 -0
  153. package/packages/cli/package.json +1 -0
  154. package/packages/core/dist/agents/legacy-persona.d.ts +4 -0
  155. package/packages/core/dist/agents/legacy-persona.d.ts.map +1 -0
  156. package/packages/core/dist/agents/legacy-persona.js +39 -0
  157. package/packages/core/dist/agents/legacy-persona.js.map +1 -0
  158. package/packages/core/dist/agents/orchestrator.d.ts +24 -0
  159. package/packages/core/dist/agents/orchestrator.d.ts.map +1 -0
  160. package/packages/core/dist/agents/orchestrator.js +88 -0
  161. package/packages/core/dist/agents/orchestrator.js.map +1 -0
  162. package/packages/core/dist/agents/persona.d.ts +56 -0
  163. package/packages/core/dist/agents/persona.d.ts.map +1 -0
  164. package/packages/core/dist/agents/persona.js +153 -0
  165. package/packages/core/dist/agents/persona.js.map +1 -0
  166. package/packages/core/dist/agents/roles.d.ts +21 -0
  167. package/packages/core/dist/agents/roles.d.ts.map +1 -0
  168. package/packages/core/dist/agents/roles.js +81 -0
  169. package/packages/core/dist/agents/roles.js.map +1 -0
  170. package/packages/core/dist/agents/team.d.ts +105 -0
  171. package/packages/core/dist/agents/team.d.ts.map +1 -0
  172. package/packages/core/dist/agents/team.js +623 -0
  173. package/packages/core/dist/agents/team.js.map +1 -0
  174. package/packages/core/dist/computer/keys.d.ts +12 -0
  175. package/packages/core/dist/computer/keys.d.ts.map +1 -0
  176. package/packages/core/dist/computer/keys.js +56 -0
  177. package/packages/core/dist/computer/keys.js.map +1 -0
  178. package/packages/core/dist/computer/mcp-server.d.ts +11 -0
  179. package/packages/core/dist/computer/mcp-server.d.ts.map +1 -0
  180. package/packages/core/dist/computer/mcp-server.js +228 -0
  181. package/packages/core/dist/computer/mcp-server.js.map +1 -0
  182. package/packages/core/dist/computer/powershell.d.ts +13 -0
  183. package/packages/core/dist/computer/powershell.d.ts.map +1 -0
  184. package/packages/core/dist/computer/powershell.js +359 -0
  185. package/packages/core/dist/computer/powershell.js.map +1 -0
  186. package/packages/core/dist/computer/tools.d.ts +43 -0
  187. package/packages/core/dist/computer/tools.d.ts.map +1 -0
  188. package/packages/core/dist/computer/tools.js +260 -0
  189. package/packages/core/dist/computer/tools.js.map +1 -0
  190. package/packages/core/dist/config.d.ts +32 -0
  191. package/packages/core/dist/config.d.ts.map +1 -0
  192. package/packages/core/dist/config.js +329 -0
  193. package/packages/core/dist/config.js.map +1 -0
  194. package/packages/core/dist/cron/parse.d.ts +52 -0
  195. package/packages/core/dist/cron/parse.d.ts.map +1 -0
  196. package/packages/core/dist/cron/parse.js +277 -0
  197. package/packages/core/dist/cron/parse.js.map +1 -0
  198. package/packages/core/dist/cron/scheduler.d.ts +102 -0
  199. package/packages/core/dist/cron/scheduler.d.ts.map +1 -0
  200. package/packages/core/dist/cron/scheduler.js +334 -0
  201. package/packages/core/dist/cron/scheduler.js.map +1 -0
  202. package/packages/core/dist/cron/script.d.ts +9 -0
  203. package/packages/core/dist/cron/script.d.ts.map +1 -0
  204. package/packages/core/dist/cron/script.js +113 -0
  205. package/packages/core/dist/cron/script.js.map +1 -0
  206. package/packages/core/dist/cron/store.d.ts +77 -0
  207. package/packages/core/dist/cron/store.d.ts.map +1 -0
  208. package/packages/core/dist/cron/store.js +229 -0
  209. package/packages/core/dist/cron/store.js.map +1 -0
  210. package/packages/core/dist/gateway/policy.d.ts +113 -0
  211. package/packages/core/dist/gateway/policy.d.ts.map +1 -0
  212. package/packages/core/dist/gateway/policy.js +373 -0
  213. package/packages/core/dist/gateway/policy.js.map +1 -0
  214. package/packages/core/dist/index.d.ts +45 -0
  215. package/packages/core/dist/index.d.ts.map +1 -0
  216. package/packages/core/dist/index.js +52 -0
  217. package/packages/core/dist/index.js.map +1 -0
  218. package/packages/core/dist/logger.d.ts +21 -0
  219. package/packages/core/dist/logger.d.ts.map +1 -0
  220. package/packages/core/dist/logger.js +61 -0
  221. package/packages/core/dist/logger.js.map +1 -0
  222. package/packages/core/dist/memory/db.d.ts +12 -0
  223. package/packages/core/dist/memory/db.d.ts.map +1 -0
  224. package/packages/core/dist/memory/db.js +414 -0
  225. package/packages/core/dist/memory/db.js.map +1 -0
  226. package/packages/core/dist/memory/extractor.d.ts +35 -0
  227. package/packages/core/dist/memory/extractor.d.ts.map +1 -0
  228. package/packages/core/dist/memory/extractor.js +159 -0
  229. package/packages/core/dist/memory/extractor.js.map +1 -0
  230. package/packages/core/dist/memory/gate.d.ts +68 -0
  231. package/packages/core/dist/memory/gate.d.ts.map +1 -0
  232. package/packages/core/dist/memory/gate.js +163 -0
  233. package/packages/core/dist/memory/gate.js.map +1 -0
  234. package/packages/core/dist/memory/recall.d.ts +61 -0
  235. package/packages/core/dist/memory/recall.d.ts.map +1 -0
  236. package/packages/core/dist/memory/recall.js +342 -0
  237. package/packages/core/dist/memory/recall.js.map +1 -0
  238. package/packages/core/dist/memory/sleep.d.ts +105 -0
  239. package/packages/core/dist/memory/sleep.d.ts.map +1 -0
  240. package/packages/core/dist/memory/sleep.js +888 -0
  241. package/packages/core/dist/memory/sleep.js.map +1 -0
  242. package/packages/core/dist/memory/store.d.ts +263 -0
  243. package/packages/core/dist/memory/store.d.ts.map +1 -0
  244. package/packages/core/dist/memory/store.js +999 -0
  245. package/packages/core/dist/memory/store.js.map +1 -0
  246. package/packages/core/dist/migration-cron.d.ts +37 -0
  247. package/packages/core/dist/migration-cron.d.ts.map +1 -0
  248. package/packages/core/dist/migration-cron.js +257 -0
  249. package/packages/core/dist/migration-cron.js.map +1 -0
  250. package/packages/core/dist/migration-scripts.d.ts +15 -0
  251. package/packages/core/dist/migration-scripts.d.ts.map +1 -0
  252. package/packages/core/dist/migration-scripts.js +97 -0
  253. package/packages/core/dist/migration-scripts.js.map +1 -0
  254. package/packages/core/dist/migration.d.ts +33 -0
  255. package/packages/core/dist/migration.d.ts.map +1 -0
  256. package/packages/core/dist/migration.js +296 -0
  257. package/packages/core/dist/migration.js.map +1 -0
  258. package/packages/core/dist/org/bridge.d.ts +42 -0
  259. package/packages/core/dist/org/bridge.d.ts.map +1 -0
  260. package/packages/core/dist/org/bridge.js +139 -0
  261. package/packages/core/dist/org/bridge.js.map +1 -0
  262. package/packages/core/dist/org/controller.d.ts +118 -0
  263. package/packages/core/dist/org/controller.d.ts.map +1 -0
  264. package/packages/core/dist/org/controller.js +1431 -0
  265. package/packages/core/dist/org/controller.js.map +1 -0
  266. package/packages/core/dist/org/mcp-bridge.d.ts +11 -0
  267. package/packages/core/dist/org/mcp-bridge.d.ts.map +1 -0
  268. package/packages/core/dist/org/mcp-bridge.js +148 -0
  269. package/packages/core/dist/org/mcp-bridge.js.map +1 -0
  270. package/packages/core/dist/org/planner.d.ts +60 -0
  271. package/packages/core/dist/org/planner.d.ts.map +1 -0
  272. package/packages/core/dist/org/planner.js +175 -0
  273. package/packages/core/dist/org/planner.js.map +1 -0
  274. package/packages/core/dist/org/ponytail.d.ts +24 -0
  275. package/packages/core/dist/org/ponytail.d.ts.map +1 -0
  276. package/packages/core/dist/org/ponytail.js +53 -0
  277. package/packages/core/dist/org/ponytail.js.map +1 -0
  278. package/packages/core/dist/org/project-mcp.d.ts +32 -0
  279. package/packages/core/dist/org/project-mcp.d.ts.map +1 -0
  280. package/packages/core/dist/org/project-mcp.js +53 -0
  281. package/packages/core/dist/org/project-mcp.js.map +1 -0
  282. package/packages/core/dist/org/prompts.d.ts +71 -0
  283. package/packages/core/dist/org/prompts.d.ts.map +1 -0
  284. package/packages/core/dist/org/prompts.js +268 -0
  285. package/packages/core/dist/org/prompts.js.map +1 -0
  286. package/packages/core/dist/org/store.d.ts +176 -0
  287. package/packages/core/dist/org/store.d.ts.map +1 -0
  288. package/packages/core/dist/org/store.js +594 -0
  289. package/packages/core/dist/org/store.js.map +1 -0
  290. package/packages/core/dist/org/tools.d.ts +22 -0
  291. package/packages/core/dist/org/tools.d.ts.map +1 -0
  292. package/packages/core/dist/org/tools.js +578 -0
  293. package/packages/core/dist/org/tools.js.map +1 -0
  294. package/packages/core/dist/profile.d.ts +16 -0
  295. package/packages/core/dist/profile.d.ts.map +1 -0
  296. package/packages/core/dist/profile.js +176 -0
  297. package/packages/core/dist/profile.js.map +1 -0
  298. package/packages/core/dist/providers/catalogue.d.ts +6 -0
  299. package/packages/core/dist/providers/catalogue.d.ts.map +1 -0
  300. package/packages/core/dist/providers/catalogue.js +104 -0
  301. package/packages/core/dist/providers/catalogue.js.map +1 -0
  302. package/packages/core/dist/providers/claude-code.d.ts +10 -0
  303. package/packages/core/dist/providers/claude-code.d.ts.map +1 -0
  304. package/packages/core/dist/providers/claude-code.js +321 -0
  305. package/packages/core/dist/providers/claude-code.js.map +1 -0
  306. package/packages/core/dist/providers/codex.d.ts +10 -0
  307. package/packages/core/dist/providers/codex.d.ts.map +1 -0
  308. package/packages/core/dist/providers/codex.js +375 -0
  309. package/packages/core/dist/providers/codex.js.map +1 -0
  310. package/packages/core/dist/providers/process.d.ts +48 -0
  311. package/packages/core/dist/providers/process.d.ts.map +1 -0
  312. package/packages/core/dist/providers/process.js +165 -0
  313. package/packages/core/dist/providers/process.js.map +1 -0
  314. package/packages/core/dist/providers/quota.d.ts +13 -0
  315. package/packages/core/dist/providers/quota.d.ts.map +1 -0
  316. package/packages/core/dist/providers/quota.js +231 -0
  317. package/packages/core/dist/providers/quota.js.map +1 -0
  318. package/packages/core/dist/providers/registry.d.ts +27 -0
  319. package/packages/core/dist/providers/registry.d.ts.map +1 -0
  320. package/packages/core/dist/providers/registry.js +64 -0
  321. package/packages/core/dist/providers/registry.js.map +1 -0
  322. package/packages/core/dist/runtime.d.ts +149 -0
  323. package/packages/core/dist/runtime.d.ts.map +1 -0
  324. package/packages/core/dist/runtime.js +778 -0
  325. package/packages/core/dist/runtime.js.map +1 -0
  326. package/packages/core/dist/skills/import.d.ts +41 -0
  327. package/packages/core/dist/skills/import.d.ts.map +1 -0
  328. package/packages/core/dist/skills/import.js +129 -0
  329. package/packages/core/dist/skills/import.js.map +1 -0
  330. package/packages/core/dist/skills/store.d.ts +57 -0
  331. package/packages/core/dist/skills/store.d.ts.map +1 -0
  332. package/packages/core/dist/skills/store.js +126 -0
  333. package/packages/core/dist/skills/store.js.map +1 -0
  334. package/packages/core/dist/tools/browser.d.ts +20 -0
  335. package/packages/core/dist/tools/browser.d.ts.map +1 -0
  336. package/packages/core/dist/tools/browser.js +72 -0
  337. package/packages/core/dist/tools/browser.js.map +1 -0
  338. package/packages/core/dist/tools/catalog.d.ts +67 -0
  339. package/packages/core/dist/tools/catalog.d.ts.map +1 -0
  340. package/packages/core/dist/tools/catalog.js +233 -0
  341. package/packages/core/dist/tools/catalog.js.map +1 -0
  342. package/packages/core/dist/tools/hub.d.ts +68 -0
  343. package/packages/core/dist/tools/hub.d.ts.map +1 -0
  344. package/packages/core/dist/tools/hub.js +213 -0
  345. package/packages/core/dist/tools/hub.js.map +1 -0
  346. package/packages/core/dist/types.d.ts +1031 -0
  347. package/packages/core/dist/types.d.ts.map +1 -0
  348. package/packages/core/dist/types.js +22 -0
  349. package/packages/core/dist/types.js.map +1 -0
  350. package/packages/core/dist/util/queue.d.ts +25 -0
  351. package/packages/core/dist/util/queue.d.ts.map +1 -0
  352. package/packages/core/dist/util/queue.js +64 -0
  353. package/packages/core/dist/util/queue.js.map +1 -0
  354. package/packages/core/package.json +1 -0
  355. package/packages/server/dist/auth.d.ts +12 -0
  356. package/packages/server/dist/auth.d.ts.map +1 -0
  357. package/packages/server/dist/auth.js +61 -0
  358. package/packages/server/dist/auth.js.map +1 -0
  359. package/packages/server/dist/context.d.ts +29 -0
  360. package/packages/server/dist/context.d.ts.map +1 -0
  361. package/packages/server/dist/context.js +46 -0
  362. package/packages/server/dist/context.js.map +1 -0
  363. package/packages/server/dist/env.d.ts +8 -0
  364. package/packages/server/dist/env.d.ts.map +1 -0
  365. package/packages/server/dist/env.js +36 -0
  366. package/packages/server/dist/env.js.map +1 -0
  367. package/packages/server/dist/gateways/push.d.ts +22 -0
  368. package/packages/server/dist/gateways/push.d.ts.map +1 -0
  369. package/packages/server/dist/gateways/push.js +267 -0
  370. package/packages/server/dist/gateways/push.js.map +1 -0
  371. package/packages/server/dist/gateways/telegram-api.d.ts +82 -0
  372. package/packages/server/dist/gateways/telegram-api.d.ts.map +1 -0
  373. package/packages/server/dist/gateways/telegram-api.js +168 -0
  374. package/packages/server/dist/gateways/telegram-api.js.map +1 -0
  375. package/packages/server/dist/gateways/telegram.d.ts +32 -0
  376. package/packages/server/dist/gateways/telegram.d.ts.map +1 -0
  377. package/packages/server/dist/gateways/telegram.js +583 -0
  378. package/packages/server/dist/gateways/telegram.js.map +1 -0
  379. package/packages/server/dist/index.d.ts +12 -0
  380. package/packages/server/dist/index.d.ts.map +1 -0
  381. package/packages/server/dist/index.js +12 -0
  382. package/packages/server/dist/index.js.map +1 -0
  383. package/packages/server/dist/main.d.ts +2 -0
  384. package/packages/server/dist/main.d.ts.map +1 -0
  385. package/packages/server/dist/main.js +74 -0
  386. package/packages/server/dist/main.js.map +1 -0
  387. package/packages/server/dist/routes/agents.d.ts +5 -0
  388. package/packages/server/dist/routes/agents.d.ts.map +1 -0
  389. package/packages/server/dist/routes/agents.js +6 -0
  390. package/packages/server/dist/routes/agents.js.map +1 -0
  391. package/packages/server/dist/routes/chat.d.ts +10 -0
  392. package/packages/server/dist/routes/chat.d.ts.map +1 -0
  393. package/packages/server/dist/routes/chat.js +36 -0
  394. package/packages/server/dist/routes/chat.js.map +1 -0
  395. package/packages/server/dist/routes/config.d.ts +4 -0
  396. package/packages/server/dist/routes/config.d.ts.map +1 -0
  397. package/packages/server/dist/routes/config.js +58 -0
  398. package/packages/server/dist/routes/config.js.map +1 -0
  399. package/packages/server/dist/routes/cron.d.ts +10 -0
  400. package/packages/server/dist/routes/cron.d.ts.map +1 -0
  401. package/packages/server/dist/routes/cron.js +128 -0
  402. package/packages/server/dist/routes/cron.js.map +1 -0
  403. package/packages/server/dist/routes/gateways.d.ts +10 -0
  404. package/packages/server/dist/routes/gateways.d.ts.map +1 -0
  405. package/packages/server/dist/routes/gateways.js +32 -0
  406. package/packages/server/dist/routes/gateways.js.map +1 -0
  407. package/packages/server/dist/routes/health.d.ts +8 -0
  408. package/packages/server/dist/routes/health.d.ts.map +1 -0
  409. package/packages/server/dist/routes/health.js +12 -0
  410. package/packages/server/dist/routes/health.js.map +1 -0
  411. package/packages/server/dist/routes/memories.d.ts +11 -0
  412. package/packages/server/dist/routes/memories.d.ts.map +1 -0
  413. package/packages/server/dist/routes/memories.js +134 -0
  414. package/packages/server/dist/routes/memories.js.map +1 -0
  415. package/packages/server/dist/routes/org.d.ts +13 -0
  416. package/packages/server/dist/routes/org.d.ts.map +1 -0
  417. package/packages/server/dist/routes/org.js +316 -0
  418. package/packages/server/dist/routes/org.js.map +1 -0
  419. package/packages/server/dist/routes/profile.d.ts +4 -0
  420. package/packages/server/dist/routes/profile.d.ts.map +1 -0
  421. package/packages/server/dist/routes/profile.js +51 -0
  422. package/packages/server/dist/routes/profile.js.map +1 -0
  423. package/packages/server/dist/routes/providers.d.ts +9 -0
  424. package/packages/server/dist/routes/providers.d.ts.map +1 -0
  425. package/packages/server/dist/routes/providers.js +41 -0
  426. package/packages/server/dist/routes/providers.js.map +1 -0
  427. package/packages/server/dist/routes/sessions.d.ts +9 -0
  428. package/packages/server/dist/routes/sessions.d.ts.map +1 -0
  429. package/packages/server/dist/routes/sessions.js +72 -0
  430. package/packages/server/dist/routes/sessions.js.map +1 -0
  431. package/packages/server/dist/routes/sleep.d.ts +12 -0
  432. package/packages/server/dist/routes/sleep.d.ts.map +1 -0
  433. package/packages/server/dist/routes/sleep.js +70 -0
  434. package/packages/server/dist/routes/sleep.js.map +1 -0
  435. package/packages/server/dist/routes/stats.d.ts +17 -0
  436. package/packages/server/dist/routes/stats.d.ts.map +1 -0
  437. package/packages/server/dist/routes/stats.js +57 -0
  438. package/packages/server/dist/routes/stats.js.map +1 -0
  439. package/packages/server/dist/routes/team.d.ts +11 -0
  440. package/packages/server/dist/routes/team.d.ts.map +1 -0
  441. package/packages/server/dist/routes/team.js +36 -0
  442. package/packages/server/dist/routes/team.js.map +1 -0
  443. package/packages/server/dist/routes/tools.d.ts +10 -0
  444. package/packages/server/dist/routes/tools.d.ts.map +1 -0
  445. package/packages/server/dist/routes/tools.js +128 -0
  446. package/packages/server/dist/routes/tools.js.map +1 -0
  447. package/packages/server/dist/routes/tts.d.ts +12 -0
  448. package/packages/server/dist/routes/tts.d.ts.map +1 -0
  449. package/packages/server/dist/routes/tts.js +38 -0
  450. package/packages/server/dist/routes/tts.js.map +1 -0
  451. package/packages/server/dist/routes/ws.d.ts +13 -0
  452. package/packages/server/dist/routes/ws.d.ts.map +1 -0
  453. package/packages/server/dist/routes/ws.js +96 -0
  454. package/packages/server/dist/routes/ws.js.map +1 -0
  455. package/packages/server/dist/schemas.d.ts +981 -0
  456. package/packages/server/dist/schemas.d.ts.map +1 -0
  457. package/packages/server/dist/schemas.js +339 -0
  458. package/packages/server/dist/schemas.js.map +1 -0
  459. package/packages/server/dist/server.d.ts +20 -0
  460. package/packages/server/dist/server.d.ts.map +1 -0
  461. package/packages/server/dist/server.js +234 -0
  462. package/packages/server/dist/server.js.map +1 -0
  463. package/packages/server/dist/services/stream.d.ts +77 -0
  464. package/packages/server/dist/services/stream.d.ts.map +1 -0
  465. package/packages/server/dist/services/stream.js +84 -0
  466. package/packages/server/dist/services/stream.js.map +1 -0
  467. package/packages/server/dist/services/tts.d.ts +53 -0
  468. package/packages/server/dist/services/tts.d.ts.map +1 -0
  469. package/packages/server/dist/services/tts.js +281 -0
  470. package/packages/server/dist/services/tts.js.map +1 -0
  471. package/packages/server/dist/services/voice-keys.d.ts +26 -0
  472. package/packages/server/dist/services/voice-keys.d.ts.map +1 -0
  473. package/packages/server/dist/services/voice-keys.js +51 -0
  474. package/packages/server/dist/services/voice-keys.js.map +1 -0
  475. package/packages/server/dist/static.d.ts +12 -0
  476. package/packages/server/dist/static.d.ts.map +1 -0
  477. package/packages/server/dist/static.js +63 -0
  478. package/packages/server/dist/static.js.map +1 -0
  479. package/packages/server/package.json +1 -0
  480. package/packages/web/dist/apple-touch-icon.png +0 -0
  481. package/packages/web/dist/assets/3d-force-graph-BPZmoydi.js +1163 -0
  482. package/packages/web/dist/assets/bricolage-grotesque-latin-ext-wght-normal-CcLUaPy7.woff2 +0 -0
  483. package/packages/web/dist/assets/bricolage-grotesque-latin-wght-normal-DLoelf7F.woff2 +0 -0
  484. package/packages/web/dist/assets/bricolage-grotesque-vietnamese-wght-normal-BUzh504Q.woff2 +0 -0
  485. package/packages/web/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  486. package/packages/web/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  487. package/packages/web/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  488. package/packages/web/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  489. package/packages/web/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  490. package/packages/web/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  491. package/packages/web/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  492. package/packages/web/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  493. package/packages/web/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  494. package/packages/web/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  495. package/packages/web/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  496. package/packages/web/dist/assets/index-IBSTzK7-.js +1255 -0
  497. package/packages/web/dist/assets/index-qUXUui7W.css +1 -0
  498. package/packages/web/dist/assets/three-spritetext-B9ZIW7c-.js +4 -0
  499. package/packages/web/dist/assets/three.module-cmFfBtHS.js +4228 -0
  500. package/packages/web/dist/favicon.ico +0 -0
  501. package/packages/web/dist/favicon.svg +2 -0
  502. package/packages/web/dist/index.html +28 -0
  503. package/packages/web/dist/logo-light.svg +2 -0
  504. package/packages/web/dist/logo.svg +2 -0
  505. package/packages/web/dist/mark-light.svg +2 -0
  506. package/packages/web/dist/mark.svg +2 -0
  507. package/packages/web/package.json +1 -0
  508. package/scripts/rookery.mjs +183 -0
@@ -0,0 +1,999 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { ASSISTANT_MEMORY_OWNER, } from '../types.js';
3
+ import { openDatabase } from './db.js';
4
+ import { OrgStore } from '../org/store.js';
5
+ import { CronStore } from '../cron/store.js';
6
+ /** All persistence for sessions, transcripts, long-term memories, the organisation and schedules. */
7
+ export class Store {
8
+ db;
9
+ /** Companies, teams, agents, assignments and messages. */
10
+ org;
11
+ /** Schedules and their runs. */
12
+ cron;
13
+ constructor(pathOrDb) {
14
+ this.db = typeof pathOrDb === 'string' ? openDatabase(pathOrDb) : pathOrDb;
15
+ this.org = new OrgStore(this.db);
16
+ this.cron = new CronStore(this.db);
17
+ }
18
+ close() {
19
+ this.db.close();
20
+ }
21
+ /* ---------------------------- sessions ---------------------------- */
22
+ createSession(input) {
23
+ const now = Date.now();
24
+ const session = {
25
+ id: randomUUID(),
26
+ title: input.title?.trim() || 'New conversation',
27
+ kind: input.kind ?? 'chat',
28
+ provider: input.provider,
29
+ model: input.model,
30
+ cwd: input.cwd,
31
+ projectId: input.projectId,
32
+ agentId: input.agentId,
33
+ createdAt: now,
34
+ updatedAt: now,
35
+ archived: false,
36
+ messageCount: 0,
37
+ };
38
+ this.db
39
+ .prepare(
40
+ // `agent` is omitted on purpose: the column survives for old rows but
41
+ // a session no longer has one, so it falls back to its SQL default.
42
+ `INSERT INTO sessions
43
+ (id, title, kind, provider, model, cwd, project_id, agent_id, provider_session_id, created_at, updated_at, archived)
44
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0)`)
45
+ .run(session.id, session.title, session.kind, session.provider, session.model ?? null, session.cwd, session.projectId ?? null, session.agentId ?? null, now, now);
46
+ return session;
47
+ }
48
+ getSession(id) {
49
+ const row = this.db
50
+ .prepare(`SELECT s.*, (SELECT COUNT(*) FROM messages m WHERE m.session_id = s.id) AS message_count
51
+ FROM sessions s WHERE s.id = ?`)
52
+ .get(id);
53
+ return row ? mapSession(row) : null;
54
+ }
55
+ /**
56
+ * Recent sessions. `agentId` narrows to one counterpart: an agent id for
57
+ * direct chats with that agent, `null` for conversations with the assistant.
58
+ */
59
+ listSessions(options = {}) {
60
+ const limit = options.limit ?? 50;
61
+ const scope = (options.agentId === undefined ? '' : options.agentId === null ? ' AND s.agent_id IS NULL' : ' AND s.agent_id = ?') +
62
+ (options.kind ? ' AND s.kind = ?' : '');
63
+ const values = [options.includeArchived ? 1 : 0];
64
+ if (options.agentId)
65
+ values.push(options.agentId);
66
+ if (options.kind)
67
+ values.push(options.kind);
68
+ values.push(limit);
69
+ const rows = this.db
70
+ .prepare(`SELECT s.*, (SELECT COUNT(*) FROM messages m WHERE m.session_id = s.id) AS message_count
71
+ FROM sessions s
72
+ WHERE (? = 1 OR s.archived = 0)` + scope + `
73
+ ORDER BY s.updated_at DESC
74
+ LIMIT ?`)
75
+ .all(...values);
76
+ return rows.map(mapSession);
77
+ }
78
+ updateSession(id, patch) {
79
+ const columns = {
80
+ title: 'title',
81
+ provider: 'provider',
82
+ model: 'model',
83
+ cwd: 'cwd',
84
+ projectId: 'project_id',
85
+ providerSessionId: 'provider_session_id',
86
+ archived: 'archived',
87
+ };
88
+ const sets = [];
89
+ const values = [];
90
+ for (const [key, column] of Object.entries(columns)) {
91
+ const value = patch[key];
92
+ if (value === undefined)
93
+ continue;
94
+ sets.push(column + ' = ?');
95
+ values.push(typeof value === 'boolean' ? (value ? 1 : 0) : value);
96
+ }
97
+ if (!sets.length)
98
+ return;
99
+ sets.push('updated_at = ?');
100
+ values.push(Date.now(), id);
101
+ this.db.prepare('UPDATE sessions SET ' + sets.join(', ') + ' WHERE id = ?').run(...values);
102
+ }
103
+ deleteSession(id) {
104
+ this.db.prepare('DELETE FROM sessions WHERE id = ?').run(id);
105
+ }
106
+ /* ---------------------------- messages ---------------------------- */
107
+ addMessage(input) {
108
+ const message = {
109
+ id: randomUUID(),
110
+ sessionId: input.sessionId,
111
+ role: input.role,
112
+ content: input.content,
113
+ provider: input.provider,
114
+ model: input.model,
115
+ agent: input.agent,
116
+ usage: input.usage,
117
+ toolCalls: input.toolCalls,
118
+ createdAt: Date.now(),
119
+ };
120
+ this.db
121
+ .prepare(`INSERT INTO messages (id, session_id, role, content, provider, model, agent, usage, created_at, tool_calls)
122
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
123
+ .run(message.id, message.sessionId, message.role, message.content, message.provider ?? null, message.model ?? null, message.agent ?? null, message.usage ? JSON.stringify(message.usage) : null, message.createdAt, message.toolCalls?.length ? JSON.stringify(message.toolCalls) : null);
124
+ this.db
125
+ .prepare('UPDATE sessions SET updated_at = ? WHERE id = ?')
126
+ .run(message.createdAt, message.sessionId);
127
+ return message;
128
+ }
129
+ /** Transcript in chronological order. `limit` keeps the most recent turns. */
130
+ getMessages(sessionId, limit) {
131
+ const rows = limit
132
+ ? this.db
133
+ .prepare(`SELECT * FROM (
134
+ SELECT * FROM messages WHERE session_id = ? ORDER BY created_at DESC LIMIT ?
135
+ ) ORDER BY created_at ASC`)
136
+ .all(sessionId, limit)
137
+ : this.db
138
+ .prepare('SELECT * FROM messages WHERE session_id = ? ORDER BY created_at ASC')
139
+ .all(sessionId);
140
+ return rows.map(mapMessage);
141
+ }
142
+ countMessages(sessionId) {
143
+ const row = this.db
144
+ .prepare('SELECT COUNT(*) AS n FROM messages WHERE session_id = ?')
145
+ .get(sessionId);
146
+ return row.n;
147
+ }
148
+ /* ---------------------------- memories ---------------------------- */
149
+ /**
150
+ * Insert a memory, or reinforce the existing one when the same sentence is
151
+ * already known to the same owner. Reinforcing raises importance instead of
152
+ * creating noise.
153
+ */
154
+ upsertMemory(input) {
155
+ const content = input.content.trim();
156
+ if (!content)
157
+ throw new Error('A memory needs content.');
158
+ const owner = input.owner ?? ASSISTANT_MEMORY_OWNER;
159
+ const now = Date.now();
160
+ const existing = this.db
161
+ .prepare('SELECT * FROM memories WHERE owner = ? AND kind = ? AND content = ?')
162
+ .get(owner, input.kind, content);
163
+ if (existing) {
164
+ // Reinforcement is damped and stops entirely near the top. Hearing the
165
+ // same sentence again says the extractor likes saying it, not that the
166
+ // memory earned its rank - that is what `usefulness` is for, and this
167
+ // path deliberately never touches it.
168
+ const base = Math.max(Number(existing.importance), input.importance ?? 0.5);
169
+ const importance = base >= 0.8 ? Math.min(1, base) : Math.min(1, base + 0.02);
170
+ const tags = mergeTags(parseTags(existing.tags), input.tags ?? []);
171
+ this.db
172
+ .prepare(`UPDATE memories
173
+ SET importance = ?, tags = ?, updated_at = ?, forgotten = 0,
174
+ dormant_at = NULL, superseded_by = NULL
175
+ WHERE id = ?`)
176
+ .run(importance, JSON.stringify(tags), now, existing.id);
177
+ return this.getMemory(existing.id);
178
+ }
179
+ const record = {
180
+ id: randomUUID(),
181
+ kind: input.kind,
182
+ content,
183
+ tags: input.tags ?? [],
184
+ importance: clamp01(input.importance ?? 0.5),
185
+ owner,
186
+ sourceSessionId: input.sourceSessionId,
187
+ createdAt: now,
188
+ updatedAt: now,
189
+ accessCount: 0,
190
+ forgotten: false,
191
+ origin: input.origin ?? 'extract',
192
+ pinned: input.pinned ?? false,
193
+ sleepRunId: input.sleepRunId,
194
+ usefulness: 0,
195
+ };
196
+ this.db
197
+ .prepare(`INSERT INTO memories
198
+ (id, kind, content, tags, importance, owner, source_session_id, created_at, updated_at,
199
+ access_count, forgotten, origin, pinned, sleep_run_id, usefulness)
200
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?, ?, 0)`)
201
+ .run(record.id, record.kind, record.content, JSON.stringify(record.tags), record.importance, record.owner, record.sourceSessionId ?? null, now, now, record.origin, record.pinned ? 1 : 0, record.sleepRunId ?? null);
202
+ return record;
203
+ }
204
+ /**
205
+ * Edit a memory in place. Used by the inspector (pin, re-word, change
206
+ * weight, wake it up) and by the sleep run when it retires one.
207
+ */
208
+ updateMemory(id, patch) {
209
+ const columns = {
210
+ content: 'content',
211
+ kind: 'kind',
212
+ importance: 'importance',
213
+ pinned: 'pinned',
214
+ dormantAt: 'dormant_at',
215
+ supersededBy: 'superseded_by',
216
+ forgotten: 'forgotten',
217
+ sleepRunId: 'sleep_run_id',
218
+ };
219
+ const sets = [];
220
+ const values = [];
221
+ for (const [key, column] of Object.entries(columns)) {
222
+ const value = patch[key];
223
+ if (value === undefined)
224
+ continue;
225
+ sets.push(column + ' = ?');
226
+ values.push(typeof value === 'boolean' ? (value ? 1 : 0) : value);
227
+ }
228
+ if (patch.tags) {
229
+ sets.push('tags = ?');
230
+ values.push(JSON.stringify([...new Set(patch.tags)]));
231
+ }
232
+ if (!sets.length)
233
+ return this.getMemory(id);
234
+ sets.push('updated_at = ?');
235
+ values.push(Date.now(), id);
236
+ this.db.prepare('UPDATE memories SET ' + sets.join(', ') + ' WHERE id = ?').run(...values);
237
+ return this.getMemory(id);
238
+ }
239
+ /**
240
+ * Put a memory to sleep: out of recall, still in the table and in the UI.
241
+ * `sleep_run_id` records the run that did it, which is what undo looks for,
242
+ * so it is overwritten rather than kept - undo always targets the night
243
+ * that last touched a memory.
244
+ */
245
+ sleepMemory(id, options = {}) {
246
+ // `updated_at` is deliberately left alone: it means "when the content
247
+ // last changed", and filing a memory away is not a change to what it
248
+ // says. Bumping it made an old memory look fresh to the recency score,
249
+ // so after an undo the night would no longer recognise it as stale.
250
+ this.db
251
+ .prepare(`UPDATE memories
252
+ SET dormant_at = ?, superseded_by = ?,
253
+ sleep_run_id = COALESCE(?, sleep_run_id)
254
+ WHERE id = ?`)
255
+ .run(Date.now(), options.supersededBy ?? null, options.runId ?? null, id);
256
+ }
257
+ /** Bring one back. The inspector's "wake" button, and what undo uses. */
258
+ wakeMemory(id) {
259
+ this.db
260
+ .prepare('UPDATE memories SET dormant_at = NULL, superseded_by = NULL WHERE id = ?')
261
+ .run(id);
262
+ }
263
+ getMemory(id) {
264
+ const row = this.db.prepare('SELECT * FROM memories WHERE id = ?').get(id);
265
+ return row ? mapMemory(row) : null;
266
+ }
267
+ /**
268
+ * Browse the bank. Sleeping memories are included by default because this
269
+ * is what the inspector lists; the recall path filters them out itself.
270
+ */
271
+ listMemories(options = {}) {
272
+ const limit = options.limit ?? 200;
273
+ const kinds = options.kinds ?? [];
274
+ const owner = options.owner ?? ASSISTANT_MEMORY_OWNER;
275
+ const placeholders = kinds.map(() => '?').join(', ');
276
+ const sql = 'SELECT * FROM memories WHERE owner = ? AND (? = 1 OR forgotten = 0)' +
277
+ (options.includeDormant === false ? ' AND dormant_at IS NULL' : '') +
278
+ (options.since ? ' AND created_at >= ?' : '') +
279
+ (kinds.length ? ' AND kind IN (' + placeholders + ')' : '') +
280
+ ' ORDER BY importance DESC, updated_at DESC LIMIT ?';
281
+ const values = [owner, options.includeForgotten ? 1 : 0];
282
+ if (options.since)
283
+ values.push(options.since);
284
+ values.push(...kinds, limit);
285
+ const rows = this.db.prepare(sql).all(...values);
286
+ return rows.map(mapMemory);
287
+ }
288
+ /**
289
+ * Live memories that carry tags but hang off no entity yet.
290
+ *
291
+ * Everything written before the graph existed is in this state, and so is
292
+ * anything whose entity links were lost. Light sleep uses this to catch a
293
+ * bank up without a single model call.
294
+ */
295
+ memoriesWithoutEntities(owner, limit = 500) {
296
+ const rows = this.db
297
+ .prepare(`SELECT m.* FROM memories m
298
+ WHERE m.owner = ? AND m.forgotten = 0 AND m.dormant_at IS NULL
299
+ AND m.tags != '[]'
300
+ AND NOT EXISTS (SELECT 1 FROM memory_entity_links l WHERE l.memory_id = m.id)
301
+ ORDER BY m.importance DESC
302
+ LIMIT ?`)
303
+ .all(owner, limit);
304
+ return rows.map(mapMemory);
305
+ }
306
+ /** Every live memory of one owner, oldest first. The sleep run's input. */
307
+ liveMemories(owner) {
308
+ const rows = this.db
309
+ .prepare(`SELECT * FROM memories
310
+ WHERE owner = ? AND forgotten = 0 AND dormant_at IS NULL
311
+ ORDER BY created_at ASC`)
312
+ .all(owner);
313
+ return rows.map(mapMemory);
314
+ }
315
+ /** Owners with at least one live memory. Used to decide which banks sleep. */
316
+ memoryOwners() {
317
+ const rows = this.db
318
+ .prepare(`SELECT owner, COUNT(*) AS live, MAX(created_at) AS newest
319
+ FROM memories
320
+ WHERE forgotten = 0 AND dormant_at IS NULL
321
+ GROUP BY owner`)
322
+ .all();
323
+ return rows.map((row) => ({
324
+ owner: row.owner,
325
+ live: Number(row.live ?? 0),
326
+ newest: Number(row.newest ?? 0),
327
+ }));
328
+ }
329
+ /** Soft delete, so a wrong memory can be audited rather than vanishing. */
330
+ forgetMemory(id) {
331
+ this.db
332
+ .prepare('UPDATE memories SET forgotten = 1, updated_at = ? WHERE id = ?')
333
+ .run(Date.now(), id);
334
+ }
335
+ deleteMemory(id) {
336
+ this.db.prepare('DELETE FROM memories WHERE id = ?').run(id);
337
+ }
338
+ /**
339
+ * Record that a memory was actually used. This is the only path that
340
+ * raises `usefulness`, and it is damped so a single busy day cannot make
341
+ * a memory permanent.
342
+ */
343
+ touchMemories(ids) {
344
+ if (!ids.length)
345
+ return;
346
+ const now = Date.now();
347
+ const statement = this.db.prepare(`UPDATE memories
348
+ SET last_accessed_at = ?,
349
+ access_count = access_count + 1,
350
+ usefulness = MIN(1.0, usefulness + 0.03)
351
+ WHERE id = ?`);
352
+ for (const id of ids)
353
+ statement.run(now, id);
354
+ }
355
+ memoryStats(owner = ASSISTANT_MEMORY_OWNER) {
356
+ const count = (sql) => this.db.prepare(sql).get(owner)?.n ?? 0;
357
+ const total = count('SELECT COUNT(*) AS n FROM memories WHERE owner = ? AND forgotten = 0 AND dormant_at IS NULL');
358
+ const forgotten = count('SELECT COUNT(*) AS n FROM memories WHERE owner = ? AND forgotten = 1');
359
+ const dormant = count('SELECT COUNT(*) AS n FROM memories WHERE owner = ? AND forgotten = 0 AND dormant_at IS NOT NULL');
360
+ const pinned = count('SELECT COUNT(*) AS n FROM memories WHERE owner = ? AND forgotten = 0 AND pinned = 1');
361
+ const entities = count('SELECT COUNT(*) AS n FROM memory_entities WHERE owner = ?');
362
+ const edges = count('SELECT COUNT(*) AS n FROM memory_edges WHERE owner = ?');
363
+ const rows = this.db
364
+ .prepare(`SELECT kind, COUNT(*) AS n FROM memories
365
+ WHERE owner = ? AND forgotten = 0 AND dormant_at IS NULL GROUP BY kind`)
366
+ .all(owner);
367
+ const byKind = {};
368
+ for (const row of rows)
369
+ byKind[row.kind] = row.n;
370
+ return { total, byKind, forgotten, dormant, pinned, entities, edges };
371
+ }
372
+ /* ----------------------------- statistics ---------------------------- */
373
+ /**
374
+ * The dashboard's numbers: real totals, plus a day-by-day series.
375
+ *
376
+ * `memoryStats` answers "what does the bank hold"; this answers "how much
377
+ * is there across the whole system, and when did it happen". Both count in
378
+ * SQL rather than over a fetched page, because every list endpoint is
379
+ * capped and a number derived from a capped list is silently wrong once
380
+ * the cap bites.
381
+ *
382
+ * Days are local calendar days. The server runs on the same machine as the
383
+ * person reading the chart, so "Tuesday" should mean the Tuesday they had,
384
+ * not the one UTC had. Empty days are not emitted - the client knows which
385
+ * window it wants and fills the gaps itself.
386
+ */
387
+ stats(options) {
388
+ const owner = options.owner || ASSISTANT_MEMORY_OWNER;
389
+ const until = options.until ?? Date.now();
390
+ const since = Math.min(options.since, until);
391
+ const count = (sql, ...values) => this.db.prepare(sql).get(...values)?.n ?? 0;
392
+ // Reused rather than recounted, so the dashboard and the memory page can
393
+ // never disagree about how many memories there are.
394
+ const memory = this.memoryStats(owner);
395
+ const totals = {
396
+ sessions: count('SELECT COUNT(*) AS n FROM sessions WHERE archived = 0'),
397
+ archivedSessions: count('SELECT COUNT(*) AS n FROM sessions WHERE archived = 1'),
398
+ messages: count('SELECT COUNT(*) AS n FROM messages'),
399
+ assignments: count('SELECT COUNT(*) AS n FROM assignments WHERE org_id = ?', options.orgId),
400
+ runningAssignments: count("SELECT COUNT(*) AS n FROM assignments WHERE org_id = ? AND status IN ('pending', 'running')", options.orgId),
401
+ tasks: count('SELECT COUNT(*) AS n FROM tasks WHERE org_id = ?', options.orgId),
402
+ openTasks: count("SELECT COUNT(*) AS n FROM tasks WHERE org_id = ? AND status IN ('open', 'planned', 'running')", options.orgId),
403
+ cronJobs: count('SELECT COUNT(*) AS n FROM cron_jobs WHERE org_id = ?', options.orgId),
404
+ cronRuns: count('SELECT COUNT(*) AS n FROM cron_runs WHERE org_id = ?', options.orgId),
405
+ memories: memory.total,
406
+ agents: count('SELECT COUNT(*) AS n FROM agents WHERE org_id = ? AND archived = 0', options.orgId),
407
+ };
408
+ const buckets = new Map();
409
+ const bucket = (day) => {
410
+ const existing = buckets.get(day);
411
+ if (existing)
412
+ return existing;
413
+ const created = {
414
+ day,
415
+ sessions: 0,
416
+ messages: 0,
417
+ assignments: 0,
418
+ tasks: 0,
419
+ cronRuns: 0,
420
+ memories: 0,
421
+ inputTokens: 0,
422
+ outputTokens: 0,
423
+ };
424
+ buckets.set(day, created);
425
+ return created;
426
+ };
427
+ /**
428
+ * One GROUP BY per table. Timestamps are milliseconds and SQLite's date
429
+ * functions want seconds, hence the division; `localtime` is what turns
430
+ * an instant into the day the user had. Table and column are literals
431
+ * from the calls right below, never anything a request carried.
432
+ */
433
+ const perDay = (table, column, filter, values) => {
434
+ const rows = this.db
435
+ .prepare(`SELECT strftime('%Y-%m-%d', ${column} / 1000, 'unixepoch', 'localtime') AS day, COUNT(*) AS n
436
+ FROM ${table}
437
+ WHERE ${column} >= ? AND ${column} <= ?` +
438
+ (filter ? ' AND ' + filter : '') +
439
+ ' GROUP BY day')
440
+ .all(...[since, until, ...values]);
441
+ return new Map(rows.map((row) => [String(row.day), Number(row.n ?? 0)]));
442
+ };
443
+ for (const [day, n] of perDay('sessions', 'created_at', '', []))
444
+ bucket(day).sessions = n;
445
+ for (const [day, n] of perDay('messages', 'created_at', '', []))
446
+ bucket(day).messages = n;
447
+ for (const [day, n] of perDay('assignments', 'created_at', 'org_id = ?', [options.orgId]))
448
+ bucket(day).assignments = n;
449
+ for (const [day, n] of perDay('tasks', 'created_at', 'org_id = ?', [options.orgId]))
450
+ bucket(day).tasks = n;
451
+ // A run is dated by when it started; `finished_at` is null while it runs.
452
+ for (const [day, n] of perDay('cron_runs', 'started_at', 'org_id = ?', [options.orgId]))
453
+ bucket(day).cronRuns = n;
454
+ for (const [day, n] of perDay('memories', 'created_at', 'owner = ?', [owner]))
455
+ bucket(day).memories = n;
456
+ // `messages.usage` is a JSON blob rather than columns, so the tokens can
457
+ // only be summed with json_extract. That is the difference between one
458
+ // query and one request per conversation, and worth the guard: json_valid
459
+ // skips anything an older build may have written, and if the function is
460
+ // missing altogether the two figures simply stay unknown.
461
+ let tokensAvailable = false;
462
+ try {
463
+ const rows = this.db
464
+ .prepare(`SELECT strftime('%Y-%m-%d', created_at / 1000, 'unixepoch', 'localtime') AS day,
465
+ SUM(COALESCE(json_extract(usage, '$.inputTokens'), 0)) AS input_tokens,
466
+ SUM(COALESCE(json_extract(usage, '$.outputTokens'), 0)) AS output_tokens
467
+ FROM messages
468
+ WHERE created_at >= ? AND created_at <= ? AND usage IS NOT NULL AND json_valid(usage)
469
+ GROUP BY day`)
470
+ .all(...[since, until]);
471
+ tokensAvailable = rows.length > 0;
472
+ for (const row of rows) {
473
+ const entry = bucket(String(row.day));
474
+ entry.inputTokens = Number(row.input_tokens ?? 0);
475
+ entry.outputTokens = Number(row.output_tokens ?? 0);
476
+ }
477
+ }
478
+ catch {
479
+ tokensAvailable = false;
480
+ }
481
+ const series = [...buckets.values()].sort((a, b) => a.day.localeCompare(b.day));
482
+ return { since, until, orgId: options.orgId, owner, totals, series, tokensAvailable };
483
+ }
484
+ /* ---------------------------- entities ---------------------------- */
485
+ /**
486
+ * Find or create the entity for a name, and count the mention. Entities
487
+ * come from memory tags at write time and get their proper kind and their
488
+ * merged spellings from the nightly run.
489
+ */
490
+ upsertEntity(input) {
491
+ const name = input.name.trim();
492
+ const slug = entitySlug(name);
493
+ if (!slug)
494
+ throw new Error('An entity needs a name.');
495
+ const now = Date.now();
496
+ const existing = this.db
497
+ .prepare('SELECT * FROM memory_entities WHERE owner = ? AND slug = ?')
498
+ .get(input.owner, slug);
499
+ if (existing) {
500
+ // A concrete kind wins over the default `topic`, but never the other way.
501
+ const kind = input.kind && input.kind !== 'topic' ? input.kind : existing.kind;
502
+ this.db
503
+ .prepare('UPDATE memory_entities SET kind = ?, last_seen_at = ? WHERE id = ?')
504
+ .run(kind, now, existing.id);
505
+ return mapEntity({ ...existing, kind, last_seen_at: now });
506
+ }
507
+ const entity = {
508
+ id: randomUUID(),
509
+ owner: input.owner,
510
+ name,
511
+ slug,
512
+ kind: input.kind ?? 'topic',
513
+ mentions: 0,
514
+ firstSeenAt: now,
515
+ lastSeenAt: now,
516
+ };
517
+ this.db
518
+ .prepare(`INSERT INTO memory_entities (id, owner, name, slug, kind, mentions, first_seen_at, last_seen_at)
519
+ VALUES (?, ?, ?, ?, ?, 0, ?, ?)`)
520
+ .run(entity.id, entity.owner, entity.name, entity.slug, entity.kind, now, now);
521
+ return entity;
522
+ }
523
+ getEntity(id) {
524
+ const row = this.db.prepare('SELECT * FROM memory_entities WHERE id = ?').get(id);
525
+ return row ? mapEntity(row) : null;
526
+ }
527
+ findEntity(owner, name) {
528
+ const row = this.db
529
+ .prepare('SELECT * FROM memory_entities WHERE owner = ? AND slug = ?')
530
+ .get(owner, entitySlug(name));
531
+ return row ? mapEntity(row) : null;
532
+ }
533
+ /** Entities of one owner, most-mentioned first. */
534
+ listEntities(options = {}) {
535
+ const rows = this.db
536
+ .prepare(`SELECT * FROM memory_entities
537
+ WHERE owner = ? AND mentions >= ?
538
+ ORDER BY mentions DESC, last_seen_at DESC
539
+ LIMIT ?`)
540
+ .all(options.owner ?? ASSISTANT_MEMORY_OWNER, options.minMentions ?? 1, options.limit ?? 200);
541
+ return rows.map(mapEntity);
542
+ }
543
+ /** Attach a memory to an entity. Idempotent; the mention count follows. */
544
+ linkEntity(memoryId, entityId, weight = 1) {
545
+ this.db
546
+ .prepare('INSERT OR REPLACE INTO memory_entity_links (memory_id, entity_id, weight) VALUES (?, ?, ?)')
547
+ .run(memoryId, entityId, weight);
548
+ this.recountEntity(entityId);
549
+ }
550
+ unlinkEntity(memoryId, entityId) {
551
+ this.db
552
+ .prepare('DELETE FROM memory_entity_links WHERE memory_id = ? AND entity_id = ?')
553
+ .run(memoryId, entityId);
554
+ this.recountEntity(entityId);
555
+ }
556
+ /** Recount live mentions of one entity, and drop it when nothing is left. */
557
+ recountEntity(entityId) {
558
+ const row = this.db
559
+ .prepare(`SELECT COUNT(*) AS n
560
+ FROM memory_entity_links l
561
+ JOIN memories m ON m.id = l.memory_id
562
+ WHERE l.entity_id = ? AND m.forgotten = 0 AND m.dormant_at IS NULL`)
563
+ .get(entityId);
564
+ this.db.prepare('UPDATE memory_entities SET mentions = ? WHERE id = ?').run(row.n, entityId);
565
+ }
566
+ /** Recount every entity of one owner. Cheap enough to run after a night. */
567
+ recountEntities(owner) {
568
+ this.db
569
+ .prepare(`UPDATE memory_entities
570
+ SET mentions = (
571
+ SELECT COUNT(*) FROM memory_entity_links l
572
+ JOIN memories m ON m.id = l.memory_id
573
+ WHERE l.entity_id = memory_entities.id
574
+ AND m.forgotten = 0 AND m.dormant_at IS NULL
575
+ )
576
+ WHERE owner = ?`)
577
+ .run(owner);
578
+ }
579
+ entitiesFor(memoryId) {
580
+ const rows = this.db
581
+ .prepare(`SELECT e.* FROM memory_entities e
582
+ JOIN memory_entity_links l ON l.entity_id = e.id
583
+ WHERE l.memory_id = ?
584
+ ORDER BY e.mentions DESC`)
585
+ .all(memoryId);
586
+ return rows.map(mapEntity);
587
+ }
588
+ /** Live memories linked to any of these entities, excluding the ones given. */
589
+ memoriesForEntities(entityIds, options = {}) {
590
+ if (!entityIds.length)
591
+ return [];
592
+ const exclude = options.exclude ?? [];
593
+ const sql = `SELECT DISTINCT m.* FROM memories m
594
+ JOIN memory_entity_links l ON l.memory_id = m.id
595
+ WHERE l.entity_id IN (` + entityIds.map(() => '?').join(', ') + `)
596
+ AND m.forgotten = 0 AND m.dormant_at IS NULL` +
597
+ (exclude.length ? ' AND m.id NOT IN (' + exclude.map(() => '?').join(', ') + ')' : '') +
598
+ ' ORDER BY m.importance DESC LIMIT ?';
599
+ const rows = this.db
600
+ .prepare(sql)
601
+ .all(...[...entityIds, ...exclude, options.limit ?? 40]);
602
+ return rows.map(mapMemory);
603
+ }
604
+ /* ------------------------------ edges ------------------------------ */
605
+ /**
606
+ * Draw a relation between two memories. The same triple is never stored
607
+ * twice; a repeat raises the weight instead.
608
+ */
609
+ addEdge(input) {
610
+ if (input.srcId === input.dstId)
611
+ return null;
612
+ const now = Date.now();
613
+ const existing = this.db
614
+ .prepare('SELECT * FROM memory_edges WHERE src_id = ? AND dst_id = ? AND relation = ?')
615
+ .get(input.srcId, input.dstId, input.relation);
616
+ if (existing) {
617
+ const weight = Math.min(1, Math.max(Number(existing.weight), input.weight ?? 0.5));
618
+ this.db.prepare('UPDATE memory_edges SET weight = ? WHERE id = ?').run(weight, existing.id);
619
+ return mapEdge({ ...existing, weight });
620
+ }
621
+ const edge = {
622
+ id: randomUUID(),
623
+ owner: input.owner,
624
+ srcId: input.srcId,
625
+ dstId: input.dstId,
626
+ relation: input.relation,
627
+ weight: clamp01(input.weight ?? 0.5),
628
+ origin: input.origin ?? 'sleep',
629
+ runId: input.runId,
630
+ createdAt: now,
631
+ };
632
+ this.db
633
+ .prepare(`INSERT INTO memory_edges (id, owner, src_id, dst_id, relation, weight, origin, run_id, created_at)
634
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
635
+ .run(edge.id, edge.owner, edge.srcId, edge.dstId, edge.relation, edge.weight, edge.origin, edge.runId ?? null, now);
636
+ return edge;
637
+ }
638
+ /** Edges leaving these memories, optionally narrowed to some relations. */
639
+ edgesFrom(ids, relations) {
640
+ if (!ids.length)
641
+ return [];
642
+ const sql = 'SELECT * FROM memory_edges WHERE src_id IN (' + ids.map(() => '?').join(', ') + ')' +
643
+ (relations?.length ? ' AND relation IN (' + relations.map(() => '?').join(', ') + ')' : '');
644
+ const rows = this.db.prepare(sql).all(...[...ids, ...(relations ?? [])]);
645
+ return rows.map(mapEdge);
646
+ }
647
+ listEdges(owner, limit = 500) {
648
+ const rows = this.db
649
+ .prepare('SELECT * FROM memory_edges WHERE owner = ? ORDER BY created_at DESC LIMIT ?')
650
+ .all(owner, limit);
651
+ return rows.map(mapEdge);
652
+ }
653
+ deleteEdge(id) {
654
+ this.db.prepare('DELETE FROM memory_edges WHERE id = ?').run(id);
655
+ }
656
+ /** Everything hanging off one memory, for the inspector's detail panel. */
657
+ neighbourhood(id) {
658
+ const memory = this.getMemory(id);
659
+ if (!memory)
660
+ return null;
661
+ const outgoing = this.db
662
+ .prepare(`SELECT e.*, m.id AS o_id FROM memory_edges e JOIN memories m ON m.id = e.dst_id WHERE e.src_id = ?`)
663
+ .all(id)
664
+ .map((row) => ({ ...mapEdge(row), other: this.getMemory(row.o_id) }))
665
+ .filter((edge) => Boolean(edge.other));
666
+ const incoming = this.db
667
+ .prepare(`SELECT e.*, m.id AS o_id FROM memory_edges e JOIN memories m ON m.id = e.src_id WHERE e.dst_id = ?`)
668
+ .all(id)
669
+ .map((row) => ({ ...mapEdge(row), other: this.getMemory(row.o_id) }))
670
+ .filter((edge) => Boolean(edge.other));
671
+ return { memory, entities: this.entitiesFor(id), outgoing, incoming };
672
+ }
673
+ /**
674
+ * The graph the web view draws. Capped hard: a hairball of every memory
675
+ * ever stored is not a picture of anything.
676
+ */
677
+ memoryGraph(options = {}) {
678
+ const owner = options.owner ?? ASSISTANT_MEMORY_OWNER;
679
+ const limit = Math.max(10, Math.min(options.limit ?? 300, 1000));
680
+ const kinds = options.kinds ?? [];
681
+ const filters = ' AND m.forgotten = 0' +
682
+ (options.includeDormant ? '' : ' AND m.dormant_at IS NULL') +
683
+ (options.since ? ' AND m.created_at >= ?' : '') +
684
+ (kinds.length ? ' AND m.kind IN (' + kinds.map(() => '?').join(', ') + ')' : '');
685
+ const values = [owner];
686
+ if (options.entityId)
687
+ values.push(options.entityId);
688
+ if (options.since)
689
+ values.push(options.since);
690
+ values.push(...kinds, limit + 1);
691
+ const sql = options.entityId
692
+ ? `SELECT m.* FROM memories m
693
+ JOIN memory_entity_links l ON l.memory_id = m.id
694
+ WHERE m.owner = ? AND l.entity_id = ?` + filters +
695
+ ' ORDER BY m.importance DESC, m.updated_at DESC LIMIT ?'
696
+ : `SELECT m.* FROM memories m WHERE m.owner = ?` + filters +
697
+ ' ORDER BY m.importance DESC, m.updated_at DESC LIMIT ?';
698
+ const rows = this.db.prepare(sql).all(...values);
699
+ const truncated = rows.length > limit;
700
+ const memories = rows.slice(0, limit).map(mapMemory);
701
+ const ids = memories.map((memory) => memory.id);
702
+ if (!ids.length)
703
+ return { entities: [], memories: [], edges: [], links: [], truncated: false };
704
+ const placeholders = ids.map(() => '?').join(', ');
705
+ const linkRows = this.db
706
+ .prepare('SELECT memory_id, entity_id FROM memory_entity_links WHERE memory_id IN (' + placeholders + ')')
707
+ .all(...ids);
708
+ const links = linkRows.map((row) => ({
709
+ memoryId: row.memory_id,
710
+ entityId: row.entity_id,
711
+ }));
712
+ const entityIds = [...new Set(links.map((link) => link.entityId))];
713
+ const entities = entityIds.length
714
+ ? this.db
715
+ .prepare('SELECT * FROM memory_entities WHERE id IN (' + entityIds.map(() => '?').join(', ') + ')')
716
+ .all(...entityIds).map(mapEntity)
717
+ : [];
718
+ // Only edges with both ends inside the picture; a dangling line is noise.
719
+ const edges = this.db
720
+ .prepare('SELECT * FROM memory_edges WHERE src_id IN (' + placeholders + ') AND dst_id IN (' + placeholders + ')')
721
+ .all(...[...ids, ...ids]).map(mapEdge);
722
+ return { entities, memories, edges, links, truncated };
723
+ }
724
+ /* --------------------------- sleep runs --------------------------- */
725
+ createSleepRun(input) {
726
+ const run = {
727
+ id: randomUUID(),
728
+ owner: input.owner,
729
+ trigger: input.trigger,
730
+ status: 'running',
731
+ startedAt: Date.now(),
732
+ readCount: 0,
733
+ mergedCount: 0,
734
+ dormantCount: 0,
735
+ edgeCount: 0,
736
+ insightCount: 0,
737
+ conflictCount: 0,
738
+ resolvedCount: 0,
739
+ modelCalls: 0,
740
+ };
741
+ this.db
742
+ .prepare('INSERT INTO sleep_runs (id, owner, trigger, status, started_at) VALUES (?, ?, ?, ?, ?)')
743
+ .run(run.id, run.owner, run.trigger, run.status, run.startedAt);
744
+ return run;
745
+ }
746
+ updateSleepRun(id, patch) {
747
+ const columns = {
748
+ status: 'status',
749
+ finishedAt: 'finished_at',
750
+ durationMs: 'duration_ms',
751
+ readCount: 'read_count',
752
+ mergedCount: 'merged_count',
753
+ dormantCount: 'dormant_count',
754
+ edgeCount: 'edge_count',
755
+ insightCount: 'insight_count',
756
+ conflictCount: 'conflict_count',
757
+ resolvedCount: 'resolved_count',
758
+ modelCalls: 'model_calls',
759
+ report: 'report',
760
+ error: 'error',
761
+ undoneAt: 'undone_at',
762
+ };
763
+ const sets = [];
764
+ const values = [];
765
+ for (const [key, column] of Object.entries(columns)) {
766
+ const value = patch[key];
767
+ if (value === undefined)
768
+ continue;
769
+ sets.push(column + ' = ?');
770
+ values.push(value);
771
+ }
772
+ if (!sets.length)
773
+ return this.getSleepRun(id);
774
+ values.push(id);
775
+ this.db.prepare('UPDATE sleep_runs SET ' + sets.join(', ') + ' WHERE id = ?').run(...values);
776
+ return this.getSleepRun(id);
777
+ }
778
+ getSleepRun(id) {
779
+ const row = this.db.prepare('SELECT * FROM sleep_runs WHERE id = ?').get(id);
780
+ return row ? mapSleepRun(row) : null;
781
+ }
782
+ listSleepRuns(options = {}) {
783
+ const rows = options.owner
784
+ ? this.db
785
+ .prepare('SELECT * FROM sleep_runs WHERE owner = ? ORDER BY started_at DESC LIMIT ?')
786
+ .all(options.owner, options.limit ?? 30)
787
+ : this.db
788
+ .prepare('SELECT * FROM sleep_runs ORDER BY started_at DESC LIMIT ?')
789
+ .all(options.limit ?? 30);
790
+ return rows.map(mapSleepRun);
791
+ }
792
+ /** When this owner last finished a night. Drives "what is new since then". */
793
+ lastSleepAt(owner) {
794
+ const row = this.db
795
+ .prepare("SELECT MAX(finished_at) AS at FROM sleep_runs WHERE owner = ? AND status = 'done' AND undone_at IS NULL")
796
+ .get(owner);
797
+ return Number(row?.at ?? 0);
798
+ }
799
+ /**
800
+ * Take back one night, in a single transaction: the memories the run wrote
801
+ * are deleted, everything it put to sleep wakes up, and its edges go. This
802
+ * is what makes an unattended nightly process acceptable at all.
803
+ */
804
+ undoSleepRun(id) {
805
+ const run = this.getSleepRun(id);
806
+ if (!run || run.undoneAt)
807
+ return null;
808
+ const counts = { woken: 0, removed: 0, edges: 0 };
809
+ // Counted up front: deleting a memory cascades its edges away, so a
810
+ // count taken afterwards would report a fraction of what actually went.
811
+ const edgesBefore = this.db
812
+ .prepare('SELECT COUNT(*) AS n FROM memory_edges WHERE run_id = ?')
813
+ .get(id).n;
814
+ this.db.exec('BEGIN');
815
+ try {
816
+ // The two sets are kept disjoint: a memory this run wrote and a memory
817
+ // it put to sleep are handled by different branches, never both.
818
+ const written = this.db
819
+ .prepare("SELECT id FROM memories WHERE sleep_run_id = ? AND origin = 'sleep' AND dormant_at IS NULL")
820
+ .all(id);
821
+ // Anything that pointed at a memory this run created must let go first.
822
+ for (const row of written) {
823
+ this.db
824
+ .prepare('UPDATE memories SET superseded_by = NULL WHERE superseded_by = ?')
825
+ .run(row.id);
826
+ }
827
+ const asleep = this.db
828
+ .prepare('SELECT id FROM memories WHERE sleep_run_id = ? AND dormant_at IS NOT NULL')
829
+ .all(id);
830
+ for (const row of asleep) {
831
+ this.db
832
+ .prepare('UPDATE memories SET dormant_at = NULL, superseded_by = NULL, sleep_run_id = NULL WHERE id = ?')
833
+ .run(row.id);
834
+ counts.woken += 1;
835
+ }
836
+ for (const row of written) {
837
+ this.db.prepare('DELETE FROM memories WHERE id = ?').run(row.id);
838
+ counts.removed += 1;
839
+ }
840
+ this.db.prepare('DELETE FROM memory_edges WHERE run_id = ?').run(id);
841
+ counts.edges = edgesBefore;
842
+ this.db
843
+ .prepare('UPDATE sleep_runs SET undone_at = ? WHERE id = ?')
844
+ .run(Date.now(), id);
845
+ this.db.exec('COMMIT');
846
+ }
847
+ catch (error) {
848
+ this.db.exec('ROLLBACK');
849
+ throw error;
850
+ }
851
+ this.recountEntities(run.owner);
852
+ return counts;
853
+ }
854
+ /* ------------------------------- meta ------------------------------- */
855
+ // Beyond the schema version, `meta` is a generic key/value store for small
856
+ // mappings that don't warrant their own table, e.g. Telegram-chat-to-session.
857
+ getMeta(key) {
858
+ const row = this.db.prepare('SELECT value FROM meta WHERE key = ?').get(key);
859
+ return row ? row.value : null;
860
+ }
861
+ setMeta(key, value) {
862
+ this.db.prepare('INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)').run(key, value);
863
+ }
864
+ deleteMeta(key) {
865
+ this.db.prepare('DELETE FROM meta WHERE key = ?').run(key);
866
+ }
867
+ }
868
+ /* ------------------------------ mappers ------------------------------ */
869
+ function mapSession(row) {
870
+ return {
871
+ id: row.id,
872
+ title: row.title,
873
+ kind: (row.kind === 'voice' ? 'voice' : 'chat'),
874
+ provider: row.provider,
875
+ model: row.model ?? undefined,
876
+ cwd: row.cwd,
877
+ projectId: row.project_id ?? undefined,
878
+ agentId: row.agent_id ?? undefined,
879
+ providerSessionId: row.provider_session_id ?? undefined,
880
+ createdAt: Number(row.created_at),
881
+ updatedAt: Number(row.updated_at),
882
+ archived: Number(row.archived) === 1,
883
+ messageCount: Number(row.message_count ?? 0),
884
+ };
885
+ }
886
+ function mapMessage(row) {
887
+ return {
888
+ id: row.id,
889
+ sessionId: row.session_id,
890
+ role: row.role,
891
+ content: row.content,
892
+ provider: row.provider ?? undefined,
893
+ model: row.model ?? undefined,
894
+ agent: row.agent ?? undefined,
895
+ toolCalls: row.tool_calls ? JSON.parse(row.tool_calls) : undefined,
896
+ usage: row.usage ? JSON.parse(row.usage) : undefined,
897
+ createdAt: Number(row.created_at),
898
+ };
899
+ }
900
+ export function mapMemory(row) {
901
+ return {
902
+ id: row.id,
903
+ kind: row.kind,
904
+ content: row.content,
905
+ tags: parseTags(row.tags),
906
+ importance: Number(row.importance),
907
+ owner: row.owner ?? ASSISTANT_MEMORY_OWNER,
908
+ sourceSessionId: row.source_session_id ?? undefined,
909
+ createdAt: Number(row.created_at),
910
+ updatedAt: Number(row.updated_at),
911
+ lastAccessedAt: row.last_accessed_at ? Number(row.last_accessed_at) : undefined,
912
+ accessCount: Number(row.access_count ?? 0),
913
+ forgotten: Number(row.forgotten) === 1,
914
+ origin: (row.origin ?? 'extract'),
915
+ pinned: Number(row.pinned ?? 0) === 1,
916
+ dormantAt: row.dormant_at ? Number(row.dormant_at) : undefined,
917
+ supersededBy: row.superseded_by ?? undefined,
918
+ sleepRunId: row.sleep_run_id ?? undefined,
919
+ usefulness: Number(row.usefulness ?? 0),
920
+ };
921
+ }
922
+ export function mapEntity(row) {
923
+ return {
924
+ id: row.id,
925
+ owner: row.owner,
926
+ name: row.name,
927
+ slug: row.slug,
928
+ kind: (row.kind ?? 'topic'),
929
+ mentions: Number(row.mentions ?? 0),
930
+ firstSeenAt: Number(row.first_seen_at),
931
+ lastSeenAt: Number(row.last_seen_at),
932
+ };
933
+ }
934
+ export function mapEdge(row) {
935
+ return {
936
+ id: row.id,
937
+ owner: row.owner,
938
+ srcId: row.src_id,
939
+ dstId: row.dst_id,
940
+ relation: row.relation,
941
+ weight: Number(row.weight ?? 0.5),
942
+ origin: (row.origin ?? 'sleep'),
943
+ runId: row.run_id ?? undefined,
944
+ createdAt: Number(row.created_at),
945
+ };
946
+ }
947
+ export function mapSleepRun(row) {
948
+ return {
949
+ id: row.id,
950
+ owner: row.owner,
951
+ trigger: row.trigger,
952
+ status: row.status,
953
+ startedAt: Number(row.started_at),
954
+ finishedAt: row.finished_at ? Number(row.finished_at) : undefined,
955
+ durationMs: row.duration_ms ? Number(row.duration_ms) : undefined,
956
+ readCount: Number(row.read_count ?? 0),
957
+ mergedCount: Number(row.merged_count ?? 0),
958
+ dormantCount: Number(row.dormant_count ?? 0),
959
+ edgeCount: Number(row.edge_count ?? 0),
960
+ insightCount: Number(row.insight_count ?? 0),
961
+ conflictCount: Number(row.conflict_count ?? 0),
962
+ resolvedCount: Number(row.resolved_count ?? 0),
963
+ modelCalls: Number(row.model_calls ?? 0),
964
+ report: row.report ?? undefined,
965
+ error: row.error ?? undefined,
966
+ undoneAt: row.undone_at ? Number(row.undone_at) : undefined,
967
+ };
968
+ }
969
+ /**
970
+ * Normalise a name to the key entities are deduplicated by, so "Rookery",
971
+ * "rookery" and "Rookery-Agent " all land on the same node.
972
+ */
973
+ export function entitySlug(name) {
974
+ return name
975
+ .toLowerCase()
976
+ .normalize('NFKD')
977
+ .replace(/\p{Diacritic}/gu, '')
978
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
979
+ .replace(/^-+|-+$/g, '')
980
+ .slice(0, 60);
981
+ }
982
+ function parseTags(value) {
983
+ if (typeof value !== 'string')
984
+ return [];
985
+ try {
986
+ const parsed = JSON.parse(value);
987
+ return Array.isArray(parsed) ? parsed.map(String) : [];
988
+ }
989
+ catch {
990
+ return [];
991
+ }
992
+ }
993
+ function mergeTags(a, b) {
994
+ return [...new Set([...a, ...b])];
995
+ }
996
+ function clamp01(value) {
997
+ return Math.min(1, Math.max(0, value));
998
+ }
999
+ //# sourceMappingURL=store.js.map