@rubytech/create-sitedesk-code 0.1.517 → 0.1.519

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 (243) hide show
  1. package/dist/__tests__/edge-bind-template-wiring.test.js +37 -0
  2. package/dist/__tests__/samba-provision.test.js +103 -1
  3. package/dist/__tests__/tier-flag.test.js +10 -6
  4. package/dist/index.js +20 -5
  5. package/dist/samba-provision.js +72 -0
  6. package/dist/tier-flag.js +10 -5
  7. package/package.json +1 -1
  8. package/payload/platform/lib/entitlement/dist/index.d.ts +24 -0
  9. package/payload/platform/lib/entitlement/dist/index.d.ts.map +1 -1
  10. package/payload/platform/lib/entitlement/dist/index.js +40 -2
  11. package/payload/platform/lib/entitlement/dist/index.js.map +1 -1
  12. package/payload/platform/plugins/admin/mcp/dist/index.js +5 -9
  13. package/payload/platform/plugins/admin/mcp/dist/index.js.map +1 -1
  14. package/payload/platform/plugins/admin/skills/admin-user-management/SKILL.md +1 -1
  15. package/payload/platform/plugins/admin/skills/platform-architecture/SKILL.md +261 -8
  16. package/payload/platform/plugins/admin/skills/whats-new/SKILL.md +12 -0
  17. package/payload/platform/plugins/docs/references/admin-ui.md +44 -6
  18. package/payload/platform/plugins/docs/references/samba.md +2 -0
  19. package/payload/platform/plugins/whatsapp/references/channels-whatsapp.md +7 -3
  20. package/payload/platform/scripts/check-no-esm-require.mjs +5 -3
  21. package/payload/platform/scripts/generate-entitlement-fixture.mjs +1 -1
  22. package/payload/platform/services/claude-session-manager/dist/rc-daemon.d.ts.map +1 -1
  23. package/payload/platform/services/claude-session-manager/dist/rc-daemon.js +16 -1
  24. package/payload/platform/services/claude-session-manager/dist/rc-daemon.js.map +1 -1
  25. package/payload/platform/services/claude-session-manager/dist/slice-memory-policy.d.ts.map +1 -1
  26. package/payload/platform/services/claude-session-manager/dist/slice-memory-policy.js +15 -0
  27. package/payload/platform/services/claude-session-manager/dist/slice-memory-policy.js.map +1 -1
  28. package/payload/platform/services/claude-session-manager/dist/webchat-channel-mcp.d.ts.map +1 -1
  29. package/payload/platform/services/claude-session-manager/dist/webchat-channel-mcp.js +5 -3
  30. package/payload/platform/services/claude-session-manager/dist/webchat-channel-mcp.js.map +1 -1
  31. package/payload/platform/services/telegram-channel/dist/instructions.d.ts.map +1 -1
  32. package/payload/platform/services/telegram-channel/dist/instructions.js +13 -10
  33. package/payload/platform/services/telegram-channel/dist/instructions.js.map +1 -1
  34. package/payload/platform/services/webchat-channel/dist/instructions.d.ts +6 -2
  35. package/payload/platform/services/webchat-channel/dist/instructions.d.ts.map +1 -1
  36. package/payload/platform/services/webchat-channel/dist/instructions.js +66 -32
  37. package/payload/platform/services/webchat-channel/dist/instructions.js.map +1 -1
  38. package/payload/platform/services/webchat-channel/dist/notification.d.ts +2 -1
  39. package/payload/platform/services/webchat-channel/dist/notification.d.ts.map +1 -1
  40. package/payload/platform/services/webchat-channel/dist/notification.js +11 -4
  41. package/payload/platform/services/webchat-channel/dist/notification.js.map +1 -1
  42. package/payload/platform/services/webchat-channel/dist/server.d.ts.map +1 -1
  43. package/payload/platform/services/webchat-channel/dist/server.js +30 -14
  44. package/payload/platform/services/webchat-channel/dist/server.js.map +1 -1
  45. package/payload/platform/services/webchat-channel/dist/turn-follow.d.ts.map +1 -1
  46. package/payload/platform/services/webchat-channel/dist/turn-follow.js +11 -5
  47. package/payload/platform/services/webchat-channel/dist/turn-follow.js.map +1 -1
  48. package/payload/platform/services/whatsapp-channel/dist/notification.d.ts +18 -4
  49. package/payload/platform/services/whatsapp-channel/dist/notification.d.ts.map +1 -1
  50. package/payload/platform/services/whatsapp-channel/dist/notification.js +19 -7
  51. package/payload/platform/services/whatsapp-channel/dist/notification.js.map +1 -1
  52. package/payload/platform/services/whatsapp-channel/dist/server.d.ts.map +1 -1
  53. package/payload/platform/services/whatsapp-channel/dist/server.js +23 -3
  54. package/payload/platform/services/whatsapp-channel/dist/server.js.map +1 -1
  55. package/payload/platform/services/whatsapp-channel/dist/targets.d.ts.map +1 -1
  56. package/payload/platform/services/whatsapp-channel/dist/targets.js +8 -2
  57. package/payload/platform/services/whatsapp-channel/dist/targets.js.map +1 -1
  58. package/payload/platform/templates/systemd/edge.service.template +1 -1
  59. package/payload/server/chunk-PXNY2TAP.js +1980 -0
  60. package/payload/server/chunk-TIIWMF5G.js +4837 -0
  61. package/payload/server/{chunk-S6HYTIU3.js → chunk-UX2FRNO7.js} +72 -2031
  62. package/payload/server/manager-B6OFOXSW.js +61 -0
  63. package/payload/server/maxy-edge.js +5 -3
  64. package/payload/server/package.json +2 -1
  65. package/payload/server/public/activity.html +5 -5
  66. package/payload/server/public/agents.html +4 -4
  67. package/payload/server/public/assets/{AdminLoginScreens-B5qKb3YK.js → AdminLoginScreens-BZPbCk8g.js} +1 -1
  68. package/payload/server/public/assets/AdminLoginScreens-BZPbCk8g.js.br +0 -0
  69. package/payload/server/public/assets/AdminLoginScreens-BZPbCk8g.js.gz +0 -0
  70. package/payload/server/public/assets/AdminShell-Bpo_wgxm.js +2 -0
  71. package/payload/server/public/assets/AdminShell-Bpo_wgxm.js.br +0 -0
  72. package/payload/server/public/assets/AdminShell-Bpo_wgxm.js.gz +0 -0
  73. package/payload/server/public/assets/{activity-DmnVUDYO.js → activity-DOsfKzT3.js} +1 -1
  74. package/payload/server/public/assets/activity-DOsfKzT3.js.br +0 -0
  75. package/payload/server/public/assets/activity-DOsfKzT3.js.gz +0 -0
  76. package/payload/server/public/assets/admin-COgD1z5a.js +1 -0
  77. package/payload/server/public/assets/admin-COgD1z5a.js.br +0 -0
  78. package/payload/server/public/assets/admin-COgD1z5a.js.gz +0 -0
  79. package/payload/server/public/assets/{agents-Bmq9X7P3.js → agents-DqDnZTH_.js} +1 -1
  80. package/payload/server/public/assets/agents-DqDnZTH_.js.br +0 -0
  81. package/payload/server/public/assets/agents-DqDnZTH_.js.gz +0 -0
  82. package/payload/server/public/assets/{browser-B1G-W80B.js → browser-FL17Dfp0.js} +1 -1
  83. package/payload/server/public/assets/browser-FL17Dfp0.js.br +0 -0
  84. package/payload/server/public/assets/browser-FL17Dfp0.js.gz +0 -0
  85. package/payload/server/public/assets/calendar-CLfLvsnV.js +1 -0
  86. package/payload/server/public/assets/calendar-CLfLvsnV.js.br +0 -0
  87. package/payload/server/public/assets/calendar-CLfLvsnV.js.gz +0 -0
  88. package/payload/server/public/assets/chat-DYq4FxMG.js +1 -0
  89. package/payload/server/public/assets/chat-DYq4FxMG.js.br +0 -0
  90. package/payload/server/public/assets/chat-DYq4FxMG.js.gz +0 -0
  91. package/payload/server/public/assets/chevron-left-DWt5cdUo.js +1 -0
  92. package/payload/server/public/assets/chevron-right-B9suVrYy.js +1 -0
  93. package/payload/server/public/assets/chevron-right-B9suVrYy.js.br +0 -0
  94. package/payload/server/public/assets/clock-DW6qVXtv.js +1 -0
  95. package/payload/server/public/assets/clock-DW6qVXtv.js.br +0 -0
  96. package/payload/server/public/assets/clock-DW6qVXtv.js.gz +0 -0
  97. package/payload/server/public/assets/data-C8rbOgds.js +1 -0
  98. package/payload/server/public/assets/data-C8rbOgds.js.br +0 -0
  99. package/payload/server/public/assets/data-C8rbOgds.js.gz +0 -0
  100. package/payload/server/public/assets/{file-text-BVqqaDun.js → file-text-DNm0AzUz.js} +1 -1
  101. package/payload/server/public/assets/file-text-DNm0AzUz.js.br +0 -0
  102. package/payload/server/public/assets/file-text-DNm0AzUz.js.gz +0 -0
  103. package/payload/server/public/assets/{graph-CEcME0lp.js → graph-fAvmlVzh.js} +3 -3
  104. package/payload/server/public/assets/graph-fAvmlVzh.js.br +0 -0
  105. package/payload/server/public/assets/graph-fAvmlVzh.js.gz +0 -0
  106. package/payload/server/public/assets/{graph-labels-Zl32_AOH.js → graph-labels-CwdkCxfs.js} +1 -1
  107. package/payload/server/public/assets/graph-labels-CwdkCxfs.js.br +0 -0
  108. package/payload/server/public/assets/graph-labels-CwdkCxfs.js.gz +0 -0
  109. package/payload/server/public/assets/{maximize-2-rkkMyAhf.js → maximize-2-B6tAPhC2.js} +1 -1
  110. package/payload/server/public/assets/maximize-2-B6tAPhC2.js.br +0 -0
  111. package/payload/server/public/assets/maximize-2-B6tAPhC2.js.gz +0 -0
  112. package/payload/server/public/assets/operator-CTKvBVjk.js +1 -0
  113. package/payload/server/public/assets/operator-CTKvBVjk.js.br +0 -0
  114. package/payload/server/public/assets/operator-CTKvBVjk.js.gz +0 -0
  115. package/payload/server/public/assets/page-BWoNW3sa.js +32 -0
  116. package/payload/server/public/assets/page-BWoNW3sa.js.br +0 -0
  117. package/payload/server/public/assets/page-BWoNW3sa.js.gz +0 -0
  118. package/payload/server/public/assets/page-O5HkHQw4.js +1 -0
  119. package/payload/server/public/assets/page-O5HkHQw4.js.br +0 -0
  120. package/payload/server/public/assets/page-O5HkHQw4.js.gz +0 -0
  121. package/payload/server/public/assets/{public-Cqgfmo1D.js → public-BF1rnVPa.js} +1 -1
  122. package/payload/server/public/assets/public-BF1rnVPa.js.br +0 -0
  123. package/payload/server/public/assets/public-BF1rnVPa.js.gz +0 -0
  124. package/payload/server/public/assets/{rotate-ccw-O3RmqoTy.js → rotate-ccw-B8TqfCy4.js} +1 -1
  125. package/payload/server/public/assets/rotate-ccw-B8TqfCy4.js.br +0 -0
  126. package/payload/server/public/assets/rotate-ccw-B8TqfCy4.js.gz +0 -0
  127. package/payload/server/public/assets/{routines-DMYObMUy.js → routines-4R7BLZyH.js} +1 -1
  128. package/payload/server/public/assets/routines-4R7BLZyH.js.br +0 -0
  129. package/payload/server/public/assets/routines-4R7BLZyH.js.gz +0 -0
  130. package/payload/server/public/assets/{skills-DON1BKu5.js → skills-CQ9Qs2tg.js} +1 -1
  131. package/payload/server/public/assets/skills-CQ9Qs2tg.js.br +0 -0
  132. package/payload/server/public/assets/skills-CQ9Qs2tg.js.gz +0 -0
  133. package/payload/server/public/assets/tasks-DePyOrRk.js +1 -0
  134. package/payload/server/public/assets/tasks-DePyOrRk.js.br +0 -0
  135. package/payload/server/public/assets/tasks-DePyOrRk.js.gz +0 -0
  136. package/payload/server/public/assets/{time-entry-format-4zgmuQI0.js → time-entry-format-D9gtnG01.js} +1 -1
  137. package/payload/server/public/assets/time-entry-format-D9gtnG01.js.br +0 -0
  138. package/payload/server/public/assets/time-entry-format-D9gtnG01.js.gz +0 -0
  139. package/payload/server/public/assets/{triangle-alert-By5D7wuI.js → triangle-alert-DAtm2mLL.js} +1 -1
  140. package/payload/server/public/assets/triangle-alert-DAtm2mLL.js.br +0 -0
  141. package/payload/server/public/assets/triangle-alert-DAtm2mLL.js.gz +0 -0
  142. package/payload/server/public/assets/{useCopyFeedback-Dx0vtm9s.js → useCopyFeedback-uMJT-p6i.js} +1 -1
  143. package/payload/server/public/assets/useCopyFeedback-uMJT-p6i.js.br +0 -0
  144. package/payload/server/public/assets/useCopyFeedback-uMJT-p6i.js.gz +0 -0
  145. package/payload/server/public/assets/useSubAccountSwitcher-BufCPDDH.js +14 -0
  146. package/payload/server/public/assets/useSubAccountSwitcher-BufCPDDH.js.br +0 -0
  147. package/payload/server/public/assets/useSubAccountSwitcher-BufCPDDH.js.gz +0 -0
  148. package/payload/server/public/assets/useSubAccountSwitcher-iCzsV96x.css +1 -0
  149. package/payload/server/public/assets/useSubAccountSwitcher-iCzsV96x.css.br +0 -0
  150. package/payload/server/public/assets/useSubAccountSwitcher-iCzsV96x.css.gz +0 -0
  151. package/payload/server/public/assets/useVoiceRecorder-BFrPC-s7.js +2 -0
  152. package/payload/server/public/assets/useVoiceRecorder-BFrPC-s7.js.br +0 -0
  153. package/payload/server/public/assets/useVoiceRecorder-BFrPC-s7.js.gz +0 -0
  154. package/payload/server/public/assets/{wrench-CHfMwLza.js → wrench-CYgaN7K9.js} +1 -1
  155. package/payload/server/public/assets/wrench-CYgaN7K9.js.br +1 -0
  156. package/payload/server/public/assets/wrench-CYgaN7K9.js.gz +0 -0
  157. package/payload/server/public/browser.html +4 -4
  158. package/payload/server/public/calendar.html +7 -7
  159. package/payload/server/public/chat.html +13 -13
  160. package/payload/server/public/data.html +11 -11
  161. package/payload/server/public/graph.html +9 -9
  162. package/payload/server/public/index.html +14 -14
  163. package/payload/server/public/operator.html +14 -14
  164. package/payload/server/public/public.html +13 -13
  165. package/payload/server/public/routines.html +6 -6
  166. package/payload/server/public/skills.html +5 -5
  167. package/payload/server/public/tasks.html +6 -6
  168. package/payload/server/server.js +8156 -11969
  169. package/payload/server/public/assets/AdminLoginScreens-B5qKb3YK.js.br +0 -0
  170. package/payload/server/public/assets/AdminLoginScreens-B5qKb3YK.js.gz +0 -0
  171. package/payload/server/public/assets/AdminShell-BgJEq2zJ.js +0 -2
  172. package/payload/server/public/assets/AdminShell-BgJEq2zJ.js.br +0 -0
  173. package/payload/server/public/assets/AdminShell-BgJEq2zJ.js.gz +0 -0
  174. package/payload/server/public/assets/activity-DmnVUDYO.js.br +0 -0
  175. package/payload/server/public/assets/activity-DmnVUDYO.js.gz +0 -0
  176. package/payload/server/public/assets/admin-Dpge4OG9.js +0 -1
  177. package/payload/server/public/assets/admin-Dpge4OG9.js.br +0 -0
  178. package/payload/server/public/assets/admin-Dpge4OG9.js.gz +0 -0
  179. package/payload/server/public/assets/agents-Bmq9X7P3.js.br +0 -0
  180. package/payload/server/public/assets/agents-Bmq9X7P3.js.gz +0 -0
  181. package/payload/server/public/assets/browser-B1G-W80B.js.br +0 -0
  182. package/payload/server/public/assets/browser-B1G-W80B.js.gz +0 -0
  183. package/payload/server/public/assets/calendar-CHgrOFIN.js +0 -1
  184. package/payload/server/public/assets/calendar-CHgrOFIN.js.br +0 -0
  185. package/payload/server/public/assets/calendar-CHgrOFIN.js.gz +0 -0
  186. package/payload/server/public/assets/chat-CIwmmtwP.js +0 -1
  187. package/payload/server/public/assets/chat-CIwmmtwP.js.br +0 -0
  188. package/payload/server/public/assets/chat-CIwmmtwP.js.gz +0 -0
  189. package/payload/server/public/assets/chevron-left-EQjfaQ-n.js +0 -1
  190. package/payload/server/public/assets/chevron-left-EQjfaQ-n.js.br +0 -0
  191. package/payload/server/public/assets/chevron-right-Ct8jZUGP.js +0 -1
  192. package/payload/server/public/assets/chevron-right-Ct8jZUGP.js.br +0 -0
  193. package/payload/server/public/assets/clock-Cxz5ybck.js +0 -1
  194. package/payload/server/public/assets/clock-Cxz5ybck.js.br +0 -0
  195. package/payload/server/public/assets/clock-Cxz5ybck.js.gz +0 -0
  196. package/payload/server/public/assets/data-BQVXKVsJ.js +0 -1
  197. package/payload/server/public/assets/data-BQVXKVsJ.js.br +0 -1
  198. package/payload/server/public/assets/data-BQVXKVsJ.js.gz +0 -0
  199. package/payload/server/public/assets/file-text-BVqqaDun.js.br +0 -0
  200. package/payload/server/public/assets/file-text-BVqqaDun.js.gz +0 -0
  201. package/payload/server/public/assets/graph-CEcME0lp.js.br +0 -0
  202. package/payload/server/public/assets/graph-CEcME0lp.js.gz +0 -0
  203. package/payload/server/public/assets/graph-labels-Zl32_AOH.js.br +0 -0
  204. package/payload/server/public/assets/graph-labels-Zl32_AOH.js.gz +0 -0
  205. package/payload/server/public/assets/maximize-2-rkkMyAhf.js.br +0 -0
  206. package/payload/server/public/assets/maximize-2-rkkMyAhf.js.gz +0 -0
  207. package/payload/server/public/assets/operator-DlL023ch.js +0 -1
  208. package/payload/server/public/assets/operator-DlL023ch.js.br +0 -0
  209. package/payload/server/public/assets/operator-DlL023ch.js.gz +0 -0
  210. package/payload/server/public/assets/page-BAmYYqxp.js +0 -1
  211. package/payload/server/public/assets/page-BAmYYqxp.js.br +0 -0
  212. package/payload/server/public/assets/page-BAmYYqxp.js.gz +0 -0
  213. package/payload/server/public/assets/page-k0BhBkA2.js +0 -32
  214. package/payload/server/public/assets/page-k0BhBkA2.js.br +0 -0
  215. package/payload/server/public/assets/page-k0BhBkA2.js.gz +0 -0
  216. package/payload/server/public/assets/public-Cqgfmo1D.js.br +0 -0
  217. package/payload/server/public/assets/public-Cqgfmo1D.js.gz +0 -0
  218. package/payload/server/public/assets/rotate-ccw-O3RmqoTy.js.br +0 -0
  219. package/payload/server/public/assets/rotate-ccw-O3RmqoTy.js.gz +0 -0
  220. package/payload/server/public/assets/routines-DMYObMUy.js.br +0 -0
  221. package/payload/server/public/assets/routines-DMYObMUy.js.gz +0 -0
  222. package/payload/server/public/assets/skills-DON1BKu5.js.br +0 -0
  223. package/payload/server/public/assets/skills-DON1BKu5.js.gz +0 -0
  224. package/payload/server/public/assets/tasks-C2PhUSrf.js +0 -1
  225. package/payload/server/public/assets/tasks-C2PhUSrf.js.br +0 -0
  226. package/payload/server/public/assets/tasks-C2PhUSrf.js.gz +0 -0
  227. package/payload/server/public/assets/time-entry-format-4zgmuQI0.js.br +0 -0
  228. package/payload/server/public/assets/time-entry-format-4zgmuQI0.js.gz +0 -0
  229. package/payload/server/public/assets/triangle-alert-By5D7wuI.js.br +0 -0
  230. package/payload/server/public/assets/triangle-alert-By5D7wuI.js.gz +0 -0
  231. package/payload/server/public/assets/useCopyFeedback-Dx0vtm9s.js.br +0 -0
  232. package/payload/server/public/assets/useCopyFeedback-Dx0vtm9s.js.gz +0 -0
  233. package/payload/server/public/assets/useSubAccountSwitcher-CRWoQXuU.js +0 -9
  234. package/payload/server/public/assets/useSubAccountSwitcher-CRWoQXuU.js.br +0 -0
  235. package/payload/server/public/assets/useSubAccountSwitcher-CRWoQXuU.js.gz +0 -0
  236. package/payload/server/public/assets/useSubAccountSwitcher-UQQDcj0B.css +0 -1
  237. package/payload/server/public/assets/useSubAccountSwitcher-UQQDcj0B.css.br +0 -0
  238. package/payload/server/public/assets/useSubAccountSwitcher-UQQDcj0B.css.gz +0 -0
  239. package/payload/server/public/assets/useVoiceRecorder-BgwOCCwj.js +0 -2
  240. package/payload/server/public/assets/useVoiceRecorder-BgwOCCwj.js.br +0 -0
  241. package/payload/server/public/assets/useVoiceRecorder-BgwOCCwj.js.gz +0 -0
  242. package/payload/server/public/assets/wrench-CHfMwLza.js.br +0 -0
  243. package/payload/server/public/assets/wrench-CHfMwLza.js.gz +0 -0
@@ -0,0 +1,1980 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+
3
+ // app/lib/paths.ts
4
+ import { homedir } from "os";
5
+ import { resolve, join } from "path";
6
+ import { existsSync, readFileSync } from "fs";
7
+ var configDirName = ".maxy";
8
+ var commercialMode = false;
9
+ var bundleMode = "none";
10
+ var bundleAllowlist = [];
11
+ var vncDisplayNum = 99;
12
+ var rfbPortNum = 5900;
13
+ var websockifyPortNum = 6080;
14
+ var cdpPortNum = 9222;
15
+ var portSource = "dev-default";
16
+ var platformRoot = process.env.MAXY_PLATFORM_ROOT;
17
+ if (platformRoot) {
18
+ const brandPath = join(platformRoot, "config", "brand.json");
19
+ if (existsSync(brandPath)) {
20
+ let brand;
21
+ try {
22
+ brand = JSON.parse(readFileSync(brandPath, "utf-8"));
23
+ } catch (err) {
24
+ const detail = (err instanceof Error ? err.message : String(err)).slice(0, 160);
25
+ console.error(`[paths] error reason=brand-config-missing path=${brandPath} detail="parse failed: ${detail.replace(/"/g, "'")}"`);
26
+ throw err;
27
+ }
28
+ if (typeof brand.configDir === "string") configDirName = brand.configDir;
29
+ if (brand.commercialMode === true) commercialMode = true;
30
+ if (brand.shipsPremiumBundles === true) {
31
+ bundleMode = "all";
32
+ } else if (Array.isArray(brand.shipsPremiumBundles)) {
33
+ const arr = brand.shipsPremiumBundles;
34
+ for (const entry of arr) {
35
+ if (typeof entry !== "string" || entry.length === 0) {
36
+ throw new Error(
37
+ `brand.json at ${brandPath} shipsPremiumBundles array contains invalid entry: ${JSON.stringify(entry)}`
38
+ );
39
+ }
40
+ }
41
+ bundleMode = "allowlist";
42
+ bundleAllowlist = arr;
43
+ }
44
+ if (typeof brand.vncDisplay === "number") vncDisplayNum = brand.vncDisplay;
45
+ const brandLabel = configDirName.replace(/^\./, "");
46
+ const required = [
47
+ ["rfbPort", brand.rfbPort],
48
+ ["websockifyPort", brand.websockifyPort],
49
+ ["cdpPort", brand.cdpPort]
50
+ ];
51
+ for (const [field, value] of required) {
52
+ if (typeof value !== "number") {
53
+ const keys = Object.keys(brand).join(",");
54
+ console.error(`[paths] error reason=cdp-port-unresolved brand=${brandLabel} path=${brandPath} field=${field} json_keys=${keys}`);
55
+ throw new Error(`brand.json at ${brandPath} missing required field: ${field}`);
56
+ }
57
+ }
58
+ rfbPortNum = brand.rfbPort;
59
+ websockifyPortNum = brand.websockifyPort;
60
+ cdpPortNum = brand.cdpPort;
61
+ portSource = "brand.json";
62
+ }
63
+ }
64
+ var MAXY_DIR = resolve(homedir(), configDirName);
65
+ var BRAND_NAME = configDirName.replace(/^\./, "");
66
+ var COMMERCIAL_MODE = commercialMode;
67
+ var BUNDLE_MODE = bundleMode;
68
+ var BUNDLE_ALLOWLIST = bundleAllowlist;
69
+ var VNC_DISPLAY = `:${vncDisplayNum}`;
70
+ var RFB_PORT = rfbPortNum;
71
+ var WEBSOCKIFY_PORT = websockifyPortNum;
72
+ var CDP_PORT = cdpPortNum;
73
+ console.log(
74
+ `[paths] brand=${configDirName.replace(/^\./, "")} vncDisplay=${vncDisplayNum} rfbPort=${RFB_PORT} websockifyPort=${WEBSOCKIFY_PORT} cdpPort=${CDP_PORT} source=${portSource}`
75
+ );
76
+ var CHROMIUM_PROFILE_DIR = resolve(homedir(), configDirName, "chromium-profile");
77
+ var PLATFORM_ROOT = process.env.MAXY_PLATFORM_ROOT ?? resolve(process.cwd(), "..");
78
+ var USERS_FILE = resolve(MAXY_DIR, "users.json");
79
+ var LID_MAP_FILE = resolve(MAXY_DIR, "whatsapp-lid-map.json");
80
+ var LOG_DIR = resolve(MAXY_DIR, "logs");
81
+ var USERS_AUDIT_LOG = resolve(LOG_DIR, "users-audit.log");
82
+ var BIN_DIR = resolve(MAXY_DIR, "bin");
83
+ var REMOTE_PASSWORD_FILE = resolve(MAXY_DIR, ".remote-password");
84
+ var REMOTE_SESSION_SECRET_FILE = resolve(MAXY_DIR, "credentials", "remote-session-secret");
85
+ var ADMIN_SESSION_SECRET_FILE = resolve(MAXY_DIR, "credentials", "admin-session-secret");
86
+ var INSTALL_OWNER_FILE = resolve(MAXY_DIR, ".install-owner");
87
+ var TELEGRAM_WEBHOOK_SECRET_FILE = resolve(MAXY_DIR, ".telegram-webhook-secret");
88
+ var TELEGRAM_ADMIN_WEBHOOK_SECRET_FILE = resolve(MAXY_DIR, ".telegram-admin-webhook-secret");
89
+ var VISITOR_TOKEN_SECRET_FILE = resolve(MAXY_DIR, "credentials", "visitor-token-secret");
90
+ var CLAUDE_CREDENTIALS_FILE = resolve(MAXY_DIR, ".claude", ".credentials.json");
91
+
92
+ // app/lib/system-path-slugs.ts
93
+ var SYSTEM_PATH_SLUGS = ["public", "public-chat", "chat", "graph", "data", "browser"];
94
+
95
+ // app/lib/claude-agent/account.ts
96
+ import { resolve as resolve2 } from "path";
97
+ import { readFileSync as readFileSync3, readdirSync, existsSync as existsSync3, statSync } from "fs";
98
+
99
+ // ../lib/brand-templating/src/index.ts
100
+ import { join as join2 } from "path";
101
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
102
+ var PLACEHOLDER = "{{productName}}";
103
+ var cachedProductName = null;
104
+ function brandJsonPath() {
105
+ const platformRoot2 = process.env.MAXY_PLATFORM_ROOT;
106
+ if (!platformRoot2) {
107
+ throw new Error(
108
+ "[skill-loader] MAXY_PLATFORM_ROOT not set \u2014 cannot resolve brand.json"
109
+ );
110
+ }
111
+ return join2(platformRoot2, "config", "brand.json");
112
+ }
113
+ function getBrandProductName() {
114
+ if (cachedProductName !== null) return cachedProductName;
115
+ const path = brandJsonPath();
116
+ if (!existsSync2(path)) {
117
+ throw new Error(`[skill-loader] brand.json missing at ${path}`);
118
+ }
119
+ let parsed;
120
+ try {
121
+ parsed = JSON.parse(readFileSync2(path, "utf-8"));
122
+ } catch (err) {
123
+ throw new Error(
124
+ `[skill-loader] brand.json unreadable at ${path}: ${err instanceof Error ? err.message : String(err)}`
125
+ );
126
+ }
127
+ const value = parsed.productName;
128
+ if (typeof value !== "string" || value.trim() === "") {
129
+ throw new Error(
130
+ `[skill-loader] brand.json at ${path} has missing or empty productName`
131
+ );
132
+ }
133
+ cachedProductName = value;
134
+ return value;
135
+ }
136
+ function substituteBrandPlaceholders(content, sourcePath) {
137
+ if (!content.includes(PLACEHOLDER)) return content;
138
+ let productName;
139
+ try {
140
+ productName = getBrandProductName();
141
+ } catch (err) {
142
+ console.error(
143
+ `[skill-loader] ERROR: brand.json missing \u2014 cannot resolve productName for skill ${sourcePath}`
144
+ );
145
+ throw err;
146
+ }
147
+ const occurrences = content.split(PLACEHOLDER).length - 1;
148
+ const substituted = content.split(PLACEHOLDER).join(productName);
149
+ console.log(
150
+ `[skill-loader] brand-substituted productName=${productName} skill=${sourcePath} occurrences=${occurrences}`
151
+ );
152
+ return substituted;
153
+ }
154
+
155
+ // app/lib/claude-agent/account.ts
156
+ var PLATFORM_ROOT2 = process.env.MAXY_PLATFORM_ROOT ?? resolve2(process.cwd(), "..");
157
+ var ACCOUNTS_DIR = resolve2(PLATFORM_ROOT2, "..", "data/accounts");
158
+ if (!existsSync3(PLATFORM_ROOT2)) {
159
+ throw new Error(
160
+ `PLATFORM_ROOT does not exist: ${PLATFORM_ROOT2}
161
+ Set the MAXY_PLATFORM_ROOT environment variable to the absolute path of the platform directory.`
162
+ );
163
+ }
164
+ var _stubDirsLoggedThisBoot = /* @__PURE__ */ new Set();
165
+ function listValidAccounts() {
166
+ if (!existsSync3(ACCOUNTS_DIR)) return [];
167
+ const out = [];
168
+ const entries = readdirSync(ACCOUNTS_DIR, { withFileTypes: true });
169
+ for (const entry of entries) {
170
+ if (!entry.isDirectory()) continue;
171
+ if (entry.name.startsWith(".")) continue;
172
+ const accountDir = resolve2(ACCOUNTS_DIR, entry.name);
173
+ const configPath = resolve2(accountDir, "account.json");
174
+ if (!existsSync3(configPath)) {
175
+ if (!_stubDirsLoggedThisBoot.has(entry.name)) {
176
+ console.error(
177
+ `[platform] accounts-state STUB-DIR id=${entry.name} \u2014 onboarding leak; remove or repair`
178
+ );
179
+ _stubDirsLoggedThisBoot.add(entry.name);
180
+ }
181
+ continue;
182
+ }
183
+ let config;
184
+ try {
185
+ config = JSON.parse(readFileSync3(configPath, "utf-8"));
186
+ } catch {
187
+ console.error(
188
+ `[platform] accounts-state CORRUPT-JSON id=${entry.name} \u2014 account.json failed to parse; treating as stub`
189
+ );
190
+ continue;
191
+ }
192
+ out.push({ accountId: config.accountId, accountDir, config });
193
+ }
194
+ return out;
195
+ }
196
+ function isValidAccountId(id) {
197
+ return listValidAccounts().some((a) => a.accountId === id);
198
+ }
199
+ function resolveAccount() {
200
+ if (!existsSync3(ACCOUNTS_DIR)) return null;
201
+ let usersJsonUserId = null;
202
+ if (existsSync3(USERS_FILE)) {
203
+ try {
204
+ const raw = readFileSync3(USERS_FILE, "utf-8").trim();
205
+ if (raw) {
206
+ const users = JSON.parse(raw);
207
+ if (users.length > 0) {
208
+ usersJsonUserId = users[0].userId;
209
+ }
210
+ }
211
+ } catch {
212
+ }
213
+ }
214
+ const entries = readdirSync(ACCOUNTS_DIR, { withFileTypes: true });
215
+ let fallback = null;
216
+ for (const entry of entries) {
217
+ if (!entry.isDirectory()) continue;
218
+ const configPath = resolve2(ACCOUNTS_DIR, entry.name, "account.json");
219
+ if (!existsSync3(configPath)) continue;
220
+ const raw = readFileSync3(configPath, "utf-8");
221
+ let config;
222
+ try {
223
+ config = JSON.parse(raw);
224
+ } catch {
225
+ console.error(`[maxy] account.json is corrupt at ${configPath} \u2014 skipping`);
226
+ continue;
227
+ }
228
+ if (!config.adminModel || !config.publicModel) {
229
+ throw new Error(
230
+ `[maxy] account.json at ${configPath} is missing required model fields (adminModel / publicModel). Update account.json with valid model identifiers.`
231
+ );
232
+ }
233
+ const result = {
234
+ accountId: config.accountId,
235
+ accountDir: resolve2(ACCOUNTS_DIR, entry.name),
236
+ config
237
+ };
238
+ if (usersJsonUserId && config.admins?.some((a) => a.userId === usersJsonUserId)) {
239
+ return result;
240
+ }
241
+ if (!fallback) {
242
+ fallback = result;
243
+ }
244
+ }
245
+ if (usersJsonUserId && fallback) {
246
+ console.warn(
247
+ `[maxy] resolveAccount: no account matches users.json userId ${usersJsonUserId} \u2014 falling back to ${fallback.accountId}`
248
+ );
249
+ }
250
+ return fallback;
251
+ }
252
+ function readAgentFile(accountDir, agentName, filename) {
253
+ const filePath = resolve2(accountDir, "agents", agentName, filename);
254
+ if (!existsSync3(filePath)) return null;
255
+ const raw = readFileSync3(filePath, "utf-8");
256
+ if (filename.endsWith(".md")) {
257
+ return substituteBrandPlaceholders(raw, filePath);
258
+ }
259
+ return raw;
260
+ }
261
+ var RESERVED_SLUGS = /* @__PURE__ */ new Set(["admin", "api", "assets", "agent-assets", "brand", "bot", "privacy"]);
262
+ var SHADOWED_SLUGS = new Set(SYSTEM_PATH_SLUGS);
263
+ var SLUG_PATTERN = /^[a-z][a-z0-9-]{2,49}$/;
264
+ function validateAgentSlug(slug) {
265
+ if (!SLUG_PATTERN.test(slug)) return false;
266
+ if (RESERVED_SLUGS.has(slug)) {
267
+ console.error(`[agent-slug] op=reject slug=${slug} reason=reserved`);
268
+ return false;
269
+ }
270
+ if (SHADOWED_SLUGS.has(slug)) {
271
+ console.error(`[agent-slug] op=reject slug=${slug} reason=shadowed`);
272
+ return false;
273
+ }
274
+ return true;
275
+ }
276
+ function resolveDefaultAgentSlug(accountDir) {
277
+ const configPath = resolve2(accountDir, "account.json");
278
+ if (!existsSync3(configPath)) {
279
+ console.error("[agent-resolve] account.json not found \u2014 cannot resolve defaultAgent");
280
+ return null;
281
+ }
282
+ let config;
283
+ try {
284
+ config = JSON.parse(readFileSync3(configPath, "utf-8"));
285
+ } catch (err) {
286
+ console.error("[agent-resolve] failed to read account.json:", err);
287
+ return null;
288
+ }
289
+ if (!config.defaultAgent) {
290
+ console.error("[agent-resolve] defaultAgent not configured in account.json \u2014 set it via the connect-whatsapp skill");
291
+ return null;
292
+ }
293
+ const agentConfigPath = resolve2(accountDir, "agents", config.defaultAgent, "config.json");
294
+ if (!existsSync3(agentConfigPath)) {
295
+ console.error(`[agent-resolve] defaultAgent="${config.defaultAgent}" has no config.json at ${agentConfigPath}`);
296
+ return null;
297
+ }
298
+ return config.defaultAgent;
299
+ }
300
+ function estimateTokens(text) {
301
+ return Math.ceil(text.length / 4);
302
+ }
303
+ function resolveAgentConfig(accountDir, agentName) {
304
+ let model = null;
305
+ let status = null;
306
+ let displayName = null;
307
+ let image = null;
308
+ let imageShape = null;
309
+ let showAgentName = false;
310
+ let knowledgeKeywords = null;
311
+ let accessMode = "open";
312
+ const MAX_KNOWLEDGE_KEYWORDS = 5;
313
+ const configRaw = readAgentFile(accountDir, agentName, "config.json");
314
+ if (configRaw) {
315
+ let parsed;
316
+ try {
317
+ parsed = JSON.parse(configRaw);
318
+ } catch {
319
+ console.warn(`[agent-config] ${agentName}/config.json: invalid JSON \u2014 using defaults`);
320
+ parsed = {};
321
+ }
322
+ model = typeof parsed.model === "string" ? parsed.model : null;
323
+ status = typeof parsed.status === "string" ? parsed.status : null;
324
+ displayName = typeof parsed.displayName === "string" ? parsed.displayName : null;
325
+ image = typeof parsed.image === "string" ? parsed.image : null;
326
+ if (typeof parsed.imageShape === "string" && ["circle", "rounded"].includes(parsed.imageShape)) {
327
+ imageShape = parsed.imageShape;
328
+ }
329
+ if (parsed.showAgentName === true) {
330
+ showAgentName = true;
331
+ } else if (parsed.showAgentName === "none") {
332
+ showAgentName = "none";
333
+ }
334
+ if (image || imageShape || showAgentName) {
335
+ console.log(`[agent-config] ${agentName}: image=${image || "(none)"} imageShape=${imageShape || "(none)"} showAgentName=${showAgentName}`);
336
+ }
337
+ if (typeof parsed.accessMode === "string" && ["gated", "paid"].includes(parsed.accessMode)) {
338
+ accessMode = parsed.accessMode;
339
+ }
340
+ if (Array.isArray(parsed.knowledgeKeywords) && parsed.knowledgeKeywords.length > 0) {
341
+ const filtered = parsed.knowledgeKeywords.filter((k) => typeof k === "string" && k.trim()).map((k) => k.replace(/,/g, "").trim().toLowerCase()).filter(Boolean);
342
+ if (filtered.length > MAX_KNOWLEDGE_KEYWORDS) {
343
+ console.warn(`[agent-config] ${agentName}: knowledgeKeywords has ${filtered.length} entries \u2014 capping at ${MAX_KNOWLEDGE_KEYWORDS}`);
344
+ }
345
+ knowledgeKeywords = filtered.length > 0 ? filtered.slice(0, MAX_KNOWLEDGE_KEYWORDS) : null;
346
+ }
347
+ }
348
+ let knowledge = null;
349
+ let knowledgeBaked = false;
350
+ const agentDir = resolve2(accountDir, "agents", agentName);
351
+ const knowledgePath = resolve2(agentDir, "KNOWLEDGE.md");
352
+ const summaryPath = resolve2(agentDir, "KNOWLEDGE-SUMMARY.md");
353
+ const hasKnowledge = existsSync3(knowledgePath);
354
+ const hasSummary = existsSync3(summaryPath);
355
+ if (hasKnowledge && hasSummary) {
356
+ const knowledgeMtime = statSync(knowledgePath).mtimeMs;
357
+ const summaryMtime = statSync(summaryPath).mtimeMs;
358
+ if (summaryMtime >= knowledgeMtime) {
359
+ knowledge = readFileSync3(summaryPath, "utf-8");
360
+ } else {
361
+ console.warn(`[agent-config] ${agentName}: KNOWLEDGE-SUMMARY.md is stale (KNOWLEDGE.md is newer) \u2014 using full knowledge`);
362
+ knowledge = readFileSync3(knowledgePath, "utf-8");
363
+ }
364
+ knowledgeBaked = true;
365
+ } else if (hasKnowledge) {
366
+ knowledge = readFileSync3(knowledgePath, "utf-8");
367
+ knowledgeBaked = true;
368
+ }
369
+ let budget = null;
370
+ const identityRaw = readAgentFile(accountDir, agentName, "IDENTITY.md");
371
+ const soulRaw = readAgentFile(accountDir, agentName, "SOUL.md");
372
+ if (identityRaw || soulRaw || knowledge) {
373
+ const identityTokens = identityRaw ? estimateTokens(identityRaw) : 0;
374
+ const soulTokens = soulRaw ? estimateTokens(soulRaw) : 0;
375
+ const knowledgeTokens = knowledge ? estimateTokens(knowledge) : 0;
376
+ budget = {
377
+ identity: identityTokens,
378
+ soul: soulTokens,
379
+ knowledge: knowledgeTokens,
380
+ plugins: 0,
381
+ total: identityTokens + soulTokens + knowledgeTokens
382
+ };
383
+ }
384
+ return { model, status, displayName, image, imageShape, showAgentName, knowledge, knowledgeBaked, knowledgeKeywords, budget, accessMode };
385
+ }
386
+ function isActiveAgentSlug(accountDir, slug) {
387
+ return resolveAgentConfig(accountDir, slug).status === "active";
388
+ }
389
+ function getDefaultAccountId() {
390
+ return resolveAccount()?.accountId ?? null;
391
+ }
392
+
393
+ // app/lib/neo4j-store.ts
394
+ import neo4j from "neo4j-driver";
395
+ import { randomUUID } from "crypto";
396
+ import { readFileSync as readFileSync4, readdirSync as readdirSync2, existsSync as existsSync4, openSync, readSync, closeSync, statSync as statSync2 } from "fs";
397
+ import { resolve as resolve3 } from "path";
398
+ var PLATFORM_ROOT3 = process.env.MAXY_PLATFORM_ROOT ?? resolve3(process.cwd(), "..");
399
+ var driver = null;
400
+ function readPassword() {
401
+ if (process.env.NEO4J_PASSWORD) return process.env.NEO4J_PASSWORD;
402
+ const passwordFile = resolve3(PLATFORM_ROOT3, "config/.neo4j-password");
403
+ try {
404
+ return readFileSync4(passwordFile, "utf-8").trim();
405
+ } catch {
406
+ throw new Error(
407
+ `Neo4j password not found. Expected at ${passwordFile} or in NEO4J_PASSWORD env var.`
408
+ );
409
+ }
410
+ }
411
+ function getDriver() {
412
+ if (!driver) {
413
+ const uri = process.env.NEO4J_URI;
414
+ if (!uri) {
415
+ throw new Error(
416
+ "[ui/neo4j-store] NEO4J_URI unset \u2014 refusing to default to bolt://localhost:7687"
417
+ );
418
+ }
419
+ const user = process.env.NEO4J_USER ?? "neo4j";
420
+ const password = readPassword();
421
+ console.error(`[ui/neo4j-store] resolved neo4j_uri=${uri}`);
422
+ driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
423
+ maxConnectionPoolSize: 5
424
+ });
425
+ }
426
+ return driver;
427
+ }
428
+ function getSession() {
429
+ return getDriver().session();
430
+ }
431
+ async function runAdminUserSelfHeal(args) {
432
+ const { selfHealAdminUser } = await import("./adminuser-self-heal-LC7HZAC6.js");
433
+ return selfHealAdminUser({ driver: getDriver(), ...args });
434
+ }
435
+ async function runUserProfileReconcile() {
436
+ const { reconcileUserProfiles } = await import("./userprofile-reconcile-QHVLY2AH.js");
437
+ return reconcileUserProfiles({ driver: getDriver() });
438
+ }
439
+ process.on("SIGINT", async () => {
440
+ if (driver) {
441
+ await driver.close();
442
+ driver = null;
443
+ }
444
+ });
445
+ var OLLAMA_URL = process.env.OLLAMA_URL ?? "http://localhost:11434";
446
+ var EMBED_MODEL = process.env.EMBED_MODEL ?? "nomic-embed-text";
447
+ function envInt(name, def) {
448
+ const raw = process.env[name];
449
+ if (raw === void 0 || raw === "") return def;
450
+ const n = Number(raw);
451
+ return Number.isFinite(n) ? n : def;
452
+ }
453
+ var EMBED_MODEL_CONTEXT_TOKENS = Math.max(1, Math.floor(envInt("EMBED_MODEL_CONTEXT_TOKENS", 2048)));
454
+ var EMBED_CONTEXT_MARGIN_TOKENS = 48;
455
+ var EMBED_WORST_CASE_CHARS_PER_TOKEN = 2;
456
+ var EMBED_INPUT_MAX_CHARS = Math.max(
457
+ 1,
458
+ Math.floor(
459
+ envInt(
460
+ "EMBED_INPUT_MAX_CHARS",
461
+ (EMBED_MODEL_CONTEXT_TOKENS - EMBED_CONTEXT_MARGIN_TOKENS) * EMBED_WORST_CASE_CHARS_PER_TOKEN
462
+ )
463
+ )
464
+ );
465
+ var EMBED_KEEP_ALIVE_RAW = process.env.EMBED_KEEP_ALIVE === void 0 || process.env.EMBED_KEEP_ALIVE === "" ? "-1" : process.env.EMBED_KEEP_ALIVE;
466
+ var EMBED_KEEP_ALIVE = /^-?\d+$/.test(EMBED_KEEP_ALIVE_RAW) ? Number(EMBED_KEEP_ALIVE_RAW) : EMBED_KEEP_ALIVE_RAW;
467
+ var EMBED_INTERACTIVE_TIMEOUT_MS = 5e3;
468
+ var EMBED_PRELOAD_TIMEOUT_MS = 6e4;
469
+ async function embed(text, timeoutMs = EMBED_INTERACTIVE_TIMEOUT_MS) {
470
+ const input = text.length > EMBED_INPUT_MAX_CHARS ? text.slice(0, EMBED_INPUT_MAX_CHARS) : text;
471
+ const startedAt = Date.now();
472
+ const target = `${OLLAMA_URL}/api/embed`;
473
+ let res;
474
+ try {
475
+ res = await fetch(target, {
476
+ method: "POST",
477
+ headers: { "Content-Type": "application/json" },
478
+ body: JSON.stringify({ model: EMBED_MODEL, input, keep_alive: EMBED_KEEP_ALIVE }),
479
+ signal: AbortSignal.timeout(timeoutMs)
480
+ });
481
+ } catch (err) {
482
+ const name = err instanceof Error ? err.name : "";
483
+ if (name === "TimeoutError" || name === "AbortError") {
484
+ throw new Error(
485
+ `Ollama embed request timed out after ${timeoutMs}ms (inputChars=${input.length}) at ${target}; ollama did not respond in time (slow, cold-loading, or CPU-saturated).`
486
+ );
487
+ }
488
+ let detail = err instanceof Error ? err.message : String(err);
489
+ const cause = err instanceof Error ? err.cause : void 0;
490
+ if (cause !== void 0) {
491
+ detail += `: ${cause instanceof Error ? cause.message : String(cause)}`;
492
+ }
493
+ throw new Error(
494
+ `Ollama embed request failed (inputChars=${input.length}) at ${target}: ${detail}`
495
+ );
496
+ }
497
+ if (!res.ok) {
498
+ const body = await res.text();
499
+ throw new Error(
500
+ `Ollama embedding failed (HTTP ${res.status}, inputChars=${input.length}): ${body}`
501
+ );
502
+ }
503
+ const data = await res.json();
504
+ const ms = Date.now() - startedAt;
505
+ console.error(`[embed-query] warmth=${ms > 1e3 ? "cold" : "warm"} ms=${ms}`);
506
+ return data.embeddings[0];
507
+ }
508
+ async function preloadEmbedModel() {
509
+ try {
510
+ await embed("warm", EMBED_PRELOAD_TIMEOUT_MS);
511
+ console.error("[embed-query] op=preload result=ok");
512
+ } catch (err) {
513
+ console.error(
514
+ `[embed-query] op=preload result=skip err="${err instanceof Error ? err.message : String(err)}"`
515
+ );
516
+ }
517
+ }
518
+ var sessionStoreRef = null;
519
+ function getCachedSessionId(cacheKey) {
520
+ return sessionStoreRef?.get(cacheKey)?.sessionId;
521
+ }
522
+ function cacheSessionId(cacheKey, sessionId) {
523
+ const session = sessionStoreRef?.get(cacheKey);
524
+ if (session) {
525
+ session.sessionId = sessionId;
526
+ }
527
+ }
528
+ var GREETING_DIRECTIVE = "[New session. Greet the visitor.]";
529
+ async function ensureConversation(accountId, agentType, cacheKey, visitorId, agentSlug, userId, channelOverride, channelAddressOverride) {
530
+ const cached = getCachedSessionId(cacheKey);
531
+ if (cached) return { sessionId: cached, created: false };
532
+ const sessionId = randomUUID();
533
+ const channel = channelOverride ?? (cacheKey.startsWith("whatsapp:") ? "whatsapp" : cacheKey.startsWith("telegram:") ? "telegram" : "webchat");
534
+ const channelAddress = channelAddressOverride ?? (cacheKey.startsWith("whatsapp:") ? cacheKey.slice("whatsapp:".length) : cacheKey.startsWith("telegram:") ? cacheKey.slice("telegram:".length) : sessionId);
535
+ const conversationSublabel = agentType === "admin" ? "AdminConversation" : "PublicConversation";
536
+ const handlerSlug = agentSlug ?? (agentType === "admin" ? "admin" : null);
537
+ const wantsHandledByEdge = !!handlerSlug;
538
+ const handledByClause = wantsHandledByEdge ? `WITH c, created
539
+ OPTIONAL MATCH (a:Agent {accountId: $accountId, slug: $handlerSlug})
540
+ FOREACH (_ IN CASE WHEN a IS NULL THEN [] ELSE [1] END | MERGE (c)-[:HANDLED_BY]->(a))
541
+ RETURN c.sessionId AS sessionId, created AS created, a IS NOT NULL AS handledBy` : `RETURN c.sessionId AS sessionId, created AS created, false AS handledBy`;
542
+ const session = getSession();
543
+ try {
544
+ const result = await session.run(
545
+ `OPTIONAL MATCH (prior:Conversation {accountId: $accountId, channel: $channel, channelAddress: $channelAddress})
546
+ WITH prior, coalesce(prior.sessionId, $sessionId) AS finalConvId, prior IS NULL AS created
547
+ MERGE (c:Conversation {sessionId: finalConvId})
548
+ ON CREATE SET
549
+ c:${conversationSublabel},
550
+ c.accountId = $accountId,
551
+ c.agentType = $agentType,
552
+ c.channel = $channel,
553
+ c.channelAddress = $channelAddress,
554
+ ${visitorId ? "c.visitorId = $visitorId," : ""}
555
+ ${agentSlug ? "c.agentSlug = $agentSlug," : ""}
556
+ ${userId ? "c.userId = $userId," : ""}
557
+ c.createdAt = datetime(),
558
+ c.updatedAt = datetime()
559
+ ON MATCH SET
560
+ c.updatedAt = datetime()
561
+ ${handledByClause}`,
562
+ {
563
+ sessionId,
564
+ accountId,
565
+ agentType,
566
+ channel,
567
+ channelAddress,
568
+ ...visitorId ? { visitorId } : {},
569
+ ...agentSlug ? { agentSlug } : {},
570
+ ...handlerSlug ? { handlerSlug } : {},
571
+ ...userId ? { userId } : {}
572
+ }
573
+ );
574
+ const id = result.records[0]?.get("sessionId");
575
+ const created = result.records[0]?.get("created") === true;
576
+ if (id) {
577
+ cacheSessionId(cacheKey, id);
578
+ console.error(`[session] conversation attributed: sessionId=${id.slice(0, 8)}\u2026 userId=${userId ?? "none"} ${agentType}/${accountId.slice(0, 8)}\u2026 sublabel=${conversationSublabel}`);
579
+ if (wantsHandledByEdge) {
580
+ const handled = result.records[0]?.get("handledBy");
581
+ const id8 = id.slice(0, 8);
582
+ if (handled === true) {
583
+ console.error(`[agent-graph] handled-by-write sessionId=${id8} slug=${handlerSlug}`);
584
+ } else {
585
+ console.error(`[agent-graph] handled-by-skip reason=no-agent-node sessionId=${id8} slug=${handlerSlug}`);
586
+ }
587
+ }
588
+ }
589
+ return { sessionId: id ?? null, created };
590
+ } catch (err) {
591
+ console.error(`[persist] ensureConversation failed: ${err instanceof Error ? err.message : String(err)}`);
592
+ return { sessionId: null, created: false };
593
+ } finally {
594
+ await session.close();
595
+ }
596
+ }
597
+ async function ensureSessionConversation(input) {
598
+ const t0 = Date.now();
599
+ const sublabel = input.agentType === "admin" ? "AdminConversation" : "PublicConversation";
600
+ const session = getSession();
601
+ try {
602
+ const result = await session.run(
603
+ `OPTIONAL MATCH (prior:Conversation {sessionId: $sessionId})
604
+ WITH prior IS NULL AS created
605
+ MERGE (c:Conversation {sessionId: $sessionId})
606
+ ON CREATE SET
607
+ c:${sublabel},
608
+ c.accountId = $accountId,
609
+ c.agentType = $agentType,
610
+ c.channel = $channel,
611
+ c.channelAddress = $channelAddress,
612
+ c.createdAt = datetime(),
613
+ c.updatedAt = datetime()
614
+ ON MATCH SET
615
+ c.updatedAt = datetime()
616
+ RETURN created`,
617
+ {
618
+ sessionId: input.sessionId,
619
+ accountId: input.accountId,
620
+ agentType: input.agentType,
621
+ channel: input.channel,
622
+ channelAddress: input.channelAddress
623
+ }
624
+ );
625
+ const created = result.records[0]?.get("created") === true;
626
+ console.error(
627
+ `[wa-session] op=conversation-ensure sessionId=${input.sessionId} accountId=${input.accountId} channel=${input.channel} sublabel=${sublabel} created=${created} ms=${Date.now() - t0}`
628
+ );
629
+ return { created };
630
+ } catch (err) {
631
+ const reason = err instanceof Error ? `${err.name}:${err.message.slice(0, 200)}` : String(err).slice(0, 200);
632
+ console.error(
633
+ `[wa-session] op=conversation-ensure FAIL sessionId=${input.sessionId} accountId=${input.accountId} reason=${reason} ms=${Date.now() - t0}`
634
+ );
635
+ return null;
636
+ } finally {
637
+ await session.close();
638
+ }
639
+ }
640
+ async function findRecentConversation(visitorId, accountId, agentSlug, maxAgeHours = 24) {
641
+ const session = getSession();
642
+ try {
643
+ const result = await session.run(
644
+ `MATCH (c:Conversation {visitorId: $visitorId, accountId: $accountId, agentType: 'public'})
645
+ WHERE c.agentSlug = $agentSlug
646
+ AND c.updatedAt > datetime() - duration({hours: $maxAgeHours})
647
+ AND NOT c:Trashed
648
+ RETURN c.sessionId AS sessionId
649
+ ORDER BY c.updatedAt DESC
650
+ LIMIT 1`,
651
+ { visitorId, accountId, agentSlug, maxAgeHours: neo4j.int(maxAgeHours) },
652
+ { timeout: 2e3 }
653
+ );
654
+ const record = result.records[0];
655
+ if (!record) return null;
656
+ const sessionId = record.get("sessionId");
657
+ if (!sessionId) return null;
658
+ console.log(`[persist] found recent conversation ${sessionId.slice(0, 8)}\u2026 for visitor ${visitorId.slice(0, 8)}\u2026`);
659
+ return { sessionId };
660
+ } catch (err) {
661
+ console.error(`[persist] findRecentConversation failed: ${err instanceof Error ? err.message : String(err)}`);
662
+ return null;
663
+ } finally {
664
+ await session.close();
665
+ }
666
+ }
667
+ async function createNewAdminConversation(userId, accountId, cacheKey, preMintedSessionId) {
668
+ if (!userId || !cacheKey || !accountId) {
669
+ console.error(`[admin/conversation-write] schema-violation userId=${userId ? "set" : "EMPTY"} cacheKey=${cacheKey ? "set" : "EMPTY"} accountId=${accountId ? "set" : "EMPTY"}`);
670
+ return null;
671
+ }
672
+ const sessionId = preMintedSessionId ?? randomUUID();
673
+ const session = getSession();
674
+ try {
675
+ const result = await session.run(
676
+ `OPTIONAL MATCH (existing:AdminUser {userId: $userId})
677
+ WITH existing IS NULL AS adminUserCreated
678
+ MERGE (au:AdminUser {userId: $userId})
679
+ ON CREATE SET au.accountId = $accountId,
680
+ au.createdAt = datetime(),
681
+ au.scope = 'admin'
682
+ CREATE (c:Conversation:AdminConversation {
683
+ sessionId: $sessionId,
684
+ accountId: $accountId,
685
+ agentType: 'admin',
686
+ channel: 'webchat',
687
+ channelAddress: $sessionId,
688
+ userId: $userId,
689
+ createdBySource: 'admin-conversation',
690
+ createdAt: datetime(),
691
+ updatedAt: datetime()
692
+ })-[:STARTED_BY]->(au)
693
+ RETURN adminUserCreated`,
694
+ { sessionId, accountId, userId }
695
+ );
696
+ const adminUserCreated = result.records[0]?.get("adminUserCreated") === true;
697
+ cacheSessionId(cacheKey, sessionId);
698
+ console.log(`[session] conversation created: sessionId=${sessionId.slice(0, 8)}\u2026 cacheKey=${cacheKey.slice(0, 8)}\u2026 accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} agentType=admin createdBySource=admin-conversation createdAt=set updatedAt=set sublabel=AdminConversation adminUserCreated=${adminUserCreated}`);
699
+ return sessionId;
700
+ } catch (err) {
701
+ console.error(`[session] createNewAdminConversation failed: ${err instanceof Error ? err.message : String(err)}`);
702
+ return null;
703
+ } finally {
704
+ await session.close();
705
+ }
706
+ }
707
+ var HEX_COLOR_RE = /^#[0-9a-fA-F]{3,8}$/;
708
+ async function fetchBranding(accountId) {
709
+ const session = getSession();
710
+ try {
711
+ const result = await session.run(
712
+ `MATCH (b:LocalBusiness {accountId: $accountId})
713
+ OPTIONAL MATCH (b)-[:HAS_BRAND_ASSET]->(logo:ImageObject {purpose: "logo"})
714
+ OPTIONAL MATCH (b)-[:HAS_BRAND_ASSET]->(icon:ImageObject {purpose: "icon"})
715
+ RETURN b.name AS name,
716
+ b.primaryColor AS primaryColor,
717
+ b.accentColor AS accentColor,
718
+ b.backgroundColor AS backgroundColor,
719
+ b.tagline AS tagline,
720
+ logo.contentUrl AS logoUrl,
721
+ icon.contentUrl AS faviconUrl`,
722
+ { accountId },
723
+ { timeout: 2e3 }
724
+ );
725
+ const record = result.records[0];
726
+ if (!record) return null;
727
+ const name = record.get("name");
728
+ if (!name) return null;
729
+ const primaryColor = record.get("primaryColor");
730
+ const accentColor = record.get("accentColor");
731
+ const backgroundColor = record.get("backgroundColor");
732
+ const tagline = record.get("tagline");
733
+ const logoUrl = record.get("logoUrl");
734
+ const faviconUrl = record.get("faviconUrl");
735
+ const hasBranding = primaryColor || accentColor || backgroundColor || tagline || logoUrl || faviconUrl;
736
+ if (!hasBranding) return null;
737
+ const branding = { name };
738
+ if (primaryColor && HEX_COLOR_RE.test(primaryColor)) branding.primaryColor = primaryColor;
739
+ if (accentColor && HEX_COLOR_RE.test(accentColor)) branding.accentColor = accentColor;
740
+ if (backgroundColor && HEX_COLOR_RE.test(backgroundColor)) branding.backgroundColor = backgroundColor;
741
+ if (tagline) branding.tagline = tagline;
742
+ if (logoUrl) branding.logoUrl = logoUrl;
743
+ if (faviconUrl) branding.faviconUrl = faviconUrl;
744
+ console.error(`[branding] resolved for accountId=${accountId.slice(0, 8)}\u2026: primary=${branding.primaryColor ?? "\u2013"} logo=${branding.logoUrl ? "yes" : "no"}`);
745
+ return branding;
746
+ } catch (err) {
747
+ console.error(`[branding] fetchBranding failed for accountId=${accountId.slice(0, 8)}\u2026: ${err instanceof Error ? err.message : String(err)}`);
748
+ return null;
749
+ } finally {
750
+ await session.close();
751
+ }
752
+ }
753
+ async function fetchAccountName(accountId) {
754
+ const session = getSession();
755
+ try {
756
+ const result = await session.run(
757
+ `MATCH (b:LocalBusiness {accountId: $accountId}) RETURN b.name AS name`,
758
+ { accountId },
759
+ { timeout: 2e3 }
760
+ );
761
+ const name = result.records[0]?.get("name")?.trim();
762
+ if (!name) {
763
+ console.error(`[branding] account-name-fallback accountId=${accountId.slice(0, 8)}\u2026 reason=no-name`);
764
+ return null;
765
+ }
766
+ return name;
767
+ } catch (err) {
768
+ console.error(`[branding] fetchAccountName failed for accountId=${accountId.slice(0, 8)}\u2026: ${err instanceof Error ? err.message : String(err)}`);
769
+ return null;
770
+ } finally {
771
+ await session.close();
772
+ }
773
+ }
774
+ var SUMMARY_MAX_LEN = 200;
775
+ var persistMessageLocks = /* @__PURE__ */ new Map();
776
+ async function persistMessage(sessionId, role, content, accountId, tokens, createdAt, sender, components, attachments) {
777
+ if (!content) return null;
778
+ const messageId = randomUUID();
779
+ const summary = role === "user" ? content.slice(0, SUMMARY_MAX_LEN).trim() : "";
780
+ let embedding = null;
781
+ try {
782
+ embedding = await embed(content);
783
+ } catch (err) {
784
+ console.error(`[persist] Embedding failed, storing without: ${err instanceof Error ? err.message : String(err)}`);
785
+ }
786
+ const prev = persistMessageLocks.get(sessionId);
787
+ const waited = prev !== void 0;
788
+ let release;
789
+ const mine = new Promise((resolve4) => {
790
+ release = resolve4;
791
+ });
792
+ const chained = (prev ?? Promise.resolve()).then(() => mine);
793
+ persistMessageLocks.set(sessionId, chained);
794
+ await prev;
795
+ const session = getSession();
796
+ try {
797
+ const result = await session.run(
798
+ `MATCH (c:Conversation {sessionId: $sessionId})
799
+ OPTIONAL MATCH (tail:Message)-[:PART_OF]->(c)
800
+ WHERE NOT (tail)-[:NEXT]->(:Message)
801
+ AND (tail:UserMessage OR tail:AssistantMessage)
802
+ // sublabel-scope the tail to the agent-path's own sublabels.
803
+ // Without this, a Task-857 :WhatsAppMessage row (no outgoing :NEXT)
804
+ // would be picked as tail and the agent-path would chain
805
+ // :WhatsAppMessage\u2192:UserMessage, crossing the live-channel chain.
806
+ // The live writer's tail predicate is sublabel-scoped to
807
+ // :WhatsAppMessage; this clause is the matching defence on the
808
+ // agent side.
809
+ // Capture whether THIS write's guard will fire. Read c.summary
810
+ // before the SET so the boolean reflects the pre-state, not the
811
+ // post-state \u2014 a false positive otherwise when a new user message
812
+ // happens to equal an already-set summary (verbatim retry, short
813
+ // catchphrase) and fooled a post-state equality check.
814
+ WITH c, tail, (c.summary IS NULL AND $role = 'user' AND $summary <> '') AS summarySetThisWrite
815
+ CREATE (m:Message:${role === "user" ? "UserMessage" : "AssistantMessage"} {
816
+ messageId: $messageId,
817
+ sessionId: $sessionId,
818
+ accountId: $accountId,
819
+ role: $role,
820
+ content: $content,
821
+ createdAt: ${createdAt ? "datetime($createdAt)" : "datetime()"}
822
+ ${embedding ? ", embedding: $embedding" : ""}
823
+ ${sender ? ", senderVisitorId: $senderVisitorId, senderName: $senderName" : ""}
824
+ ${tokens?.inputTokens != null ? ", inputTokens: $inputTokens" : ""}
825
+ ${tokens?.outputTokens != null ? ", outputTokens: $outputTokens" : ""}
826
+ ${tokens?.cacheReadTokens != null ? ", cacheReadTokens: $cacheReadTokens" : ""}
827
+ ${tokens?.cacheCreationTokens != null ? ", cacheCreationTokens: $cacheCreationTokens" : ""}
828
+ })
829
+ SET c.updatedAt = datetime()
830
+ CREATE (m)-[:PART_OF]->(c)
831
+ FOREACH (prev IN CASE WHEN tail IS NULL THEN [] ELSE [tail] END |
832
+ CREATE (prev)-[:NEXT]->(m)
833
+ )
834
+ FOREACH (_ IN CASE WHEN summarySetThisWrite THEN [1] ELSE [] END |
835
+ SET c.summary = $summary
836
+ )
837
+ FOREACH (comp IN $components |
838
+ CREATE (m)-[:HAS_COMPONENT]->(:Component {
839
+ componentId: comp.componentId,
840
+ sessionId: $sessionId,
841
+ accountId: $accountId,
842
+ messageId: $messageId,
843
+ name: comp.name,
844
+ data: comp.data,
845
+ ordinal: comp.ordinal,
846
+ textOffset: comp.textOffset,
847
+ submitted: false,
848
+ createdAt: datetime(),
849
+ // store the artefact attachmentId on the:Component
850
+ // itself when this is a PERSISTENT_COMPONENTS write whose disk
851
+ // write succeeded. Field is null for non-persistent / mime-skip
852
+ // / disk-fail components. Lets the audit + backfill scripts
853
+ // read the attachmentId directly off the :Component row instead
854
+ // of re-deriving (the live + heal paths use different sources \u2014
855
+ // sha256(block.id) live, componentId-fallback backfill \u2014 and
856
+ // the audit must match either).
857
+ attachmentId: comp.artefactAttachmentId
858
+ })
859
+ )
860
+ // for PERSISTENT_COMPONENTS whose disk write succeeded
861
+ // (artefactAttachmentId is non-null), MERGE the sibling
862
+ // :KnowledgeDocument projection AND a :HAS_KNOWLEDGE_DOCUMENT edge
863
+ // from the parent :Message in the same Cypher tx. ON CREATE stamps
864
+ // name+encodingFormat from the live render; ON MATCH only bumps
865
+ // updatedAt so a heal-on-resume re-run cannot clobber an operator's
866
+ // subsequent rename via the knowledge-documents API (eng-review \xA72).
867
+ // The edge makes the projection graph-discoverable from the
868
+ // conversation timeline so file-delete-cascade and conversation
869
+ // cleanup can reach it. FOREACH on the filtered list collapses to a
870
+ // no-op when no component has an attachmentId, preserving the
871
+ // text-only-turn fast path.
872
+ FOREACH (kd IN $knowledgeDocs |
873
+ MERGE (k:KnowledgeDocument {accountId: $accountId, attachmentId: kd.attachmentId})
874
+ ON CREATE SET k.name = kd.title,
875
+ k.encodingFormat = kd.mimeType,
876
+ k.createdAt = datetime(),
877
+ k.updatedAt = datetime()
878
+ ON MATCH SET k.updatedAt = datetime()
879
+ MERGE (m)-[:HAS_KNOWLEDGE_DOCUMENT]->(k)
880
+ )
881
+ FOREACH (att IN $attachments |
882
+ CREATE (m)-[:HAS_ATTACHMENT]->(:Attachment {
883
+ attachmentId: att.attachmentId,
884
+ sessionId: $sessionId,
885
+ accountId: $accountId,
886
+ messageId: $messageId,
887
+ filename: att.filename,
888
+ mimeType: att.mimeType,
889
+ sizeBytes: att.sizeBytes,
890
+ storagePath: att.storagePath,
891
+ ordinal: att.ordinal,
892
+ createdAt: datetime()
893
+ })
894
+ )
895
+ RETURN tail.messageId AS prevMessageId,
896
+ summarySetThisWrite,
897
+ size([(m2:Message)-[:PART_OF]->(c) | m2]) AS chainLen`,
898
+ {
899
+ messageId,
900
+ sessionId,
901
+ accountId,
902
+ role,
903
+ content,
904
+ summary,
905
+ ...createdAt ? { createdAt } : {},
906
+ ...embedding ? { embedding } : {},
907
+ ...sender ? { senderVisitorId: sender.visitorId, senderName: sender.displayName } : {},
908
+ ...tokens?.inputTokens != null ? { inputTokens: neo4j.int(tokens.inputTokens) } : {},
909
+ ...tokens?.outputTokens != null ? { outputTokens: neo4j.int(tokens.outputTokens) } : {},
910
+ ...tokens?.cacheReadTokens != null ? { cacheReadTokens: neo4j.int(tokens.cacheReadTokens) } : {},
911
+ ...tokens?.cacheCreationTokens != null ? { cacheCreationTokens: neo4j.int(tokens.cacheCreationTokens) } : {},
912
+ components: (components ?? []).map((comp) => ({
913
+ componentId: comp.componentId,
914
+ name: comp.name,
915
+ data: comp.data,
916
+ ordinal: neo4j.int(comp.ordinal),
917
+ textOffset: neo4j.int(comp.textOffset),
918
+ // null for non-persistent / mime-skip / disk-fail
919
+ // components; the FOREACH stamps this directly onto the
920
+ // :Component row so audit + backfill read attachmentId without
921
+ // re-deriving from componentId.
922
+ artefactAttachmentId: comp.artefactAttachmentId ?? null
923
+ })),
924
+ //:KnowledgeDocument MERGE list. One row per
925
+ // PERSISTENT_COMPONENTS component whose disk write succeeded;
926
+ // text-only / mime-skip / disk-fail components are absent so
927
+ // the FOREACH no-ops on them. attachmentId here matches the
928
+ // value the stream-parser stamped after writeAttachment.
929
+ knowledgeDocs: (components ?? []).filter((comp) => typeof comp.artefactAttachmentId === "string").map((comp) => ({
930
+ attachmentId: comp.artefactAttachmentId,
931
+ title: comp.artefactTitle ?? "",
932
+ mimeType: comp.artefactMimeType ?? ""
933
+ })),
934
+ attachments: (attachments ?? []).map((att) => ({
935
+ attachmentId: att.attachmentId,
936
+ filename: att.filename,
937
+ mimeType: att.mimeType,
938
+ sizeBytes: neo4j.int(att.sizeBytes),
939
+ storagePath: att.storagePath,
940
+ ordinal: neo4j.int(att.ordinal)
941
+ }))
942
+ }
943
+ );
944
+ if (result.records.length === 0) {
945
+ console.error(`[persist] Neo4j write skipped \u2014 conversation not found: ${sessionId.slice(0, 8)}\u2026`);
946
+ return null;
947
+ }
948
+ const record = result.records[0];
949
+ const prevMessageId = record.get("prevMessageId") ?? null;
950
+ const summarySetThisWrite = record.get("summarySetThisWrite") === true;
951
+ const chainLenRaw = record.get("chainLen");
952
+ const chainLen = typeof chainLenRaw === "bigint" ? Number(chainLenRaw) : typeof chainLenRaw?.toNumber === "function" ? chainLenRaw.toNumber() : Number(chainLenRaw ?? 0);
953
+ const messageSublabel = role === "user" ? "UserMessage" : "AssistantMessage";
954
+ console.error(`[neo4j-store] append-message sessionId=${sessionId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 prev=${prevMessageId ? prevMessageId.slice(0, 8) + "\u2026" : "null"} chainLen=${chainLen} waited=${waited} sublabel=${messageSublabel}`);
955
+ if (summarySetThisWrite) {
956
+ console.error(`[neo4j-store] conversation-summary-set sessionId=${sessionId.slice(0, 8)}\u2026 len=${summary.length}`);
957
+ }
958
+ const componentList = components ?? [];
959
+ if (componentList.length > 0) {
960
+ const relsCreated = result.summary.counters.updates().relationshipsCreated;
961
+ const expectedComponentEdges = componentList.length;
962
+ const baseEdges = relsCreated - expectedComponentEdges;
963
+ if (baseEdges < 1) {
964
+ console.error(`[neo4j-store] persist-component WARN sessionId=${sessionId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 relsCreated=${relsCreated} expected\u2265${1 + expectedComponentEdges} \u2014 component edges may not have been created`);
965
+ }
966
+ for (const comp of componentList) {
967
+ console.error(`[neo4j-store] persist-component sessionId=${sessionId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 componentId=${comp.componentId.slice(0, 8)}\u2026 name=${comp.name} dataLen=${comp.data.length} ordinal=${comp.ordinal} textOffset=${comp.textOffset}`);
968
+ }
969
+ }
970
+ const attachmentList = attachments ?? [];
971
+ if (attachmentList.length > 0) {
972
+ const relsCreated = result.summary.counters.updates().relationshipsCreated;
973
+ const expectedAttachmentEdges = attachmentList.length;
974
+ const expectedComponentEdges = (components ?? []).length;
975
+ const baseEdges = relsCreated - expectedComponentEdges - expectedAttachmentEdges;
976
+ if (baseEdges < 1) {
977
+ console.error(`[neo4j-store] persist-attachment WARN sessionId=${sessionId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 relsCreated=${relsCreated} expected\u2265${1 + expectedComponentEdges + expectedAttachmentEdges} \u2014 attachment edges may not have been created`);
978
+ }
979
+ for (const att of attachmentList) {
980
+ console.error(`[neo4j-store] persist-attachment sessionId=${sessionId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 attachmentId=${att.attachmentId.slice(0, 8)}\u2026 filename=${att.filename} mimeType=${att.mimeType} sizeBytes=${att.sizeBytes} ordinal=${att.ordinal}`);
981
+ }
982
+ }
983
+ console.error(`[persist] sessionId=${sessionId.slice(0, 8)}\u2026 role=${role} len=${content.length}${sender ? ` sender=${sender.displayName}` : ""}`);
984
+ return messageId;
985
+ } catch (err) {
986
+ console.error(`[persist] Neo4j write failed: ${err instanceof Error ? err.message : String(err)}`);
987
+ return null;
988
+ } finally {
989
+ release();
990
+ if (persistMessageLocks.get(sessionId) === chained) {
991
+ persistMessageLocks.delete(sessionId);
992
+ }
993
+ await session.close();
994
+ }
995
+ }
996
+ async function getAgentSessionIdForConversation(sessionId) {
997
+ const session = getSession();
998
+ try {
999
+ const result = await session.run(
1000
+ `MATCH (c:Conversation {sessionId: $sessionId})
1001
+ RETURN c.agentSessionId AS agentSessionId`,
1002
+ { sessionId }
1003
+ );
1004
+ const value = result.records[0]?.get("agentSessionId");
1005
+ return typeof value === "string" && value.length > 0 ? value : null;
1006
+ } catch (err) {
1007
+ console.error(`[persist] agent-session-id read failed convId=${sessionId.slice(0, 8)}\u2026 error=${err instanceof Error ? err.message : String(err)}`);
1008
+ return null;
1009
+ } finally {
1010
+ await session.close();
1011
+ }
1012
+ }
1013
+ async function getRecentMessages(sessionId, limit = 50) {
1014
+ const session = getSession();
1015
+ try {
1016
+ const result = await session.run(
1017
+ `MATCH (tail:Message {sessionId: $sessionId})
1018
+ WHERE NOT (tail)-[:NEXT]->(:Message)
1019
+ WITH tail ORDER BY tail.createdAt DESC LIMIT 1
1020
+ MATCH path = (m:Message)-[:NEXT*0..]->(tail)
1021
+ WHERE m.sessionId = $sessionId
1022
+ AND length(path) < $limit
1023
+ WITH m, length(path) AS depthFromTail
1024
+ OPTIONAL MATCH (m)-[:HAS_COMPONENT]->(c:Component)
1025
+ WITH m, depthFromTail, c ORDER BY c.ordinal ASC
1026
+ WITH m, depthFromTail,
1027
+ [comp IN collect(c) WHERE comp IS NOT NULL | comp {.*}] AS components
1028
+ OPTIONAL MATCH (m)-[:HAS_ATTACHMENT]->(a:Attachment)
1029
+ WITH m, depthFromTail, components, a ORDER BY a.ordinal ASC
1030
+ WITH m, depthFromTail, components,
1031
+ [att IN collect(a) WHERE att IS NOT NULL | att {.*}] AS attachments
1032
+ RETURN m.messageId AS messageId, m.role AS role, m.content AS content,
1033
+ m.createdAt AS createdAt, components, attachments
1034
+ ORDER BY depthFromTail DESC`,
1035
+ { sessionId, limit: neo4j.int(limit) }
1036
+ );
1037
+ return result.records.map((r) => {
1038
+ const rawComponents = r.get("components") ?? [];
1039
+ const components = rawComponents.map((c) => {
1040
+ const rawAttachmentId = c.attachmentId;
1041
+ const attachmentId = typeof rawAttachmentId === "string" && rawAttachmentId.length > 0 ? rawAttachmentId : void 0;
1042
+ return {
1043
+ componentId: String(c.componentId ?? ""),
1044
+ name: String(c.name ?? ""),
1045
+ data: String(c.data ?? ""),
1046
+ ordinal: typeof c.ordinal?.toNumber === "function" ? c.ordinal.toNumber() : Number(c.ordinal ?? 0),
1047
+ textOffset: typeof c.textOffset?.toNumber === "function" ? c.textOffset.toNumber() : Number(c.textOffset ?? 0),
1048
+ submitted: c.submitted === true,
1049
+ ...attachmentId ? { attachmentId } : {}
1050
+ };
1051
+ });
1052
+ const rawAttachments = r.get("attachments") ?? [];
1053
+ const attachments = rawAttachments.map((a) => ({
1054
+ attachmentId: String(a.attachmentId ?? ""),
1055
+ filename: String(a.filename ?? ""),
1056
+ mimeType: String(a.mimeType ?? ""),
1057
+ sizeBytes: typeof a.sizeBytes?.toNumber === "function" ? a.sizeBytes.toNumber() : Number(a.sizeBytes ?? 0),
1058
+ storagePath: String(a.storagePath ?? ""),
1059
+ ordinal: typeof a.ordinal?.toNumber === "function" ? a.ordinal.toNumber() : Number(a.ordinal ?? 0),
1060
+ accountId: String(a.accountId ?? "")
1061
+ }));
1062
+ return {
1063
+ messageId: r.get("messageId"),
1064
+ role: r.get("role"),
1065
+ content: r.get("content"),
1066
+ createdAt: String(r.get("createdAt")),
1067
+ components,
1068
+ attachments
1069
+ };
1070
+ });
1071
+ } catch (err) {
1072
+ console.error(`[persist] getRecentMessages failed: ${err instanceof Error ? err.message : String(err)}`);
1073
+ return [];
1074
+ } finally {
1075
+ await session.close();
1076
+ }
1077
+ }
1078
+ async function verifyConversationOwnership(sessionId, accountId) {
1079
+ const session = getSession();
1080
+ try {
1081
+ const result = await session.run(
1082
+ `MATCH (c:Conversation {sessionId: $sessionId, accountId: $accountId})
1083
+ RETURN c.sessionId AS id LIMIT 1`,
1084
+ { sessionId, accountId }
1085
+ );
1086
+ return result.records.length > 0;
1087
+ } catch (err) {
1088
+ console.error(`[persist] verifyConversationOwnership failed: ${err instanceof Error ? err.message : String(err)}`);
1089
+ return false;
1090
+ } finally {
1091
+ await session.close();
1092
+ }
1093
+ }
1094
+ async function getConversationOwner(sessionId) {
1095
+ const session = getSession();
1096
+ try {
1097
+ const result = await session.run(
1098
+ `MATCH (c:Conversation {sessionId: $sessionId})
1099
+ RETURN c.accountId AS accountId, c.userId AS userId LIMIT 1`,
1100
+ { sessionId }
1101
+ );
1102
+ const record = result.records[0];
1103
+ if (!record) return null;
1104
+ const accountId = record.get("accountId");
1105
+ const userId = record.get("userId");
1106
+ if (!accountId) return null;
1107
+ return { accountId, userId: userId ?? null };
1108
+ } catch (err) {
1109
+ console.error(`[persist] getConversationOwner failed: ${err instanceof Error ? err.message : String(err)}`);
1110
+ return null;
1111
+ } finally {
1112
+ await session.close();
1113
+ }
1114
+ }
1115
+ async function verifyAndGetConversationUpdatedAt(sessionId, accountId) {
1116
+ const session = getSession();
1117
+ try {
1118
+ const result = await session.run(
1119
+ `MATCH (c:Conversation {sessionId: $sessionId, accountId: $accountId})
1120
+ RETURN toString(c.updatedAt) AS updatedAt LIMIT 1`,
1121
+ { sessionId, accountId }
1122
+ );
1123
+ const record = result.records[0];
1124
+ return record ? record.get("updatedAt") : null;
1125
+ } catch (err) {
1126
+ console.error(`[persist] verifyAndGetConversationUpdatedAt failed: ${err instanceof Error ? err.message : String(err)}`);
1127
+ return null;
1128
+ } finally {
1129
+ await session.close();
1130
+ }
1131
+ }
1132
+ async function listAdminSessions(accountId, userId, limit = 20) {
1133
+ const session = getSession();
1134
+ try {
1135
+ const result = await session.run(
1136
+ `MATCH (c:Conversation {accountId: $accountId, agentType: 'admin', userId: $userId})
1137
+ WHERE NOT c:Trashed
1138
+ RETURN c.sessionId AS sessionId,
1139
+ c.name AS name,
1140
+ c.updatedAt AS updatedAt,
1141
+ c.channel AS channel
1142
+ ORDER BY c.updatedAt DESC
1143
+ LIMIT $limit`,
1144
+ { accountId, userId, limit: neo4j.int(limit) }
1145
+ );
1146
+ return result.records.map((r) => ({
1147
+ sessionId: r.get("sessionId"),
1148
+ name: r.get("name"),
1149
+ updatedAt: String(r.get("updatedAt")),
1150
+ channel: r.get("channel")
1151
+ }));
1152
+ } catch (err) {
1153
+ console.error(`[persist] listAdminSessions failed: ${err instanceof Error ? err.message : String(err)}`);
1154
+ return [];
1155
+ } finally {
1156
+ await session.close();
1157
+ }
1158
+ }
1159
+ async function deleteConversation(sessionId) {
1160
+ const session = getSession();
1161
+ try {
1162
+ const result = await session.run(
1163
+ `MATCH (c:Conversation {sessionId: $sessionId})
1164
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1165
+ OPTIONAL MATCH (m)-[:HAS_COMPONENT]->(comp:Component)
1166
+ OPTIONAL MATCH (m)-[:HAS_ATTACHMENT]->(att:Attachment)
1167
+ OPTIONAL MATCH (c)-[:HAS_TRANSCRIPT]->(t:ClaudeSession)
1168
+ DETACH DELETE att, comp, m, t, c
1169
+ RETURN count(c) AS deleted`,
1170
+ { sessionId }
1171
+ );
1172
+ const deleted = result.records[0]?.get("deleted");
1173
+ const count = typeof deleted === "object" && deleted !== null ? Number(deleted) : Number(deleted ?? 0);
1174
+ const found = count > 0;
1175
+ console.error(`[persist] deleteConversation ${sessionId.slice(0, 8)}\u2026: ${found ? "deleted" : "not found"}`);
1176
+ return { found };
1177
+ } finally {
1178
+ await session.close();
1179
+ }
1180
+ }
1181
+ async function linkConversationTranscript(sessionId, claudeSessionId, accountId) {
1182
+ if (!sessionId || !claudeSessionId || !accountId) {
1183
+ console.error(`[transcript-link] schema-violation sessionId=${sessionId ? "set" : "EMPTY"} claudeSessionId=${claudeSessionId ? "set" : "EMPTY"} accountId=${accountId ? "set" : "EMPTY"}`);
1184
+ return { linked: false };
1185
+ }
1186
+ const session = getSession();
1187
+ try {
1188
+ const result = await session.run(
1189
+ `MATCH (c:Conversation {sessionId: $sessionId, accountId: $accountId})
1190
+ MERGE (c)-[:HAS_TRANSCRIPT]->(t:ClaudeSession {claudeSessionId: $claudeSessionId})
1191
+ ON CREATE SET
1192
+ t.accountId = $accountId,
1193
+ t.createdAt = datetime()
1194
+ RETURN count(t) AS linked`,
1195
+ { sessionId, claudeSessionId, accountId }
1196
+ );
1197
+ const linked = Number(result.records[0]?.get("linked") ?? 0) > 0;
1198
+ if (!linked) {
1199
+ console.error(`[transcript-link] convId=${sessionId.slice(0, 8)}\u2026 claudeSessionId=${claudeSessionId.slice(0, 8)}\u2026 status=skipped reason=conversation-not-found`);
1200
+ }
1201
+ return { linked };
1202
+ } catch (err) {
1203
+ console.error(`[transcript-link] convId=${sessionId.slice(0, 8)}\u2026 claudeSessionId=${claudeSessionId.slice(0, 8)}\u2026 status=failed error=${err instanceof Error ? err.message : String(err)}`);
1204
+ return { linked: false };
1205
+ } finally {
1206
+ await session.close();
1207
+ }
1208
+ }
1209
+ async function getConversationClaudeSessionIds(sessionId, accountId) {
1210
+ const session = getSession();
1211
+ try {
1212
+ const result = await session.run(
1213
+ `MATCH (c:Conversation {sessionId: $sessionId, accountId: $accountId})-[:HAS_TRANSCRIPT]->(t:ClaudeSession)
1214
+ RETURN t.claudeSessionId AS claudeSessionId
1215
+ ORDER BY t.createdAt ASC`,
1216
+ { sessionId, accountId }
1217
+ );
1218
+ return result.records.map((r) => r.get("claudeSessionId")).filter((v) => typeof v === "string" && v.length > 0);
1219
+ } finally {
1220
+ await session.close();
1221
+ }
1222
+ }
1223
+ async function renameConversation(sessionId, label) {
1224
+ let embedding = null;
1225
+ try {
1226
+ embedding = await embed(label);
1227
+ } catch (err) {
1228
+ console.error(`[persist] manual-label: embedding failed, persisting without: ${err instanceof Error ? err.message : String(err)}`);
1229
+ }
1230
+ const session = getSession();
1231
+ try {
1232
+ await session.run(
1233
+ `MATCH (c:Conversation {sessionId: $sessionId})
1234
+ SET c.name = $label, c.updatedAt = datetime()
1235
+ ${embedding ? ", c.embedding = $embedding" : ""}`,
1236
+ { sessionId, label, ...embedding ? { embedding } : {} }
1237
+ );
1238
+ console.error(`[persist] manual-label: renamed ${sessionId} to "${label}"${embedding ? " (embedded)" : ""}`);
1239
+ } finally {
1240
+ await session.close();
1241
+ }
1242
+ }
1243
+ var DECAY_THRESHOLD_DAYS = 14;
1244
+ var DECAY_RATE_PER_DAY = 0.05;
1245
+ var INJECTION_THRESHOLD = 0.4;
1246
+ var MAX_SUMMARY_PREFERENCES = 30;
1247
+ async function getUserTimezone(accountId, userId) {
1248
+ const session = getSession();
1249
+ try {
1250
+ const query = userId ? `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
1251
+ RETURN up.timezone AS timezone` : `MATCH (up:UserProfile {accountId: $accountId})
1252
+ RETURN up.timezone AS timezone ORDER BY up.createdAt LIMIT 1`;
1253
+ const result = await session.run(query, { accountId, userId: userId ?? "" });
1254
+ if (result.records.length === 0) return null;
1255
+ const tz = result.records[0].get("timezone");
1256
+ return tz && tz.trim().length > 0 ? tz : null;
1257
+ } catch (err) {
1258
+ console.error(`[datetime] getUserTimezone failed: ${err instanceof Error ? err.message : String(err)}`);
1259
+ return null;
1260
+ } finally {
1261
+ await session.close();
1262
+ }
1263
+ }
1264
+ async function loadAdminUserName(userId) {
1265
+ const session = getSession();
1266
+ try {
1267
+ const result = await session.run(
1268
+ `MATCH (au:AdminUser {userId: $userId})-[:OWNS]->(p:Person)
1269
+ WHERE p.accountId = au.accountId
1270
+ RETURN p.givenName AS givenName, p.familyName AS familyName, p.avatar AS avatar
1271
+ LIMIT 1`,
1272
+ { userId }
1273
+ );
1274
+ if (result.records.length === 0) {
1275
+ return { source: "fallback", reason: "no-person-node" };
1276
+ }
1277
+ const givenName = result.records[0].get("givenName");
1278
+ const familyName = result.records[0].get("familyName");
1279
+ const avatar = result.records[0].get("avatar");
1280
+ if (!givenName || givenName.trim().length === 0) {
1281
+ return { source: "fallback", reason: "no-givenName" };
1282
+ }
1283
+ const trimmedFamily = familyName && familyName.trim().length > 0 ? familyName.trim() : null;
1284
+ const trimmedAvatar = avatar && avatar.trim().length > 0 ? avatar.trim() : null;
1285
+ const joined = trimmedFamily ? `${givenName.trim()} ${trimmedFamily}` : givenName.trim();
1286
+ return { source: "neo4j", joined, givenName: givenName.trim(), familyName: trimmedFamily, avatar: trimmedAvatar };
1287
+ } catch (err) {
1288
+ console.error(`[admin-identity] loadAdminUserName failed: ${err instanceof Error ? err.message : String(err)}`);
1289
+ return { source: "fallback", reason: "neo4j-unreachable" };
1290
+ } finally {
1291
+ await session.close();
1292
+ }
1293
+ }
1294
+ async function loadPersonNameByElementId(accountId, personId) {
1295
+ const session = getSession();
1296
+ try {
1297
+ const result = await session.run(
1298
+ `MATCH (p:Person {accountId: $accountId})
1299
+ WHERE elementId(p) = $personId
1300
+ RETURN p.givenName AS givenName, p.familyName AS familyName
1301
+ LIMIT 1`,
1302
+ { accountId, personId },
1303
+ { timeout: 2e3 }
1304
+ );
1305
+ if (result.records.length === 0) return null;
1306
+ const given = result.records[0].get("givenName");
1307
+ const family = result.records[0].get("familyName");
1308
+ if (!given || given.trim().length === 0) return null;
1309
+ const fam = family && family.trim().length > 0 ? family.trim() : null;
1310
+ return fam ? `${given.trim()} ${fam}` : given.trim();
1311
+ } catch (err) {
1312
+ console.error(
1313
+ `[admin-sessions-list] loadPersonNameByElementId failed: ${err instanceof Error ? err.message : String(err)}`
1314
+ );
1315
+ return null;
1316
+ } finally {
1317
+ await session.close();
1318
+ }
1319
+ }
1320
+ async function writeAdminUserAndPerson(params) {
1321
+ const { userId, fullName, accountId } = params;
1322
+ const trimmed = fullName.trim();
1323
+ if (!trimmed) {
1324
+ throw new Error("writeAdminUserAndPerson: fullName cannot be empty");
1325
+ }
1326
+ const firstSpace = trimmed.search(/\s/);
1327
+ const givenName = firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace).trim();
1328
+ const familyName = firstSpace === -1 ? null : trimmed.slice(firstSpace + 1).trim() || null;
1329
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1330
+ let personEmbedding = null;
1331
+ try {
1332
+ personEmbedding = await embed(
1333
+ `[Person] ${[givenName, familyName].filter(Boolean).join(" ")} role: admin-personal`
1334
+ );
1335
+ } catch (err) {
1336
+ process.stderr.write(
1337
+ `[graph-write] warn reason=embed-failed labels=Person agent=admin-bootstrap detail=${err instanceof Error ? err.message : String(err)}
1338
+ `
1339
+ );
1340
+ }
1341
+ const serverTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1342
+ const session = getSession();
1343
+ try {
1344
+ const result = await session.run(
1345
+ `MERGE (au:AdminUser {userId: $userId})
1346
+ // Task 669 \u2014 stamp accountId/role at creation so the account-scoped
1347
+ // graph-write gate (MATCH (au:AdminUser {accountId:$accountId})) matches
1348
+ // on the operator's first memory write. Mirrors seed-neo4j.sh:175-181
1349
+ // and the sibling writers (neo4j-store.ts:537,:931). COALESCE on MATCH
1350
+ // preserves an already-stamped node.
1351
+ ON CREATE SET au.createdAt = $now,
1352
+ au.accountId = $accountId, au.role = 'owner'
1353
+ ON MATCH SET au.updatedAt = $now,
1354
+ au.accountId = COALESCE(au.accountId, $accountId),
1355
+ au.role = COALESCE(au.role, 'owner')
1356
+ WITH au
1357
+
1358
+ // Task 1150 \u2014 UserProfile guaranteed off the just-MERGEd AdminUser.
1359
+ MERGE (au)-[:HAS_PROFILE]->(up:UserProfile {accountId: $accountId, userId: $userId})
1360
+ ON CREATE SET
1361
+ up.createdAt = $now,
1362
+ up.updatedAt = $now,
1363
+ up.profileVersion = 0,
1364
+ up.scope = 'admin',
1365
+ up.timezone = $serverTimezone,
1366
+ up.timezoneSource = 'server-default'
1367
+ ON MATCH SET
1368
+ up.timezoneSource = CASE WHEN up.timezone IS NULL OR trim(up.timezone) = '' THEN 'server-default' ELSE up.timezoneSource END,
1369
+ up.timezone = CASE WHEN up.timezone IS NULL OR trim(up.timezone) = '' THEN $serverTimezone ELSE up.timezone END
1370
+ WITH au, (up.createdAt = $now) AS profileIsNew
1371
+
1372
+ // Case-insensitive Person reuse: same accountId, same givenName, same familyName
1373
+ // (null/empty familyName collapsed to '' so 'Joel' does NOT match 'Joel Smalley').
1374
+ OPTIONAL MATCH (existingPerson:Person {accountId: $accountId})
1375
+ WHERE toLower(existingPerson.givenName) = toLower($givenName)
1376
+ AND coalesce(toLower(existingPerson.familyName), '') = coalesce(toLower($familyName), '')
1377
+ WITH au, profileIsNew, existingPerson
1378
+
1379
+ CALL {
1380
+ WITH au, existingPerson
1381
+ WITH au, existingPerson WHERE existingPerson IS NOT NULL
1382
+ MERGE (au)-[:OWNS]->(existingPerson)
1383
+ RETURN existingPerson AS p, true AS reused
1384
+ UNION
1385
+ WITH au, existingPerson
1386
+ WITH au WHERE existingPerson IS NULL
1387
+ CREATE (newPerson:Person {
1388
+ accountId: $accountId,
1389
+ givenName: $givenName,
1390
+ familyName: $familyName,
1391
+ role: 'admin-personal',
1392
+ scope: 'admin',
1393
+ embedding: $personEmbedding,
1394
+ createdAt: $now
1395
+ })
1396
+ MERGE (au)-[:OWNS]->(newPerson)
1397
+ RETURN newPerson AS p, false AS reused
1398
+ }
1399
+ RETURN reused, profileIsNew, elementId(p) AS personElementId,
1400
+ p.givenName AS givenName, p.familyName AS familyName`,
1401
+ { userId, accountId, givenName, familyName, now, personEmbedding, serverTimezone }
1402
+ );
1403
+ if (result.records.length === 0) {
1404
+ throw new Error("writeAdminUserAndPerson: no record returned");
1405
+ }
1406
+ const record = result.records[0];
1407
+ if (record.get("profileIsNew")) {
1408
+ console.error(
1409
+ `[profile] provisioned at admin-bootstrap userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 timezone=${serverTimezone}`
1410
+ );
1411
+ }
1412
+ return {
1413
+ personReused: record.get("reused"),
1414
+ personElementId: record.get("personElementId"),
1415
+ givenName: record.get("givenName"),
1416
+ familyName: record.get("familyName")
1417
+ };
1418
+ } finally {
1419
+ await session.close();
1420
+ }
1421
+ }
1422
+ var PROFILE_CATEGORIES = [
1423
+ "communication",
1424
+ "scheduling",
1425
+ "decision",
1426
+ "workflow",
1427
+ "content",
1428
+ "interaction"
1429
+ ];
1430
+ var PROFILE_FIELD_TEMPLATES = {
1431
+ communication: [
1432
+ "preferredChannel",
1433
+ "quietHours",
1434
+ "responseLatencyExpectation",
1435
+ "formalityLevel",
1436
+ "escalationPath"
1437
+ ],
1438
+ scheduling: [
1439
+ "workdayStartTime",
1440
+ "workdayEndTime",
1441
+ "weekendAvailability",
1442
+ "meetingBlockPreference",
1443
+ "focusBlockTiming"
1444
+ ],
1445
+ decision: [
1446
+ "riskTolerance",
1447
+ "autonomyBoundary",
1448
+ "evidenceThreshold",
1449
+ "reversibilityPreference",
1450
+ "stakeholderConsultation"
1451
+ ],
1452
+ workflow: [
1453
+ "batchingPreference",
1454
+ "taskGranularity",
1455
+ "deepWorkBlocks",
1456
+ "statusUpdateCadence",
1457
+ "toolingChoices"
1458
+ ],
1459
+ content: [
1460
+ "outputFormat",
1461
+ "lengthPreference",
1462
+ "citationStyle",
1463
+ "tonality"
1464
+ ],
1465
+ interaction: [
1466
+ "addressForm",
1467
+ "humourTolerance",
1468
+ "directnessLevel",
1469
+ "emotionalRegisterPreference"
1470
+ ]
1471
+ };
1472
+ var TOTAL_PROFILE_FIELDS = Object.values(PROFILE_FIELD_TEMPLATES).reduce(
1473
+ (n, fs) => n + fs.length,
1474
+ 0
1475
+ );
1476
+ function computeAbsentFields(preferences, extraTemplates = {}) {
1477
+ const covered = /* @__PURE__ */ new Set();
1478
+ for (const pref of preferences) {
1479
+ const isCovered = pref.notApplicable === true || pref.confidence >= INJECTION_THRESHOLD;
1480
+ if (isCovered) covered.add(`${pref.category}.${pref.key}`);
1481
+ }
1482
+ const absent = [];
1483
+ for (const [category, fields] of Object.entries(PROFILE_FIELD_TEMPLATES)) {
1484
+ for (const field of fields) {
1485
+ const dotted = `${category}.${field}`;
1486
+ if (!covered.has(dotted)) absent.push(dotted);
1487
+ }
1488
+ }
1489
+ for (const [category, fields] of Object.entries(extraTemplates)) {
1490
+ if (category in PROFILE_FIELD_TEMPLATES) continue;
1491
+ for (const field of fields) {
1492
+ const dotted = `${category}.${field}`;
1493
+ if (!covered.has(dotted)) absent.push(dotted);
1494
+ }
1495
+ }
1496
+ return absent;
1497
+ }
1498
+ function parsePluginProfileKeys(manifest) {
1499
+ const fm = manifest.match(/^---\n([\s\S]*?)\n---/);
1500
+ if (!fm) return [];
1501
+ const out = [];
1502
+ let inBlock = false;
1503
+ for (const line of fm[1].split("\n")) {
1504
+ if (/^profileKeys:/.test(line)) {
1505
+ inBlock = true;
1506
+ continue;
1507
+ }
1508
+ if (inBlock) {
1509
+ const m = line.match(/^\s+-\s+(.+?)\s*$/);
1510
+ if (m) out.push(m[1]);
1511
+ else break;
1512
+ }
1513
+ }
1514
+ return out;
1515
+ }
1516
+ function loadEnabledPluginProfileKeys(accountId) {
1517
+ const accountFile = resolve3(PLATFORM_ROOT3, "..", "data/accounts", accountId, "account.json");
1518
+ if (!existsSync4(accountFile)) return {};
1519
+ let enabled;
1520
+ try {
1521
+ const raw = readFileSync4(accountFile, "utf-8");
1522
+ const parsed = JSON.parse(raw);
1523
+ enabled = Array.isArray(parsed.enabledPlugins) ? parsed.enabledPlugins.filter((p) => typeof p === "string") : [];
1524
+ } catch (err) {
1525
+ console.error(
1526
+ `[profile-keys] account.json read failed for ${accountId.slice(0, 8)}\u2026: ${err instanceof Error ? err.message : String(err)}`
1527
+ );
1528
+ return {};
1529
+ }
1530
+ const merged = {};
1531
+ for (const pluginName of enabled) {
1532
+ const manifestPath = resolve3(PLATFORM_ROOT3, "plugins", pluginName, "PLUGIN.md");
1533
+ if (!existsSync4(manifestPath)) continue;
1534
+ let manifest;
1535
+ try {
1536
+ manifest = readFileSync4(manifestPath, "utf-8");
1537
+ } catch {
1538
+ continue;
1539
+ }
1540
+ for (const dotted of parsePluginProfileKeys(manifest)) {
1541
+ const dot = dotted.indexOf(".");
1542
+ if (dot <= 0 || dot === dotted.length - 1) {
1543
+ console.error(`[profile-keys] malformed dotted key in ${pluginName}: ${dotted}`);
1544
+ continue;
1545
+ }
1546
+ const category = dotted.slice(0, dot);
1547
+ const key = dotted.slice(dot + 1);
1548
+ if (!merged[category]) merged[category] = /* @__PURE__ */ new Set();
1549
+ merged[category].add(key);
1550
+ }
1551
+ }
1552
+ const out = {};
1553
+ for (const [cat, set] of Object.entries(merged)) out[cat] = [...set];
1554
+ return out;
1555
+ }
1556
+ var sparseStateLogged = /* @__PURE__ */ new Set();
1557
+ async function loadUserProfile(accountId, userId, sessionId) {
1558
+ console.error(
1559
+ `[profile] loadUserProfile entry accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} sessionId=${sessionId ? `${sessionId.slice(0, 8)}\u2026` : "<none>"}`
1560
+ );
1561
+ const session = getSession();
1562
+ try {
1563
+ const serverTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1564
+ const mergeResult = await session.run(
1565
+ `MATCH (au:AdminUser {userId: $userId})
1566
+ MERGE (au)-[:HAS_PROFILE]->(up:UserProfile {accountId: $accountId, userId: $userId})
1567
+ ON CREATE SET
1568
+ up.createdAt = $now,
1569
+ up.updatedAt = $now,
1570
+ up.profileVersion = 0,
1571
+ up.scope = 'admin',
1572
+ up.timezone = $serverTimezone,
1573
+ up.timezoneSource = 'server-default'
1574
+ ON MATCH SET
1575
+ up.timezoneSource = CASE WHEN up.timezone IS NULL OR trim(up.timezone) = '' THEN 'server-default' ELSE up.timezoneSource END,
1576
+ up.timezone = CASE WHEN up.timezone IS NULL OR trim(up.timezone) = '' THEN $serverTimezone ELSE up.timezone END
1577
+ RETURN up.createdAt = $now AS isNew`,
1578
+ { accountId, userId, now: (/* @__PURE__ */ new Date()).toISOString(), serverTimezone }
1579
+ );
1580
+ if (mergeResult.records.length === 0) {
1581
+ console.error(`[profile] loadUserProfile: AdminUser not found for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 \u2014 profile not created, invariant violated`);
1582
+ return null;
1583
+ }
1584
+ const isNew = mergeResult.records[0].get("isNew");
1585
+ if (isNew) {
1586
+ console.error(`[profile] created new profile: userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 timezone=${serverTimezone}`);
1587
+ }
1588
+ const nowMs = Date.now();
1589
+ const thresholdMs = DECAY_THRESHOLD_DAYS * 24 * 60 * 60 * 1e3;
1590
+ const staleResult = await session.run(
1591
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})-[:HAS_PREFERENCE]->(pref:Preference)
1592
+ WHERE pref.observedAt IS NOT NULL
1593
+ RETURN pref.preferenceId AS preferenceId,
1594
+ pref.observedAt AS observedAt,
1595
+ pref.confidence AS confidence`,
1596
+ { accountId, userId }
1597
+ );
1598
+ let decayCount = 0;
1599
+ for (const record of staleResult.records) {
1600
+ const observedAt = record.get("observedAt");
1601
+ const confidence = record.get("confidence");
1602
+ const observedMs = new Date(observedAt).getTime();
1603
+ const ageMs = nowMs - observedMs;
1604
+ if (ageMs > thresholdMs && confidence > 0) {
1605
+ const daysPastThreshold = (ageMs - thresholdMs) / (24 * 60 * 60 * 1e3);
1606
+ const decayedConfidence = Math.max(0, confidence - DECAY_RATE_PER_DAY * daysPastThreshold);
1607
+ if (decayedConfidence !== confidence) {
1608
+ await session.run(
1609
+ `MATCH (pref:Preference {preferenceId: $preferenceId, accountId: $accountId})
1610
+ SET pref.confidence = $confidence`,
1611
+ {
1612
+ preferenceId: record.get("preferenceId"),
1613
+ accountId,
1614
+ confidence: decayedConfidence
1615
+ }
1616
+ );
1617
+ decayCount++;
1618
+ }
1619
+ }
1620
+ }
1621
+ const result = await session.run(
1622
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
1623
+ OPTIONAL MATCH (au:AdminUser {userId: $userId})-[:OWNS]->(p:Person {accountId: $accountId})
1624
+ OPTIONAL MATCH (up)-[:HAS_PREFERENCE]->(pref:Preference)
1625
+ WHERE pref.confidence >= $threshold OR pref.notApplicable = true
1626
+ WITH up, p, pref
1627
+ ORDER BY pref.confidence DESC
1628
+ WITH up, p, collect(pref) AS allPrefs
1629
+ WITH up, p, allPrefs[0..$limit] AS prefs
1630
+ RETURN up, p AS person, prefs`,
1631
+ // List-range slice bounds are an integer position; a raw JS number
1632
+ // serializes as a Cypher float. Bind a Neo4j integer.
1633
+ { accountId, userId, threshold: INJECTION_THRESHOLD, limit: neo4j.int(MAX_SUMMARY_PREFERENCES) }
1634
+ );
1635
+ if (result.records.length === 0 || !result.records[0].get("up")) {
1636
+ return null;
1637
+ }
1638
+ const upNode = result.records[0].get("up");
1639
+ const profileProps = { ...upNode.properties };
1640
+ const personNode = result.records[0].get("person");
1641
+ if (personNode?.properties) {
1642
+ if (personNode.properties.givenName !== void 0) profileProps.givenName = personNode.properties.givenName;
1643
+ if (personNode.properties.familyName !== void 0) profileProps.familyName = personNode.properties.familyName;
1644
+ if (personNode.properties.email !== void 0) profileProps.email = personNode.properties.email;
1645
+ if (personNode.properties.telephone !== void 0) profileProps.telephone = personNode.properties.telephone;
1646
+ }
1647
+ const prefNodes = result.records[0].get("prefs");
1648
+ const preferences = prefNodes.map((p) => ({
1649
+ preferenceId: p.properties.preferenceId,
1650
+ category: p.properties.category,
1651
+ key: p.properties.key,
1652
+ value: p.properties.value,
1653
+ confidence: p.properties.confidence,
1654
+ source: p.properties.source,
1655
+ observedAt: p.properties.observedAt,
1656
+ notApplicable: p.properties.notApplicable === true
1657
+ }));
1658
+ const extraTemplates = loadEnabledPluginProfileKeys(accountId);
1659
+ const extraFieldCount = Object.values(extraTemplates).reduce((n, fs) => n + fs.length, 0);
1660
+ const summary = formatProfileSummary(profileProps, preferences, extraTemplates);
1661
+ const absentFields = computeAbsentFields(preferences, extraTemplates);
1662
+ const totalFields = TOTAL_PROFILE_FIELDS + extraFieldCount;
1663
+ const fieldCoverageCount = totalFields - absentFields.length;
1664
+ const presentCategories = new Set(
1665
+ preferences.filter((p) => p.notApplicable === true || p.confidence >= INJECTION_THRESHOLD).map((p) => p.category)
1666
+ );
1667
+ const absentCategories = PROFILE_CATEGORIES.filter((c) => !presentCategories.has(c));
1668
+ const categoryCoverage = PROFILE_CATEGORIES.length - absentCategories.length;
1669
+ console.error(
1670
+ `[profile] loaded for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 preferences=${preferences.length} fieldCoverage=${fieldCoverageCount}/${totalFields} categoryCoverage=${categoryCoverage}/${PROFILE_CATEGORIES.length} (decay: ${decayCount} updated)`
1671
+ );
1672
+ const identityKeys = [
1673
+ { prop: "email", token: "email" },
1674
+ // Schema-canonical name. `phone` is the synonym (rejected at tool
1675
+ // surface); the log uses `telephone` to keep grep aligned with
1676
+ // schema-base.md doctrine the brief enforces.
1677
+ { prop: "telephone", token: "telephone" },
1678
+ { prop: "givenName", token: "givenName" },
1679
+ { prop: "familyName", token: "familyName" },
1680
+ { prop: "role", token: "role" }
1681
+ ];
1682
+ const absentIdentity = identityKeys.filter((k) => {
1683
+ const v = profileProps[k.prop];
1684
+ return typeof v !== "string" || v.trim().length === 0;
1685
+ });
1686
+ const sparseFired = absentCategories.length > 0 || absentFields.length > 0 || absentIdentity.length > 0;
1687
+ if (sessionId && sparseFired) {
1688
+ const dedupeKey = `${accountId}:${userId}:${sessionId}`;
1689
+ if (!sparseStateLogged.has(dedupeKey)) {
1690
+ sparseStateLogged.add(dedupeKey);
1691
+ const FIELDS_LOG_CAP = 10;
1692
+ const absentFieldsTruncated = absentFields.length <= FIELDS_LOG_CAP ? absentFields.join(",") : `${absentFields.slice(0, FIELDS_LOG_CAP).join(",")}+${absentFields.length - FIELDS_LOG_CAP} more`;
1693
+ console.error(
1694
+ `[profile] sparse-state injected accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} sessionId=${sessionId.slice(0, 8)}\u2026 absentCategories=${absentCategories.join(",")} absentFields=${absentFieldsTruncated || "none"} absentIdentity=${absentIdentity.map((k) => k.token).join(",") || "none"}`
1695
+ );
1696
+ }
1697
+ }
1698
+ return summary;
1699
+ } catch (err) {
1700
+ console.error(`[profile] loadUserProfile failed: ${err instanceof Error ? err.message : String(err)}`);
1701
+ return null;
1702
+ } finally {
1703
+ await session.close();
1704
+ }
1705
+ }
1706
+ function formatProfileSummary(profile, preferences, extraTemplates = {}) {
1707
+ const summary = composeOperatorSummary(profile, preferences);
1708
+ return [
1709
+ `This is what you know about the operator: ${summary}.`,
1710
+ `You must seek to MAXIMISE what you know about the operator to do your job effectively.`
1711
+ ].join("\n");
1712
+ }
1713
+ function composeOperatorSummary(profile, preferences) {
1714
+ const facts = [];
1715
+ const givenName = typeof profile.givenName === "string" ? profile.givenName.trim() : "";
1716
+ const familyName = typeof profile.familyName === "string" ? profile.familyName.trim() : "";
1717
+ const fullName = [givenName, familyName].filter((s) => s.length > 0).join(" ");
1718
+ if (fullName) facts.push(`name ${fullName}`);
1719
+ if (typeof profile.role === "string" && profile.role.trim()) {
1720
+ facts.push(`role ${profile.role.trim()}`);
1721
+ }
1722
+ if (typeof profile.timezone === "string" && profile.timezone.trim()) {
1723
+ facts.push(`timezone ${profile.timezone.trim()}`);
1724
+ }
1725
+ if (typeof profile.locale === "string" && profile.locale.trim()) {
1726
+ facts.push(`locale ${profile.locale.trim()}`);
1727
+ }
1728
+ if (typeof profile.email === "string" && profile.email.trim()) {
1729
+ facts.push(`email ${profile.email.trim()}`);
1730
+ }
1731
+ if (typeof profile.telephone === "string" && profile.telephone.trim()) {
1732
+ facts.push(`telephone ${profile.telephone.trim()}`);
1733
+ }
1734
+ if (profile.expertise) {
1735
+ const expVal = typeof profile.expertise === "string" ? profile.expertise : JSON.stringify(profile.expertise);
1736
+ if (expVal.trim()) facts.push(`expertise ${expVal.trim()}`);
1737
+ }
1738
+ const byCategory = {};
1739
+ for (const pref of preferences) {
1740
+ if (pref.notApplicable === true) continue;
1741
+ if (typeof pref.value !== "string" || pref.value.trim().length === 0) continue;
1742
+ if (!byCategory[pref.category]) byCategory[pref.category] = [];
1743
+ byCategory[pref.category].push(pref.value.trim());
1744
+ }
1745
+ for (const [cat, vals] of Object.entries(byCategory)) {
1746
+ facts.push(`${cat} ${vals.join(", ")}`);
1747
+ }
1748
+ return facts.length > 0 ? facts.join("; ") : "NOTHING";
1749
+ }
1750
+ var RECENT_FAILURES_TAIL_BYTES = 10 * 1024;
1751
+ var AGENT_FILE_ROLES = [
1752
+ { filename: "IDENTITY.md", role: "identity" },
1753
+ { filename: "SOUL.md", role: "soul" },
1754
+ { filename: "KNOWLEDGE.md", role: "knowledge" },
1755
+ { filename: "KNOWLEDGE-SUMMARY.md", role: "knowledge-summary" }
1756
+ ];
1757
+ var ROLE_TO_EDGE = {
1758
+ identity: "HAS_IDENTITY",
1759
+ soul: "HAS_SOUL",
1760
+ knowledge: "HAS_KNOWLEDGE",
1761
+ "knowledge-summary": "HAS_KNOWLEDGE"
1762
+ };
1763
+ function assertSafeAgentSlug(slug) {
1764
+ if (!slug || slug.includes("/") || slug.includes("\\") || slug.includes("..")) {
1765
+ throw new Error(`[agent-graph] refusing unsafe slug=${JSON.stringify(slug)}`);
1766
+ }
1767
+ }
1768
+ function agentAttachmentId(accountId, slug, role) {
1769
+ return `agent:${accountId}:${slug}:${role}`;
1770
+ }
1771
+ async function projectAgent(accountId, accountDir, slug) {
1772
+ const start = Date.now();
1773
+ const account8 = accountId.slice(0, 8);
1774
+ try {
1775
+ assertSafeAgentSlug(slug);
1776
+ } catch (err) {
1777
+ const msg = err instanceof Error ? err.message : String(err);
1778
+ console.error(
1779
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
1780
+ );
1781
+ return;
1782
+ }
1783
+ const agentDir = resolve3(accountDir, "agents", slug);
1784
+ const configPath = resolve3(agentDir, "config.json");
1785
+ let config;
1786
+ let presentRoles = [];
1787
+ try {
1788
+ if (!existsSync4(configPath)) {
1789
+ console.error(
1790
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="config.json missing at ${configPath}"`
1791
+ );
1792
+ return;
1793
+ }
1794
+ config = JSON.parse(readFileSync4(configPath, "utf-8"));
1795
+ for (const { filename, role } of AGENT_FILE_ROLES) {
1796
+ const filePath = resolve3(agentDir, filename);
1797
+ if (!existsSync4(filePath)) continue;
1798
+ const body = readFileSync4(filePath, "utf-8");
1799
+ presentRoles.push({ role, body, edge: ROLE_TO_EDGE[role] });
1800
+ }
1801
+ } catch (err) {
1802
+ const msg = err instanceof Error ? err.message : String(err);
1803
+ console.error(
1804
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
1805
+ );
1806
+ return;
1807
+ }
1808
+ const session = getSession();
1809
+ try {
1810
+ await session.run(
1811
+ `MERGE (a:Agent {accountId: $accountId, slug: $slug})
1812
+ ON CREATE SET a.createdAt = datetime()
1813
+ SET a.displayName = $displayName,
1814
+ a.status = $status,
1815
+ a.model = $model,
1816
+ a.knowledgeKeywords = $knowledgeKeywords,
1817
+ a.role = 'agent',
1818
+ a.updatedAt = datetime()
1819
+ RETURN a.slug AS slug`,
1820
+ {
1821
+ accountId,
1822
+ slug,
1823
+ displayName: config.displayName ?? slug,
1824
+ status: config.status ?? "unknown",
1825
+ model: config.model ?? "",
1826
+ knowledgeKeywords: config.knowledgeKeywords ?? []
1827
+ }
1828
+ );
1829
+ for (const { role, body, edge } of presentRoles) {
1830
+ const attachmentId = agentAttachmentId(accountId, slug, role);
1831
+ await session.run(
1832
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
1833
+ MERGE (k:KnowledgeDocument {attachmentId: $attachmentId})
1834
+ ON CREATE SET k.createdAt = datetime()
1835
+ SET k.accountId = $accountId,
1836
+ k.role = $role,
1837
+ k.name = $name,
1838
+ k.text = $text,
1839
+ k.scope = 'admin',
1840
+ k.updatedAt = datetime()
1841
+ MERGE (a)-[:${edge}]->(k)
1842
+ RETURN k.attachmentId AS attachmentId`,
1843
+ {
1844
+ accountId,
1845
+ slug,
1846
+ attachmentId,
1847
+ role,
1848
+ name: `${slug} ${role}`,
1849
+ text: body
1850
+ }
1851
+ );
1852
+ }
1853
+ const usesResult = await session.run(
1854
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
1855
+ MATCH (k:KnowledgeDocument {accountId: $accountId})
1856
+ WHERE $slug IN coalesce(k.agents, [])
1857
+ AND NOT k.attachmentId STARTS WITH $namespacePrefix
1858
+ MERGE (a)-[:USES_KNOWLEDGE]->(k)
1859
+ RETURN count(k) AS uses`,
1860
+ {
1861
+ accountId,
1862
+ slug,
1863
+ namespacePrefix: `agent:${accountId}:${slug}:`
1864
+ }
1865
+ );
1866
+ const uses = usesResult.records[0]?.get("uses");
1867
+ const usesCount = typeof uses === "number" ? uses : uses && typeof uses.toNumber === "function" ? uses.toNumber() : 0;
1868
+ const ms = Date.now() - start;
1869
+ console.error(
1870
+ `[agent-graph] project slug=${slug} account=${account8} docs=${presentRoles.length} uses=${usesCount} ms=${ms}`
1871
+ );
1872
+ } catch (err) {
1873
+ const msg = err instanceof Error ? err.message : String(err);
1874
+ console.error(
1875
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
1876
+ );
1877
+ throw err;
1878
+ } finally {
1879
+ await session.close();
1880
+ }
1881
+ }
1882
+ async function deleteAgentProjection(accountId, slug) {
1883
+ const start = Date.now();
1884
+ const account8 = accountId.slice(0, 8);
1885
+ assertSafeAgentSlug(slug);
1886
+ const session = getSession();
1887
+ try {
1888
+ await session.run(
1889
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
1890
+ DETACH DELETE a
1891
+ WITH 1 AS _
1892
+ UNWIND $attachmentIds AS aid
1893
+ OPTIONAL MATCH (k:KnowledgeDocument {accountId: $accountId, attachmentId: aid})
1894
+ WHERE k.attachmentId STARTS WITH $namespacePrefix
1895
+ DETACH DELETE k`,
1896
+ {
1897
+ accountId,
1898
+ slug,
1899
+ namespacePrefix: `agent:${accountId}:${slug}:`,
1900
+ attachmentIds: ["identity", "soul", "knowledge", "knowledge-summary"].map((role) => agentAttachmentId(accountId, slug, role))
1901
+ }
1902
+ );
1903
+ const ms = Date.now() - start;
1904
+ console.error(
1905
+ `[agent-graph] delete slug=${slug} account=${account8} ms=${ms}`
1906
+ );
1907
+ } catch (err) {
1908
+ const msg = err instanceof Error ? err.message : String(err);
1909
+ console.error(
1910
+ `[agent-graph] delete FAILED slug=${slug} account=${account8} error="${msg}"`
1911
+ );
1912
+ throw err;
1913
+ } finally {
1914
+ await session.close();
1915
+ }
1916
+ }
1917
+
1918
+ export {
1919
+ MAXY_DIR,
1920
+ BRAND_NAME,
1921
+ COMMERCIAL_MODE,
1922
+ BUNDLE_MODE,
1923
+ BUNDLE_ALLOWLIST,
1924
+ VNC_DISPLAY,
1925
+ RFB_PORT,
1926
+ WEBSOCKIFY_PORT,
1927
+ CDP_PORT,
1928
+ CHROMIUM_PROFILE_DIR,
1929
+ USERS_FILE,
1930
+ LID_MAP_FILE,
1931
+ LOG_DIR,
1932
+ USERS_AUDIT_LOG,
1933
+ BIN_DIR,
1934
+ REMOTE_PASSWORD_FILE,
1935
+ REMOTE_SESSION_SECRET_FILE,
1936
+ INSTALL_OWNER_FILE,
1937
+ VISITOR_TOKEN_SECRET_FILE,
1938
+ CLAUDE_CREDENTIALS_FILE,
1939
+ SYSTEM_PATH_SLUGS,
1940
+ PLATFORM_ROOT2 as PLATFORM_ROOT,
1941
+ ACCOUNTS_DIR,
1942
+ listValidAccounts,
1943
+ isValidAccountId,
1944
+ resolveAccount,
1945
+ validateAgentSlug,
1946
+ resolveDefaultAgentSlug,
1947
+ resolveAgentConfig,
1948
+ isActiveAgentSlug,
1949
+ getDefaultAccountId,
1950
+ getSession,
1951
+ runAdminUserSelfHeal,
1952
+ runUserProfileReconcile,
1953
+ embed,
1954
+ preloadEmbedModel,
1955
+ GREETING_DIRECTIVE,
1956
+ ensureConversation,
1957
+ ensureSessionConversation,
1958
+ findRecentConversation,
1959
+ createNewAdminConversation,
1960
+ fetchBranding,
1961
+ fetchAccountName,
1962
+ persistMessage,
1963
+ getAgentSessionIdForConversation,
1964
+ getRecentMessages,
1965
+ verifyConversationOwnership,
1966
+ getConversationOwner,
1967
+ verifyAndGetConversationUpdatedAt,
1968
+ listAdminSessions,
1969
+ deleteConversation,
1970
+ linkConversationTranscript,
1971
+ getConversationClaudeSessionIds,
1972
+ renameConversation,
1973
+ getUserTimezone,
1974
+ loadAdminUserName,
1975
+ loadPersonNameByElementId,
1976
+ writeAdminUserAndPerson,
1977
+ loadUserProfile,
1978
+ projectAgent,
1979
+ deleteAgentProjection
1980
+ };