remoteclaw 0.1.0-next.049f396 → 0.1.0-next.05abcca

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 (1199) hide show
  1. package/README.md +11 -9
  2. package/dist/accounts-79XhjwAj.js +32 -0
  3. package/dist/accounts-B1M3fOxL.js +272 -0
  4. package/dist/accounts-BwbvnKsW.js +205 -0
  5. package/dist/accounts-CIVjmTg9.js +270 -0
  6. package/dist/accounts-D1awQXKu.js +36 -0
  7. package/dist/accounts-DHkGVGUR.js +36 -0
  8. package/dist/accounts-P7cmIXUM.js +206 -0
  9. package/dist/accounts-XFgBY644.js +47 -0
  10. package/dist/accounts-_ZuNC5bz.js +47 -0
  11. package/dist/ack-reactions-BGJ9Vigf.js +621 -0
  12. package/dist/ack-reactions-Diu9O24z.js +621 -0
  13. package/dist/acp-cli-BwZ-va2P.js +1316 -0
  14. package/dist/acp-cli-eVKByz-j.js +1311 -0
  15. package/dist/active-listener--jrUO-8L.js +37 -0
  16. package/dist/active-listener-C7SyMcNY.js +37 -0
  17. package/dist/agent-BAxK2KQW.js +688 -0
  18. package/dist/agent-Dd5Yfhmq.js +687 -0
  19. package/dist/agent-helpers-5F0tdxud.js +400 -0
  20. package/dist/agent-helpers-Bs2nBXeI.js +400 -0
  21. package/dist/agent-scope-BA1HP4K6.js +114 -0
  22. package/dist/agent-scope-CAQLm3LP.js +116 -0
  23. package/dist/agents-D--9DD91.js +754 -0
  24. package/dist/agents.config-CmyzLYqW.js +116 -0
  25. package/dist/agents.config-DerBqRzk.js +116 -0
  26. package/dist/ansi-DtaiOnt1.js +107 -0
  27. package/dist/audio-ClIuKwkl.js +43 -0
  28. package/dist/audio-DqlIYYTb.js +43 -0
  29. package/dist/audit-Cn0cNCE4.js +3114 -0
  30. package/dist/audit-DXY4NHBC.js +3114 -0
  31. package/dist/auth-B-QK8JhI.js +315 -0
  32. package/dist/auth-C1zx1O24.js +314 -0
  33. package/dist/auth-DDmNYVMW.js +448 -0
  34. package/dist/auth-DH1wEw0w.js +448 -0
  35. package/dist/banner-CBWZhANO.js +294 -0
  36. package/dist/binaries-CYwLdubd.js +13 -0
  37. package/dist/bindings-DFAFatwT.js +69 -0
  38. package/dist/bindings-GUKIzFCp.js +69 -0
  39. package/dist/bonjour-discovery-AQMJqY4V.js +378 -0
  40. package/dist/bonjour-discovery-BLcPWHFJ.js +378 -0
  41. package/dist/boot/handler.js +41 -84
  42. package/dist/browser-cli-8Dv5ogFT.js +1690 -0
  43. package/dist/browser-cli-wNLo8SOy.js +1694 -0
  44. package/dist/build-info.json +3 -3
  45. package/dist/call-BTHzKFbN.js +518 -0
  46. package/dist/call-D_NchaCs.js +517 -0
  47. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  48. package/dist/catalog-DgpN5jxU.js +186 -0
  49. package/dist/catalog-k056Nh93.js +186 -0
  50. package/dist/channel-account-context-BHIy71Yh.js +133 -0
  51. package/dist/channel-account-context-DXU_-EkJ.js +133 -0
  52. package/dist/channel-activity-BatlvP_U.js +292 -0
  53. package/dist/channel-activity-BhT7NQ_v.js +94 -0
  54. package/dist/channel-activity-CvjEwpJz.js +94 -0
  55. package/dist/channel-options-BCccA2WC.js +32 -0
  56. package/dist/channel-options-VPR_pNyS.js +33 -0
  57. package/dist/channel-selection-AH6_y6RS.js +51 -0
  58. package/dist/channel-selection-ovohyJQZ.js +51 -0
  59. package/dist/channel-web-APDaQ_wp.js +2134 -0
  60. package/dist/channel-web-BW_YuNlT.js +2132 -0
  61. package/dist/channels-cli-DVsZyaU5.js +1436 -0
  62. package/dist/channels-cli-ubrg5vcL.js +1440 -0
  63. package/dist/channels-status-issues-BbYNzwLp.js +18 -0
  64. package/dist/channels-status-issues-DRybAijg.js +18 -0
  65. package/dist/chat-envelope-AJFUAuBM.js +248 -0
  66. package/dist/chat-envelope-BrfcPlDM.js +248 -0
  67. package/dist/chrome-Bv2UtAMQ.js +1732 -0
  68. package/dist/chrome-C6Vc_7su.js +1733 -0
  69. package/dist/chunk-BAMyFYtF.js +341 -0
  70. package/dist/chunk-BzVoFUZL.js +341 -0
  71. package/dist/clack-prompter-C6mBTOzE.js +122 -0
  72. package/dist/clack-prompter-DKcYqv3o.js +121 -0
  73. package/dist/cleanup-utils-Cb-leJcy.js +94 -0
  74. package/dist/cli/daemon-cli.js +1 -1
  75. package/dist/cli-Cs1n6-eD.js +135 -0
  76. package/dist/cli-Di3p1tLN.js +131 -0
  77. package/dist/client-B6h7bgbF.js +2311 -0
  78. package/dist/client-CMtdm9Ii.js +2311 -0
  79. package/dist/clipboard-A06eV_5C.js +31 -0
  80. package/dist/clipboard-DQBl3coj.js +31 -0
  81. package/dist/command-format-BiiNHkWG.js +18 -0
  82. package/dist/command-format-Dntg_tnC.js +32 -0
  83. package/dist/command-logger/handler.js +1 -1
  84. package/dist/command-registry-CCAvdWh2.js +215 -0
  85. package/dist/commands-D93TXYhv.js +41 -0
  86. package/dist/commands-UD7V7QC9.js +41 -0
  87. package/dist/commands-registry-CCbTtSSK.js +891 -0
  88. package/dist/commands-registry-De8JhZLG.js +890 -0
  89. package/dist/common-D4fL3S2m.js +156 -0
  90. package/dist/common-DXNisGxw.js +156 -0
  91. package/dist/completion-cli-CLo-r-UP.js +452 -0
  92. package/dist/completion-cli-D4ajG3yt.js +452 -0
  93. package/dist/config-BTH7fB_v.js +3345 -0
  94. package/dist/config-DwuBnd6D.js +3347 -0
  95. package/dist/config-cli-D0D1LSNt.js +243 -0
  96. package/dist/config-cli-tWsFNKQM.js +247 -0
  97. package/dist/config-guard-BcT7soTj.js +92 -0
  98. package/dist/config-guard-Bqak3bDc.js +75 -0
  99. package/dist/config-validation-CHEjSJ5K.js +18 -0
  100. package/dist/config-validation-CvgqLhyG.js +18 -0
  101. package/dist/configure-CK_0tFJG.js +889 -0
  102. package/dist/configure-D0z0kE-B.js +891 -0
  103. package/dist/constants-BBVTjb1j.js +75 -0
  104. package/dist/constants-PMRtHBHU.js +75 -0
  105. package/dist/control-auth-DrGYtMJM.js +397 -0
  106. package/dist/control-auth-KY4Qdr2I.js +397 -0
  107. package/dist/control-ui/assets/index-DdiU_ccM.css +1 -0
  108. package/dist/control-ui/assets/index-kVUYi64u.js +7723 -0
  109. package/dist/control-ui/assets/index-kVUYi64u.js.map +1 -0
  110. package/dist/control-ui/index.html +2 -2
  111. package/dist/control-ui-assets-DO1L6M0S.js +186 -0
  112. package/dist/control-ui-assets-S_TLo6Fs.js +186 -0
  113. package/dist/conversation-label-CDH4rKMG.js +36 -0
  114. package/dist/conversation-label-CMOfgCVl.js +36 -0
  115. package/dist/cron-cli-C7h_hLHu.js +495 -0
  116. package/dist/cron-cli-DTNg0Uvl.js +499 -0
  117. package/dist/daemon-cli-BlJS9zWM.js +737 -0
  118. package/dist/daemon-cli-Cfc1yszp.js +735 -0
  119. package/dist/daemon-cli.js +174 -1167
  120. package/dist/daemon-install-BbBLuLWg.js +60 -0
  121. package/dist/daemon-install-WEBvqVOj.js +56 -0
  122. package/dist/daemon-install-helpers-BVtPC2TK.js +504 -0
  123. package/dist/daemon-install-helpers-DVr51zvE.js +504 -0
  124. package/dist/deliver-EB272zWh.js +481 -0
  125. package/dist/deliver-iGD_woru.js +481 -0
  126. package/dist/delivery-queue-BDvalA10.js +244 -0
  127. package/dist/delivery-queue-BimvYz5E.js +244 -0
  128. package/dist/devices-cli-BXCOsNFc.js +323 -0
  129. package/dist/devices-cli-CHGdYfrz.js +319 -0
  130. package/dist/diagnostics-BzzhTQzK.js +35 -0
  131. package/dist/diagnostics-DILtxtcE.js +35 -0
  132. package/dist/directory-cli-COS40yI9.js +221 -0
  133. package/dist/directory-cli-Cb5j1JTC.js +225 -0
  134. package/dist/dispatcher-BUqxh_mA.js +174 -0
  135. package/dist/dispatcher-By-KZRWZ.js +173 -0
  136. package/dist/dm-policy-shared-BCp9_z3w.js +22 -0
  137. package/dist/dm-policy-shared-DgeKqjOu.js +22 -0
  138. package/dist/dns-cli-B8yyXB2N.js +203 -0
  139. package/dist/dns-cli-DAkTk-gM.js +199 -0
  140. package/dist/dock-B0bIIDS3.js +906 -0
  141. package/dist/dock-C3PzQ6CS.js +907 -0
  142. package/dist/doctor-completion-BXGEqLhU.js +92 -0
  143. package/dist/doctor-completion-D_mNzioP.js +92 -0
  144. package/dist/doctor-config-flow-BDDsR2J1.js +978 -0
  145. package/dist/doctor-config-flow-CwFFRUic.js +979 -0
  146. package/dist/enable-C3I9dWel.js +59 -0
  147. package/dist/enable-DnwKeWnR.js +59 -0
  148. package/dist/entry.js +75 -21
  149. package/dist/env-DyyqmxSM.js +60 -0
  150. package/dist/env-vars-CD2_baIP.js +43 -0
  151. package/dist/env-vars-a7S70ba7.js +43 -0
  152. package/dist/errors-0dfGxeYQ.js +35 -0
  153. package/dist/errors-C1kDByVU.js +35 -0
  154. package/dist/exec-CAk1dxq_.js +164 -0
  155. package/dist/exec-epNpA1aU.js +164 -0
  156. package/dist/export-html/template.css +0 -36
  157. package/dist/export-html/template.js +1 -32
  158. package/dist/extensionAPI.js +1765 -1590
  159. package/dist/fetch-BMQq41sB.js +281 -0
  160. package/dist/fetch-Cky99wYB.js +281 -0
  161. package/dist/fetch-D3tw4B4n.js +67 -0
  162. package/dist/fetch-DTsU2XnC.js +67 -0
  163. package/dist/fetch-Dgm9ZHFm.js +67 -0
  164. package/dist/file-lock-DWH0TfVu.js +107 -0
  165. package/dist/file-lock-DXW9h9ek.js +107 -0
  166. package/dist/fs-safe-BjSd07M4.js +115 -0
  167. package/dist/fs-safe-aWIhCWlb.js +125 -0
  168. package/dist/gateway-cli-C4y4H61g.js +24546 -0
  169. package/dist/gateway-cli-CtFr42NV.js +24550 -0
  170. package/dist/gateway-rpc-B92CH0D3.js +28 -0
  171. package/dist/gateway-rpc-DZNlWapO.js +28 -0
  172. package/dist/gmail-setup-utils-CKyh29_R.js +422 -0
  173. package/dist/gmail-setup-utils-DquflkMR.js +423 -0
  174. package/dist/health-BYl7T-4m.js +1417 -0
  175. package/dist/health-DdviISKg.js +1414 -0
  176. package/dist/health-format-BE5TK5bs.js +28 -0
  177. package/dist/heartbeat-visibility-BO3iRpB6.js +125 -0
  178. package/dist/heartbeat-visibility-Cwp4TrTv.js +125 -0
  179. package/dist/help-format-D3JhWp1E.js +17 -0
  180. package/dist/helpers-DAEoFkbn.js +10 -0
  181. package/dist/helpers-ndPQWl6m.js +10 -0
  182. package/dist/hook-runner-global-C1thol1d.js +527 -0
  183. package/dist/hooks-cli-BKS9uZ0H.js +1221 -0
  184. package/dist/hooks-cli-FLWcCr9q.js +1217 -0
  185. package/dist/host-env-security-BGibnCbS.js +106 -0
  186. package/dist/host-env-security-axRnIi8d.js +106 -0
  187. package/dist/image-ops-CX41n0v5.js +354 -0
  188. package/dist/image-ops-DSL3eFfQ.js +354 -0
  189. package/dist/import-BSFgt760.js +604 -0
  190. package/dist/import-Da1CHJJg.js +606 -0
  191. package/dist/inbound-context-BLy-G2Eq.js +68 -0
  192. package/dist/inbound-context-a5bzQvRt.js +68 -0
  193. package/dist/index.js +137 -108
  194. package/dist/inspect-BEpFbi0c.js +286 -0
  195. package/dist/inspect-BeNNpWna.js +286 -0
  196. package/dist/installs-CH7Qq_m_.js +319 -0
  197. package/dist/installs-CcM8H2YA.js +319 -0
  198. package/dist/ipv4-DNo9AFDu.js +46 -0
  199. package/dist/ipv4-VfoVR5uR.js +46 -0
  200. package/dist/ir-BPwP8hIc.js +972 -0
  201. package/dist/json-files-BI20PLIm.js +46 -0
  202. package/dist/lifecycle-core-5Zxqwa6V.js +476 -0
  203. package/dist/lifecycle-core-C1bGeLby.js +474 -0
  204. package/dist/links-CtGBIrG8.js +15 -0
  205. package/dist/loader-BoP3JA-r.js +22411 -0
  206. package/dist/loader-DXbpue-L.js +22414 -0
  207. package/dist/logger-ASsO5Nz-.js +49 -0
  208. package/dist/logging-Cd9y2AdQ.js +20 -0
  209. package/dist/logging-DRwtiLIS.js +1 -0
  210. package/dist/logging-fywhKCmE.js +1 -0
  211. package/dist/login-B2UXzgaB.js +61 -0
  212. package/dist/login-BEFL3xY9.js +62 -0
  213. package/dist/login-qr-C7wAz2fe.js +329 -0
  214. package/dist/login-qr-DWpUP1Ud.js +325 -0
  215. package/dist/logs-cli-CAcd-pXA.js +240 -0
  216. package/dist/logs-cli-D7Bzarht.js +236 -0
  217. package/dist/markdown-tables-BBNUZp4n.js +29 -0
  218. package/dist/markdown-tables-NgPcfXoF.js +29 -0
  219. package/dist/media-4-qOIjO-.js +971 -0
  220. package/dist/media-DTwJhAbE.js +9481 -0
  221. package/dist/message-action-names-BsNTjuBE.js +2520 -0
  222. package/dist/message-action-names-ocKcq8_3.js +2520 -0
  223. package/dist/message-channel-CtcVHawF.js +91 -0
  224. package/dist/message-channel-tuc9CdEw.js +91 -0
  225. package/dist/mime-CAqaK3kp.js +146 -0
  226. package/dist/mime-ViuhRuMM.js +146 -0
  227. package/dist/net-DSkFMHJ8.js +225 -0
  228. package/dist/net-DTqfFYzt.js +225 -0
  229. package/dist/node-cli-BeXU67eQ.js +1458 -0
  230. package/dist/node-cli-i2aCtnmM.js +1462 -0
  231. package/dist/node-service-RyMlWp8N.js +67 -0
  232. package/dist/node-service-TL9b6Qfz.js +67 -0
  233. package/dist/nodes-cli-CtqnXBMD.js +1346 -0
  234. package/dist/nodes-cli-DgQU3LrG.js +1350 -0
  235. package/dist/nodes-screen-B7HJugJ0.js +250 -0
  236. package/dist/nodes-screen-nCRd71Mk.js +250 -0
  237. package/dist/note-B6142LyJ.js +92 -0
  238. package/dist/note-D-EI0czq.js +92 -0
  239. package/dist/npm-registry-spec-PPyRXSpx.js +786 -0
  240. package/dist/npm-registry-spec-uUmDWe6v.js +786 -0
  241. package/dist/npm-resolution-BC1LqCm2.js +86 -0
  242. package/dist/npm-resolution-DhlhUmRF.js +86 -0
  243. package/dist/onboard-CGpC2ecw.js +647 -0
  244. package/dist/onboard-auth-cNtb3FTP.js +211 -0
  245. package/dist/onboard-auth-gwz-0mZ6.js +207 -0
  246. package/dist/onboard-channels-CXjJYzHC.js +2548 -0
  247. package/dist/onboard-channels-vtaIxYml.js +2549 -0
  248. package/dist/onboard-config-DOmXYEvJ.js +39 -0
  249. package/dist/onboard-config-JmR21VYa.js +39 -0
  250. package/dist/onboard-helpers-8afRV_Tm.js +364 -0
  251. package/dist/onboard-helpers-DTRrJLj-.js +363 -0
  252. package/dist/onboard-jLzfwoPx.js +649 -0
  253. package/dist/onboard-remote-CFkvVAYg.js +127 -0
  254. package/dist/onboard-remote-JfBnmK70.js +127 -0
  255. package/dist/onboarding-Dt0LKvZn.js +586 -0
  256. package/dist/onboarding-gMKlA2bP.js +588 -0
  257. package/dist/onboarding.finalize-BDML6Jx7.js +403 -0
  258. package/dist/onboarding.finalize-D850VgMA.js +405 -0
  259. package/dist/onboarding.gateway-config-DolBTXWT.js +196 -0
  260. package/dist/onboarding.gateway-config-rJkIamlG.js +202 -0
  261. package/dist/outbound-CPMaDtgC.js +220 -0
  262. package/dist/outbound-CYSuCMiW.js +221 -0
  263. package/dist/outbound-attachment-Ci02LXoq.js +18 -0
  264. package/dist/outbound-attachment-CqZ7Qc_o.js +18 -0
  265. package/dist/outbound-attachment-CuqWdsdV.js +18 -0
  266. package/dist/pairing-cli-B9JKvvST.js +126 -0
  267. package/dist/pairing-cli-C4HrfIHe.js +130 -0
  268. package/dist/pairing-labels-CBmGQ31P.js +9 -0
  269. package/dist/pairing-labels-D0xwC7Xb.js +9 -0
  270. package/dist/pairing-store-BoF0g-iN.js +459 -0
  271. package/dist/pairing-store-CseXj-5p.js +460 -0
  272. package/dist/path-env-CPZbb7me.js +89 -0
  273. package/dist/path-env-GTM4HXCN.js +89 -0
  274. package/dist/path-safety-BFE0XmGC.js +14 -0
  275. package/dist/path-safety-BJ8ge6Ho.js +14 -0
  276. package/dist/paths-DHuXVC00.js +229 -0
  277. package/dist/plugin-auto-enable-B_9J1XED.js +302 -0
  278. package/dist/plugin-auto-enable-DghjlFCL.js +301 -0
  279. package/dist/plugin-registry-68h2T8vi.js +33 -0
  280. package/dist/plugin-registry-BitdVPb4.js +33 -0
  281. package/dist/plugin-sdk/agents/agent-helpers.d.ts +0 -1
  282. package/dist/plugin-sdk/agents/agent-scope.d.ts +11 -0
  283. package/dist/plugin-sdk/agents/agent-types.d.ts +1 -6
  284. package/dist/plugin-sdk/agents/agent-utils.d.ts +0 -14
  285. package/dist/plugin-sdk/agents/provider-utils.d.ts +0 -1
  286. package/dist/plugin-sdk/agents/subagent-registry.store.d.ts +0 -1
  287. package/dist/plugin-sdk/agents/subagent-spawn.d.ts +0 -1
  288. package/dist/plugin-sdk/agents/tools/sessions-helpers.d.ts +0 -1
  289. package/dist/plugin-sdk/auth/constants.d.ts +15 -0
  290. package/dist/plugin-sdk/auth/display.d.ts +7 -0
  291. package/dist/plugin-sdk/auth/doctor.d.ts +8 -0
  292. package/dist/plugin-sdk/auth/env-injection.d.ts +38 -0
  293. package/dist/plugin-sdk/auth/index.d.ts +10 -0
  294. package/dist/plugin-sdk/auth/oauth.d.ts +13 -0
  295. package/dist/plugin-sdk/auth/order.d.ts +8 -0
  296. package/dist/plugin-sdk/auth/paths.d.ts +3 -0
  297. package/dist/plugin-sdk/auth/profiles.d.ts +11 -0
  298. package/dist/plugin-sdk/auth/provider-auth.d.ts +32 -0
  299. package/dist/plugin-sdk/auth/store.d.ts +7 -0
  300. package/dist/plugin-sdk/auth/types.d.ts +45 -0
  301. package/dist/plugin-sdk/auth/usage.d.ts +80 -0
  302. package/dist/plugin-sdk/auto-reply/reply/agent-runner-execution.d.ts +0 -1
  303. package/dist/plugin-sdk/auto-reply/reply/agent-runner-utils.d.ts +3 -36
  304. package/dist/plugin-sdk/auto-reply/reply/commands-status.d.ts +1 -7
  305. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/shared.d.ts +1 -1
  306. package/dist/plugin-sdk/auto-reply/reply/commands-types.d.ts +1 -13
  307. package/dist/plugin-sdk/auto-reply/reply/directive-handling.levels.d.ts +1 -10
  308. package/dist/plugin-sdk/auto-reply/reply/directive-handling.params.d.ts +1 -11
  309. package/dist/plugin-sdk/auto-reply/reply/directive-handling.parse.d.ts +1 -29
  310. package/dist/plugin-sdk/auto-reply/reply/directive-handling.persist.d.ts +0 -3
  311. package/dist/plugin-sdk/auto-reply/reply/directive-handling.shared.d.ts +0 -25
  312. package/dist/plugin-sdk/auto-reply/reply/directives.d.ts +3 -42
  313. package/dist/plugin-sdk/auto-reply/reply/get-reply-directives-apply.d.ts +0 -9
  314. package/dist/plugin-sdk/auto-reply/reply/get-reply-directives-utils.d.ts +0 -1
  315. package/dist/plugin-sdk/auto-reply/reply/get-reply-directives.d.ts +1 -20
  316. package/dist/plugin-sdk/auto-reply/reply/get-reply-inline-actions.d.ts +1 -12
  317. package/dist/plugin-sdk/auto-reply/reply/get-reply-run.d.ts +1 -15
  318. package/dist/plugin-sdk/auto-reply/reply/queue/types.d.ts +1 -17
  319. package/dist/plugin-sdk/auto-reply/reply/response-prefix-template.d.ts +4 -6
  320. package/dist/plugin-sdk/auto-reply/reply/session-run-accounting.d.ts +0 -7
  321. package/dist/plugin-sdk/auto-reply/reply/session-updates.d.ts +0 -10
  322. package/dist/plugin-sdk/auto-reply/reply.d.ts +1 -1
  323. package/dist/plugin-sdk/auto-reply/status.d.ts +3 -12
  324. package/dist/plugin-sdk/auto-reply/templating.d.ts +0 -4
  325. package/dist/plugin-sdk/auto-reply/thinking.d.ts +0 -15
  326. package/dist/plugin-sdk/auto-reply/types.d.ts +1 -2
  327. package/dist/plugin-sdk/channels/dock.d.ts +1 -2
  328. package/dist/plugin-sdk/channels/plugins/types.adapters.d.ts +0 -6
  329. package/dist/plugin-sdk/channels/plugins/types.core.d.ts +1 -0
  330. package/dist/plugin-sdk/channels/plugins/types.d.ts +1 -1
  331. package/dist/plugin-sdk/channels/plugins/types.plugin.d.ts +1 -2
  332. package/dist/plugin-sdk/channels/voice-credentials.d.ts +26 -0
  333. package/dist/plugin-sdk/commands/agent/session.d.ts +1 -2
  334. package/dist/plugin-sdk/commands/onboard-helpers.d.ts +0 -1
  335. package/dist/plugin-sdk/commands/onboard-types.d.ts +2 -1
  336. package/dist/plugin-sdk/config/defaults.d.ts +0 -1
  337. package/dist/plugin-sdk/config/legacy.migrations.d.ts +2 -1
  338. package/dist/plugin-sdk/config/legacy.shared.d.ts +0 -9
  339. package/dist/plugin-sdk/config/sessions/types.d.ts +0 -17
  340. package/dist/plugin-sdk/config/types.agent-defaults.d.ts +28 -120
  341. package/dist/plugin-sdk/config/types.agents.d.ts +8 -0
  342. package/dist/plugin-sdk/config/types.base.d.ts +0 -1
  343. package/dist/plugin-sdk/config/types.messages.d.ts +1 -6
  344. package/dist/plugin-sdk/config/types.remoteclaw.d.ts +2 -2
  345. package/dist/plugin-sdk/config/types.tools.d.ts +1 -74
  346. package/dist/plugin-sdk/config/types.tts.d.ts +2 -1
  347. package/dist/plugin-sdk/config/zod-schema.agent-defaults.d.ts +9 -70
  348. package/dist/plugin-sdk/config/zod-schema.agent-runtime.d.ts +12 -210
  349. package/dist/plugin-sdk/config/zod-schema.agents.d.ts +14 -86
  350. package/dist/plugin-sdk/config/zod-schema.core.d.ts +6 -234
  351. package/dist/plugin-sdk/config/zod-schema.d.ts +111 -378
  352. package/dist/plugin-sdk/config/zod-schema.providers-core.d.ts +148 -160
  353. package/dist/plugin-sdk/config/zod-schema.providers-whatsapp.d.ts +12 -12
  354. package/dist/plugin-sdk/config/zod-schema.providers.d.ts +88 -96
  355. package/dist/plugin-sdk/config/zod-schema.session.d.ts +4 -10
  356. package/dist/plugin-sdk/daemon/constants.d.ts +2 -2
  357. package/dist/plugin-sdk/gateway/protocol/index.d.ts +10 -17
  358. package/dist/plugin-sdk/gateway/protocol/schema/sessions.d.ts +0 -7
  359. package/dist/plugin-sdk/gateway/server/ws-types.d.ts +2 -0
  360. package/dist/plugin-sdk/gateway/session-utils.types.d.ts +0 -3
  361. package/dist/plugin-sdk/index.js +722 -1283
  362. package/dist/plugin-sdk/infra/agent-events.d.ts +1 -1
  363. package/dist/plugin-sdk/infra/provider-usage.auth.d.ts +0 -1
  364. package/dist/plugin-sdk/infra/provider-usage.load.d.ts +0 -1
  365. package/dist/plugin-sdk/line/config-schema.d.ts +4 -4
  366. package/dist/plugin-sdk/logging/levels.d.ts +1 -1
  367. package/dist/plugin-sdk/middleware/auth-key-retry.d.ts +31 -0
  368. package/dist/plugin-sdk/middleware/channel-bridge.d.ts +4 -0
  369. package/dist/plugin-sdk/middleware/cli-runtime-base.d.ts +6 -0
  370. package/dist/plugin-sdk/middleware/error-classifier.d.ts +5 -0
  371. package/dist/plugin-sdk/middleware/media-capability.d.ts +21 -0
  372. package/dist/plugin-sdk/middleware/media-resolver.d.ts +12 -0
  373. package/dist/plugin-sdk/middleware/runtime-factory.d.ts +42 -0
  374. package/dist/plugin-sdk/middleware/runtimes/claude.d.ts +10 -0
  375. package/dist/plugin-sdk/middleware/runtimes/codex.d.ts +5 -0
  376. package/dist/plugin-sdk/middleware/runtimes/gemini.d.ts +11 -0
  377. package/dist/plugin-sdk/middleware/runtimes/opencode.d.ts +5 -0
  378. package/dist/plugin-sdk/middleware/types.d.ts +41 -1
  379. package/dist/plugin-sdk/plugin-sdk/index.d.ts +5 -1
  380. package/dist/plugin-sdk/plugins/manifest-registry.d.ts +2 -0
  381. package/dist/plugin-sdk/plugins/manifest.d.ts +4 -4
  382. package/dist/plugin-sdk/plugins/registry.d.ts +18 -0
  383. package/dist/plugin-sdk/plugins/types.d.ts +5 -1
  384. package/dist/plugin-sdk/stt/defaults.d.ts +2 -0
  385. package/dist/plugin-sdk/stt/preflight.d.ts +14 -0
  386. package/dist/plugin-sdk/stt/providers/deepgram/index.d.ts +2 -0
  387. package/dist/plugin-sdk/stt/providers/google/index.d.ts +2 -0
  388. package/dist/plugin-sdk/stt/providers/groq/index.d.ts +2 -0
  389. package/dist/plugin-sdk/stt/providers/index.d.ts +4 -0
  390. package/dist/plugin-sdk/stt/providers/mistral/index.d.ts +2 -0
  391. package/dist/plugin-sdk/stt/providers/openai/index.d.ts +2 -0
  392. package/dist/plugin-sdk/stt/stt.d.ts +27 -0
  393. package/dist/plugin-sdk/stt/types.d.ts +22 -0
  394. package/dist/plugin-sdk/terminal/palette.d.ts +2 -2
  395. package/dist/plugin-sdk/tts/providers/edge.d.ts +2 -0
  396. package/dist/plugin-sdk/tts/providers/elevenlabs.d.ts +2 -0
  397. package/dist/plugin-sdk/tts/providers/index.d.ts +4 -0
  398. package/dist/plugin-sdk/tts/providers/openai.d.ts +2 -0
  399. package/dist/plugin-sdk/tts/tts.d.ts +13 -5
  400. package/dist/plugin-sdk/tts/types.d.ts +21 -0
  401. package/dist/plugins-BviLFPLV.js +255 -0
  402. package/dist/plugins-CaudBUbl.js +254 -0
  403. package/dist/plugins-cli-CsLhphNr.js +803 -0
  404. package/dist/plugins-cli-CujSP9NS.js +807 -0
  405. package/dist/ports-BtuzUQHl.js +370 -0
  406. package/dist/ports-CMcHia07.js +96 -0
  407. package/dist/ports-DALdfBQy.js +96 -0
  408. package/dist/ports-gRBeuUtp.js +316 -0
  409. package/dist/preflight-Bq8rimP-.js +667 -0
  410. package/dist/preflight-DyYbEp9X.js +667 -0
  411. package/dist/program-D64vUv0b.js +250 -0
  412. package/dist/program-context-CTFkimUr.js +474 -0
  413. package/dist/progress-BcwxtM9Q.js +124 -0
  414. package/dist/prompt-DtWGd43j.js +21 -0
  415. package/dist/prompt-select-styled-GW2PexAK.js +1672 -0
  416. package/dist/prompt-select-styled-JOuWGHX7.js +1669 -0
  417. package/dist/prompt-style-BpUMhEHC.js +9 -0
  418. package/dist/provider-auth-B7QgxlKt.js +187 -0
  419. package/dist/provider-auth-j-EQvvIk.js +187 -0
  420. package/dist/provider-dispatcher-Bx6CaIoV.js +660 -0
  421. package/dist/provider-dispatcher-DhkvjhO5.js +659 -0
  422. package/dist/push-apns--nEiZmEN.js +711 -0
  423. package/dist/push-apns-BtS6B6lb.js +713 -0
  424. package/dist/pw-ai-BpCsXF-x.js +1908 -0
  425. package/dist/pw-ai-ud_Kbn5S.js +1911 -0
  426. package/dist/qr-cli-BCeVLGfz.js +353 -0
  427. package/dist/qr-cli-Crsqtw01.js +349 -0
  428. package/dist/redact-Ci96Gj0O.js +191 -0
  429. package/dist/redact-snapshot-B9nof-Pb.js +1952 -0
  430. package/dist/redact-snapshot-BKiS91Mj.js +1952 -0
  431. package/dist/register.agent-CcvOeVnL.js +292 -0
  432. package/dist/register.agent-azH_tdVX.js +1014 -0
  433. package/dist/register.configure-DAaZLjHs.js +130 -0
  434. package/dist/register.configure-lUl8O79m.js +135 -0
  435. package/dist/register.import-B83Dn36B.js +29 -0
  436. package/dist/register.import-wIYU2cVW.js +31 -0
  437. package/dist/register.maintenance-Bo-ooQDU.js +501 -0
  438. package/dist/register.maintenance-BwZ4OkK2.js +503 -0
  439. package/dist/register.message-BQhRoEQQ.js +687 -0
  440. package/dist/register.message-CvZKWeGb.js +691 -0
  441. package/dist/register.onboard---3EPh-O.js +98 -0
  442. package/dist/register.onboard-rsHSJUvQ.js +94 -0
  443. package/dist/register.setup-B0gc_lne.js +118 -0
  444. package/dist/register.setup-MWpb7jxL.js +114 -0
  445. package/dist/register.status-health-sessions-BZJ0wTSa.js +429 -0
  446. package/dist/register.status-health-sessions-CyrUwwtB.js +667 -0
  447. package/dist/register.subclis-i2d2ugaJ.js +267 -0
  448. package/dist/replies-BIx-MbQ7.js +136 -0
  449. package/dist/replies-DVU655H4.js +136 -0
  450. package/dist/reply-CL5VMSKN.js +12372 -0
  451. package/dist/reply-XKyfU3rS.js +12375 -0
  452. package/dist/reply-directives-DQfJ001O.js +182 -0
  453. package/dist/reply-directives-DfUITt7C.js +182 -0
  454. package/dist/reply-payloads-ZHo6kfTS.js +527 -0
  455. package/dist/reply-prefix-BSf3PC0x.js +37 -0
  456. package/dist/reply-prefix-DBTlMHLK.js +37 -0
  457. package/dist/resolve-route-B-_IgETc.js +249 -0
  458. package/dist/resolve-route-C8ZsgWDQ.js +249 -0
  459. package/dist/response-prefix-template-3LeqJx2X.js +134 -0
  460. package/dist/response-prefix-template-DBrUVx5V.js +134 -0
  461. package/dist/retry-CDrH81GP.js +77 -0
  462. package/dist/retry-Dar_7pCv.js +77 -0
  463. package/dist/run-main-rOudcbbs.js +308 -0
  464. package/dist/runtime-guard-CK80eucm.js +60 -0
  465. package/dist/runtime-status-CR9445g5.js +12 -0
  466. package/dist/runtime-status-hFVEC3wO.js +12 -0
  467. package/dist/secure-random-CLWSvf8A.js +44 -0
  468. package/dist/security-cli-B8lXw9ke.js +488 -0
  469. package/dist/security-cli-CRkS3VAf.js +483 -0
  470. package/dist/send-6g8QKfWj.js +374 -0
  471. package/dist/send-B5Hz1PIn.js +29 -0
  472. package/dist/send-B8eIlA1u.js +349 -0
  473. package/dist/send-BFZPQE4j.js +492 -0
  474. package/dist/send-BpTDvE0D.js +1779 -0
  475. package/dist/send-BxOrO1Wv.js +1776 -0
  476. package/dist/send-C6gPJu-Z.js +11 -0
  477. package/dist/send-C7MoKtkN.js +426 -0
  478. package/dist/send-CXzq2LI6.js +2245 -0
  479. package/dist/send-CYOZoObr.js +547 -0
  480. package/dist/send-CfQyIvcC.js +332 -0
  481. package/dist/send-DUtuuwhw.js +492 -0
  482. package/dist/send-DbafVwxp.js +2245 -0
  483. package/dist/send-DeZg8K7y.js +349 -0
  484. package/dist/send-DwkjxJlv.js +547 -0
  485. package/dist/send-iX9xbxlU.js +1178 -0
  486. package/dist/server-BKfCzEzd.js +206 -0
  487. package/dist/server-fmO4eo7K.js +202 -0
  488. package/dist/server-lifecycle-CgPpP10P.js +2437 -0
  489. package/dist/server-lifecycle-Cn8yY5MW.js +2437 -0
  490. package/dist/server-node-events-C-ZzSBYh.js +391 -0
  491. package/dist/server-node-events-DYlyfDHM.js +395 -0
  492. package/dist/service-C2j81L86.js +670 -0
  493. package/dist/service-C8a0SXHD.js +670 -0
  494. package/dist/session-AulYhqOb.js +170 -0
  495. package/dist/session-C6VKWvx6.js +170 -0
  496. package/dist/session-cost-usage-0Vs4hgMe.js +627 -0
  497. package/dist/session-cost-usage-C-DsaOfN.js +627 -0
  498. package/dist/session-dirs-CO1f2ArM.js +318 -0
  499. package/dist/session-dirs-DoboH7Oy.js +318 -0
  500. package/dist/session-utils-CRK8ToKG.js +621 -0
  501. package/dist/session-utils-DWlkmCX8.js +621 -0
  502. package/dist/sessions-DtqrmUJS.js +2553 -0
  503. package/dist/sessions-gT-4fcX-.js +245 -0
  504. package/dist/shell-env-DBS5su07.js +163 -0
  505. package/dist/shell-env-c3j5zcU9.js +163 -0
  506. package/dist/ssrf-8wNqPNzN.js +183 -0
  507. package/dist/ssrf-CJIdPXuS.js +183 -0
  508. package/dist/status-BI_-xpDt.js +1947 -0
  509. package/dist/status-PZVwjKjl.js +1943 -0
  510. package/dist/status.update-BmuDZ7E7.js +449 -0
  511. package/dist/status.update-Mf6HSRvU.js +449 -0
  512. package/dist/store-B7PGEdFf.js +2555 -0
  513. package/dist/store-CzhBjUCN.js +64 -0
  514. package/dist/store-YkSxKAey.js +53 -0
  515. package/dist/store-ZNeFv2Q7.js +64 -0
  516. package/dist/subagent-registry-R1DiAM4R.js +4839 -0
  517. package/dist/subagent-registry-xLRXC8Bg.js +4841 -0
  518. package/dist/subsystem-BAW_f3DI.js +1195 -0
  519. package/dist/subsystem-DGSHVL8I.js +1081 -0
  520. package/dist/system-cli-9SvRrT9D.js +77 -0
  521. package/dist/system-cli-yCa5Q1YM.js +73 -0
  522. package/dist/systemd-40Rij3QR.js +547 -0
  523. package/dist/systemd-5C97CSzd.js +547 -0
  524. package/dist/systemd-hints-3iQteJw-.js +278 -0
  525. package/dist/systemd-hints-CyQqHq1i.js +278 -0
  526. package/dist/systemd-linger-B2rPbnAi.js +75 -0
  527. package/dist/systemd-linger-DDvkfxH-.js +75 -0
  528. package/dist/table-DFx25vNb.js +279 -0
  529. package/dist/tables-C5fI0PmT.js +55 -0
  530. package/dist/tables-Cm9qvQ9D.js +55 -0
  531. package/dist/tables-fRe01eP1.js +55 -0
  532. package/dist/tailnet-Da-_9e8E.js +40 -0
  533. package/dist/tailnet-xt92Yaop.js +40 -0
  534. package/dist/tailscale-CnV0JWca.js +230 -0
  535. package/dist/tailscale-VkEC8dzj.js +230 -0
  536. package/dist/targets-C99szk_e.js +114 -0
  537. package/dist/targets-CPaTjbpp.js +2607 -0
  538. package/dist/targets-D-p4rJVS.js +650 -0
  539. package/dist/targets-D2OQt8-7.js +650 -0
  540. package/dist/targets-D94MtTiZ.js +2606 -0
  541. package/dist/targets-RajrXTl7.js +220 -0
  542. package/dist/targets-_UWmnyI9.js +53 -0
  543. package/dist/targets-tDrl_ioQ.js +46 -0
  544. package/dist/thinking-4nOZPunr.js +60 -0
  545. package/dist/thinking-ZfH2V9Os.js +60 -0
  546. package/dist/tokens-TtJJxzRr.js +21 -0
  547. package/dist/tool-display-Bxs_1jIn.js +785 -0
  548. package/dist/tool-display-D9p_Ttkq.js +785 -0
  549. package/dist/tool-images-9Ron321Q.js +263 -0
  550. package/dist/tool-images-BWhy6WRN.js +263 -0
  551. package/dist/trash-B5xyvBDf.js +125 -0
  552. package/dist/trash-BpB96kHe.js +125 -0
  553. package/dist/tui-Ba0uZDrg.js +3237 -0
  554. package/dist/tui-Biz0HqDj.js +3237 -0
  555. package/dist/tui-cli-C-UV6o2v.js +63 -0
  556. package/dist/tui-cli-Ds_bLT-h.js +67 -0
  557. package/dist/types.tools-BBb2rl3g.js +23 -0
  558. package/dist/types.tools-BDJw1yFx.js +23 -0
  559. package/dist/update-Barj5dsg.js +349 -0
  560. package/dist/update-D839Q8su.js +349 -0
  561. package/dist/update-cli-C0LnrpIt.js +1148 -0
  562. package/dist/update-cli-CUypa-T-.js +1150 -0
  563. package/dist/usage-BI9kergH.js +5465 -0
  564. package/dist/utils-DPoNpP7D.js +631 -0
  565. package/dist/version-3QUZW8EP.js +52 -0
  566. package/dist/version-CVMnqdzu.js +52 -0
  567. package/dist/voice-credentials-64XAMSJm.js +46 -0
  568. package/dist/voice-credentials-v-CQkTpD.js +46 -0
  569. package/dist/web-63IbbidQ.js +3051 -0
  570. package/dist/web-D9N764Da.js +80 -0
  571. package/dist/web-DUvNYLzr.js +75 -0
  572. package/dist/webhooks-cli-owhVNNkz.js +334 -0
  573. package/dist/webhooks-cli-zlvka6QD.js +330 -0
  574. package/dist/whatsapp-actions-8DejyRG5.js +126 -0
  575. package/dist/whatsapp-actions-DCzp5LKe.js +131 -0
  576. package/dist/widearea-dns-CQqZIeu8.js +127 -0
  577. package/dist/workspace-CB7pVojf.js +441 -0
  578. package/dist/workspace-DWEyzM0F.js +439 -0
  579. package/dist/zod-schema-CvFqwpNE.js +2719 -0
  580. package/dist/zod-schema-Y5SQgJLm.js +2719 -0
  581. package/extensions/matrix/src/matrix/monitor/replies.ts +0 -24
  582. package/extensions/mattermost/src/mattermost/monitor-helpers.ts +0 -1
  583. package/extensions/voice-call/index.ts +18 -1
  584. package/package.json +3 -4
  585. package/dist/accounts-7fm_KzPm.js +0 -32
  586. package/dist/accounts-BFy_Z3od.js +0 -272
  587. package/dist/accounts-BTXSfPWi.js +0 -270
  588. package/dist/accounts-BxGS70Do.js +0 -36
  589. package/dist/accounts-CNY1TGj1.js +0 -47
  590. package/dist/accounts-DqRQ75w3.js +0 -36
  591. package/dist/accounts-iODF3SK2.js +0 -47
  592. package/dist/ack-reactions-C1hk85VE.js +0 -446
  593. package/dist/ack-reactions-DRC2CiDQ.js +0 -446
  594. package/dist/acp-cli-DD-PD4NM.js +0 -1326
  595. package/dist/acp-cli-DIyRCOum.js +0 -1320
  596. package/dist/active-listener-VzhWW8W6.js +0 -37
  597. package/dist/active-listener-z0qVEcom.js +0 -37
  598. package/dist/agent-D2HeDFFR.js +0 -731
  599. package/dist/agent-Da_eZ5BP.js +0 -732
  600. package/dist/agent-helpers-B6VfZ9_u.js +0 -606
  601. package/dist/agent-helpers-CTx5KKJu.js +0 -606
  602. package/dist/agent-scope-BqPmD-Ax.js +0 -114
  603. package/dist/agent-scope-DgQzamQB.js +0 -116
  604. package/dist/agents-TB3QpHoo.js +0 -788
  605. package/dist/agents.config-BsAQTYe1.js +0 -116
  606. package/dist/agents.config-C9fyYfAh.js +0 -116
  607. package/dist/ansi-D04X81yq.js +0 -14
  608. package/dist/audio-DPOuhNq7.js +0 -43
  609. package/dist/audio-VBcVDa08.js +0 -43
  610. package/dist/audio-preflight-CK3EA3Dv.js +0 -69
  611. package/dist/audio-preflight-tdXtrutj.js +0 -64
  612. package/dist/audit-CJipUWDi.js +0 -3138
  613. package/dist/audit-COWzB9Y1.js +0 -3138
  614. package/dist/auth-CAczFgAO.js +0 -448
  615. package/dist/auth-Deh9i9Eg.js +0 -448
  616. package/dist/auth-profiles-BquJGKLC.js +0 -279
  617. package/dist/auth-profiles-D8vKiBPq.js +0 -281
  618. package/dist/banner-CUWBOR42.js +0 -294
  619. package/dist/binaries-DXW6oATV.js +0 -13
  620. package/dist/bindings-8YtSWb91.js +0 -69
  621. package/dist/bindings-l1R5LQQH.js +0 -69
  622. package/dist/bonjour-discovery-DdAk1VyO.js +0 -378
  623. package/dist/bonjour-discovery-DuhiIZZx.js +0 -378
  624. package/dist/browser-cli-5Q9lhGdd.js +0 -1687
  625. package/dist/browser-cli-D2qMeSx1.js +0 -1692
  626. package/dist/call-CZHVeMf1.js +0 -2828
  627. package/dist/call-CoMjY7ah.js +0 -2829
  628. package/dist/catalog-CYiAleBT.js +0 -185
  629. package/dist/catalog-pjPqB2hC.js +0 -185
  630. package/dist/channel-account-context-CvIDAtHS.js +0 -550
  631. package/dist/channel-account-context-q-o0pG1A.js +0 -550
  632. package/dist/channel-activity-BaCNOZpP.js +0 -94
  633. package/dist/channel-activity-Cd1JhIUj.js +0 -292
  634. package/dist/channel-activity-DTKGf3j5.js +0 -94
  635. package/dist/channel-options-8SjIcDDI.js +0 -33
  636. package/dist/channel-options-BtQGtMF4.js +0 -32
  637. package/dist/channel-selection-C4DzrynU.js +0 -51
  638. package/dist/channel-selection-DdfhwFuY.js +0 -51
  639. package/dist/channel-web-BKJSXnwf.js +0 -2136
  640. package/dist/channel-web-BUzvNE_A.js +0 -2134
  641. package/dist/channels-cli-CCXY796Z.js +0 -1421
  642. package/dist/channels-cli-DTfx1zFC.js +0 -1426
  643. package/dist/channels-status-issues-DnmuqPsi.js +0 -18
  644. package/dist/channels-status-issues-p1pCvTh8.js +0 -18
  645. package/dist/chat-envelope-DEZ-5RY8.js +0 -248
  646. package/dist/chat-envelope-el7Uo-Fe.js +0 -248
  647. package/dist/chrome-Dd4dv0Vh.js +0 -1732
  648. package/dist/chrome-DdNEInwI.js +0 -1733
  649. package/dist/chunk-CSQfUhgF.js +0 -341
  650. package/dist/chunk-D0Y_w4oX.js +0 -341
  651. package/dist/clack-prompter-B7tOxhJd.js +0 -122
  652. package/dist/clack-prompter-CCFnKP_1.js +0 -121
  653. package/dist/cleanup-utils-CqAVZz2b.js +0 -94
  654. package/dist/cli-BRwDPW0r.js +0 -125
  655. package/dist/cli-CV86F7iv.js +0 -130
  656. package/dist/clipboard-D7_SKHPK.js +0 -31
  657. package/dist/clipboard-Dzkx6Q2K.js +0 -31
  658. package/dist/command-format-CVfo8I5f.js +0 -18
  659. package/dist/command-format-DgXcqxBt.js +0 -32
  660. package/dist/command-registry-BvLC28b4.js +0 -215
  661. package/dist/commands-B49Lu-pa.js +0 -41
  662. package/dist/commands-DI1BCqnj.js +0 -41
  663. package/dist/commands-registry-Cr6SIR3n.js +0 -892
  664. package/dist/commands-registry-agiTEGDz.js +0 -893
  665. package/dist/common-CMI-qsF8.js +0 -156
  666. package/dist/common-DSVmydhm.js +0 -156
  667. package/dist/completion-cli-C7O4JU8t.js +0 -452
  668. package/dist/completion-cli-CQNXtEJ7.js +0 -452
  669. package/dist/config-ChYRSJQt.js +0 -6953
  670. package/dist/config-CwtWvygh.js +0 -6951
  671. package/dist/config-cli-Df5nJcfO.js +0 -241
  672. package/dist/config-cli-Dqe5O1pl.js +0 -246
  673. package/dist/config-guard-C6hyuH-z.js +0 -75
  674. package/dist/config-guard-kNMQS_tm.js +0 -97
  675. package/dist/config-validation-BZBaBH69.js +0 -18
  676. package/dist/config-validation-DkrbzCyL.js +0 -18
  677. package/dist/configure-CoJmCHqT.js +0 -891
  678. package/dist/configure-DJbojDRf.js +0 -889
  679. package/dist/constants-BmRFoHl0.js +0 -67
  680. package/dist/constants-C9WPAluB.js +0 -67
  681. package/dist/control-auth-7k6Cb2zH.js +0 -397
  682. package/dist/control-auth-DBxfkJ3g.js +0 -397
  683. package/dist/control-ui/assets/index-B4ZM1lW1.js +0 -7738
  684. package/dist/control-ui/assets/index-B4ZM1lW1.js.map +0 -1
  685. package/dist/control-ui/assets/index-PED72sKF.css +0 -1
  686. package/dist/control-ui-assets-Cx_mw4D0.js +0 -186
  687. package/dist/control-ui-assets-W1AUuGrO.js +0 -186
  688. package/dist/conversation-label-C4SDz4sT.js +0 -36
  689. package/dist/conversation-label-D1frnvYe.js +0 -36
  690. package/dist/cron-cli-BJXQKtR3.js +0 -495
  691. package/dist/cron-cli-CTIj0WPW.js +0 -490
  692. package/dist/daemon-cli-CZbHvkRG.js +0 -1197
  693. package/dist/daemon-cli-Cf_YKWvV.js +0 -1199
  694. package/dist/daemon-install-CcohRvKV.js +0 -55
  695. package/dist/daemon-install-DDshfT0J.js +0 -60
  696. package/dist/daemon-install-helpers-CFGAfRlj.js +0 -462
  697. package/dist/daemon-install-helpers-DIUzSFG1.js +0 -462
  698. package/dist/defaults-B5KStIBg.js +0 -7
  699. package/dist/defaults-xUAL2Z-F.js +0 -7
  700. package/dist/deliver-BDf2lIEK.js +0 -481
  701. package/dist/deliver-DvmkSwLt.js +0 -481
  702. package/dist/delivery-queue-Cfa9Wmxp.js +0 -244
  703. package/dist/delivery-queue-CxVRi4tw.js +0 -244
  704. package/dist/devices-cli-CRsW5WOw.js +0 -316
  705. package/dist/devices-cli-Crzrk5uf.js +0 -321
  706. package/dist/diagnostics-99iCgBUh.js +0 -46
  707. package/dist/diagnostics-VC0cz7kX.js +0 -46
  708. package/dist/directory-cli-BnoQqeOX.js +0 -222
  709. package/dist/directory-cli-DdBAX3AV.js +0 -217
  710. package/dist/dm-policy-shared-DNqPbnip.js +0 -22
  711. package/dist/dm-policy-shared-vCb_hnqo.js +0 -22
  712. package/dist/dns-cli-D410XQr9.js +0 -197
  713. package/dist/dns-cli-Fgg96Xkg.js +0 -202
  714. package/dist/dock-DXSgTbDw.js +0 -928
  715. package/dist/dock-FtQwUHXE.js +0 -929
  716. package/dist/doctor-completion-BWmtCiFR.js +0 -92
  717. package/dist/doctor-completion-DTM_wDxy.js +0 -92
  718. package/dist/doctor-config-flow-Ccna5fPs.js +0 -1934
  719. package/dist/doctor-config-flow-DqzrK_jh.js +0 -1933
  720. package/dist/enable-DcJnkzfz.js +0 -59
  721. package/dist/enable-ibNq4UWy.js +0 -59
  722. package/dist/env-DeF64iu0.js +0 -60
  723. package/dist/env-vars-7aZqKPhk.js +0 -93
  724. package/dist/env-vars-CLGbxdpL.js +0 -93
  725. package/dist/errors-8F-77i6m.js +0 -35
  726. package/dist/errors-DZ199hOo.js +0 -35
  727. package/dist/exec-DbKuYyM1.js +0 -164
  728. package/dist/exec-DkFE7lqU.js +0 -164
  729. package/dist/fetch-C6XKGA11.js +0 -67
  730. package/dist/fetch-CEDsOiql.js +0 -67
  731. package/dist/fetch-ePscvwi1.js +0 -67
  732. package/dist/file-lock-CIvloidc.js +0 -107
  733. package/dist/file-lock-CzBL_VIx.js +0 -107
  734. package/dist/fs-safe-DSwT85uK.js +0 -88
  735. package/dist/fs-safe-DkBhNAc3.js +0 -98
  736. package/dist/gateway-cli-BJooqlkO.js +0 -23747
  737. package/dist/gateway-cli-C2wPjxY4.js +0 -23742
  738. package/dist/gateway-rpc-BcT4FqJQ.js +0 -28
  739. package/dist/gateway-rpc-DhKAJ5EW.js +0 -28
  740. package/dist/gmail-setup-utils-Cnx8A5pW.js +0 -422
  741. package/dist/gmail-setup-utils-nkabbKOE.js +0 -423
  742. package/dist/health-BZX-PyP0.js +0 -1420
  743. package/dist/health-BgD0koJx.js +0 -1423
  744. package/dist/health-format-BG95OE6N.js +0 -28
  745. package/dist/heartbeat-visibility-DeW9EIeS.js +0 -125
  746. package/dist/heartbeat-visibility-DvogUlnZ.js +0 -125
  747. package/dist/help-format-DAxf0l_h.js +0 -17
  748. package/dist/helpers-R7bU5IBz.js +0 -10
  749. package/dist/helpers-kkeXif0Q.js +0 -10
  750. package/dist/hook-runner-global-cyaKukZP.js +0 -527
  751. package/dist/hooks-cli-DTygpzqS.js +0 -1217
  752. package/dist/hooks-cli-Dg853OdZ.js +0 -1222
  753. package/dist/host-env-security-Bms2_EMV.js +0 -92
  754. package/dist/host-env-security-szwfmhC4.js +0 -92
  755. package/dist/image-ops-Bi6JPSkD.js +0 -354
  756. package/dist/image-ops-DWytvdh_.js +0 -354
  757. package/dist/import-D8BBZQgl.js +0 -170
  758. package/dist/import-DQ6NI4Fz.js +0 -168
  759. package/dist/inbound-context-CPkkQW0i.js +0 -68
  760. package/dist/inbound-context-DS_kpIYI.js +0 -68
  761. package/dist/inbound-path-policy-Bg4gZBx-.js +0 -250
  762. package/dist/inbound-path-policy-sdr5Ji0k.js +0 -250
  763. package/dist/inspect-Dt8hogS3.js +0 -559
  764. package/dist/inspect-vYIL1oA0.js +0 -559
  765. package/dist/installs-ClX3qQmh.js +0 -325
  766. package/dist/installs-CxjOiLUM.js +0 -325
  767. package/dist/ipv4--2WXMVtE.js +0 -46
  768. package/dist/ipv4-CDQpx1A7.js +0 -46
  769. package/dist/ir-BvKdMuSP.js +0 -940
  770. package/dist/json-files-DzpTak5i.js +0 -46
  771. package/dist/links-C3soDNDH.js +0 -15
  772. package/dist/loader-BWZ_iRxI.js +0 -22624
  773. package/dist/loader-ClFP7wvS.js +0 -22621
  774. package/dist/local-roots-B6rSCu4U.js +0 -314
  775. package/dist/local-roots-v2HlOaG5.js +0 -313
  776. package/dist/logger-Bw3cFE5t.js +0 -49
  777. package/dist/logging-C-nxX2fn.js +0 -20
  778. package/dist/login-Cmpeb59f.js +0 -62
  779. package/dist/login-D1CV2eNF.js +0 -61
  780. package/dist/login-qr-B3tpFLRV.js +0 -327
  781. package/dist/login-qr-CSQzrtFX.js +0 -322
  782. package/dist/logs-cli-BSiUZwb2.js +0 -238
  783. package/dist/logs-cli-DDtoJ1Fr.js +0 -233
  784. package/dist/markdown-tables-PJUMrC4T.js +0 -29
  785. package/dist/markdown-tables-dDWBbtqd.js +0 -29
  786. package/dist/media-Dqv7Q0aS.js +0 -10492
  787. package/dist/media-DtN0R9A0.js +0 -940
  788. package/dist/message-action-names-Bs50Ia1g.js +0 -2521
  789. package/dist/message-action-names-Btd7cMvx.js +0 -2521
  790. package/dist/message-channel-DzJqHVZD.js +0 -91
  791. package/dist/message-channel-uWMAiywE.js +0 -91
  792. package/dist/mime-BS3jhcZE.js +0 -149
  793. package/dist/mime-Cxh_64P6.js +0 -149
  794. package/dist/net-Cg8AQeke.js +0 -225
  795. package/dist/net-D6D0wgcF.js +0 -225
  796. package/dist/node-cli-Q2-n3Fgv.js +0 -24
  797. package/dist/node-cli-Uf6lAntf.js +0 -24
  798. package/dist/nodes-cli-DVLvMgBV.js +0 -1343
  799. package/dist/nodes-cli-Dxf7vAKk.js +0 -1348
  800. package/dist/nodes-screen-BR9sYoPa.js +0 -250
  801. package/dist/nodes-screen-Cw7Hv7M2.js +0 -250
  802. package/dist/note-Dlv4NmlQ.js +0 -92
  803. package/dist/note-kvWV4xtw.js +0 -92
  804. package/dist/npm-registry-spec-0qiKawvv.js +0 -786
  805. package/dist/npm-registry-spec-COvUzy5J.js +0 -786
  806. package/dist/npm-resolution-DJnq5QBs.js +0 -86
  807. package/dist/npm-resolution-DVl2spoD.js +0 -86
  808. package/dist/onboard-BcQWYGY3.js +0 -405
  809. package/dist/onboard-RQ_FAMyg.js +0 -407
  810. package/dist/onboard-channels-CHh_BuxJ.js +0 -2547
  811. package/dist/onboard-channels-DXD-CK_M.js +0 -2548
  812. package/dist/onboard-config-BCTthQ7J.js +0 -24
  813. package/dist/onboard-config-y-2cgT0V.js +0 -24
  814. package/dist/onboard-helpers-BRMP8mup.js +0 -362
  815. package/dist/onboard-helpers-CUGbuZwH.js +0 -363
  816. package/dist/onboard-remote-D-qWujdL.js +0 -127
  817. package/dist/onboard-remote-o_OW-uzc.js +0 -127
  818. package/dist/onboarding-Bf9kVcef.js +0 -541
  819. package/dist/onboarding-CVlOLLp1.js +0 -543
  820. package/dist/onboarding.finalize-CQSt37fw.js +0 -398
  821. package/dist/onboarding.finalize-DggVL7Ay.js +0 -401
  822. package/dist/onboarding.gateway-config-BLca3Td2.js +0 -198
  823. package/dist/onboarding.gateway-config-C1mcOkRh.js +0 -191
  824. package/dist/outbound-DXXccLDS.js +0 -220
  825. package/dist/outbound-ZnVvUReT.js +0 -221
  826. package/dist/outbound-attachment-CfRb07J7.js +0 -18
  827. package/dist/outbound-attachment-DGXTtERK.js +0 -18
  828. package/dist/outbound-attachment-_jj74QBM.js +0 -18
  829. package/dist/pairing-cli-Bgm4fRA3.js +0 -127
  830. package/dist/pairing-cli-J0uGb1nU.js +0 -122
  831. package/dist/pairing-labels-CVm65Jkh.js +0 -9
  832. package/dist/pairing-labels-DD1mcvQG.js +0 -9
  833. package/dist/pairing-store-5qapT5-t.js +0 -460
  834. package/dist/pairing-store-MLceBEeL.js +0 -459
  835. package/dist/path-env-DR5vn3QL.js +0 -89
  836. package/dist/path-env-qRJbjJzj.js +0 -89
  837. package/dist/path-guards-CIx4hURU.js +0 -31
  838. package/dist/path-guards-CrQOUlsq.js +0 -31
  839. package/dist/path-safety-DkT9RmTG.js +0 -14
  840. package/dist/path-safety-juI2XbO1.js +0 -14
  841. package/dist/paths-BTaH3rLn.js +0 -232
  842. package/dist/plugin-auto-enable-BUSF117F.js +0 -301
  843. package/dist/plugin-auto-enable-CoDnqA0S.js +0 -302
  844. package/dist/plugin-registry-D2B6nbn1.js +0 -33
  845. package/dist/plugin-registry-fLaMC0ik.js +0 -33
  846. package/dist/plugin-sdk/agents/agent-helpers/thinking.d.ts +0 -5
  847. package/dist/plugin-sdk/agents/agent-paths.d.ts +0 -1
  848. package/dist/plugin-sdk/agents/auth-profiles/constants.d.ts +0 -16
  849. package/dist/plugin-sdk/agents/auth-profiles/display.d.ts +0 -7
  850. package/dist/plugin-sdk/agents/auth-profiles/doctor.d.ts +0 -8
  851. package/dist/plugin-sdk/agents/auth-profiles/oauth.d.ts +0 -14
  852. package/dist/plugin-sdk/agents/auth-profiles/paths.d.ts +0 -4
  853. package/dist/plugin-sdk/agents/auth-profiles/profiles.d.ts +0 -12
  854. package/dist/plugin-sdk/agents/auth-profiles/session-override.d.ts +0 -18
  855. package/dist/plugin-sdk/agents/auth-profiles/store.d.ts +0 -10
  856. package/dist/plugin-sdk/agents/auth-profiles/types.d.ts +0 -13
  857. package/dist/plugin-sdk/agents/auth-profiles.d.ts +0 -8
  858. package/dist/plugin-sdk/agents/defaults.d.ts +0 -3
  859. package/dist/plugin-sdk/agents/provider-auth.d.ts +0 -40
  860. package/dist/plugin-sdk/auto-reply/model-runtime.d.ts +0 -17
  861. package/dist/plugin-sdk/auto-reply/reply/directive-handling.auth.d.ts +0 -19
  862. package/dist/plugin-sdk/auto-reply/reply/elevated-allowlist-matcher.d.ts +0 -20
  863. package/dist/plugin-sdk/auto-reply/reply/elevated-unavailable.d.ts +0 -8
  864. package/dist/plugin-sdk/auto-reply/reply/reply-elevated.d.ts +0 -16
  865. package/dist/plugin-sdk/compat/legacy-names.d.ts +0 -8
  866. package/dist/plugin-sdk/config/legacy.migrations.part-1.d.ts +0 -2
  867. package/dist/plugin-sdk/config/legacy.migrations.part-2.d.ts +0 -2
  868. package/dist/plugin-sdk/config/legacy.migrations.part-3.d.ts +0 -2
  869. package/dist/plugin-sdk/config/model-input.d.ts +0 -9
  870. package/dist/plugin-sdk/config/zod-schema.agent-model.d.ts +0 -5
  871. package/dist/plugin-sdk/link-understanding/apply.d.ts +0 -10
  872. package/dist/plugin-sdk/link-understanding/defaults.d.ts +0 -2
  873. package/dist/plugin-sdk/link-understanding/detect.d.ts +0 -3
  874. package/dist/plugin-sdk/link-understanding/format.d.ts +0 -4
  875. package/dist/plugin-sdk/link-understanding/runner.d.ts +0 -11
  876. package/dist/plugin-sdk/media/input-files.d.ts +0 -95
  877. package/dist/plugin-sdk/media-understanding/apply.d.ts +0 -19
  878. package/dist/plugin-sdk/media-understanding/attachments.d.ts +0 -49
  879. package/dist/plugin-sdk/media-understanding/audio-preflight.d.ts +0 -16
  880. package/dist/plugin-sdk/media-understanding/concurrency.d.ts +0 -1
  881. package/dist/plugin-sdk/media-understanding/defaults.d.ts +0 -12
  882. package/dist/plugin-sdk/media-understanding/errors.d.ts +0 -6
  883. package/dist/plugin-sdk/media-understanding/format.d.ts +0 -7
  884. package/dist/plugin-sdk/media-understanding/fs.d.ts +0 -1
  885. package/dist/plugin-sdk/media-understanding/output-extract.d.ts +0 -2
  886. package/dist/plugin-sdk/media-understanding/providers/anthropic/index.d.ts +0 -2
  887. package/dist/plugin-sdk/media-understanding/providers/deepgram/index.d.ts +0 -2
  888. package/dist/plugin-sdk/media-understanding/providers/google/index.d.ts +0 -2
  889. package/dist/plugin-sdk/media-understanding/providers/google/video.d.ts +0 -3
  890. package/dist/plugin-sdk/media-understanding/providers/groq/index.d.ts +0 -2
  891. package/dist/plugin-sdk/media-understanding/providers/index.d.ts +0 -4
  892. package/dist/plugin-sdk/media-understanding/providers/minimax/index.d.ts +0 -2
  893. package/dist/plugin-sdk/media-understanding/providers/mistral/index.d.ts +0 -2
  894. package/dist/plugin-sdk/media-understanding/providers/moonshot/index.d.ts +0 -2
  895. package/dist/plugin-sdk/media-understanding/providers/moonshot/video.d.ts +0 -3
  896. package/dist/plugin-sdk/media-understanding/providers/openai/index.d.ts +0 -2
  897. package/dist/plugin-sdk/media-understanding/providers/zai/index.d.ts +0 -2
  898. package/dist/plugin-sdk/media-understanding/resolve.d.ts +0 -44
  899. package/dist/plugin-sdk/media-understanding/runner.d.ts +0 -34
  900. package/dist/plugin-sdk/media-understanding/runner.entries.d.ts +0 -33
  901. package/dist/plugin-sdk/media-understanding/scope.d.ts +0 -9
  902. package/dist/plugin-sdk/media-understanding/types.d.ts +0 -74
  903. package/dist/plugin-sdk/media-understanding/video.d.ts +0 -2
  904. package/dist/plugin-sdk/sessions/model-overrides.d.ts +0 -14
  905. package/dist/plugin-sdk/telegram/reasoning-lane-coordinator.d.ts +0 -18
  906. package/dist/plugin-sdk/utils/mask-api-key.d.ts +0 -1
  907. package/dist/plugin-sdk/utils/run-with-concurrency.d.ts +0 -11
  908. package/dist/plugins-CsYMlnVa.js +0 -455
  909. package/dist/plugins-Dhit-VHt.js +0 -453
  910. package/dist/plugins-cli-BwuvKtN-.js +0 -798
  911. package/dist/plugins-cli-D34k2VsI.js +0 -793
  912. package/dist/ports-DrruB2fK.js +0 -370
  913. package/dist/ports-GT1yV-Tg.js +0 -96
  914. package/dist/ports-NPqtlfp0.js +0 -316
  915. package/dist/ports-QMI4-F9m.js +0 -96
  916. package/dist/program-C5ukTU6N.js +0 -244
  917. package/dist/program-context-D55P0vBV.js +0 -474
  918. package/dist/progress-CBkSaM6z.js +0 -124
  919. package/dist/prompt-Bllj1dhc.js +0 -21
  920. package/dist/prompt-select-styled-WStiI-bz.js +0 -1647
  921. package/dist/prompt-select-styled-ram-aXWu.js +0 -1650
  922. package/dist/prompt-style-DVEm3BZW.js +0 -9
  923. package/dist/provider-dispatcher-epFKwpGK.js +0 -659
  924. package/dist/provider-dispatcher-vEBMmwZ0.js +0 -660
  925. package/dist/push-apns-C0LyG-WB.js +0 -713
  926. package/dist/push-apns-DuG95AKC.js +0 -711
  927. package/dist/pw-ai-TygsEDgY.js +0 -1906
  928. package/dist/pw-ai-eS0sIkZo.js +0 -1910
  929. package/dist/qr-cli-B8sYhugo.js +0 -352
  930. package/dist/qr-cli-yP8i4Iv1.js +0 -347
  931. package/dist/redact-eZq1uwNK.js +0 -191
  932. package/dist/redact-snapshot-gOLgfKp3.js +0 -2028
  933. package/dist/redact-snapshot-uT-CXbM8.js +0 -2028
  934. package/dist/register.agent-CSoigVGq.js +0 -1043
  935. package/dist/register.agent-GZLrbUPm.js +0 -286
  936. package/dist/register.configure-CXpiRohq.js +0 -124
  937. package/dist/register.configure-RaqiHe5L.js +0 -130
  938. package/dist/register.import-Bs-UkOs-.js +0 -27
  939. package/dist/register.import-DLng8g-e.js +0 -30
  940. package/dist/register.maintenance-B-ZLQ56Y.js +0 -494
  941. package/dist/register.maintenance-Bjr_SmG9.js +0 -497
  942. package/dist/register.message-BCQ8Vg4O.js +0 -686
  943. package/dist/register.message-ChhiSr7g.js +0 -681
  944. package/dist/register.onboard-DJCqNufv.js +0 -257
  945. package/dist/register.onboard-jlxjsrv6.js +0 -262
  946. package/dist/register.setup-C-sdixz5.js +0 -114
  947. package/dist/register.setup-Dwpe4ArC.js +0 -109
  948. package/dist/register.status-health-sessions-BWFRHBCZ.js +0 -669
  949. package/dist/register.status-health-sessions-D7noMz9y.js +0 -423
  950. package/dist/register.subclis-DFI5u4a6.js +0 -267
  951. package/dist/replies-Bzcj-R8d.js +0 -136
  952. package/dist/replies-uvTI-4lg.js +0 -136
  953. package/dist/reply-B9qz9Wwk.js +0 -13897
  954. package/dist/reply-CmGAXQKc.js +0 -13900
  955. package/dist/reply-directives-Be97YiyM.js +0 -182
  956. package/dist/reply-directives-DsLughUT.js +0 -182
  957. package/dist/reply-payloads-DW0YgT82.js +0 -527
  958. package/dist/reply-prefix-BzoT8h8o.js +0 -38
  959. package/dist/reply-prefix-CSaiVnkC.js +0 -38
  960. package/dist/resolve-route-2P40JKXk.js +0 -249
  961. package/dist/resolve-route-_CwEKLq6.js +0 -249
  962. package/dist/response-prefix-template-BAlvtSjL.js +0 -136
  963. package/dist/response-prefix-template-D-tls8tI.js +0 -136
  964. package/dist/retry-B042l5UJ.js +0 -77
  965. package/dist/retry-BhuXOEVR.js +0 -77
  966. package/dist/run-main-B-O5ZtbU.js +0 -320
  967. package/dist/runner-DGkTSlOS.js +0 -2294
  968. package/dist/runner-hs4uxAUP.js +0 -2294
  969. package/dist/runtime-DJNp29jv.js +0 -94
  970. package/dist/runtime-guard-DZ_xuCc4.js +0 -60
  971. package/dist/secure-random-DTcQnwrI.js +0 -44
  972. package/dist/security-cli-1iY1lW6F.js +0 -484
  973. package/dist/security-cli-BuiPPQYU.js +0 -478
  974. package/dist/send-3lgWtHHf.js +0 -349
  975. package/dist/send-6l2S1bcr.js +0 -11
  976. package/dist/send-9NV7sSlD.js +0 -2245
  977. package/dist/send-B0TcjZUD.js +0 -1778
  978. package/dist/send-Bb6K_10X.js +0 -2245
  979. package/dist/send-BzN7X1Om.js +0 -374
  980. package/dist/send-CLrRM0El.js +0 -426
  981. package/dist/send-Caz-txXK.js +0 -492
  982. package/dist/send-DJEr4rP6.js +0 -547
  983. package/dist/send-DJiDHXsu.js +0 -349
  984. package/dist/send-DOjg7kJj.js +0 -1775
  985. package/dist/send-DVXOiKT4.js +0 -1174
  986. package/dist/send-Dc_K995l.js +0 -547
  987. package/dist/send-Dh6d3CLl.js +0 -332
  988. package/dist/send-iPAfbiYM.js +0 -492
  989. package/dist/send-pwe9Gu8e.js +0 -29
  990. package/dist/server-B0IC-Osg.js +0 -205
  991. package/dist/server-MccRxMpb.js +0 -200
  992. package/dist/server-lifecycle-C_0CfoP7.js +0 -2437
  993. package/dist/server-lifecycle-IKdGw1kM.js +0 -2437
  994. package/dist/server-node-events-Czr2gXp_.js +0 -393
  995. package/dist/server-node-events-DFG6cXud.js +0 -398
  996. package/dist/service-Bjqii5nW.js +0 -670
  997. package/dist/service-fp29z5Ww.js +0 -670
  998. package/dist/session-DBL5nHDy.js +0 -170
  999. package/dist/session-cost-usage-DX09eTPU.js +0 -627
  1000. package/dist/session-cost-usage-yYi525j3.js +0 -627
  1001. package/dist/session-dirs-Cj5xi7zX.js +0 -947
  1002. package/dist/session-dirs-DdF6TDsE.js +0 -947
  1003. package/dist/session-utils-C7BtKlun.js +0 -625
  1004. package/dist/session-utils-CLe1dano.js +0 -625
  1005. package/dist/session-xKIW6gL2.js +0 -170
  1006. package/dist/sessions-C65iUuN9.js +0 -2593
  1007. package/dist/sessions-DjZ9IshB.js +0 -252
  1008. package/dist/ssrf-Ck9HDZpv.js +0 -183
  1009. package/dist/ssrf-m7kFIobZ.js +0 -183
  1010. package/dist/status-C6ghjxvX.js +0 -2072
  1011. package/dist/status-D-qTB8aZ.js +0 -2068
  1012. package/dist/status.update-C55QM2xs.js +0 -79
  1013. package/dist/status.update-CBmPXwYN.js +0 -79
  1014. package/dist/store-Bjk6rTC_.js +0 -53
  1015. package/dist/store-C3tOpizT.js +0 -64
  1016. package/dist/store-uRA67h-o.js +0 -2595
  1017. package/dist/store-v3P-OWhi.js +0 -64
  1018. package/dist/subagent-registry-BTG1aAZ8.js +0 -4860
  1019. package/dist/subagent-registry-CoclNL5c.js +0 -4858
  1020. package/dist/subsystem-COd61u0P.js +0 -1139
  1021. package/dist/subsystem-D9ZpRKFP.js +0 -1079
  1022. package/dist/system-cli-C__5QOMX.js +0 -70
  1023. package/dist/system-cli-Dr4XoVTq.js +0 -75
  1024. package/dist/systemd-DSnlM3jX.js +0 -547
  1025. package/dist/systemd-TfK8GuTx.js +0 -547
  1026. package/dist/systemd-linger-Axnc1xCb.js +0 -75
  1027. package/dist/systemd-linger-_0_-RY4v.js +0 -75
  1028. package/dist/table-DPTzZyhu.js +0 -279
  1029. package/dist/tables-BQ-CvUfT.js +0 -55
  1030. package/dist/tables-D3a9iSU1.js +0 -55
  1031. package/dist/tables-D3zdgEuK.js +0 -55
  1032. package/dist/tailnet-CEudzG0i.js +0 -40
  1033. package/dist/tailnet-PnMrjwGT.js +0 -40
  1034. package/dist/tailscale-DTATQxAG.js +0 -230
  1035. package/dist/tailscale-Dbyahx0J.js +0 -230
  1036. package/dist/targets-B_0Y1i-1.js +0 -2173
  1037. package/dist/targets-CMhBAn87.js +0 -120
  1038. package/dist/targets-CTmhieRB.js +0 -650
  1039. package/dist/targets-CcTME3bp.js +0 -46
  1040. package/dist/targets-DfaVEd_u.js +0 -220
  1041. package/dist/targets-DtiQgjEL.js +0 -2172
  1042. package/dist/targets-DyybKefq.js +0 -53
  1043. package/dist/targets-rDolm5YS.js +0 -650
  1044. package/dist/tokens-DzFOtLlW.js +0 -21
  1045. package/dist/tool-display-Br6mwaJc.js +0 -785
  1046. package/dist/tool-display-sgNwLOBj.js +0 -785
  1047. package/dist/tool-images-BNfIJ_Kj.js +0 -263
  1048. package/dist/tool-images-kloBqxqK.js +0 -263
  1049. package/dist/trash-DPi0aCCQ.js +0 -125
  1050. package/dist/trash-D_Jd_yQZ.js +0 -125
  1051. package/dist/tui-BSDCI2hh.js +0 -3392
  1052. package/dist/tui-DT7hLOBk.js +0 -3392
  1053. package/dist/tui-cli-DUWvLaoG.js +0 -58
  1054. package/dist/tui-cli-Dn2iXQTO.js +0 -63
  1055. package/dist/update-Bgl3Pk2N.js +0 -349
  1056. package/dist/update-CFPFib4P.js +0 -349
  1057. package/dist/update-cli-DSDSQ2Xi.js +0 -1373
  1058. package/dist/update-cli-DYR_7NLy.js +0 -1370
  1059. package/dist/usage-CS1zeIan.js +0 -5279
  1060. package/dist/utils-LBKvDoPx.js +0 -631
  1061. package/dist/web-BECD5Akw.js +0 -70
  1062. package/dist/web-D4oENnAL.js +0 -3065
  1063. package/dist/web-KP-TI2sO.js +0 -76
  1064. package/dist/webhooks-cli-BqoG_i-D.js +0 -328
  1065. package/dist/webhooks-cli-Ddu7dfdE.js +0 -333
  1066. package/dist/whatsapp-actions-BZLIjQ8J.js +0 -122
  1067. package/dist/whatsapp-actions-KCc1vHN5.js +0 -128
  1068. package/dist/widearea-dns-DSoaA-eH.js +0 -127
  1069. package/dist/workspace-4EaHHEWi.js +0 -447
  1070. package/dist/workspace-B_1t_yq3.js +0 -449
  1071. /package/dist/{account-lookup-0KDSp5Mj.js → account-lookup-C0ndrpt-.js} +0 -0
  1072. /package/dist/{account-lookup-zvANGr2x.js → account-lookup-CIY_RKhi.js} +0 -0
  1073. /package/dist/{api-BeQMq2iS.js → api-BE4ZCWWB.js} +0 -0
  1074. /package/dist/{api-CxX8-gGz.js → api-wsk9zRVi.js} +0 -0
  1075. /package/dist/{argv-Co-b9Zsc.js → argv-BY8EVMTP.js} +0 -0
  1076. /package/dist/{brew-DbSbN8sD.js → brew-CmTYeZk1.js} +0 -0
  1077. /package/dist/{brew-C4zKZsHX.js → brew-V4lMBeE3.js} +0 -0
  1078. /package/dist/{chat-type-CYPyHAj-.js → chat-type-BP9akbag.js} +0 -0
  1079. /package/dist/{chat-type-DKb2TlGZ.js → chat-type-CH3W-zKy.js} +0 -0
  1080. /package/dist/{cleanup-utils-CwQvD73q.js → cleanup-utils-ZC2zvntc.js} +0 -0
  1081. /package/dist/{cli-name-BicfmwQX.js → cli-name-BZsYSp9l.js} +0 -0
  1082. /package/dist/{cli-name-C6rJGl18.js → cli-name-CRe5Ow_t.js} +0 -0
  1083. /package/dist/{cli-utils-BhXbz2UF.js → cli-utils-BUOtyfnU.js} +0 -0
  1084. /package/dist/{cli-utils-DZe_rVkZ.js → cli-utils-CGB3cBZm.js} +0 -0
  1085. /package/dist/{client-C61M8zI3.js → client-9dK56xly.js} +0 -0
  1086. /package/dist/{client-DdpmATKq.js → client-D-R1YdRD.js} +0 -0
  1087. /package/dist/{command-options-C4paWSGf.js → command-options-CnHA4TzR.js} +0 -0
  1088. /package/dist/{command-options-CA30lfLK.js → command-options-D2nN4AXX.js} +0 -0
  1089. /package/dist/{config-eval-CjGZtLwx.js → config-eval-BQIR-wSg.js} +0 -0
  1090. /package/dist/{config-eval-H_wlEYIG.js → config-eval-Bh82JoXK.js} +0 -0
  1091. /package/dist/{constants-ChptG3d7.js → constants-C7j1VA2S.js} +0 -0
  1092. /package/dist/{constants-DY6b-_Wl.js → constants-DoYLsBmv.js} +0 -0
  1093. /package/dist/{credentials-BHWUBHMd.js → credentials-C_RoJFmK.js} +0 -0
  1094. /package/dist/{credentials-DFsi1_e8.js → credentials-DM_Dj0m8.js} +0 -0
  1095. /package/dist/{daemon-runtime-CMnbwryP.js → daemon-runtime-9oDBR7YW.js} +0 -0
  1096. /package/dist/{daemon-runtime-CvqE4ysg.js → daemon-runtime-CzFI2dPw.js} +0 -0
  1097. /package/dist/{dangerous-name-matching-BzmiLXmA.js → dangerous-name-matching-BlTBBZns.js} +0 -0
  1098. /package/dist/{dangerous-name-matching-DaVRgwer.js → dangerous-name-matching-CSq9sJDG.js} +0 -0
  1099. /package/dist/{dangerous-tools-BOLoCRv4.js → dangerous-tools-BRmbBvRf.js} +0 -0
  1100. /package/dist/{dangerous-tools-Baq7Q-i6.js → dangerous-tools-D4jtl72G.js} +0 -0
  1101. /package/dist/{fetch-timeout-DTIN7CGM.js → fetch-timeout-CytN1wiO.js} +0 -0
  1102. /package/dist/{fetch-timeout-DoySHqfO.js → fetch-timeout-DBRRPNBi.js} +0 -0
  1103. /package/dist/{file-identity-BxlKD8Ys.js → file-identity-CeRK5CJC.js} +0 -0
  1104. /package/dist/{format-duration-CqUERz51.js → format-duration-B-Uv5nOi.js} +0 -0
  1105. /package/dist/{format-duration-Ct-yiwkS.js → format-duration-D1M3Zxu6.js} +0 -0
  1106. /package/dist/{format-relative-79_Y1n2Y.js → format-relative-Czf5fUjn.js} +0 -0
  1107. /package/dist/{format-relative-CxLpEQOX.js → format-relative-zwkkXJvs.js} +0 -0
  1108. /package/dist/{health-format-B_QRD8Si.js → health-format-DF54wvUU.js} +0 -0
  1109. /package/dist/{heartbeat-wake-LGEgcXjs.js → heartbeat-wake-CvHncCjP.js} +0 -0
  1110. /package/dist/{heartbeat-wake-Y97geucO.js → heartbeat-wake-DLxQm6-U.js} +0 -0
  1111. /package/dist/{help-format-NNm_Ov4H.js → help-format-CJQ7APRn.js} +0 -0
  1112. /package/dist/{helpers-BAsMXprO.js → helpers-BER76F_2.js} +0 -0
  1113. /package/dist/{helpers-DLgbkcEn.js → helpers-n2CtWpm9.js} +0 -0
  1114. /package/dist/{input-provenance-Bn6thJNm.js → input-provenance-gIfDn1ki.js} +0 -0
  1115. /package/dist/{input-provenance-xUsSMOsz.js → input-provenance-wkso1o5V.js} +0 -0
  1116. /package/dist/{ip-C9q3Oq20.js → ip-D4VG5EJO.js} +0 -0
  1117. /package/dist/{ip-D0zgNmBV.js → ip-MwCwRA7c.js} +0 -0
  1118. /package/dist/{is-main-DN8-sNR5.js → is-main-BmHYGRhd.js} +0 -0
  1119. /package/dist/{json-file-B7l5-Xhr.js → json-file-BW22hGtf.js} +0 -0
  1120. /package/dist/{json-file-ChO_R9yh.js → json-file-DwRAfAAy.js} +0 -0
  1121. /package/dist/{json-files-CmpYSF4G.js → json-files-Dy52honG.js} +0 -0
  1122. /package/dist/{lanes-ByWMUgrz.js → lanes-1CBKdsiR.js} +0 -0
  1123. /package/dist/{lanes-cHJ5arWg.js → lanes-DqVYfPRG.js} +0 -0
  1124. /package/dist/{links-Bz4V7R_p.js → links-CwTlzaPe.js} +0 -0
  1125. /package/dist/{location-DBWCGNLq.js → location-50gaJF5Z.js} +0 -0
  1126. /package/dist/{location-GbZ0bBRU.js → location-Qo8Ii1zo.js} +0 -0
  1127. /package/dist/{logger-DyL5G2DO.js → logger-B8BE0PyS.js} +0 -0
  1128. /package/dist/{logger-BWMPnILd.js → logger-CPvz-aPM.js} +0 -0
  1129. /package/dist/{logger-GvipVDfh.js → logger-cL0D2DCr.js} +0 -0
  1130. /package/dist/{logging-D8-Kozjc.js → logging-DTEoeoa3.js} +0 -0
  1131. /package/dist/{mutable-allowlist-detectors-DiZDtmlZ.js → mutable-allowlist-detectors-BXE7Hr7F.js} +0 -0
  1132. /package/dist/{mutable-allowlist-detectors-U5ThQr9V.js → mutable-allowlist-detectors-CtKavajp.js} +0 -0
  1133. /package/dist/{parse-log-line-enq8pduH.js → parse-log-line-GisaZn5H.js} +0 -0
  1134. /package/dist/{parse-log-line-mz9TG6ig.js → parse-log-line-ZsbwG_u7.js} +0 -0
  1135. /package/dist/{parse-timeout-BMP8a0_a.js → parse-timeout-BpphuwYl.js} +0 -0
  1136. /package/dist/{parse-timeout-CDkco8kd.js → parse-timeout-CE6BjmGU.js} +0 -0
  1137. /package/dist/plugin-sdk/{agents → auth}/api-key-rotation.d.ts +0 -0
  1138. /package/dist/plugin-sdk/{media-understanding → stt}/providers/deepgram/audio.d.ts +0 -0
  1139. /package/dist/plugin-sdk/{media-understanding → stt}/providers/google/audio.d.ts +0 -0
  1140. /package/dist/plugin-sdk/{media-understanding → stt}/providers/google/inline-data.d.ts +0 -0
  1141. /package/dist/plugin-sdk/{media-understanding → stt}/providers/openai/audio.d.ts +0 -0
  1142. /package/dist/plugin-sdk/{media-understanding → stt}/providers/shared.d.ts +0 -0
  1143. /package/dist/{plugins-allowlist-BbTQ5Z2k.js → plugins-allowlist-A38nxBRG.js} +0 -0
  1144. /package/dist/{plugins-allowlist-C20oaESO.js → plugins-allowlist-D2tS9tcu.js} +0 -0
  1145. /package/dist/{polls-B0CCBDeR.js → polls-BLyT08ZI.js} +0 -0
  1146. /package/dist/{polls-CwwHzYBM.js → polls-BmymsJEe.js} +0 -0
  1147. /package/dist/{ports-lsof-Wteul3ju.js → ports-lsof-CDyv5GJd.js} +0 -0
  1148. /package/dist/{process-scoped-map-CV9kDvfG.js → process-scoped-map-BCJR56ZB.js} +0 -0
  1149. /package/dist/{process-scoped-map-PEvnG75N.js → process-scoped-map-Cb1EHPyN.js} +0 -0
  1150. /package/dist/{program-context-jqeI5alP.js → program-context-DlXnmuB7.js} +0 -0
  1151. /package/dist/{progress-C1kUfYL-.js → progress-DRLmcFiG.js} +0 -0
  1152. /package/dist/{prompt-Yn2yClg1.js → prompt-BRGfic91.js} +0 -0
  1153. /package/dist/{prompt-style-DjEYC_s-.js → prompt-style-CUuA6OCy.js} +0 -0
  1154. /package/dist/{provider-utils-3JTMJroG.js → provider-utils-C9kBVF1f.js} +0 -0
  1155. /package/dist/{provider-utils-FaBmofiq.js → provider-utils-DiLhkKQp.js} +0 -0
  1156. /package/dist/{proxy-DL3MD6-P.js → proxy-BMJL0Qog.js} +0 -0
  1157. /package/dist/{proxy-DpNv2cSV.js → proxy-D-qGA1vm.js} +0 -0
  1158. /package/dist/{pw-ai-state-CGfLv6nV.js → pw-ai-state--TxTVwRW.js} +0 -0
  1159. /package/dist/{pw-ai-state-Dynx20hr.js → pw-ai-state-CwXeO5d0.js} +0 -0
  1160. /package/dist/{redact-Dx1Fue21.js → redact-BW8tobyp.js} +0 -0
  1161. /package/dist/{redact-identifier-BTIWtaa-.js → redact-identifier-BJOQDEj0.js} +0 -0
  1162. /package/dist/{redact-identifier-CAagcfWA.js → redact-identifier-Bv5SUUw-.js} +0 -0
  1163. /package/dist/{remoteclaw-root-C2HV2VeC.js → remoteclaw-root-BfPjgewe.js} +0 -0
  1164. /package/dist/{remoteclaw-root-DybYl8PL.js → remoteclaw-root-E4-hmb4E.js} +0 -0
  1165. /package/dist/{render-CCLsW6Lz.js → render-BhKzKdV0.js} +0 -0
  1166. /package/dist/{render-uf6PvGMV.js → render-e7fENCYH.js} +0 -0
  1167. /package/dist/{retry-DnqPAqWp.js → retry-BWv_fy4u.js} +0 -0
  1168. /package/dist/{runtime-guard-U-ewY_QH.js → runtime-guard-Bhx-pb8_.js} +0 -0
  1169. /package/dist/{secret-equal-BbHdTtqY.js → secret-equal-D6AoXne1.js} +0 -0
  1170. /package/dist/{secret-equal-CXJEZiWb.js → secret-equal-DLnUuWM3.js} +0 -0
  1171. /package/dist/{secure-random-CS2mSdTn.js → secure-random-CJtykx_p.js} +0 -0
  1172. /package/dist/{secure-random-_dzDDlFo.js → secure-random-CRVHgtmO.js} +0 -0
  1173. /package/dist/{session-key-5YLnn_qf.js → session-key-BF-9YzxC.js} +0 -0
  1174. /package/dist/{session-key-C2n-VILA.js → session-key-CgKWfjoZ.js} +0 -0
  1175. /package/dist/{stagger-BXv_apuy.js → stagger--wvODnNe.js} +0 -0
  1176. /package/dist/{stagger-MI9gd2rQ.js → stagger-BLmTO4cK.js} +0 -0
  1177. /package/dist/{status-BmtCS3T1.js → status-1zVD-Clq.js} +0 -0
  1178. /package/dist/{status-BrwHRn2B.js → status-BtRY0nXQ.js} +0 -0
  1179. /package/dist/{strip-inbound-meta-DjKcSFaW.js → strip-inbound-meta-zmUXypSS.js} +0 -0
  1180. /package/dist/{strip-inbound-meta-jy3bkUab.js → strip-inbound-meta-zqtN9FTK.js} +0 -0
  1181. /package/dist/{table-C1rdyYl9.js → table-On3hkCqi.js} +0 -0
  1182. /package/dist/{target-errors-BDpPcwh5.js → target-errors-DJVRKFcU.js} +0 -0
  1183. /package/dist/{target-errors-DdIAPcMM.js → target-errors-GZXDqlUu.js} +0 -0
  1184. /package/dist/{targets-C-2xwh9f.js → targets-B46m7u5J.js} +0 -0
  1185. /package/dist/{targets-D-qLBpTA.js → targets-B_d_1z3N.js} +0 -0
  1186. /package/dist/{targets-UncQvCVs.js → targets-D01MJGnh.js} +0 -0
  1187. /package/dist/{targets-BMenhVHg.js → targets-D3r6Zgic.js} +0 -0
  1188. /package/dist/{text-format-BQ3z_OXA.js → text-format-DarxU3JH.js} +0 -0
  1189. /package/dist/{text-format-oWqzVmah.js → text-format-Ds92M9UT.js} +0 -0
  1190. /package/dist/{tokens-B-jmvNR9.js → tokens-Dw7ZdYwT.js} +0 -0
  1191. /package/dist/{usage-BdhBT0Vz.js → usage-BIzKZ5dT.js} +0 -0
  1192. /package/dist/{usage-BtQcAnf6.js → usage-BvZOzIC7.js} +0 -0
  1193. /package/dist/{usage-format-C3mNLfhI.js → usage-format-CmniSPCG.js} +0 -0
  1194. /package/dist/{usage-format-DAaPzr_z.js → usage-format-D_KQYQ-w.js} +0 -0
  1195. /package/dist/{widearea-dns-CsmBVbez.js → widearea-dns-D01FFYZ8.js} +0 -0
  1196. /package/dist/{workspace-BzPeZDew.js → workspace-BJCKO8Ns.js} +0 -0
  1197. /package/dist/{workspace-DkGLVfOl.js → workspace-BisvA9oA.js} +0 -0
  1198. /package/dist/{wsl-B_sPlzWw.js → wsl-PDLKeX04.js} +0 -0
  1199. /package/dist/{wsl-BCnYV9O0.js → wsl-kFaeW76c.js} +0 -0
@@ -1,2593 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
- import { Q as normalizeE164, dn as resolveRequiredHomeDir, o as createSubsystemLogger } from "./entry.js";
3
- import { n as isPidAlive, t as resolveProcessScopedMap } from "./process-scoped-map-PEvnG75N.js";
4
- import { c as normalizeMainKey, g as normalizeOptionalAccountId, l as resolveAgentIdFromSessionKey, r as buildAgentMainSessionKey, s as normalizeAgentId, t as DEFAULT_AGENT_ID } from "./session-key-C2n-VILA.js";
5
- import { _ as parseDurationMs, i as loadConfig, v as parseByteSize } from "./config-CwtWvygh.js";
6
- import { c as normalizeHyphenSlug, t as getChannelDock } from "./dock-DXSgTbDw.js";
7
- import { c as normalizeMessageChannel, s as listDeliverableMessageChannels } from "./message-channel-uWMAiywE.js";
8
- import { t as normalizeChatType } from "./chat-type-CYPyHAj-.js";
9
- import { n as resolveConversationLabel } from "./conversation-label-C4SDz4sT.js";
10
- import { r as normalizeChannelId } from "./plugins-Dhit-VHt.js";
11
- import { a as hasToolCall, c as resolveSessionFilePath, d as resolveSessionTranscriptPathInDir, f as resolveSessionTranscriptsDir, h as validateSessionId, i as extractToolCallNames, l as resolveSessionFilePathOptions, m as resolveStorePath, n as stripMessageIdHints, o as SAFE_SESSION_ID_RE, p as resolveSessionTranscriptsDirForAgent, s as resolveDefaultSessionStorePath, t as stripEnvelope, u as resolveSessionTranscriptPath } from "./chat-envelope-DEZ-5RY8.js";
12
- import { n as hasInterSessionUserProvenance } from "./input-provenance-xUsSMOsz.js";
13
- import { t as stripInboundMetadata } from "./strip-inbound-meta-DjKcSFaW.js";
14
- import os from "node:os";
15
- import path from "node:path";
16
- import fs from "node:fs";
17
- import fsp from "node:fs/promises";
18
- import crypto from "node:crypto";
19
-
20
- //#region src/config/sessions/group.ts
21
- const getGroupSurfaces = () => new Set([...listDeliverableMessageChannels(), "webchat"]);
22
- function normalizeGroupLabel(raw) {
23
- return normalizeHyphenSlug(raw);
24
- }
25
- function shortenGroupId(value) {
26
- const trimmed = value?.trim() ?? "";
27
- if (!trimmed) return "";
28
- if (trimmed.length <= 14) return trimmed;
29
- return `${trimmed.slice(0, 6)}...${trimmed.slice(-4)}`;
30
- }
31
- function buildGroupDisplayName(params) {
32
- const providerKey = (params.provider?.trim().toLowerCase() || "group").trim();
33
- const groupChannel = params.groupChannel?.trim();
34
- const space = params.space?.trim();
35
- const subject = params.subject?.trim();
36
- const detail = (groupChannel && space ? `${space}${groupChannel.startsWith("#") ? "" : "#"}${groupChannel}` : groupChannel || subject || space || "") || "";
37
- const fallbackId = params.id?.trim() || params.key;
38
- const rawLabel = detail || fallbackId;
39
- let token = normalizeGroupLabel(rawLabel);
40
- if (!token) token = normalizeGroupLabel(shortenGroupId(rawLabel));
41
- if (!params.groupChannel && token.startsWith("#")) token = token.replace(/^#+/, "");
42
- if (token && !/^[@#]/.test(token) && !token.startsWith("g-") && !token.includes("#")) token = `g-${token}`;
43
- return token ? `${providerKey}:${token}` : providerKey;
44
- }
45
- function resolveGroupSessionKey(ctx) {
46
- const from = typeof ctx.From === "string" ? ctx.From.trim() : "";
47
- const chatType = ctx.ChatType?.trim().toLowerCase();
48
- const normalizedChatType = chatType === "channel" ? "channel" : chatType === "group" ? "group" : void 0;
49
- const isWhatsAppGroupId = from.toLowerCase().endsWith("@g.us");
50
- if (!(normalizedChatType === "group" || normalizedChatType === "channel" || from.includes(":group:") || from.includes(":channel:") || isWhatsAppGroupId)) return null;
51
- const providerHint = ctx.Provider?.trim().toLowerCase();
52
- const parts = from.split(":").filter(Boolean);
53
- const head = parts[0]?.trim().toLowerCase() ?? "";
54
- const headIsSurface = head ? getGroupSurfaces().has(head) : false;
55
- const provider = headIsSurface ? head : providerHint ?? (isWhatsAppGroupId ? "whatsapp" : void 0);
56
- if (!provider) return null;
57
- const second = parts[1]?.trim().toLowerCase();
58
- const secondIsKind = second === "group" || second === "channel";
59
- const kind = secondIsKind ? second : from.includes(":channel:") || normalizedChatType === "channel" ? "channel" : "group";
60
- const finalId = (headIsSurface ? secondIsKind ? parts.slice(2).join(":") : parts.slice(1).join(":") : from).trim().toLowerCase();
61
- if (!finalId) return null;
62
- return {
63
- key: `${provider}:${kind}:${finalId}`,
64
- channel: provider,
65
- id: finalId,
66
- chatType: kind === "channel" ? "channel" : "group"
67
- };
68
- }
69
-
70
- //#endregion
71
- //#region src/config/sessions/artifacts.ts
72
- const ARCHIVE_TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(?:\.\d{3})?Z$/;
73
- const LEGACY_STORE_BACKUP_RE = /^sessions\.json\.bak\.\d+$/;
74
- function hasArchiveSuffix(fileName, reason) {
75
- const marker = `.${reason}.`;
76
- const index = fileName.lastIndexOf(marker);
77
- if (index < 0) return false;
78
- const raw = fileName.slice(index + marker.length);
79
- return ARCHIVE_TIMESTAMP_RE.test(raw);
80
- }
81
- function isSessionArchiveArtifactName(fileName) {
82
- if (LEGACY_STORE_BACKUP_RE.test(fileName)) return true;
83
- return hasArchiveSuffix(fileName, "deleted") || hasArchiveSuffix(fileName, "reset") || hasArchiveSuffix(fileName, "bak");
84
- }
85
- function isPrimarySessionTranscriptFileName(fileName) {
86
- if (fileName === "sessions.json") return false;
87
- if (!fileName.endsWith(".jsonl")) return false;
88
- return !isSessionArchiveArtifactName(fileName);
89
- }
90
- function formatSessionArchiveTimestamp(nowMs = Date.now()) {
91
- return new Date(nowMs).toISOString().replaceAll(":", "-");
92
- }
93
- function restoreSessionArchiveTimestamp(raw) {
94
- const [datePart, timePart] = raw.split("T");
95
- if (!datePart || !timePart) return raw;
96
- return `${datePart}T${timePart.replace(/-/g, ":")}`;
97
- }
98
- function parseSessionArchiveTimestamp(fileName, reason) {
99
- const marker = `.${reason}.`;
100
- const index = fileName.lastIndexOf(marker);
101
- if (index < 0) return null;
102
- const raw = fileName.slice(index + marker.length);
103
- if (!raw) return null;
104
- if (!ARCHIVE_TIMESTAMP_RE.test(raw)) return null;
105
- const timestamp = Date.parse(restoreSessionArchiveTimestamp(raw));
106
- return Number.isNaN(timestamp) ? null : timestamp;
107
- }
108
-
109
- //#endregion
110
- //#region src/config/sessions/metadata.ts
111
- const mergeOrigin = (existing, next) => {
112
- if (!existing && !next) return;
113
- const merged = existing ? { ...existing } : {};
114
- if (next?.label) merged.label = next.label;
115
- if (next?.provider) merged.provider = next.provider;
116
- if (next?.surface) merged.surface = next.surface;
117
- if (next?.chatType) merged.chatType = next.chatType;
118
- if (next?.from) merged.from = next.from;
119
- if (next?.to) merged.to = next.to;
120
- if (next?.accountId) merged.accountId = next.accountId;
121
- if (next?.threadId != null && next.threadId !== "") merged.threadId = next.threadId;
122
- return Object.keys(merged).length > 0 ? merged : void 0;
123
- };
124
- function deriveSessionOrigin(ctx) {
125
- const label = resolveConversationLabel(ctx)?.trim();
126
- const provider = normalizeMessageChannel(typeof ctx.OriginatingChannel === "string" && ctx.OriginatingChannel || ctx.Surface || ctx.Provider);
127
- const surface = ctx.Surface?.trim().toLowerCase();
128
- const chatType = normalizeChatType(ctx.ChatType) ?? void 0;
129
- const from = ctx.From?.trim();
130
- const to = (typeof ctx.OriginatingTo === "string" ? ctx.OriginatingTo : ctx.To)?.trim() ?? void 0;
131
- const accountId = ctx.AccountId?.trim();
132
- const threadId = ctx.MessageThreadId ?? void 0;
133
- const origin = {};
134
- if (label) origin.label = label;
135
- if (provider) origin.provider = provider;
136
- if (surface) origin.surface = surface;
137
- if (chatType) origin.chatType = chatType;
138
- if (from) origin.from = from;
139
- if (to) origin.to = to;
140
- if (accountId) origin.accountId = accountId;
141
- if (threadId != null && threadId !== "") origin.threadId = threadId;
142
- return Object.keys(origin).length > 0 ? origin : void 0;
143
- }
144
- function snapshotSessionOrigin(entry) {
145
- if (!entry?.origin) return;
146
- return { ...entry.origin };
147
- }
148
- function deriveGroupSessionPatch(params) {
149
- const resolution = params.groupResolution ?? resolveGroupSessionKey(params.ctx);
150
- if (!resolution?.channel) return null;
151
- const channel = resolution.channel;
152
- const subject = params.ctx.GroupSubject?.trim();
153
- const space = params.ctx.GroupSpace?.trim();
154
- const explicitChannel = params.ctx.GroupChannel?.trim();
155
- const normalizedChannel = normalizeChannelId(channel);
156
- const isChannelProvider = Boolean(normalizedChannel && getChannelDock(normalizedChannel)?.capabilities.chatTypes.includes("channel"));
157
- const nextGroupChannel = explicitChannel ?? ((resolution.chatType === "channel" || isChannelProvider) && subject && subject.startsWith("#") ? subject : void 0);
158
- const nextSubject = nextGroupChannel ? void 0 : subject;
159
- const patch = {
160
- chatType: resolution.chatType ?? "group",
161
- channel,
162
- groupId: resolution.id
163
- };
164
- if (nextSubject) patch.subject = nextSubject;
165
- if (nextGroupChannel) patch.groupChannel = nextGroupChannel;
166
- if (space) patch.space = space;
167
- const displayName = buildGroupDisplayName({
168
- provider: channel,
169
- subject: nextSubject ?? params.existing?.subject,
170
- groupChannel: nextGroupChannel ?? params.existing?.groupChannel,
171
- space: space ?? params.existing?.space,
172
- id: resolution.id,
173
- key: params.sessionKey
174
- });
175
- if (displayName) patch.displayName = displayName;
176
- return patch;
177
- }
178
- function deriveSessionMetaPatch(params) {
179
- const groupPatch = deriveGroupSessionPatch(params);
180
- const origin = deriveSessionOrigin(params.ctx);
181
- if (!groupPatch && !origin) return null;
182
- const patch = groupPatch ? { ...groupPatch } : {};
183
- const mergedOrigin = mergeOrigin(params.existing?.origin, origin);
184
- if (mergedOrigin) patch.origin = mergedOrigin;
185
- return Object.keys(patch).length > 0 ? patch : null;
186
- }
187
-
188
- //#endregion
189
- //#region src/config/sessions/main-session.ts
190
- function resolveMainSessionKey(cfg) {
191
- if (cfg?.session?.scope === "global") return "global";
192
- const agents = cfg?.agents?.list ?? [];
193
- return buildAgentMainSessionKey({
194
- agentId: normalizeAgentId(agents.find((agent) => agent?.default)?.id ?? agents[0]?.id ?? DEFAULT_AGENT_ID),
195
- mainKey: normalizeMainKey(cfg?.session?.mainKey)
196
- });
197
- }
198
- function resolveMainSessionKeyFromConfig() {
199
- return resolveMainSessionKey(loadConfig());
200
- }
201
- function resolveAgentMainSessionKey(params) {
202
- const mainKey = normalizeMainKey(params.cfg?.session?.mainKey);
203
- return buildAgentMainSessionKey({
204
- agentId: params.agentId,
205
- mainKey
206
- });
207
- }
208
- function resolveExplicitAgentSessionKey(params) {
209
- const agentId = params.agentId?.trim();
210
- if (!agentId) return;
211
- return resolveAgentMainSessionKey({
212
- cfg: params.cfg,
213
- agentId
214
- });
215
- }
216
- function canonicalizeMainSessionAlias(params) {
217
- const raw = params.sessionKey.trim();
218
- if (!raw) return raw;
219
- const agentId = normalizeAgentId(params.agentId);
220
- const mainKey = normalizeMainKey(params.cfg?.session?.mainKey);
221
- const agentMainSessionKey = buildAgentMainSessionKey({
222
- agentId,
223
- mainKey
224
- });
225
- const agentMainAliasKey = buildAgentMainSessionKey({
226
- agentId,
227
- mainKey: "main"
228
- });
229
- const isMainAlias = raw === "main" || raw === mainKey || raw === agentMainSessionKey || raw === agentMainAliasKey;
230
- if (params.cfg?.session?.scope === "global" && isMainAlias) return "global";
231
- if (isMainAlias) return agentMainSessionKey;
232
- return raw;
233
- }
234
-
235
- //#endregion
236
- //#region src/config/sessions/types.ts
237
- function normalizeRuntimeField(value) {
238
- const trimmed = value?.trim();
239
- return trimmed ? trimmed : void 0;
240
- }
241
- function normalizeSessionRuntimeModelFields(entry) {
242
- const normalizedModel = normalizeRuntimeField(entry.model);
243
- const normalizedProvider = normalizeRuntimeField(entry.modelProvider);
244
- let next = entry;
245
- if (!normalizedModel) {
246
- if (entry.model !== void 0 || entry.modelProvider !== void 0) {
247
- next = { ...next };
248
- delete next.model;
249
- delete next.modelProvider;
250
- }
251
- return next;
252
- }
253
- if (entry.model !== normalizedModel) {
254
- if (next === entry) next = { ...next };
255
- next.model = normalizedModel;
256
- }
257
- if (!normalizedProvider) {
258
- if (entry.modelProvider !== void 0) {
259
- if (next === entry) next = { ...next };
260
- delete next.modelProvider;
261
- }
262
- return next;
263
- }
264
- if (entry.modelProvider !== normalizedProvider) {
265
- if (next === entry) next = { ...next };
266
- next.modelProvider = normalizedProvider;
267
- }
268
- return next;
269
- }
270
- function setSessionRuntimeModel(entry, runtime) {
271
- const provider = runtime.provider.trim();
272
- const model = runtime.model.trim();
273
- if (!provider || !model) return false;
274
- entry.modelProvider = provider;
275
- entry.model = model;
276
- return true;
277
- }
278
- function mergeSessionEntry(existing, patch) {
279
- const sessionId = patch.sessionId ?? existing?.sessionId ?? crypto.randomUUID();
280
- const updatedAt = Math.max(existing?.updatedAt ?? 0, patch.updatedAt ?? 0, Date.now());
281
- if (!existing) return normalizeSessionRuntimeModelFields({
282
- ...patch,
283
- sessionId,
284
- updatedAt
285
- });
286
- const next = {
287
- ...existing,
288
- ...patch,
289
- sessionId,
290
- updatedAt
291
- };
292
- if (Object.hasOwn(patch, "model") && !Object.hasOwn(patch, "modelProvider")) {
293
- const patchedModel = normalizeRuntimeField(patch.model);
294
- const existingModel = normalizeRuntimeField(existing.model);
295
- if (patchedModel && patchedModel !== existingModel) delete next.modelProvider;
296
- }
297
- return normalizeSessionRuntimeModelFields(next);
298
- }
299
- function resolveFreshSessionTotalTokens(entry) {
300
- const total = entry?.totalTokens;
301
- if (typeof total !== "number" || !Number.isFinite(total) || total < 0) return;
302
- if (entry?.totalTokensFresh === false) return;
303
- return total;
304
- }
305
- function isSessionTotalTokensFresh(entry) {
306
- return resolveFreshSessionTotalTokens(entry) !== void 0;
307
- }
308
- const DEFAULT_RESET_TRIGGER = "/new";
309
- const DEFAULT_RESET_TRIGGERS = ["/new", "/reset"];
310
- const DEFAULT_IDLE_MINUTES = 60;
311
-
312
- //#endregion
313
- //#region src/config/sessions/reset.ts
314
- const DEFAULT_RESET_MODE = "daily";
315
- const DEFAULT_RESET_AT_HOUR = 4;
316
- const THREAD_SESSION_MARKERS = [":thread:", ":topic:"];
317
- const GROUP_SESSION_MARKERS = [":group:", ":channel:"];
318
- function isThreadSessionKey(sessionKey) {
319
- const normalized = (sessionKey ?? "").toLowerCase();
320
- if (!normalized) return false;
321
- return THREAD_SESSION_MARKERS.some((marker) => normalized.includes(marker));
322
- }
323
- function resolveSessionResetType(params) {
324
- if (params.isThread || isThreadSessionKey(params.sessionKey)) return "thread";
325
- if (params.isGroup) return "group";
326
- const normalized = (params.sessionKey ?? "").toLowerCase();
327
- if (GROUP_SESSION_MARKERS.some((marker) => normalized.includes(marker))) return "group";
328
- return "direct";
329
- }
330
- function resolveThreadFlag(params) {
331
- if (params.messageThreadId != null) return true;
332
- if (params.threadLabel?.trim()) return true;
333
- if (params.threadStarterBody?.trim()) return true;
334
- if (params.parentSessionKey?.trim()) return true;
335
- return isThreadSessionKey(params.sessionKey);
336
- }
337
- function resolveDailyResetAtMs(now, atHour) {
338
- const normalizedAtHour = normalizeResetAtHour(atHour);
339
- const resetAt = new Date(now);
340
- resetAt.setHours(normalizedAtHour, 0, 0, 0);
341
- if (now < resetAt.getTime()) resetAt.setDate(resetAt.getDate() - 1);
342
- return resetAt.getTime();
343
- }
344
- function resolveSessionResetPolicy(params) {
345
- const sessionCfg = params.sessionCfg;
346
- const baseReset = params.resetOverride ?? sessionCfg?.reset;
347
- const typeReset = params.resetOverride ? void 0 : sessionCfg?.resetByType?.[params.resetType] ?? (params.resetType === "direct" ? (sessionCfg?.resetByType)?.dm : void 0);
348
- const hasExplicitReset = Boolean(baseReset || sessionCfg?.resetByType);
349
- const legacyIdleMinutes = params.resetOverride ? void 0 : sessionCfg?.idleMinutes;
350
- const mode = typeReset?.mode ?? baseReset?.mode ?? (!hasExplicitReset && legacyIdleMinutes != null ? "idle" : DEFAULT_RESET_MODE);
351
- const atHour = normalizeResetAtHour(typeReset?.atHour ?? baseReset?.atHour ?? DEFAULT_RESET_AT_HOUR);
352
- const idleMinutesRaw = typeReset?.idleMinutes ?? baseReset?.idleMinutes ?? legacyIdleMinutes;
353
- let idleMinutes;
354
- if (idleMinutesRaw != null) {
355
- const normalized = Math.floor(idleMinutesRaw);
356
- if (Number.isFinite(normalized)) idleMinutes = Math.max(normalized, 1);
357
- } else if (mode === "idle") idleMinutes = DEFAULT_IDLE_MINUTES;
358
- return {
359
- mode,
360
- atHour,
361
- idleMinutes
362
- };
363
- }
364
- function resolveChannelResetConfig(params) {
365
- const resetByChannel = params.sessionCfg?.resetByChannel;
366
- if (!resetByChannel) return;
367
- const normalized = normalizeMessageChannel(params.channel);
368
- const fallback = params.channel?.trim().toLowerCase();
369
- const key = normalized ?? fallback;
370
- if (!key) return;
371
- return resetByChannel[key] ?? resetByChannel[key.toLowerCase()];
372
- }
373
- function evaluateSessionFreshness(params) {
374
- const dailyResetAt = params.policy.mode === "daily" ? resolveDailyResetAtMs(params.now, params.policy.atHour) : void 0;
375
- const idleExpiresAt = params.policy.idleMinutes != null ? params.updatedAt + params.policy.idleMinutes * 6e4 : void 0;
376
- const staleDaily = dailyResetAt != null && params.updatedAt < dailyResetAt;
377
- const staleIdle = idleExpiresAt != null && params.now > idleExpiresAt;
378
- return {
379
- fresh: !(staleDaily || staleIdle),
380
- dailyResetAt,
381
- idleExpiresAt
382
- };
383
- }
384
- function normalizeResetAtHour(value) {
385
- if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_RESET_AT_HOUR;
386
- const normalized = Math.floor(value);
387
- if (!Number.isFinite(normalized)) return DEFAULT_RESET_AT_HOUR;
388
- if (normalized < 0) return 0;
389
- if (normalized > 23) return 23;
390
- return normalized;
391
- }
392
-
393
- //#endregion
394
- //#region src/config/sessions/session-key.ts
395
- function deriveSessionKey(scope, ctx) {
396
- if (scope === "global") return "global";
397
- const resolvedGroup = resolveGroupSessionKey(ctx);
398
- if (resolvedGroup) return resolvedGroup.key;
399
- return (ctx.From ? normalizeE164(ctx.From) : "") || "unknown";
400
- }
401
- /**
402
- * Resolve the session key with a canonical direct-chat bucket (default: "main").
403
- * All non-group direct chats collapse to this bucket; groups stay isolated.
404
- */
405
- function resolveSessionKey(scope, ctx, mainKey) {
406
- const explicit = ctx.SessionKey?.trim();
407
- if (explicit) return explicit.toLowerCase();
408
- const raw = deriveSessionKey(scope, ctx);
409
- if (scope === "global") return raw;
410
- const canonical = buildAgentMainSessionKey({
411
- agentId: DEFAULT_AGENT_ID,
412
- mainKey: normalizeMainKey(mainKey)
413
- });
414
- if (!(raw.includes(":group:") || raw.includes(":channel:"))) return canonical;
415
- return `agent:${DEFAULT_AGENT_ID}:${raw}`;
416
- }
417
-
418
- //#endregion
419
- //#region src/agents/session-write-lock.ts
420
- const CLEANUP_SIGNALS = [
421
- "SIGINT",
422
- "SIGTERM",
423
- "SIGQUIT",
424
- "SIGABRT"
425
- ];
426
- const CLEANUP_STATE_KEY = Symbol.for("remoteclaw.sessionWriteLockCleanupState");
427
- const HELD_LOCKS_KEY = Symbol.for("remoteclaw.sessionWriteLockHeldLocks");
428
- const WATCHDOG_STATE_KEY = Symbol.for("remoteclaw.sessionWriteLockWatchdogState");
429
- const DEFAULT_STALE_MS = 1800 * 1e3;
430
- const DEFAULT_MAX_HOLD_MS = 300 * 1e3;
431
- const DEFAULT_WATCHDOG_INTERVAL_MS = 6e4;
432
- const DEFAULT_TIMEOUT_GRACE_MS = 120 * 1e3;
433
- const HELD_LOCKS = resolveProcessScopedMap(HELD_LOCKS_KEY);
434
- function resolveCleanupState() {
435
- const proc = process;
436
- if (!proc[CLEANUP_STATE_KEY]) proc[CLEANUP_STATE_KEY] = {
437
- registered: false,
438
- cleanupHandlers: /* @__PURE__ */ new Map()
439
- };
440
- return proc[CLEANUP_STATE_KEY];
441
- }
442
- function resolveWatchdogState() {
443
- const proc = process;
444
- if (!proc[WATCHDOG_STATE_KEY]) proc[WATCHDOG_STATE_KEY] = {
445
- started: false,
446
- intervalMs: DEFAULT_WATCHDOG_INTERVAL_MS
447
- };
448
- return proc[WATCHDOG_STATE_KEY];
449
- }
450
- function resolvePositiveMs(value, fallback, opts = {}) {
451
- if (typeof value !== "number" || Number.isNaN(value) || value <= 0) return fallback;
452
- if (value === Number.POSITIVE_INFINITY) return opts.allowInfinity ? value : fallback;
453
- if (!Number.isFinite(value)) return fallback;
454
- return value;
455
- }
456
- async function releaseHeldLock(normalizedSessionFile, held, opts = {}) {
457
- if (HELD_LOCKS.get(normalizedSessionFile) !== held) return false;
458
- if (opts.force) held.count = 0;
459
- else {
460
- held.count -= 1;
461
- if (held.count > 0) return false;
462
- }
463
- if (held.releasePromise) {
464
- await held.releasePromise.catch(() => void 0);
465
- return true;
466
- }
467
- HELD_LOCKS.delete(normalizedSessionFile);
468
- held.releasePromise = (async () => {
469
- try {
470
- await held.handle.close();
471
- } catch {}
472
- try {
473
- await fsp.rm(held.lockPath, { force: true });
474
- } catch {}
475
- })();
476
- try {
477
- await held.releasePromise;
478
- return true;
479
- } finally {
480
- held.releasePromise = void 0;
481
- }
482
- }
483
- /**
484
- * Synchronously release all held locks.
485
- * Used during process exit when async operations aren't reliable.
486
- */
487
- function releaseAllLocksSync() {
488
- for (const [sessionFile, held] of HELD_LOCKS) {
489
- try {
490
- if (typeof held.handle.close === "function") held.handle.close().catch(() => {});
491
- } catch {}
492
- try {
493
- fs.rmSync(held.lockPath, { force: true });
494
- } catch {}
495
- HELD_LOCKS.delete(sessionFile);
496
- }
497
- }
498
- async function runLockWatchdogCheck(nowMs = Date.now()) {
499
- let released = 0;
500
- for (const [sessionFile, held] of HELD_LOCKS.entries()) {
501
- const heldForMs = nowMs - held.acquiredAt;
502
- if (heldForMs <= held.maxHoldMs) continue;
503
- console.warn(`[session-write-lock] releasing lock held for ${heldForMs}ms (max=${held.maxHoldMs}ms): ${held.lockPath}`);
504
- if (await releaseHeldLock(sessionFile, held, { force: true })) released += 1;
505
- }
506
- return released;
507
- }
508
- function ensureWatchdogStarted(intervalMs) {
509
- const watchdogState = resolveWatchdogState();
510
- if (watchdogState.started) return;
511
- watchdogState.started = true;
512
- watchdogState.intervalMs = intervalMs;
513
- watchdogState.timer = setInterval(() => {
514
- runLockWatchdogCheck().catch(() => {});
515
- }, intervalMs);
516
- watchdogState.timer.unref?.();
517
- }
518
- function handleTerminationSignal(signal) {
519
- releaseAllLocksSync();
520
- const cleanupState = resolveCleanupState();
521
- if (process.listenerCount(signal) === 1) {
522
- const handler = cleanupState.cleanupHandlers.get(signal);
523
- if (handler) {
524
- process.off(signal, handler);
525
- cleanupState.cleanupHandlers.delete(signal);
526
- }
527
- try {
528
- process.kill(process.pid, signal);
529
- } catch {}
530
- }
531
- }
532
- function registerCleanupHandlers() {
533
- const cleanupState = resolveCleanupState();
534
- if (!cleanupState.registered) {
535
- cleanupState.registered = true;
536
- process.on("exit", () => {
537
- releaseAllLocksSync();
538
- });
539
- }
540
- ensureWatchdogStarted(DEFAULT_WATCHDOG_INTERVAL_MS);
541
- for (const signal of CLEANUP_SIGNALS) {
542
- if (cleanupState.cleanupHandlers.has(signal)) continue;
543
- try {
544
- const handler = () => handleTerminationSignal(signal);
545
- cleanupState.cleanupHandlers.set(signal, handler);
546
- process.on(signal, handler);
547
- } catch {}
548
- }
549
- }
550
- async function readLockPayload(lockPath) {
551
- try {
552
- const raw = await fsp.readFile(lockPath, "utf8");
553
- const parsed = JSON.parse(raw);
554
- const payload = {};
555
- if (typeof parsed.pid === "number") payload.pid = parsed.pid;
556
- if (typeof parsed.createdAt === "string") payload.createdAt = parsed.createdAt;
557
- return payload;
558
- } catch {
559
- return null;
560
- }
561
- }
562
- function inspectLockPayload(payload, staleMs, nowMs) {
563
- const pid = typeof payload?.pid === "number" ? payload.pid : null;
564
- const pidAlive = pid !== null ? isPidAlive(pid) : false;
565
- const createdAt = typeof payload?.createdAt === "string" ? payload.createdAt : null;
566
- const createdAtMs = createdAt ? Date.parse(createdAt) : NaN;
567
- const ageMs = Number.isFinite(createdAtMs) ? Math.max(0, nowMs - createdAtMs) : null;
568
- const staleReasons = [];
569
- if (pid === null) staleReasons.push("missing-pid");
570
- else if (!pidAlive) staleReasons.push("dead-pid");
571
- if (ageMs === null) staleReasons.push("invalid-createdAt");
572
- else if (ageMs > staleMs) staleReasons.push("too-old");
573
- return {
574
- pid,
575
- pidAlive,
576
- createdAt,
577
- ageMs,
578
- stale: staleReasons.length > 0,
579
- staleReasons
580
- };
581
- }
582
- function lockInspectionNeedsMtimeStaleFallback(details) {
583
- return details.stale && details.staleReasons.every((reason) => reason === "missing-pid" || reason === "invalid-createdAt");
584
- }
585
- async function shouldReclaimContendedLockFile(lockPath, details, staleMs, nowMs) {
586
- if (!details.stale) return false;
587
- if (!lockInspectionNeedsMtimeStaleFallback(details)) return true;
588
- try {
589
- const stat = await fsp.stat(lockPath);
590
- return Math.max(0, nowMs - stat.mtimeMs) > staleMs;
591
- } catch (error) {
592
- return error?.code !== "ENOENT";
593
- }
594
- }
595
- async function cleanStaleLockFiles(params) {
596
- const sessionsDir = path.resolve(params.sessionsDir);
597
- const staleMs = resolvePositiveMs(params.staleMs, DEFAULT_STALE_MS);
598
- const removeStale = params.removeStale !== false;
599
- const nowMs = params.nowMs ?? Date.now();
600
- let entries = [];
601
- try {
602
- entries = await fsp.readdir(sessionsDir, { withFileTypes: true });
603
- } catch (err) {
604
- if (err.code === "ENOENT") return {
605
- locks: [],
606
- cleaned: []
607
- };
608
- throw err;
609
- }
610
- const locks = [];
611
- const cleaned = [];
612
- const lockEntries = entries.filter((entry) => entry.name.endsWith(".jsonl.lock")).toSorted((a, b) => a.name.localeCompare(b.name));
613
- for (const entry of lockEntries) {
614
- const lockPath = path.join(sessionsDir, entry.name);
615
- const lockInfo = {
616
- lockPath,
617
- ...inspectLockPayload(await readLockPayload(lockPath), staleMs, nowMs),
618
- removed: false
619
- };
620
- if (lockInfo.stale && removeStale) {
621
- await fsp.rm(lockPath, { force: true });
622
- lockInfo.removed = true;
623
- cleaned.push(lockInfo);
624
- params.log?.warn?.(`removed stale session lock: ${lockPath} (${lockInfo.staleReasons.join(", ") || "unknown"})`);
625
- }
626
- locks.push(lockInfo);
627
- }
628
- return {
629
- locks,
630
- cleaned
631
- };
632
- }
633
- async function acquireSessionWriteLock(params) {
634
- registerCleanupHandlers();
635
- const timeoutMs = resolvePositiveMs(params.timeoutMs, 1e4, { allowInfinity: true });
636
- const staleMs = resolvePositiveMs(params.staleMs, DEFAULT_STALE_MS);
637
- const maxHoldMs = resolvePositiveMs(params.maxHoldMs, DEFAULT_MAX_HOLD_MS);
638
- const sessionFile = path.resolve(params.sessionFile);
639
- const sessionDir = path.dirname(sessionFile);
640
- await fsp.mkdir(sessionDir, { recursive: true });
641
- let normalizedDir = sessionDir;
642
- try {
643
- normalizedDir = await fsp.realpath(sessionDir);
644
- } catch {}
645
- const normalizedSessionFile = path.join(normalizedDir, path.basename(sessionFile));
646
- const lockPath = `${normalizedSessionFile}.lock`;
647
- const allowReentrant = params.allowReentrant ?? true;
648
- const held = HELD_LOCKS.get(normalizedSessionFile);
649
- if (allowReentrant && held) {
650
- held.count += 1;
651
- return { release: async () => {
652
- await releaseHeldLock(normalizedSessionFile, held);
653
- } };
654
- }
655
- const startedAt = Date.now();
656
- let attempt = 0;
657
- while (Date.now() - startedAt < timeoutMs) {
658
- attempt += 1;
659
- let handle = null;
660
- try {
661
- handle = await fsp.open(lockPath, "wx");
662
- const createdAt = (/* @__PURE__ */ new Date()).toISOString();
663
- await handle.writeFile(JSON.stringify({
664
- pid: process.pid,
665
- createdAt
666
- }, null, 2), "utf8");
667
- const createdHeld = {
668
- count: 1,
669
- handle,
670
- lockPath,
671
- acquiredAt: Date.now(),
672
- maxHoldMs
673
- };
674
- HELD_LOCKS.set(normalizedSessionFile, createdHeld);
675
- return { release: async () => {
676
- await releaseHeldLock(normalizedSessionFile, createdHeld);
677
- } };
678
- } catch (err) {
679
- if (handle) {
680
- try {
681
- await handle.close();
682
- } catch {}
683
- try {
684
- await fsp.rm(lockPath, { force: true });
685
- } catch {}
686
- }
687
- if (err.code !== "EEXIST") throw err;
688
- const payload = await readLockPayload(lockPath);
689
- const nowMs = Date.now();
690
- if (await shouldReclaimContendedLockFile(lockPath, inspectLockPayload(payload, staleMs, nowMs), staleMs, nowMs)) {
691
- await fsp.rm(lockPath, { force: true });
692
- continue;
693
- }
694
- const delay = Math.min(1e3, 50 * attempt);
695
- await new Promise((r) => setTimeout(r, delay));
696
- }
697
- }
698
- const payload = await readLockPayload(lockPath);
699
- const owner = typeof payload?.pid === "number" ? `pid=${payload.pid}` : "unknown";
700
- throw new Error(`session file locked (timeout ${timeoutMs}ms): ${owner} ${lockPath}`);
701
- }
702
- const __testing = {
703
- cleanupSignals: [...CLEANUP_SIGNALS],
704
- handleTerminationSignal,
705
- releaseAllLocksSync,
706
- runLockWatchdogCheck
707
- };
708
-
709
- //#endregion
710
- //#region src/utils/directive-tags.ts
711
- const AUDIO_TAG_RE = /\[\[\s*audio_as_voice\s*\]\]/gi;
712
- const REPLY_TAG_RE = /\[\[\s*(?:reply_to_current|reply_to\s*:\s*([^\]\n]+))\s*\]\]/gi;
713
- function normalizeDirectiveWhitespace(text) {
714
- return text.replace(/[ \t]+/g, " ").replace(/[ \t]*\n[ \t]*/g, "\n").trim();
715
- }
716
- function stripInlineDirectiveTagsForDisplay(text) {
717
- if (!text) return {
718
- text,
719
- changed: false
720
- };
721
- const stripped = text.replace(AUDIO_TAG_RE, "").replace(REPLY_TAG_RE, "");
722
- return {
723
- text: stripped,
724
- changed: stripped !== text
725
- };
726
- }
727
- function isMessageTextPart(part) {
728
- return Boolean(part) && part?.type === "text" && typeof part.text === "string";
729
- }
730
- /**
731
- * Strips inline directive tags from message text blocks while preserving message shape.
732
- * Empty post-strip text stays empty-string to preserve caller semantics.
733
- */
734
- function stripInlineDirectiveTagsFromMessageForDisplay(message) {
735
- if (!message) return message;
736
- if (!Array.isArray(message.content)) return message;
737
- const cleaned = message.content.map((part) => {
738
- if (!part || typeof part !== "object") return part;
739
- const record = part;
740
- if (!isMessageTextPart(record)) return part;
741
- return {
742
- ...record,
743
- text: stripInlineDirectiveTagsForDisplay(record.text).text
744
- };
745
- });
746
- return {
747
- ...message,
748
- content: cleaned
749
- };
750
- }
751
- function parseInlineDirectives(text, options = {}) {
752
- const { currentMessageId, stripAudioTag = true, stripReplyTags = true } = options;
753
- if (!text) return {
754
- text: "",
755
- audioAsVoice: false,
756
- replyToCurrent: false,
757
- hasAudioTag: false,
758
- hasReplyTag: false
759
- };
760
- let cleaned = text;
761
- let audioAsVoice = false;
762
- let hasAudioTag = false;
763
- let hasReplyTag = false;
764
- let sawCurrent = false;
765
- let lastExplicitId;
766
- cleaned = cleaned.replace(AUDIO_TAG_RE, (match) => {
767
- audioAsVoice = true;
768
- hasAudioTag = true;
769
- return stripAudioTag ? " " : match;
770
- });
771
- cleaned = cleaned.replace(REPLY_TAG_RE, (match, idRaw) => {
772
- hasReplyTag = true;
773
- if (idRaw === void 0) sawCurrent = true;
774
- else {
775
- const id = idRaw.trim();
776
- if (id) lastExplicitId = id;
777
- }
778
- return stripReplyTags ? " " : match;
779
- });
780
- cleaned = normalizeDirectiveWhitespace(cleaned);
781
- const replyToId = lastExplicitId ?? (sawCurrent ? currentMessageId?.trim() || void 0 : void 0);
782
- return {
783
- text: cleaned,
784
- audioAsVoice,
785
- replyToId,
786
- replyToExplicitId: lastExplicitId,
787
- replyToCurrent: sawCurrent,
788
- hasAudioTag,
789
- hasReplyTag
790
- };
791
- }
792
-
793
- //#endregion
794
- //#region src/gateway/chat-sanitize.ts
795
- function stripEnvelopeFromContentWithRole(content, stripUserEnvelope) {
796
- let changed = false;
797
- return {
798
- content: content.map((item) => {
799
- if (!item || typeof item !== "object") return item;
800
- const entry = item;
801
- if (entry.type !== "text" || typeof entry.text !== "string") return item;
802
- const inboundStripped = stripInboundMetadata(entry.text);
803
- const stripped = stripUserEnvelope ? stripMessageIdHints(stripEnvelope(inboundStripped)) : inboundStripped;
804
- if (stripped === entry.text) return item;
805
- changed = true;
806
- return {
807
- ...entry,
808
- text: stripped
809
- };
810
- }),
811
- changed
812
- };
813
- }
814
- function stripEnvelopeFromMessage(message) {
815
- if (!message || typeof message !== "object") return message;
816
- const entry = message;
817
- const stripUserEnvelope = (typeof entry.role === "string" ? entry.role.toLowerCase() : "") === "user";
818
- let changed = false;
819
- const next = { ...entry };
820
- if (typeof entry.content === "string") {
821
- const inboundStripped = stripInboundMetadata(entry.content);
822
- const stripped = stripUserEnvelope ? stripMessageIdHints(stripEnvelope(inboundStripped)) : inboundStripped;
823
- if (stripped !== entry.content) {
824
- next.content = stripped;
825
- changed = true;
826
- }
827
- } else if (Array.isArray(entry.content)) {
828
- const updated = stripEnvelopeFromContentWithRole(entry.content, stripUserEnvelope);
829
- if (updated.changed) {
830
- next.content = updated.content;
831
- changed = true;
832
- }
833
- } else if (typeof entry.text === "string") {
834
- const inboundStripped = stripInboundMetadata(entry.text);
835
- const stripped = stripUserEnvelope ? stripMessageIdHints(stripEnvelope(inboundStripped)) : inboundStripped;
836
- if (stripped !== entry.text) {
837
- next.text = stripped;
838
- changed = true;
839
- }
840
- }
841
- return changed ? next : message;
842
- }
843
- function stripEnvelopeFromMessages(messages) {
844
- if (messages.length === 0) return messages;
845
- let changed = false;
846
- const next = messages.map((message) => {
847
- const stripped = stripEnvelopeFromMessage(message);
848
- if (stripped !== message) changed = true;
849
- return stripped;
850
- });
851
- return changed ? next : messages;
852
- }
853
-
854
- //#endregion
855
- //#region src/gateway/session-utils.fs.ts
856
- const sessionTitleFieldsCache = /* @__PURE__ */ new Map();
857
- const MAX_SESSION_TITLE_FIELDS_CACHE_ENTRIES = 5e3;
858
- function readSessionTitleFieldsCacheKey(filePath, opts) {
859
- return `${filePath}\t${opts?.includeInterSession === true ? "1" : "0"}`;
860
- }
861
- function getCachedSessionTitleFields(cacheKey, stat) {
862
- const cached = sessionTitleFieldsCache.get(cacheKey);
863
- if (!cached) return null;
864
- if (cached.mtimeMs !== stat.mtimeMs || cached.size !== stat.size) {
865
- sessionTitleFieldsCache.delete(cacheKey);
866
- return null;
867
- }
868
- sessionTitleFieldsCache.delete(cacheKey);
869
- sessionTitleFieldsCache.set(cacheKey, cached);
870
- return {
871
- firstUserMessage: cached.firstUserMessage,
872
- lastMessagePreview: cached.lastMessagePreview
873
- };
874
- }
875
- function setCachedSessionTitleFields(cacheKey, stat, value) {
876
- sessionTitleFieldsCache.set(cacheKey, {
877
- ...value,
878
- mtimeMs: stat.mtimeMs,
879
- size: stat.size
880
- });
881
- while (sessionTitleFieldsCache.size > MAX_SESSION_TITLE_FIELDS_CACHE_ENTRIES) {
882
- const oldestKey = sessionTitleFieldsCache.keys().next().value;
883
- if (typeof oldestKey !== "string" || !oldestKey) break;
884
- sessionTitleFieldsCache.delete(oldestKey);
885
- }
886
- }
887
- function readSessionMessages(sessionId, storePath, sessionFile) {
888
- const filePath = resolveSessionTranscriptCandidates(sessionId, storePath, sessionFile).find((p) => fs.existsSync(p));
889
- if (!filePath) return [];
890
- const lines = fs.readFileSync(filePath, "utf-8").split(/\r?\n/);
891
- const messages = [];
892
- for (const line of lines) {
893
- if (!line.trim()) continue;
894
- try {
895
- const parsed = JSON.parse(line);
896
- if (parsed?.message) {
897
- messages.push(parsed.message);
898
- continue;
899
- }
900
- if (parsed?.type === "compaction") {
901
- const ts = typeof parsed.timestamp === "string" ? Date.parse(parsed.timestamp) : NaN;
902
- const timestamp = Number.isFinite(ts) ? ts : Date.now();
903
- messages.push({
904
- role: "system",
905
- content: [{
906
- type: "text",
907
- text: "Compaction"
908
- }],
909
- timestamp,
910
- __remoteclaw: {
911
- kind: "compaction",
912
- id: typeof parsed.id === "string" ? parsed.id : void 0
913
- }
914
- });
915
- }
916
- } catch {}
917
- }
918
- return messages;
919
- }
920
- function resolveSessionTranscriptCandidates(sessionId, storePath, sessionFile, agentId) {
921
- const candidates = [];
922
- const pushCandidate = (resolve) => {
923
- try {
924
- candidates.push(resolve());
925
- } catch {}
926
- };
927
- if (storePath) {
928
- const sessionsDir = path.dirname(storePath);
929
- if (sessionFile) pushCandidate(() => resolveSessionFilePath(sessionId, { sessionFile }, {
930
- sessionsDir,
931
- agentId
932
- }));
933
- pushCandidate(() => resolveSessionTranscriptPathInDir(sessionId, sessionsDir));
934
- } else if (sessionFile) if (agentId) pushCandidate(() => resolveSessionFilePath(sessionId, { sessionFile }, { agentId }));
935
- else {
936
- const trimmed = sessionFile.trim();
937
- if (trimmed) candidates.push(path.resolve(trimmed));
938
- }
939
- if (agentId) pushCandidate(() => resolveSessionTranscriptPath(sessionId, agentId));
940
- const home = resolveRequiredHomeDir(process.env, os.homedir);
941
- const legacyDir = path.join(home, ".remoteclaw", "sessions");
942
- pushCandidate(() => resolveSessionTranscriptPathInDir(sessionId, legacyDir));
943
- return Array.from(new Set(candidates));
944
- }
945
- function canonicalizePathForComparison$1(filePath) {
946
- const resolved = path.resolve(filePath);
947
- try {
948
- return fs.realpathSync(resolved);
949
- } catch {
950
- return resolved;
951
- }
952
- }
953
- function archiveFileOnDisk(filePath, reason) {
954
- const archived = `${filePath}.${reason}.${formatSessionArchiveTimestamp()}`;
955
- fs.renameSync(filePath, archived);
956
- return archived;
957
- }
958
- /**
959
- * Archives all transcript files for a given session.
960
- * Best-effort: silently skips files that don't exist or fail to rename.
961
- */
962
- function archiveSessionTranscripts(opts) {
963
- const archived = [];
964
- const storeDir = opts.restrictToStoreDir && opts.storePath ? canonicalizePathForComparison$1(path.dirname(opts.storePath)) : null;
965
- for (const candidate of resolveSessionTranscriptCandidates(opts.sessionId, opts.storePath, opts.sessionFile, opts.agentId)) {
966
- const candidatePath = canonicalizePathForComparison$1(candidate);
967
- if (storeDir) {
968
- const relative = path.relative(storeDir, candidatePath);
969
- if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) continue;
970
- }
971
- if (!fs.existsSync(candidatePath)) continue;
972
- try {
973
- archived.push(archiveFileOnDisk(candidatePath, opts.reason));
974
- } catch {}
975
- }
976
- return archived;
977
- }
978
- async function cleanupArchivedSessionTranscripts(opts) {
979
- if (!Number.isFinite(opts.olderThanMs) || opts.olderThanMs < 0) return {
980
- removed: 0,
981
- scanned: 0
982
- };
983
- const now = opts.nowMs ?? Date.now();
984
- const reason = opts.reason ?? "deleted";
985
- const directories = Array.from(new Set(opts.directories.map((dir) => path.resolve(dir))));
986
- let removed = 0;
987
- let scanned = 0;
988
- for (const dir of directories) {
989
- const entries = await fs.promises.readdir(dir).catch(() => []);
990
- for (const entry of entries) {
991
- const timestamp = parseSessionArchiveTimestamp(entry, reason);
992
- if (timestamp == null) continue;
993
- scanned += 1;
994
- if (now - timestamp <= opts.olderThanMs) continue;
995
- const fullPath = path.join(dir, entry);
996
- if (!(await fs.promises.stat(fullPath).catch(() => null))?.isFile()) continue;
997
- await fs.promises.rm(fullPath).catch(() => void 0);
998
- removed += 1;
999
- }
1000
- }
1001
- return {
1002
- removed,
1003
- scanned
1004
- };
1005
- }
1006
- function jsonUtf8Bytes(value) {
1007
- try {
1008
- return Buffer.byteLength(JSON.stringify(value), "utf8");
1009
- } catch {
1010
- return Buffer.byteLength(String(value), "utf8");
1011
- }
1012
- }
1013
- function capArrayByJsonBytes(items, maxBytes) {
1014
- if (items.length === 0) return {
1015
- items,
1016
- bytes: 2
1017
- };
1018
- const parts = items.map((item) => jsonUtf8Bytes(item));
1019
- let bytes = 2 + parts.reduce((a, b) => a + b, 0) + (items.length - 1);
1020
- let start = 0;
1021
- while (bytes > maxBytes && start < items.length - 1) {
1022
- bytes -= parts[start] + 1;
1023
- start += 1;
1024
- }
1025
- return {
1026
- items: start > 0 ? items.slice(start) : items,
1027
- bytes
1028
- };
1029
- }
1030
- const MAX_LINES_TO_SCAN = 10;
1031
- function readSessionTitleFieldsFromTranscript(sessionId, storePath, sessionFile, agentId, opts) {
1032
- const filePath = resolveSessionTranscriptCandidates(sessionId, storePath, sessionFile, agentId).find((p) => fs.existsSync(p));
1033
- if (!filePath) return {
1034
- firstUserMessage: null,
1035
- lastMessagePreview: null
1036
- };
1037
- let stat;
1038
- try {
1039
- stat = fs.statSync(filePath);
1040
- } catch {
1041
- return {
1042
- firstUserMessage: null,
1043
- lastMessagePreview: null
1044
- };
1045
- }
1046
- const cacheKey = readSessionTitleFieldsCacheKey(filePath, opts);
1047
- const cached = getCachedSessionTitleFields(cacheKey, stat);
1048
- if (cached) return cached;
1049
- if (stat.size === 0) {
1050
- const empty = {
1051
- firstUserMessage: null,
1052
- lastMessagePreview: null
1053
- };
1054
- setCachedSessionTitleFields(cacheKey, stat, empty);
1055
- return empty;
1056
- }
1057
- let fd = null;
1058
- try {
1059
- fd = fs.openSync(filePath, "r");
1060
- const size = stat.size;
1061
- let firstUserMessage = null;
1062
- try {
1063
- const chunk = readTranscriptHeadChunk(fd);
1064
- if (chunk) firstUserMessage = extractFirstUserMessageFromTranscriptChunk(chunk, opts);
1065
- } catch {}
1066
- let lastMessagePreview = null;
1067
- try {
1068
- lastMessagePreview = readLastMessagePreviewFromOpenTranscript({
1069
- fd,
1070
- size
1071
- });
1072
- } catch {}
1073
- const result = {
1074
- firstUserMessage,
1075
- lastMessagePreview
1076
- };
1077
- setCachedSessionTitleFields(cacheKey, stat, result);
1078
- return result;
1079
- } catch {
1080
- return {
1081
- firstUserMessage: null,
1082
- lastMessagePreview: null
1083
- };
1084
- } finally {
1085
- if (fd !== null) try {
1086
- fs.closeSync(fd);
1087
- } catch {}
1088
- }
1089
- }
1090
- function extractTextFromContent(content) {
1091
- if (typeof content === "string") return stripInlineDirectiveTagsForDisplay(content).text.trim() || null;
1092
- if (!Array.isArray(content)) return null;
1093
- for (const part of content) {
1094
- if (!part || typeof part.text !== "string") continue;
1095
- if (part.type === "text" || part.type === "output_text" || part.type === "input_text") {
1096
- const normalized = stripInlineDirectiveTagsForDisplay(part.text).text.trim();
1097
- if (normalized) return normalized;
1098
- }
1099
- }
1100
- return null;
1101
- }
1102
- function readTranscriptHeadChunk(fd, maxBytes = 8192) {
1103
- const buf = Buffer.alloc(maxBytes);
1104
- const bytesRead = fs.readSync(fd, buf, 0, buf.length, 0);
1105
- if (bytesRead <= 0) return null;
1106
- return buf.toString("utf-8", 0, bytesRead);
1107
- }
1108
- function extractFirstUserMessageFromTranscriptChunk(chunk, opts) {
1109
- const lines = chunk.split(/\r?\n/).slice(0, MAX_LINES_TO_SCAN);
1110
- for (const line of lines) {
1111
- if (!line.trim()) continue;
1112
- try {
1113
- const msg = JSON.parse(line)?.message;
1114
- if (msg?.role !== "user") continue;
1115
- if (opts?.includeInterSession !== true && hasInterSessionUserProvenance(msg)) continue;
1116
- const text = extractTextFromContent(msg.content);
1117
- if (text) return text;
1118
- } catch {}
1119
- }
1120
- return null;
1121
- }
1122
- const LAST_MSG_MAX_BYTES = 16384;
1123
- const LAST_MSG_MAX_LINES = 20;
1124
- function readLastMessagePreviewFromOpenTranscript(params) {
1125
- const readStart = Math.max(0, params.size - LAST_MSG_MAX_BYTES);
1126
- const readLen = Math.min(params.size, LAST_MSG_MAX_BYTES);
1127
- const buf = Buffer.alloc(readLen);
1128
- fs.readSync(params.fd, buf, 0, readLen, readStart);
1129
- const tailLines = buf.toString("utf-8").split(/\r?\n/).filter((l) => l.trim()).slice(-LAST_MSG_MAX_LINES);
1130
- for (let i = tailLines.length - 1; i >= 0; i--) {
1131
- const line = tailLines[i];
1132
- try {
1133
- const msg = JSON.parse(line)?.message;
1134
- if (msg?.role !== "user" && msg?.role !== "assistant") continue;
1135
- const text = extractTextFromContent(msg.content);
1136
- if (text) return text;
1137
- } catch {}
1138
- }
1139
- return null;
1140
- }
1141
- const PREVIEW_READ_SIZES = [
1142
- 64 * 1024,
1143
- 256 * 1024,
1144
- 1024 * 1024
1145
- ];
1146
- const PREVIEW_MAX_LINES = 200;
1147
- function normalizeRole(role, isTool) {
1148
- if (isTool) return "tool";
1149
- switch ((role ?? "").toLowerCase()) {
1150
- case "user": return "user";
1151
- case "assistant": return "assistant";
1152
- case "system": return "system";
1153
- case "tool": return "tool";
1154
- default: return "other";
1155
- }
1156
- }
1157
- function truncatePreviewText(text, maxChars) {
1158
- if (maxChars <= 0 || text.length <= maxChars) return text;
1159
- if (maxChars <= 3) return text.slice(0, maxChars);
1160
- return `${text.slice(0, maxChars - 3)}...`;
1161
- }
1162
- function extractPreviewText(message) {
1163
- if (typeof message.content === "string") {
1164
- const normalized = stripInlineDirectiveTagsForDisplay(message.content).text.trim();
1165
- return normalized ? normalized : null;
1166
- }
1167
- if (Array.isArray(message.content)) {
1168
- const parts = message.content.map((entry) => typeof entry?.text === "string" ? stripInlineDirectiveTagsForDisplay(entry.text).text : "").filter((text) => text.trim().length > 0);
1169
- if (parts.length > 0) return parts.join("\n").trim();
1170
- }
1171
- if (typeof message.text === "string") {
1172
- const normalized = stripInlineDirectiveTagsForDisplay(message.text).text.trim();
1173
- return normalized ? normalized : null;
1174
- }
1175
- return null;
1176
- }
1177
- function isToolCall(message) {
1178
- return hasToolCall(message);
1179
- }
1180
- function extractToolNames(message) {
1181
- return extractToolCallNames(message);
1182
- }
1183
- function extractMediaSummary(message) {
1184
- if (!Array.isArray(message.content)) return null;
1185
- for (const entry of message.content) {
1186
- const raw = typeof entry?.type === "string" ? entry.type.trim().toLowerCase() : "";
1187
- if (!raw || raw === "text" || raw === "toolcall" || raw === "tool_call") continue;
1188
- return `[${raw}]`;
1189
- }
1190
- return null;
1191
- }
1192
- function buildPreviewItems(messages, maxItems, maxChars) {
1193
- const items = [];
1194
- for (const message of messages) {
1195
- const toolCall = isToolCall(message);
1196
- const role = normalizeRole(message.role, toolCall);
1197
- let text = extractPreviewText(message);
1198
- if (!text) {
1199
- const toolNames = extractToolNames(message);
1200
- if (toolNames.length > 0) {
1201
- const shown = toolNames.slice(0, 2);
1202
- const overflow = toolNames.length - shown.length;
1203
- text = `call ${shown.join(", ")}`;
1204
- if (overflow > 0) text += ` +${overflow}`;
1205
- }
1206
- }
1207
- if (!text) text = extractMediaSummary(message);
1208
- if (!text) continue;
1209
- let trimmed = text.trim();
1210
- if (!trimmed) continue;
1211
- if (role === "user") trimmed = stripEnvelope(trimmed);
1212
- trimmed = truncatePreviewText(trimmed, maxChars);
1213
- items.push({
1214
- role,
1215
- text: trimmed
1216
- });
1217
- }
1218
- if (items.length <= maxItems) return items;
1219
- return items.slice(-maxItems);
1220
- }
1221
- function readRecentMessagesFromTranscript(filePath, maxMessages, readBytes) {
1222
- let fd = null;
1223
- try {
1224
- fd = fs.openSync(filePath, "r");
1225
- const size = fs.fstatSync(fd).size;
1226
- if (size === 0) return [];
1227
- const readStart = Math.max(0, size - readBytes);
1228
- const readLen = Math.min(size, readBytes);
1229
- const buf = Buffer.alloc(readLen);
1230
- fs.readSync(fd, buf, 0, readLen, readStart);
1231
- const tailLines = buf.toString("utf-8").split(/\r?\n/).filter((l) => l.trim()).slice(-PREVIEW_MAX_LINES);
1232
- const collected = [];
1233
- for (let i = tailLines.length - 1; i >= 0; i--) {
1234
- const line = tailLines[i];
1235
- try {
1236
- const msg = JSON.parse(line)?.message;
1237
- if (msg && typeof msg === "object") {
1238
- collected.push(msg);
1239
- if (collected.length >= maxMessages) break;
1240
- }
1241
- } catch {}
1242
- }
1243
- return collected.toReversed();
1244
- } catch {
1245
- return [];
1246
- } finally {
1247
- if (fd !== null) fs.closeSync(fd);
1248
- }
1249
- }
1250
- function readSessionPreviewItemsFromTranscript(sessionId, storePath, sessionFile, agentId, maxItems, maxChars) {
1251
- const filePath = resolveSessionTranscriptCandidates(sessionId, storePath, sessionFile, agentId).find((p) => fs.existsSync(p));
1252
- if (!filePath) return [];
1253
- const boundedItems = Math.max(1, Math.min(maxItems, 50));
1254
- const boundedChars = Math.max(20, Math.min(maxChars, 2e3));
1255
- for (const readSize of PREVIEW_READ_SIZES) {
1256
- const messages = readRecentMessagesFromTranscript(filePath, boundedItems, readSize);
1257
- if (messages.length > 0 || readSize === PREVIEW_READ_SIZES[PREVIEW_READ_SIZES.length - 1]) return buildPreviewItems(messages, boundedItems, boundedChars);
1258
- }
1259
- return [];
1260
- }
1261
-
1262
- //#endregion
1263
- //#region src/utils/account-id.ts
1264
- function normalizeAccountId(value) {
1265
- return normalizeOptionalAccountId(value);
1266
- }
1267
-
1268
- //#endregion
1269
- //#region src/utils/delivery-context.ts
1270
- function normalizeDeliveryContext(context) {
1271
- if (!context) return;
1272
- const channel = typeof context.channel === "string" ? normalizeMessageChannel(context.channel) ?? context.channel.trim() : void 0;
1273
- const to = typeof context.to === "string" ? context.to.trim() : void 0;
1274
- const accountId = normalizeAccountId(context.accountId);
1275
- const threadId = typeof context.threadId === "number" && Number.isFinite(context.threadId) ? Math.trunc(context.threadId) : typeof context.threadId === "string" ? context.threadId.trim() : void 0;
1276
- const normalizedThreadId = typeof threadId === "string" ? threadId ? threadId : void 0 : threadId;
1277
- if (!channel && !to && !accountId && normalizedThreadId == null) return;
1278
- const normalized = {
1279
- channel: channel || void 0,
1280
- to: to || void 0,
1281
- accountId
1282
- };
1283
- if (normalizedThreadId != null) normalized.threadId = normalizedThreadId;
1284
- return normalized;
1285
- }
1286
- function normalizeSessionDeliveryFields(source) {
1287
- if (!source) return {
1288
- deliveryContext: void 0,
1289
- lastChannel: void 0,
1290
- lastTo: void 0,
1291
- lastAccountId: void 0,
1292
- lastThreadId: void 0
1293
- };
1294
- const merged = mergeDeliveryContext(normalizeDeliveryContext({
1295
- channel: source.lastChannel ?? source.channel,
1296
- to: source.lastTo,
1297
- accountId: source.lastAccountId,
1298
- threadId: source.lastThreadId
1299
- }), normalizeDeliveryContext(source.deliveryContext));
1300
- if (!merged) return {
1301
- deliveryContext: void 0,
1302
- lastChannel: void 0,
1303
- lastTo: void 0,
1304
- lastAccountId: void 0,
1305
- lastThreadId: void 0
1306
- };
1307
- return {
1308
- deliveryContext: merged,
1309
- lastChannel: merged.channel,
1310
- lastTo: merged.to,
1311
- lastAccountId: merged.accountId,
1312
- lastThreadId: merged.threadId
1313
- };
1314
- }
1315
- function deliveryContextFromSession(entry) {
1316
- if (!entry) return;
1317
- return normalizeSessionDeliveryFields({
1318
- channel: entry.channel,
1319
- lastChannel: entry.lastChannel,
1320
- lastTo: entry.lastTo,
1321
- lastAccountId: entry.lastAccountId,
1322
- lastThreadId: entry.lastThreadId ?? entry.deliveryContext?.threadId ?? entry.origin?.threadId,
1323
- deliveryContext: entry.deliveryContext
1324
- }).deliveryContext;
1325
- }
1326
- function mergeDeliveryContext(primary, fallback) {
1327
- const normalizedPrimary = normalizeDeliveryContext(primary);
1328
- const normalizedFallback = normalizeDeliveryContext(fallback);
1329
- if (!normalizedPrimary && !normalizedFallback) return;
1330
- return normalizeDeliveryContext({
1331
- channel: normalizedPrimary?.channel ?? normalizedFallback?.channel,
1332
- to: normalizedPrimary?.to ?? normalizedFallback?.to,
1333
- accountId: normalizedPrimary?.accountId ?? normalizedFallback?.accountId,
1334
- threadId: normalizedPrimary?.threadId ?? normalizedFallback?.threadId
1335
- });
1336
- }
1337
-
1338
- //#endregion
1339
- //#region src/config/cache-utils.ts
1340
- function resolveCacheTtlMs(params) {
1341
- const { envValue, defaultTtlMs } = params;
1342
- if (envValue) {
1343
- const parsed = Number.parseInt(envValue, 10);
1344
- if (Number.isFinite(parsed) && parsed >= 0) return parsed;
1345
- }
1346
- return defaultTtlMs;
1347
- }
1348
- function isCacheEnabled(ttlMs) {
1349
- return ttlMs > 0;
1350
- }
1351
- function getFileMtimeMs(filePath) {
1352
- try {
1353
- return fs.statSync(filePath).mtimeMs;
1354
- } catch {
1355
- return;
1356
- }
1357
- }
1358
-
1359
- //#endregion
1360
- //#region src/config/sessions/disk-budget.ts
1361
- const NOOP_LOGGER = {
1362
- warn: () => {},
1363
- info: () => {}
1364
- };
1365
- function canonicalizePathForComparison(filePath) {
1366
- const resolved = path.resolve(filePath);
1367
- try {
1368
- return fs.realpathSync(resolved);
1369
- } catch {
1370
- return resolved;
1371
- }
1372
- }
1373
- function measureStoreBytes(store) {
1374
- return Buffer.byteLength(JSON.stringify(store, null, 2), "utf-8");
1375
- }
1376
- function measureStoreEntryChunkBytes(key, entry) {
1377
- const singleEntryStore = JSON.stringify({ [key]: entry }, null, 2);
1378
- if (!singleEntryStore.startsWith("{\n") || !singleEntryStore.endsWith("\n}")) return measureStoreBytes({ [key]: entry }) - 4;
1379
- const chunk = singleEntryStore.slice(2, -2);
1380
- return Buffer.byteLength(chunk, "utf-8");
1381
- }
1382
- function buildStoreEntryChunkSizeMap(store) {
1383
- const out = /* @__PURE__ */ new Map();
1384
- for (const [key, entry] of Object.entries(store)) out.set(key, measureStoreEntryChunkBytes(key, entry));
1385
- return out;
1386
- }
1387
- function getEntryUpdatedAt$1(entry) {
1388
- if (!entry) return 0;
1389
- const updatedAt = entry.updatedAt;
1390
- return Number.isFinite(updatedAt) ? updatedAt : 0;
1391
- }
1392
- function buildSessionIdRefCounts(store) {
1393
- const counts = /* @__PURE__ */ new Map();
1394
- for (const entry of Object.values(store)) {
1395
- const sessionId = entry?.sessionId;
1396
- if (!sessionId) continue;
1397
- counts.set(sessionId, (counts.get(sessionId) ?? 0) + 1);
1398
- }
1399
- return counts;
1400
- }
1401
- function resolveSessionTranscriptPathForEntry(params) {
1402
- if (!params.entry.sessionId) return null;
1403
- try {
1404
- const resolved = resolveSessionFilePath(params.entry.sessionId, params.entry, { sessionsDir: params.sessionsDir });
1405
- const resolvedSessionsDir = canonicalizePathForComparison(params.sessionsDir);
1406
- const resolvedPath = canonicalizePathForComparison(resolved);
1407
- const relative = path.relative(resolvedSessionsDir, resolvedPath);
1408
- if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) return null;
1409
- return resolvedPath;
1410
- } catch {
1411
- return null;
1412
- }
1413
- }
1414
- function resolveReferencedSessionTranscriptPaths(params) {
1415
- const referenced = /* @__PURE__ */ new Set();
1416
- for (const entry of Object.values(params.store)) {
1417
- const resolved = resolveSessionTranscriptPathForEntry({
1418
- sessionsDir: params.sessionsDir,
1419
- entry
1420
- });
1421
- if (resolved) referenced.add(canonicalizePathForComparison(resolved));
1422
- }
1423
- return referenced;
1424
- }
1425
- async function readSessionsDirFiles(sessionsDir) {
1426
- const dirEntries = await fs.promises.readdir(sessionsDir, { withFileTypes: true }).catch(() => []);
1427
- const files = [];
1428
- for (const dirent of dirEntries) {
1429
- if (!dirent.isFile()) continue;
1430
- const filePath = path.join(sessionsDir, dirent.name);
1431
- const stat = await fs.promises.stat(filePath).catch(() => null);
1432
- if (!stat?.isFile()) continue;
1433
- files.push({
1434
- path: filePath,
1435
- canonicalPath: canonicalizePathForComparison(filePath),
1436
- name: dirent.name,
1437
- size: stat.size,
1438
- mtimeMs: stat.mtimeMs
1439
- });
1440
- }
1441
- return files;
1442
- }
1443
- async function removeFileIfExists(filePath) {
1444
- const stat = await fs.promises.stat(filePath).catch(() => null);
1445
- if (!stat?.isFile()) return 0;
1446
- await fs.promises.rm(filePath, { force: true }).catch(() => void 0);
1447
- return stat.size;
1448
- }
1449
- async function removeFileForBudget(params) {
1450
- const resolvedPath = path.resolve(params.filePath);
1451
- const canonicalPath = params.canonicalPath ?? canonicalizePathForComparison(resolvedPath);
1452
- if (params.dryRun) {
1453
- if (params.simulatedRemovedPaths.has(canonicalPath)) return 0;
1454
- const size = params.fileSizesByPath.get(canonicalPath) ?? 0;
1455
- if (size <= 0) return 0;
1456
- params.simulatedRemovedPaths.add(canonicalPath);
1457
- return size;
1458
- }
1459
- return removeFileIfExists(resolvedPath);
1460
- }
1461
- async function enforceSessionDiskBudget(params) {
1462
- const maxBytes = params.maintenance.maxDiskBytes;
1463
- const highWaterBytes = params.maintenance.highWaterBytes;
1464
- if (maxBytes == null || highWaterBytes == null) return null;
1465
- const log = params.log ?? NOOP_LOGGER;
1466
- const dryRun = params.dryRun === true;
1467
- const sessionsDir = path.dirname(params.storePath);
1468
- const files = await readSessionsDirFiles(sessionsDir);
1469
- const fileSizesByPath = new Map(files.map((file) => [file.canonicalPath, file.size]));
1470
- const simulatedRemovedPaths = /* @__PURE__ */ new Set();
1471
- const resolvedStorePath = canonicalizePathForComparison(params.storePath);
1472
- const storeFile = files.find((file) => file.canonicalPath === resolvedStorePath);
1473
- let projectedStoreBytes = measureStoreBytes(params.store);
1474
- let total = files.reduce((sum, file) => sum + file.size, 0) - (storeFile?.size ?? 0) + projectedStoreBytes;
1475
- const totalBefore = total;
1476
- if (total <= maxBytes) return {
1477
- totalBytesBefore: totalBefore,
1478
- totalBytesAfter: total,
1479
- removedFiles: 0,
1480
- removedEntries: 0,
1481
- freedBytes: 0,
1482
- maxBytes,
1483
- highWaterBytes,
1484
- overBudget: false
1485
- };
1486
- if (params.warnOnly) {
1487
- log.warn("session disk budget exceeded (warn-only mode)", {
1488
- sessionsDir,
1489
- totalBytes: total,
1490
- maxBytes,
1491
- highWaterBytes
1492
- });
1493
- return {
1494
- totalBytesBefore: totalBefore,
1495
- totalBytesAfter: total,
1496
- removedFiles: 0,
1497
- removedEntries: 0,
1498
- freedBytes: 0,
1499
- maxBytes,
1500
- highWaterBytes,
1501
- overBudget: true
1502
- };
1503
- }
1504
- let removedFiles = 0;
1505
- let removedEntries = 0;
1506
- let freedBytes = 0;
1507
- const referencedPaths = resolveReferencedSessionTranscriptPaths({
1508
- sessionsDir,
1509
- store: params.store
1510
- });
1511
- const removableFileQueue = files.filter((file) => isSessionArchiveArtifactName(file.name) || isPrimarySessionTranscriptFileName(file.name) && !referencedPaths.has(file.canonicalPath)).toSorted((a, b) => a.mtimeMs - b.mtimeMs);
1512
- for (const file of removableFileQueue) {
1513
- if (total <= highWaterBytes) break;
1514
- const deletedBytes = await removeFileForBudget({
1515
- filePath: file.path,
1516
- canonicalPath: file.canonicalPath,
1517
- dryRun,
1518
- fileSizesByPath,
1519
- simulatedRemovedPaths
1520
- });
1521
- if (deletedBytes <= 0) continue;
1522
- total -= deletedBytes;
1523
- freedBytes += deletedBytes;
1524
- removedFiles += 1;
1525
- }
1526
- if (total > highWaterBytes) {
1527
- const activeSessionKey = params.activeSessionKey?.trim().toLowerCase();
1528
- const sessionIdRefCounts = buildSessionIdRefCounts(params.store);
1529
- const entryChunkBytesByKey = buildStoreEntryChunkSizeMap(params.store);
1530
- const keys = Object.keys(params.store).toSorted((a, b) => {
1531
- return getEntryUpdatedAt$1(params.store[a]) - getEntryUpdatedAt$1(params.store[b]);
1532
- });
1533
- for (const key of keys) {
1534
- if (total <= highWaterBytes) break;
1535
- if (activeSessionKey && key.trim().toLowerCase() === activeSessionKey) continue;
1536
- const entry = params.store[key];
1537
- if (!entry) continue;
1538
- const previousProjectedBytes = projectedStoreBytes;
1539
- delete params.store[key];
1540
- const chunkBytes = entryChunkBytesByKey.get(key);
1541
- entryChunkBytesByKey.delete(key);
1542
- if (typeof chunkBytes === "number" && Number.isFinite(chunkBytes) && chunkBytes >= 0) projectedStoreBytes = Math.max(2, projectedStoreBytes - (chunkBytes + 2));
1543
- else projectedStoreBytes = measureStoreBytes(params.store);
1544
- total += projectedStoreBytes - previousProjectedBytes;
1545
- removedEntries += 1;
1546
- const sessionId = entry.sessionId;
1547
- if (!sessionId) continue;
1548
- const nextRefCount = (sessionIdRefCounts.get(sessionId) ?? 1) - 1;
1549
- if (nextRefCount > 0) {
1550
- sessionIdRefCounts.set(sessionId, nextRefCount);
1551
- continue;
1552
- }
1553
- sessionIdRefCounts.delete(sessionId);
1554
- const transcriptPath = resolveSessionTranscriptPathForEntry({
1555
- sessionsDir,
1556
- entry
1557
- });
1558
- if (!transcriptPath) continue;
1559
- const deletedBytes = await removeFileForBudget({
1560
- filePath: transcriptPath,
1561
- dryRun,
1562
- fileSizesByPath,
1563
- simulatedRemovedPaths
1564
- });
1565
- if (deletedBytes <= 0) continue;
1566
- total -= deletedBytes;
1567
- freedBytes += deletedBytes;
1568
- removedFiles += 1;
1569
- }
1570
- }
1571
- if (!dryRun) {
1572
- if (total > highWaterBytes) log.warn("session disk budget still above high-water target after cleanup", {
1573
- sessionsDir,
1574
- totalBytes: total,
1575
- maxBytes,
1576
- highWaterBytes,
1577
- removedFiles,
1578
- removedEntries
1579
- });
1580
- else if (removedFiles > 0 || removedEntries > 0) log.info("applied session disk budget cleanup", {
1581
- sessionsDir,
1582
- totalBytesBefore: totalBefore,
1583
- totalBytesAfter: total,
1584
- maxBytes,
1585
- highWaterBytes,
1586
- removedFiles,
1587
- removedEntries
1588
- });
1589
- }
1590
- return {
1591
- totalBytesBefore: totalBefore,
1592
- totalBytesAfter: total,
1593
- removedFiles,
1594
- removedEntries,
1595
- freedBytes,
1596
- maxBytes,
1597
- highWaterBytes,
1598
- overBudget: true
1599
- };
1600
- }
1601
-
1602
- //#endregion
1603
- //#region src/config/sessions/store.ts
1604
- const log = createSubsystemLogger("sessions/store");
1605
- const SESSION_STORE_CACHE = /* @__PURE__ */ new Map();
1606
- const DEFAULT_SESSION_STORE_TTL_MS = 45e3;
1607
- function isSessionStoreRecord(value) {
1608
- return !!value && typeof value === "object" && !Array.isArray(value);
1609
- }
1610
- function getSessionStoreTtl() {
1611
- return resolveCacheTtlMs({
1612
- envValue: process.env.REMOTECLAW_SESSION_CACHE_TTL_MS,
1613
- defaultTtlMs: DEFAULT_SESSION_STORE_TTL_MS
1614
- });
1615
- }
1616
- function isSessionStoreCacheEnabled() {
1617
- return isCacheEnabled(getSessionStoreTtl());
1618
- }
1619
- function isSessionStoreCacheValid(entry) {
1620
- const now = Date.now();
1621
- const ttl = getSessionStoreTtl();
1622
- return now - entry.loadedAt <= ttl;
1623
- }
1624
- function invalidateSessionStoreCache(storePath) {
1625
- SESSION_STORE_CACHE.delete(storePath);
1626
- }
1627
- function normalizeSessionEntryDelivery(entry) {
1628
- const normalized = normalizeSessionDeliveryFields({
1629
- channel: entry.channel,
1630
- lastChannel: entry.lastChannel,
1631
- lastTo: entry.lastTo,
1632
- lastAccountId: entry.lastAccountId,
1633
- lastThreadId: entry.lastThreadId ?? entry.deliveryContext?.threadId ?? entry.origin?.threadId,
1634
- deliveryContext: entry.deliveryContext
1635
- });
1636
- const nextDelivery = normalized.deliveryContext;
1637
- const sameDelivery = (entry.deliveryContext?.channel ?? void 0) === nextDelivery?.channel && (entry.deliveryContext?.to ?? void 0) === nextDelivery?.to && (entry.deliveryContext?.accountId ?? void 0) === nextDelivery?.accountId && (entry.deliveryContext?.threadId ?? void 0) === nextDelivery?.threadId;
1638
- const sameLast = entry.lastChannel === normalized.lastChannel && entry.lastTo === normalized.lastTo && entry.lastAccountId === normalized.lastAccountId && entry.lastThreadId === normalized.lastThreadId;
1639
- if (sameDelivery && sameLast) return entry;
1640
- return {
1641
- ...entry,
1642
- deliveryContext: nextDelivery,
1643
- lastChannel: normalized.lastChannel,
1644
- lastTo: normalized.lastTo,
1645
- lastAccountId: normalized.lastAccountId,
1646
- lastThreadId: normalized.lastThreadId
1647
- };
1648
- }
1649
- function removeThreadFromDeliveryContext(context) {
1650
- if (!context || context.threadId == null) return context;
1651
- const next = { ...context };
1652
- delete next.threadId;
1653
- return next;
1654
- }
1655
- function normalizeStoreSessionKey(sessionKey) {
1656
- return sessionKey.trim().toLowerCase();
1657
- }
1658
- function resolveStoreSessionEntry(params) {
1659
- const trimmedKey = params.sessionKey.trim();
1660
- const normalizedKey = normalizeStoreSessionKey(trimmedKey);
1661
- const legacyKeySet = /* @__PURE__ */ new Set();
1662
- if (trimmedKey !== normalizedKey && Object.prototype.hasOwnProperty.call(params.store, trimmedKey)) legacyKeySet.add(trimmedKey);
1663
- let existing = params.store[normalizedKey] ?? (legacyKeySet.size > 0 ? params.store[trimmedKey] : void 0);
1664
- let existingUpdatedAt = existing?.updatedAt ?? 0;
1665
- for (const [candidateKey, candidateEntry] of Object.entries(params.store)) {
1666
- if (candidateKey === normalizedKey) continue;
1667
- if (candidateKey.toLowerCase() !== normalizedKey) continue;
1668
- legacyKeySet.add(candidateKey);
1669
- const candidateUpdatedAt = candidateEntry?.updatedAt ?? 0;
1670
- if (!existing || candidateUpdatedAt > existingUpdatedAt) {
1671
- existing = candidateEntry;
1672
- existingUpdatedAt = candidateUpdatedAt;
1673
- }
1674
- }
1675
- return {
1676
- normalizedKey,
1677
- existing,
1678
- legacyKeys: [...legacyKeySet]
1679
- };
1680
- }
1681
- function normalizeSessionStore(store) {
1682
- for (const [key, entry] of Object.entries(store)) {
1683
- if (!entry) continue;
1684
- const normalized = normalizeSessionEntryDelivery(normalizeSessionRuntimeModelFields(entry));
1685
- if (normalized !== entry) store[key] = normalized;
1686
- }
1687
- }
1688
- function clearSessionStoreCacheForTest() {
1689
- SESSION_STORE_CACHE.clear();
1690
- for (const queue of LOCK_QUEUES.values()) for (const task of queue.pending) task.reject(/* @__PURE__ */ new Error("session store queue cleared for test"));
1691
- LOCK_QUEUES.clear();
1692
- }
1693
- /** Expose lock queue size for tests. */
1694
- function getSessionStoreLockQueueSizeForTest() {
1695
- return LOCK_QUEUES.size;
1696
- }
1697
- async function withSessionStoreLockForTest(storePath, fn, opts = {}) {
1698
- return await withSessionStoreLock(storePath, fn, opts);
1699
- }
1700
- function loadSessionStore(storePath, opts = {}) {
1701
- if (!opts.skipCache && isSessionStoreCacheEnabled()) {
1702
- const cached = SESSION_STORE_CACHE.get(storePath);
1703
- if (cached && isSessionStoreCacheValid(cached)) {
1704
- if (getFileMtimeMs(storePath) === cached.mtimeMs) return structuredClone(cached.store);
1705
- invalidateSessionStoreCache(storePath);
1706
- }
1707
- }
1708
- let store = {};
1709
- let mtimeMs = getFileMtimeMs(storePath);
1710
- const maxReadAttempts = process.platform === "win32" ? 3 : 1;
1711
- const retryBuf = maxReadAttempts > 1 ? new Int32Array(new SharedArrayBuffer(4)) : void 0;
1712
- for (let attempt = 0; attempt < maxReadAttempts; attempt++) try {
1713
- const raw = fs.readFileSync(storePath, "utf-8");
1714
- if (raw.length === 0 && attempt < maxReadAttempts - 1) {
1715
- Atomics.wait(retryBuf, 0, 0, 50);
1716
- continue;
1717
- }
1718
- const parsed = JSON.parse(raw);
1719
- if (isSessionStoreRecord(parsed)) store = parsed;
1720
- mtimeMs = getFileMtimeMs(storePath) ?? mtimeMs;
1721
- break;
1722
- } catch {
1723
- if (attempt < maxReadAttempts - 1) {
1724
- Atomics.wait(retryBuf, 0, 0, 50);
1725
- continue;
1726
- }
1727
- }
1728
- for (const entry of Object.values(store)) {
1729
- if (!entry || typeof entry !== "object") continue;
1730
- const rec = entry;
1731
- if (typeof rec.channel !== "string" && typeof rec.provider === "string") {
1732
- rec.channel = rec.provider;
1733
- delete rec.provider;
1734
- }
1735
- if (typeof rec.lastChannel !== "string" && typeof rec.lastProvider === "string") {
1736
- rec.lastChannel = rec.lastProvider;
1737
- delete rec.lastProvider;
1738
- }
1739
- if (typeof rec.groupChannel !== "string" && typeof rec.room === "string") {
1740
- rec.groupChannel = rec.room;
1741
- delete rec.room;
1742
- } else if ("room" in rec) delete rec.room;
1743
- }
1744
- if (!opts.skipCache && isSessionStoreCacheEnabled()) SESSION_STORE_CACHE.set(storePath, {
1745
- store: structuredClone(store),
1746
- loadedAt: Date.now(),
1747
- storePath,
1748
- mtimeMs
1749
- });
1750
- return structuredClone(store);
1751
- }
1752
- function readSessionUpdatedAt(params) {
1753
- try {
1754
- return resolveStoreSessionEntry({
1755
- store: loadSessionStore(params.storePath),
1756
- sessionKey: params.sessionKey
1757
- }).existing?.updatedAt;
1758
- } catch {
1759
- return;
1760
- }
1761
- }
1762
- const DEFAULT_SESSION_PRUNE_AFTER_MS = 720 * 60 * 60 * 1e3;
1763
- const DEFAULT_SESSION_MAX_ENTRIES = 500;
1764
- const DEFAULT_SESSION_ROTATE_BYTES = 10485760;
1765
- const DEFAULT_SESSION_MAINTENANCE_MODE = "warn";
1766
- const DEFAULT_SESSION_DISK_BUDGET_HIGH_WATER_RATIO = .8;
1767
- function resolvePruneAfterMs(maintenance) {
1768
- const raw = maintenance?.pruneAfter ?? maintenance?.pruneDays;
1769
- if (raw === void 0 || raw === null || raw === "") return DEFAULT_SESSION_PRUNE_AFTER_MS;
1770
- try {
1771
- return parseDurationMs(String(raw).trim(), { defaultUnit: "d" });
1772
- } catch {
1773
- return DEFAULT_SESSION_PRUNE_AFTER_MS;
1774
- }
1775
- }
1776
- function resolveRotateBytes(maintenance) {
1777
- const raw = maintenance?.rotateBytes;
1778
- if (raw === void 0 || raw === null || raw === "") return DEFAULT_SESSION_ROTATE_BYTES;
1779
- try {
1780
- return parseByteSize(String(raw).trim(), { defaultUnit: "b" });
1781
- } catch {
1782
- return DEFAULT_SESSION_ROTATE_BYTES;
1783
- }
1784
- }
1785
- function resolveResetArchiveRetentionMs(maintenance, pruneAfterMs) {
1786
- const raw = maintenance?.resetArchiveRetention;
1787
- if (raw === false) return null;
1788
- if (raw === void 0 || raw === null || raw === "") return pruneAfterMs;
1789
- try {
1790
- return parseDurationMs(String(raw).trim(), { defaultUnit: "d" });
1791
- } catch {
1792
- return pruneAfterMs;
1793
- }
1794
- }
1795
- function resolveMaxDiskBytes(maintenance) {
1796
- const raw = maintenance?.maxDiskBytes;
1797
- if (raw === void 0 || raw === null || raw === "") return null;
1798
- try {
1799
- return parseByteSize(String(raw).trim(), { defaultUnit: "b" });
1800
- } catch {
1801
- return null;
1802
- }
1803
- }
1804
- function resolveHighWaterBytes(maintenance, maxDiskBytes) {
1805
- const computeDefault = () => {
1806
- if (maxDiskBytes == null) return null;
1807
- if (maxDiskBytes <= 0) return 0;
1808
- return Math.max(1, Math.min(maxDiskBytes, Math.floor(maxDiskBytes * DEFAULT_SESSION_DISK_BUDGET_HIGH_WATER_RATIO)));
1809
- };
1810
- if (maxDiskBytes == null) return null;
1811
- const raw = maintenance?.highWaterBytes;
1812
- if (raw === void 0 || raw === null || raw === "") return computeDefault();
1813
- try {
1814
- const parsed = parseByteSize(String(raw).trim(), { defaultUnit: "b" });
1815
- return Math.min(parsed, maxDiskBytes);
1816
- } catch {
1817
- return computeDefault();
1818
- }
1819
- }
1820
- /**
1821
- * Resolve maintenance settings from remoteclaw.json (`session.maintenance`).
1822
- * Falls back to built-in defaults when config is missing or unset.
1823
- */
1824
- function resolveMaintenanceConfig() {
1825
- let maintenance;
1826
- try {
1827
- maintenance = loadConfig().session?.maintenance;
1828
- } catch {}
1829
- const pruneAfterMs = resolvePruneAfterMs(maintenance);
1830
- const maxDiskBytes = resolveMaxDiskBytes(maintenance);
1831
- return {
1832
- mode: maintenance?.mode ?? DEFAULT_SESSION_MAINTENANCE_MODE,
1833
- pruneAfterMs,
1834
- maxEntries: maintenance?.maxEntries ?? DEFAULT_SESSION_MAX_ENTRIES,
1835
- rotateBytes: resolveRotateBytes(maintenance),
1836
- resetArchiveRetentionMs: resolveResetArchiveRetentionMs(maintenance, pruneAfterMs),
1837
- maxDiskBytes,
1838
- highWaterBytes: resolveHighWaterBytes(maintenance, maxDiskBytes)
1839
- };
1840
- }
1841
- /**
1842
- * Remove entries whose `updatedAt` is older than the configured threshold.
1843
- * Entries without `updatedAt` are kept (cannot determine staleness).
1844
- * Mutates `store` in-place.
1845
- */
1846
- function pruneStaleEntries(store, overrideMaxAgeMs, opts = {}) {
1847
- const maxAgeMs = overrideMaxAgeMs ?? resolveMaintenanceConfig().pruneAfterMs;
1848
- const cutoffMs = Date.now() - maxAgeMs;
1849
- let pruned = 0;
1850
- for (const [key, entry] of Object.entries(store)) if (entry?.updatedAt != null && entry.updatedAt < cutoffMs) {
1851
- opts.onPruned?.({
1852
- key,
1853
- entry
1854
- });
1855
- delete store[key];
1856
- pruned++;
1857
- }
1858
- if (pruned > 0 && opts.log !== false) log.info("pruned stale session entries", {
1859
- pruned,
1860
- maxAgeMs
1861
- });
1862
- return pruned;
1863
- }
1864
- /**
1865
- * Cap the store to the N most recently updated entries.
1866
- * Entries without `updatedAt` are sorted last (removed first when over limit).
1867
- * Mutates `store` in-place.
1868
- */
1869
- function getEntryUpdatedAt(entry) {
1870
- return entry?.updatedAt ?? Number.NEGATIVE_INFINITY;
1871
- }
1872
- function getActiveSessionMaintenanceWarning(params) {
1873
- const activeSessionKey = params.activeSessionKey.trim();
1874
- if (!activeSessionKey) return null;
1875
- const activeEntry = params.store[activeSessionKey];
1876
- if (!activeEntry) return null;
1877
- const cutoffMs = (params.nowMs ?? Date.now()) - params.pruneAfterMs;
1878
- const wouldPrune = activeEntry.updatedAt != null ? activeEntry.updatedAt < cutoffMs : false;
1879
- const keys = Object.keys(params.store);
1880
- const wouldCap = keys.length > params.maxEntries && keys.toSorted((a, b) => getEntryUpdatedAt(params.store[b]) - getEntryUpdatedAt(params.store[a])).slice(params.maxEntries).includes(activeSessionKey);
1881
- if (!wouldPrune && !wouldCap) return null;
1882
- return {
1883
- activeSessionKey,
1884
- activeUpdatedAt: activeEntry.updatedAt,
1885
- totalEntries: keys.length,
1886
- pruneAfterMs: params.pruneAfterMs,
1887
- maxEntries: params.maxEntries,
1888
- wouldPrune,
1889
- wouldCap
1890
- };
1891
- }
1892
- function capEntryCount(store, overrideMax, opts = {}) {
1893
- const maxEntries = overrideMax ?? resolveMaintenanceConfig().maxEntries;
1894
- const keys = Object.keys(store);
1895
- if (keys.length <= maxEntries) return 0;
1896
- const toRemove = keys.toSorted((a, b) => {
1897
- const aTime = getEntryUpdatedAt(store[a]);
1898
- return getEntryUpdatedAt(store[b]) - aTime;
1899
- }).slice(maxEntries);
1900
- for (const key of toRemove) {
1901
- const entry = store[key];
1902
- if (entry) opts.onCapped?.({
1903
- key,
1904
- entry
1905
- });
1906
- delete store[key];
1907
- }
1908
- if (opts.log !== false) log.info("capped session entry count", {
1909
- removed: toRemove.length,
1910
- maxEntries
1911
- });
1912
- return toRemove.length;
1913
- }
1914
- async function getSessionFileSize(storePath) {
1915
- try {
1916
- return (await fs.promises.stat(storePath)).size;
1917
- } catch {
1918
- return null;
1919
- }
1920
- }
1921
- /**
1922
- * Rotate the sessions file if it exceeds the configured size threshold.
1923
- * Renames the current file to `sessions.json.bak.{timestamp}` and cleans up
1924
- * old rotation backups, keeping only the 3 most recent `.bak.*` files.
1925
- */
1926
- async function rotateSessionFile(storePath, overrideBytes) {
1927
- const maxBytes = overrideBytes ?? resolveMaintenanceConfig().rotateBytes;
1928
- const fileSize = await getSessionFileSize(storePath);
1929
- if (fileSize == null) return false;
1930
- if (fileSize <= maxBytes) return false;
1931
- const backupPath = `${storePath}.bak.${Date.now()}`;
1932
- try {
1933
- await fs.promises.rename(storePath, backupPath);
1934
- log.info("rotated session store file", {
1935
- backupPath: path.basename(backupPath),
1936
- sizeBytes: fileSize
1937
- });
1938
- } catch {
1939
- return false;
1940
- }
1941
- try {
1942
- const dir = path.dirname(storePath);
1943
- const baseName = path.basename(storePath);
1944
- const backups = (await fs.promises.readdir(dir)).filter((f) => f.startsWith(`${baseName}.bak.`)).toSorted().toReversed();
1945
- const maxBackups = 3;
1946
- if (backups.length > maxBackups) {
1947
- const toDelete = backups.slice(maxBackups);
1948
- for (const old of toDelete) await fs.promises.unlink(path.join(dir, old)).catch(() => void 0);
1949
- log.info("cleaned up old session store backups", { deleted: toDelete.length });
1950
- }
1951
- } catch {}
1952
- return true;
1953
- }
1954
- async function saveSessionStoreUnlocked(storePath, store, opts) {
1955
- invalidateSessionStoreCache(storePath);
1956
- normalizeSessionStore(store);
1957
- if (!opts?.skipMaintenance) {
1958
- const maintenance = {
1959
- ...resolveMaintenanceConfig(),
1960
- ...opts?.maintenanceOverride
1961
- };
1962
- const shouldWarnOnly = maintenance.mode === "warn";
1963
- const beforeCount = Object.keys(store).length;
1964
- if (shouldWarnOnly) {
1965
- const activeSessionKey = opts?.activeSessionKey?.trim();
1966
- if (activeSessionKey) {
1967
- const warning = getActiveSessionMaintenanceWarning({
1968
- store,
1969
- activeSessionKey,
1970
- pruneAfterMs: maintenance.pruneAfterMs,
1971
- maxEntries: maintenance.maxEntries
1972
- });
1973
- if (warning) {
1974
- log.warn("session maintenance would evict active session; skipping enforcement", {
1975
- activeSessionKey: warning.activeSessionKey,
1976
- wouldPrune: warning.wouldPrune,
1977
- wouldCap: warning.wouldCap,
1978
- pruneAfterMs: warning.pruneAfterMs,
1979
- maxEntries: warning.maxEntries
1980
- });
1981
- await opts?.onWarn?.(warning);
1982
- }
1983
- }
1984
- const diskBudget = await enforceSessionDiskBudget({
1985
- store,
1986
- storePath,
1987
- activeSessionKey: opts?.activeSessionKey,
1988
- maintenance,
1989
- warnOnly: true,
1990
- log
1991
- });
1992
- await opts?.onMaintenanceApplied?.({
1993
- mode: maintenance.mode,
1994
- beforeCount,
1995
- afterCount: Object.keys(store).length,
1996
- pruned: 0,
1997
- capped: 0,
1998
- diskBudget
1999
- });
2000
- } else {
2001
- const removedSessionFiles = /* @__PURE__ */ new Map();
2002
- const pruned = pruneStaleEntries(store, maintenance.pruneAfterMs, { onPruned: ({ entry }) => {
2003
- if (!removedSessionFiles.has(entry.sessionId) || entry.sessionFile) removedSessionFiles.set(entry.sessionId, entry.sessionFile);
2004
- } });
2005
- const capped = capEntryCount(store, maintenance.maxEntries, { onCapped: ({ entry }) => {
2006
- if (!removedSessionFiles.has(entry.sessionId) || entry.sessionFile) removedSessionFiles.set(entry.sessionId, entry.sessionFile);
2007
- } });
2008
- const archivedDirs = /* @__PURE__ */ new Set();
2009
- const referencedSessionIds = new Set(Object.values(store).map((entry) => entry?.sessionId).filter((id) => Boolean(id)));
2010
- for (const [sessionId, sessionFile] of removedSessionFiles) {
2011
- if (referencedSessionIds.has(sessionId)) continue;
2012
- const archived = archiveSessionTranscripts({
2013
- sessionId,
2014
- storePath,
2015
- sessionFile,
2016
- reason: "deleted",
2017
- restrictToStoreDir: true
2018
- });
2019
- for (const archivedPath of archived) archivedDirs.add(path.dirname(archivedPath));
2020
- }
2021
- if (archivedDirs.size > 0 || maintenance.resetArchiveRetentionMs != null) {
2022
- const targetDirs = archivedDirs.size > 0 ? [...archivedDirs] : [path.dirname(path.resolve(storePath))];
2023
- await cleanupArchivedSessionTranscripts({
2024
- directories: targetDirs,
2025
- olderThanMs: maintenance.pruneAfterMs,
2026
- reason: "deleted"
2027
- });
2028
- if (maintenance.resetArchiveRetentionMs != null) await cleanupArchivedSessionTranscripts({
2029
- directories: targetDirs,
2030
- olderThanMs: maintenance.resetArchiveRetentionMs,
2031
- reason: "reset"
2032
- });
2033
- }
2034
- await rotateSessionFile(storePath, maintenance.rotateBytes);
2035
- const diskBudget = await enforceSessionDiskBudget({
2036
- store,
2037
- storePath,
2038
- activeSessionKey: opts?.activeSessionKey,
2039
- maintenance,
2040
- warnOnly: false,
2041
- log
2042
- });
2043
- await opts?.onMaintenanceApplied?.({
2044
- mode: maintenance.mode,
2045
- beforeCount,
2046
- afterCount: Object.keys(store).length,
2047
- pruned,
2048
- capped,
2049
- diskBudget
2050
- });
2051
- }
2052
- }
2053
- await fs.promises.mkdir(path.dirname(storePath), { recursive: true });
2054
- const json = JSON.stringify(store, null, 2);
2055
- if (process.platform === "win32") {
2056
- const tmp = `${storePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
2057
- try {
2058
- await fs.promises.writeFile(tmp, json, "utf-8");
2059
- for (let i = 0; i < 5; i++) try {
2060
- await fs.promises.rename(tmp, storePath);
2061
- break;
2062
- } catch {
2063
- if (i < 4) await new Promise((r) => setTimeout(r, 50 * (i + 1)));
2064
- if (i === 4) log.warn(`rename failed after 5 attempts: ${storePath}`);
2065
- }
2066
- } catch (err) {
2067
- if ((err && typeof err === "object" && "code" in err ? String(err.code) : null) === "ENOENT") return;
2068
- throw err;
2069
- } finally {
2070
- await fs.promises.rm(tmp, { force: true }).catch(() => void 0);
2071
- }
2072
- return;
2073
- }
2074
- const tmp = `${storePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
2075
- try {
2076
- await fs.promises.writeFile(tmp, json, {
2077
- mode: 384,
2078
- encoding: "utf-8"
2079
- });
2080
- await fs.promises.rename(tmp, storePath);
2081
- await fs.promises.chmod(storePath, 384);
2082
- } catch (err) {
2083
- if ((err && typeof err === "object" && "code" in err ? String(err.code) : null) === "ENOENT") {
2084
- try {
2085
- await fs.promises.mkdir(path.dirname(storePath), { recursive: true });
2086
- await fs.promises.writeFile(storePath, json, {
2087
- mode: 384,
2088
- encoding: "utf-8"
2089
- });
2090
- await fs.promises.chmod(storePath, 384);
2091
- } catch (err2) {
2092
- if ((err2 && typeof err2 === "object" && "code" in err2 ? String(err2.code) : null) === "ENOENT") return;
2093
- throw err2;
2094
- }
2095
- return;
2096
- }
2097
- throw err;
2098
- } finally {
2099
- await fs.promises.rm(tmp, { force: true });
2100
- }
2101
- }
2102
- async function saveSessionStore(storePath, store, opts) {
2103
- await withSessionStoreLock(storePath, async () => {
2104
- await saveSessionStoreUnlocked(storePath, store, opts);
2105
- });
2106
- }
2107
- async function updateSessionStore(storePath, mutator, opts) {
2108
- return await withSessionStoreLock(storePath, async () => {
2109
- const store = loadSessionStore(storePath, { skipCache: true });
2110
- const result = await mutator(store);
2111
- await saveSessionStoreUnlocked(storePath, store, opts);
2112
- return result;
2113
- });
2114
- }
2115
- const LOCK_QUEUES = /* @__PURE__ */ new Map();
2116
- function lockTimeoutError(storePath) {
2117
- return /* @__PURE__ */ new Error(`timeout waiting for session store lock: ${storePath}`);
2118
- }
2119
- function getOrCreateLockQueue(storePath) {
2120
- const existing = LOCK_QUEUES.get(storePath);
2121
- if (existing) return existing;
2122
- const created = {
2123
- running: false,
2124
- pending: []
2125
- };
2126
- LOCK_QUEUES.set(storePath, created);
2127
- return created;
2128
- }
2129
- async function drainSessionStoreLockQueue(storePath) {
2130
- const queue = LOCK_QUEUES.get(storePath);
2131
- if (!queue || queue.running) return;
2132
- queue.running = true;
2133
- try {
2134
- while (queue.pending.length > 0) {
2135
- const task = queue.pending.shift();
2136
- if (!task) continue;
2137
- const remainingTimeoutMs = task.timeoutMs ?? Number.POSITIVE_INFINITY;
2138
- if (task.timeoutMs != null && remainingTimeoutMs <= 0) {
2139
- task.reject(lockTimeoutError(storePath));
2140
- continue;
2141
- }
2142
- let lock;
2143
- let result;
2144
- let failed;
2145
- let hasFailure = false;
2146
- try {
2147
- lock = await acquireSessionWriteLock({
2148
- sessionFile: storePath,
2149
- timeoutMs: remainingTimeoutMs,
2150
- staleMs: task.staleMs
2151
- });
2152
- result = await task.fn();
2153
- } catch (err) {
2154
- hasFailure = true;
2155
- failed = err;
2156
- } finally {
2157
- await lock?.release().catch(() => void 0);
2158
- }
2159
- if (hasFailure) {
2160
- task.reject(failed);
2161
- continue;
2162
- }
2163
- task.resolve(result);
2164
- }
2165
- } finally {
2166
- queue.running = false;
2167
- if (queue.pending.length === 0) LOCK_QUEUES.delete(storePath);
2168
- else queueMicrotask(() => {
2169
- drainSessionStoreLockQueue(storePath);
2170
- });
2171
- }
2172
- }
2173
- async function withSessionStoreLock(storePath, fn, opts = {}) {
2174
- if (!storePath || typeof storePath !== "string") throw new Error(`withSessionStoreLock: storePath must be a non-empty string, got ${JSON.stringify(storePath)}`);
2175
- const timeoutMs = opts.timeoutMs ?? 1e4;
2176
- const staleMs = opts.staleMs ?? 3e4;
2177
- opts.pollIntervalMs;
2178
- const hasTimeout = timeoutMs > 0 && Number.isFinite(timeoutMs);
2179
- const queue = getOrCreateLockQueue(storePath);
2180
- return await new Promise((resolve, reject) => {
2181
- const task = {
2182
- fn: async () => await fn(),
2183
- resolve: (value) => resolve(value),
2184
- reject,
2185
- timeoutMs: hasTimeout ? timeoutMs : void 0,
2186
- staleMs
2187
- };
2188
- queue.pending.push(task);
2189
- drainSessionStoreLockQueue(storePath);
2190
- });
2191
- }
2192
- async function updateSessionStoreEntry(params) {
2193
- const { storePath, sessionKey, update } = params;
2194
- return await withSessionStoreLock(storePath, async () => {
2195
- const store = loadSessionStore(storePath, { skipCache: true });
2196
- const resolved = resolveStoreSessionEntry({
2197
- store,
2198
- sessionKey
2199
- });
2200
- const existing = resolved.existing;
2201
- if (!existing) return null;
2202
- const patch = await update(existing);
2203
- if (!patch) return existing;
2204
- const next = mergeSessionEntry(existing, patch);
2205
- store[resolved.normalizedKey] = next;
2206
- for (const legacyKey of resolved.legacyKeys) delete store[legacyKey];
2207
- await saveSessionStoreUnlocked(storePath, store, { activeSessionKey: resolved.normalizedKey });
2208
- return next;
2209
- });
2210
- }
2211
- async function recordSessionMetaFromInbound(params) {
2212
- const { storePath, sessionKey, ctx } = params;
2213
- const createIfMissing = params.createIfMissing ?? true;
2214
- return await updateSessionStore(storePath, (store) => {
2215
- const resolved = resolveStoreSessionEntry({
2216
- store,
2217
- sessionKey
2218
- });
2219
- const existing = resolved.existing;
2220
- const patch = deriveSessionMetaPatch({
2221
- ctx,
2222
- sessionKey: resolved.normalizedKey,
2223
- existing,
2224
- groupResolution: params.groupResolution
2225
- });
2226
- if (!patch) {
2227
- if (existing && resolved.legacyKeys.length > 0) {
2228
- store[resolved.normalizedKey] = existing;
2229
- for (const legacyKey of resolved.legacyKeys) delete store[legacyKey];
2230
- }
2231
- return existing ?? null;
2232
- }
2233
- if (!existing && !createIfMissing) return null;
2234
- const next = mergeSessionEntry(existing, patch);
2235
- store[resolved.normalizedKey] = next;
2236
- for (const legacyKey of resolved.legacyKeys) delete store[legacyKey];
2237
- return next;
2238
- }, { activeSessionKey: normalizeStoreSessionKey(sessionKey) });
2239
- }
2240
- async function updateLastRoute(params) {
2241
- const { storePath, sessionKey, channel, to, accountId, threadId, ctx } = params;
2242
- return await withSessionStoreLock(storePath, async () => {
2243
- const store = loadSessionStore(storePath);
2244
- const resolved = resolveStoreSessionEntry({
2245
- store,
2246
- sessionKey
2247
- });
2248
- const existing = resolved.existing;
2249
- const now = Date.now();
2250
- const explicitContext = normalizeDeliveryContext(params.deliveryContext);
2251
- const inlineContext = normalizeDeliveryContext({
2252
- channel,
2253
- to,
2254
- accountId,
2255
- threadId
2256
- });
2257
- const mergedInput = mergeDeliveryContext(explicitContext, inlineContext);
2258
- const explicitDeliveryContext = params.deliveryContext;
2259
- const explicitThreadValue = (explicitDeliveryContext != null && Object.prototype.hasOwnProperty.call(explicitDeliveryContext, "threadId") ? explicitDeliveryContext.threadId : void 0) ?? (threadId != null && threadId !== "" ? threadId : void 0);
2260
- const merged = mergeDeliveryContext(mergedInput, Boolean(explicitContext?.channel || explicitContext?.to || inlineContext?.channel || inlineContext?.to) && explicitThreadValue == null ? removeThreadFromDeliveryContext(deliveryContextFromSession(existing)) : deliveryContextFromSession(existing));
2261
- const normalized = normalizeSessionDeliveryFields({ deliveryContext: {
2262
- channel: merged?.channel,
2263
- to: merged?.to,
2264
- accountId: merged?.accountId,
2265
- threadId: merged?.threadId
2266
- } });
2267
- const metaPatch = ctx ? deriveSessionMetaPatch({
2268
- ctx,
2269
- sessionKey: resolved.normalizedKey,
2270
- existing,
2271
- groupResolution: params.groupResolution
2272
- }) : null;
2273
- const basePatch = {
2274
- updatedAt: Math.max(existing?.updatedAt ?? 0, now),
2275
- deliveryContext: normalized.deliveryContext,
2276
- lastChannel: normalized.lastChannel,
2277
- lastTo: normalized.lastTo,
2278
- lastAccountId: normalized.lastAccountId,
2279
- lastThreadId: normalized.lastThreadId
2280
- };
2281
- const next = mergeSessionEntry(existing, metaPatch ? {
2282
- ...basePatch,
2283
- ...metaPatch
2284
- } : basePatch);
2285
- store[resolved.normalizedKey] = next;
2286
- for (const legacyKey of resolved.legacyKeys) delete store[legacyKey];
2287
- await saveSessionStoreUnlocked(storePath, store, { activeSessionKey: resolved.normalizedKey });
2288
- return next;
2289
- });
2290
- }
2291
-
2292
- //#endregion
2293
- //#region src/sessions/transcript-events.ts
2294
- const SESSION_TRANSCRIPT_LISTENERS = /* @__PURE__ */ new Set();
2295
- function emitSessionTranscriptUpdate(sessionFile) {
2296
- const trimmed = sessionFile.trim();
2297
- if (!trimmed) return;
2298
- const update = { sessionFile: trimmed };
2299
- for (const listener of SESSION_TRANSCRIPT_LISTENERS) listener(update);
2300
- }
2301
-
2302
- //#endregion
2303
- //#region src/config/sessions/constants.ts
2304
- /** Session transcript format version (matches pi-coding-agent SessionManager v3 layout). */
2305
- const CURRENT_SESSION_VERSION = 3;
2306
-
2307
- //#endregion
2308
- //#region src/config/sessions/session-file.ts
2309
- async function resolveAndPersistSessionFile(params) {
2310
- const { sessionId, sessionKey, sessionStore, storePath } = params;
2311
- const baseEntry = params.sessionEntry ?? sessionStore[sessionKey] ?? {
2312
- sessionId,
2313
- updatedAt: Date.now()
2314
- };
2315
- const fallbackSessionFile = params.fallbackSessionFile?.trim();
2316
- const sessionFile = resolveSessionFilePath(sessionId, !baseEntry.sessionFile && fallbackSessionFile ? {
2317
- ...baseEntry,
2318
- sessionFile: fallbackSessionFile
2319
- } : baseEntry, {
2320
- agentId: params.agentId,
2321
- sessionsDir: params.sessionsDir
2322
- });
2323
- const persistedEntry = {
2324
- ...baseEntry,
2325
- sessionId,
2326
- updatedAt: Date.now(),
2327
- sessionFile
2328
- };
2329
- if (baseEntry.sessionId !== sessionId || baseEntry.sessionFile !== sessionFile) {
2330
- sessionStore[sessionKey] = persistedEntry;
2331
- await updateSessionStore(storePath, (store) => {
2332
- store[sessionKey] = {
2333
- ...store[sessionKey],
2334
- ...persistedEntry
2335
- };
2336
- }, params.activeSessionKey ? { activeSessionKey: params.activeSessionKey } : void 0);
2337
- return {
2338
- sessionFile,
2339
- sessionEntry: persistedEntry
2340
- };
2341
- }
2342
- sessionStore[sessionKey] = persistedEntry;
2343
- return {
2344
- sessionFile,
2345
- sessionEntry: persistedEntry
2346
- };
2347
- }
2348
-
2349
- //#endregion
2350
- //#region src/config/sessions/transcript.ts
2351
- function stripQuery(value) {
2352
- const noHash = value.split("#")[0] ?? value;
2353
- return noHash.split("?")[0] ?? noHash;
2354
- }
2355
- function extractFileNameFromMediaUrl(value) {
2356
- const trimmed = value.trim();
2357
- if (!trimmed) return null;
2358
- const cleaned = stripQuery(trimmed);
2359
- try {
2360
- const parsed = new URL(cleaned);
2361
- const base = path.basename(parsed.pathname);
2362
- if (!base) return null;
2363
- try {
2364
- return decodeURIComponent(base);
2365
- } catch {
2366
- return base;
2367
- }
2368
- } catch {
2369
- const base = path.basename(cleaned);
2370
- if (!base || base === "/" || base === ".") return null;
2371
- return base;
2372
- }
2373
- }
2374
- function resolveMirroredTranscriptText(params) {
2375
- const mediaUrls = params.mediaUrls?.filter((url) => url && url.trim()) ?? [];
2376
- if (mediaUrls.length > 0) {
2377
- const names = mediaUrls.map((url) => extractFileNameFromMediaUrl(url)).filter((name) => Boolean(name && name.trim()));
2378
- if (names.length > 0) return names.join(", ");
2379
- return "media";
2380
- }
2381
- const trimmed = (params.text ?? "").trim();
2382
- return trimmed ? trimmed : null;
2383
- }
2384
- async function ensureSessionHeader(params) {
2385
- if (fs.existsSync(params.sessionFile)) return;
2386
- await fs.promises.mkdir(path.dirname(params.sessionFile), { recursive: true });
2387
- const header = {
2388
- type: "session",
2389
- version: CURRENT_SESSION_VERSION,
2390
- id: params.sessionId,
2391
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2392
- cwd: process.cwd()
2393
- };
2394
- await fs.promises.writeFile(params.sessionFile, `${JSON.stringify(header)}\n`, {
2395
- encoding: "utf-8",
2396
- mode: 384
2397
- });
2398
- }
2399
- async function appendAssistantMessageToSessionTranscript(params) {
2400
- const sessionKey = params.sessionKey.trim();
2401
- if (!sessionKey) return {
2402
- ok: false,
2403
- reason: "missing sessionKey"
2404
- };
2405
- const mirrorText = resolveMirroredTranscriptText({
2406
- text: params.text,
2407
- mediaUrls: params.mediaUrls
2408
- });
2409
- if (!mirrorText) return {
2410
- ok: false,
2411
- reason: "empty text"
2412
- };
2413
- const storePath = params.storePath ?? resolveDefaultSessionStorePath(params.agentId);
2414
- const store = loadSessionStore(storePath, { skipCache: true });
2415
- const entry = store[sessionKey];
2416
- if (!entry?.sessionId) return {
2417
- ok: false,
2418
- reason: `unknown sessionKey: ${sessionKey}`
2419
- };
2420
- let sessionFile;
2421
- try {
2422
- sessionFile = (await resolveAndPersistSessionFile({
2423
- sessionId: entry.sessionId,
2424
- sessionKey,
2425
- sessionStore: store,
2426
- storePath,
2427
- sessionEntry: entry,
2428
- agentId: params.agentId,
2429
- sessionsDir: path.dirname(storePath)
2430
- })).sessionFile;
2431
- } catch (err) {
2432
- return {
2433
- ok: false,
2434
- reason: err instanceof Error ? err.message : String(err)
2435
- };
2436
- }
2437
- await ensureSessionHeader({
2438
- sessionFile,
2439
- sessionId: entry.sessionId
2440
- });
2441
- const line = {
2442
- type: "message",
2443
- message: {
2444
- role: "assistant",
2445
- content: [{
2446
- type: "text",
2447
- text: mirrorText
2448
- }],
2449
- api: "openai-responses",
2450
- provider: "remoteclaw",
2451
- model: "delivery-mirror",
2452
- usage: {
2453
- input: 0,
2454
- output: 0,
2455
- cacheRead: 0,
2456
- cacheWrite: 0,
2457
- totalTokens: 0,
2458
- cost: {
2459
- input: 0,
2460
- output: 0,
2461
- cacheRead: 0,
2462
- cacheWrite: 0,
2463
- total: 0
2464
- }
2465
- },
2466
- stopReason: "stop",
2467
- timestamp: Date.now()
2468
- }
2469
- };
2470
- await fs.promises.appendFile(sessionFile, `${JSON.stringify(line)}\n`, "utf-8");
2471
- emitSessionTranscriptUpdate(sessionFile);
2472
- return {
2473
- ok: true,
2474
- sessionFile
2475
- };
2476
- }
2477
-
2478
- //#endregion
2479
- //#region src/config/sessions/delivery-info.ts
2480
- /**
2481
- * Extract deliveryContext and threadId from a sessionKey.
2482
- * Supports both :thread: (most channels) and :topic: (Telegram).
2483
- */
2484
- function parseSessionThreadInfo(sessionKey) {
2485
- if (!sessionKey) return {
2486
- baseSessionKey: void 0,
2487
- threadId: void 0
2488
- };
2489
- const topicIndex = sessionKey.lastIndexOf(":topic:");
2490
- const threadIndex = sessionKey.lastIndexOf(":thread:");
2491
- const markerIndex = Math.max(topicIndex, threadIndex);
2492
- const marker = topicIndex > threadIndex ? ":topic:" : ":thread:";
2493
- return {
2494
- baseSessionKey: markerIndex === -1 ? sessionKey : sessionKey.slice(0, markerIndex),
2495
- threadId: (markerIndex === -1 ? void 0 : sessionKey.slice(markerIndex + marker.length))?.trim() || void 0
2496
- };
2497
- }
2498
- function extractDeliveryInfo(sessionKey) {
2499
- const { baseSessionKey, threadId } = parseSessionThreadInfo(sessionKey);
2500
- if (!sessionKey || !baseSessionKey) return {
2501
- deliveryContext: void 0,
2502
- threadId
2503
- };
2504
- let deliveryContext;
2505
- try {
2506
- const store = loadSessionStore(resolveStorePath(loadConfig().session?.store));
2507
- let entry = store[sessionKey];
2508
- if (!entry?.deliveryContext && baseSessionKey !== sessionKey) entry = store[baseSessionKey];
2509
- if (entry?.deliveryContext) deliveryContext = {
2510
- channel: entry.deliveryContext.channel,
2511
- to: entry.deliveryContext.to,
2512
- accountId: entry.deliveryContext.accountId
2513
- };
2514
- } catch {}
2515
- return {
2516
- deliveryContext,
2517
- threadId
2518
- };
2519
- }
2520
-
2521
- //#endregion
2522
- //#region src/config/sessions.ts
2523
- var sessions_exports = /* @__PURE__ */ __exportAll({
2524
- DEFAULT_IDLE_MINUTES: () => DEFAULT_IDLE_MINUTES,
2525
- DEFAULT_RESET_AT_HOUR: () => DEFAULT_RESET_AT_HOUR,
2526
- DEFAULT_RESET_MODE: () => DEFAULT_RESET_MODE,
2527
- DEFAULT_RESET_TRIGGER: () => DEFAULT_RESET_TRIGGER,
2528
- DEFAULT_RESET_TRIGGERS: () => DEFAULT_RESET_TRIGGERS,
2529
- SAFE_SESSION_ID_RE: () => SAFE_SESSION_ID_RE,
2530
- appendAssistantMessageToSessionTranscript: () => appendAssistantMessageToSessionTranscript,
2531
- buildGroupDisplayName: () => buildGroupDisplayName,
2532
- canonicalizeMainSessionAlias: () => canonicalizeMainSessionAlias,
2533
- capEntryCount: () => capEntryCount,
2534
- clearSessionStoreCacheForTest: () => clearSessionStoreCacheForTest,
2535
- deriveGroupSessionPatch: () => deriveGroupSessionPatch,
2536
- deriveSessionKey: () => deriveSessionKey,
2537
- deriveSessionMetaPatch: () => deriveSessionMetaPatch,
2538
- deriveSessionOrigin: () => deriveSessionOrigin,
2539
- enforceSessionDiskBudget: () => enforceSessionDiskBudget,
2540
- evaluateSessionFreshness: () => evaluateSessionFreshness,
2541
- extractDeliveryInfo: () => extractDeliveryInfo,
2542
- formatSessionArchiveTimestamp: () => formatSessionArchiveTimestamp,
2543
- getActiveSessionMaintenanceWarning: () => getActiveSessionMaintenanceWarning,
2544
- getSessionStoreLockQueueSizeForTest: () => getSessionStoreLockQueueSizeForTest,
2545
- isPrimarySessionTranscriptFileName: () => isPrimarySessionTranscriptFileName,
2546
- isSessionArchiveArtifactName: () => isSessionArchiveArtifactName,
2547
- isSessionTotalTokensFresh: () => isSessionTotalTokensFresh,
2548
- isThreadSessionKey: () => isThreadSessionKey,
2549
- loadSessionStore: () => loadSessionStore,
2550
- mergeSessionEntry: () => mergeSessionEntry,
2551
- normalizeSessionRuntimeModelFields: () => normalizeSessionRuntimeModelFields,
2552
- parseSessionArchiveTimestamp: () => parseSessionArchiveTimestamp,
2553
- parseSessionThreadInfo: () => parseSessionThreadInfo,
2554
- pruneStaleEntries: () => pruneStaleEntries,
2555
- readSessionUpdatedAt: () => readSessionUpdatedAt,
2556
- recordSessionMetaFromInbound: () => recordSessionMetaFromInbound,
2557
- resolveAgentIdFromSessionKey: () => resolveAgentIdFromSessionKey,
2558
- resolveAgentMainSessionKey: () => resolveAgentMainSessionKey,
2559
- resolveAndPersistSessionFile: () => resolveAndPersistSessionFile,
2560
- resolveChannelResetConfig: () => resolveChannelResetConfig,
2561
- resolveDailyResetAtMs: () => resolveDailyResetAtMs,
2562
- resolveDefaultSessionStorePath: () => resolveDefaultSessionStorePath,
2563
- resolveExplicitAgentSessionKey: () => resolveExplicitAgentSessionKey,
2564
- resolveFreshSessionTotalTokens: () => resolveFreshSessionTotalTokens,
2565
- resolveGroupSessionKey: () => resolveGroupSessionKey,
2566
- resolveMainSessionKey: () => resolveMainSessionKey,
2567
- resolveMainSessionKeyFromConfig: () => resolveMainSessionKeyFromConfig,
2568
- resolveMaintenanceConfig: () => resolveMaintenanceConfig,
2569
- resolveMirroredTranscriptText: () => resolveMirroredTranscriptText,
2570
- resolveSessionFilePath: () => resolveSessionFilePath,
2571
- resolveSessionFilePathOptions: () => resolveSessionFilePathOptions,
2572
- resolveSessionKey: () => resolveSessionKey,
2573
- resolveSessionResetPolicy: () => resolveSessionResetPolicy,
2574
- resolveSessionResetType: () => resolveSessionResetType,
2575
- resolveSessionTranscriptPath: () => resolveSessionTranscriptPath,
2576
- resolveSessionTranscriptPathInDir: () => resolveSessionTranscriptPathInDir,
2577
- resolveSessionTranscriptsDir: () => resolveSessionTranscriptsDir,
2578
- resolveSessionTranscriptsDirForAgent: () => resolveSessionTranscriptsDirForAgent,
2579
- resolveStorePath: () => resolveStorePath,
2580
- resolveThreadFlag: () => resolveThreadFlag,
2581
- rotateSessionFile: () => rotateSessionFile,
2582
- saveSessionStore: () => saveSessionStore,
2583
- setSessionRuntimeModel: () => setSessionRuntimeModel,
2584
- snapshotSessionOrigin: () => snapshotSessionOrigin,
2585
- updateLastRoute: () => updateLastRoute,
2586
- updateSessionStore: () => updateSessionStore,
2587
- updateSessionStoreEntry: () => updateSessionStoreEntry,
2588
- validateSessionId: () => validateSessionId,
2589
- withSessionStoreLockForTest: () => withSessionStoreLockForTest
2590
- });
2591
-
2592
- //#endregion
2593
- export { snapshotSessionOrigin as $, readSessionTitleFieldsFromTranscript as A, resolveChannelResetConfig as B, normalizeAccountId as C, cleanupArchivedSessionTranscripts as D, capArrayByJsonBytes as E, stripInlineDirectiveTagsForDisplay as F, resolveFreshSessionTotalTokens as G, resolveSessionResetType as H, stripInlineDirectiveTagsFromMessageForDisplay as I, resolveAgentMainSessionKey as J, setSessionRuntimeModel as K, cleanStaleLockFiles as L, stripEnvelopeFromMessage as M, stripEnvelopeFromMessages as N, readSessionMessages as O, parseInlineDirectives as P, deriveSessionMetaPatch as Q, resolveSessionKey as R, normalizeSessionDeliveryFields as S, archiveSessionTranscripts as T, resolveThreadFlag as U, resolveSessionResetPolicy as V, DEFAULT_RESET_TRIGGERS as W, resolveMainSessionKey as X, resolveExplicitAgentSessionKey as Y, resolveMainSessionKeyFromConfig as Z, updateSessionStoreEntry as _, resolveMirroredTranscriptText as a, mergeDeliveryContext as b, capEntryCount as c, readSessionUpdatedAt as d, formatSessionArchiveTimestamp as et, recordSessionMetaFromInbound as f, updateSessionStore as g, updateLastRoute as h, appendAssistantMessageToSessionTranscript as i, resolveSessionTranscriptCandidates as j, readSessionPreviewItemsFromTranscript as k, loadSessionStore as l, saveSessionStore as m, extractDeliveryInfo as n, buildGroupDisplayName as nt, resolveAndPersistSessionFile as o, resolveMaintenanceConfig as p, canonicalizeMainSessionAlias as q, parseSessionThreadInfo as r, resolveGroupSessionKey as rt, CURRENT_SESSION_VERSION as s, sessions_exports as t, isPrimarySessionTranscriptFileName as tt, pruneStaleEntries as u, enforceSessionDiskBudget as v, archiveFileOnDisk as w, normalizeDeliveryContext as x, deliveryContextFromSession as y, evaluateSessionFreshness as z };