remoteclaw 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2113) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +661 -0
  3. package/README.md +492 -0
  4. package/assets/chrome-extension/README.md +23 -0
  5. package/assets/chrome-extension/background-utils.js +48 -0
  6. package/assets/chrome-extension/background.js +899 -0
  7. package/assets/chrome-extension/icons/icon128.png +0 -0
  8. package/assets/chrome-extension/icons/icon16.png +0 -0
  9. package/assets/chrome-extension/icons/icon32.png +0 -0
  10. package/assets/chrome-extension/icons/icon48.png +0 -0
  11. package/assets/chrome-extension/manifest.json +25 -0
  12. package/assets/chrome-extension/options-validation.js +57 -0
  13. package/assets/chrome-extension/options.html +200 -0
  14. package/assets/chrome-extension/options.js +74 -0
  15. package/assets/clawtributor-avatar-placeholder.png +0 -0
  16. package/assets/dmg-background-small.png +0 -0
  17. package/assets/dmg-background.png +0 -0
  18. package/dist/account-lookup-C0ndrpt-.js +11 -0
  19. package/dist/account-lookup-CIY_RKhi.js +11 -0
  20. package/dist/accounts-B1M3fOxL.js +272 -0
  21. package/dist/accounts-B8PGQWQl.js +205 -0
  22. package/dist/accounts-CIVjmTg9.js +270 -0
  23. package/dist/accounts-D1awQXKu.js +36 -0
  24. package/dist/accounts-DHkGVGUR.js +36 -0
  25. package/dist/accounts-DyW1A_l8.js +206 -0
  26. package/dist/accounts-XFgBY644.js +47 -0
  27. package/dist/accounts-_ZuNC5bz.js +47 -0
  28. package/dist/accounts-uVavganx.js +32 -0
  29. package/dist/ack-reactions-B7iqdPZX.js +621 -0
  30. package/dist/ack-reactions-BapxA9fC.js +621 -0
  31. package/dist/acp-cli-7Plvw9pp.js +1316 -0
  32. package/dist/acp-cli-DmtggLxa.js +1311 -0
  33. package/dist/active-listener--jrUO-8L.js +37 -0
  34. package/dist/active-listener-DtU9K0MR.js +37 -0
  35. package/dist/agent-CX8QVdF4.js +688 -0
  36. package/dist/agent-HReIYVG-.js +687 -0
  37. package/dist/agent-helpers-5F0tdxud.js +400 -0
  38. package/dist/agent-helpers-Bs2nBXeI.js +400 -0
  39. package/dist/agent-scope-CWV-U3Ce.js +161 -0
  40. package/dist/agent-scope-FzE2oRm0.js +159 -0
  41. package/dist/agents-D9BWNEQX.js +769 -0
  42. package/dist/agents.config-0v2zcEf7.js +106 -0
  43. package/dist/agents.config-9DL6QCZc.js +106 -0
  44. package/dist/ansi-DtaiOnt1.js +107 -0
  45. package/dist/api-BE4ZCWWB.js +17 -0
  46. package/dist/api-wsk9zRVi.js +17 -0
  47. package/dist/argv-DW4MYBdJ.js +101 -0
  48. package/dist/audio-ClIuKwkl.js +43 -0
  49. package/dist/audio-DqlIYYTb.js +43 -0
  50. package/dist/audit-Bggny6TT.js +3089 -0
  51. package/dist/audit-DpuJ16Rj.js +3089 -0
  52. package/dist/auth-B-QK8JhI.js +315 -0
  53. package/dist/auth-C1zx1O24.js +314 -0
  54. package/dist/auth-DDmNYVMW.js +448 -0
  55. package/dist/auth-DH1wEw0w.js +448 -0
  56. package/dist/banner-BiLVJ0wV.js +294 -0
  57. package/dist/binaries-QJ-UTgL-.js +13 -0
  58. package/dist/bindings-6FvW-Ys9.js +69 -0
  59. package/dist/bindings-SnU_X1kX.js +69 -0
  60. package/dist/bonjour-discovery-AQMJqY4V.js +378 -0
  61. package/dist/bonjour-discovery-BLcPWHFJ.js +378 -0
  62. package/dist/boot/handler.js +1455 -0
  63. package/dist/brew-CBsS-Vq1.js +46 -0
  64. package/dist/brew-V4lMBeE3.js +46 -0
  65. package/dist/browser-cli-B5uW_onK.js +1690 -0
  66. package/dist/browser-cli-ClfZn9_h.js +1694 -0
  67. package/dist/build-info.json +5 -0
  68. package/dist/bundled/boot/HOOK.md +24 -0
  69. package/dist/bundled/command-logger/HOOK.md +122 -0
  70. package/dist/call-DHcgnRYq.js +518 -0
  71. package/dist/call-Wjjo7gwP.js +517 -0
  72. package/dist/canvas-host/a2ui/.bundle.hash +1 -0
  73. package/dist/canvas-host/a2ui/a2ui.bundle.js +17815 -0
  74. package/dist/canvas-host/a2ui/index.html +307 -0
  75. package/dist/catalog-CU0Xn2G1.js +186 -0
  76. package/dist/catalog-DDkwdGfX.js +186 -0
  77. package/dist/channel-account-context-BHIy71Yh.js +133 -0
  78. package/dist/channel-account-context-DXU_-EkJ.js +133 -0
  79. package/dist/channel-activity-BhT7NQ_v.js +94 -0
  80. package/dist/channel-activity-CvjEwpJz.js +94 -0
  81. package/dist/channel-activity-nsL1WwXH.js +292 -0
  82. package/dist/channel-options-B1tMfA9G.js +32 -0
  83. package/dist/channel-options-gEMUQQGy.js +33 -0
  84. package/dist/channel-selection-C3BMbeUs.js +51 -0
  85. package/dist/channel-selection-DHUO7WUa.js +51 -0
  86. package/dist/channel-web-DBCMnF6w.js +2132 -0
  87. package/dist/channel-web-DjD8eqnc.js +2134 -0
  88. package/dist/channels-cli-BfPB163m.js +1436 -0
  89. package/dist/channels-cli-dEMJmZF8.js +1440 -0
  90. package/dist/channels-status-issues-BMadvA0-.js +18 -0
  91. package/dist/channels-status-issues-D5fT2H21.js +18 -0
  92. package/dist/chat-envelope-AJFUAuBM.js +248 -0
  93. package/dist/chat-envelope-BrfcPlDM.js +248 -0
  94. package/dist/chat-type-BP9akbag.js +11 -0
  95. package/dist/chat-type-CH3W-zKy.js +11 -0
  96. package/dist/chrome-BQX0gpUh.js +1732 -0
  97. package/dist/chrome-CIytlE5x.js +1733 -0
  98. package/dist/chunk-BAMyFYtF.js +341 -0
  99. package/dist/chunk-BzVoFUZL.js +341 -0
  100. package/dist/clack-prompter-C6mBTOzE.js +122 -0
  101. package/dist/clack-prompter-DKcYqv3o.js +121 -0
  102. package/dist/cleanup-utils-Cb-leJcy.js +94 -0
  103. package/dist/cleanup-utils-ZC2zvntc.js +94 -0
  104. package/dist/cli/daemon-cli.js +9 -0
  105. package/dist/cli-BErCYGAt.js +131 -0
  106. package/dist/cli-EEZfdXxg.js +135 -0
  107. package/dist/cli-name-BZsYSp9l.js +23 -0
  108. package/dist/cli-name-CRe5Ow_t.js +23 -0
  109. package/dist/cli-utils-BUOtyfnU.js +16 -0
  110. package/dist/cli-utils-CGB3cBZm.js +16 -0
  111. package/dist/client-1TPQCsEe.js +2311 -0
  112. package/dist/client-9dK56xly.js +22 -0
  113. package/dist/client-CBpe99dr.js +2311 -0
  114. package/dist/client-D-R1YdRD.js +22 -0
  115. package/dist/clipboard-A06eV_5C.js +31 -0
  116. package/dist/clipboard-DQBl3coj.js +31 -0
  117. package/dist/command-format-BiiNHkWG.js +18 -0
  118. package/dist/command-format-Dntg_tnC.js +32 -0
  119. package/dist/command-logger/handler.js +57 -0
  120. package/dist/command-options-CnHA4TzR.js +26 -0
  121. package/dist/command-options-D2nN4AXX.js +26 -0
  122. package/dist/command-registry-BnrYqd5P.js +215 -0
  123. package/dist/commands-BrlSPrp8.js +41 -0
  124. package/dist/commands-keXWOHRq.js +41 -0
  125. package/dist/commands-registry-Cz77bvxB.js +887 -0
  126. package/dist/commands-registry-DRX3F4kj.js +888 -0
  127. package/dist/common-CBefYisq.js +156 -0
  128. package/dist/common-D4fL3S2m.js +156 -0
  129. package/dist/completion-cli-CXb-Xk3v.js +452 -0
  130. package/dist/completion-cli-Ca4Y7cQg.js +452 -0
  131. package/dist/config-CqP5tE9Z.js +3317 -0
  132. package/dist/config-cli-BYqebY6-.js +247 -0
  133. package/dist/config-cli-DKXHNFPz.js +243 -0
  134. package/dist/config-eval-BQIR-wSg.js +102 -0
  135. package/dist/config-eval-Bh82JoXK.js +102 -0
  136. package/dist/config-guard-BBPYncEK.js +92 -0
  137. package/dist/config-guard-CTQwNBtb.js +75 -0
  138. package/dist/config-qAZfcdDM.js +3315 -0
  139. package/dist/config-validation-BrjiFbBk.js +18 -0
  140. package/dist/config-validation-DSXKFJHF.js +18 -0
  141. package/dist/configure-C--DXb5y.js +885 -0
  142. package/dist/configure-D7tKM02_.js +883 -0
  143. package/dist/constants-BBVTjb1j.js +75 -0
  144. package/dist/constants-C7j1VA2S.js +12 -0
  145. package/dist/constants-DoYLsBmv.js +12 -0
  146. package/dist/constants-PMRtHBHU.js +75 -0
  147. package/dist/control-auth-BB_AdEQ8.js +397 -0
  148. package/dist/control-auth-Drc3vO7k.js +397 -0
  149. package/dist/control-ui/apple-touch-icon.png +0 -0
  150. package/dist/control-ui/assets/index-DdiU_ccM.css +1 -0
  151. package/dist/control-ui/assets/index-kVUYi64u.js +7723 -0
  152. package/dist/control-ui/assets/index-kVUYi64u.js.map +1 -0
  153. package/dist/control-ui/assets/pt-BR-eq0TfCI7.js +2 -0
  154. package/dist/control-ui/assets/pt-BR-eq0TfCI7.js.map +1 -0
  155. package/dist/control-ui/assets/zh-CN-DmLG2MF9.js +2 -0
  156. package/dist/control-ui/assets/zh-CN-DmLG2MF9.js.map +1 -0
  157. package/dist/control-ui/assets/zh-TW-BLErH0EM.js +2 -0
  158. package/dist/control-ui/assets/zh-TW-BLErH0EM.js.map +1 -0
  159. package/dist/control-ui/favicon-32.png +0 -0
  160. package/dist/control-ui/favicon.ico +0 -0
  161. package/dist/control-ui/favicon.svg +67 -0
  162. package/dist/control-ui/index.html +17 -0
  163. package/dist/control-ui-assets-DO1L6M0S.js +186 -0
  164. package/dist/control-ui-assets-S_TLo6Fs.js +186 -0
  165. package/dist/conversation-label-CDH4rKMG.js +36 -0
  166. package/dist/conversation-label-CMOfgCVl.js +36 -0
  167. package/dist/credentials-C_RoJFmK.js +91 -0
  168. package/dist/credentials-DM_Dj0m8.js +91 -0
  169. package/dist/cron-cli-DrEGbTLF.js +499 -0
  170. package/dist/cron-cli-iMnjEJcP.js +495 -0
  171. package/dist/daemon-cli-BXOrRB0h.js +735 -0
  172. package/dist/daemon-cli-DbOrC1C6.js +737 -0
  173. package/dist/daemon-cli.js +14217 -0
  174. package/dist/daemon-install-LufHc-Sn.js +60 -0
  175. package/dist/daemon-install-WEBvqVOj.js +56 -0
  176. package/dist/daemon-install-helpers-4BLEBjpg.js +504 -0
  177. package/dist/daemon-install-helpers-DVr51zvE.js +504 -0
  178. package/dist/daemon-runtime-9oDBR7YW.js +13 -0
  179. package/dist/daemon-runtime-CzFI2dPw.js +13 -0
  180. package/dist/dangerous-name-matching-BlTBBZns.js +45 -0
  181. package/dist/dangerous-name-matching-CSq9sJDG.js +45 -0
  182. package/dist/dangerous-tools-BRmbBvRf.js +253 -0
  183. package/dist/dangerous-tools-D4jtl72G.js +253 -0
  184. package/dist/deliver-C3Xs-DSE.js +481 -0
  185. package/dist/deliver-D49hWPWI.js +481 -0
  186. package/dist/delivery-queue-BDvalA10.js +244 -0
  187. package/dist/delivery-queue-BLMWPoKl.js +244 -0
  188. package/dist/devices-cli-6XBBb605.js +323 -0
  189. package/dist/devices-cli-BmB_Y5Tj.js +319 -0
  190. package/dist/diagnostics-BzzhTQzK.js +35 -0
  191. package/dist/diagnostics-DILtxtcE.js +35 -0
  192. package/dist/directory-cli-BnVIzNxj.js +225 -0
  193. package/dist/directory-cli-I7RtmvoP.js +221 -0
  194. package/dist/dispatcher-B7Yu14v7.js +173 -0
  195. package/dist/dispatcher-ClUtg8F9.js +174 -0
  196. package/dist/dm-policy-shared-Cd6QFFx6.js +22 -0
  197. package/dist/dm-policy-shared-DqkEp7h7.js +22 -0
  198. package/dist/dns-cli-Cm47-vJu.js +203 -0
  199. package/dist/dns-cli-DW4a6yJH.js +199 -0
  200. package/dist/dock-BFxpyZEm.js +906 -0
  201. package/dist/dock-Hf1acwVy.js +907 -0
  202. package/dist/doctor-completion-CefSDbii.js +92 -0
  203. package/dist/doctor-completion-DuOl6k-Z.js +92 -0
  204. package/dist/doctor-config-flow-DQdWVm5G.js +979 -0
  205. package/dist/doctor-config-flow-DZCCqya1.js +978 -0
  206. package/dist/enable-C3I9dWel.js +59 -0
  207. package/dist/enable-DnwKeWnR.js +59 -0
  208. package/dist/entry.js +2674 -0
  209. package/dist/env-DyyqmxSM.js +60 -0
  210. package/dist/env-vars-CD2_baIP.js +43 -0
  211. package/dist/env-vars-a7S70ba7.js +43 -0
  212. package/dist/errors-0dfGxeYQ.js +35 -0
  213. package/dist/errors-C1kDByVU.js +35 -0
  214. package/dist/exec-CAk1dxq_.js +164 -0
  215. package/dist/exec-epNpA1aU.js +164 -0
  216. package/dist/export-html/template.css +1024 -0
  217. package/dist/export-html/template.html +88 -0
  218. package/dist/export-html/template.js +1766 -0
  219. package/dist/export-html/vendor/highlight.min.js +1213 -0
  220. package/dist/export-html/vendor/marked.min.js +6 -0
  221. package/dist/extensionAPI.js +11699 -0
  222. package/dist/fetch-BMQq41sB.js +281 -0
  223. package/dist/fetch-CduIccDV.js +67 -0
  224. package/dist/fetch-Cky99wYB.js +281 -0
  225. package/dist/fetch-D3tw4B4n.js +67 -0
  226. package/dist/fetch-DTsU2XnC.js +67 -0
  227. package/dist/fetch-timeout-CytN1wiO.js +43 -0
  228. package/dist/fetch-timeout-DBRRPNBi.js +43 -0
  229. package/dist/file-identity-CeRK5CJC.js +12 -0
  230. package/dist/file-lock-DWH0TfVu.js +107 -0
  231. package/dist/file-lock-DXW9h9ek.js +107 -0
  232. package/dist/format-duration-B-Uv5nOi.js +35 -0
  233. package/dist/format-duration-Oj8pTbYL.js +35 -0
  234. package/dist/format-relative-Czf5fUjn.js +55 -0
  235. package/dist/format-relative-zwkkXJvs.js +55 -0
  236. package/dist/fs-safe-BjSd07M4.js +115 -0
  237. package/dist/fs-safe-aWIhCWlb.js +125 -0
  238. package/dist/gateway-cli-BQ5Nrc2v.js +24127 -0
  239. package/dist/gateway-cli-x9Pn-J8m.js +24131 -0
  240. package/dist/gateway-rpc-C9zLj_Sl.js +28 -0
  241. package/dist/gateway-rpc-Cdx4sTh5.js +28 -0
  242. package/dist/gmail-setup-utils-CKyh29_R.js +422 -0
  243. package/dist/gmail-setup-utils-DquflkMR.js +423 -0
  244. package/dist/health-DlRS-gIZ.js +1414 -0
  245. package/dist/health-UZKtVUZc.js +1417 -0
  246. package/dist/health-format-BE5TK5bs.js +28 -0
  247. package/dist/health-format-DF54wvUU.js +28 -0
  248. package/dist/heartbeat-visibility-98-alasQ.js +125 -0
  249. package/dist/heartbeat-visibility-CGSqfsb3.js +125 -0
  250. package/dist/heartbeat-wake-CvHncCjP.js +182 -0
  251. package/dist/heartbeat-wake-DLxQm6-U.js +182 -0
  252. package/dist/help-format-CJQ7APRn.js +17 -0
  253. package/dist/help-format-D3JhWp1E.js +17 -0
  254. package/dist/helpers-703bXVlF.js +25 -0
  255. package/dist/helpers-DAEoFkbn.js +10 -0
  256. package/dist/helpers-n2CtWpm9.js +25 -0
  257. package/dist/helpers-ndPQWl6m.js +10 -0
  258. package/dist/hook-runner-global-nAi_RVmo.js +527 -0
  259. package/dist/hooks-cli-BN23UkSe.js +1221 -0
  260. package/dist/hooks-cli-CCigUQAP.js +1217 -0
  261. package/dist/host-env-security-BGibnCbS.js +106 -0
  262. package/dist/host-env-security-axRnIi8d.js +106 -0
  263. package/dist/image-ops-CX41n0v5.js +354 -0
  264. package/dist/image-ops-DSL3eFfQ.js +354 -0
  265. package/dist/import-BwboAUxS.js +604 -0
  266. package/dist/import-TnR4slPl.js +606 -0
  267. package/dist/inbound-context-BLy-G2Eq.js +68 -0
  268. package/dist/inbound-context-Cuu0thCw.js +68 -0
  269. package/dist/index.js +598 -0
  270. package/dist/input-provenance-gIfDn1ki.js +35 -0
  271. package/dist/input-provenance-wkso1o5V.js +35 -0
  272. package/dist/inspect-BEpFbi0c.js +286 -0
  273. package/dist/inspect-BeNNpWna.js +286 -0
  274. package/dist/installs-BmtDxAA-.js +319 -0
  275. package/dist/installs-DJ188C74.js +319 -0
  276. package/dist/ip-D4VG5EJO.js +200 -0
  277. package/dist/ip-MwCwRA7c.js +200 -0
  278. package/dist/ipv4-DNo9AFDu.js +46 -0
  279. package/dist/ipv4-VfoVR5uR.js +46 -0
  280. package/dist/ir-DRpvvv-1.js +972 -0
  281. package/dist/is-main-BE1Jih91.js +30 -0
  282. package/dist/json-file-BW22hGtf.js +25 -0
  283. package/dist/json-file-DwRAfAAy.js +25 -0
  284. package/dist/json-files-BI20PLIm.js +46 -0
  285. package/dist/json-files-Dy52honG.js +46 -0
  286. package/dist/lanes-1CBKdsiR.js +58 -0
  287. package/dist/lanes-DqVYfPRG.js +58 -0
  288. package/dist/lifecycle-core-BzhjWI2E.js +476 -0
  289. package/dist/lifecycle-core-DctTLBFp.js +474 -0
  290. package/dist/links-CtGBIrG8.js +15 -0
  291. package/dist/links-CwTlzaPe.js +15 -0
  292. package/dist/loader-BLMpE4uG.js +22397 -0
  293. package/dist/loader-C5cQlGXB.js +22400 -0
  294. package/dist/location-BUhzov-a.js +43 -0
  295. package/dist/location-Qo8Ii1zo.js +43 -0
  296. package/dist/logger-ASsO5Nz-.js +49 -0
  297. package/dist/logger-B8BE0PyS.js +12 -0
  298. package/dist/logger-CPvz-aPM.js +47 -0
  299. package/dist/logger-cL0D2DCr.js +12 -0
  300. package/dist/logging-Cd9y2AdQ.js +20 -0
  301. package/dist/logging-DRwtiLIS.js +1 -0
  302. package/dist/logging-DTEoeoa3.js +19 -0
  303. package/dist/logging-fywhKCmE.js +1 -0
  304. package/dist/login-B5TdMKIC.js +61 -0
  305. package/dist/login-Cak5EAvl.js +62 -0
  306. package/dist/login-qr-BuTJwO4R.js +329 -0
  307. package/dist/login-qr-Do-8NFKK.js +325 -0
  308. package/dist/logs-cli-BkCweYSR.js +240 -0
  309. package/dist/logs-cli-CMUTrgGH.js +236 -0
  310. package/dist/markdown-tables-B3sXo71y.js +29 -0
  311. package/dist/markdown-tables-C48ANSSq.js +29 -0
  312. package/dist/media-DcDCPyuW.js +971 -0
  313. package/dist/media-DgxPvn2i.js +9492 -0
  314. package/dist/message-action-names-BwpFcASf.js +2520 -0
  315. package/dist/message-action-names-CH6TDClE.js +2520 -0
  316. package/dist/message-channel-CtcVHawF.js +91 -0
  317. package/dist/message-channel-tuc9CdEw.js +91 -0
  318. package/dist/mime-CAqaK3kp.js +146 -0
  319. package/dist/mime-ViuhRuMM.js +146 -0
  320. package/dist/mutable-allowlist-detectors-BXE7Hr7F.js +64 -0
  321. package/dist/mutable-allowlist-detectors-CtKavajp.js +64 -0
  322. package/dist/net-DSkFMHJ8.js +225 -0
  323. package/dist/net-DTqfFYzt.js +225 -0
  324. package/dist/node-cli-DTp-eCFc.js +1386 -0
  325. package/dist/node-cli-Yd_KvTgV.js +1390 -0
  326. package/dist/node-service-RyMlWp8N.js +67 -0
  327. package/dist/node-service-TL9b6Qfz.js +67 -0
  328. package/dist/nodes-cli-BcXyjWnw.js +1350 -0
  329. package/dist/nodes-cli-DHHf5weG.js +1346 -0
  330. package/dist/nodes-screen-B7HJugJ0.js +250 -0
  331. package/dist/nodes-screen-nCRd71Mk.js +250 -0
  332. package/dist/note-B6142LyJ.js +92 -0
  333. package/dist/note-D-EI0czq.js +92 -0
  334. package/dist/npm-registry-spec-PPyRXSpx.js +786 -0
  335. package/dist/npm-registry-spec-uUmDWe6v.js +786 -0
  336. package/dist/npm-resolution-C-6NY92-.js +86 -0
  337. package/dist/npm-resolution-DSRcDO7P.js +86 -0
  338. package/dist/onboard-D0pXb_02.js +645 -0
  339. package/dist/onboard-DdAR-LF_.js +647 -0
  340. package/dist/onboard-auth-cNtb3FTP.js +211 -0
  341. package/dist/onboard-auth-gwz-0mZ6.js +207 -0
  342. package/dist/onboard-channels-8SAR1gMS.js +2618 -0
  343. package/dist/onboard-channels-tRmXz2Lj.js +2619 -0
  344. package/dist/onboard-config-DOmXYEvJ.js +39 -0
  345. package/dist/onboard-config-JmR21VYa.js +39 -0
  346. package/dist/onboard-helpers-DGVxeLf_.js +358 -0
  347. package/dist/onboard-helpers-DdqoC3w8.js +357 -0
  348. package/dist/onboard-remote-CspZpXS9.js +127 -0
  349. package/dist/onboard-remote-DJcHZQqI.js +127 -0
  350. package/dist/onboarding-BH0siVu3.js +586 -0
  351. package/dist/onboarding-CKmRrgeq.js +588 -0
  352. package/dist/onboarding.finalize-BGyWeNH5.js +402 -0
  353. package/dist/onboarding.finalize-BpVbqIc1.js +404 -0
  354. package/dist/onboarding.gateway-config-B4xt1gtO.js +202 -0
  355. package/dist/onboarding.gateway-config-CT9RcbVE.js +196 -0
  356. package/dist/outbound-B3wlEY-e.js +220 -0
  357. package/dist/outbound-KHig2PTG.js +221 -0
  358. package/dist/outbound-attachment-BZkefkAT.js +18 -0
  359. package/dist/outbound-attachment-D5FMlKjS.js +18 -0
  360. package/dist/outbound-attachment-DjvyU7Oq.js +18 -0
  361. package/dist/pairing-cli-BTwS98JV.js +130 -0
  362. package/dist/pairing-cli-C8jztqm2.js +126 -0
  363. package/dist/pairing-labels-E2eoE9tc.js +9 -0
  364. package/dist/pairing-labels-Ks4ey7DT.js +9 -0
  365. package/dist/pairing-store-C7DF-eCM.js +460 -0
  366. package/dist/pairing-store-CU4_h9xa.js +459 -0
  367. package/dist/parse-log-line-GisaZn5H.js +44 -0
  368. package/dist/parse-log-line-ZsbwG_u7.js +44 -0
  369. package/dist/parse-timeout-BpphuwYl.js +16 -0
  370. package/dist/parse-timeout-CE6BjmGU.js +16 -0
  371. package/dist/path-env-DMKJ1GE3.js +89 -0
  372. package/dist/path-env-Dq-jhL2Z.js +89 -0
  373. package/dist/path-safety-BFE0XmGC.js +14 -0
  374. package/dist/path-safety-BJ8ge6Ho.js +14 -0
  375. package/dist/paths-DHuXVC00.js +229 -0
  376. package/dist/plugin-auto-enable-Bms-lvxW.js +289 -0
  377. package/dist/plugin-auto-enable-fc5IL3zs.js +288 -0
  378. package/dist/plugin-registry-BrQP6X71.js +33 -0
  379. package/dist/plugin-registry-nbb06LsB.js +33 -0
  380. package/dist/plugin-sdk/account-id.d.ts +1 -0
  381. package/dist/plugin-sdk/account-id.js +34 -0
  382. package/dist/plugin-sdk/agents/agent-helpers/errors.d.ts +55 -0
  383. package/dist/plugin-sdk/agents/agent-helpers/google.d.ts +3 -0
  384. package/dist/plugin-sdk/agents/agent-helpers/images.d.ts +21 -0
  385. package/dist/plugin-sdk/agents/agent-helpers/message-sanitization.d.ts +14 -0
  386. package/dist/plugin-sdk/agents/agent-helpers/messaging-dedupe.d.ts +10 -0
  387. package/dist/plugin-sdk/agents/agent-helpers/openai.d.ts +9 -0
  388. package/dist/plugin-sdk/agents/agent-helpers/turns.d.ts +20 -0
  389. package/dist/plugin-sdk/agents/agent-helpers/types.d.ts +1 -0
  390. package/dist/plugin-sdk/agents/agent-helpers.d.ts +10 -0
  391. package/dist/plugin-sdk/agents/agent-messaging.d.ts +8 -0
  392. package/dist/plugin-sdk/agents/agent-scope.d.ts +81 -0
  393. package/dist/plugin-sdk/agents/agent-types.d.ts +73 -0
  394. package/dist/plugin-sdk/agents/agent-utils.d.ts +25 -0
  395. package/dist/plugin-sdk/agents/announce-idempotency.d.ts +11 -0
  396. package/dist/plugin-sdk/agents/block-chunker.d.ts +19 -0
  397. package/dist/plugin-sdk/agents/channel-tools.d.ts +27 -0
  398. package/dist/plugin-sdk/agents/cli-session.d.ts +3 -0
  399. package/dist/plugin-sdk/agents/current-time.d.ts +17 -0
  400. package/dist/plugin-sdk/agents/date-time.d.ts +13 -0
  401. package/dist/plugin-sdk/agents/identity-avatar.d.ts +15 -0
  402. package/dist/plugin-sdk/agents/identity.d.ts +28 -0
  403. package/dist/plugin-sdk/agents/image-sanitization.d.ts +8 -0
  404. package/dist/plugin-sdk/agents/lanes.d.ts +3 -0
  405. package/dist/plugin-sdk/agents/live-auth-keys.d.ts +6 -0
  406. package/dist/plugin-sdk/agents/owner-display.d.ts +19 -0
  407. package/dist/plugin-sdk/agents/provider-utils.d.ts +20 -0
  408. package/dist/plugin-sdk/agents/schema/typebox.d.ts +14 -0
  409. package/dist/plugin-sdk/agents/session-write-lock.d.ts +53 -0
  410. package/dist/plugin-sdk/agents/stable-stringify.d.ts +1 -0
  411. package/dist/plugin-sdk/agents/subagent-announce-queue.d.ts +24 -0
  412. package/dist/plugin-sdk/agents/subagent-announce.d.ts +39 -0
  413. package/dist/plugin-sdk/agents/subagent-depth.d.ts +11 -0
  414. package/dist/plugin-sdk/agents/subagent-lifecycle-events.d.ts +18 -0
  415. package/dist/plugin-sdk/agents/subagent-registry-cleanup.d.ts +24 -0
  416. package/dist/plugin-sdk/agents/subagent-registry-completion.d.ts +15 -0
  417. package/dist/plugin-sdk/agents/subagent-registry-queries.d.ts +11 -0
  418. package/dist/plugin-sdk/agents/subagent-registry-state.d.ts +7 -0
  419. package/dist/plugin-sdk/agents/subagent-registry.d.ts +45 -0
  420. package/dist/plugin-sdk/agents/subagent-registry.store.d.ts +4 -0
  421. package/dist/plugin-sdk/agents/subagent-registry.types.d.ts +34 -0
  422. package/dist/plugin-sdk/agents/subagent-spawn.d.ts +46 -0
  423. package/dist/plugin-sdk/agents/timeout.d.ts +8 -0
  424. package/dist/plugin-sdk/agents/tool-call-id.d.ts +27 -0
  425. package/dist/plugin-sdk/agents/tool-display-common.d.ts +32 -0
  426. package/dist/plugin-sdk/agents/tool-display.d.ts +15 -0
  427. package/dist/plugin-sdk/agents/tool-images.d.ts +10 -0
  428. package/dist/plugin-sdk/agents/tools/agent-step.d.ts +15 -0
  429. package/dist/plugin-sdk/agents/tools/common.d.ts +80 -0
  430. package/dist/plugin-sdk/agents/tools/discord-actions-guild.d.ts +4 -0
  431. package/dist/plugin-sdk/agents/tools/discord-actions-messaging.d.ts +6 -0
  432. package/dist/plugin-sdk/agents/tools/discord-actions-moderation-shared.d.ts +13 -0
  433. package/dist/plugin-sdk/agents/tools/discord-actions-moderation.d.ts +4 -0
  434. package/dist/plugin-sdk/agents/tools/discord-actions-presence.d.ts +4 -0
  435. package/dist/plugin-sdk/agents/tools/discord-actions.d.ts +5 -0
  436. package/dist/plugin-sdk/agents/tools/sessions-access.d.ts +42 -0
  437. package/dist/plugin-sdk/agents/tools/sessions-helpers.d.ts +51 -0
  438. package/dist/plugin-sdk/agents/tools/sessions-resolution.d.ts +59 -0
  439. package/dist/plugin-sdk/agents/tools/sessions-send-helpers.d.ts +34 -0
  440. package/dist/plugin-sdk/agents/tools/slack-actions.d.ts +15 -0
  441. package/dist/plugin-sdk/agents/tools/telegram-actions.d.ts +7 -0
  442. package/dist/plugin-sdk/agents/tools/whatsapp-actions.d.ts +3 -0
  443. package/dist/plugin-sdk/agents/tools/whatsapp-target-auth.d.ts +10 -0
  444. package/dist/plugin-sdk/agents/usage.d.ts +49 -0
  445. package/dist/plugin-sdk/agents/workspace.d.ts +1 -0
  446. package/dist/plugin-sdk/auth/api-key-rotation.d.ts +22 -0
  447. package/dist/plugin-sdk/auth/constants.d.ts +15 -0
  448. package/dist/plugin-sdk/auth/display.d.ts +7 -0
  449. package/dist/plugin-sdk/auth/doctor.d.ts +8 -0
  450. package/dist/plugin-sdk/auth/env-injection.d.ts +38 -0
  451. package/dist/plugin-sdk/auth/index.d.ts +10 -0
  452. package/dist/plugin-sdk/auth/oauth.d.ts +13 -0
  453. package/dist/plugin-sdk/auth/order.d.ts +8 -0
  454. package/dist/plugin-sdk/auth/paths.d.ts +3 -0
  455. package/dist/plugin-sdk/auth/profiles.d.ts +11 -0
  456. package/dist/plugin-sdk/auth/provider-auth.d.ts +32 -0
  457. package/dist/plugin-sdk/auth/store.d.ts +7 -0
  458. package/dist/plugin-sdk/auth/types.d.ts +45 -0
  459. package/dist/plugin-sdk/auth/usage.d.ts +80 -0
  460. package/dist/plugin-sdk/auto-reply/chunk.d.ts +45 -0
  461. package/dist/plugin-sdk/auto-reply/command-auth.d.ts +17 -0
  462. package/dist/plugin-sdk/auto-reply/command-detection.d.ts +13 -0
  463. package/dist/plugin-sdk/auto-reply/commands-args.d.ts +3 -0
  464. package/dist/plugin-sdk/auto-reply/commands-registry.d.ts +47 -0
  465. package/dist/plugin-sdk/auto-reply/commands-registry.data.d.ts +3 -0
  466. package/dist/plugin-sdk/auto-reply/commands-registry.types.d.ts +66 -0
  467. package/dist/plugin-sdk/auto-reply/dispatch.d.ts +32 -0
  468. package/dist/plugin-sdk/auto-reply/envelope.d.ts +58 -0
  469. package/dist/plugin-sdk/auto-reply/fallback-state.d.ts +55 -0
  470. package/dist/plugin-sdk/auto-reply/group-activation.d.ts +6 -0
  471. package/dist/plugin-sdk/auto-reply/heartbeat-reply-payload.d.ts +2 -0
  472. package/dist/plugin-sdk/auto-reply/heartbeat.d.ts +16 -0
  473. package/dist/plugin-sdk/auto-reply/inbound-debounce.d.ts +17 -0
  474. package/dist/plugin-sdk/auto-reply/media-note.d.ts +2 -0
  475. package/dist/plugin-sdk/auto-reply/model.d.ts +8 -0
  476. package/dist/plugin-sdk/auto-reply/reply/abort.d.ts +32 -0
  477. package/dist/plugin-sdk/auto-reply/reply/agent-runner-execution.d.ts +58 -0
  478. package/dist/plugin-sdk/auto-reply/reply/agent-runner-helpers.d.ts +15 -0
  479. package/dist/plugin-sdk/auto-reply/reply/agent-runner-payloads.d.ts +27 -0
  480. package/dist/plugin-sdk/auto-reply/reply/agent-runner-utils.d.ts +119 -0
  481. package/dist/plugin-sdk/auto-reply/reply/agent-runner.d.ts +36 -0
  482. package/dist/plugin-sdk/auto-reply/reply/block-reply-coalescer.d.ts +15 -0
  483. package/dist/plugin-sdk/auto-reply/reply/block-reply-pipeline.d.ts +31 -0
  484. package/dist/plugin-sdk/auto-reply/reply/block-streaming.d.ts +22 -0
  485. package/dist/plugin-sdk/auto-reply/reply/body.d.ts +10 -0
  486. package/dist/plugin-sdk/auto-reply/reply/command-gates.d.ts +18 -0
  487. package/dist/plugin-sdk/auto-reply/reply/commands-allowlist.d.ts +2 -0
  488. package/dist/plugin-sdk/auto-reply/reply/commands-config.d.ts +3 -0
  489. package/dist/plugin-sdk/auto-reply/reply/commands-context.d.ts +12 -0
  490. package/dist/plugin-sdk/auto-reply/reply/commands-core.d.ts +13 -0
  491. package/dist/plugin-sdk/auto-reply/reply/commands-export-session.d.ts +3 -0
  492. package/dist/plugin-sdk/auto-reply/reply/commands-info.d.ts +11 -0
  493. package/dist/plugin-sdk/auto-reply/reply/commands-plugin.d.ts +13 -0
  494. package/dist/plugin-sdk/auto-reply/reply/commands-session.d.ts +8 -0
  495. package/dist/plugin-sdk/auto-reply/reply/commands-setunset-standard.d.ts +10 -0
  496. package/dist/plugin-sdk/auto-reply/reply/commands-setunset.d.ts +34 -0
  497. package/dist/plugin-sdk/auto-reply/reply/commands-slash-parse.d.ts +24 -0
  498. package/dist/plugin-sdk/auto-reply/reply/commands-status.d.ts +20 -0
  499. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-agents.d.ts +3 -0
  500. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-focus.d.ts +3 -0
  501. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-help.d.ts +2 -0
  502. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-info.d.ts +3 -0
  503. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-kill.d.ts +3 -0
  504. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-list.d.ts +3 -0
  505. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-log.d.ts +3 -0
  506. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-send.d.ts +3 -0
  507. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-spawn.d.ts +3 -0
  508. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/action-unfocus.d.ts +3 -0
  509. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/shared.d.ts +81 -0
  510. package/dist/plugin-sdk/auto-reply/reply/commands-subagents.d.ts +4 -0
  511. package/dist/plugin-sdk/auto-reply/reply/commands-tts.d.ts +2 -0
  512. package/dist/plugin-sdk/auto-reply/reply/commands-types.d.ts +49 -0
  513. package/dist/plugin-sdk/auto-reply/reply/commands.d.ts +4 -0
  514. package/dist/plugin-sdk/auto-reply/reply/config-commands.d.ts +15 -0
  515. package/dist/plugin-sdk/auto-reply/reply/config-value.d.ts +4 -0
  516. package/dist/plugin-sdk/auto-reply/reply/debug-commands.d.ts +16 -0
  517. package/dist/plugin-sdk/auto-reply/reply/directive-handling.d.ts +6 -0
  518. package/dist/plugin-sdk/auto-reply/reply/directive-handling.fast-lane.d.ts +7 -0
  519. package/dist/plugin-sdk/auto-reply/reply/directive-handling.impl.d.ts +3 -0
  520. package/dist/plugin-sdk/auto-reply/reply/directive-handling.levels.d.ts +11 -0
  521. package/dist/plugin-sdk/auto-reply/reply/directive-handling.params.d.ts +49 -0
  522. package/dist/plugin-sdk/auto-reply/reply/directive-handling.parse.d.ts +37 -0
  523. package/dist/plugin-sdk/auto-reply/reply/directive-handling.persist.d.ts +39 -0
  524. package/dist/plugin-sdk/auto-reply/reply/directive-handling.queue-validation.d.ts +10 -0
  525. package/dist/plugin-sdk/auto-reply/reply/directive-handling.shared.d.ts +4 -0
  526. package/dist/plugin-sdk/auto-reply/reply/directive-parsing.d.ts +5 -0
  527. package/dist/plugin-sdk/auto-reply/reply/directives.d.ts +19 -0
  528. package/dist/plugin-sdk/auto-reply/reply/dispatch-from-config.d.ts +16 -0
  529. package/dist/plugin-sdk/auto-reply/reply/dispatcher-registry.d.ts +24 -0
  530. package/dist/plugin-sdk/auto-reply/reply/followup-runner.d.ts +16 -0
  531. package/dist/plugin-sdk/auto-reply/reply/get-reply-directives-apply.d.ts +55 -0
  532. package/dist/plugin-sdk/auto-reply/reply/get-reply-directives-utils.d.ts +2 -0
  533. package/dist/plugin-sdk/auto-reply/reply/get-reply-directives.d.ts +102 -0
  534. package/dist/plugin-sdk/auto-reply/reply/get-reply-inline-actions.d.ts +45 -0
  535. package/dist/plugin-sdk/auto-reply/reply/get-reply-run.d.ts +59 -0
  536. package/dist/plugin-sdk/auto-reply/reply/get-reply.d.ts +4 -0
  537. package/dist/plugin-sdk/auto-reply/reply/groups.d.ts +26 -0
  538. package/dist/plugin-sdk/auto-reply/reply/history.d.ts +72 -0
  539. package/dist/plugin-sdk/auto-reply/reply/inbound-context.d.ts +8 -0
  540. package/dist/plugin-sdk/auto-reply/reply/inbound-dedupe.d.ts +8 -0
  541. package/dist/plugin-sdk/auto-reply/reply/inbound-meta.d.ts +3 -0
  542. package/dist/plugin-sdk/auto-reply/reply/inbound-text.d.ts +1 -0
  543. package/dist/plugin-sdk/auto-reply/reply/line-directives.d.ts +22 -0
  544. package/dist/plugin-sdk/auto-reply/reply/mentions.d.ts +19 -0
  545. package/dist/plugin-sdk/auto-reply/reply/normalize-reply.d.ts +11 -0
  546. package/dist/plugin-sdk/auto-reply/reply/origin-routing.d.ts +13 -0
  547. package/dist/plugin-sdk/auto-reply/reply/provider-dispatcher.d.ts +19 -0
  548. package/dist/plugin-sdk/auto-reply/reply/queue/cleanup.d.ts +6 -0
  549. package/dist/plugin-sdk/auto-reply/reply/queue/directive.d.ts +15 -0
  550. package/dist/plugin-sdk/auto-reply/reply/queue/drain.d.ts +2 -0
  551. package/dist/plugin-sdk/auto-reply/reply/queue/enqueue.d.ts +3 -0
  552. package/dist/plugin-sdk/auto-reply/reply/queue/normalize.d.ts +3 -0
  553. package/dist/plugin-sdk/auto-reply/reply/queue/settings.d.ts +2 -0
  554. package/dist/plugin-sdk/auto-reply/reply/queue/state.d.ts +20 -0
  555. package/dist/plugin-sdk/auto-reply/reply/queue/types.d.ts +72 -0
  556. package/dist/plugin-sdk/auto-reply/reply/queue-policy.d.ts +8 -0
  557. package/dist/plugin-sdk/auto-reply/reply/queue.d.ts +8 -0
  558. package/dist/plugin-sdk/auto-reply/reply/reply-delivery.d.ts +27 -0
  559. package/dist/plugin-sdk/auto-reply/reply/reply-directives.d.ts +14 -0
  560. package/dist/plugin-sdk/auto-reply/reply/reply-dispatcher.d.ts +53 -0
  561. package/dist/plugin-sdk/auto-reply/reply/reply-inline.d.ts +8 -0
  562. package/dist/plugin-sdk/auto-reply/reply/reply-payloads.d.ts +27 -0
  563. package/dist/plugin-sdk/auto-reply/reply/reply-reference.d.ts +20 -0
  564. package/dist/plugin-sdk/auto-reply/reply/reply-tags.d.ts +6 -0
  565. package/dist/plugin-sdk/auto-reply/reply/reply-threading.d.ts +9 -0
  566. package/dist/plugin-sdk/auto-reply/reply/response-prefix-template.d.ts +49 -0
  567. package/dist/plugin-sdk/auto-reply/reply/route-reply.d.ts +56 -0
  568. package/dist/plugin-sdk/auto-reply/reply/session-reset-prompt.d.ts +1 -0
  569. package/dist/plugin-sdk/auto-reply/reply/session-run-accounting.d.ts +4 -0
  570. package/dist/plugin-sdk/auto-reply/reply/session-updates.d.ts +8 -0
  571. package/dist/plugin-sdk/auto-reply/reply/session-usage.d.ts +21 -0
  572. package/dist/plugin-sdk/auto-reply/reply/session.d.ts +26 -0
  573. package/dist/plugin-sdk/auto-reply/reply/strip-inbound-meta.d.ts +27 -0
  574. package/dist/plugin-sdk/auto-reply/reply/subagents-utils.d.ts +26 -0
  575. package/dist/plugin-sdk/auto-reply/reply/typing-mode.d.ts +27 -0
  576. package/dist/plugin-sdk/auto-reply/reply/typing.d.ts +18 -0
  577. package/dist/plugin-sdk/auto-reply/reply/untrusted-context.d.ts +1 -0
  578. package/dist/plugin-sdk/auto-reply/reply.d.ts +5 -0
  579. package/dist/plugin-sdk/auto-reply/send-policy.d.ts +6 -0
  580. package/dist/plugin-sdk/auto-reply/status.d.ts +50 -0
  581. package/dist/plugin-sdk/auto-reply/templating.d.ts +155 -0
  582. package/dist/plugin-sdk/auto-reply/thinking.d.ts +7 -0
  583. package/dist/plugin-sdk/auto-reply/tokens.d.ts +3 -0
  584. package/dist/plugin-sdk/auto-reply/types.d.ts +79 -0
  585. package/dist/plugin-sdk/channel-web.d.ts +6 -0
  586. package/dist/plugin-sdk/channels/account-summary.d.ts +17 -0
  587. package/dist/plugin-sdk/channels/ack-reactions.d.ts +29 -0
  588. package/dist/plugin-sdk/channels/allow-from.d.ts +11 -0
  589. package/dist/plugin-sdk/channels/allowlist-match.d.ts +16 -0
  590. package/dist/plugin-sdk/channels/allowlists/resolve-utils.d.ts +33 -0
  591. package/dist/plugin-sdk/channels/channel-config.d.ts +39 -0
  592. package/dist/plugin-sdk/channels/chat-type.d.ts +2 -0
  593. package/dist/plugin-sdk/channels/command-gating.d.ts +20 -0
  594. package/dist/plugin-sdk/channels/conversation-label.d.ts +2 -0
  595. package/dist/plugin-sdk/channels/dock.d.ts +24 -0
  596. package/dist/plugin-sdk/channels/draft-stream-controls.d.ts +54 -0
  597. package/dist/plugin-sdk/channels/draft-stream-loop.d.ts +13 -0
  598. package/dist/plugin-sdk/channels/location.d.ts +21 -0
  599. package/dist/plugin-sdk/channels/logging.d.ts +20 -0
  600. package/dist/plugin-sdk/channels/mention-gating.d.ts +27 -0
  601. package/dist/plugin-sdk/channels/model-overrides.d.ts +18 -0
  602. package/dist/plugin-sdk/channels/plugins/account-action-gate.d.ts +5 -0
  603. package/dist/plugin-sdk/channels/plugins/account-helpers.d.ts +6 -0
  604. package/dist/plugin-sdk/channels/plugins/actions/discord/handle-action.d.ts +3 -0
  605. package/dist/plugin-sdk/channels/plugins/actions/discord/handle-action.guild-admin.d.ts +9 -0
  606. package/dist/plugin-sdk/channels/plugins/actions/discord.d.ts +2 -0
  607. package/dist/plugin-sdk/channels/plugins/actions/shared.d.ts +7 -0
  608. package/dist/plugin-sdk/channels/plugins/actions/signal.d.ts +2 -0
  609. package/dist/plugin-sdk/channels/plugins/actions/telegram.d.ts +2 -0
  610. package/dist/plugin-sdk/channels/plugins/agent-tools/whatsapp-login.d.ts +2 -0
  611. package/dist/plugin-sdk/channels/plugins/allowlist-match.d.ts +2 -0
  612. package/dist/plugin-sdk/channels/plugins/bluebubbles-actions.d.ts +48 -0
  613. package/dist/plugin-sdk/channels/plugins/channel-config.d.ts +2 -0
  614. package/dist/plugin-sdk/channels/plugins/config-helpers.d.ts +14 -0
  615. package/dist/plugin-sdk/channels/plugins/config-schema.d.ts +3 -0
  616. package/dist/plugin-sdk/channels/plugins/config-writes.d.ts +7 -0
  617. package/dist/plugin-sdk/channels/plugins/directory-config.d.ts +16 -0
  618. package/dist/plugin-sdk/channels/plugins/group-mentions.d.ts +18 -0
  619. package/dist/plugin-sdk/channels/plugins/helpers.d.ts +8 -0
  620. package/dist/plugin-sdk/channels/plugins/index.d.ts +8 -0
  621. package/dist/plugin-sdk/channels/plugins/media-limits.d.ts +9 -0
  622. package/dist/plugin-sdk/channels/plugins/media-payload.d.ts +15 -0
  623. package/dist/plugin-sdk/channels/plugins/message-action-names.d.ts +2 -0
  624. package/dist/plugin-sdk/channels/plugins/normalize/discord.d.ts +14 -0
  625. package/dist/plugin-sdk/channels/plugins/normalize/imessage.d.ts +2 -0
  626. package/dist/plugin-sdk/channels/plugins/normalize/shared.d.ts +6 -0
  627. package/dist/plugin-sdk/channels/plugins/normalize/signal.d.ts +2 -0
  628. package/dist/plugin-sdk/channels/plugins/normalize/slack.d.ts +2 -0
  629. package/dist/plugin-sdk/channels/plugins/normalize/telegram.d.ts +2 -0
  630. package/dist/plugin-sdk/channels/plugins/normalize/whatsapp.d.ts +3 -0
  631. package/dist/plugin-sdk/channels/plugins/onboarding/channel-access-configure.d.ts +21 -0
  632. package/dist/plugin-sdk/channels/plugins/onboarding/channel-access.d.ts +31 -0
  633. package/dist/plugin-sdk/channels/plugins/onboarding/discord.d.ts +2 -0
  634. package/dist/plugin-sdk/channels/plugins/onboarding/helpers.d.ts +177 -0
  635. package/dist/plugin-sdk/channels/plugins/onboarding/imessage.d.ts +6 -0
  636. package/dist/plugin-sdk/channels/plugins/onboarding/signal.d.ts +7 -0
  637. package/dist/plugin-sdk/channels/plugins/onboarding/slack.d.ts +2 -0
  638. package/dist/plugin-sdk/channels/plugins/onboarding/telegram.d.ts +4 -0
  639. package/dist/plugin-sdk/channels/plugins/onboarding/whatsapp.d.ts +2 -0
  640. package/dist/plugin-sdk/channels/plugins/onboarding-types.d.ts +77 -0
  641. package/dist/plugin-sdk/channels/plugins/outbound/load.d.ts +2 -0
  642. package/dist/plugin-sdk/channels/plugins/pairing-message.d.ts +1 -0
  643. package/dist/plugin-sdk/channels/plugins/pairing.d.ts +16 -0
  644. package/dist/plugin-sdk/channels/plugins/registry-loader.d.ts +5 -0
  645. package/dist/plugin-sdk/channels/plugins/setup-helpers.d.ts +13 -0
  646. package/dist/plugin-sdk/channels/plugins/status-issues/bluebubbles.d.ts +2 -0
  647. package/dist/plugin-sdk/channels/plugins/status-issues/discord.d.ts +2 -0
  648. package/dist/plugin-sdk/channels/plugins/status-issues/shared.d.ts +29 -0
  649. package/dist/plugin-sdk/channels/plugins/status-issues/telegram.d.ts +2 -0
  650. package/dist/plugin-sdk/channels/plugins/status-issues/whatsapp.d.ts +2 -0
  651. package/dist/plugin-sdk/channels/plugins/types.adapters.d.ts +282 -0
  652. package/dist/plugin-sdk/channels/plugins/types.core.d.ts +350 -0
  653. package/dist/plugin-sdk/channels/plugins/types.d.ts +6 -0
  654. package/dist/plugin-sdk/channels/plugins/types.plugin.d.ts +53 -0
  655. package/dist/plugin-sdk/channels/plugins/whatsapp-heartbeat.d.ts +11 -0
  656. package/dist/plugin-sdk/channels/plugins/whatsapp-shared.d.ts +5 -0
  657. package/dist/plugin-sdk/channels/registry.d.ts +15 -0
  658. package/dist/plugin-sdk/channels/reply-prefix.d.ts +24 -0
  659. package/dist/plugin-sdk/channels/sender-label.d.ts +9 -0
  660. package/dist/plugin-sdk/channels/session.d.ts +18 -0
  661. package/dist/plugin-sdk/channels/status-reactions.d.ts +62 -0
  662. package/dist/plugin-sdk/channels/targets.d.ts +42 -0
  663. package/dist/plugin-sdk/channels/telegram/api.d.ts +5 -0
  664. package/dist/plugin-sdk/channels/typing-lifecycle.d.ts +12 -0
  665. package/dist/plugin-sdk/channels/typing.d.ts +13 -0
  666. package/dist/plugin-sdk/channels/voice-credentials.d.ts +26 -0
  667. package/dist/plugin-sdk/channels/web/index.d.ts +1 -0
  668. package/dist/plugin-sdk/cli/cli-name.d.ts +3 -0
  669. package/dist/plugin-sdk/cli/command-format.d.ts +1 -0
  670. package/dist/plugin-sdk/cli/deps.d.ts +18 -0
  671. package/dist/plugin-sdk/cli/outbound-send-deps.d.ts +4 -0
  672. package/dist/plugin-sdk/cli/outbound-send-mapping.d.ts +10 -0
  673. package/dist/plugin-sdk/cli/parse-bytes.d.ts +4 -0
  674. package/dist/plugin-sdk/cli/parse-duration.d.ts +4 -0
  675. package/dist/plugin-sdk/cli/profile-utils.d.ts +2 -0
  676. package/dist/plugin-sdk/cli/progress.d.ts +24 -0
  677. package/dist/plugin-sdk/cli/wait.d.ts +1 -0
  678. package/dist/plugin-sdk/commands/agent/delivery.d.ts +25 -0
  679. package/dist/plugin-sdk/commands/agent/run-context.d.ts +2 -0
  680. package/dist/plugin-sdk/commands/agent/session-store.d.ts +16 -0
  681. package/dist/plugin-sdk/commands/agent/session.d.ts +32 -0
  682. package/dist/plugin-sdk/commands/agent/types.d.ts +89 -0
  683. package/dist/plugin-sdk/commands/agent.d.ts +14 -0
  684. package/dist/plugin-sdk/commands/daemon-runtime.d.ts +8 -0
  685. package/dist/plugin-sdk/commands/health.d.ts +63 -0
  686. package/dist/plugin-sdk/commands/oauth-flow.d.ts +21 -0
  687. package/dist/plugin-sdk/commands/onboard-helpers.d.ts +76 -0
  688. package/dist/plugin-sdk/commands/onboard-types.d.ts +65 -0
  689. package/dist/plugin-sdk/commands/signal-install.d.ts +30 -0
  690. package/dist/plugin-sdk/config/agent-dirs.d.ts +14 -0
  691. package/dist/plugin-sdk/config/agent-limits.d.ts +6 -0
  692. package/dist/plugin-sdk/config/backup-rotation.d.ts +5 -0
  693. package/dist/plugin-sdk/config/cache-utils.d.ts +6 -0
  694. package/dist/plugin-sdk/config/commands.d.ts +20 -0
  695. package/dist/plugin-sdk/config/config-paths.d.ts +10 -0
  696. package/dist/plugin-sdk/config/config.d.ts +7 -0
  697. package/dist/plugin-sdk/config/dangerous-name-matching.d.ts +12 -0
  698. package/dist/plugin-sdk/config/defaults.d.ts +18 -0
  699. package/dist/plugin-sdk/config/discord-preview-streaming.d.ts +25 -0
  700. package/dist/plugin-sdk/config/env-preserve.d.ts +10 -0
  701. package/dist/plugin-sdk/config/env-substitution.d.ts +36 -0
  702. package/dist/plugin-sdk/config/env-vars.d.ts +6 -0
  703. package/dist/plugin-sdk/config/group-policy.d.ts +49 -0
  704. package/dist/plugin-sdk/config/includes.d.ts +32 -0
  705. package/dist/plugin-sdk/config/io.d.ts +60 -0
  706. package/dist/plugin-sdk/config/legacy-migrate.d.ts +5 -0
  707. package/dist/plugin-sdk/config/legacy.d.ts +6 -0
  708. package/dist/plugin-sdk/config/legacy.migrations.d.ts +2 -0
  709. package/dist/plugin-sdk/config/legacy.rules.d.ts +2 -0
  710. package/dist/plugin-sdk/config/legacy.shared.d.ts +10 -0
  711. package/dist/plugin-sdk/config/markdown-tables.d.ts +7 -0
  712. package/dist/plugin-sdk/config/merge-config.d.ts +7 -0
  713. package/dist/plugin-sdk/config/merge-patch.d.ts +5 -0
  714. package/dist/plugin-sdk/config/normalize-paths.d.ts +8 -0
  715. package/dist/plugin-sdk/config/paths.d.ts +57 -0
  716. package/dist/plugin-sdk/config/prototype-keys.d.ts +1 -0
  717. package/dist/plugin-sdk/config/runtime-group-policy.d.ts +56 -0
  718. package/dist/plugin-sdk/config/runtime-overrides.d.ts +15 -0
  719. package/dist/plugin-sdk/config/sessions/artifacts.d.ts +5 -0
  720. package/dist/plugin-sdk/config/sessions/constants.d.ts +2 -0
  721. package/dist/plugin-sdk/config/sessions/delivery-info.d.ts +16 -0
  722. package/dist/plugin-sdk/config/sessions/disk-budget.d.ts +28 -0
  723. package/dist/plugin-sdk/config/sessions/group.d.ts +11 -0
  724. package/dist/plugin-sdk/config/sessions/main-session.d.ts +43 -0
  725. package/dist/plugin-sdk/config/sessions/metadata.d.ts +16 -0
  726. package/dist/plugin-sdk/config/sessions/paths.d.ts +21 -0
  727. package/dist/plugin-sdk/config/sessions/reset.d.ts +43 -0
  728. package/dist/plugin-sdk/config/sessions/session-file.d.ts +15 -0
  729. package/dist/plugin-sdk/config/sessions/session-key.d.ts +8 -0
  730. package/dist/plugin-sdk/config/sessions/store.d.ts +123 -0
  731. package/dist/plugin-sdk/config/sessions/transcript.d.ts +18 -0
  732. package/dist/plugin-sdk/config/sessions/types.d.ts +136 -0
  733. package/dist/plugin-sdk/config/sessions.d.ts +13 -0
  734. package/dist/plugin-sdk/config/talk.d.ts +21 -0
  735. package/dist/plugin-sdk/config/telegram-custom-commands.d.ts +24 -0
  736. package/dist/plugin-sdk/config/types.agent-defaults.d.ts +168 -0
  737. package/dist/plugin-sdk/config/types.agents-shared.d.ts +43 -0
  738. package/dist/plugin-sdk/config/types.agents.d.ts +66 -0
  739. package/dist/plugin-sdk/config/types.approvals.d.ts +26 -0
  740. package/dist/plugin-sdk/config/types.auth.d.ts +28 -0
  741. package/dist/plugin-sdk/config/types.base.d.ts +202 -0
  742. package/dist/plugin-sdk/config/types.browser.d.ts +65 -0
  743. package/dist/plugin-sdk/config/types.channel-messaging-common.d.ts +44 -0
  744. package/dist/plugin-sdk/config/types.channels.d.ts +53 -0
  745. package/dist/plugin-sdk/config/types.cron.d.ts +26 -0
  746. package/dist/plugin-sdk/config/types.d.ts +27 -0
  747. package/dist/plugin-sdk/config/types.discord.d.ts +271 -0
  748. package/dist/plugin-sdk/config/types.gateway.d.ts +335 -0
  749. package/dist/plugin-sdk/config/types.googlechat.d.ts +107 -0
  750. package/dist/plugin-sdk/config/types.hooks.d.ts +123 -0
  751. package/dist/plugin-sdk/config/types.imessage.d.ts +77 -0
  752. package/dist/plugin-sdk/config/types.installs.d.ts +14 -0
  753. package/dist/plugin-sdk/config/types.irc.d.ts +53 -0
  754. package/dist/plugin-sdk/config/types.messages.d.ts +149 -0
  755. package/dist/plugin-sdk/config/types.models.d.ts +41 -0
  756. package/dist/plugin-sdk/config/types.msteams.d.ts +108 -0
  757. package/dist/plugin-sdk/config/types.node-host.d.ts +10 -0
  758. package/dist/plugin-sdk/config/types.plugins.d.ts +23 -0
  759. package/dist/plugin-sdk/config/types.queue.d.ts +14 -0
  760. package/dist/plugin-sdk/config/types.remoteclaw.d.ts +119 -0
  761. package/dist/plugin-sdk/config/types.signal.d.ts +46 -0
  762. package/dist/plugin-sdk/config/types.slack.d.ts +179 -0
  763. package/dist/plugin-sdk/config/types.telegram.d.ts +187 -0
  764. package/dist/plugin-sdk/config/types.tools.d.ts +249 -0
  765. package/dist/plugin-sdk/config/types.tts.d.ts +79 -0
  766. package/dist/plugin-sdk/config/types.whatsapp.d.ts +101 -0
  767. package/dist/plugin-sdk/config/validation.d.ts +37 -0
  768. package/dist/plugin-sdk/config/version.d.ts +8 -0
  769. package/dist/plugin-sdk/config/zod-schema.agent-defaults.d.ts +93 -0
  770. package/dist/plugin-sdk/config/zod-schema.agent-runtime.d.ts +302 -0
  771. package/dist/plugin-sdk/config/zod-schema.agents.d.ts +224 -0
  772. package/dist/plugin-sdk/config/zod-schema.allowdeny.d.ts +13 -0
  773. package/dist/plugin-sdk/config/zod-schema.approvals.d.ts +15 -0
  774. package/dist/plugin-sdk/config/zod-schema.channels.d.ts +6 -0
  775. package/dist/plugin-sdk/config/zod-schema.core.d.ts +355 -0
  776. package/dist/plugin-sdk/config/zod-schema.d.ts +3155 -0
  777. package/dist/plugin-sdk/config/zod-schema.hooks.d.ts +85 -0
  778. package/dist/plugin-sdk/config/zod-schema.installs.d.ts +16 -0
  779. package/dist/plugin-sdk/config/zod-schema.providers-core.d.ts +3656 -0
  780. package/dist/plugin-sdk/config/zod-schema.providers-whatsapp.d.ts +235 -0
  781. package/dist/plugin-sdk/config/zod-schema.providers.d.ts +2182 -0
  782. package/dist/plugin-sdk/config/zod-schema.sensitive.d.ts +2 -0
  783. package/dist/plugin-sdk/config/zod-schema.session.d.ts +228 -0
  784. package/dist/plugin-sdk/cron/delivery.d.ts +9 -0
  785. package/dist/plugin-sdk/cron/parse.d.ts +1 -0
  786. package/dist/plugin-sdk/cron/schedule.d.ts +2 -0
  787. package/dist/plugin-sdk/cron/service/jobs.d.ts +21 -0
  788. package/dist/plugin-sdk/cron/service/locked.d.ts +2 -0
  789. package/dist/plugin-sdk/cron/service/normalize.d.ts +18 -0
  790. package/dist/plugin-sdk/cron/service/ops.d.ts +81 -0
  791. package/dist/plugin-sdk/cron/service/state.d.ts +125 -0
  792. package/dist/plugin-sdk/cron/service/store.d.ts +9 -0
  793. package/dist/plugin-sdk/cron/service/timer.d.ts +47 -0
  794. package/dist/plugin-sdk/cron/service.d.ts +66 -0
  795. package/dist/plugin-sdk/cron/session-reaper.d.ts +35 -0
  796. package/dist/plugin-sdk/cron/stagger.d.ts +8 -0
  797. package/dist/plugin-sdk/cron/store.d.ts +6 -0
  798. package/dist/plugin-sdk/cron/types.d.ts +131 -0
  799. package/dist/plugin-sdk/cron/webhook-url.d.ts +1 -0
  800. package/dist/plugin-sdk/daemon/constants.d.ts +35 -0
  801. package/dist/plugin-sdk/discord/accounts.d.ts +21 -0
  802. package/dist/plugin-sdk/discord/api.d.ts +11 -0
  803. package/dist/plugin-sdk/discord/audit.d.ts +29 -0
  804. package/dist/plugin-sdk/discord/chunk.d.ts +20 -0
  805. package/dist/plugin-sdk/discord/client.d.ts +21 -0
  806. package/dist/plugin-sdk/discord/components-registry.d.ts +16 -0
  807. package/dist/plugin-sdk/discord/components.d.ts +196 -0
  808. package/dist/plugin-sdk/discord/directory-live.d.ts +4 -0
  809. package/dist/plugin-sdk/discord/draft-chunking.d.ts +6 -0
  810. package/dist/plugin-sdk/discord/draft-stream.d.ts +21 -0
  811. package/dist/plugin-sdk/discord/gateway-logging.d.ts +8 -0
  812. package/dist/plugin-sdk/discord/guilds.d.ts +6 -0
  813. package/dist/plugin-sdk/discord/monitor/agent-components.d.ts +55 -0
  814. package/dist/plugin-sdk/discord/monitor/allow-list.d.ts +174 -0
  815. package/dist/plugin-sdk/discord/monitor/commands.d.ts +2 -0
  816. package/dist/plugin-sdk/discord/monitor/format.d.ts +13 -0
  817. package/dist/plugin-sdk/discord/monitor/gateway-plugin.d.ts +8 -0
  818. package/dist/plugin-sdk/discord/monitor/gateway-registry.d.ts +9 -0
  819. package/dist/plugin-sdk/discord/monitor/listeners.d.ts +44 -0
  820. package/dist/plugin-sdk/discord/monitor/message-handler.d.ts +5 -0
  821. package/dist/plugin-sdk/discord/monitor/message-handler.preflight.d.ts +14 -0
  822. package/dist/plugin-sdk/discord/monitor/message-handler.preflight.types.d.ts +95 -0
  823. package/dist/plugin-sdk/discord/monitor/message-handler.process.d.ts +2 -0
  824. package/dist/plugin-sdk/discord/monitor/message-utils.d.ts +40 -0
  825. package/dist/plugin-sdk/discord/monitor/native-command.d.ts +23 -0
  826. package/dist/plugin-sdk/discord/monitor/presence-cache.d.ts +9 -0
  827. package/dist/plugin-sdk/discord/monitor/presence.d.ts +5 -0
  828. package/dist/plugin-sdk/discord/monitor/provider.allowlist.d.ts +14 -0
  829. package/dist/plugin-sdk/discord/monitor/provider.d.ts +28 -0
  830. package/dist/plugin-sdk/discord/monitor/provider.lifecycle.d.ts +23 -0
  831. package/dist/plugin-sdk/discord/monitor/reply-context.d.ts +17 -0
  832. package/dist/plugin-sdk/discord/monitor/reply-delivery.d.ts +22 -0
  833. package/dist/plugin-sdk/discord/monitor/rest-fetch.d.ts +2 -0
  834. package/dist/plugin-sdk/discord/monitor/sender-identity.d.ts +31 -0
  835. package/dist/plugin-sdk/discord/monitor/system-events.d.ts +2 -0
  836. package/dist/plugin-sdk/discord/monitor/thread-bindings.d.ts +5 -0
  837. package/dist/plugin-sdk/discord/monitor/thread-bindings.discord-api.d.ts +36 -0
  838. package/dist/plugin-sdk/discord/monitor/thread-bindings.lifecycle.d.ts +30 -0
  839. package/dist/plugin-sdk/discord/monitor/thread-bindings.manager.d.ts +17 -0
  840. package/dist/plugin-sdk/discord/monitor/thread-bindings.messages.d.ts +17 -0
  841. package/dist/plugin-sdk/discord/monitor/thread-bindings.state.d.ts +61 -0
  842. package/dist/plugin-sdk/discord/monitor/thread-bindings.types.d.ts +64 -0
  843. package/dist/plugin-sdk/discord/monitor/threading.d.ts +106 -0
  844. package/dist/plugin-sdk/discord/monitor/typing.d.ts +5 -0
  845. package/dist/plugin-sdk/discord/monitor.d.ts +10 -0
  846. package/dist/plugin-sdk/discord/monitor.gateway.d.ts +12 -0
  847. package/dist/plugin-sdk/discord/pluralkit.d.ts +26 -0
  848. package/dist/plugin-sdk/discord/probe.d.ts +28 -0
  849. package/dist/plugin-sdk/discord/resolve-channels.d.ts +15 -0
  850. package/dist/plugin-sdk/discord/resolve-users.d.ts +14 -0
  851. package/dist/plugin-sdk/discord/send.channels.d.ts +17 -0
  852. package/dist/plugin-sdk/discord/send.components.d.ts +17 -0
  853. package/dist/plugin-sdk/discord/send.d.ts +10 -0
  854. package/dist/plugin-sdk/discord/send.emojis-stickers.d.ts +4 -0
  855. package/dist/plugin-sdk/discord/send.guild.d.ts +24 -0
  856. package/dist/plugin-sdk/discord/send.messages.d.ts +20 -0
  857. package/dist/plugin-sdk/discord/send.outbound.d.ts +57 -0
  858. package/dist/plugin-sdk/discord/send.permissions.d.ts +20 -0
  859. package/dist/plugin-sdk/discord/send.reactions.d.ts +15 -0
  860. package/dist/plugin-sdk/discord/send.shared.d.ts +85 -0
  861. package/dist/plugin-sdk/discord/send.types.d.ts +144 -0
  862. package/dist/plugin-sdk/discord/targets.d.ts +18 -0
  863. package/dist/plugin-sdk/discord/token.d.ts +11 -0
  864. package/dist/plugin-sdk/discord/voice/command.d.ts +15 -0
  865. package/dist/plugin-sdk/discord/voice/manager.d.ts +52 -0
  866. package/dist/plugin-sdk/discord/voice-message.d.ts +50 -0
  867. package/dist/plugin-sdk/gateway/call.d.ts +65 -0
  868. package/dist/plugin-sdk/gateway/chat-abort.d.ts +44 -0
  869. package/dist/plugin-sdk/gateway/chat-sanitize.d.ts +4 -0
  870. package/dist/plugin-sdk/gateway/client.d.ts +64 -0
  871. package/dist/plugin-sdk/gateway/control-ui-shared.d.ts +9 -0
  872. package/dist/plugin-sdk/gateway/credentials.d.ts +36 -0
  873. package/dist/plugin-sdk/gateway/device-auth.d.ts +11 -0
  874. package/dist/plugin-sdk/gateway/method-scopes.d.ts +22 -0
  875. package/dist/plugin-sdk/gateway/net.d.ts +77 -0
  876. package/dist/plugin-sdk/gateway/node-registry.d.ts +60 -0
  877. package/dist/plugin-sdk/gateway/protocol/client-info.d.ts +58 -0
  878. package/dist/plugin-sdk/gateway/protocol/index.d.ts +490 -0
  879. package/dist/plugin-sdk/gateway/protocol/schema/agent.d.ts +89 -0
  880. package/dist/plugin-sdk/gateway/protocol/schema/agents-models.d.ts +188 -0
  881. package/dist/plugin-sdk/gateway/protocol/schema/channels.d.ts +134 -0
  882. package/dist/plugin-sdk/gateway/protocol/schema/config.d.ts +53 -0
  883. package/dist/plugin-sdk/gateway/protocol/schema/cron.d.ts +324 -0
  884. package/dist/plugin-sdk/gateway/protocol/schema/devices.d.ts +41 -0
  885. package/dist/plugin-sdk/gateway/protocol/schema/error-codes.d.ts +14 -0
  886. package/dist/plugin-sdk/gateway/protocol/schema/frames.d.ts +168 -0
  887. package/dist/plugin-sdk/gateway/protocol/schema/logs-chat.d.ts +45 -0
  888. package/dist/plugin-sdk/gateway/protocol/schema/nodes.d.ts +64 -0
  889. package/dist/plugin-sdk/gateway/protocol/schema/primitives.d.ts +4 -0
  890. package/dist/plugin-sdk/gateway/protocol/schema/protocol-schemas.d.ts +3 -0
  891. package/dist/plugin-sdk/gateway/protocol/schema/push.d.ts +15 -0
  892. package/dist/plugin-sdk/gateway/protocol/schema/sessions.d.ts +74 -0
  893. package/dist/plugin-sdk/gateway/protocol/schema/snapshot.d.ts +69 -0
  894. package/dist/plugin-sdk/gateway/protocol/schema/types.d.ts +120 -0
  895. package/dist/plugin-sdk/gateway/protocol/schema/wizard.d.ts +86 -0
  896. package/dist/plugin-sdk/gateway/protocol/schema.d.ts +16 -0
  897. package/dist/plugin-sdk/gateway/server/ws-types.d.ts +11 -0
  898. package/dist/plugin-sdk/gateway/server-broadcast.d.ts +17 -0
  899. package/dist/plugin-sdk/gateway/server-channels.d.ts +26 -0
  900. package/dist/plugin-sdk/gateway/server-constants.d.ts +10 -0
  901. package/dist/plugin-sdk/gateway/server-methods/types.d.ts +84 -0
  902. package/dist/plugin-sdk/gateway/server-shared.d.ts +7 -0
  903. package/dist/plugin-sdk/gateway/session-utils.fs.d.ts +48 -0
  904. package/dist/plugin-sdk/gateway/session-utils.types.d.ts +81 -0
  905. package/dist/plugin-sdk/gateway/ws-log.d.ts +5 -0
  906. package/dist/plugin-sdk/gateway/ws-logging.d.ts +4 -0
  907. package/dist/plugin-sdk/globals.d.ts +11 -0
  908. package/dist/plugin-sdk/hooks/internal-hooks.d.ts +140 -0
  909. package/dist/plugin-sdk/hooks/types.d.ts +62 -0
  910. package/dist/plugin-sdk/imessage/accounts.d.ts +16 -0
  911. package/dist/plugin-sdk/imessage/client.d.ts +46 -0
  912. package/dist/plugin-sdk/imessage/constants.d.ts +2 -0
  913. package/dist/plugin-sdk/imessage/monitor/abort-handler.d.ts +9 -0
  914. package/dist/plugin-sdk/imessage/monitor/deliver.d.ts +14 -0
  915. package/dist/plugin-sdk/imessage/monitor/echo-cache.d.ts +9 -0
  916. package/dist/plugin-sdk/imessage/monitor/inbound-processing.d.ts +96 -0
  917. package/dist/plugin-sdk/imessage/monitor/monitor-provider.d.ts +7 -0
  918. package/dist/plugin-sdk/imessage/monitor/parse-notification.d.ts +2 -0
  919. package/dist/plugin-sdk/imessage/monitor/runtime.d.ts +4 -0
  920. package/dist/plugin-sdk/imessage/monitor/types.d.ts +37 -0
  921. package/dist/plugin-sdk/imessage/monitor.d.ts +2 -0
  922. package/dist/plugin-sdk/imessage/probe.d.ts +17 -0
  923. package/dist/plugin-sdk/imessage/send.d.ts +34 -0
  924. package/dist/plugin-sdk/imessage/target-parsing-helpers.d.ts +45 -0
  925. package/dist/plugin-sdk/imessage/targets.d.ts +39 -0
  926. package/dist/plugin-sdk/index.d.ts +1 -0
  927. package/dist/plugin-sdk/index.js +24140 -0
  928. package/dist/plugin-sdk/infra/agent-events.d.ts +21 -0
  929. package/dist/plugin-sdk/infra/archive-path.d.ts +12 -0
  930. package/dist/plugin-sdk/infra/archive.d.ts +46 -0
  931. package/dist/plugin-sdk/infra/backoff.d.ts +8 -0
  932. package/dist/plugin-sdk/infra/brew.d.ts +8 -0
  933. package/dist/plugin-sdk/infra/channel-activity.d.ts +18 -0
  934. package/dist/plugin-sdk/infra/channel-summary.d.ts +6 -0
  935. package/dist/plugin-sdk/infra/dedupe.d.ts +12 -0
  936. package/dist/plugin-sdk/infra/device-auth-store.d.ts +18 -0
  937. package/dist/plugin-sdk/infra/device-identity.d.ts +11 -0
  938. package/dist/plugin-sdk/infra/device-pairing.d.ts +101 -0
  939. package/dist/plugin-sdk/infra/diagnostic-events.d.ts +140 -0
  940. package/dist/plugin-sdk/infra/diagnostic-flags.d.ts +4 -0
  941. package/dist/plugin-sdk/infra/dotenv.d.ts +3 -0
  942. package/dist/plugin-sdk/infra/env.d.ts +11 -0
  943. package/dist/plugin-sdk/infra/errors.d.ts +11 -0
  944. package/dist/plugin-sdk/infra/fetch.d.ts +2 -0
  945. package/dist/plugin-sdk/infra/file-identity.d.ts +5 -0
  946. package/dist/plugin-sdk/infra/file-lock.d.ts +2 -0
  947. package/dist/plugin-sdk/infra/format-time/format-datetime.d.ts +35 -0
  948. package/dist/plugin-sdk/infra/format-time/format-duration.d.ts +23 -0
  949. package/dist/plugin-sdk/infra/format-time/format-relative.d.ts +39 -0
  950. package/dist/plugin-sdk/infra/fs-safe.d.ts +25 -0
  951. package/dist/plugin-sdk/infra/gemini-auth.d.ts +16 -0
  952. package/dist/plugin-sdk/infra/git-commit.d.ts +4 -0
  953. package/dist/plugin-sdk/infra/git-root.d.ts +7 -0
  954. package/dist/plugin-sdk/infra/heartbeat-active-hours.d.ts +5 -0
  955. package/dist/plugin-sdk/infra/heartbeat-events-filter.d.ts +8 -0
  956. package/dist/plugin-sdk/infra/heartbeat-events.d.ts +21 -0
  957. package/dist/plugin-sdk/infra/heartbeat-reason.d.ts +5 -0
  958. package/dist/plugin-sdk/infra/heartbeat-runner.d.ts +45 -0
  959. package/dist/plugin-sdk/infra/heartbeat-visibility.d.ts +17 -0
  960. package/dist/plugin-sdk/infra/heartbeat-wake.d.ts +31 -0
  961. package/dist/plugin-sdk/infra/home-dir.d.ts +7 -0
  962. package/dist/plugin-sdk/infra/host-env-security.d.ts +21 -0
  963. package/dist/plugin-sdk/infra/http-body.d.ts +46 -0
  964. package/dist/plugin-sdk/infra/json-file.d.ts +2 -0
  965. package/dist/plugin-sdk/infra/json-files.d.ts +5 -0
  966. package/dist/plugin-sdk/infra/map-size.d.ts +1 -0
  967. package/dist/plugin-sdk/infra/net/fetch-guard.d.ts +21 -0
  968. package/dist/plugin-sdk/infra/net/hostname.d.ts +1 -0
  969. package/dist/plugin-sdk/infra/net/ssrf.d.ts +35 -0
  970. package/dist/plugin-sdk/infra/outbound/abort.d.ts +8 -0
  971. package/dist/plugin-sdk/infra/outbound/agent-delivery.d.ts +46 -0
  972. package/dist/plugin-sdk/infra/outbound/bound-delivery-router.d.ts +16 -0
  973. package/dist/plugin-sdk/infra/outbound/channel-selection.d.ts +11 -0
  974. package/dist/plugin-sdk/infra/outbound/channel-target.d.ts +6 -0
  975. package/dist/plugin-sdk/infra/outbound/deliver.d.ts +81 -0
  976. package/dist/plugin-sdk/infra/outbound/delivery-queue.d.ts +78 -0
  977. package/dist/plugin-sdk/infra/outbound/directory-cache.d.ts +24 -0
  978. package/dist/plugin-sdk/infra/outbound/envelope.d.ts +16 -0
  979. package/dist/plugin-sdk/infra/outbound/format.d.ts +39 -0
  980. package/dist/plugin-sdk/infra/outbound/identity.d.ts +8 -0
  981. package/dist/plugin-sdk/infra/outbound/message-action-spec.d.ts +5 -0
  982. package/dist/plugin-sdk/infra/outbound/payloads.d.ts +18 -0
  983. package/dist/plugin-sdk/infra/outbound/session-binding-service.d.ts +57 -0
  984. package/dist/plugin-sdk/infra/outbound/target-errors.d.ts +6 -0
  985. package/dist/plugin-sdk/infra/outbound/target-normalization.d.ts +4 -0
  986. package/dist/plugin-sdk/infra/outbound/target-resolver.d.ts +53 -0
  987. package/dist/plugin-sdk/infra/outbound/targets.d.ts +87 -0
  988. package/dist/plugin-sdk/infra/pairing-files.d.ts +23 -0
  989. package/dist/plugin-sdk/infra/pairing-pending.d.ts +13 -0
  990. package/dist/plugin-sdk/infra/pairing-token.d.ts +3 -0
  991. package/dist/plugin-sdk/infra/path-guards.d.ts +5 -0
  992. package/dist/plugin-sdk/infra/path-safety.d.ts +2 -0
  993. package/dist/plugin-sdk/infra/plain-object.d.ts +4 -0
  994. package/dist/plugin-sdk/infra/prototype-keys.d.ts +1 -0
  995. package/dist/plugin-sdk/infra/provider-usage.auth.d.ts +10 -0
  996. package/dist/plugin-sdk/infra/provider-usage.d.ts +4 -0
  997. package/dist/plugin-sdk/infra/provider-usage.fetch.claude.d.ts +2 -0
  998. package/dist/plugin-sdk/infra/provider-usage.fetch.codex.d.ts +2 -0
  999. package/dist/plugin-sdk/infra/provider-usage.fetch.copilot.d.ts +2 -0
  1000. package/dist/plugin-sdk/infra/provider-usage.fetch.d.ts +6 -0
  1001. package/dist/plugin-sdk/infra/provider-usage.fetch.gemini.d.ts +2 -0
  1002. package/dist/plugin-sdk/infra/provider-usage.fetch.minimax.d.ts +2 -0
  1003. package/dist/plugin-sdk/infra/provider-usage.fetch.shared.d.ts +12 -0
  1004. package/dist/plugin-sdk/infra/provider-usage.fetch.zai.d.ts +2 -0
  1005. package/dist/plugin-sdk/infra/provider-usage.format.d.ts +13 -0
  1006. package/dist/plugin-sdk/infra/provider-usage.load.d.ts +11 -0
  1007. package/dist/plugin-sdk/infra/provider-usage.shared.d.ts +8 -0
  1008. package/dist/plugin-sdk/infra/provider-usage.types.d.ts +17 -0
  1009. package/dist/plugin-sdk/infra/restart.d.ts +70 -0
  1010. package/dist/plugin-sdk/infra/retry-policy.d.ts +25 -0
  1011. package/dist/plugin-sdk/infra/retry.d.ts +21 -0
  1012. package/dist/plugin-sdk/infra/safe-executable-value.d.ts +1 -0
  1013. package/dist/plugin-sdk/infra/scp-host.d.ts +2 -0
  1014. package/dist/plugin-sdk/infra/secure-random.d.ts +2 -0
  1015. package/dist/plugin-sdk/infra/session-cost-usage.d.ts +45 -0
  1016. package/dist/plugin-sdk/infra/session-cost-usage.types.d.ts +153 -0
  1017. package/dist/plugin-sdk/infra/session-maintenance-warning.d.ts +10 -0
  1018. package/dist/plugin-sdk/infra/shell-env.d.ts +34 -0
  1019. package/dist/plugin-sdk/infra/system-events.d.ts +18 -0
  1020. package/dist/plugin-sdk/infra/tailnet.d.ts +8 -0
  1021. package/dist/plugin-sdk/infra/tls/fingerprint.d.ts +1 -0
  1022. package/dist/plugin-sdk/infra/tls/gateway.d.ts +16 -0
  1023. package/dist/plugin-sdk/infra/tmp-remoteclaw-dir.d.ts +18 -0
  1024. package/dist/plugin-sdk/infra/transport-ready.d.ts +16 -0
  1025. package/dist/plugin-sdk/infra/unhandled-rejections.d.ts +15 -0
  1026. package/dist/plugin-sdk/infra/ws.d.ts +2 -0
  1027. package/dist/plugin-sdk/infra/wsl.d.ts +11 -0
  1028. package/dist/plugin-sdk/line/accounts.d.ts +10 -0
  1029. package/dist/plugin-sdk/line/actions.d.ts +22 -0
  1030. package/dist/plugin-sdk/line/auto-reply-delivery.d.ts +38 -0
  1031. package/dist/plugin-sdk/line/bot-access.d.ts +17 -0
  1032. package/dist/plugin-sdk/line/bot-handlers.d.ts +13 -0
  1033. package/dist/plugin-sdk/line/bot-message-context.d.ts +118 -0
  1034. package/dist/plugin-sdk/line/bot.d.ts +24 -0
  1035. package/dist/plugin-sdk/line/channel-access-token.d.ts +4 -0
  1036. package/dist/plugin-sdk/line/config-schema.d.ts +62 -0
  1037. package/dist/plugin-sdk/line/download.d.ts +7 -0
  1038. package/dist/plugin-sdk/line/flex-templates/basic-cards.d.ts +46 -0
  1039. package/dist/plugin-sdk/line/flex-templates/common.d.ts +2 -0
  1040. package/dist/plugin-sdk/line/flex-templates/media-control-cards.d.ts +73 -0
  1041. package/dist/plugin-sdk/line/flex-templates/message.d.ts +6 -0
  1042. package/dist/plugin-sdk/line/flex-templates/schedule-cards.d.ts +55 -0
  1043. package/dist/plugin-sdk/line/flex-templates/types.d.ts +19 -0
  1044. package/dist/plugin-sdk/line/flex-templates.d.ts +5 -0
  1045. package/dist/plugin-sdk/line/markdown-to-line.d.ts +72 -0
  1046. package/dist/plugin-sdk/line/monitor.d.ts +28 -0
  1047. package/dist/plugin-sdk/line/probe.d.ts +2 -0
  1048. package/dist/plugin-sdk/line/reply-chunks.d.ts +24 -0
  1049. package/dist/plugin-sdk/line/send.d.ts +91 -0
  1050. package/dist/plugin-sdk/line/signature.d.ts +1 -0
  1051. package/dist/plugin-sdk/line/template-messages.d.ts +100 -0
  1052. package/dist/plugin-sdk/line/types.d.ts +112 -0
  1053. package/dist/plugin-sdk/line/webhook-node.d.ts +15 -0
  1054. package/dist/plugin-sdk/line/webhook-utils.d.ts +3 -0
  1055. package/dist/plugin-sdk/line/webhook.d.ts +19 -0
  1056. package/dist/plugin-sdk/logger.d.ts +6 -0
  1057. package/dist/plugin-sdk/logging/config.d.ts +4 -0
  1058. package/dist/plugin-sdk/logging/console.d.ts +23 -0
  1059. package/dist/plugin-sdk/logging/diagnostic-session-state.d.ts +30 -0
  1060. package/dist/plugin-sdk/logging/diagnostic.d.ts +65 -0
  1061. package/dist/plugin-sdk/logging/env-log-level.d.ts +2 -0
  1062. package/dist/plugin-sdk/logging/levels.d.ts +5 -0
  1063. package/dist/plugin-sdk/logging/logger.d.ts +44 -0
  1064. package/dist/plugin-sdk/logging/node-require.d.ts +1 -0
  1065. package/dist/plugin-sdk/logging/redact-identifier.d.ts +4 -0
  1066. package/dist/plugin-sdk/logging/redact.d.ts +9 -0
  1067. package/dist/plugin-sdk/logging/state.d.ts +19 -0
  1068. package/dist/plugin-sdk/logging/subsystem.d.ts +18 -0
  1069. package/dist/plugin-sdk/logging/timestamps.d.ts +1 -0
  1070. package/dist/plugin-sdk/logging.d.ts +10 -0
  1071. package/dist/plugin-sdk/markdown/fences.d.ts +10 -0
  1072. package/dist/plugin-sdk/markdown/ir.d.ts +32 -0
  1073. package/dist/plugin-sdk/markdown/render.d.ts +18 -0
  1074. package/dist/plugin-sdk/markdown/tables.d.ts +2 -0
  1075. package/dist/plugin-sdk/markdown/whatsapp.d.ts +14 -0
  1076. package/dist/plugin-sdk/media/audio-tags.d.ts +10 -0
  1077. package/dist/plugin-sdk/media/audio.d.ts +19 -0
  1078. package/dist/plugin-sdk/media/base64.d.ts +6 -0
  1079. package/dist/plugin-sdk/media/constants.d.ts +7 -0
  1080. package/dist/plugin-sdk/media/fetch.d.ts +23 -0
  1081. package/dist/plugin-sdk/media/image-ops.d.ts +41 -0
  1082. package/dist/plugin-sdk/media/inbound-path-policy.d.ts +18 -0
  1083. package/dist/plugin-sdk/media/local-roots.d.ts +3 -0
  1084. package/dist/plugin-sdk/media/mime.d.ts +16 -0
  1085. package/dist/plugin-sdk/media/outbound-attachment.d.ts +6 -0
  1086. package/dist/plugin-sdk/media/parse.d.ts +8 -0
  1087. package/dist/plugin-sdk/media/png-encode.d.ts +8 -0
  1088. package/dist/plugin-sdk/media/read-response-with-limit.d.ts +7 -0
  1089. package/dist/plugin-sdk/media/store.d.ts +33 -0
  1090. package/dist/plugin-sdk/middleware/auth-key-retry.d.ts +31 -0
  1091. package/dist/plugin-sdk/middleware/channel-bridge.d.ts +43 -0
  1092. package/dist/plugin-sdk/middleware/cli-runtime-base.d.ts +47 -0
  1093. package/dist/plugin-sdk/middleware/delivery-adapter.d.ts +36 -0
  1094. package/dist/plugin-sdk/middleware/error-classifier.d.ts +19 -0
  1095. package/dist/plugin-sdk/middleware/mcp-side-effects.d.ts +20 -0
  1096. package/dist/plugin-sdk/middleware/media-capability.d.ts +21 -0
  1097. package/dist/plugin-sdk/middleware/media-resolver.d.ts +12 -0
  1098. package/dist/plugin-sdk/middleware/runtime-factory.d.ts +6 -0
  1099. package/dist/plugin-sdk/middleware/runtimes/claude.d.ts +37 -0
  1100. package/dist/plugin-sdk/middleware/runtimes/codex.d.ts +79 -0
  1101. package/dist/plugin-sdk/middleware/runtimes/gemini.d.ts +63 -0
  1102. package/dist/plugin-sdk/middleware/runtimes/opencode.d.ts +59 -0
  1103. package/dist/plugin-sdk/middleware/session-map.d.ts +36 -0
  1104. package/dist/plugin-sdk/middleware/system-prompt.d.ts +30 -0
  1105. package/dist/plugin-sdk/middleware/types.d.ts +236 -0
  1106. package/dist/plugin-sdk/pairing/pairing-labels.d.ts +2 -0
  1107. package/dist/plugin-sdk/pairing/pairing-messages.d.ts +6 -0
  1108. package/dist/plugin-sdk/pairing/pairing-store.d.ts +48 -0
  1109. package/dist/plugin-sdk/plugin-sdk/account-id.d.ts +1 -0
  1110. package/dist/plugin-sdk/plugin-sdk/agent-media-payload.d.ts +12 -0
  1111. package/dist/plugin-sdk/plugin-sdk/allow-from.d.ts +32 -0
  1112. package/dist/plugin-sdk/plugin-sdk/command-auth.d.ts +25 -0
  1113. package/dist/plugin-sdk/plugin-sdk/config-paths.d.ts +6 -0
  1114. package/dist/plugin-sdk/plugin-sdk/file-lock.d.ts +16 -0
  1115. package/dist/plugin-sdk/plugin-sdk/group-access.d.ts +16 -0
  1116. package/dist/plugin-sdk/plugin-sdk/index.d.ts +166 -0
  1117. package/dist/plugin-sdk/plugin-sdk/json-store.d.ts +5 -0
  1118. package/dist/plugin-sdk/plugin-sdk/onboarding.d.ts +11 -0
  1119. package/dist/plugin-sdk/plugin-sdk/persistent-dedupe.d.ts +20 -0
  1120. package/dist/plugin-sdk/plugin-sdk/reply-payload.d.ts +22 -0
  1121. package/dist/plugin-sdk/plugin-sdk/run-command.d.ts +12 -0
  1122. package/dist/plugin-sdk/plugin-sdk/runtime.d.ts +10 -0
  1123. package/dist/plugin-sdk/plugin-sdk/slack-message-actions.d.ts +11 -0
  1124. package/dist/plugin-sdk/plugin-sdk/status-helpers.d.ts +88 -0
  1125. package/dist/plugin-sdk/plugin-sdk/temp-path.d.ts +12 -0
  1126. package/dist/plugin-sdk/plugin-sdk/text-chunking.d.ts +1 -0
  1127. package/dist/plugin-sdk/plugin-sdk/tool-send.d.ts +4 -0
  1128. package/dist/plugin-sdk/plugin-sdk/webhook-path.d.ts +6 -0
  1129. package/dist/plugin-sdk/plugin-sdk/webhook-targets.d.ts +23 -0
  1130. package/dist/plugin-sdk/plugins/bundled-dir.d.ts +1 -0
  1131. package/dist/plugin-sdk/plugins/commands.d.ts +83 -0
  1132. package/dist/plugin-sdk/plugins/config-schema.d.ts +2 -0
  1133. package/dist/plugin-sdk/plugins/config-state.d.ts +30 -0
  1134. package/dist/plugin-sdk/plugins/discovery.d.ts +24 -0
  1135. package/dist/plugin-sdk/plugins/hook-runner-global.d.ts +37 -0
  1136. package/dist/plugin-sdk/plugins/hooks.d.ts +49 -0
  1137. package/dist/plugin-sdk/plugins/http-path.d.ts +1 -0
  1138. package/dist/plugin-sdk/plugins/http-registry.d.ts +13 -0
  1139. package/dist/plugin-sdk/plugins/manifest-registry.d.ts +35 -0
  1140. package/dist/plugin-sdk/plugins/manifest.d.ts +65 -0
  1141. package/dist/plugin-sdk/plugins/path-safety.d.ts +5 -0
  1142. package/dist/plugin-sdk/plugins/registry.d.ts +148 -0
  1143. package/dist/plugin-sdk/plugins/runtime/native-deps.d.ts +8 -0
  1144. package/dist/plugin-sdk/plugins/runtime/types.d.ts +310 -0
  1145. package/dist/plugin-sdk/plugins/runtime.d.ts +5 -0
  1146. package/dist/plugin-sdk/plugins/schema-validator.d.ts +10 -0
  1147. package/dist/plugin-sdk/plugins/types.d.ts +491 -0
  1148. package/dist/plugin-sdk/polls.d.ts +31 -0
  1149. package/dist/plugin-sdk/process/command-queue.d.ts +51 -0
  1150. package/dist/plugin-sdk/process/exec.d.ts +30 -0
  1151. package/dist/plugin-sdk/process/lanes.d.ts +6 -0
  1152. package/dist/plugin-sdk/process/spawn-utils.d.ts +26 -0
  1153. package/dist/plugin-sdk/routing/account-id.d.ts +3 -0
  1154. package/dist/plugin-sdk/routing/account-lookup.d.ts +1 -0
  1155. package/dist/plugin-sdk/routing/bindings.d.ts +11 -0
  1156. package/dist/plugin-sdk/routing/resolve-route.d.ts +42 -0
  1157. package/dist/plugin-sdk/routing/session-key.d.ts +48 -0
  1158. package/dist/plugin-sdk/runtime.d.ts +7 -0
  1159. package/dist/plugin-sdk/security/channel-metadata.d.ts +6 -0
  1160. package/dist/plugin-sdk/security/dm-policy-shared.d.ts +33 -0
  1161. package/dist/plugin-sdk/security/external-content.d.ts +53 -0
  1162. package/dist/plugin-sdk/security/safe-regex.d.ts +2 -0
  1163. package/dist/plugin-sdk/security/scan-paths.d.ts +5 -0
  1164. package/dist/plugin-sdk/security/secret-equal.d.ts +1 -0
  1165. package/dist/plugin-sdk/sessions/input-provenance.d.ts +16 -0
  1166. package/dist/plugin-sdk/sessions/level-overrides.d.ts +10 -0
  1167. package/dist/plugin-sdk/sessions/send-policy.d.ts +11 -0
  1168. package/dist/plugin-sdk/sessions/session-key-utils.d.ts +16 -0
  1169. package/dist/plugin-sdk/sessions/session-label.d.ts +9 -0
  1170. package/dist/plugin-sdk/sessions/transcript-events.d.ts +7 -0
  1171. package/dist/plugin-sdk/shared/avatar-policy.d.ts +16 -0
  1172. package/dist/plugin-sdk/shared/chat-content.d.ts +5 -0
  1173. package/dist/plugin-sdk/shared/chat-envelope.d.ts +2 -0
  1174. package/dist/plugin-sdk/shared/device-auth.d.ts +13 -0
  1175. package/dist/plugin-sdk/shared/gateway-bind-url.d.ts +14 -0
  1176. package/dist/plugin-sdk/shared/net/ip.d.ts +19 -0
  1177. package/dist/plugin-sdk/shared/operator-scope-compat.d.ts +5 -0
  1178. package/dist/plugin-sdk/shared/pid-alive.d.ts +1 -0
  1179. package/dist/plugin-sdk/shared/process-scoped-map.d.ts +1 -0
  1180. package/dist/plugin-sdk/shared/string-normalization.d.ts +4 -0
  1181. package/dist/plugin-sdk/shared/subagents-format.d.ts +15 -0
  1182. package/dist/plugin-sdk/shared/tailscale-status.d.ts +8 -0
  1183. package/dist/plugin-sdk/shared/text/code-regions.d.ts +6 -0
  1184. package/dist/plugin-sdk/shared/text/reasoning-tags.d.ts +6 -0
  1185. package/dist/plugin-sdk/shared/text-chunking.d.ts +1 -0
  1186. package/dist/plugin-sdk/signal/accounts.d.ts +17 -0
  1187. package/dist/plugin-sdk/signal/client.d.ts +32 -0
  1188. package/dist/plugin-sdk/signal/daemon.d.ts +26 -0
  1189. package/dist/plugin-sdk/signal/format.d.ts +17 -0
  1190. package/dist/plugin-sdk/signal/identity.d.ts +24 -0
  1191. package/dist/plugin-sdk/signal/index.d.ts +5 -0
  1192. package/dist/plugin-sdk/signal/monitor/event-handler.d.ts +5 -0
  1193. package/dist/plugin-sdk/signal/monitor/event-handler.types.d.ts +125 -0
  1194. package/dist/plugin-sdk/signal/monitor/mentions.d.ts +2 -0
  1195. package/dist/plugin-sdk/signal/monitor.d.ts +25 -0
  1196. package/dist/plugin-sdk/signal/probe.d.ts +7 -0
  1197. package/dist/plugin-sdk/signal/reaction-level.d.ts +17 -0
  1198. package/dist/plugin-sdk/signal/rpc-context.d.ts +9 -0
  1199. package/dist/plugin-sdk/signal/send-reactions.d.ts +32 -0
  1200. package/dist/plugin-sdk/signal/send.d.ts +25 -0
  1201. package/dist/plugin-sdk/signal/sse-reconnect.d.ts +13 -0
  1202. package/dist/plugin-sdk/slack/accounts.d.ts +32 -0
  1203. package/dist/plugin-sdk/slack/actions.d.ts +56 -0
  1204. package/dist/plugin-sdk/slack/blocks-fallback.d.ts +2 -0
  1205. package/dist/plugin-sdk/slack/blocks-input.d.ts +3 -0
  1206. package/dist/plugin-sdk/slack/channel-migration.d.ts +20 -0
  1207. package/dist/plugin-sdk/slack/client.d.ts +4 -0
  1208. package/dist/plugin-sdk/slack/directory-live.d.ts +4 -0
  1209. package/dist/plugin-sdk/slack/draft-stream.d.ts +25 -0
  1210. package/dist/plugin-sdk/slack/format.d.ts +7 -0
  1211. package/dist/plugin-sdk/slack/http/index.d.ts +1 -0
  1212. package/dist/plugin-sdk/slack/http/registry.d.ts +12 -0
  1213. package/dist/plugin-sdk/slack/index.d.ts +6 -0
  1214. package/dist/plugin-sdk/slack/manifest.d.ts +17 -0
  1215. package/dist/plugin-sdk/slack/message-actions.d.ts +4 -0
  1216. package/dist/plugin-sdk/slack/modal-metadata.d.ts +7 -0
  1217. package/dist/plugin-sdk/slack/monitor/allow-list.d.ts +23 -0
  1218. package/dist/plugin-sdk/slack/monitor/auth.d.ts +11 -0
  1219. package/dist/plugin-sdk/slack/monitor/channel-config.d.ts +41 -0
  1220. package/dist/plugin-sdk/slack/monitor/commands.d.ts +9 -0
  1221. package/dist/plugin-sdk/slack/monitor/context.d.ts +104 -0
  1222. package/dist/plugin-sdk/slack/monitor/events/channels.d.ts +4 -0
  1223. package/dist/plugin-sdk/slack/monitor/events/interactions.d.ts +4 -0
  1224. package/dist/plugin-sdk/slack/monitor/events/members.d.ts +4 -0
  1225. package/dist/plugin-sdk/slack/monitor/events/messages.d.ts +6 -0
  1226. package/dist/plugin-sdk/slack/monitor/events/pins.d.ts +4 -0
  1227. package/dist/plugin-sdk/slack/monitor/events/reactions.d.ts +4 -0
  1228. package/dist/plugin-sdk/slack/monitor/events.d.ts +8 -0
  1229. package/dist/plugin-sdk/slack/monitor/external-arg-menu-store.d.ts +18 -0
  1230. package/dist/plugin-sdk/slack/monitor/media.d.ts +66 -0
  1231. package/dist/plugin-sdk/slack/monitor/message-handler/dispatch.d.ts +12 -0
  1232. package/dist/plugin-sdk/slack/monitor/message-handler/prepare.d.ts +13 -0
  1233. package/dist/plugin-sdk/slack/monitor/message-handler/types.d.ts +22 -0
  1234. package/dist/plugin-sdk/slack/monitor/message-handler.d.ts +11 -0
  1235. package/dist/plugin-sdk/slack/monitor/mrkdwn.d.ts +1 -0
  1236. package/dist/plugin-sdk/slack/monitor/policy.d.ts +5 -0
  1237. package/dist/plugin-sdk/slack/monitor/provider.d.ts +7 -0
  1238. package/dist/plugin-sdk/slack/monitor/replies.d.ts +53 -0
  1239. package/dist/plugin-sdk/slack/monitor/room-context.d.ts +14 -0
  1240. package/dist/plugin-sdk/slack/monitor/slash.d.ts +6 -0
  1241. package/dist/plugin-sdk/slack/monitor/thread-resolution.d.ts +12 -0
  1242. package/dist/plugin-sdk/slack/monitor/types.d.ts +97 -0
  1243. package/dist/plugin-sdk/slack/monitor.d.ts +5 -0
  1244. package/dist/plugin-sdk/slack/probe.d.ts +14 -0
  1245. package/dist/plugin-sdk/slack/resolve-channels.d.ts +19 -0
  1246. package/dist/plugin-sdk/slack/resolve-users.d.ts +26 -0
  1247. package/dist/plugin-sdk/slack/send.d.ts +22 -0
  1248. package/dist/plugin-sdk/slack/stream-mode.d.ts +23 -0
  1249. package/dist/plugin-sdk/slack/streaming.d.ts +72 -0
  1250. package/dist/plugin-sdk/slack/targets.d.ts +7 -0
  1251. package/dist/plugin-sdk/slack/threading-tool-context.d.ts +10 -0
  1252. package/dist/plugin-sdk/slack/threading.d.ts +29 -0
  1253. package/dist/plugin-sdk/slack/token.d.ts +3 -0
  1254. package/dist/plugin-sdk/slack/types.d.ts +58 -0
  1255. package/dist/plugin-sdk/stt/defaults.d.ts +2 -0
  1256. package/dist/plugin-sdk/stt/preflight.d.ts +14 -0
  1257. package/dist/plugin-sdk/stt/providers/deepgram/audio.d.ts +4 -0
  1258. package/dist/plugin-sdk/stt/providers/deepgram/index.d.ts +2 -0
  1259. package/dist/plugin-sdk/stt/providers/google/audio.d.ts +3 -0
  1260. package/dist/plugin-sdk/stt/providers/google/index.d.ts +2 -0
  1261. package/dist/plugin-sdk/stt/providers/google/inline-data.d.ts +20 -0
  1262. package/dist/plugin-sdk/stt/providers/groq/index.d.ts +2 -0
  1263. package/dist/plugin-sdk/stt/providers/index.d.ts +4 -0
  1264. package/dist/plugin-sdk/stt/providers/mistral/index.d.ts +2 -0
  1265. package/dist/plugin-sdk/stt/providers/openai/audio.d.ts +3 -0
  1266. package/dist/plugin-sdk/stt/providers/openai/index.d.ts +2 -0
  1267. package/dist/plugin-sdk/stt/providers/shared.d.ts +20 -0
  1268. package/dist/plugin-sdk/stt/stt.d.ts +27 -0
  1269. package/dist/plugin-sdk/stt/types.d.ts +22 -0
  1270. package/dist/plugin-sdk/telegram/accounts.d.ts +21 -0
  1271. package/dist/plugin-sdk/telegram/allowed-updates.d.ts +4 -0
  1272. package/dist/plugin-sdk/telegram/api-logging.d.ts +11 -0
  1273. package/dist/plugin-sdk/telegram/audit.d.ts +29 -0
  1274. package/dist/plugin-sdk/telegram/bot/delivery.d.ts +35 -0
  1275. package/dist/plugin-sdk/telegram/bot/helpers.d.ts +128 -0
  1276. package/dist/plugin-sdk/telegram/bot/types.d.ts +28 -0
  1277. package/dist/plugin-sdk/telegram/bot-access.d.ts +26 -0
  1278. package/dist/plugin-sdk/telegram/bot-handlers.d.ts +2 -0
  1279. package/dist/plugin-sdk/telegram/bot-message-context.d.ts +144 -0
  1280. package/dist/plugin-sdk/telegram/bot-message-dispatch.d.ts +19 -0
  1281. package/dist/plugin-sdk/telegram/bot-message.d.ts +20 -0
  1282. package/dist/plugin-sdk/telegram/bot-native-command-menu.d.ts +33 -0
  1283. package/dist/plugin-sdk/telegram/bot-native-commands.d.ts +59 -0
  1284. package/dist/plugin-sdk/telegram/bot-updates.d.ts +31 -0
  1285. package/dist/plugin-sdk/telegram/bot.d.ts +62 -0
  1286. package/dist/plugin-sdk/telegram/button-types.d.ts +7 -0
  1287. package/dist/plugin-sdk/telegram/caption.d.ts +5 -0
  1288. package/dist/plugin-sdk/telegram/dm-access.d.ts +18 -0
  1289. package/dist/plugin-sdk/telegram/draft-stream.d.ts +37 -0
  1290. package/dist/plugin-sdk/telegram/fetch.d.ts +5 -0
  1291. package/dist/plugin-sdk/telegram/format.d.ts +18 -0
  1292. package/dist/plugin-sdk/telegram/group-access.d.ts +54 -0
  1293. package/dist/plugin-sdk/telegram/group-config-helpers.d.ts +7 -0
  1294. package/dist/plugin-sdk/telegram/group-migration.d.ts +20 -0
  1295. package/dist/plugin-sdk/telegram/inline-buttons.d.ts +11 -0
  1296. package/dist/plugin-sdk/telegram/lane-delivery.d.ts +56 -0
  1297. package/dist/plugin-sdk/telegram/monitor.d.ts +19 -0
  1298. package/dist/plugin-sdk/telegram/network-config.d.ts +33 -0
  1299. package/dist/plugin-sdk/telegram/network-errors.d.ts +5 -0
  1300. package/dist/plugin-sdk/telegram/outbound-params.d.ts +2 -0
  1301. package/dist/plugin-sdk/telegram/probe.d.ts +17 -0
  1302. package/dist/plugin-sdk/telegram/proxy.d.ts +1 -0
  1303. package/dist/plugin-sdk/telegram/reaction-level.d.ts +11 -0
  1304. package/dist/plugin-sdk/telegram/send.d.ts +153 -0
  1305. package/dist/plugin-sdk/telegram/sent-message-cache.d.ts +16 -0
  1306. package/dist/plugin-sdk/telegram/status-reaction-variants.d.ts +21 -0
  1307. package/dist/plugin-sdk/telegram/sticker-cache.d.ts +47 -0
  1308. package/dist/plugin-sdk/telegram/target-writeback.d.ts +7 -0
  1309. package/dist/plugin-sdk/telegram/targets.d.ts +11 -0
  1310. package/dist/plugin-sdk/telegram/token.d.ts +13 -0
  1311. package/dist/plugin-sdk/telegram/update-offset-store.d.ts +15 -0
  1312. package/dist/plugin-sdk/telegram/voice.d.ts +16 -0
  1313. package/dist/plugin-sdk/telegram/webhook.d.ts +20 -0
  1314. package/dist/plugin-sdk/terminal/ansi.d.ts +2 -0
  1315. package/dist/plugin-sdk/terminal/health-style.d.ts +1 -0
  1316. package/dist/plugin-sdk/terminal/links.d.ts +6 -0
  1317. package/dist/plugin-sdk/terminal/palette.d.ts +10 -0
  1318. package/dist/plugin-sdk/terminal/progress-line.d.ts +3 -0
  1319. package/dist/plugin-sdk/terminal/prompt-style.d.ts +3 -0
  1320. package/dist/plugin-sdk/terminal/restore.d.ts +17 -0
  1321. package/dist/plugin-sdk/terminal/theme.d.ts +15 -0
  1322. package/dist/plugin-sdk/tts/providers/edge.d.ts +2 -0
  1323. package/dist/plugin-sdk/tts/providers/elevenlabs.d.ts +2 -0
  1324. package/dist/plugin-sdk/tts/providers/index.d.ts +4 -0
  1325. package/dist/plugin-sdk/tts/providers/openai.d.ts +2 -0
  1326. package/dist/plugin-sdk/tts/tts-core.d.ts +38 -0
  1327. package/dist/plugin-sdk/tts/tts.d.ts +185 -0
  1328. package/dist/plugin-sdk/tts/types.d.ts +21 -0
  1329. package/dist/plugin-sdk/types/agent-types.d.ts +1 -0
  1330. package/dist/plugin-sdk/utils/account-id.d.ts +1 -0
  1331. package/dist/plugin-sdk/utils/boolean.d.ts +5 -0
  1332. package/dist/plugin-sdk/utils/chunk-items.d.ts +1 -0
  1333. package/dist/plugin-sdk/utils/delivery-context.d.ts +29 -0
  1334. package/dist/plugin-sdk/utils/directive-tags.d.ts +29 -0
  1335. package/dist/plugin-sdk/utils/fetch-timeout.d.ts +13 -0
  1336. package/dist/plugin-sdk/utils/message-channel.d.ts +27 -0
  1337. package/dist/plugin-sdk/utils/normalize-secret-input.d.ts +11 -0
  1338. package/dist/plugin-sdk/utils/provider-utils.d.ts +9 -0
  1339. package/dist/plugin-sdk/utils/queue-helpers.d.ts +80 -0
  1340. package/dist/plugin-sdk/utils/reaction-level.d.ts +15 -0
  1341. package/dist/plugin-sdk/utils/transcript-tools.d.ts +8 -0
  1342. package/dist/plugin-sdk/utils/usage-format.d.ts +26 -0
  1343. package/dist/plugin-sdk/utils/with-timeout.d.ts +1 -0
  1344. package/dist/plugin-sdk/utils.d.ts +63 -0
  1345. package/dist/plugin-sdk/version.d.ts +8 -0
  1346. package/dist/plugin-sdk/web/accounts.d.ts +39 -0
  1347. package/dist/plugin-sdk/web/active-listener.d.ts +25 -0
  1348. package/dist/plugin-sdk/web/auth-store.d.ts +26 -0
  1349. package/dist/plugin-sdk/web/auto-reply/constants.d.ts +1 -0
  1350. package/dist/plugin-sdk/web/auto-reply/deliver-reply.d.ts +19 -0
  1351. package/dist/plugin-sdk/web/auto-reply/heartbeat-runner.d.ts +20 -0
  1352. package/dist/plugin-sdk/web/auto-reply/loggers.d.ts +4 -0
  1353. package/dist/plugin-sdk/web/auto-reply/mentions.d.ts +19 -0
  1354. package/dist/plugin-sdk/web/auto-reply/monitor/ack-reaction.d.ts +13 -0
  1355. package/dist/plugin-sdk/web/auto-reply/monitor/broadcast.d.ts +16 -0
  1356. package/dist/plugin-sdk/web/auto-reply/monitor/commands.d.ts +2 -0
  1357. package/dist/plugin-sdk/web/auto-reply/monitor/echo.d.ts +17 -0
  1358. package/dist/plugin-sdk/web/auto-reply/monitor/group-activation.d.ts +9 -0
  1359. package/dist/plugin-sdk/web/auto-reply/monitor/group-gating.d.ts +33 -0
  1360. package/dist/plugin-sdk/web/auto-reply/monitor/group-members.d.ts +6 -0
  1361. package/dist/plugin-sdk/web/auto-reply/monitor/last-route.d.ts +15 -0
  1362. package/dist/plugin-sdk/web/auto-reply/monitor/message-line.d.ts +11 -0
  1363. package/dist/plugin-sdk/web/auto-reply/monitor/on-message.d.ts +24 -0
  1364. package/dist/plugin-sdk/web/auto-reply/monitor/peer.d.ts +2 -0
  1365. package/dist/plugin-sdk/web/auto-reply/monitor/process-message.d.ts +40 -0
  1366. package/dist/plugin-sdk/web/auto-reply/monitor.d.ts +5 -0
  1367. package/dist/plugin-sdk/web/auto-reply/session-snapshot.d.ts +17 -0
  1368. package/dist/plugin-sdk/web/auto-reply/types.d.ts +30 -0
  1369. package/dist/plugin-sdk/web/auto-reply/util.d.ts +2 -0
  1370. package/dist/plugin-sdk/web/auto-reply.d.ts +1 -0
  1371. package/dist/plugin-sdk/web/auto-reply.impl.d.ts +5 -0
  1372. package/dist/plugin-sdk/web/inbound/access-control.d.ts +36 -0
  1373. package/dist/plugin-sdk/web/inbound/dedupe.d.ts +2 -0
  1374. package/dist/plugin-sdk/web/inbound/extract.d.ts +13 -0
  1375. package/dist/plugin-sdk/web/inbound/media.d.ts +7 -0
  1376. package/dist/plugin-sdk/web/inbound/monitor.d.ts +30 -0
  1377. package/dist/plugin-sdk/web/inbound/send-api.d.ts +22 -0
  1378. package/dist/plugin-sdk/web/inbound/types.d.ts +41 -0
  1379. package/dist/plugin-sdk/web/inbound.d.ts +4 -0
  1380. package/dist/plugin-sdk/web/login-qr.d.ts +19 -0
  1381. package/dist/plugin-sdk/web/login.d.ts +3 -0
  1382. package/dist/plugin-sdk/web/media.d.ts +43 -0
  1383. package/dist/plugin-sdk/web/outbound.d.ts +24 -0
  1384. package/dist/plugin-sdk/web/qr-image.d.ts +4 -0
  1385. package/dist/plugin-sdk/web/reconnect.d.ts +12 -0
  1386. package/dist/plugin-sdk/web/session.d.ts +14 -0
  1387. package/dist/plugin-sdk/web/vcard.d.ts +6 -0
  1388. package/dist/plugin-sdk/whatsapp/normalize.d.ts +6 -0
  1389. package/dist/plugin-sdk/whatsapp/resolve-outbound-target.d.ts +12 -0
  1390. package/dist/plugin-sdk/wizard/prompts.d.ts +43 -0
  1391. package/dist/plugin-sdk/wizard/session.d.ts +42 -0
  1392. package/dist/plugins-Ca4Ybd3t.js +254 -0
  1393. package/dist/plugins-Cjhc9NMf.js +255 -0
  1394. package/dist/plugins-allowlist-A38nxBRG.js +15 -0
  1395. package/dist/plugins-allowlist-D2tS9tcu.js +15 -0
  1396. package/dist/plugins-cli-BvgKK5Ww.js +807 -0
  1397. package/dist/plugins-cli-oK0lk1Ku.js +803 -0
  1398. package/dist/polls-BLyT08ZI.js +33 -0
  1399. package/dist/polls-BmymsJEe.js +33 -0
  1400. package/dist/ports-B4hTs4XH.js +96 -0
  1401. package/dist/ports-CZEhYDiS.js +370 -0
  1402. package/dist/ports-DALdfBQy.js +96 -0
  1403. package/dist/ports-gRBeuUtp.js +316 -0
  1404. package/dist/ports-lsof-CDyv5GJd.js +27 -0
  1405. package/dist/preflight-Bq8rimP-.js +667 -0
  1406. package/dist/preflight-DyYbEp9X.js +667 -0
  1407. package/dist/process-scoped-map-BCJR56ZB.js +39 -0
  1408. package/dist/process-scoped-map-Cb1EHPyN.js +39 -0
  1409. package/dist/program-DKWIpFO9.js +250 -0
  1410. package/dist/program-context-Cgy5-iZi.js +474 -0
  1411. package/dist/program-context-DlXnmuB7.js +17 -0
  1412. package/dist/progress-BcwxtM9Q.js +124 -0
  1413. package/dist/progress-DRLmcFiG.js +123 -0
  1414. package/dist/prompt-BRGfic91.js +21 -0
  1415. package/dist/prompt-CZpYe6wn.js +21 -0
  1416. package/dist/prompt-select-styled-CY647QfO.js +1669 -0
  1417. package/dist/prompt-select-styled-pddqKMoY.js +1672 -0
  1418. package/dist/prompt-style-BpUMhEHC.js +9 -0
  1419. package/dist/prompt-style-CUuA6OCy.js +9 -0
  1420. package/dist/provider-auth-B7QgxlKt.js +187 -0
  1421. package/dist/provider-auth-j-EQvvIk.js +187 -0
  1422. package/dist/provider-dispatcher-DX896bb6.js +659 -0
  1423. package/dist/provider-dispatcher-IV_mSji1.js +660 -0
  1424. package/dist/provider-utils-C9kBVF1f.js +79 -0
  1425. package/dist/provider-utils-DiLhkKQp.js +79 -0
  1426. package/dist/proxy-BMJL0Qog.js +16 -0
  1427. package/dist/proxy-D-qGA1vm.js +16 -0
  1428. package/dist/push-apns--nEiZmEN.js +711 -0
  1429. package/dist/push-apns-BtS6B6lb.js +713 -0
  1430. package/dist/pw-ai-DkXUNGEs.js +1908 -0
  1431. package/dist/pw-ai-oQ2VDwbk.js +1911 -0
  1432. package/dist/pw-ai-state--TxTVwRW.js +11 -0
  1433. package/dist/pw-ai-state-CwXeO5d0.js +11 -0
  1434. package/dist/qr-cli-BffaTzZT.js +353 -0
  1435. package/dist/qr-cli-CKHw8aW4.js +349 -0
  1436. package/dist/redact-BW8tobyp.js +191 -0
  1437. package/dist/redact-Ci96Gj0O.js +191 -0
  1438. package/dist/redact-identifier-Bv5SUUw-.js +15 -0
  1439. package/dist/redact-identifier-HyK89Sod.js +15 -0
  1440. package/dist/redact-snapshot-PHeKfwLg.js +1934 -0
  1441. package/dist/redact-snapshot-h25IHbX2.js +1934 -0
  1442. package/dist/register.agent-BhJGcSwi.js +1029 -0
  1443. package/dist/register.agent-DYcLNpJD.js +292 -0
  1444. package/dist/register.configure-V-MeA6h7.js +135 -0
  1445. package/dist/register.configure-oCfJYt2T.js +130 -0
  1446. package/dist/register.import-CROeeohP.js +31 -0
  1447. package/dist/register.import-DrHKMUlv.js +29 -0
  1448. package/dist/register.maintenance-XRDiAiai.js +501 -0
  1449. package/dist/register.maintenance-mHTyzd1l.js +503 -0
  1450. package/dist/register.message-9FClPeyR.js +687 -0
  1451. package/dist/register.message-DigNUgXx.js +691 -0
  1452. package/dist/register.onboard-CF1DK5RO.js +92 -0
  1453. package/dist/register.onboard-Cm2ExJRM.js +96 -0
  1454. package/dist/register.setup-BEV_QLoU.js +114 -0
  1455. package/dist/register.setup-BboalnlO.js +118 -0
  1456. package/dist/register.status-health-sessions-B5flqjtZ.js +666 -0
  1457. package/dist/register.status-health-sessions-DbQPmWOW.js +428 -0
  1458. package/dist/register.subclis-FFHoriVe.js +267 -0
  1459. package/dist/remoteclaw-root-BfPjgewe.js +88 -0
  1460. package/dist/remoteclaw-root-E4-hmb4E.js +88 -0
  1461. package/dist/render-6ahYfPwj.js +104 -0
  1462. package/dist/render-BhKzKdV0.js +104 -0
  1463. package/dist/render-e7fENCYH.js +104 -0
  1464. package/dist/replies-Dc_GFb85.js +136 -0
  1465. package/dist/replies-nkw9sahT.js +136 -0
  1466. package/dist/reply-D0iVkyuP.js +12366 -0
  1467. package/dist/reply-DEPE5T_9.js +12363 -0
  1468. package/dist/reply-directives-Bbyf2UON.js +182 -0
  1469. package/dist/reply-directives-DiRJRT_6.js +182 -0
  1470. package/dist/reply-payloads-DDrMOUKP.js +527 -0
  1471. package/dist/reply-prefix-Buyx2ZZC.js +37 -0
  1472. package/dist/reply-prefix-D7E0w0O2.js +37 -0
  1473. package/dist/resolve-route-BBOsg5KI.js +249 -0
  1474. package/dist/resolve-route-Dyx3ifWH.js +249 -0
  1475. package/dist/response-prefix-template-CZOMBOE6.js +134 -0
  1476. package/dist/response-prefix-template-xsasdq1T.js +134 -0
  1477. package/dist/retry-BWv_fy4u.js +77 -0
  1478. package/dist/retry-D7zwz3HY.js +77 -0
  1479. package/dist/retry-Dar_7pCv.js +77 -0
  1480. package/dist/rolldown-runtime-Cbj13DAv.js +20 -0
  1481. package/dist/run-main-BUSpd6Gy.js +308 -0
  1482. package/dist/runtime-guard-Bhx-pb8_.js +60 -0
  1483. package/dist/runtime-guard-DAHXelsb.js +60 -0
  1484. package/dist/runtime-status-CR9445g5.js +12 -0
  1485. package/dist/runtime-status-hFVEC3wO.js +12 -0
  1486. package/dist/secret-equal-D6AoXne1.js +11 -0
  1487. package/dist/secret-equal-DLnUuWM3.js +11 -0
  1488. package/dist/secure-random-B8v4P_PH.js +44 -0
  1489. package/dist/secure-random-Ba4Y5xG5.js +12 -0
  1490. package/dist/secure-random-CRVHgtmO.js +12 -0
  1491. package/dist/security-cli-C8r-8YZ7.js +488 -0
  1492. package/dist/security-cli-Cy2Jqb0n.js +483 -0
  1493. package/dist/send-B5iWtbNX.js +349 -0
  1494. package/dist/send-BaaCgoKI.js +374 -0
  1495. package/dist/send-Brtl2skD.js +332 -0
  1496. package/dist/send-BuKAbt8a.js +547 -0
  1497. package/dist/send-BxQ1YFYH.js +1178 -0
  1498. package/dist/send-C7xFV4Ul.js +29 -0
  1499. package/dist/send-C9pLn8Zz.js +11 -0
  1500. package/dist/send-CPn9GDbB.js +349 -0
  1501. package/dist/send-DJ5jHNeg.js +1779 -0
  1502. package/dist/send-DLLYgtkJ.js +2245 -0
  1503. package/dist/send-DO4RP5yz.js +1776 -0
  1504. package/dist/send-DYHrHs_8.js +492 -0
  1505. package/dist/send-DZ80jwFi.js +426 -0
  1506. package/dist/send-Dbl0_FNE.js +2245 -0
  1507. package/dist/send-DpaTnM-a.js +492 -0
  1508. package/dist/send-gxeISRd1.js +547 -0
  1509. package/dist/server-BZfrR2D5.js +206 -0
  1510. package/dist/server-CW4QQmFB.js +202 -0
  1511. package/dist/server-lifecycle-CY3Lxtea.js +2437 -0
  1512. package/dist/server-lifecycle-X3AKkvMo.js +2437 -0
  1513. package/dist/server-node-events-q5He8xk5.js +391 -0
  1514. package/dist/server-node-events-udPU4Xlv.js +395 -0
  1515. package/dist/service-C2j81L86.js +670 -0
  1516. package/dist/service-C8a0SXHD.js +670 -0
  1517. package/dist/session-C6VKWvx6.js +170 -0
  1518. package/dist/session-cost-usage-0Vs4hgMe.js +627 -0
  1519. package/dist/session-cost-usage-C-DsaOfN.js +627 -0
  1520. package/dist/session-dirs-CO1f2ArM.js +318 -0
  1521. package/dist/session-dirs-DoboH7Oy.js +318 -0
  1522. package/dist/session-enM9-2If.js +170 -0
  1523. package/dist/session-key-BF-9YzxC.js +235 -0
  1524. package/dist/session-key-CgKWfjoZ.js +235 -0
  1525. package/dist/session-utils-VKfyrS3d.js +621 -0
  1526. package/dist/session-utils-_U6PeQeD.js +621 -0
  1527. package/dist/sessions-Dg3febTj.js +2553 -0
  1528. package/dist/sessions-Fhrpa-qj.js +245 -0
  1529. package/dist/shell-env-DBS5su07.js +163 -0
  1530. package/dist/shell-env-c3j5zcU9.js +163 -0
  1531. package/dist/ssrf-8wNqPNzN.js +183 -0
  1532. package/dist/ssrf-CJIdPXuS.js +183 -0
  1533. package/dist/stagger--wvODnNe.js +56 -0
  1534. package/dist/stagger-BLmTO4cK.js +56 -0
  1535. package/dist/status-1zVD-Clq.js +21 -0
  1536. package/dist/status-B_wW9Vt8.js +1936 -0
  1537. package/dist/status-BtRY0nXQ.js +21 -0
  1538. package/dist/status-D3leIzsB.js +1940 -0
  1539. package/dist/status.update-BmuDZ7E7.js +449 -0
  1540. package/dist/status.update-Mf6HSRvU.js +449 -0
  1541. package/dist/store-BmUyjVdV.js +2555 -0
  1542. package/dist/store-CzhBjUCN.js +64 -0
  1543. package/dist/store-DlqiXmDO.js +53 -0
  1544. package/dist/store-LXf4lUUA.js +64 -0
  1545. package/dist/strip-inbound-meta-zmUXypSS.js +110 -0
  1546. package/dist/strip-inbound-meta-zqtN9FTK.js +110 -0
  1547. package/dist/subagent-registry-BCGOdOC-.js +4839 -0
  1548. package/dist/subagent-registry-Bjx9LVlV.js +4841 -0
  1549. package/dist/subsystem-BAW_f3DI.js +1195 -0
  1550. package/dist/subsystem-DE8w_S23.js +1081 -0
  1551. package/dist/system-cli-CDi0wZXE.js +73 -0
  1552. package/dist/system-cli-CrzLj6XB.js +77 -0
  1553. package/dist/systemd-40Rij3QR.js +547 -0
  1554. package/dist/systemd-5C97CSzd.js +547 -0
  1555. package/dist/systemd-hints-CyQqHq1i.js +278 -0
  1556. package/dist/systemd-hints-Dbpv6gQ1.js +278 -0
  1557. package/dist/systemd-linger-B2rPbnAi.js +75 -0
  1558. package/dist/systemd-linger-DDvkfxH-.js +75 -0
  1559. package/dist/table-DFx25vNb.js +279 -0
  1560. package/dist/table-On3hkCqi.js +278 -0
  1561. package/dist/tables-BFyFqtLB.js +55 -0
  1562. package/dist/tables-Crybi0rV.js +55 -0
  1563. package/dist/tables-Dwxstcvj.js +55 -0
  1564. package/dist/tailnet-Da-_9e8E.js +40 -0
  1565. package/dist/tailnet-xt92Yaop.js +40 -0
  1566. package/dist/tailscale-CnV0JWca.js +230 -0
  1567. package/dist/tailscale-VkEC8dzj.js +230 -0
  1568. package/dist/target-errors-ChjvOMuV.js +26 -0
  1569. package/dist/target-errors-GZXDqlUu.js +26 -0
  1570. package/dist/targets-B46m7u5J.js +45 -0
  1571. package/dist/targets-BegO82oK.js +2614 -0
  1572. package/dist/targets-BpTQ50aN.js +649 -0
  1573. package/dist/targets-BtGRUQMa.js +79 -0
  1574. package/dist/targets-C99szk_e.js +114 -0
  1575. package/dist/targets-CmC5m7Ey.js +53 -0
  1576. package/dist/targets-D01MJGnh.js +79 -0
  1577. package/dist/targets-D3r6Zgic.js +39 -0
  1578. package/dist/targets-D7PT_rdO.js +45 -0
  1579. package/dist/targets-D8Rv_6CT.js +649 -0
  1580. package/dist/targets-DJ_OVcyq.js +220 -0
  1581. package/dist/targets-_UWmnyI9.js +53 -0
  1582. package/dist/targets-felDvoku.js +2613 -0
  1583. package/dist/targets-tDrl_ioQ.js +46 -0
  1584. package/dist/text-format-DarxU3JH.js +9 -0
  1585. package/dist/text-format-Ds92M9UT.js +9 -0
  1586. package/dist/thinking-4nOZPunr.js +60 -0
  1587. package/dist/thinking-ZfH2V9Os.js +60 -0
  1588. package/dist/tokens-Dw7ZdYwT.js +21 -0
  1589. package/dist/tokens-TtJJxzRr.js +21 -0
  1590. package/dist/tool-display-Bxs_1jIn.js +785 -0
  1591. package/dist/tool-display-D9p_Ttkq.js +785 -0
  1592. package/dist/tool-images-9Ron321Q.js +263 -0
  1593. package/dist/tool-images-BWhy6WRN.js +263 -0
  1594. package/dist/trash-BpB96kHe.js +125 -0
  1595. package/dist/trash-De0DLz-t.js +125 -0
  1596. package/dist/tui-M21MnbJp.js +3237 -0
  1597. package/dist/tui-cli-mxjebFIk.js +63 -0
  1598. package/dist/tui-cli-x2aEqskG.js +67 -0
  1599. package/dist/tui-qVJob4mN.js +3237 -0
  1600. package/dist/types.tools-BBb2rl3g.js +23 -0
  1601. package/dist/types.tools-BDJw1yFx.js +23 -0
  1602. package/dist/update-Bv3EwRgy.js +349 -0
  1603. package/dist/update-D2gIPs2g.js +349 -0
  1604. package/dist/update-cli-B_tiAE6B.js +1149 -0
  1605. package/dist/update-cli-DdERWV6b.js +1147 -0
  1606. package/dist/usage-BIzKZ5dT.js +57 -0
  1607. package/dist/usage-BvZOzIC7.js +57 -0
  1608. package/dist/usage-CCU9qNC5.js +5472 -0
  1609. package/dist/usage-format-CmniSPCG.js +31 -0
  1610. package/dist/usage-format-D_KQYQ-w.js +31 -0
  1611. package/dist/utils-DPoNpP7D.js +631 -0
  1612. package/dist/version-3QUZW8EP.js +52 -0
  1613. package/dist/version-CVMnqdzu.js +52 -0
  1614. package/dist/voice-credentials-CxWaO19D.js +46 -0
  1615. package/dist/voice-credentials-DXU-y9z7.js +46 -0
  1616. package/dist/warning-filter.js +48 -0
  1617. package/dist/web-CCN82vao.js +74 -0
  1618. package/dist/web-MFXYQO8v.js +79 -0
  1619. package/dist/web-zotCHj-B.js +3051 -0
  1620. package/dist/webhooks-cli-BB6FZ7La.js +330 -0
  1621. package/dist/webhooks-cli-BoZinXXo.js +334 -0
  1622. package/dist/whatsapp-actions-COMlNQFa.js +126 -0
  1623. package/dist/whatsapp-actions-YZgc7smO.js +131 -0
  1624. package/dist/widearea-dns-CQqZIeu8.js +127 -0
  1625. package/dist/widearea-dns-D01FFYZ8.js +127 -0
  1626. package/dist/workspace-BJCKO8Ns.js +10 -0
  1627. package/dist/workspace-BisvA9oA.js +10 -0
  1628. package/dist/workspace-Bj_uUDJr.js +439 -0
  1629. package/dist/workspace-S9vwEco2.js +441 -0
  1630. package/dist/wsl-PDLKeX04.js +52 -0
  1631. package/dist/wsl-kFaeW76c.js +52 -0
  1632. package/dist/zod-schema-7uqrpeBz.js +2715 -0
  1633. package/dist/zod-schema-CdBaNuxH.js +2715 -0
  1634. package/extensions/bluebubbles/README.md +45 -0
  1635. package/extensions/bluebubbles/index.ts +19 -0
  1636. package/extensions/bluebubbles/package.json +33 -0
  1637. package/extensions/bluebubbles/remoteclaw.plugin.json +9 -0
  1638. package/extensions/bluebubbles/src/account-resolve.ts +35 -0
  1639. package/extensions/bluebubbles/src/accounts.ts +90 -0
  1640. package/extensions/bluebubbles/src/actions.ts +460 -0
  1641. package/extensions/bluebubbles/src/attachments.ts +268 -0
  1642. package/extensions/bluebubbles/src/channel.ts +418 -0
  1643. package/extensions/bluebubbles/src/chat.ts +329 -0
  1644. package/extensions/bluebubbles/src/config-schema.ts +65 -0
  1645. package/extensions/bluebubbles/src/history.ts +177 -0
  1646. package/extensions/bluebubbles/src/media-send.ts +317 -0
  1647. package/extensions/bluebubbles/src/monitor-normalize.ts +825 -0
  1648. package/extensions/bluebubbles/src/monitor-processing.ts +1448 -0
  1649. package/extensions/bluebubbles/src/monitor-reply-cache.ts +185 -0
  1650. package/extensions/bluebubbles/src/monitor-shared.ts +41 -0
  1651. package/extensions/bluebubbles/src/monitor.ts +534 -0
  1652. package/extensions/bluebubbles/src/multipart.ts +32 -0
  1653. package/extensions/bluebubbles/src/onboarding.ts +340 -0
  1654. package/extensions/bluebubbles/src/probe.ts +163 -0
  1655. package/extensions/bluebubbles/src/reactions.ts +182 -0
  1656. package/extensions/bluebubbles/src/request-url.ts +12 -0
  1657. package/extensions/bluebubbles/src/runtime.ts +34 -0
  1658. package/extensions/bluebubbles/src/send-helpers.ts +53 -0
  1659. package/extensions/bluebubbles/src/send.ts +472 -0
  1660. package/extensions/bluebubbles/src/targets.ts +370 -0
  1661. package/extensions/bluebubbles/src/test-harness.ts +79 -0
  1662. package/extensions/bluebubbles/src/test-mocks.ts +11 -0
  1663. package/extensions/bluebubbles/src/types.ts +135 -0
  1664. package/extensions/device-pair/index.ts +529 -0
  1665. package/extensions/device-pair/remoteclaw.plugin.json +20 -0
  1666. package/extensions/diagnostics-otel/index.ts +15 -0
  1667. package/extensions/diagnostics-otel/node_modules/.bin/acorn +21 -0
  1668. package/extensions/diagnostics-otel/package.json +24 -0
  1669. package/extensions/diagnostics-otel/remoteclaw.plugin.json +8 -0
  1670. package/extensions/diagnostics-otel/src/service.ts +682 -0
  1671. package/extensions/discord/index.ts +19 -0
  1672. package/extensions/discord/package.json +11 -0
  1673. package/extensions/discord/remoteclaw.plugin.json +9 -0
  1674. package/extensions/discord/src/channel.ts +451 -0
  1675. package/extensions/discord/src/runtime.ts +14 -0
  1676. package/extensions/discord/src/subagent-hooks.ts +152 -0
  1677. package/extensions/feishu/index.ts +63 -0
  1678. package/extensions/feishu/package.json +34 -0
  1679. package/extensions/feishu/remoteclaw.plugin.json +9 -0
  1680. package/extensions/feishu/skills/feishu-doc/SKILL.md +105 -0
  1681. package/extensions/feishu/skills/feishu-doc/references/block-types.md +103 -0
  1682. package/extensions/feishu/skills/feishu-drive/SKILL.md +97 -0
  1683. package/extensions/feishu/skills/feishu-perm/SKILL.md +119 -0
  1684. package/extensions/feishu/skills/feishu-wiki/SKILL.md +111 -0
  1685. package/extensions/feishu/src/accounts.ts +144 -0
  1686. package/extensions/feishu/src/bitable.ts +739 -0
  1687. package/extensions/feishu/src/bot.ts +1006 -0
  1688. package/extensions/feishu/src/channel.ts +359 -0
  1689. package/extensions/feishu/src/client.ts +118 -0
  1690. package/extensions/feishu/src/config-schema.ts +226 -0
  1691. package/extensions/feishu/src/dedup.ts +54 -0
  1692. package/extensions/feishu/src/directory.ts +177 -0
  1693. package/extensions/feishu/src/doc-schema.ts +47 -0
  1694. package/extensions/feishu/src/docx.ts +536 -0
  1695. package/extensions/feishu/src/drive-schema.ts +46 -0
  1696. package/extensions/feishu/src/drive.ts +227 -0
  1697. package/extensions/feishu/src/dynamic-agent.ts +131 -0
  1698. package/extensions/feishu/src/external-keys.ts +19 -0
  1699. package/extensions/feishu/src/media.ts +441 -0
  1700. package/extensions/feishu/src/mention.ts +133 -0
  1701. package/extensions/feishu/src/monitor.ts +397 -0
  1702. package/extensions/feishu/src/onboarding.ts +351 -0
  1703. package/extensions/feishu/src/outbound.ts +55 -0
  1704. package/extensions/feishu/src/perm-schema.ts +52 -0
  1705. package/extensions/feishu/src/perm.ts +173 -0
  1706. package/extensions/feishu/src/policy.ts +120 -0
  1707. package/extensions/feishu/src/probe.ts +44 -0
  1708. package/extensions/feishu/src/reactions.ts +160 -0
  1709. package/extensions/feishu/src/reply-dispatcher.ts +239 -0
  1710. package/extensions/feishu/src/runtime.ts +14 -0
  1711. package/extensions/feishu/src/send-result.ts +29 -0
  1712. package/extensions/feishu/src/send-target.ts +25 -0
  1713. package/extensions/feishu/src/send.ts +313 -0
  1714. package/extensions/feishu/src/streaming-card.ts +218 -0
  1715. package/extensions/feishu/src/targets.ts +78 -0
  1716. package/extensions/feishu/src/tools-config.ts +21 -0
  1717. package/extensions/feishu/src/types.ts +81 -0
  1718. package/extensions/feishu/src/typing.ts +80 -0
  1719. package/extensions/feishu/src/wiki-schema.ts +55 -0
  1720. package/extensions/feishu/src/wiki.ts +232 -0
  1721. package/extensions/googlechat/index.ts +19 -0
  1722. package/extensions/googlechat/node_modules/.bin/nlc +21 -0
  1723. package/extensions/googlechat/node_modules/.bin/node-llama-cpp +21 -0
  1724. package/extensions/googlechat/node_modules/.bin/remoteclaw +21 -0
  1725. package/extensions/googlechat/node_modules/.bin/tsc +21 -0
  1726. package/extensions/googlechat/node_modules/.bin/tsserver +21 -0
  1727. package/extensions/googlechat/package.json +37 -0
  1728. package/extensions/googlechat/remoteclaw.plugin.json +9 -0
  1729. package/extensions/googlechat/src/accounts.ts +147 -0
  1730. package/extensions/googlechat/src/actions.ts +176 -0
  1731. package/extensions/googlechat/src/api.ts +282 -0
  1732. package/extensions/googlechat/src/auth.ts +137 -0
  1733. package/extensions/googlechat/src/channel.ts +576 -0
  1734. package/extensions/googlechat/src/monitor.ts +965 -0
  1735. package/extensions/googlechat/src/onboarding.ts +270 -0
  1736. package/extensions/googlechat/src/runtime.ts +14 -0
  1737. package/extensions/googlechat/src/targets.ts +65 -0
  1738. package/extensions/googlechat/src/types.config.ts +3 -0
  1739. package/extensions/googlechat/src/types.ts +73 -0
  1740. package/extensions/imessage/index.ts +17 -0
  1741. package/extensions/imessage/package.json +12 -0
  1742. package/extensions/imessage/remoteclaw.plugin.json +9 -0
  1743. package/extensions/imessage/src/channel.ts +304 -0
  1744. package/extensions/imessage/src/runtime.ts +14 -0
  1745. package/extensions/irc/index.ts +17 -0
  1746. package/extensions/irc/package.json +11 -0
  1747. package/extensions/irc/remoteclaw.plugin.json +9 -0
  1748. package/extensions/irc/src/accounts.ts +268 -0
  1749. package/extensions/irc/src/channel.ts +364 -0
  1750. package/extensions/irc/src/client.ts +439 -0
  1751. package/extensions/irc/src/config-schema.ts +91 -0
  1752. package/extensions/irc/src/connect-options.ts +30 -0
  1753. package/extensions/irc/src/control-chars.ts +22 -0
  1754. package/extensions/irc/src/inbound.ts +371 -0
  1755. package/extensions/irc/src/monitor.ts +146 -0
  1756. package/extensions/irc/src/normalize.ts +123 -0
  1757. package/extensions/irc/src/onboarding.ts +479 -0
  1758. package/extensions/irc/src/policy.ts +166 -0
  1759. package/extensions/irc/src/probe.ts +53 -0
  1760. package/extensions/irc/src/protocol.ts +169 -0
  1761. package/extensions/irc/src/runtime.ts +14 -0
  1762. package/extensions/irc/src/send.ts +88 -0
  1763. package/extensions/irc/src/types.ts +98 -0
  1764. package/extensions/line/index.ts +19 -0
  1765. package/extensions/line/package.json +27 -0
  1766. package/extensions/line/remoteclaw.plugin.json +9 -0
  1767. package/extensions/line/src/card-command.ts +344 -0
  1768. package/extensions/line/src/channel.ts +797 -0
  1769. package/extensions/line/src/runtime.ts +14 -0
  1770. package/extensions/matrix/CHANGELOG.md +32 -0
  1771. package/extensions/matrix/index.ts +17 -0
  1772. package/extensions/matrix/node_modules/.bin/markdown-it +21 -0
  1773. package/extensions/matrix/package.json +33 -0
  1774. package/extensions/matrix/remoteclaw.plugin.json +9 -0
  1775. package/extensions/matrix/src/actions.ts +195 -0
  1776. package/extensions/matrix/src/channel.ts +486 -0
  1777. package/extensions/matrix/src/config-schema.ts +63 -0
  1778. package/extensions/matrix/src/directory-live.ts +208 -0
  1779. package/extensions/matrix/src/group-mentions.ts +52 -0
  1780. package/extensions/matrix/src/matrix/accounts.ts +137 -0
  1781. package/extensions/matrix/src/matrix/actions/client.ts +47 -0
  1782. package/extensions/matrix/src/matrix/actions/limits.ts +6 -0
  1783. package/extensions/matrix/src/matrix/actions/messages.ts +126 -0
  1784. package/extensions/matrix/src/matrix/actions/pins.ts +84 -0
  1785. package/extensions/matrix/src/matrix/actions/reactions.ts +102 -0
  1786. package/extensions/matrix/src/matrix/actions/room.ts +85 -0
  1787. package/extensions/matrix/src/matrix/actions/summary.ts +75 -0
  1788. package/extensions/matrix/src/matrix/actions/types.ts +85 -0
  1789. package/extensions/matrix/src/matrix/actions.ts +15 -0
  1790. package/extensions/matrix/src/matrix/active-client.ts +32 -0
  1791. package/extensions/matrix/src/matrix/client/config.ts +219 -0
  1792. package/extensions/matrix/src/matrix/client/create-client.ts +123 -0
  1793. package/extensions/matrix/src/matrix/client/logging.ts +36 -0
  1794. package/extensions/matrix/src/matrix/client/runtime.ts +4 -0
  1795. package/extensions/matrix/src/matrix/client/shared.ts +201 -0
  1796. package/extensions/matrix/src/matrix/client/storage.ts +131 -0
  1797. package/extensions/matrix/src/matrix/client/types.ts +34 -0
  1798. package/extensions/matrix/src/matrix/client-bootstrap.ts +39 -0
  1799. package/extensions/matrix/src/matrix/client.ts +14 -0
  1800. package/extensions/matrix/src/matrix/credentials.ts +125 -0
  1801. package/extensions/matrix/src/matrix/deps.ts +60 -0
  1802. package/extensions/matrix/src/matrix/format.ts +22 -0
  1803. package/extensions/matrix/src/matrix/index.ts +11 -0
  1804. package/extensions/matrix/src/matrix/monitor/allowlist.ts +103 -0
  1805. package/extensions/matrix/src/matrix/monitor/auto-join.ts +71 -0
  1806. package/extensions/matrix/src/matrix/monitor/direct.ts +104 -0
  1807. package/extensions/matrix/src/matrix/monitor/events.ts +148 -0
  1808. package/extensions/matrix/src/matrix/monitor/handler.ts +688 -0
  1809. package/extensions/matrix/src/matrix/monitor/index.ts +358 -0
  1810. package/extensions/matrix/src/matrix/monitor/location.ts +100 -0
  1811. package/extensions/matrix/src/matrix/monitor/media.ts +118 -0
  1812. package/extensions/matrix/src/matrix/monitor/mentions.ts +62 -0
  1813. package/extensions/matrix/src/matrix/monitor/replies.ts +100 -0
  1814. package/extensions/matrix/src/matrix/monitor/room-info.ts +55 -0
  1815. package/extensions/matrix/src/matrix/monitor/rooms.ts +47 -0
  1816. package/extensions/matrix/src/matrix/monitor/threads.ts +68 -0
  1817. package/extensions/matrix/src/matrix/monitor/types.ts +39 -0
  1818. package/extensions/matrix/src/matrix/poll-types.ts +167 -0
  1819. package/extensions/matrix/src/matrix/probe.ts +69 -0
  1820. package/extensions/matrix/src/matrix/send/client.ts +97 -0
  1821. package/extensions/matrix/src/matrix/send/formatting.ts +93 -0
  1822. package/extensions/matrix/src/matrix/send/media.ts +230 -0
  1823. package/extensions/matrix/src/matrix/send/targets.ts +150 -0
  1824. package/extensions/matrix/src/matrix/send/types.ts +109 -0
  1825. package/extensions/matrix/src/matrix/send-queue.ts +44 -0
  1826. package/extensions/matrix/src/matrix/send.ts +265 -0
  1827. package/extensions/matrix/src/onboarding.ts +446 -0
  1828. package/extensions/matrix/src/outbound.ts +55 -0
  1829. package/extensions/matrix/src/resolve-targets.ts +126 -0
  1830. package/extensions/matrix/src/runtime.ts +14 -0
  1831. package/extensions/matrix/src/tool-actions.ts +164 -0
  1832. package/extensions/matrix/src/types.ts +114 -0
  1833. package/extensions/mattermost/index.ts +17 -0
  1834. package/extensions/mattermost/package.json +25 -0
  1835. package/extensions/mattermost/remoteclaw.plugin.json +9 -0
  1836. package/extensions/mattermost/src/channel.ts +439 -0
  1837. package/extensions/mattermost/src/config-schema.ts +62 -0
  1838. package/extensions/mattermost/src/group-mentions.ts +15 -0
  1839. package/extensions/mattermost/src/mattermost/accounts.ts +128 -0
  1840. package/extensions/mattermost/src/mattermost/client.ts +230 -0
  1841. package/extensions/mattermost/src/mattermost/index.ts +9 -0
  1842. package/extensions/mattermost/src/mattermost/monitor-helpers.ts +71 -0
  1843. package/extensions/mattermost/src/mattermost/monitor-onchar.ts +25 -0
  1844. package/extensions/mattermost/src/mattermost/monitor-websocket.ts +221 -0
  1845. package/extensions/mattermost/src/mattermost/monitor.ts +1061 -0
  1846. package/extensions/mattermost/src/mattermost/probe.ts +61 -0
  1847. package/extensions/mattermost/src/mattermost/reactions.test-helpers.ts +83 -0
  1848. package/extensions/mattermost/src/mattermost/reactions.ts +124 -0
  1849. package/extensions/mattermost/src/mattermost/reconnect.ts +103 -0
  1850. package/extensions/mattermost/src/mattermost/send.ts +231 -0
  1851. package/extensions/mattermost/src/normalize.ts +46 -0
  1852. package/extensions/mattermost/src/onboarding-helpers.ts +1 -0
  1853. package/extensions/mattermost/src/onboarding.ts +182 -0
  1854. package/extensions/mattermost/src/runtime.ts +14 -0
  1855. package/extensions/mattermost/src/types.ts +62 -0
  1856. package/extensions/msteams/CHANGELOG.md +35 -0
  1857. package/extensions/msteams/index.ts +17 -0
  1858. package/extensions/msteams/package.json +32 -0
  1859. package/extensions/msteams/remoteclaw.plugin.json +9 -0
  1860. package/extensions/msteams/src/attachments/download.ts +282 -0
  1861. package/extensions/msteams/src/attachments/graph.ts +354 -0
  1862. package/extensions/msteams/src/attachments/html.ts +90 -0
  1863. package/extensions/msteams/src/attachments/payload.ts +14 -0
  1864. package/extensions/msteams/src/attachments/remote-media.ts +42 -0
  1865. package/extensions/msteams/src/attachments/shared.ts +404 -0
  1866. package/extensions/msteams/src/attachments/types.ts +37 -0
  1867. package/extensions/msteams/src/attachments.ts +18 -0
  1868. package/extensions/msteams/src/channel.ts +464 -0
  1869. package/extensions/msteams/src/conversation-store-fs.ts +165 -0
  1870. package/extensions/msteams/src/conversation-store-memory.ts +47 -0
  1871. package/extensions/msteams/src/conversation-store.ts +41 -0
  1872. package/extensions/msteams/src/directory-live.ts +108 -0
  1873. package/extensions/msteams/src/errors.ts +190 -0
  1874. package/extensions/msteams/src/file-consent-helpers.ts +73 -0
  1875. package/extensions/msteams/src/file-consent.ts +126 -0
  1876. package/extensions/msteams/src/file-lock.ts +1 -0
  1877. package/extensions/msteams/src/graph-chat.ts +53 -0
  1878. package/extensions/msteams/src/graph-upload.ts +452 -0
  1879. package/extensions/msteams/src/graph-users.ts +29 -0
  1880. package/extensions/msteams/src/graph.ts +81 -0
  1881. package/extensions/msteams/src/inbound.ts +48 -0
  1882. package/extensions/msteams/src/index.ts +4 -0
  1883. package/extensions/msteams/src/media-helpers.ts +105 -0
  1884. package/extensions/msteams/src/mentions.ts +114 -0
  1885. package/extensions/msteams/src/messenger.ts +484 -0
  1886. package/extensions/msteams/src/monitor-handler/inbound-media.ts +128 -0
  1887. package/extensions/msteams/src/monitor-handler/message-handler.ts +661 -0
  1888. package/extensions/msteams/src/monitor-handler.ts +162 -0
  1889. package/extensions/msteams/src/monitor-types.ts +5 -0
  1890. package/extensions/msteams/src/monitor.ts +305 -0
  1891. package/extensions/msteams/src/onboarding.ts +406 -0
  1892. package/extensions/msteams/src/outbound.ts +46 -0
  1893. package/extensions/msteams/src/pending-uploads.ts +89 -0
  1894. package/extensions/msteams/src/policy.ts +259 -0
  1895. package/extensions/msteams/src/polls-store-memory.ts +32 -0
  1896. package/extensions/msteams/src/polls.ts +315 -0
  1897. package/extensions/msteams/src/probe.ts +94 -0
  1898. package/extensions/msteams/src/reply-dispatcher.ts +132 -0
  1899. package/extensions/msteams/src/resolve-allowlist.ts +198 -0
  1900. package/extensions/msteams/src/runtime.ts +14 -0
  1901. package/extensions/msteams/src/sdk-types.ts +19 -0
  1902. package/extensions/msteams/src/sdk.ts +33 -0
  1903. package/extensions/msteams/src/send-context.ts +164 -0
  1904. package/extensions/msteams/src/send.ts +530 -0
  1905. package/extensions/msteams/src/sent-message-cache.ts +44 -0
  1906. package/extensions/msteams/src/storage.ts +25 -0
  1907. package/extensions/msteams/src/store-fs.ts +44 -0
  1908. package/extensions/msteams/src/test-runtime.ts +16 -0
  1909. package/extensions/msteams/src/token-response.ts +11 -0
  1910. package/extensions/msteams/src/token.ts +19 -0
  1911. package/extensions/nextcloud-talk/index.ts +17 -0
  1912. package/extensions/nextcloud-talk/package.json +30 -0
  1913. package/extensions/nextcloud-talk/remoteclaw.plugin.json +9 -0
  1914. package/extensions/nextcloud-talk/src/accounts.ts +170 -0
  1915. package/extensions/nextcloud-talk/src/channel.ts +416 -0
  1916. package/extensions/nextcloud-talk/src/config-schema.ts +72 -0
  1917. package/extensions/nextcloud-talk/src/format.ts +79 -0
  1918. package/extensions/nextcloud-talk/src/inbound.ts +342 -0
  1919. package/extensions/nextcloud-talk/src/monitor.ts +275 -0
  1920. package/extensions/nextcloud-talk/src/normalize.ts +39 -0
  1921. package/extensions/nextcloud-talk/src/onboarding.ts +349 -0
  1922. package/extensions/nextcloud-talk/src/policy.ts +180 -0
  1923. package/extensions/nextcloud-talk/src/room-info.ts +125 -0
  1924. package/extensions/nextcloud-talk/src/runtime.ts +14 -0
  1925. package/extensions/nextcloud-talk/src/send.ts +215 -0
  1926. package/extensions/nextcloud-talk/src/signature.ts +72 -0
  1927. package/extensions/nextcloud-talk/src/types.ts +184 -0
  1928. package/extensions/nostr/CHANGELOG.md +44 -0
  1929. package/extensions/nostr/README.md +136 -0
  1930. package/extensions/nostr/index.ts +68 -0
  1931. package/extensions/nostr/node_modules/.bin/tsc +21 -0
  1932. package/extensions/nostr/node_modules/.bin/tsserver +21 -0
  1933. package/extensions/nostr/package.json +30 -0
  1934. package/extensions/nostr/remoteclaw.plugin.json +9 -0
  1935. package/extensions/nostr/src/channel.ts +345 -0
  1936. package/extensions/nostr/src/config-schema.ts +90 -0
  1937. package/extensions/nostr/src/metrics.ts +458 -0
  1938. package/extensions/nostr/src/nostr-bus.ts +719 -0
  1939. package/extensions/nostr/src/nostr-profile-http.ts +519 -0
  1940. package/extensions/nostr/src/nostr-profile-import.ts +262 -0
  1941. package/extensions/nostr/src/nostr-profile.ts +277 -0
  1942. package/extensions/nostr/src/nostr-state-store.ts +226 -0
  1943. package/extensions/nostr/src/runtime.ts +14 -0
  1944. package/extensions/nostr/src/seen-tracker.ts +289 -0
  1945. package/extensions/nostr/src/types.ts +101 -0
  1946. package/extensions/phone-control/index.ts +421 -0
  1947. package/extensions/phone-control/remoteclaw.plugin.json +10 -0
  1948. package/extensions/shared/resolve-target-test-helpers.ts +66 -0
  1949. package/extensions/signal/index.ts +17 -0
  1950. package/extensions/signal/package.json +12 -0
  1951. package/extensions/signal/remoteclaw.plugin.json +9 -0
  1952. package/extensions/signal/src/channel.ts +299 -0
  1953. package/extensions/signal/src/runtime.ts +14 -0
  1954. package/extensions/slack/index.ts +17 -0
  1955. package/extensions/slack/package.json +12 -0
  1956. package/extensions/slack/remoteclaw.plugin.json +9 -0
  1957. package/extensions/slack/src/channel.ts +421 -0
  1958. package/extensions/slack/src/runtime.ts +14 -0
  1959. package/extensions/synology-chat/index.ts +17 -0
  1960. package/extensions/synology-chat/package.json +28 -0
  1961. package/extensions/synology-chat/remoteclaw.plugin.json +9 -0
  1962. package/extensions/synology-chat/src/accounts.ts +87 -0
  1963. package/extensions/synology-chat/src/channel.ts +347 -0
  1964. package/extensions/synology-chat/src/client.ts +142 -0
  1965. package/extensions/synology-chat/src/runtime.ts +20 -0
  1966. package/extensions/synology-chat/src/security.ts +140 -0
  1967. package/extensions/synology-chat/src/types.ts +60 -0
  1968. package/extensions/synology-chat/src/webhook-handler.ts +221 -0
  1969. package/extensions/talk-voice/index.ts +150 -0
  1970. package/extensions/talk-voice/remoteclaw.plugin.json +10 -0
  1971. package/extensions/telegram/index.ts +17 -0
  1972. package/extensions/telegram/package.json +12 -0
  1973. package/extensions/telegram/remoteclaw.plugin.json +9 -0
  1974. package/extensions/telegram/src/channel.ts +569 -0
  1975. package/extensions/telegram/src/runtime.ts +14 -0
  1976. package/extensions/test-utils/runtime-env.ts +12 -0
  1977. package/extensions/thread-ownership/index.ts +133 -0
  1978. package/extensions/thread-ownership/remoteclaw.plugin.json +28 -0
  1979. package/extensions/tlon/README.md +5 -0
  1980. package/extensions/tlon/index.ts +17 -0
  1981. package/extensions/tlon/package.json +29 -0
  1982. package/extensions/tlon/remoteclaw.plugin.json +9 -0
  1983. package/extensions/tlon/src/account-fields.ts +25 -0
  1984. package/extensions/tlon/src/channel.ts +384 -0
  1985. package/extensions/tlon/src/config-schema.ts +41 -0
  1986. package/extensions/tlon/src/monitor/discovery.ts +78 -0
  1987. package/extensions/tlon/src/monitor/history.ts +92 -0
  1988. package/extensions/tlon/src/monitor/index.ts +591 -0
  1989. package/extensions/tlon/src/monitor/processed-messages.ts +33 -0
  1990. package/extensions/tlon/src/monitor/utils.ts +106 -0
  1991. package/extensions/tlon/src/onboarding.ts +229 -0
  1992. package/extensions/tlon/src/runtime.ts +14 -0
  1993. package/extensions/tlon/src/targets.ts +89 -0
  1994. package/extensions/tlon/src/types.ts +99 -0
  1995. package/extensions/tlon/src/urbit/auth.ts +48 -0
  1996. package/extensions/tlon/src/urbit/base-url.ts +57 -0
  1997. package/extensions/tlon/src/urbit/channel-client.ts +158 -0
  1998. package/extensions/tlon/src/urbit/channel-ops.ts +164 -0
  1999. package/extensions/tlon/src/urbit/context.ts +47 -0
  2000. package/extensions/tlon/src/urbit/errors.ts +51 -0
  2001. package/extensions/tlon/src/urbit/fetch.ts +39 -0
  2002. package/extensions/tlon/src/urbit/send.ts +131 -0
  2003. package/extensions/tlon/src/urbit/sse-client.ts +431 -0
  2004. package/extensions/twitch/CHANGELOG.md +39 -0
  2005. package/extensions/twitch/README.md +89 -0
  2006. package/extensions/twitch/index.ts +20 -0
  2007. package/extensions/twitch/package.json +17 -0
  2008. package/extensions/twitch/remoteclaw.plugin.json +9 -0
  2009. package/extensions/twitch/src/access-control.ts +166 -0
  2010. package/extensions/twitch/src/actions.ts +174 -0
  2011. package/extensions/twitch/src/client-manager-registry.ts +115 -0
  2012. package/extensions/twitch/src/config-schema.ts +84 -0
  2013. package/extensions/twitch/src/config.ts +116 -0
  2014. package/extensions/twitch/src/monitor.ts +273 -0
  2015. package/extensions/twitch/src/onboarding.ts +417 -0
  2016. package/extensions/twitch/src/outbound.ts +187 -0
  2017. package/extensions/twitch/src/plugin.ts +274 -0
  2018. package/extensions/twitch/src/probe.ts +119 -0
  2019. package/extensions/twitch/src/resolver.ts +137 -0
  2020. package/extensions/twitch/src/runtime.ts +14 -0
  2021. package/extensions/twitch/src/send.ts +136 -0
  2022. package/extensions/twitch/src/status.ts +179 -0
  2023. package/extensions/twitch/src/test-fixtures.ts +30 -0
  2024. package/extensions/twitch/src/token.ts +94 -0
  2025. package/extensions/twitch/src/twitch-client.ts +277 -0
  2026. package/extensions/twitch/src/types.ts +141 -0
  2027. package/extensions/twitch/src/utils/markdown.ts +98 -0
  2028. package/extensions/twitch/src/utils/twitch.ts +80 -0
  2029. package/extensions/voice-call/CHANGELOG.md +49 -0
  2030. package/extensions/voice-call/README.md +181 -0
  2031. package/extensions/voice-call/index.ts +529 -0
  2032. package/extensions/voice-call/package.json +16 -0
  2033. package/extensions/voice-call/remoteclaw.plugin.json +559 -0
  2034. package/extensions/voice-call/src/allowlist.ts +19 -0
  2035. package/extensions/voice-call/src/cli.ts +380 -0
  2036. package/extensions/voice-call/src/config.ts +477 -0
  2037. package/extensions/voice-call/src/core-bridge.ts +170 -0
  2038. package/extensions/voice-call/src/manager/context.ts +41 -0
  2039. package/extensions/voice-call/src/manager/events.ts +242 -0
  2040. package/extensions/voice-call/src/manager/lookup.ts +35 -0
  2041. package/extensions/voice-call/src/manager/outbound.ts +380 -0
  2042. package/extensions/voice-call/src/manager/state.ts +48 -0
  2043. package/extensions/voice-call/src/manager/store.ts +94 -0
  2044. package/extensions/voice-call/src/manager/timers.ts +112 -0
  2045. package/extensions/voice-call/src/manager/twiml.ts +9 -0
  2046. package/extensions/voice-call/src/manager.ts +209 -0
  2047. package/extensions/voice-call/src/media-stream.ts +527 -0
  2048. package/extensions/voice-call/src/providers/base.ts +67 -0
  2049. package/extensions/voice-call/src/providers/index.ts +10 -0
  2050. package/extensions/voice-call/src/providers/mock.ts +165 -0
  2051. package/extensions/voice-call/src/providers/plivo.ts +560 -0
  2052. package/extensions/voice-call/src/providers/stt-openai-realtime.ts +311 -0
  2053. package/extensions/voice-call/src/providers/telnyx.ts +318 -0
  2054. package/extensions/voice-call/src/providers/tts-openai.ts +259 -0
  2055. package/extensions/voice-call/src/providers/twilio/api.ts +42 -0
  2056. package/extensions/voice-call/src/providers/twilio/webhook.ts +33 -0
  2057. package/extensions/voice-call/src/providers/twilio.ts +688 -0
  2058. package/extensions/voice-call/src/response-generator.ts +174 -0
  2059. package/extensions/voice-call/src/runtime.ts +217 -0
  2060. package/extensions/voice-call/src/telephony-audio.ts +90 -0
  2061. package/extensions/voice-call/src/telephony-tts.ts +106 -0
  2062. package/extensions/voice-call/src/tunnel.ts +314 -0
  2063. package/extensions/voice-call/src/types.ts +280 -0
  2064. package/extensions/voice-call/src/utils.ts +14 -0
  2065. package/extensions/voice-call/src/voice-mapping.ts +67 -0
  2066. package/extensions/voice-call/src/webhook-security.ts +880 -0
  2067. package/extensions/voice-call/src/webhook.ts +556 -0
  2068. package/extensions/whatsapp/index.ts +17 -0
  2069. package/extensions/whatsapp/package.json +12 -0
  2070. package/extensions/whatsapp/remoteclaw.plugin.json +9 -0
  2071. package/extensions/whatsapp/src/channel.ts +459 -0
  2072. package/extensions/whatsapp/src/runtime.ts +14 -0
  2073. package/extensions/zalo/CHANGELOG.md +29 -0
  2074. package/extensions/zalo/README.md +50 -0
  2075. package/extensions/zalo/index.ts +19 -0
  2076. package/extensions/zalo/package.json +32 -0
  2077. package/extensions/zalo/remoteclaw.plugin.json +9 -0
  2078. package/extensions/zalo/src/accounts.ts +82 -0
  2079. package/extensions/zalo/src/actions.ts +56 -0
  2080. package/extensions/zalo/src/api.ts +208 -0
  2081. package/extensions/zalo/src/channel.ts +398 -0
  2082. package/extensions/zalo/src/config-schema.ts +27 -0
  2083. package/extensions/zalo/src/group-access.ts +48 -0
  2084. package/extensions/zalo/src/monitor.ts +675 -0
  2085. package/extensions/zalo/src/monitor.webhook.ts +219 -0
  2086. package/extensions/zalo/src/onboarding.ts +398 -0
  2087. package/extensions/zalo/src/probe.ts +45 -0
  2088. package/extensions/zalo/src/proxy.ts +24 -0
  2089. package/extensions/zalo/src/runtime.ts +14 -0
  2090. package/extensions/zalo/src/send.ts +124 -0
  2091. package/extensions/zalo/src/status-issues.ts +53 -0
  2092. package/extensions/zalo/src/token.ts +62 -0
  2093. package/extensions/zalo/src/types.ts +48 -0
  2094. package/extensions/zalouser/CHANGELOG.md +31 -0
  2095. package/extensions/zalouser/README.md +225 -0
  2096. package/extensions/zalouser/index.ts +31 -0
  2097. package/extensions/zalouser/package.json +32 -0
  2098. package/extensions/zalouser/remoteclaw.plugin.json +9 -0
  2099. package/extensions/zalouser/src/accounts.ts +138 -0
  2100. package/extensions/zalouser/src/channel.ts +652 -0
  2101. package/extensions/zalouser/src/config-schema.ts +28 -0
  2102. package/extensions/zalouser/src/monitor.ts +619 -0
  2103. package/extensions/zalouser/src/onboarding.ts +428 -0
  2104. package/extensions/zalouser/src/probe.ts +27 -0
  2105. package/extensions/zalouser/src/runtime.ts +14 -0
  2106. package/extensions/zalouser/src/send.ts +141 -0
  2107. package/extensions/zalouser/src/status-issues.ts +89 -0
  2108. package/extensions/zalouser/src/tool.ts +166 -0
  2109. package/extensions/zalouser/src/types.ts +105 -0
  2110. package/extensions/zalouser/src/zca.ts +198 -0
  2111. package/package.json +250 -15
  2112. package/remoteclaw.mjs +56 -0
  2113. package/index.js +0 -4
@@ -0,0 +1,4839 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
+ import { Kt as resolveStateDir, _ as defaultRuntime, k as normalizeChannelId, o as createSubsystemLogger } from "./entry.js";
3
+ import { i as loadConfig, q as DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH } from "./config-qAZfcdDM.js";
4
+ import { C as parseAgentSessionKey, S as isSubagentSessionKey, b as isAcpSessionKey, c as normalizeMainKey, h as normalizeAccountId, l as resolveAgentIdFromSessionKey, y as getSubagentDepth } from "./session-key-BF-9YzxC.js";
5
+ import { d as resolveDefaultAgentId, f as resolveSessionAgentId } from "./agent-scope-FzE2oRm0.js";
6
+ import { g as parseDurationMs } from "./zod-schema-7uqrpeBz.js";
7
+ import { a as isInternalMessageChannel, c as normalizeMessageChannel, n as isDeliverableMessageChannel, t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-tuc9CdEw.js";
8
+ import { Y as resolveMainSessionKey, b as mergeDeliveryContext, l as loadSessionStore, x as normalizeDeliveryContext, y as deliveryContextFromSession } from "./sessions-Dg3febTj.js";
9
+ import { r as normalizeChannelId$1, t as getChannelPlugin } from "./plugins-Ca4Ybd3t.js";
10
+ import { m as resolveStorePath } from "./chat-envelope-AJFUAuBM.js";
11
+ import { n as callGateway } from "./call-Wjjo7gwP.js";
12
+ import { r as CommandLane, s as onAgentEvent, t as AGENT_LANE_NESTED } from "./lanes-1CBKdsiR.js";
13
+ import { a as resolveEffectiveMessagesConfig, n as resolveResponsePrefixTemplate } from "./response-prefix-template-xsasdq1T.js";
14
+ import { s as sanitizeUserFacingText } from "./agent-helpers-Bs2nBXeI.js";
15
+ import { r as isSilentReplyText, t as SILENT_REPLY_TOKEN } from "./tokens-Dw7ZdYwT.js";
16
+ import { t as getGlobalHookRunner, u as shouldSuppressReasoningPayload } from "./hook-runner-global-nAi_RVmo.js";
17
+ import { n as saveJsonFile, t as loadJsonFile } from "./json-file-DwRAfAAy.js";
18
+ import os from "node:os";
19
+ import path from "node:path";
20
+ import fs from "node:fs";
21
+ import JSON5 from "json5";
22
+ import crypto from "node:crypto";
23
+
24
+ //#region src/utils/queue-helpers.ts
25
+ function clearQueueSummaryState(state) {
26
+ state.droppedCount = 0;
27
+ state.summaryLines = [];
28
+ }
29
+ function previewQueueSummaryPrompt(params) {
30
+ return buildQueueSummaryPrompt({
31
+ state: {
32
+ dropPolicy: params.state.dropPolicy,
33
+ droppedCount: params.state.droppedCount,
34
+ summaryLines: [...params.state.summaryLines]
35
+ },
36
+ noun: params.noun,
37
+ title: params.title
38
+ });
39
+ }
40
+ function applyQueueRuntimeSettings(params) {
41
+ params.target.mode = params.settings.mode;
42
+ params.target.debounceMs = typeof params.settings.debounceMs === "number" ? Math.max(0, params.settings.debounceMs) : params.target.debounceMs;
43
+ params.target.cap = typeof params.settings.cap === "number" && params.settings.cap > 0 ? Math.floor(params.settings.cap) : params.target.cap;
44
+ params.target.dropPolicy = params.settings.dropPolicy ?? params.target.dropPolicy;
45
+ }
46
+ function elideQueueText(text, limit = 140) {
47
+ if (text.length <= limit) return text;
48
+ return `${text.slice(0, Math.max(0, limit - 1)).trimEnd()}…`;
49
+ }
50
+ function buildQueueSummaryLine(text, limit = 160) {
51
+ return elideQueueText(text.replace(/\s+/g, " ").trim(), limit);
52
+ }
53
+ function shouldSkipQueueItem(params) {
54
+ if (!params.dedupe) return false;
55
+ return params.dedupe(params.item, params.items);
56
+ }
57
+ function applyQueueDropPolicy(params) {
58
+ const cap = params.queue.cap;
59
+ if (cap <= 0 || params.queue.items.length < cap) return true;
60
+ if (params.queue.dropPolicy === "new") return false;
61
+ const dropCount = params.queue.items.length - cap + 1;
62
+ const dropped = params.queue.items.splice(0, dropCount);
63
+ if (params.queue.dropPolicy === "summarize") {
64
+ for (const item of dropped) {
65
+ params.queue.droppedCount += 1;
66
+ params.queue.summaryLines.push(buildQueueSummaryLine(params.summarize(item)));
67
+ }
68
+ const limit = Math.max(0, params.summaryLimit ?? cap);
69
+ while (params.queue.summaryLines.length > limit) params.queue.summaryLines.shift();
70
+ }
71
+ return true;
72
+ }
73
+ function waitForQueueDebounce(queue) {
74
+ if (process.env.REMOTECLAW_TEST_FAST === "1") return Promise.resolve();
75
+ const debounceMs = Math.max(0, queue.debounceMs);
76
+ if (debounceMs <= 0) return Promise.resolve();
77
+ return new Promise((resolve) => {
78
+ const check = () => {
79
+ const since = Date.now() - queue.lastEnqueuedAt;
80
+ if (since >= debounceMs) {
81
+ resolve();
82
+ return;
83
+ }
84
+ setTimeout(check, debounceMs - since);
85
+ };
86
+ check();
87
+ });
88
+ }
89
+ function beginQueueDrain(map, key) {
90
+ const queue = map.get(key);
91
+ if (!queue || queue.draining) return;
92
+ queue.draining = true;
93
+ return queue;
94
+ }
95
+ async function drainNextQueueItem(items, run) {
96
+ const next = items[0];
97
+ if (!next) return false;
98
+ await run(next);
99
+ items.shift();
100
+ return true;
101
+ }
102
+ async function drainCollectItemIfNeeded(params) {
103
+ if (!params.forceIndividualCollect && !params.isCrossChannel) return "skipped";
104
+ if (params.isCrossChannel) params.setForceIndividualCollect?.(true);
105
+ return await drainNextQueueItem(params.items, params.run) ? "drained" : "empty";
106
+ }
107
+ async function drainCollectQueueStep(params) {
108
+ return await drainCollectItemIfNeeded({
109
+ forceIndividualCollect: params.collectState.forceIndividualCollect,
110
+ isCrossChannel: params.isCrossChannel,
111
+ setForceIndividualCollect: (next) => {
112
+ params.collectState.forceIndividualCollect = next;
113
+ },
114
+ items: params.items,
115
+ run: params.run
116
+ });
117
+ }
118
+ function buildQueueSummaryPrompt(params) {
119
+ if (params.state.dropPolicy !== "summarize" || params.state.droppedCount <= 0) return;
120
+ const noun = params.noun;
121
+ const lines = [params.title ?? `[Queue overflow] Dropped ${params.state.droppedCount} ${noun}${params.state.droppedCount === 1 ? "" : "s"} due to cap.`];
122
+ if (params.state.summaryLines.length > 0) {
123
+ lines.push("Summary:");
124
+ for (const line of params.state.summaryLines) lines.push(`- ${line}`);
125
+ }
126
+ clearQueueSummaryState(params.state);
127
+ return lines.join("\n");
128
+ }
129
+ function buildCollectPrompt(params) {
130
+ const blocks = [params.title];
131
+ if (params.summary) blocks.push(params.summary);
132
+ params.items.forEach((item, idx) => {
133
+ blocks.push(params.renderItem(item, idx));
134
+ });
135
+ return blocks.join("\n\n");
136
+ }
137
+ function hasCrossChannelItems(items, resolveKey) {
138
+ const keys = /* @__PURE__ */ new Set();
139
+ let hasUnkeyed = false;
140
+ for (const item of items) {
141
+ const resolved = resolveKey(item);
142
+ if (resolved.cross) return true;
143
+ if (!resolved.key) {
144
+ hasUnkeyed = true;
145
+ continue;
146
+ }
147
+ keys.add(resolved.key);
148
+ }
149
+ if (keys.size === 0) return false;
150
+ if (hasUnkeyed) return true;
151
+ return keys.size > 1;
152
+ }
153
+
154
+ //#endregion
155
+ //#region src/auto-reply/reply/directive-parsing.ts
156
+ function skipDirectiveArgPrefix(raw) {
157
+ let i = 0;
158
+ const len = raw.length;
159
+ while (i < len && /\s/.test(raw[i])) i += 1;
160
+ if (raw[i] === ":") {
161
+ i += 1;
162
+ while (i < len && /\s/.test(raw[i])) i += 1;
163
+ }
164
+ return i;
165
+ }
166
+ function takeDirectiveToken(raw, startIndex) {
167
+ let i = startIndex;
168
+ const len = raw.length;
169
+ while (i < len && /\s/.test(raw[i])) i += 1;
170
+ if (i >= len) return {
171
+ token: null,
172
+ nextIndex: i
173
+ };
174
+ const start = i;
175
+ while (i < len && !/\s/.test(raw[i])) i += 1;
176
+ if (start === i) return {
177
+ token: null,
178
+ nextIndex: i
179
+ };
180
+ const token = raw.slice(start, i);
181
+ while (i < len && /\s/.test(raw[i])) i += 1;
182
+ return {
183
+ token,
184
+ nextIndex: i
185
+ };
186
+ }
187
+
188
+ //#endregion
189
+ //#region src/auto-reply/reply/queue/normalize.ts
190
+ function normalizeQueueMode(raw) {
191
+ if (!raw) return;
192
+ const cleaned = raw.trim().toLowerCase();
193
+ if (cleaned === "queue" || cleaned === "queued") return "steer";
194
+ if (cleaned === "interrupt" || cleaned === "interrupts" || cleaned === "abort") return "interrupt";
195
+ if (cleaned === "steer" || cleaned === "steering") return "steer";
196
+ if (cleaned === "followup" || cleaned === "follow-ups" || cleaned === "followups") return "followup";
197
+ if (cleaned === "collect" || cleaned === "coalesce") return "collect";
198
+ if (cleaned === "steer+backlog" || cleaned === "steer-backlog" || cleaned === "steer_backlog") return "steer-backlog";
199
+ }
200
+ function normalizeQueueDropPolicy(raw) {
201
+ if (!raw) return;
202
+ const cleaned = raw.trim().toLowerCase();
203
+ if (cleaned === "old" || cleaned === "oldest") return "old";
204
+ if (cleaned === "new" || cleaned === "newest") return "new";
205
+ if (cleaned === "summarize" || cleaned === "summary") return "summarize";
206
+ }
207
+
208
+ //#endregion
209
+ //#region src/auto-reply/reply/queue/directive.ts
210
+ function parseQueueDebounce(raw) {
211
+ if (!raw) return;
212
+ try {
213
+ const parsed = parseDurationMs(raw.trim(), { defaultUnit: "ms" });
214
+ if (!parsed || parsed < 0) return;
215
+ return Math.round(parsed);
216
+ } catch {
217
+ return;
218
+ }
219
+ }
220
+ function parseQueueCap(raw) {
221
+ if (!raw) return;
222
+ const num = Number(raw);
223
+ if (!Number.isFinite(num)) return;
224
+ const cap = Math.floor(num);
225
+ if (cap < 1) return;
226
+ return cap;
227
+ }
228
+ function parseQueueDirectiveArgs(raw) {
229
+ const len = raw.length;
230
+ let i = skipDirectiveArgPrefix(raw);
231
+ let consumed = i;
232
+ let queueMode;
233
+ let queueReset = false;
234
+ let rawMode;
235
+ let debounceMs;
236
+ let cap;
237
+ let dropPolicy;
238
+ let rawDebounce;
239
+ let rawCap;
240
+ let rawDrop;
241
+ let hasOptions = false;
242
+ const takeToken = () => {
243
+ const res = takeDirectiveToken(raw, i);
244
+ i = res.nextIndex;
245
+ return res.token;
246
+ };
247
+ while (i < len) {
248
+ const token = takeToken();
249
+ if (!token) break;
250
+ const lowered = token.trim().toLowerCase();
251
+ if (lowered === "default" || lowered === "reset" || lowered === "clear") {
252
+ queueReset = true;
253
+ consumed = i;
254
+ break;
255
+ }
256
+ if (lowered.startsWith("debounce:") || lowered.startsWith("debounce=")) {
257
+ rawDebounce = token.split(/[:=]/)[1] ?? "";
258
+ debounceMs = parseQueueDebounce(rawDebounce);
259
+ hasOptions = true;
260
+ consumed = i;
261
+ continue;
262
+ }
263
+ if (lowered.startsWith("cap:") || lowered.startsWith("cap=")) {
264
+ rawCap = token.split(/[:=]/)[1] ?? "";
265
+ cap = parseQueueCap(rawCap);
266
+ hasOptions = true;
267
+ consumed = i;
268
+ continue;
269
+ }
270
+ if (lowered.startsWith("drop:") || lowered.startsWith("drop=")) {
271
+ rawDrop = token.split(/[:=]/)[1] ?? "";
272
+ dropPolicy = normalizeQueueDropPolicy(rawDrop);
273
+ hasOptions = true;
274
+ consumed = i;
275
+ continue;
276
+ }
277
+ const mode = normalizeQueueMode(token);
278
+ if (mode) {
279
+ queueMode = mode;
280
+ rawMode = token;
281
+ consumed = i;
282
+ continue;
283
+ }
284
+ break;
285
+ }
286
+ return {
287
+ consumed,
288
+ queueMode,
289
+ queueReset,
290
+ rawMode,
291
+ debounceMs,
292
+ cap,
293
+ dropPolicy,
294
+ rawDebounce,
295
+ rawCap,
296
+ rawDrop,
297
+ hasOptions
298
+ };
299
+ }
300
+ function extractQueueDirective(body) {
301
+ if (!body) return {
302
+ cleaned: "",
303
+ hasDirective: false,
304
+ queueReset: false,
305
+ hasOptions: false
306
+ };
307
+ const match = /(?:^|\s)\/queue(?=$|\s|:)/i.exec(body);
308
+ if (!match) return {
309
+ cleaned: body.trim(),
310
+ hasDirective: false,
311
+ queueReset: false,
312
+ hasOptions: false
313
+ };
314
+ const start = match.index + match[0].indexOf("/queue");
315
+ const argsStart = start + 6;
316
+ const parsed = parseQueueDirectiveArgs(body.slice(argsStart));
317
+ return {
318
+ cleaned: `${body.slice(0, start)} ${body.slice(argsStart + parsed.consumed)}`.replace(/\s+/g, " ").trim(),
319
+ queueMode: parsed.queueMode,
320
+ queueReset: parsed.queueReset,
321
+ rawMode: parsed.rawMode,
322
+ debounceMs: parsed.debounceMs,
323
+ cap: parsed.cap,
324
+ dropPolicy: parsed.dropPolicy,
325
+ rawDebounce: parsed.rawDebounce,
326
+ rawCap: parsed.rawCap,
327
+ rawDrop: parsed.rawDrop,
328
+ hasDirective: true,
329
+ hasOptions: parsed.hasOptions
330
+ };
331
+ }
332
+
333
+ //#endregion
334
+ //#region src/infra/diagnostic-events.ts
335
+ function getDiagnosticEventsState() {
336
+ const globalStore = globalThis;
337
+ if (!globalStore.__remoteclawDiagnosticEventsState) globalStore.__remoteclawDiagnosticEventsState = {
338
+ seq: 0,
339
+ listeners: /* @__PURE__ */ new Set(),
340
+ dispatchDepth: 0
341
+ };
342
+ return globalStore.__remoteclawDiagnosticEventsState;
343
+ }
344
+ function isDiagnosticsEnabled(config) {
345
+ return config?.diagnostics?.enabled === true;
346
+ }
347
+ function emitDiagnosticEvent(event) {
348
+ const state = getDiagnosticEventsState();
349
+ if (state.dispatchDepth > 100) {
350
+ console.error(`[diagnostic-events] recursion guard tripped at depth=${state.dispatchDepth}, dropping type=${event.type}`);
351
+ return;
352
+ }
353
+ const enriched = {
354
+ ...event,
355
+ seq: state.seq += 1,
356
+ ts: Date.now()
357
+ };
358
+ state.dispatchDepth += 1;
359
+ for (const listener of state.listeners) try {
360
+ listener(enriched);
361
+ } catch (err) {
362
+ const errorMessage = err instanceof Error ? err.stack ?? err.message : typeof err === "string" ? err : String(err);
363
+ console.error(`[diagnostic-events] listener error type=${enriched.type} seq=${enriched.seq}: ${errorMessage}`);
364
+ }
365
+ state.dispatchDepth -= 1;
366
+ }
367
+
368
+ //#endregion
369
+ //#region src/logging/diagnostic-session-state.ts
370
+ const diagnosticSessionStates = /* @__PURE__ */ new Map();
371
+ const SESSION_STATE_TTL_MS = 1800 * 1e3;
372
+ const SESSION_STATE_PRUNE_INTERVAL_MS = 60 * 1e3;
373
+ const SESSION_STATE_MAX_ENTRIES = 2e3;
374
+ let lastSessionPruneAt = 0;
375
+ function pruneDiagnosticSessionStates(now = Date.now(), force = false) {
376
+ const shouldPruneForSize = diagnosticSessionStates.size > SESSION_STATE_MAX_ENTRIES;
377
+ if (!force && !shouldPruneForSize && now - lastSessionPruneAt < SESSION_STATE_PRUNE_INTERVAL_MS) return;
378
+ lastSessionPruneAt = now;
379
+ for (const [key, state] of diagnosticSessionStates.entries()) {
380
+ const ageMs = now - state.lastActivity;
381
+ if (state.state === "idle" && state.queueDepth <= 0 && ageMs > SESSION_STATE_TTL_MS) diagnosticSessionStates.delete(key);
382
+ }
383
+ if (diagnosticSessionStates.size <= SESSION_STATE_MAX_ENTRIES) return;
384
+ const excess = diagnosticSessionStates.size - SESSION_STATE_MAX_ENTRIES;
385
+ const ordered = Array.from(diagnosticSessionStates.entries()).toSorted((a, b) => a[1].lastActivity - b[1].lastActivity);
386
+ for (let i = 0; i < excess; i += 1) {
387
+ const key = ordered[i]?.[0];
388
+ if (!key) break;
389
+ diagnosticSessionStates.delete(key);
390
+ }
391
+ }
392
+ function resolveSessionKey({ sessionKey, sessionId }) {
393
+ return sessionKey ?? sessionId ?? "unknown";
394
+ }
395
+ function findStateBySessionId(sessionId) {
396
+ for (const state of diagnosticSessionStates.values()) if (state.sessionId === sessionId) return state;
397
+ }
398
+ function getDiagnosticSessionState(ref) {
399
+ pruneDiagnosticSessionStates();
400
+ const key = resolveSessionKey(ref);
401
+ const existing = diagnosticSessionStates.get(key) ?? (ref.sessionId && findStateBySessionId(ref.sessionId));
402
+ if (existing) {
403
+ if (ref.sessionId) existing.sessionId = ref.sessionId;
404
+ if (ref.sessionKey) existing.sessionKey = ref.sessionKey;
405
+ return existing;
406
+ }
407
+ const created = {
408
+ sessionId: ref.sessionId,
409
+ sessionKey: ref.sessionKey,
410
+ lastActivity: Date.now(),
411
+ state: "idle",
412
+ queueDepth: 0
413
+ };
414
+ diagnosticSessionStates.set(key, created);
415
+ pruneDiagnosticSessionStates(Date.now(), true);
416
+ return created;
417
+ }
418
+
419
+ //#endregion
420
+ //#region src/logging/diagnostic.ts
421
+ const diag = createSubsystemLogger("diagnostic");
422
+ const webhookStats = {
423
+ received: 0,
424
+ processed: 0,
425
+ errors: 0,
426
+ lastReceived: 0
427
+ };
428
+ let lastActivityAt = 0;
429
+ function markActivity() {
430
+ lastActivityAt = Date.now();
431
+ }
432
+ function logWebhookReceived(params) {
433
+ webhookStats.received += 1;
434
+ webhookStats.lastReceived = Date.now();
435
+ if (diag.isEnabled("debug")) diag.debug(`webhook received: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} total=${webhookStats.received}`);
436
+ emitDiagnosticEvent({
437
+ type: "webhook.received",
438
+ channel: params.channel,
439
+ updateType: params.updateType,
440
+ chatId: params.chatId
441
+ });
442
+ markActivity();
443
+ }
444
+ function logWebhookProcessed(params) {
445
+ webhookStats.processed += 1;
446
+ if (diag.isEnabled("debug")) diag.debug(`webhook processed: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} duration=${params.durationMs ?? 0}ms processed=${webhookStats.processed}`);
447
+ emitDiagnosticEvent({
448
+ type: "webhook.processed",
449
+ channel: params.channel,
450
+ updateType: params.updateType,
451
+ chatId: params.chatId,
452
+ durationMs: params.durationMs
453
+ });
454
+ markActivity();
455
+ }
456
+ function logWebhookError(params) {
457
+ webhookStats.errors += 1;
458
+ diag.error(`webhook error: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} error="${params.error}" errors=${webhookStats.errors}`);
459
+ emitDiagnosticEvent({
460
+ type: "webhook.error",
461
+ channel: params.channel,
462
+ updateType: params.updateType,
463
+ chatId: params.chatId,
464
+ error: params.error
465
+ });
466
+ markActivity();
467
+ }
468
+ function logMessageQueued(params) {
469
+ const state = getDiagnosticSessionState(params);
470
+ state.queueDepth += 1;
471
+ state.lastActivity = Date.now();
472
+ if (diag.isEnabled("debug")) diag.debug(`message queued: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} source=${params.source} queueDepth=${state.queueDepth} sessionState=${state.state}`);
473
+ emitDiagnosticEvent({
474
+ type: "message.queued",
475
+ sessionId: state.sessionId,
476
+ sessionKey: state.sessionKey,
477
+ channel: params.channel,
478
+ source: params.source,
479
+ queueDepth: state.queueDepth
480
+ });
481
+ markActivity();
482
+ }
483
+ function logMessageProcessed(params) {
484
+ if (params.outcome === "error" ? diag.isEnabled("error") : diag.isEnabled("debug")) {
485
+ const payload = `message processed: channel=${params.channel} chatId=${params.chatId ?? "unknown"} messageId=${params.messageId ?? "unknown"} sessionId=${params.sessionId ?? "unknown"} sessionKey=${params.sessionKey ?? "unknown"} outcome=${params.outcome} duration=${params.durationMs ?? 0}ms${params.reason ? ` reason=${params.reason}` : ""}${params.error ? ` error="${params.error}"` : ""}`;
486
+ if (params.outcome === "error") diag.error(payload);
487
+ else diag.debug(payload);
488
+ }
489
+ emitDiagnosticEvent({
490
+ type: "message.processed",
491
+ channel: params.channel,
492
+ chatId: params.chatId,
493
+ messageId: params.messageId,
494
+ sessionId: params.sessionId,
495
+ sessionKey: params.sessionKey,
496
+ durationMs: params.durationMs,
497
+ outcome: params.outcome,
498
+ reason: params.reason,
499
+ error: params.error
500
+ });
501
+ markActivity();
502
+ }
503
+ function logSessionStateChange(params) {
504
+ const state = getDiagnosticSessionState(params);
505
+ const isProbeSession = state.sessionId?.startsWith("probe-") ?? false;
506
+ const prevState = state.state;
507
+ state.state = params.state;
508
+ state.lastActivity = Date.now();
509
+ if (params.state === "idle") state.queueDepth = Math.max(0, state.queueDepth - 1);
510
+ if (!isProbeSession && diag.isEnabled("debug")) diag.debug(`session state: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} prev=${prevState} new=${params.state} reason="${params.reason ?? ""}" queueDepth=${state.queueDepth}`);
511
+ emitDiagnosticEvent({
512
+ type: "session.state",
513
+ sessionId: state.sessionId,
514
+ sessionKey: state.sessionKey,
515
+ prevState,
516
+ state: params.state,
517
+ reason: params.reason,
518
+ queueDepth: state.queueDepth
519
+ });
520
+ markActivity();
521
+ }
522
+ function logSessionStuck(params) {
523
+ const state = getDiagnosticSessionState(params);
524
+ diag.warn(`stuck session: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} state=${params.state} age=${Math.round(params.ageMs / 1e3)}s queueDepth=${state.queueDepth}`);
525
+ emitDiagnosticEvent({
526
+ type: "session.stuck",
527
+ sessionId: state.sessionId,
528
+ sessionKey: state.sessionKey,
529
+ state: params.state,
530
+ ageMs: params.ageMs,
531
+ queueDepth: state.queueDepth
532
+ });
533
+ markActivity();
534
+ }
535
+ function logLaneDequeue(lane, waitMs, queueSize) {
536
+ diag.debug(`lane dequeue: lane=${lane} waitMs=${waitMs} queueSize=${queueSize}`);
537
+ emitDiagnosticEvent({
538
+ type: "queue.lane.dequeue",
539
+ lane,
540
+ queueSize,
541
+ waitMs
542
+ });
543
+ markActivity();
544
+ }
545
+ let heartbeatInterval = null;
546
+ function startDiagnosticHeartbeat() {
547
+ if (heartbeatInterval) return;
548
+ heartbeatInterval = setInterval(() => {
549
+ const now = Date.now();
550
+ pruneDiagnosticSessionStates(now, true);
551
+ const activeCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "processing").length;
552
+ const waitingCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "waiting").length;
553
+ const totalQueued = Array.from(diagnosticSessionStates.values()).reduce((sum, s) => sum + s.queueDepth, 0);
554
+ if (!(lastActivityAt > 0 || webhookStats.received > 0 || activeCount > 0 || waitingCount > 0 || totalQueued > 0)) return;
555
+ if (now - lastActivityAt > 12e4 && activeCount === 0 && waitingCount === 0) return;
556
+ diag.debug(`heartbeat: webhooks=${webhookStats.received}/${webhookStats.processed}/${webhookStats.errors} active=${activeCount} waiting=${waitingCount} queued=${totalQueued}`);
557
+ emitDiagnosticEvent({
558
+ type: "diagnostic.heartbeat",
559
+ webhooks: {
560
+ received: webhookStats.received,
561
+ processed: webhookStats.processed,
562
+ errors: webhookStats.errors
563
+ },
564
+ active: activeCount,
565
+ waiting: waitingCount,
566
+ queued: totalQueued
567
+ });
568
+ for (const [, state] of diagnosticSessionStates) {
569
+ const ageMs = now - state.lastActivity;
570
+ if (state.state === "processing" && ageMs > 12e4) logSessionStuck({
571
+ sessionId: state.sessionId,
572
+ sessionKey: state.sessionKey,
573
+ state: state.state,
574
+ ageMs
575
+ });
576
+ }
577
+ }, 3e4);
578
+ heartbeatInterval.unref?.();
579
+ }
580
+ function stopDiagnosticHeartbeat() {
581
+ if (heartbeatInterval) {
582
+ clearInterval(heartbeatInterval);
583
+ heartbeatInterval = null;
584
+ }
585
+ }
586
+
587
+ //#endregion
588
+ //#region src/process/command-queue.ts
589
+ /**
590
+ * Dedicated error type thrown when a queued command is rejected because
591
+ * its lane was cleared. Callers that fire-and-forget enqueued tasks can
592
+ * catch (or ignore) this specific type to avoid unhandled-rejection noise.
593
+ */
594
+ var CommandLaneClearedError = class extends Error {
595
+ constructor(lane) {
596
+ super(lane ? `Command lane "${lane}" cleared` : "Command lane cleared");
597
+ this.name = "CommandLaneClearedError";
598
+ }
599
+ };
600
+ const lanes = /* @__PURE__ */ new Map();
601
+ let nextTaskId = 1;
602
+ function getLaneState(lane) {
603
+ const existing = lanes.get(lane);
604
+ if (existing) return existing;
605
+ const created = {
606
+ lane,
607
+ queue: [],
608
+ activeTaskIds: /* @__PURE__ */ new Set(),
609
+ maxConcurrent: 1,
610
+ draining: false,
611
+ generation: 0
612
+ };
613
+ lanes.set(lane, created);
614
+ return created;
615
+ }
616
+ function completeTask(state, taskId, taskGeneration) {
617
+ if (taskGeneration !== state.generation) return false;
618
+ state.activeTaskIds.delete(taskId);
619
+ return true;
620
+ }
621
+ function drainLane(lane) {
622
+ const state = getLaneState(lane);
623
+ if (state.draining) return;
624
+ state.draining = true;
625
+ const pump = () => {
626
+ while (state.activeTaskIds.size < state.maxConcurrent && state.queue.length > 0) {
627
+ const entry = state.queue.shift();
628
+ const waitedMs = Date.now() - entry.enqueuedAt;
629
+ if (waitedMs >= entry.warnAfterMs) {
630
+ entry.onWait?.(waitedMs, state.queue.length);
631
+ diag.warn(`lane wait exceeded: lane=${lane} waitedMs=${waitedMs} queueAhead=${state.queue.length}`);
632
+ }
633
+ logLaneDequeue(lane, waitedMs, state.queue.length);
634
+ const taskId = nextTaskId++;
635
+ const taskGeneration = state.generation;
636
+ state.activeTaskIds.add(taskId);
637
+ (async () => {
638
+ const startTime = Date.now();
639
+ try {
640
+ const result = await entry.task();
641
+ if (completeTask(state, taskId, taskGeneration)) {
642
+ diag.debug(`lane task done: lane=${lane} durationMs=${Date.now() - startTime} active=${state.activeTaskIds.size} queued=${state.queue.length}`);
643
+ pump();
644
+ }
645
+ entry.resolve(result);
646
+ } catch (err) {
647
+ const completedCurrentGeneration = completeTask(state, taskId, taskGeneration);
648
+ if (!(lane.startsWith("auth-probe:") || lane.startsWith("session:probe-"))) diag.error(`lane task error: lane=${lane} durationMs=${Date.now() - startTime} error="${String(err)}"`);
649
+ if (completedCurrentGeneration) pump();
650
+ entry.reject(err);
651
+ }
652
+ })();
653
+ }
654
+ state.draining = false;
655
+ };
656
+ pump();
657
+ }
658
+ function setCommandLaneConcurrency(lane, maxConcurrent) {
659
+ const cleaned = lane.trim() || CommandLane.Main;
660
+ const state = getLaneState(cleaned);
661
+ state.maxConcurrent = Math.max(1, Math.floor(maxConcurrent));
662
+ drainLane(cleaned);
663
+ }
664
+ function getQueueSize(lane = CommandLane.Main) {
665
+ const resolved = lane.trim() || CommandLane.Main;
666
+ const state = lanes.get(resolved);
667
+ if (!state) return 0;
668
+ return state.queue.length + state.activeTaskIds.size;
669
+ }
670
+ function getTotalQueueSize() {
671
+ let total = 0;
672
+ for (const s of lanes.values()) total += s.queue.length + s.activeTaskIds.size;
673
+ return total;
674
+ }
675
+ function clearCommandLane(lane = CommandLane.Main) {
676
+ const cleaned = lane.trim() || CommandLane.Main;
677
+ const state = lanes.get(cleaned);
678
+ if (!state) return 0;
679
+ const removed = state.queue.length;
680
+ const pending = state.queue.splice(0);
681
+ for (const entry of pending) entry.reject(new CommandLaneClearedError(cleaned));
682
+ return removed;
683
+ }
684
+ /**
685
+ * Reset all lane runtime state to idle. Used after SIGUSR1 in-process
686
+ * restarts where interrupted tasks' finally blocks may not run, leaving
687
+ * stale active task IDs that permanently block new work from draining.
688
+ *
689
+ * Bumps lane generation and clears execution counters so stale completions
690
+ * from old in-flight tasks are ignored. Queued entries are intentionally
691
+ * preserved — they represent pending user work that should still execute
692
+ * after restart.
693
+ *
694
+ * After resetting, drains any lanes that still have queued entries so
695
+ * preserved work is pumped immediately rather than waiting for a future
696
+ * `enqueueCommandInLane()` call (which may never come).
697
+ */
698
+ function resetAllLanes() {
699
+ const lanesToDrain = [];
700
+ for (const state of lanes.values()) {
701
+ state.generation += 1;
702
+ state.activeTaskIds.clear();
703
+ state.draining = false;
704
+ if (state.queue.length > 0) lanesToDrain.push(state.lane);
705
+ }
706
+ for (const lane of lanesToDrain) drainLane(lane);
707
+ }
708
+ /**
709
+ * Returns the total number of actively executing tasks across all lanes
710
+ * (excludes queued-but-not-started entries).
711
+ */
712
+ function getActiveTaskCount() {
713
+ let total = 0;
714
+ for (const s of lanes.values()) total += s.activeTaskIds.size;
715
+ return total;
716
+ }
717
+ /**
718
+ * Wait for all currently active tasks across all lanes to finish.
719
+ * Polls at a short interval; resolves when no tasks are active or
720
+ * when `timeoutMs` elapses (whichever comes first).
721
+ *
722
+ * New tasks enqueued after this call are ignored — only tasks that are
723
+ * already executing are waited on.
724
+ */
725
+ function waitForActiveTasks(timeoutMs) {
726
+ const POLL_INTERVAL_MS = 50;
727
+ const deadline = Date.now() + timeoutMs;
728
+ const activeAtStart = /* @__PURE__ */ new Set();
729
+ for (const state of lanes.values()) for (const taskId of state.activeTaskIds) activeAtStart.add(taskId);
730
+ return new Promise((resolve) => {
731
+ const check = () => {
732
+ if (activeAtStart.size === 0) {
733
+ resolve({ drained: true });
734
+ return;
735
+ }
736
+ let hasPending = false;
737
+ for (const state of lanes.values()) {
738
+ for (const taskId of state.activeTaskIds) if (activeAtStart.has(taskId)) {
739
+ hasPending = true;
740
+ break;
741
+ }
742
+ if (hasPending) break;
743
+ }
744
+ if (!hasPending) {
745
+ resolve({ drained: true });
746
+ return;
747
+ }
748
+ if (Date.now() >= deadline) {
749
+ resolve({ drained: false });
750
+ return;
751
+ }
752
+ setTimeout(check, POLL_INTERVAL_MS);
753
+ };
754
+ check();
755
+ });
756
+ }
757
+
758
+ //#endregion
759
+ //#region src/auto-reply/reply/queue/state.ts
760
+ const DEFAULT_QUEUE_DEBOUNCE_MS = 1e3;
761
+ const DEFAULT_QUEUE_CAP = 20;
762
+ const DEFAULT_QUEUE_DROP = "summarize";
763
+ const FOLLOWUP_QUEUES = /* @__PURE__ */ new Map();
764
+ function getExistingFollowupQueue(key) {
765
+ const cleaned = key.trim();
766
+ if (!cleaned) return;
767
+ return FOLLOWUP_QUEUES.get(cleaned);
768
+ }
769
+ function getFollowupQueue(key, settings) {
770
+ const existing = FOLLOWUP_QUEUES.get(key);
771
+ if (existing) {
772
+ applyQueueRuntimeSettings({
773
+ target: existing,
774
+ settings
775
+ });
776
+ return existing;
777
+ }
778
+ const created = {
779
+ items: [],
780
+ draining: false,
781
+ lastEnqueuedAt: 0,
782
+ mode: settings.mode,
783
+ debounceMs: typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : DEFAULT_QUEUE_DEBOUNCE_MS,
784
+ cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : DEFAULT_QUEUE_CAP,
785
+ dropPolicy: settings.dropPolicy ?? DEFAULT_QUEUE_DROP,
786
+ droppedCount: 0,
787
+ summaryLines: []
788
+ };
789
+ applyQueueRuntimeSettings({
790
+ target: created,
791
+ settings
792
+ });
793
+ FOLLOWUP_QUEUES.set(key, created);
794
+ return created;
795
+ }
796
+ function clearFollowupQueue(key) {
797
+ const cleaned = key.trim();
798
+ const queue = getExistingFollowupQueue(cleaned);
799
+ if (!queue) return 0;
800
+ const cleared = queue.items.length + queue.droppedCount;
801
+ queue.items.length = 0;
802
+ queue.droppedCount = 0;
803
+ queue.summaryLines = [];
804
+ queue.lastRun = void 0;
805
+ queue.lastEnqueuedAt = 0;
806
+ FOLLOWUP_QUEUES.delete(cleaned);
807
+ return cleared;
808
+ }
809
+
810
+ //#endregion
811
+ //#region src/auto-reply/reply/queue/cleanup.ts
812
+ function clearSessionQueues(keys) {
813
+ const seen = /* @__PURE__ */ new Set();
814
+ let followupCleared = 0;
815
+ let laneCleared = 0;
816
+ const clearedKeys = [];
817
+ for (const key of keys) {
818
+ const cleaned = key?.trim();
819
+ if (!cleaned || seen.has(cleaned)) continue;
820
+ seen.add(cleaned);
821
+ clearedKeys.push(cleaned);
822
+ followupCleared += clearFollowupQueue(cleaned);
823
+ laneCleared += clearCommandLane("default");
824
+ }
825
+ return {
826
+ followupCleared,
827
+ laneCleared,
828
+ keys: clearedKeys
829
+ };
830
+ }
831
+
832
+ //#endregion
833
+ //#region src/line/flex-templates/common.ts
834
+ function attachFooterText(bubble, footer) {
835
+ bubble.footer = {
836
+ type: "box",
837
+ layout: "vertical",
838
+ contents: [{
839
+ type: "text",
840
+ text: footer,
841
+ size: "xs",
842
+ color: "#AAAAAA",
843
+ wrap: true,
844
+ align: "center"
845
+ }],
846
+ paddingAll: "lg",
847
+ backgroundColor: "#FAFAFA"
848
+ };
849
+ }
850
+
851
+ //#endregion
852
+ //#region src/line/flex-templates/schedule-cards.ts
853
+ function buildTitleSubtitleHeader(params) {
854
+ const { title, subtitle } = params;
855
+ const headerContents = [{
856
+ type: "text",
857
+ text: title,
858
+ weight: "bold",
859
+ size: "xl",
860
+ color: "#111111",
861
+ wrap: true
862
+ }];
863
+ if (subtitle) headerContents.push({
864
+ type: "text",
865
+ text: subtitle,
866
+ size: "sm",
867
+ color: "#888888",
868
+ margin: "sm",
869
+ wrap: true
870
+ });
871
+ return headerContents;
872
+ }
873
+ function buildCardHeaderSections(headerContents) {
874
+ return [{
875
+ type: "box",
876
+ layout: "vertical",
877
+ contents: headerContents,
878
+ paddingBottom: "lg"
879
+ }, {
880
+ type: "separator",
881
+ color: "#EEEEEE"
882
+ }];
883
+ }
884
+ function createMegaBubbleWithFooter(params) {
885
+ const bubble = {
886
+ type: "bubble",
887
+ size: "mega",
888
+ body: {
889
+ type: "box",
890
+ layout: "vertical",
891
+ contents: params.bodyContents,
892
+ paddingAll: "xl",
893
+ backgroundColor: "#FFFFFF"
894
+ }
895
+ };
896
+ if (params.footer) attachFooterText(bubble, params.footer);
897
+ return bubble;
898
+ }
899
+ /**
900
+ * Create a receipt/summary card (for orders, transactions, data tables)
901
+ *
902
+ * Editorial design: Clean table layout with alternating row backgrounds,
903
+ * prominent total section, and clear visual hierarchy.
904
+ */
905
+ function createReceiptCard(params) {
906
+ const { title, subtitle, items, total, footer } = params;
907
+ const itemRows = items.slice(0, 12).map((item, index) => ({
908
+ type: "box",
909
+ layout: "horizontal",
910
+ contents: [{
911
+ type: "text",
912
+ text: item.name,
913
+ size: "sm",
914
+ color: item.highlight ? "#111111" : "#666666",
915
+ weight: item.highlight ? "bold" : "regular",
916
+ flex: 3,
917
+ wrap: true
918
+ }, {
919
+ type: "text",
920
+ text: item.value,
921
+ size: "sm",
922
+ color: item.highlight ? "#06C755" : "#333333",
923
+ weight: item.highlight ? "bold" : "regular",
924
+ flex: 2,
925
+ align: "end",
926
+ wrap: true
927
+ }],
928
+ paddingAll: "md",
929
+ backgroundColor: index % 2 === 0 ? "#FFFFFF" : "#FAFAFA"
930
+ }));
931
+ const bodyContents = [...buildCardHeaderSections(buildTitleSubtitleHeader({
932
+ title,
933
+ subtitle
934
+ })), {
935
+ type: "box",
936
+ layout: "vertical",
937
+ contents: itemRows,
938
+ margin: "md",
939
+ cornerRadius: "md",
940
+ borderWidth: "light",
941
+ borderColor: "#EEEEEE"
942
+ }];
943
+ if (total) bodyContents.push({
944
+ type: "box",
945
+ layout: "horizontal",
946
+ contents: [{
947
+ type: "text",
948
+ text: total.label,
949
+ size: "lg",
950
+ weight: "bold",
951
+ color: "#111111",
952
+ flex: 2
953
+ }, {
954
+ type: "text",
955
+ text: total.value,
956
+ size: "xl",
957
+ weight: "bold",
958
+ color: "#06C755",
959
+ flex: 2,
960
+ align: "end"
961
+ }],
962
+ margin: "xl",
963
+ paddingAll: "lg",
964
+ backgroundColor: "#F0FDF4",
965
+ cornerRadius: "lg"
966
+ });
967
+ return createMegaBubbleWithFooter({
968
+ bodyContents,
969
+ footer
970
+ });
971
+ }
972
+ /**
973
+ * Create a calendar event card (for meetings, appointments, reminders)
974
+ *
975
+ * Editorial design: Date as hero, strong typographic hierarchy,
976
+ * color-blocked zones, full text wrapping for readability.
977
+ */
978
+ function createEventCard(params) {
979
+ const { title, date, time, location, description, calendar, isAllDay, action } = params;
980
+ const dateBlock = {
981
+ type: "box",
982
+ layout: "vertical",
983
+ contents: [{
984
+ type: "text",
985
+ text: date.toUpperCase(),
986
+ size: "sm",
987
+ weight: "bold",
988
+ color: "#06C755",
989
+ wrap: true
990
+ }, {
991
+ type: "text",
992
+ text: isAllDay ? "ALL DAY" : time ?? "",
993
+ size: "xxl",
994
+ weight: "bold",
995
+ color: "#111111",
996
+ wrap: true,
997
+ margin: "xs"
998
+ }],
999
+ paddingBottom: "lg",
1000
+ borderWidth: "none"
1001
+ };
1002
+ if (!time && !isAllDay) dateBlock.contents = [{
1003
+ type: "text",
1004
+ text: date,
1005
+ size: "xl",
1006
+ weight: "bold",
1007
+ color: "#111111",
1008
+ wrap: true
1009
+ }];
1010
+ const bodyContents = [dateBlock, {
1011
+ type: "box",
1012
+ layout: "horizontal",
1013
+ contents: [{
1014
+ type: "box",
1015
+ layout: "vertical",
1016
+ contents: [],
1017
+ width: "4px",
1018
+ backgroundColor: "#06C755",
1019
+ cornerRadius: "2px"
1020
+ }, {
1021
+ type: "box",
1022
+ layout: "vertical",
1023
+ contents: [{
1024
+ type: "text",
1025
+ text: title,
1026
+ size: "lg",
1027
+ weight: "bold",
1028
+ color: "#1a1a1a",
1029
+ wrap: true
1030
+ }, ...calendar ? [{
1031
+ type: "text",
1032
+ text: calendar,
1033
+ size: "xs",
1034
+ color: "#888888",
1035
+ margin: "sm",
1036
+ wrap: true
1037
+ }] : []],
1038
+ flex: 1,
1039
+ paddingStart: "lg"
1040
+ }],
1041
+ paddingTop: "lg",
1042
+ paddingBottom: "lg",
1043
+ borderWidth: "light",
1044
+ borderColor: "#EEEEEE"
1045
+ }];
1046
+ if (location || description) {
1047
+ const detailItems = [];
1048
+ if (location) detailItems.push({
1049
+ type: "box",
1050
+ layout: "horizontal",
1051
+ contents: [{
1052
+ type: "text",
1053
+ text: "📍",
1054
+ size: "sm",
1055
+ flex: 0
1056
+ }, {
1057
+ type: "text",
1058
+ text: location,
1059
+ size: "sm",
1060
+ color: "#444444",
1061
+ margin: "md",
1062
+ flex: 1,
1063
+ wrap: true
1064
+ }],
1065
+ alignItems: "flex-start"
1066
+ });
1067
+ if (description) detailItems.push({
1068
+ type: "text",
1069
+ text: description,
1070
+ size: "sm",
1071
+ color: "#666666",
1072
+ wrap: true,
1073
+ margin: location ? "lg" : "none"
1074
+ });
1075
+ bodyContents.push({
1076
+ type: "box",
1077
+ layout: "vertical",
1078
+ contents: detailItems,
1079
+ margin: "lg",
1080
+ paddingAll: "lg",
1081
+ backgroundColor: "#F8F9FA",
1082
+ cornerRadius: "lg"
1083
+ });
1084
+ }
1085
+ return {
1086
+ type: "bubble",
1087
+ size: "mega",
1088
+ body: {
1089
+ type: "box",
1090
+ layout: "vertical",
1091
+ contents: bodyContents,
1092
+ paddingAll: "xl",
1093
+ backgroundColor: "#FFFFFF",
1094
+ action
1095
+ }
1096
+ };
1097
+ }
1098
+ /**
1099
+ * Create a calendar agenda card showing multiple events
1100
+ *
1101
+ * Editorial timeline design: Time-focused left column with event details
1102
+ * on the right. Visual accent bars indicate event priority/recency.
1103
+ */
1104
+ function createAgendaCard(params) {
1105
+ const { title, subtitle, events, footer } = params;
1106
+ const headerContents = buildTitleSubtitleHeader({
1107
+ title,
1108
+ subtitle
1109
+ });
1110
+ const eventItems = events.slice(0, 6).map((event, index) => {
1111
+ const isActive = event.isNow || index === 0;
1112
+ const accentColor = isActive ? "#06C755" : "#E5E5E5";
1113
+ const timeColumn = {
1114
+ type: "box",
1115
+ layout: "vertical",
1116
+ contents: [{
1117
+ type: "text",
1118
+ text: event.time ?? "—",
1119
+ size: "sm",
1120
+ weight: isActive ? "bold" : "regular",
1121
+ color: isActive ? "#06C755" : "#666666",
1122
+ align: "end",
1123
+ wrap: true
1124
+ }],
1125
+ width: "65px",
1126
+ justifyContent: "flex-start"
1127
+ };
1128
+ const dotColumn = {
1129
+ type: "box",
1130
+ layout: "vertical",
1131
+ contents: [{
1132
+ type: "box",
1133
+ layout: "vertical",
1134
+ contents: [],
1135
+ width: "10px",
1136
+ height: "10px",
1137
+ backgroundColor: accentColor,
1138
+ cornerRadius: "5px"
1139
+ }],
1140
+ width: "24px",
1141
+ alignItems: "center",
1142
+ justifyContent: "flex-start",
1143
+ paddingTop: "xs"
1144
+ };
1145
+ const detailContents = [{
1146
+ type: "text",
1147
+ text: event.title,
1148
+ size: "md",
1149
+ weight: "bold",
1150
+ color: "#1a1a1a",
1151
+ wrap: true
1152
+ }];
1153
+ const secondaryParts = [];
1154
+ if (event.location) secondaryParts.push(event.location);
1155
+ if (event.calendar) secondaryParts.push(event.calendar);
1156
+ if (secondaryParts.length > 0) detailContents.push({
1157
+ type: "text",
1158
+ text: secondaryParts.join(" · "),
1159
+ size: "xs",
1160
+ color: "#888888",
1161
+ wrap: true,
1162
+ margin: "xs"
1163
+ });
1164
+ return {
1165
+ type: "box",
1166
+ layout: "horizontal",
1167
+ contents: [
1168
+ timeColumn,
1169
+ dotColumn,
1170
+ {
1171
+ type: "box",
1172
+ layout: "vertical",
1173
+ contents: detailContents,
1174
+ flex: 1
1175
+ }
1176
+ ],
1177
+ margin: index > 0 ? "xl" : void 0,
1178
+ alignItems: "flex-start"
1179
+ };
1180
+ });
1181
+ return createMegaBubbleWithFooter({
1182
+ bodyContents: [...buildCardHeaderSections(headerContents), {
1183
+ type: "box",
1184
+ layout: "vertical",
1185
+ contents: eventItems,
1186
+ paddingTop: "xl"
1187
+ }],
1188
+ footer
1189
+ });
1190
+ }
1191
+
1192
+ //#endregion
1193
+ //#region src/line/flex-templates/media-control-cards.ts
1194
+ /**
1195
+ * Create a media player card for Sonos, Spotify, Apple Music, etc.
1196
+ *
1197
+ * Editorial design: Album art hero with gradient overlay for text,
1198
+ * prominent now-playing indicator, refined playback controls.
1199
+ */
1200
+ function createMediaPlayerCard(params) {
1201
+ const { title, subtitle, source, imageUrl, isPlaying, progress, controls, extraActions } = params;
1202
+ const trackInfo = [{
1203
+ type: "text",
1204
+ text: title,
1205
+ weight: "bold",
1206
+ size: "xl",
1207
+ color: "#111111",
1208
+ wrap: true
1209
+ }];
1210
+ if (subtitle) trackInfo.push({
1211
+ type: "text",
1212
+ text: subtitle,
1213
+ size: "md",
1214
+ color: "#666666",
1215
+ wrap: true,
1216
+ margin: "sm"
1217
+ });
1218
+ const statusItems = [];
1219
+ if (isPlaying !== void 0) statusItems.push({
1220
+ type: "box",
1221
+ layout: "horizontal",
1222
+ contents: [{
1223
+ type: "box",
1224
+ layout: "vertical",
1225
+ contents: [],
1226
+ width: "8px",
1227
+ height: "8px",
1228
+ backgroundColor: isPlaying ? "#06C755" : "#CCCCCC",
1229
+ cornerRadius: "4px"
1230
+ }, {
1231
+ type: "text",
1232
+ text: isPlaying ? "Now Playing" : "Paused",
1233
+ size: "xs",
1234
+ color: isPlaying ? "#06C755" : "#888888",
1235
+ weight: "bold",
1236
+ margin: "sm"
1237
+ }],
1238
+ alignItems: "center"
1239
+ });
1240
+ if (source) statusItems.push({
1241
+ type: "text",
1242
+ text: source,
1243
+ size: "xs",
1244
+ color: "#AAAAAA",
1245
+ margin: statusItems.length > 0 ? "lg" : void 0
1246
+ });
1247
+ if (progress) statusItems.push({
1248
+ type: "text",
1249
+ text: progress,
1250
+ size: "xs",
1251
+ color: "#888888",
1252
+ align: "end",
1253
+ flex: 1
1254
+ });
1255
+ const bodyContents = [{
1256
+ type: "box",
1257
+ layout: "vertical",
1258
+ contents: trackInfo
1259
+ }];
1260
+ if (statusItems.length > 0) bodyContents.push({
1261
+ type: "box",
1262
+ layout: "horizontal",
1263
+ contents: statusItems,
1264
+ margin: "lg",
1265
+ alignItems: "center"
1266
+ });
1267
+ const bubble = {
1268
+ type: "bubble",
1269
+ size: "mega",
1270
+ body: {
1271
+ type: "box",
1272
+ layout: "vertical",
1273
+ contents: bodyContents,
1274
+ paddingAll: "xl",
1275
+ backgroundColor: "#FFFFFF"
1276
+ }
1277
+ };
1278
+ if (imageUrl) bubble.hero = {
1279
+ type: "image",
1280
+ url: imageUrl,
1281
+ size: "full",
1282
+ aspectRatio: "1:1",
1283
+ aspectMode: "cover"
1284
+ };
1285
+ if (controls || extraActions?.length) {
1286
+ const footerContents = [];
1287
+ if (controls) {
1288
+ const controlButtons = [];
1289
+ if (controls.previous) controlButtons.push({
1290
+ type: "button",
1291
+ action: {
1292
+ type: "postback",
1293
+ label: "⏮",
1294
+ data: controls.previous.data
1295
+ },
1296
+ style: "secondary",
1297
+ flex: 1,
1298
+ height: "sm"
1299
+ });
1300
+ if (controls.play) controlButtons.push({
1301
+ type: "button",
1302
+ action: {
1303
+ type: "postback",
1304
+ label: "▶",
1305
+ data: controls.play.data
1306
+ },
1307
+ style: isPlaying ? "secondary" : "primary",
1308
+ flex: 1,
1309
+ height: "sm",
1310
+ margin: controls.previous ? "md" : void 0
1311
+ });
1312
+ if (controls.pause) controlButtons.push({
1313
+ type: "button",
1314
+ action: {
1315
+ type: "postback",
1316
+ label: "⏸",
1317
+ data: controls.pause.data
1318
+ },
1319
+ style: isPlaying ? "primary" : "secondary",
1320
+ flex: 1,
1321
+ height: "sm",
1322
+ margin: controlButtons.length > 0 ? "md" : void 0
1323
+ });
1324
+ if (controls.next) controlButtons.push({
1325
+ type: "button",
1326
+ action: {
1327
+ type: "postback",
1328
+ label: "⏭",
1329
+ data: controls.next.data
1330
+ },
1331
+ style: "secondary",
1332
+ flex: 1,
1333
+ height: "sm",
1334
+ margin: controlButtons.length > 0 ? "md" : void 0
1335
+ });
1336
+ if (controlButtons.length > 0) footerContents.push({
1337
+ type: "box",
1338
+ layout: "horizontal",
1339
+ contents: controlButtons
1340
+ });
1341
+ }
1342
+ if (extraActions?.length) footerContents.push({
1343
+ type: "box",
1344
+ layout: "horizontal",
1345
+ contents: extraActions.slice(0, 2).map((action, index) => ({
1346
+ type: "button",
1347
+ action: {
1348
+ type: "postback",
1349
+ label: action.label.slice(0, 15),
1350
+ data: action.data
1351
+ },
1352
+ style: "secondary",
1353
+ flex: 1,
1354
+ height: "sm",
1355
+ margin: index > 0 ? "md" : void 0
1356
+ })),
1357
+ margin: "md"
1358
+ });
1359
+ if (footerContents.length > 0) bubble.footer = {
1360
+ type: "box",
1361
+ layout: "vertical",
1362
+ contents: footerContents,
1363
+ paddingAll: "lg",
1364
+ backgroundColor: "#FAFAFA"
1365
+ };
1366
+ }
1367
+ return bubble;
1368
+ }
1369
+ /**
1370
+ * Create an Apple TV remote card with a D-pad and control rows.
1371
+ */
1372
+ function createAppleTvRemoteCard(params) {
1373
+ const { deviceName, status, actionData } = params;
1374
+ const headerContents = [{
1375
+ type: "text",
1376
+ text: deviceName,
1377
+ weight: "bold",
1378
+ size: "xl",
1379
+ color: "#111111",
1380
+ wrap: true
1381
+ }];
1382
+ if (status) headerContents.push({
1383
+ type: "text",
1384
+ text: status,
1385
+ size: "sm",
1386
+ color: "#666666",
1387
+ wrap: true,
1388
+ margin: "sm"
1389
+ });
1390
+ const makeButton = (label, data, style = "secondary") => ({
1391
+ type: "button",
1392
+ action: {
1393
+ type: "postback",
1394
+ label,
1395
+ data
1396
+ },
1397
+ style,
1398
+ height: "sm",
1399
+ flex: 1
1400
+ });
1401
+ const dpadRows = [
1402
+ {
1403
+ type: "box",
1404
+ layout: "horizontal",
1405
+ contents: [
1406
+ { type: "filler" },
1407
+ makeButton("↑", actionData.up),
1408
+ { type: "filler" }
1409
+ ]
1410
+ },
1411
+ {
1412
+ type: "box",
1413
+ layout: "horizontal",
1414
+ contents: [
1415
+ makeButton("←", actionData.left),
1416
+ makeButton("OK", actionData.select, "primary"),
1417
+ makeButton("→", actionData.right)
1418
+ ],
1419
+ margin: "md"
1420
+ },
1421
+ {
1422
+ type: "box",
1423
+ layout: "horizontal",
1424
+ contents: [
1425
+ { type: "filler" },
1426
+ makeButton("↓", actionData.down),
1427
+ { type: "filler" }
1428
+ ],
1429
+ margin: "md"
1430
+ }
1431
+ ];
1432
+ const menuRow = {
1433
+ type: "box",
1434
+ layout: "horizontal",
1435
+ contents: [makeButton("Menu", actionData.menu), makeButton("Home", actionData.home)],
1436
+ margin: "lg"
1437
+ };
1438
+ const playbackRow = {
1439
+ type: "box",
1440
+ layout: "horizontal",
1441
+ contents: [makeButton("Play", actionData.play), makeButton("Pause", actionData.pause)],
1442
+ margin: "md"
1443
+ };
1444
+ const volumeRow = {
1445
+ type: "box",
1446
+ layout: "horizontal",
1447
+ contents: [
1448
+ makeButton("Vol +", actionData.volumeUp),
1449
+ makeButton("Mute", actionData.mute),
1450
+ makeButton("Vol -", actionData.volumeDown)
1451
+ ],
1452
+ margin: "md"
1453
+ };
1454
+ return {
1455
+ type: "bubble",
1456
+ size: "mega",
1457
+ body: {
1458
+ type: "box",
1459
+ layout: "vertical",
1460
+ contents: [
1461
+ {
1462
+ type: "box",
1463
+ layout: "vertical",
1464
+ contents: headerContents
1465
+ },
1466
+ {
1467
+ type: "separator",
1468
+ margin: "lg",
1469
+ color: "#EEEEEE"
1470
+ },
1471
+ ...dpadRows,
1472
+ menuRow,
1473
+ playbackRow,
1474
+ volumeRow
1475
+ ],
1476
+ paddingAll: "xl",
1477
+ backgroundColor: "#FFFFFF"
1478
+ }
1479
+ };
1480
+ }
1481
+ /**
1482
+ * Create a device control card for Apple TV, smart home devices, etc.
1483
+ *
1484
+ * Editorial design: Device-focused header with status indicator,
1485
+ * clean control grid with clear visual hierarchy.
1486
+ */
1487
+ function createDeviceControlCard(params) {
1488
+ const { deviceName, deviceType, status, isOnline, imageUrl, controls } = params;
1489
+ const headerContents = [{
1490
+ type: "box",
1491
+ layout: "horizontal",
1492
+ contents: [{
1493
+ type: "box",
1494
+ layout: "vertical",
1495
+ contents: [],
1496
+ width: "10px",
1497
+ height: "10px",
1498
+ backgroundColor: isOnline !== false ? "#06C755" : "#FF5555",
1499
+ cornerRadius: "5px"
1500
+ }, {
1501
+ type: "text",
1502
+ text: deviceName,
1503
+ weight: "bold",
1504
+ size: "xl",
1505
+ color: "#111111",
1506
+ wrap: true,
1507
+ flex: 1,
1508
+ margin: "md"
1509
+ }],
1510
+ alignItems: "center"
1511
+ }];
1512
+ if (deviceType) headerContents.push({
1513
+ type: "text",
1514
+ text: deviceType,
1515
+ size: "sm",
1516
+ color: "#888888",
1517
+ margin: "sm"
1518
+ });
1519
+ if (status) headerContents.push({
1520
+ type: "box",
1521
+ layout: "vertical",
1522
+ contents: [{
1523
+ type: "text",
1524
+ text: status,
1525
+ size: "sm",
1526
+ color: "#444444",
1527
+ wrap: true
1528
+ }],
1529
+ margin: "lg",
1530
+ paddingAll: "md",
1531
+ backgroundColor: "#F8F9FA",
1532
+ cornerRadius: "md"
1533
+ });
1534
+ const bubble = {
1535
+ type: "bubble",
1536
+ size: "mega",
1537
+ body: {
1538
+ type: "box",
1539
+ layout: "vertical",
1540
+ contents: headerContents,
1541
+ paddingAll: "xl",
1542
+ backgroundColor: "#FFFFFF"
1543
+ }
1544
+ };
1545
+ if (imageUrl) bubble.hero = {
1546
+ type: "image",
1547
+ url: imageUrl,
1548
+ size: "full",
1549
+ aspectRatio: "16:9",
1550
+ aspectMode: "cover"
1551
+ };
1552
+ if (controls.length > 0) {
1553
+ const rows = [];
1554
+ const limitedControls = controls.slice(0, 6);
1555
+ for (let i = 0; i < limitedControls.length; i += 2) {
1556
+ const rowButtons = [];
1557
+ for (let j = i; j < Math.min(i + 2, limitedControls.length); j++) {
1558
+ const ctrl = limitedControls[j];
1559
+ const buttonLabel = ctrl.icon ? `${ctrl.icon} ${ctrl.label}` : ctrl.label;
1560
+ rowButtons.push({
1561
+ type: "button",
1562
+ action: {
1563
+ type: "postback",
1564
+ label: buttonLabel.slice(0, 18),
1565
+ data: ctrl.data
1566
+ },
1567
+ style: ctrl.style ?? "secondary",
1568
+ flex: 1,
1569
+ height: "sm",
1570
+ margin: j > i ? "md" : void 0
1571
+ });
1572
+ }
1573
+ if (rowButtons.length === 1) rowButtons.push({ type: "filler" });
1574
+ rows.push({
1575
+ type: "box",
1576
+ layout: "horizontal",
1577
+ contents: rowButtons,
1578
+ margin: i > 0 ? "md" : void 0
1579
+ });
1580
+ }
1581
+ bubble.footer = {
1582
+ type: "box",
1583
+ layout: "vertical",
1584
+ contents: rows,
1585
+ paddingAll: "lg",
1586
+ backgroundColor: "#FAFAFA"
1587
+ };
1588
+ }
1589
+ return bubble;
1590
+ }
1591
+
1592
+ //#endregion
1593
+ //#region src/auto-reply/reply/line-directives.ts
1594
+ /**
1595
+ * Parse LINE-specific directives from text and extract them into ReplyPayload fields.
1596
+ *
1597
+ * Supported directives:
1598
+ * - [[quick_replies: option1, option2, option3]]
1599
+ * - [[location: title | address | latitude | longitude]]
1600
+ * - [[confirm: question | yes_label | no_label]]
1601
+ * - [[buttons: title | text | btn1:data1, btn2:data2]]
1602
+ * - [[media_player: title | artist | source | imageUrl | playing/paused]]
1603
+ * - [[event: title | date | time | location | description]]
1604
+ * - [[agenda: title | event1_title:event1_time, event2_title:event2_time, ...]]
1605
+ * - [[device: name | type | status | ctrl1:data1, ctrl2:data2]]
1606
+ * - [[appletv_remote: name | status]]
1607
+ *
1608
+ * Returns the modified payload with directives removed from text and fields populated.
1609
+ */
1610
+ function parseLineDirectives(payload) {
1611
+ let text = payload.text;
1612
+ if (!text) return payload;
1613
+ const result = { ...payload };
1614
+ const lineData = { ...result.channelData?.line };
1615
+ const toSlug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "device";
1616
+ const lineActionData = (action, extras) => {
1617
+ const base = [`line.action=${encodeURIComponent(action)}`];
1618
+ if (extras) for (const [key, value] of Object.entries(extras)) base.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
1619
+ return base.join("&");
1620
+ };
1621
+ const quickRepliesMatch = text.match(/\[\[quick_replies:\s*([^\]]+)\]\]/i);
1622
+ if (quickRepliesMatch) {
1623
+ const options = quickRepliesMatch[1].split(",").map((s) => s.trim()).filter(Boolean);
1624
+ if (options.length > 0) lineData.quickReplies = [...lineData.quickReplies || [], ...options];
1625
+ text = text.replace(quickRepliesMatch[0], "").trim();
1626
+ }
1627
+ const locationMatch = text.match(/\[\[location:\s*([^\]]+)\]\]/i);
1628
+ if (locationMatch && !lineData.location) {
1629
+ const parts = locationMatch[1].split("|").map((s) => s.trim());
1630
+ if (parts.length >= 4) {
1631
+ const [title, address, latStr, lonStr] = parts;
1632
+ const latitude = parseFloat(latStr);
1633
+ const longitude = parseFloat(lonStr);
1634
+ if (!isNaN(latitude) && !isNaN(longitude)) lineData.location = {
1635
+ title: title || "Location",
1636
+ address: address || "",
1637
+ latitude,
1638
+ longitude
1639
+ };
1640
+ }
1641
+ text = text.replace(locationMatch[0], "").trim();
1642
+ }
1643
+ const confirmMatch = text.match(/\[\[confirm:\s*([^\]]+)\]\]/i);
1644
+ if (confirmMatch && !lineData.templateMessage) {
1645
+ const parts = confirmMatch[1].split("|").map((s) => s.trim());
1646
+ if (parts.length >= 3) {
1647
+ const [question, yesPart, noPart] = parts;
1648
+ const [yesLabel, yesData] = yesPart.includes(":") ? yesPart.split(":").map((s) => s.trim()) : [yesPart, yesPart.toLowerCase()];
1649
+ const [noLabel, noData] = noPart.includes(":") ? noPart.split(":").map((s) => s.trim()) : [noPart, noPart.toLowerCase()];
1650
+ lineData.templateMessage = {
1651
+ type: "confirm",
1652
+ text: question,
1653
+ confirmLabel: yesLabel,
1654
+ confirmData: yesData,
1655
+ cancelLabel: noLabel,
1656
+ cancelData: noData,
1657
+ altText: question
1658
+ };
1659
+ }
1660
+ text = text.replace(confirmMatch[0], "").trim();
1661
+ }
1662
+ const buttonsMatch = text.match(/\[\[buttons:\s*([^\]]+)\]\]/i);
1663
+ if (buttonsMatch && !lineData.templateMessage) {
1664
+ const parts = buttonsMatch[1].split("|").map((s) => s.trim());
1665
+ if (parts.length >= 3) {
1666
+ const [title, bodyText, actionsStr] = parts;
1667
+ const actions = actionsStr.split(",").map((actionStr) => {
1668
+ const trimmed = actionStr.trim();
1669
+ const colonIndex = (() => {
1670
+ const index = trimmed.indexOf(":");
1671
+ if (index === -1) return -1;
1672
+ const lower = trimmed.toLowerCase();
1673
+ if (lower.startsWith("http://") || lower.startsWith("https://")) return -1;
1674
+ return index;
1675
+ })();
1676
+ let label;
1677
+ let data;
1678
+ if (colonIndex === -1) {
1679
+ label = trimmed;
1680
+ data = trimmed;
1681
+ } else {
1682
+ label = trimmed.slice(0, colonIndex).trim();
1683
+ data = trimmed.slice(colonIndex + 1).trim();
1684
+ }
1685
+ if (data.startsWith("http://") || data.startsWith("https://")) return {
1686
+ type: "uri",
1687
+ label,
1688
+ uri: data
1689
+ };
1690
+ if (data.includes("=")) return {
1691
+ type: "postback",
1692
+ label,
1693
+ data
1694
+ };
1695
+ return {
1696
+ type: "message",
1697
+ label,
1698
+ data: data || label
1699
+ };
1700
+ });
1701
+ if (actions.length > 0) lineData.templateMessage = {
1702
+ type: "buttons",
1703
+ title,
1704
+ text: bodyText,
1705
+ actions: actions.slice(0, 4),
1706
+ altText: `${title}: ${bodyText}`
1707
+ };
1708
+ }
1709
+ text = text.replace(buttonsMatch[0], "").trim();
1710
+ }
1711
+ const mediaPlayerMatch = text.match(/\[\[media_player:\s*([^\]]+)\]\]/i);
1712
+ if (mediaPlayerMatch && !lineData.flexMessage) {
1713
+ const parts = mediaPlayerMatch[1].split("|").map((s) => s.trim());
1714
+ if (parts.length >= 1) {
1715
+ const [title, artist, source, imageUrl, statusStr] = parts;
1716
+ const isPlaying = statusStr?.toLowerCase() === "playing";
1717
+ const validImageUrl = imageUrl?.startsWith("https://") ? imageUrl : void 0;
1718
+ const deviceKey = toSlug(source || title || "media");
1719
+ const card = createMediaPlayerCard({
1720
+ title: title || "Unknown Track",
1721
+ subtitle: artist || void 0,
1722
+ source: source || void 0,
1723
+ imageUrl: validImageUrl,
1724
+ isPlaying: statusStr ? isPlaying : void 0,
1725
+ controls: {
1726
+ previous: { data: lineActionData("previous", { "line.device": deviceKey }) },
1727
+ play: { data: lineActionData("play", { "line.device": deviceKey }) },
1728
+ pause: { data: lineActionData("pause", { "line.device": deviceKey }) },
1729
+ next: { data: lineActionData("next", { "line.device": deviceKey }) }
1730
+ }
1731
+ });
1732
+ lineData.flexMessage = {
1733
+ altText: `🎵 ${title}${artist ? ` - ${artist}` : ""}`,
1734
+ contents: card
1735
+ };
1736
+ }
1737
+ text = text.replace(mediaPlayerMatch[0], "").trim();
1738
+ }
1739
+ const eventMatch = text.match(/\[\[event:\s*([^\]]+)\]\]/i);
1740
+ if (eventMatch && !lineData.flexMessage) {
1741
+ const parts = eventMatch[1].split("|").map((s) => s.trim());
1742
+ if (parts.length >= 2) {
1743
+ const [title, date, time, location, description] = parts;
1744
+ const card = createEventCard({
1745
+ title: title || "Event",
1746
+ date: date || "TBD",
1747
+ time: time || void 0,
1748
+ location: location || void 0,
1749
+ description: description || void 0
1750
+ });
1751
+ lineData.flexMessage = {
1752
+ altText: `📅 ${title} - ${date}${time ? ` ${time}` : ""}`,
1753
+ contents: card
1754
+ };
1755
+ }
1756
+ text = text.replace(eventMatch[0], "").trim();
1757
+ }
1758
+ const appleTvMatch = text.match(/\[\[appletv_remote:\s*([^\]]+)\]\]/i);
1759
+ if (appleTvMatch && !lineData.flexMessage) {
1760
+ const parts = appleTvMatch[1].split("|").map((s) => s.trim());
1761
+ if (parts.length >= 1) {
1762
+ const [deviceName, status] = parts;
1763
+ const deviceKey = toSlug(deviceName || "apple_tv");
1764
+ const card = createAppleTvRemoteCard({
1765
+ deviceName: deviceName || "Apple TV",
1766
+ status: status || void 0,
1767
+ actionData: {
1768
+ up: lineActionData("up", { "line.device": deviceKey }),
1769
+ down: lineActionData("down", { "line.device": deviceKey }),
1770
+ left: lineActionData("left", { "line.device": deviceKey }),
1771
+ right: lineActionData("right", { "line.device": deviceKey }),
1772
+ select: lineActionData("select", { "line.device": deviceKey }),
1773
+ menu: lineActionData("menu", { "line.device": deviceKey }),
1774
+ home: lineActionData("home", { "line.device": deviceKey }),
1775
+ play: lineActionData("play", { "line.device": deviceKey }),
1776
+ pause: lineActionData("pause", { "line.device": deviceKey }),
1777
+ volumeUp: lineActionData("volume_up", { "line.device": deviceKey }),
1778
+ volumeDown: lineActionData("volume_down", { "line.device": deviceKey }),
1779
+ mute: lineActionData("mute", { "line.device": deviceKey })
1780
+ }
1781
+ });
1782
+ lineData.flexMessage = {
1783
+ altText: `📺 ${deviceName || "Apple TV"} Remote`,
1784
+ contents: card
1785
+ };
1786
+ }
1787
+ text = text.replace(appleTvMatch[0], "").trim();
1788
+ }
1789
+ const agendaMatch = text.match(/\[\[agenda:\s*([^\]]+)\]\]/i);
1790
+ if (agendaMatch && !lineData.flexMessage) {
1791
+ const parts = agendaMatch[1].split("|").map((s) => s.trim());
1792
+ if (parts.length >= 2) {
1793
+ const [title, eventsStr] = parts;
1794
+ const events = eventsStr.split(",").map((eventStr) => {
1795
+ const trimmed = eventStr.trim();
1796
+ const colonIdx = trimmed.lastIndexOf(":");
1797
+ if (colonIdx > 0) return {
1798
+ title: trimmed.slice(0, colonIdx).trim(),
1799
+ time: trimmed.slice(colonIdx + 1).trim()
1800
+ };
1801
+ return { title: trimmed };
1802
+ });
1803
+ const card = createAgendaCard({
1804
+ title: title || "Agenda",
1805
+ events
1806
+ });
1807
+ lineData.flexMessage = {
1808
+ altText: `📋 ${title} (${events.length} events)`,
1809
+ contents: card
1810
+ };
1811
+ }
1812
+ text = text.replace(agendaMatch[0], "").trim();
1813
+ }
1814
+ const deviceMatch = text.match(/\[\[device:\s*([^\]]+)\]\]/i);
1815
+ if (deviceMatch && !lineData.flexMessage) {
1816
+ const parts = deviceMatch[1].split("|").map((s) => s.trim());
1817
+ if (parts.length >= 1) {
1818
+ const [deviceName, deviceType, status, controlsStr] = parts;
1819
+ const deviceKey = toSlug(deviceName || "device");
1820
+ const controls = controlsStr ? controlsStr.split(",").map((ctrlStr) => {
1821
+ const [label, data] = ctrlStr.split(":").map((s) => s.trim());
1822
+ return {
1823
+ label,
1824
+ data: lineActionData(data || label.toLowerCase().replace(/\s+/g, "_"), { "line.device": deviceKey })
1825
+ };
1826
+ }) : [];
1827
+ const card = createDeviceControlCard({
1828
+ deviceName: deviceName || "Device",
1829
+ deviceType: deviceType || void 0,
1830
+ status: status || void 0,
1831
+ controls
1832
+ });
1833
+ lineData.flexMessage = {
1834
+ altText: `📱 ${deviceName}${status ? `: ${status}` : ""}`,
1835
+ contents: card
1836
+ };
1837
+ }
1838
+ text = text.replace(deviceMatch[0], "").trim();
1839
+ }
1840
+ text = text.replace(/\n{3,}/g, "\n\n").trim();
1841
+ result.text = text || void 0;
1842
+ if (Object.keys(lineData).length > 0) result.channelData = {
1843
+ ...result.channelData,
1844
+ line: lineData
1845
+ };
1846
+ return result;
1847
+ }
1848
+ /**
1849
+ * Check if text contains any LINE directives
1850
+ */
1851
+ function hasLineDirectives(text) {
1852
+ return /\[\[(quick_replies|location|confirm|buttons|media_player|event|agenda|device|appletv_remote):/i.test(text);
1853
+ }
1854
+
1855
+ //#endregion
1856
+ //#region src/auto-reply/reply/normalize-reply.ts
1857
+ function normalizeReplyPayload(payload, opts = {}) {
1858
+ const hasMedia = Boolean(payload.mediaUrl || (payload.mediaUrls?.length ?? 0) > 0);
1859
+ const hasChannelData = Boolean(payload.channelData && Object.keys(payload.channelData).length > 0);
1860
+ const trimmed = payload.text?.trim() ?? "";
1861
+ if (!trimmed && !hasMedia && !hasChannelData) {
1862
+ opts.onSkip?.("empty");
1863
+ return null;
1864
+ }
1865
+ const silentToken = opts.silentToken ?? SILENT_REPLY_TOKEN;
1866
+ let text = payload.text ?? void 0;
1867
+ if (text && isSilentReplyText(text, silentToken)) {
1868
+ if (!hasMedia && !hasChannelData) {
1869
+ opts.onSkip?.("silent");
1870
+ return null;
1871
+ }
1872
+ text = "";
1873
+ }
1874
+ if (text && !trimmed) text = "";
1875
+ if (text) text = sanitizeUserFacingText(text, { errorContext: Boolean(payload.isError) });
1876
+ if (!text?.trim() && !hasMedia && !hasChannelData) {
1877
+ opts.onSkip?.("empty");
1878
+ return null;
1879
+ }
1880
+ let enrichedPayload = {
1881
+ ...payload,
1882
+ text
1883
+ };
1884
+ if (text && hasLineDirectives(text)) {
1885
+ enrichedPayload = parseLineDirectives(enrichedPayload);
1886
+ text = enrichedPayload.text;
1887
+ }
1888
+ const effectivePrefix = opts.responsePrefixContext ? resolveResponsePrefixTemplate(opts.responsePrefix, opts.responsePrefixContext) : opts.responsePrefix;
1889
+ if (effectivePrefix && text && !text.startsWith(effectivePrefix)) text = `${effectivePrefix} ${text}`;
1890
+ return {
1891
+ ...enrichedPayload,
1892
+ text
1893
+ };
1894
+ }
1895
+
1896
+ //#endregion
1897
+ //#region src/auto-reply/reply/route-reply.ts
1898
+ /**
1899
+ * Provider-agnostic reply router.
1900
+ *
1901
+ * Routes replies to the originating channel based on OriginatingChannel/OriginatingTo
1902
+ * instead of using the session's lastChannel. This ensures replies go back to the
1903
+ * provider where the message originated, even when the main session is shared
1904
+ * across multiple providers.
1905
+ */
1906
+ /**
1907
+ * Routes a reply payload to the specified channel.
1908
+ *
1909
+ * This function provides a unified interface for sending messages to any
1910
+ * supported provider. It's used by the followup queue to route replies
1911
+ * back to the originating channel when OriginatingChannel/OriginatingTo
1912
+ * are set.
1913
+ */
1914
+ async function routeReply(params) {
1915
+ const { payload, channel, to, accountId, threadId, cfg, abortSignal } = params;
1916
+ if (shouldSuppressReasoningPayload(payload)) return { ok: true };
1917
+ const normalizedChannel = normalizeMessageChannel(channel);
1918
+ const resolvedAgentId = params.sessionKey ? resolveSessionAgentId({
1919
+ sessionKey: params.sessionKey,
1920
+ config: cfg
1921
+ }) : void 0;
1922
+ const normalized = normalizeReplyPayload(payload, { responsePrefix: params.sessionKey ? resolveEffectiveMessagesConfig(cfg, resolvedAgentId ?? resolveSessionAgentId({ config: cfg }), {
1923
+ channel: normalizedChannel,
1924
+ accountId
1925
+ }).responsePrefix : cfg.messages?.responsePrefix === "auto" ? void 0 : cfg.messages?.responsePrefix });
1926
+ if (!normalized) return { ok: true };
1927
+ let text = normalized.text ?? "";
1928
+ let mediaUrls = (normalized.mediaUrls?.filter(Boolean) ?? []).length ? normalized.mediaUrls?.filter(Boolean) : normalized.mediaUrl ? [normalized.mediaUrl] : [];
1929
+ const replyToId = normalized.replyToId;
1930
+ if (!text.trim() && mediaUrls.length === 0) return { ok: true };
1931
+ if (channel === INTERNAL_MESSAGE_CHANNEL) return {
1932
+ ok: false,
1933
+ error: "Webchat routing not supported for queued replies"
1934
+ };
1935
+ const channelId = normalizeChannelId$1(channel) ?? null;
1936
+ if (!channelId) return {
1937
+ ok: false,
1938
+ error: `Unknown channel: ${String(channel)}`
1939
+ };
1940
+ if (abortSignal?.aborted) return {
1941
+ ok: false,
1942
+ error: "Reply routing aborted"
1943
+ };
1944
+ const resolvedReplyToId = replyToId ?? (channelId === "slack" && threadId != null && threadId !== "" ? String(threadId) : void 0);
1945
+ const resolvedThreadId = channelId === "slack" ? null : threadId ?? null;
1946
+ try {
1947
+ const { deliverOutboundPayloads } = await import("./deliver-D49hWPWI.js").then((n) => n.n);
1948
+ return {
1949
+ ok: true,
1950
+ messageId: (await deliverOutboundPayloads({
1951
+ cfg,
1952
+ channel: channelId,
1953
+ to,
1954
+ accountId: accountId ?? void 0,
1955
+ payloads: [normalized],
1956
+ replyToId: resolvedReplyToId ?? null,
1957
+ threadId: resolvedThreadId,
1958
+ agentId: resolvedAgentId,
1959
+ abortSignal,
1960
+ mirror: params.mirror !== false && params.sessionKey ? {
1961
+ sessionKey: params.sessionKey,
1962
+ agentId: resolvedAgentId,
1963
+ text,
1964
+ mediaUrls
1965
+ } : void 0
1966
+ })).at(-1)?.messageId
1967
+ };
1968
+ } catch (err) {
1969
+ return {
1970
+ ok: false,
1971
+ error: `Failed to route reply to ${channel}: ${err instanceof Error ? err.message : String(err)}`
1972
+ };
1973
+ }
1974
+ }
1975
+ /**
1976
+ * Checks if a channel type is routable via routeReply.
1977
+ *
1978
+ * Some channels (webchat) require special handling and cannot be routed through
1979
+ * this generic interface.
1980
+ */
1981
+ function isRoutableChannel(channel) {
1982
+ if (!channel || channel === INTERNAL_MESSAGE_CHANNEL) return false;
1983
+ return normalizeChannelId$1(channel) !== null;
1984
+ }
1985
+
1986
+ //#endregion
1987
+ //#region src/auto-reply/reply/queue/drain.ts
1988
+ function resolveOriginRoutingMetadata(items) {
1989
+ return {
1990
+ originatingChannel: items.find((item) => item.originatingChannel)?.originatingChannel,
1991
+ originatingTo: items.find((item) => item.originatingTo)?.originatingTo,
1992
+ originatingAccountId: items.find((item) => item.originatingAccountId)?.originatingAccountId,
1993
+ originatingThreadId: items.find((item) => item.originatingThreadId != null && item.originatingThreadId !== "")?.originatingThreadId
1994
+ };
1995
+ }
1996
+ function resolveCrossChannelKey(item) {
1997
+ const { originatingChannel: channel, originatingTo: to, originatingAccountId: accountId } = item;
1998
+ const threadId = item.originatingThreadId;
1999
+ if (!channel && !to && !accountId && (threadId == null || threadId === "")) return {};
2000
+ if (!isRoutableChannel(channel) || !to) return { cross: true };
2001
+ return { key: [
2002
+ channel,
2003
+ to,
2004
+ accountId || "",
2005
+ threadId != null && threadId !== "" ? String(threadId) : ""
2006
+ ].join("|") };
2007
+ }
2008
+ function scheduleFollowupDrain(key, runFollowup) {
2009
+ const queue = beginQueueDrain(FOLLOWUP_QUEUES, key);
2010
+ if (!queue) return;
2011
+ (async () => {
2012
+ try {
2013
+ const collectState = { forceIndividualCollect: false };
2014
+ while (queue.items.length > 0 || queue.droppedCount > 0) {
2015
+ await waitForQueueDebounce(queue);
2016
+ if (queue.mode === "collect") {
2017
+ const collectDrainResult = await drainCollectQueueStep({
2018
+ collectState,
2019
+ isCrossChannel: hasCrossChannelItems(queue.items, resolveCrossChannelKey),
2020
+ items: queue.items,
2021
+ run: runFollowup
2022
+ });
2023
+ if (collectDrainResult === "empty") break;
2024
+ if (collectDrainResult === "drained") continue;
2025
+ const items = queue.items.slice();
2026
+ const summary = previewQueueSummaryPrompt({
2027
+ state: queue,
2028
+ noun: "message"
2029
+ });
2030
+ const run = items.at(-1)?.run ?? queue.lastRun;
2031
+ if (!run) break;
2032
+ const routing = resolveOriginRoutingMetadata(items);
2033
+ await runFollowup({
2034
+ prompt: buildCollectPrompt({
2035
+ title: "[Queued messages while agent was busy]",
2036
+ items,
2037
+ summary,
2038
+ renderItem: (item, idx) => `---\nQueued #${idx + 1}\n${item.prompt}`.trim()
2039
+ }),
2040
+ run,
2041
+ enqueuedAt: Date.now(),
2042
+ ...routing
2043
+ });
2044
+ queue.items.splice(0, items.length);
2045
+ if (summary) clearQueueSummaryState(queue);
2046
+ continue;
2047
+ }
2048
+ const summaryPrompt = previewQueueSummaryPrompt({
2049
+ state: queue,
2050
+ noun: "message"
2051
+ });
2052
+ if (summaryPrompt) {
2053
+ const run = queue.lastRun;
2054
+ if (!run) break;
2055
+ if (!await drainNextQueueItem(queue.items, async (item) => {
2056
+ await runFollowup({
2057
+ prompt: summaryPrompt,
2058
+ run,
2059
+ enqueuedAt: Date.now(),
2060
+ originatingChannel: item.originatingChannel,
2061
+ originatingTo: item.originatingTo,
2062
+ originatingAccountId: item.originatingAccountId,
2063
+ originatingThreadId: item.originatingThreadId
2064
+ });
2065
+ })) break;
2066
+ clearQueueSummaryState(queue);
2067
+ continue;
2068
+ }
2069
+ if (!await drainNextQueueItem(queue.items, runFollowup)) break;
2070
+ }
2071
+ } catch (err) {
2072
+ queue.lastEnqueuedAt = Date.now();
2073
+ defaultRuntime.error?.(`followup queue drain failed for ${key}: ${String(err)}`);
2074
+ } finally {
2075
+ queue.draining = false;
2076
+ if (queue.items.length === 0 && queue.droppedCount === 0) FOLLOWUP_QUEUES.delete(key);
2077
+ else scheduleFollowupDrain(key, runFollowup);
2078
+ }
2079
+ })();
2080
+ }
2081
+
2082
+ //#endregion
2083
+ //#region src/auto-reply/reply/queue/enqueue.ts
2084
+ function isRunAlreadyQueued(run, items, allowPromptFallback = false) {
2085
+ const hasSameRouting = (item) => item.originatingChannel === run.originatingChannel && item.originatingTo === run.originatingTo && item.originatingAccountId === run.originatingAccountId && item.originatingThreadId === run.originatingThreadId;
2086
+ const messageId = run.messageId?.trim();
2087
+ if (messageId) return items.some((item) => item.messageId?.trim() === messageId && hasSameRouting(item));
2088
+ if (!allowPromptFallback) return false;
2089
+ return items.some((item) => item.prompt === run.prompt && hasSameRouting(item));
2090
+ }
2091
+ function enqueueFollowupRun(key, run, settings, dedupeMode = "message-id") {
2092
+ const queue = getFollowupQueue(key, settings);
2093
+ const dedupe = dedupeMode === "none" ? void 0 : (item, items) => isRunAlreadyQueued(item, items, dedupeMode === "prompt");
2094
+ if (shouldSkipQueueItem({
2095
+ item: run,
2096
+ items: queue.items,
2097
+ dedupe
2098
+ })) return false;
2099
+ queue.lastEnqueuedAt = Date.now();
2100
+ queue.lastRun = run.run;
2101
+ if (!applyQueueDropPolicy({
2102
+ queue,
2103
+ summarize: (item) => item.summaryLine?.trim() || item.prompt.trim()
2104
+ })) return false;
2105
+ queue.items.push(run);
2106
+ return true;
2107
+ }
2108
+ function getFollowupQueueDepth(key) {
2109
+ const queue = getExistingFollowupQueue(key);
2110
+ if (!queue) return 0;
2111
+ return queue.items.length;
2112
+ }
2113
+
2114
+ //#endregion
2115
+ //#region src/auto-reply/reply/queue/settings.ts
2116
+ function defaultQueueModeForChannel(_channel) {
2117
+ return "collect";
2118
+ }
2119
+ /** Resolve per-channel debounce override from debounceMsByChannel map. */
2120
+ function resolveChannelDebounce(byChannel, channelKey) {
2121
+ if (!channelKey || !byChannel) return;
2122
+ const value = byChannel[channelKey];
2123
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
2124
+ }
2125
+ function resolvePluginDebounce(channelKey) {
2126
+ if (!channelKey) return;
2127
+ const value = getChannelPlugin(channelKey)?.defaults?.queue?.debounceMs;
2128
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
2129
+ }
2130
+ function resolveQueueSettings(params) {
2131
+ const channelKey = params.channel?.trim().toLowerCase();
2132
+ const queueCfg = params.cfg.messages?.queue;
2133
+ const providerModeRaw = channelKey && queueCfg?.byChannel ? queueCfg.byChannel[channelKey] : void 0;
2134
+ const resolvedMode = params.inlineMode ?? normalizeQueueMode(params.sessionEntry?.queueMode) ?? normalizeQueueMode(providerModeRaw) ?? normalizeQueueMode(queueCfg?.mode) ?? defaultQueueModeForChannel(channelKey);
2135
+ const debounceRaw = params.inlineOptions?.debounceMs ?? params.sessionEntry?.queueDebounceMs ?? resolveChannelDebounce(queueCfg?.debounceMsByChannel, channelKey) ?? resolvePluginDebounce(channelKey) ?? queueCfg?.debounceMs ?? DEFAULT_QUEUE_DEBOUNCE_MS;
2136
+ const capRaw = params.inlineOptions?.cap ?? params.sessionEntry?.queueCap ?? queueCfg?.cap ?? DEFAULT_QUEUE_CAP;
2137
+ const dropRaw = params.inlineOptions?.dropPolicy ?? params.sessionEntry?.queueDrop ?? normalizeQueueDropPolicy(queueCfg?.drop) ?? DEFAULT_QUEUE_DROP;
2138
+ return {
2139
+ mode: resolvedMode,
2140
+ debounceMs: typeof debounceRaw === "number" ? Math.max(0, debounceRaw) : void 0,
2141
+ cap: typeof capRaw === "number" ? Math.max(1, Math.floor(capRaw)) : void 0,
2142
+ dropPolicy: dropRaw
2143
+ };
2144
+ }
2145
+
2146
+ //#endregion
2147
+ //#region src/infra/outbound/session-binding-service.ts
2148
+ function normalizeConversationRef(ref) {
2149
+ return {
2150
+ channel: ref.channel.trim().toLowerCase(),
2151
+ accountId: normalizeAccountId(ref.accountId),
2152
+ conversationId: ref.conversationId.trim(),
2153
+ parentConversationId: ref.parentConversationId?.trim() || void 0
2154
+ };
2155
+ }
2156
+ function toAdapterKey(params) {
2157
+ return `${params.channel.trim().toLowerCase()}:${normalizeAccountId(params.accountId)}`;
2158
+ }
2159
+ const ADAPTERS_BY_CHANNEL_ACCOUNT = /* @__PURE__ */ new Map();
2160
+ function registerSessionBindingAdapter(adapter) {
2161
+ const key = toAdapterKey({
2162
+ channel: adapter.channel,
2163
+ accountId: adapter.accountId
2164
+ });
2165
+ ADAPTERS_BY_CHANNEL_ACCOUNT.set(key, {
2166
+ ...adapter,
2167
+ channel: adapter.channel.trim().toLowerCase(),
2168
+ accountId: normalizeAccountId(adapter.accountId)
2169
+ });
2170
+ }
2171
+ function unregisterSessionBindingAdapter(params) {
2172
+ ADAPTERS_BY_CHANNEL_ACCOUNT.delete(toAdapterKey(params));
2173
+ }
2174
+ function resolveAdapterForConversation(ref) {
2175
+ const normalized = normalizeConversationRef(ref);
2176
+ const key = toAdapterKey({
2177
+ channel: normalized.channel,
2178
+ accountId: normalized.accountId
2179
+ });
2180
+ return ADAPTERS_BY_CHANNEL_ACCOUNT.get(key) ?? null;
2181
+ }
2182
+ function dedupeBindings(records) {
2183
+ const byId = /* @__PURE__ */ new Map();
2184
+ for (const record of records) {
2185
+ if (!record?.bindingId) continue;
2186
+ byId.set(record.bindingId, record);
2187
+ }
2188
+ return [...byId.values()];
2189
+ }
2190
+ function createDefaultSessionBindingService() {
2191
+ return {
2192
+ bind: async (input) => {
2193
+ const normalizedConversation = normalizeConversationRef(input.conversation);
2194
+ const adapter = resolveAdapterForConversation(normalizedConversation);
2195
+ if (!adapter?.bind) throw new Error(`Session binding adapter unavailable for ${normalizedConversation.channel}:${normalizedConversation.accountId}`);
2196
+ const bound = await adapter.bind({
2197
+ ...input,
2198
+ conversation: normalizedConversation
2199
+ });
2200
+ if (!bound) throw new Error("Session binding adapter failed to bind target conversation");
2201
+ return bound;
2202
+ },
2203
+ listBySession: (targetSessionKey) => {
2204
+ const key = targetSessionKey.trim();
2205
+ if (!key) return [];
2206
+ const results = [];
2207
+ for (const adapter of ADAPTERS_BY_CHANNEL_ACCOUNT.values()) {
2208
+ const entries = adapter.listBySession(key);
2209
+ if (entries.length > 0) results.push(...entries);
2210
+ }
2211
+ return dedupeBindings(results);
2212
+ },
2213
+ resolveByConversation: (ref) => {
2214
+ const normalized = normalizeConversationRef(ref);
2215
+ if (!normalized.channel || !normalized.conversationId) return null;
2216
+ const adapter = resolveAdapterForConversation(normalized);
2217
+ if (!adapter) return null;
2218
+ return adapter.resolveByConversation(normalized);
2219
+ },
2220
+ touch: (bindingId, at) => {
2221
+ const normalizedBindingId = bindingId.trim();
2222
+ if (!normalizedBindingId) return;
2223
+ for (const adapter of ADAPTERS_BY_CHANNEL_ACCOUNT.values()) adapter.touch?.(normalizedBindingId, at);
2224
+ },
2225
+ unbind: async (input) => {
2226
+ const removed = [];
2227
+ for (const adapter of ADAPTERS_BY_CHANNEL_ACCOUNT.values()) {
2228
+ if (!adapter.unbind) continue;
2229
+ const entries = await adapter.unbind(input);
2230
+ if (entries.length > 0) removed.push(...entries);
2231
+ }
2232
+ return dedupeBindings(removed);
2233
+ }
2234
+ };
2235
+ }
2236
+ const DEFAULT_SESSION_BINDING_SERVICE = createDefaultSessionBindingService();
2237
+ function getSessionBindingService() {
2238
+ return DEFAULT_SESSION_BINDING_SERVICE;
2239
+ }
2240
+
2241
+ //#endregion
2242
+ //#region src/infra/outbound/bound-delivery-router.ts
2243
+ function isActiveBinding(record) {
2244
+ return record.status === "active";
2245
+ }
2246
+ function resolveBindingForRequester(requester, bindings) {
2247
+ const matchingChannelAccount = bindings.filter((entry) => entry.conversation.channel === requester.channel && entry.conversation.accountId === requester.accountId);
2248
+ if (matchingChannelAccount.length === 0) return null;
2249
+ const exactConversation = matchingChannelAccount.find((entry) => entry.conversation.conversationId === requester.conversationId);
2250
+ if (exactConversation) return exactConversation;
2251
+ if (matchingChannelAccount.length === 1) return matchingChannelAccount[0] ?? null;
2252
+ return null;
2253
+ }
2254
+ function createBoundDeliveryRouter(service = getSessionBindingService()) {
2255
+ return { resolveDestination: (input) => {
2256
+ const targetSessionKey = input.targetSessionKey.trim();
2257
+ if (!targetSessionKey) return {
2258
+ binding: null,
2259
+ mode: "fallback",
2260
+ reason: "missing-target-session"
2261
+ };
2262
+ const activeBindings = service.listBySession(targetSessionKey).filter(isActiveBinding);
2263
+ if (activeBindings.length === 0) return {
2264
+ binding: null,
2265
+ mode: "fallback",
2266
+ reason: "no-active-binding"
2267
+ };
2268
+ if (!input.requester) {
2269
+ if (activeBindings.length === 1) return {
2270
+ binding: activeBindings[0] ?? null,
2271
+ mode: "bound",
2272
+ reason: "single-active-binding"
2273
+ };
2274
+ return {
2275
+ binding: null,
2276
+ mode: "fallback",
2277
+ reason: "ambiguous-without-requester"
2278
+ };
2279
+ }
2280
+ const requester = {
2281
+ channel: input.requester.channel.trim().toLowerCase(),
2282
+ accountId: input.requester.accountId.trim(),
2283
+ conversationId: input.requester.conversationId.trim(),
2284
+ parentConversationId: input.requester.parentConversationId?.trim() || void 0
2285
+ };
2286
+ if (!requester.channel || !requester.conversationId) return {
2287
+ binding: null,
2288
+ mode: "fallback",
2289
+ reason: "invalid-requester"
2290
+ };
2291
+ const fromRequester = resolveBindingForRequester(requester, activeBindings);
2292
+ if (fromRequester) return {
2293
+ binding: fromRequester,
2294
+ mode: "bound",
2295
+ reason: "requester-match"
2296
+ };
2297
+ if (activeBindings.length === 1 && !input.failClosed) return {
2298
+ binding: activeBindings[0] ?? null,
2299
+ mode: "bound",
2300
+ reason: "single-active-binding-fallback"
2301
+ };
2302
+ return {
2303
+ binding: null,
2304
+ mode: "fallback",
2305
+ reason: "no-requester-match"
2306
+ };
2307
+ } };
2308
+ }
2309
+
2310
+ //#endregion
2311
+ //#region src/shared/chat-content.ts
2312
+ function extractTextFromChatContent(content, opts) {
2313
+ const normalize = opts?.normalizeText ?? ((text) => text.replace(/\s+/g, " ").trim());
2314
+ const joinWith = opts?.joinWith ?? " ";
2315
+ if (typeof content === "string") {
2316
+ const normalized = normalize(opts?.sanitizeText ? opts.sanitizeText(content) : content);
2317
+ return normalized ? normalized : null;
2318
+ }
2319
+ if (!Array.isArray(content)) return null;
2320
+ const chunks = [];
2321
+ for (const block of content) {
2322
+ if (!block || typeof block !== "object") continue;
2323
+ if (block.type !== "text") continue;
2324
+ const text = block.text;
2325
+ if (typeof text !== "string") continue;
2326
+ const value = opts?.sanitizeText ? opts.sanitizeText(text) : text;
2327
+ if (value.trim()) chunks.push(value);
2328
+ }
2329
+ const joined = normalize(chunks.join(joinWith));
2330
+ return joined ? joined : null;
2331
+ }
2332
+
2333
+ //#endregion
2334
+ //#region src/agents/announce-idempotency.ts
2335
+ function buildAnnounceIdFromChildRun(params) {
2336
+ return `v1:${params.childSessionKey}:${params.childRunId}`;
2337
+ }
2338
+ function buildAnnounceIdempotencyKey(announceId) {
2339
+ return `announce:${announceId}`;
2340
+ }
2341
+
2342
+ //#endregion
2343
+ //#region src/agents/subagent-depth.ts
2344
+ function normalizeSpawnDepth(value) {
2345
+ if (typeof value === "number") return Number.isInteger(value) && value >= 0 ? value : void 0;
2346
+ if (typeof value === "string") {
2347
+ const trimmed = value.trim();
2348
+ if (!trimmed) return;
2349
+ const numeric = Number(trimmed);
2350
+ return Number.isInteger(numeric) && numeric >= 0 ? numeric : void 0;
2351
+ }
2352
+ }
2353
+ function normalizeSessionKey(value) {
2354
+ if (typeof value !== "string") return;
2355
+ return value.trim() || void 0;
2356
+ }
2357
+ function readSessionStore(storePath) {
2358
+ try {
2359
+ const raw = fs.readFileSync(storePath, "utf-8");
2360
+ const parsed = JSON5.parse(raw);
2361
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
2362
+ } catch {}
2363
+ return {};
2364
+ }
2365
+ function buildKeyCandidates(rawKey, cfg) {
2366
+ if (!cfg) return [rawKey];
2367
+ if (rawKey === "global" || rawKey === "unknown") return [rawKey];
2368
+ if (parseAgentSessionKey(rawKey)) return [rawKey];
2369
+ const prefixed = `agent:${resolveDefaultAgentId(cfg)}:${rawKey}`;
2370
+ return prefixed === rawKey ? [rawKey] : [rawKey, prefixed];
2371
+ }
2372
+ function findEntryBySessionId(store, sessionId) {
2373
+ const normalizedSessionId = normalizeSessionKey(sessionId);
2374
+ if (!normalizedSessionId) return;
2375
+ for (const entry of Object.values(store)) {
2376
+ const candidateSessionId = normalizeSessionKey(entry?.sessionId);
2377
+ if (candidateSessionId && candidateSessionId === normalizedSessionId) return entry;
2378
+ }
2379
+ }
2380
+ function resolveEntryForSessionKey(params) {
2381
+ const candidates = buildKeyCandidates(params.sessionKey, params.cfg);
2382
+ if (params.store) {
2383
+ for (const key of candidates) {
2384
+ const entry = params.store[key];
2385
+ if (entry) return entry;
2386
+ }
2387
+ return findEntryBySessionId(params.store, params.sessionKey);
2388
+ }
2389
+ if (!params.cfg) return;
2390
+ for (const key of candidates) {
2391
+ const parsed = parseAgentSessionKey(key);
2392
+ if (!parsed?.agentId) continue;
2393
+ const storePath = resolveStorePath(params.cfg.session?.store, { agentId: parsed.agentId });
2394
+ let store = params.cache.get(storePath);
2395
+ if (!store) {
2396
+ store = readSessionStore(storePath);
2397
+ params.cache.set(storePath, store);
2398
+ }
2399
+ const entry = store[key] ?? findEntryBySessionId(store, params.sessionKey);
2400
+ if (entry) return entry;
2401
+ }
2402
+ }
2403
+ function getSubagentDepthFromSessionStore(sessionKey, opts) {
2404
+ const raw = (sessionKey ?? "").trim();
2405
+ const fallbackDepth = getSubagentDepth(raw);
2406
+ if (!raw) return fallbackDepth;
2407
+ const cache = /* @__PURE__ */ new Map();
2408
+ const visited = /* @__PURE__ */ new Set();
2409
+ const depthFromStore = (key) => {
2410
+ const normalizedKey = normalizeSessionKey(key);
2411
+ if (!normalizedKey) return;
2412
+ if (visited.has(normalizedKey)) return;
2413
+ visited.add(normalizedKey);
2414
+ const entry = resolveEntryForSessionKey({
2415
+ sessionKey: normalizedKey,
2416
+ cfg: opts?.cfg,
2417
+ store: opts?.store,
2418
+ cache
2419
+ });
2420
+ const storedDepth = normalizeSpawnDepth(entry?.spawnDepth);
2421
+ if (storedDepth !== void 0) return storedDepth;
2422
+ const spawnedBy = normalizeSessionKey(entry?.spawnedBy);
2423
+ if (!spawnedBy) return;
2424
+ const parentDepth = depthFromStore(spawnedBy);
2425
+ if (parentDepth !== void 0) return parentDepth + 1;
2426
+ return getSubagentDepth(spawnedBy) + 1;
2427
+ };
2428
+ return depthFromStore(raw) ?? fallbackDepth;
2429
+ }
2430
+
2431
+ //#endregion
2432
+ //#region src/agents/tools/sessions-resolution.ts
2433
+ function resolveMainSessionAlias(cfg) {
2434
+ const mainKey = normalizeMainKey(cfg.session?.mainKey);
2435
+ const scope = cfg.session?.scope ?? "per-sender";
2436
+ return {
2437
+ mainKey,
2438
+ alias: scope === "global" ? "global" : mainKey,
2439
+ scope
2440
+ };
2441
+ }
2442
+ function resolveDisplaySessionKey(params) {
2443
+ if (params.key === params.alias) return "main";
2444
+ if (params.key === params.mainKey) return "main";
2445
+ return params.key;
2446
+ }
2447
+ function resolveInternalSessionKey(params) {
2448
+ if (params.key === "main") return params.alias;
2449
+ return params.key;
2450
+ }
2451
+ async function listSpawnedSessionKeys(params) {
2452
+ const limit = typeof params.limit === "number" && Number.isFinite(params.limit) ? Math.max(1, Math.floor(params.limit)) : 500;
2453
+ try {
2454
+ const list = await callGateway({
2455
+ method: "sessions.list",
2456
+ params: {
2457
+ includeGlobal: false,
2458
+ includeUnknown: false,
2459
+ limit,
2460
+ spawnedBy: params.requesterSessionKey
2461
+ }
2462
+ });
2463
+ const keys = (Array.isArray(list?.sessions) ? list.sessions : []).map((entry) => typeof entry?.key === "string" ? entry.key : "").map((value) => value.trim()).filter(Boolean);
2464
+ return new Set(keys);
2465
+ } catch {
2466
+ return /* @__PURE__ */ new Set();
2467
+ }
2468
+ }
2469
+ async function isRequesterSpawnedSessionVisible(params) {
2470
+ if (params.requesterSessionKey === params.targetSessionKey) return true;
2471
+ return (await listSpawnedSessionKeys({
2472
+ requesterSessionKey: params.requesterSessionKey,
2473
+ limit: params.limit
2474
+ })).has(params.targetSessionKey);
2475
+ }
2476
+ function shouldVerifyRequesterSpawnedSessionVisibility(params) {
2477
+ return params.restrictToSpawned && !params.resolvedViaSessionId && params.requesterSessionKey !== params.targetSessionKey;
2478
+ }
2479
+ async function isResolvedSessionVisibleToRequester(params) {
2480
+ if (!shouldVerifyRequesterSpawnedSessionVisibility({
2481
+ requesterSessionKey: params.requesterSessionKey,
2482
+ targetSessionKey: params.targetSessionKey,
2483
+ restrictToSpawned: params.restrictToSpawned,
2484
+ resolvedViaSessionId: params.resolvedViaSessionId
2485
+ })) return true;
2486
+ return await isRequesterSpawnedSessionVisible({
2487
+ requesterSessionKey: params.requesterSessionKey,
2488
+ targetSessionKey: params.targetSessionKey,
2489
+ limit: params.limit
2490
+ });
2491
+ }
2492
+ const SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2493
+ function looksLikeSessionId(value) {
2494
+ return SESSION_ID_RE.test(value.trim());
2495
+ }
2496
+ function looksLikeSessionKey(value) {
2497
+ const raw = value.trim();
2498
+ if (!raw) return false;
2499
+ if (raw === "main" || raw === "global" || raw === "unknown") return true;
2500
+ if (isAcpSessionKey(raw)) return true;
2501
+ if (raw.startsWith("agent:")) return true;
2502
+ if (raw.startsWith("cron:") || raw.startsWith("hook:")) return true;
2503
+ if (raw.startsWith("node-") || raw.startsWith("node:")) return true;
2504
+ if (raw.includes(":group:") || raw.includes(":channel:")) return true;
2505
+ return false;
2506
+ }
2507
+ function shouldResolveSessionIdInput(value) {
2508
+ return looksLikeSessionId(value) || !looksLikeSessionKey(value);
2509
+ }
2510
+ async function resolveSessionKeyFromSessionId(params) {
2511
+ try {
2512
+ const result = await callGateway({
2513
+ method: "sessions.resolve",
2514
+ params: {
2515
+ sessionId: params.sessionId,
2516
+ spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0,
2517
+ includeGlobal: !params.restrictToSpawned,
2518
+ includeUnknown: !params.restrictToSpawned
2519
+ }
2520
+ });
2521
+ const key = typeof result?.key === "string" ? result.key.trim() : "";
2522
+ if (!key) throw new Error(`Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`);
2523
+ return {
2524
+ ok: true,
2525
+ key,
2526
+ displayKey: resolveDisplaySessionKey({
2527
+ key,
2528
+ alias: params.alias,
2529
+ mainKey: params.mainKey
2530
+ }),
2531
+ resolvedViaSessionId: true
2532
+ };
2533
+ } catch (err) {
2534
+ if (params.restrictToSpawned) return {
2535
+ ok: false,
2536
+ status: "forbidden",
2537
+ error: `Session not visible from this sandboxed agent session: ${params.sessionId}`
2538
+ };
2539
+ return {
2540
+ ok: false,
2541
+ status: "error",
2542
+ error: (err instanceof Error ? err.message : String(err)) || `Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`
2543
+ };
2544
+ }
2545
+ }
2546
+ async function resolveSessionKeyFromKey(params) {
2547
+ try {
2548
+ const result = await callGateway({
2549
+ method: "sessions.resolve",
2550
+ params: {
2551
+ key: params.key,
2552
+ spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0
2553
+ }
2554
+ });
2555
+ const key = typeof result?.key === "string" ? result.key.trim() : "";
2556
+ if (!key) return null;
2557
+ return {
2558
+ ok: true,
2559
+ key,
2560
+ displayKey: resolveDisplaySessionKey({
2561
+ key,
2562
+ alias: params.alias,
2563
+ mainKey: params.mainKey
2564
+ }),
2565
+ resolvedViaSessionId: false
2566
+ };
2567
+ } catch {
2568
+ return null;
2569
+ }
2570
+ }
2571
+ async function resolveSessionReference(params) {
2572
+ const raw = params.sessionKey.trim();
2573
+ if (shouldResolveSessionIdInput(raw)) {
2574
+ const resolvedByKey = await resolveSessionKeyFromKey({
2575
+ key: raw,
2576
+ alias: params.alias,
2577
+ mainKey: params.mainKey,
2578
+ requesterInternalKey: params.requesterInternalKey,
2579
+ restrictToSpawned: params.restrictToSpawned
2580
+ });
2581
+ if (resolvedByKey) return resolvedByKey;
2582
+ return await resolveSessionKeyFromSessionId({
2583
+ sessionId: raw,
2584
+ alias: params.alias,
2585
+ mainKey: params.mainKey,
2586
+ requesterInternalKey: params.requesterInternalKey,
2587
+ restrictToSpawned: params.restrictToSpawned
2588
+ });
2589
+ }
2590
+ const resolvedKey = resolveInternalSessionKey({
2591
+ key: raw,
2592
+ alias: params.alias,
2593
+ mainKey: params.mainKey
2594
+ });
2595
+ return {
2596
+ ok: true,
2597
+ key: resolvedKey,
2598
+ displayKey: resolveDisplaySessionKey({
2599
+ key: resolvedKey,
2600
+ alias: params.alias,
2601
+ mainKey: params.mainKey
2602
+ }),
2603
+ resolvedViaSessionId: false
2604
+ };
2605
+ }
2606
+
2607
+ //#endregion
2608
+ //#region src/agents/tools/sessions-access.ts
2609
+ function resolveSessionToolsVisibility(cfg) {
2610
+ const raw = cfg.tools?.sessions?.visibility;
2611
+ const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
2612
+ if (value === "self" || value === "tree" || value === "agent" || value === "all") return value;
2613
+ return "tree";
2614
+ }
2615
+ function resolveEffectiveSessionToolsVisibility(params) {
2616
+ const visibility = resolveSessionToolsVisibility(params.cfg);
2617
+ if (!params.sandboxed) return visibility;
2618
+ if ((params.cfg.agents?.defaults?.sandbox?.sessionToolsVisibility ?? "spawned") === "spawned" && visibility !== "tree") return "tree";
2619
+ return visibility;
2620
+ }
2621
+ function resolveSandboxSessionToolsVisibility(cfg) {
2622
+ return cfg.agents?.defaults?.sandbox?.sessionToolsVisibility ?? "spawned";
2623
+ }
2624
+ function resolveSandboxedSessionToolContext(params) {
2625
+ const { mainKey, alias } = resolveMainSessionAlias(params.cfg);
2626
+ const visibility = resolveSandboxSessionToolsVisibility(params.cfg);
2627
+ const requesterInternalKey = typeof params.agentSessionKey === "string" && params.agentSessionKey.trim() ? resolveInternalSessionKey({
2628
+ key: params.agentSessionKey,
2629
+ alias,
2630
+ mainKey
2631
+ }) : void 0;
2632
+ return {
2633
+ mainKey,
2634
+ alias,
2635
+ visibility,
2636
+ requesterInternalKey,
2637
+ effectiveRequesterKey: requesterInternalKey ?? alias,
2638
+ restrictToSpawned: params.sandboxed === true && visibility === "spawned" && !!requesterInternalKey && !isSubagentSessionKey(requesterInternalKey)
2639
+ };
2640
+ }
2641
+ function createAgentToAgentPolicy(cfg) {
2642
+ const routingA2A = cfg.tools?.agentToAgent;
2643
+ const enabled = routingA2A?.enabled === true;
2644
+ const allowPatterns = Array.isArray(routingA2A?.allow) ? routingA2A.allow : [];
2645
+ const matchesAllow = (agentId) => {
2646
+ if (allowPatterns.length === 0) return true;
2647
+ return allowPatterns.some((pattern) => {
2648
+ const raw = String(pattern ?? "").trim();
2649
+ if (!raw) return false;
2650
+ if (raw === "*") return true;
2651
+ if (!raw.includes("*")) return raw === agentId;
2652
+ const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2653
+ return new RegExp(`^${escaped.replaceAll("\\*", ".*")}$`, "i").test(agentId);
2654
+ });
2655
+ };
2656
+ const isAllowed = (requesterAgentId, targetAgentId) => {
2657
+ if (requesterAgentId === targetAgentId) return true;
2658
+ if (!enabled) return false;
2659
+ return matchesAllow(requesterAgentId) && matchesAllow(targetAgentId);
2660
+ };
2661
+ return {
2662
+ enabled,
2663
+ matchesAllow,
2664
+ isAllowed
2665
+ };
2666
+ }
2667
+ function actionPrefix(action) {
2668
+ if (action === "history") return "Session history";
2669
+ if (action === "send") return "Session send";
2670
+ return "Session list";
2671
+ }
2672
+ function a2aDisabledMessage(action) {
2673
+ if (action === "history") return "Agent-to-agent history is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent access.";
2674
+ if (action === "send") return "Agent-to-agent messaging is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent sends.";
2675
+ return "Agent-to-agent listing is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent visibility.";
2676
+ }
2677
+ function a2aDeniedMessage(action) {
2678
+ if (action === "history") return "Agent-to-agent history denied by tools.agentToAgent.allow.";
2679
+ if (action === "send") return "Agent-to-agent messaging denied by tools.agentToAgent.allow.";
2680
+ return "Agent-to-agent listing denied by tools.agentToAgent.allow.";
2681
+ }
2682
+ function crossVisibilityMessage(action) {
2683
+ if (action === "history") return "Session history visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
2684
+ if (action === "send") return "Session send visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
2685
+ return "Session list visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
2686
+ }
2687
+ function selfVisibilityMessage(action) {
2688
+ return `${actionPrefix(action)} visibility is restricted to the current session (tools.sessions.visibility=self).`;
2689
+ }
2690
+ function treeVisibilityMessage(action) {
2691
+ return `${actionPrefix(action)} visibility is restricted to the current session tree (tools.sessions.visibility=tree).`;
2692
+ }
2693
+ async function createSessionVisibilityGuard(params) {
2694
+ const requesterAgentId = resolveAgentIdFromSessionKey(params.requesterSessionKey);
2695
+ const spawnedKeys = params.visibility === "tree" ? await listSpawnedSessionKeys({ requesterSessionKey: params.requesterSessionKey }) : null;
2696
+ const check = (targetSessionKey) => {
2697
+ const targetAgentId = resolveAgentIdFromSessionKey(targetSessionKey);
2698
+ if (targetAgentId !== requesterAgentId) {
2699
+ if (params.visibility !== "all") return {
2700
+ allowed: false,
2701
+ status: "forbidden",
2702
+ error: crossVisibilityMessage(params.action)
2703
+ };
2704
+ if (!params.a2aPolicy.enabled) return {
2705
+ allowed: false,
2706
+ status: "forbidden",
2707
+ error: a2aDisabledMessage(params.action)
2708
+ };
2709
+ if (!params.a2aPolicy.isAllowed(requesterAgentId, targetAgentId)) return {
2710
+ allowed: false,
2711
+ status: "forbidden",
2712
+ error: a2aDeniedMessage(params.action)
2713
+ };
2714
+ return { allowed: true };
2715
+ }
2716
+ if (params.visibility === "self" && targetSessionKey !== params.requesterSessionKey) return {
2717
+ allowed: false,
2718
+ status: "forbidden",
2719
+ error: selfVisibilityMessage(params.action)
2720
+ };
2721
+ if (params.visibility === "tree" && targetSessionKey !== params.requesterSessionKey && !spawnedKeys?.has(targetSessionKey)) return {
2722
+ allowed: false,
2723
+ status: "forbidden",
2724
+ error: treeVisibilityMessage(params.action)
2725
+ };
2726
+ return { allowed: true };
2727
+ };
2728
+ return { check };
2729
+ }
2730
+
2731
+ //#endregion
2732
+ //#region src/shared/text/code-regions.ts
2733
+ function findCodeRegions(text) {
2734
+ const regions = [];
2735
+ for (const match of text.matchAll(/(^|\n)(```|~~~)[^\n]*\n[\s\S]*?(?:\n\2(?:\n|$)|$)/g)) {
2736
+ const start = (match.index ?? 0) + match[1].length;
2737
+ regions.push({
2738
+ start,
2739
+ end: start + match[0].length - match[1].length
2740
+ });
2741
+ }
2742
+ for (const match of text.matchAll(/`+[^`]+`+/g)) {
2743
+ const start = match.index ?? 0;
2744
+ const end = start + match[0].length;
2745
+ if (!regions.some((r) => start >= r.start && end <= r.end)) regions.push({
2746
+ start,
2747
+ end
2748
+ });
2749
+ }
2750
+ regions.sort((a, b) => a.start - b.start);
2751
+ return regions;
2752
+ }
2753
+ function isInsideCode(pos, regions) {
2754
+ return regions.some((r) => pos >= r.start && pos < r.end);
2755
+ }
2756
+
2757
+ //#endregion
2758
+ //#region src/shared/text/reasoning-tags.ts
2759
+ const QUICK_TAG_RE = /<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i;
2760
+ const FINAL_TAG_RE = /<\s*\/?\s*final\b[^<>]*>/gi;
2761
+ const THINKING_TAG_RE = /<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^<>]*>/gi;
2762
+ function applyTrim(value, mode) {
2763
+ if (mode === "none") return value;
2764
+ if (mode === "start") return value.trimStart();
2765
+ return value.trim();
2766
+ }
2767
+ function stripReasoningTagsFromText(text, options) {
2768
+ if (!text) return text;
2769
+ if (!QUICK_TAG_RE.test(text)) return text;
2770
+ const mode = options?.mode ?? "strict";
2771
+ const trimMode = options?.trim ?? "both";
2772
+ let cleaned = text;
2773
+ if (FINAL_TAG_RE.test(cleaned)) {
2774
+ FINAL_TAG_RE.lastIndex = 0;
2775
+ const finalMatches = [];
2776
+ const preCodeRegions = findCodeRegions(cleaned);
2777
+ for (const match of cleaned.matchAll(FINAL_TAG_RE)) {
2778
+ const start = match.index ?? 0;
2779
+ finalMatches.push({
2780
+ start,
2781
+ length: match[0].length,
2782
+ inCode: isInsideCode(start, preCodeRegions)
2783
+ });
2784
+ }
2785
+ for (let i = finalMatches.length - 1; i >= 0; i--) {
2786
+ const m = finalMatches[i];
2787
+ if (!m.inCode) cleaned = cleaned.slice(0, m.start) + cleaned.slice(m.start + m.length);
2788
+ }
2789
+ } else FINAL_TAG_RE.lastIndex = 0;
2790
+ const codeRegions = findCodeRegions(cleaned);
2791
+ THINKING_TAG_RE.lastIndex = 0;
2792
+ let result = "";
2793
+ let lastIndex = 0;
2794
+ let inThinking = false;
2795
+ for (const match of cleaned.matchAll(THINKING_TAG_RE)) {
2796
+ const idx = match.index ?? 0;
2797
+ const isClose = match[1] === "/";
2798
+ if (isInsideCode(idx, codeRegions)) continue;
2799
+ if (!inThinking) {
2800
+ result += cleaned.slice(lastIndex, idx);
2801
+ if (!isClose) inThinking = true;
2802
+ } else if (isClose) inThinking = false;
2803
+ lastIndex = idx + match[0].length;
2804
+ }
2805
+ if (!inThinking || mode === "preserve") result += cleaned.slice(lastIndex);
2806
+ return applyTrim(result, trimMode);
2807
+ }
2808
+
2809
+ //#endregion
2810
+ //#region src/agents/agent-utils.ts
2811
+ /**
2812
+ * Strip malformed Minimax tool invocations that leak into text content.
2813
+ * Minimax sometimes embeds tool calls as XML in text blocks instead of
2814
+ * proper structured tool calls. This removes:
2815
+ * - <invoke name="...">...</invoke> blocks
2816
+ * - </minimax:tool_call> closing tags
2817
+ */
2818
+ function stripMinimaxToolCallXml(text) {
2819
+ if (!text) return text;
2820
+ if (!/minimax:tool_call/i.test(text)) return text;
2821
+ let cleaned = text.replace(/<invoke\b[^>]*>[\s\S]*?<\/invoke>/gi, "");
2822
+ cleaned = cleaned.replace(/<\/?minimax:tool_call>/gi, "");
2823
+ return cleaned;
2824
+ }
2825
+ /**
2826
+ * Strip downgraded tool call text representations that leak into text content.
2827
+ * When replaying history to Gemini, tool calls without `thought_signature` are
2828
+ * downgraded to text blocks like `[Tool Call: name (ID: ...)]`. These should
2829
+ * not be shown to users.
2830
+ */
2831
+ function stripDowngradedToolCallText(text) {
2832
+ if (!text) return text;
2833
+ if (!/\[Tool (?:Call|Result)/i.test(text) && !/\[Historical context/i.test(text)) return text;
2834
+ const consumeJsonish = (input, start, options) => {
2835
+ const { allowLeadingNewlines = false } = options ?? {};
2836
+ let index = start;
2837
+ while (index < input.length) {
2838
+ const ch = input[index];
2839
+ if (ch === " " || ch === " ") {
2840
+ index += 1;
2841
+ continue;
2842
+ }
2843
+ if (allowLeadingNewlines && (ch === "\n" || ch === "\r")) {
2844
+ index += 1;
2845
+ continue;
2846
+ }
2847
+ break;
2848
+ }
2849
+ if (index >= input.length) return null;
2850
+ const startChar = input[index];
2851
+ if (startChar === "{" || startChar === "[") {
2852
+ let depth = 0;
2853
+ let inString = false;
2854
+ let escape = false;
2855
+ for (let i = index; i < input.length; i += 1) {
2856
+ const ch = input[i];
2857
+ if (inString) {
2858
+ if (escape) escape = false;
2859
+ else if (ch === "\\") escape = true;
2860
+ else if (ch === "\"") inString = false;
2861
+ continue;
2862
+ }
2863
+ if (ch === "\"") {
2864
+ inString = true;
2865
+ continue;
2866
+ }
2867
+ if (ch === "{" || ch === "[") {
2868
+ depth += 1;
2869
+ continue;
2870
+ }
2871
+ if (ch === "}" || ch === "]") {
2872
+ depth -= 1;
2873
+ if (depth === 0) return i + 1;
2874
+ }
2875
+ }
2876
+ return null;
2877
+ }
2878
+ if (startChar === "\"") {
2879
+ let escape = false;
2880
+ for (let i = index + 1; i < input.length; i += 1) {
2881
+ const ch = input[i];
2882
+ if (escape) {
2883
+ escape = false;
2884
+ continue;
2885
+ }
2886
+ if (ch === "\\") {
2887
+ escape = true;
2888
+ continue;
2889
+ }
2890
+ if (ch === "\"") return i + 1;
2891
+ }
2892
+ return null;
2893
+ }
2894
+ let end = index;
2895
+ while (end < input.length && input[end] !== "\n" && input[end] !== "\r") end += 1;
2896
+ return end;
2897
+ };
2898
+ const stripToolCalls = (input) => {
2899
+ const markerRe = /\[Tool Call:[^\]]*\]/gi;
2900
+ let result = "";
2901
+ let cursor = 0;
2902
+ for (const match of input.matchAll(markerRe)) {
2903
+ const start = match.index ?? 0;
2904
+ if (start < cursor) continue;
2905
+ result += input.slice(cursor, start);
2906
+ let index = start + match[0].length;
2907
+ while (index < input.length && (input[index] === " " || input[index] === " ")) index += 1;
2908
+ if (input[index] === "\r") {
2909
+ index += 1;
2910
+ if (input[index] === "\n") index += 1;
2911
+ } else if (input[index] === "\n") index += 1;
2912
+ while (index < input.length && (input[index] === " " || input[index] === " ")) index += 1;
2913
+ if (input.slice(index, index + 9).toLowerCase() === "arguments") {
2914
+ index += 9;
2915
+ if (input[index] === ":") index += 1;
2916
+ if (input[index] === " ") index += 1;
2917
+ const end = consumeJsonish(input, index, { allowLeadingNewlines: true });
2918
+ if (end !== null) index = end;
2919
+ }
2920
+ if ((input[index] === "\n" || input[index] === "\r") && (result.endsWith("\n") || result.endsWith("\r") || result.length === 0)) {
2921
+ if (input[index] === "\r") index += 1;
2922
+ if (input[index] === "\n") index += 1;
2923
+ }
2924
+ cursor = index;
2925
+ }
2926
+ result += input.slice(cursor);
2927
+ return result;
2928
+ };
2929
+ let cleaned = stripToolCalls(text);
2930
+ cleaned = cleaned.replace(/\[Tool Result for ID[^\]]*\]\n?[\s\S]*?(?=\n*\[Tool |\n*$)/gi, "");
2931
+ cleaned = cleaned.replace(/\[Historical context:[^\]]*\]\n?/gi, "");
2932
+ return cleaned.trim();
2933
+ }
2934
+ /**
2935
+ * Strip thinking tags and their content from text.
2936
+ * This is a safety net for cases where the model outputs <think> tags
2937
+ * that slip through other filtering mechanisms.
2938
+ */
2939
+ function stripThinkingTagsFromText(text) {
2940
+ return stripReasoningTagsFromText(text, {
2941
+ mode: "strict",
2942
+ trim: "both"
2943
+ });
2944
+ }
2945
+
2946
+ //#endregion
2947
+ //#region src/agents/tools/sessions-helpers.ts
2948
+ function normalizeKey(value) {
2949
+ const trimmed = value?.trim();
2950
+ return trimmed ? trimmed : void 0;
2951
+ }
2952
+ function classifySessionKind(params) {
2953
+ const key = params.key;
2954
+ if (key === params.alias || key === params.mainKey) return "main";
2955
+ if (key.startsWith("cron:")) return "cron";
2956
+ if (key.startsWith("hook:")) return "hook";
2957
+ if (key.startsWith("node-") || key.startsWith("node:")) return "node";
2958
+ if (params.gatewayKind === "group") return "group";
2959
+ if (key.includes(":group:") || key.includes(":channel:")) return "group";
2960
+ return "other";
2961
+ }
2962
+ function deriveChannel(params) {
2963
+ if (params.kind === "cron" || params.kind === "hook" || params.kind === "node") return "internal";
2964
+ const channel = normalizeKey(params.channel ?? void 0);
2965
+ if (channel) return channel;
2966
+ const lastChannel = normalizeKey(params.lastChannel ?? void 0);
2967
+ if (lastChannel) return lastChannel;
2968
+ const parts = params.key.split(":").filter(Boolean);
2969
+ if (parts.length >= 3 && (parts[1] === "group" || parts[1] === "channel")) return parts[0];
2970
+ return "unknown";
2971
+ }
2972
+ function stripToolMessages(messages) {
2973
+ return messages.filter((msg) => {
2974
+ if (!msg || typeof msg !== "object") return true;
2975
+ const role = msg.role;
2976
+ return role !== "toolResult" && role !== "tool";
2977
+ });
2978
+ }
2979
+ /**
2980
+ * Sanitize text content to strip tool call markers and thinking tags.
2981
+ * This ensures user-facing text doesn't leak internal tool representations.
2982
+ */
2983
+ function sanitizeTextContent(text) {
2984
+ if (!text) return text;
2985
+ return stripThinkingTagsFromText(stripDowngradedToolCallText(stripMinimaxToolCallXml(text)));
2986
+ }
2987
+ function extractAssistantText(message) {
2988
+ if (!message || typeof message !== "object") return;
2989
+ if (message.role !== "assistant") return;
2990
+ const content = message.content;
2991
+ if (!Array.isArray(content)) return;
2992
+ const joined = extractTextFromChatContent(content, {
2993
+ sanitizeText: sanitizeTextContent,
2994
+ joinWith: "",
2995
+ normalizeText: (text) => text.trim()
2996
+ }) ?? "";
2997
+ const stopReason = message.stopReason;
2998
+ const errorMessage = message.errorMessage;
2999
+ const errorContext = stopReason === "error" || typeof errorMessage === "string" && Boolean(errorMessage.trim());
3000
+ return joined ? sanitizeUserFacingText(joined, { errorContext }) : void 0;
3001
+ }
3002
+
3003
+ //#endregion
3004
+ //#region src/agents/tools/agent-step.ts
3005
+ async function readLatestAssistantReply(params) {
3006
+ const history = await callGateway({
3007
+ method: "chat.history",
3008
+ params: {
3009
+ sessionKey: params.sessionKey,
3010
+ limit: params.limit ?? 50
3011
+ }
3012
+ });
3013
+ const filtered = stripToolMessages(Array.isArray(history?.messages) ? history.messages : []);
3014
+ for (let i = filtered.length - 1; i >= 0; i -= 1) {
3015
+ const candidate = filtered[i];
3016
+ if (!candidate || typeof candidate !== "object") continue;
3017
+ if (candidate.role !== "assistant") continue;
3018
+ const text = extractAssistantText(candidate);
3019
+ if (!text?.trim()) continue;
3020
+ return text;
3021
+ }
3022
+ }
3023
+ async function runAgentStep(params) {
3024
+ const stepIdem = crypto.randomUUID();
3025
+ const response = await callGateway({
3026
+ method: "agent",
3027
+ params: {
3028
+ message: params.message,
3029
+ sessionKey: params.sessionKey,
3030
+ idempotencyKey: stepIdem,
3031
+ deliver: false,
3032
+ channel: params.channel ?? INTERNAL_MESSAGE_CHANNEL,
3033
+ lane: params.lane ?? AGENT_LANE_NESTED,
3034
+ extraSystemPrompt: params.extraSystemPrompt,
3035
+ inputProvenance: {
3036
+ kind: "inter_session",
3037
+ sourceSessionKey: params.sourceSessionKey,
3038
+ sourceChannel: params.sourceChannel,
3039
+ sourceTool: params.sourceTool ?? "sessions_send"
3040
+ }
3041
+ },
3042
+ timeoutMs: 1e4
3043
+ });
3044
+ const resolvedRunId = (typeof response?.runId === "string" && response.runId ? response.runId : "") || stepIdem;
3045
+ const stepWaitMs = Math.min(params.timeoutMs, 6e4);
3046
+ if ((await callGateway({
3047
+ method: "agent.wait",
3048
+ params: {
3049
+ runId: resolvedRunId,
3050
+ timeoutMs: stepWaitMs
3051
+ },
3052
+ timeoutMs: stepWaitMs + 2e3
3053
+ }))?.status !== "ok") return;
3054
+ return await readLatestAssistantReply({ sessionKey: params.sessionKey });
3055
+ }
3056
+
3057
+ //#endregion
3058
+ //#region src/agents/tools/sessions-send-helpers.ts
3059
+ const ANNOUNCE_SKIP_TOKEN = "ANNOUNCE_SKIP";
3060
+ const REPLY_SKIP_TOKEN = "REPLY_SKIP";
3061
+ const DEFAULT_PING_PONG_TURNS = 5;
3062
+ const MAX_PING_PONG_TURNS = 5;
3063
+ function resolveAnnounceTargetFromKey(sessionKey) {
3064
+ const rawParts = sessionKey.split(":").filter(Boolean);
3065
+ const parts = rawParts.length >= 3 && rawParts[0] === "agent" ? rawParts.slice(2) : rawParts;
3066
+ if (parts.length < 3) return null;
3067
+ const [channelRaw, kind, ...rest] = parts;
3068
+ if (kind !== "group" && kind !== "channel") return null;
3069
+ let threadId;
3070
+ const restJoined = rest.join(":");
3071
+ const topicMatch = restJoined.match(/:topic:(\d+)$/);
3072
+ const threadMatch = restJoined.match(/:thread:(\d+)$/);
3073
+ const match = topicMatch || threadMatch;
3074
+ if (match) threadId = match[1];
3075
+ const id = match ? restJoined.replace(/:(topic|thread):\d+$/, "") : restJoined.trim();
3076
+ if (!id) return null;
3077
+ if (!channelRaw) return null;
3078
+ const normalizedChannel = normalizeChannelId$1(channelRaw) ?? normalizeChannelId(channelRaw);
3079
+ const channel = normalizedChannel ?? channelRaw.toLowerCase();
3080
+ const kindTarget = (() => {
3081
+ if (!normalizedChannel) return id;
3082
+ if (normalizedChannel === "discord" || normalizedChannel === "slack") return `channel:${id}`;
3083
+ return kind === "channel" ? `channel:${id}` : `group:${id}`;
3084
+ })();
3085
+ return {
3086
+ channel,
3087
+ to: (normalizedChannel ? getChannelPlugin(normalizedChannel)?.messaging?.normalizeTarget?.(kindTarget) : void 0) ?? kindTarget,
3088
+ threadId
3089
+ };
3090
+ }
3091
+ function buildAgentToAgentMessageContext(params) {
3092
+ return [
3093
+ "Agent-to-agent message context:",
3094
+ params.requesterSessionKey ? `Agent 1 (requester) session: ${params.requesterSessionKey}.` : void 0,
3095
+ params.requesterChannel ? `Agent 1 (requester) channel: ${params.requesterChannel}.` : void 0,
3096
+ `Agent 2 (target) session: ${params.targetSessionKey}.`
3097
+ ].filter(Boolean).join("\n");
3098
+ }
3099
+ function buildAgentToAgentReplyContext(params) {
3100
+ return [
3101
+ "Agent-to-agent reply step:",
3102
+ `Current agent: ${params.currentRole === "requester" ? "Agent 1 (requester)" : "Agent 2 (target)"}.`,
3103
+ `Turn ${params.turn} of ${params.maxTurns}.`,
3104
+ params.requesterSessionKey ? `Agent 1 (requester) session: ${params.requesterSessionKey}.` : void 0,
3105
+ params.requesterChannel ? `Agent 1 (requester) channel: ${params.requesterChannel}.` : void 0,
3106
+ `Agent 2 (target) session: ${params.targetSessionKey}.`,
3107
+ params.targetChannel ? `Agent 2 (target) channel: ${params.targetChannel}.` : void 0,
3108
+ `If you want to stop the ping-pong, reply exactly "${REPLY_SKIP_TOKEN}".`
3109
+ ].filter(Boolean).join("\n");
3110
+ }
3111
+ function buildAgentToAgentAnnounceContext(params) {
3112
+ return [
3113
+ "Agent-to-agent announce step:",
3114
+ params.requesterSessionKey ? `Agent 1 (requester) session: ${params.requesterSessionKey}.` : void 0,
3115
+ params.requesterChannel ? `Agent 1 (requester) channel: ${params.requesterChannel}.` : void 0,
3116
+ `Agent 2 (target) session: ${params.targetSessionKey}.`,
3117
+ params.targetChannel ? `Agent 2 (target) channel: ${params.targetChannel}.` : void 0,
3118
+ `Original request: ${params.originalMessage}`,
3119
+ params.roundOneReply ? `Round 1 reply: ${params.roundOneReply}` : "Round 1 reply: (not available).",
3120
+ params.latestReply ? `Latest reply: ${params.latestReply}` : "Latest reply: (not available).",
3121
+ `If you want to remain silent, reply exactly "${ANNOUNCE_SKIP_TOKEN}".`,
3122
+ "Any other reply will be posted to the target channel.",
3123
+ "After this reply, the agent-to-agent conversation is over."
3124
+ ].filter(Boolean).join("\n");
3125
+ }
3126
+ function isAnnounceSkip(text) {
3127
+ return (text ?? "").trim() === ANNOUNCE_SKIP_TOKEN;
3128
+ }
3129
+ function isReplySkip(text) {
3130
+ return (text ?? "").trim() === REPLY_SKIP_TOKEN;
3131
+ }
3132
+ function resolvePingPongTurns(cfg) {
3133
+ const raw = cfg?.session?.agentToAgent?.maxPingPongTurns;
3134
+ const fallback = DEFAULT_PING_PONG_TURNS;
3135
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return fallback;
3136
+ const rounded = Math.floor(raw);
3137
+ return Math.max(0, Math.min(MAX_PING_PONG_TURNS, rounded));
3138
+ }
3139
+
3140
+ //#endregion
3141
+ //#region src/agents/subagent-announce.ts
3142
+ const FAST_TEST_MODE = process.env.REMOTECLAW_TEST_FAST === "1";
3143
+ const FAST_TEST_RETRY_INTERVAL_MS = 8;
3144
+ const FAST_TEST_REPLY_CHANGE_WAIT_MS = 20;
3145
+ const DEFAULT_SUBAGENT_ANNOUNCE_TIMEOUT_MS = 6e4;
3146
+ const MAX_TIMER_SAFE_TIMEOUT_MS = 2147e6;
3147
+ const DIRECT_ANNOUNCE_TRANSIENT_RETRY_DELAYS_MS = FAST_TEST_MODE ? [
3148
+ 8,
3149
+ 16,
3150
+ 32
3151
+ ] : [
3152
+ 5e3,
3153
+ 1e4,
3154
+ 2e4
3155
+ ];
3156
+ function resolveSubagentAnnounceTimeoutMs(cfg) {
3157
+ const configured = cfg.agents?.defaults?.subagents?.announceTimeoutMs;
3158
+ if (typeof configured !== "number" || !Number.isFinite(configured)) return DEFAULT_SUBAGENT_ANNOUNCE_TIMEOUT_MS;
3159
+ return Math.min(Math.max(1, Math.floor(configured)), MAX_TIMER_SAFE_TIMEOUT_MS);
3160
+ }
3161
+ function buildCompletionDeliveryMessage(params) {
3162
+ const findingsText = params.findings.trim();
3163
+ if (isAnnounceSkip(findingsText)) return "";
3164
+ const hasFindings = findingsText.length > 0 && findingsText !== "(no output)";
3165
+ const header = (() => {
3166
+ if (params.outcome?.status === "error") return params.spawnMode === "session" ? `❌ Subagent ${params.subagentName} failed this task (session remains active)` : `❌ Subagent ${params.subagentName} failed`;
3167
+ if (params.outcome?.status === "timeout") return params.spawnMode === "session" ? `⏱️ Subagent ${params.subagentName} timed out on this task (session remains active)` : `⏱️ Subagent ${params.subagentName} timed out`;
3168
+ return params.spawnMode === "session" ? `✅ Subagent ${params.subagentName} completed this task (session remains active)` : `✅ Subagent ${params.subagentName} finished`;
3169
+ })();
3170
+ if (!hasFindings) return header;
3171
+ return `${header}\n\n${findingsText}`;
3172
+ }
3173
+ function summarizeDeliveryError(error) {
3174
+ if (error instanceof Error) return error.message || "error";
3175
+ if (typeof error === "string") return error;
3176
+ if (error === void 0 || error === null) return "unknown error";
3177
+ try {
3178
+ return JSON.stringify(error);
3179
+ } catch {
3180
+ return "error";
3181
+ }
3182
+ }
3183
+ const TRANSIENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS = [
3184
+ /\berrorcode=unavailable\b/i,
3185
+ /\bstatus\s*[:=]\s*"?unavailable\b/i,
3186
+ /\bUNAVAILABLE\b/,
3187
+ /no active .* listener/i,
3188
+ /gateway not connected/i,
3189
+ /gateway closed \(1006/i,
3190
+ /gateway timeout/i,
3191
+ /\b(econnreset|econnrefused|etimedout|enotfound|ehostunreach|network error)\b/i
3192
+ ];
3193
+ const PERMANENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS = [
3194
+ /unsupported channel/i,
3195
+ /unknown channel/i,
3196
+ /chat not found/i,
3197
+ /user not found/i,
3198
+ /bot was blocked by the user/i,
3199
+ /forbidden: bot was kicked/i,
3200
+ /recipient is not a valid/i,
3201
+ /outbound not configured for channel/i
3202
+ ];
3203
+ function isTransientAnnounceDeliveryError(error) {
3204
+ const message = summarizeDeliveryError(error);
3205
+ if (!message) return false;
3206
+ if (PERMANENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS.some((re) => re.test(message))) return false;
3207
+ return TRANSIENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS.some((re) => re.test(message));
3208
+ }
3209
+ async function waitForAnnounceRetryDelay(ms, signal) {
3210
+ if (ms <= 0) return;
3211
+ if (!signal) {
3212
+ await new Promise((resolve) => setTimeout(resolve, ms));
3213
+ return;
3214
+ }
3215
+ if (signal.aborted) return;
3216
+ await new Promise((resolve) => {
3217
+ const timer = setTimeout(() => {
3218
+ signal.removeEventListener("abort", onAbort);
3219
+ resolve();
3220
+ }, ms);
3221
+ const onAbort = () => {
3222
+ clearTimeout(timer);
3223
+ signal.removeEventListener("abort", onAbort);
3224
+ resolve();
3225
+ };
3226
+ signal.addEventListener("abort", onAbort, { once: true });
3227
+ });
3228
+ }
3229
+ async function runAnnounceDeliveryWithRetry(params) {
3230
+ let retryIndex = 0;
3231
+ for (;;) {
3232
+ if (params.signal?.aborted) throw new Error("announce delivery aborted");
3233
+ try {
3234
+ return await params.run();
3235
+ } catch (err) {
3236
+ const delayMs = DIRECT_ANNOUNCE_TRANSIENT_RETRY_DELAYS_MS[retryIndex];
3237
+ if (delayMs == null || !isTransientAnnounceDeliveryError(err) || params.signal?.aborted) throw err;
3238
+ const nextAttempt = retryIndex + 2;
3239
+ const maxAttempts = DIRECT_ANNOUNCE_TRANSIENT_RETRY_DELAYS_MS.length + 1;
3240
+ defaultRuntime.log(`[warn] Subagent announce ${params.operation} transient failure, retrying ${nextAttempt}/${maxAttempts} in ${Math.round(delayMs / 1e3)}s: ${summarizeDeliveryError(err)}`);
3241
+ retryIndex += 1;
3242
+ await waitForAnnounceRetryDelay(delayMs, params.signal);
3243
+ }
3244
+ }
3245
+ }
3246
+ function extractToolResultText(content) {
3247
+ if (typeof content === "string") return sanitizeTextContent(content);
3248
+ if (content && typeof content === "object" && !Array.isArray(content)) {
3249
+ const obj = content;
3250
+ if (typeof obj.text === "string") return sanitizeTextContent(obj.text);
3251
+ if (typeof obj.output === "string") return sanitizeTextContent(obj.output);
3252
+ if (typeof obj.content === "string") return sanitizeTextContent(obj.content);
3253
+ if (typeof obj.result === "string") return sanitizeTextContent(obj.result);
3254
+ if (typeof obj.error === "string") return sanitizeTextContent(obj.error);
3255
+ if (typeof obj.summary === "string") return sanitizeTextContent(obj.summary);
3256
+ }
3257
+ if (!Array.isArray(content)) return "";
3258
+ return extractTextFromChatContent(content, {
3259
+ sanitizeText: sanitizeTextContent,
3260
+ normalizeText: (text) => text,
3261
+ joinWith: "\n"
3262
+ })?.trim() ?? "";
3263
+ }
3264
+ function extractInlineTextContent(content) {
3265
+ if (!Array.isArray(content)) return "";
3266
+ return extractTextFromChatContent(content, {
3267
+ sanitizeText: sanitizeTextContent,
3268
+ normalizeText: (text) => text.trim(),
3269
+ joinWith: ""
3270
+ }) ?? "";
3271
+ }
3272
+ function extractSubagentOutputText(message) {
3273
+ if (!message || typeof message !== "object") return "";
3274
+ const role = message.role;
3275
+ const content = message.content;
3276
+ if (role === "assistant") {
3277
+ const assistantText = extractAssistantText(message);
3278
+ if (assistantText) return assistantText;
3279
+ if (typeof content === "string") return sanitizeTextContent(content);
3280
+ if (Array.isArray(content)) return extractInlineTextContent(content);
3281
+ return "";
3282
+ }
3283
+ if (role === "toolResult" || role === "tool") return extractToolResultText(message.content);
3284
+ if (role == null) {
3285
+ if (typeof content === "string") return sanitizeTextContent(content);
3286
+ if (Array.isArray(content)) return extractInlineTextContent(content);
3287
+ }
3288
+ return "";
3289
+ }
3290
+ async function readLatestSubagentOutput(sessionKey) {
3291
+ try {
3292
+ const latestAssistant = await readLatestAssistantReply({
3293
+ sessionKey,
3294
+ limit: 50
3295
+ });
3296
+ if (latestAssistant?.trim()) return latestAssistant;
3297
+ } catch {}
3298
+ const history = await callGateway({
3299
+ method: "chat.history",
3300
+ params: {
3301
+ sessionKey,
3302
+ limit: 50
3303
+ }
3304
+ });
3305
+ const messages = Array.isArray(history?.messages) ? history.messages : [];
3306
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
3307
+ const msg = messages[i];
3308
+ const text = extractSubagentOutputText(msg);
3309
+ if (text) return text;
3310
+ }
3311
+ }
3312
+ async function readLatestSubagentOutputWithRetry(params) {
3313
+ const RETRY_INTERVAL_MS = FAST_TEST_MODE ? FAST_TEST_RETRY_INTERVAL_MS : 100;
3314
+ const deadline = Date.now() + Math.max(0, Math.min(params.maxWaitMs, 15e3));
3315
+ let result;
3316
+ while (Date.now() < deadline) {
3317
+ result = await readLatestSubagentOutput(params.sessionKey);
3318
+ if (result?.trim()) return result;
3319
+ await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL_MS));
3320
+ }
3321
+ return result;
3322
+ }
3323
+ async function waitForSubagentOutputChange(params) {
3324
+ const baseline = params.baselineReply.trim();
3325
+ if (!baseline) return params.baselineReply;
3326
+ const RETRY_INTERVAL_MS = FAST_TEST_MODE ? FAST_TEST_RETRY_INTERVAL_MS : 100;
3327
+ const deadline = Date.now() + Math.max(0, Math.min(params.maxWaitMs, 5e3));
3328
+ let latest = params.baselineReply;
3329
+ while (Date.now() < deadline) {
3330
+ const next = await readLatestSubagentOutput(params.sessionKey);
3331
+ if (next?.trim()) {
3332
+ latest = next;
3333
+ if (next.trim() !== baseline) return next;
3334
+ }
3335
+ await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL_MS));
3336
+ }
3337
+ return latest;
3338
+ }
3339
+ function formatDurationShort(valueMs) {
3340
+ if (!valueMs || !Number.isFinite(valueMs) || valueMs <= 0) return "n/a";
3341
+ const totalSeconds = Math.round(valueMs / 1e3);
3342
+ const hours = Math.floor(totalSeconds / 3600);
3343
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
3344
+ const seconds = totalSeconds % 60;
3345
+ if (hours > 0) return `${hours}h${minutes}m`;
3346
+ if (minutes > 0) return `${minutes}m${seconds}s`;
3347
+ return `${seconds}s`;
3348
+ }
3349
+ function formatTokenCount(value) {
3350
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return "0";
3351
+ if (value >= 1e6) return `${(value / 1e6).toFixed(1)}m`;
3352
+ if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
3353
+ return String(Math.round(value));
3354
+ }
3355
+ async function buildCompactAnnounceStatsLine(params) {
3356
+ const cfg = loadConfig();
3357
+ const agentId = resolveAgentIdFromSessionKey(params.sessionKey);
3358
+ const storePath = resolveStorePath(cfg.session?.store, { agentId });
3359
+ let entry = loadSessionStore(storePath)[params.sessionKey];
3360
+ const tokenWaitAttempts = FAST_TEST_MODE ? 1 : 3;
3361
+ for (let attempt = 0; attempt < tokenWaitAttempts; attempt += 1) {
3362
+ if (typeof entry?.inputTokens === "number" || typeof entry?.outputTokens === "number" || typeof entry?.totalTokens === "number") break;
3363
+ if (!FAST_TEST_MODE) await new Promise((resolve) => setTimeout(resolve, 150));
3364
+ entry = loadSessionStore(storePath)[params.sessionKey];
3365
+ }
3366
+ const input = typeof entry?.inputTokens === "number" ? entry.inputTokens : 0;
3367
+ const output = typeof entry?.outputTokens === "number" ? entry.outputTokens : 0;
3368
+ const ioTotal = input + output;
3369
+ const promptCache = typeof entry?.totalTokens === "number" ? entry.totalTokens : void 0;
3370
+ const parts = [`runtime ${formatDurationShort(typeof params.startedAt === "number" && typeof params.endedAt === "number" ? Math.max(0, params.endedAt - params.startedAt) : void 0)}`, `tokens ${formatTokenCount(ioTotal)} (in ${formatTokenCount(input)} / out ${formatTokenCount(output)})`];
3371
+ if (typeof promptCache === "number" && promptCache > ioTotal) parts.push(`prompt/cache ${formatTokenCount(promptCache)}`);
3372
+ return `Stats: ${parts.join(" • ")}`;
3373
+ }
3374
+ function resolveAnnounceOrigin(entry, requesterOrigin) {
3375
+ const normalizedRequester = normalizeDeliveryContext(requesterOrigin);
3376
+ const normalizedEntry = deliveryContextFromSession(entry);
3377
+ if (normalizedRequester?.channel && isInternalMessageChannel(normalizedRequester.channel)) return mergeDeliveryContext({
3378
+ accountId: normalizedRequester.accountId,
3379
+ threadId: normalizedRequester.threadId
3380
+ }, normalizedEntry);
3381
+ return mergeDeliveryContext(normalizedRequester, normalizedRequester?.to && normalizedRequester.threadId == null && normalizedEntry?.threadId != null ? (() => {
3382
+ const { threadId: _ignore, ...rest } = normalizedEntry;
3383
+ return rest;
3384
+ })() : normalizedEntry);
3385
+ }
3386
+ async function resolveSubagentCompletionOrigin(params) {
3387
+ const requesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
3388
+ const requesterConversation = (() => {
3389
+ const channel = requesterOrigin?.channel?.trim().toLowerCase();
3390
+ const to = requesterOrigin?.to?.trim();
3391
+ const accountId = normalizeAccountId(requesterOrigin?.accountId);
3392
+ const conversationId = (requesterOrigin?.threadId != null && requesterOrigin.threadId !== "" ? String(requesterOrigin.threadId).trim() : void 0) || (to?.startsWith("channel:") ? to.slice(8) : "");
3393
+ if (!channel || !conversationId) return;
3394
+ return {
3395
+ channel,
3396
+ accountId,
3397
+ conversationId
3398
+ };
3399
+ })();
3400
+ const route = createBoundDeliveryRouter().resolveDestination({
3401
+ eventKind: "task_completion",
3402
+ targetSessionKey: params.childSessionKey,
3403
+ requester: requesterConversation,
3404
+ failClosed: false
3405
+ });
3406
+ if (route.mode === "bound" && route.binding) return {
3407
+ origin: mergeDeliveryContext({
3408
+ channel: route.binding.conversation.channel,
3409
+ accountId: route.binding.conversation.accountId,
3410
+ to: `channel:${route.binding.conversation.conversationId}`,
3411
+ threadId: route.binding.conversation.conversationId
3412
+ }, requesterOrigin),
3413
+ routeMode: "bound"
3414
+ };
3415
+ const hookRunner = getGlobalHookRunner();
3416
+ if (!hookRunner?.hasHooks("subagent_delivery_target")) return {
3417
+ origin: requesterOrigin,
3418
+ routeMode: "fallback"
3419
+ };
3420
+ try {
3421
+ const hookOrigin = normalizeDeliveryContext((await hookRunner.runSubagentDeliveryTarget({
3422
+ childSessionKey: params.childSessionKey,
3423
+ requesterSessionKey: params.requesterSessionKey,
3424
+ requesterOrigin,
3425
+ childRunId: params.childRunId,
3426
+ spawnMode: params.spawnMode,
3427
+ expectsCompletionMessage: params.expectsCompletionMessage
3428
+ }, {
3429
+ runId: params.childRunId,
3430
+ childSessionKey: params.childSessionKey,
3431
+ requesterSessionKey: params.requesterSessionKey
3432
+ }))?.origin);
3433
+ if (!hookOrigin) return {
3434
+ origin: requesterOrigin,
3435
+ routeMode: "fallback"
3436
+ };
3437
+ if (hookOrigin.channel && !isDeliverableMessageChannel(hookOrigin.channel)) return {
3438
+ origin: requesterOrigin,
3439
+ routeMode: "fallback"
3440
+ };
3441
+ return {
3442
+ origin: mergeDeliveryContext(hookOrigin, requesterOrigin),
3443
+ routeMode: "hook"
3444
+ };
3445
+ } catch {
3446
+ return {
3447
+ origin: requesterOrigin,
3448
+ routeMode: "fallback"
3449
+ };
3450
+ }
3451
+ }
3452
+ function resolveRequesterStoreKey(cfg, requesterSessionKey) {
3453
+ const raw = (requesterSessionKey ?? "").trim();
3454
+ if (!raw) return raw;
3455
+ if (raw === "global" || raw === "unknown") return raw;
3456
+ if (raw.startsWith("agent:")) return raw;
3457
+ const mainKey = normalizeMainKey(cfg.session?.mainKey);
3458
+ if (raw === "main" || raw === mainKey) return resolveMainSessionKey(cfg);
3459
+ return `agent:${resolveAgentIdFromSessionKey(raw)}:${raw}`;
3460
+ }
3461
+ function loadRequesterSessionEntry(requesterSessionKey) {
3462
+ const cfg = loadConfig();
3463
+ const canonicalKey = resolveRequesterStoreKey(cfg, requesterSessionKey);
3464
+ const agentId = resolveAgentIdFromSessionKey(canonicalKey);
3465
+ return {
3466
+ cfg,
3467
+ entry: loadSessionStore(resolveStorePath(cfg.session?.store, { agentId }))[canonicalKey],
3468
+ canonicalKey
3469
+ };
3470
+ }
3471
+ async function maybeQueueSubagentAnnounce(params) {
3472
+ if (params.signal?.aborted) return "none";
3473
+ const { cfg, entry } = loadRequesterSessionEntry(params.requesterSessionKey);
3474
+ resolveRequesterStoreKey(cfg, params.requesterSessionKey);
3475
+ if (!entry?.sessionId) return "none";
3476
+ const queueSettings = resolveQueueSettings({
3477
+ cfg,
3478
+ channel: entry?.channel ?? entry?.lastChannel,
3479
+ sessionEntry: entry
3480
+ });
3481
+ queueSettings.mode === "followup" || queueSettings.mode === "collect" || queueSettings.mode === "steer-backlog" || queueSettings.mode;
3482
+ return "none";
3483
+ }
3484
+ function queueOutcomeToDeliveryResult(outcome) {
3485
+ if (outcome === "steered") return {
3486
+ delivered: true,
3487
+ path: "steered"
3488
+ };
3489
+ if (outcome === "queued") return {
3490
+ delivered: true,
3491
+ path: "queued"
3492
+ };
3493
+ return {
3494
+ delivered: false,
3495
+ path: "none"
3496
+ };
3497
+ }
3498
+ async function sendSubagentAnnounceDirectly(params) {
3499
+ if (params.signal?.aborted) return {
3500
+ delivered: false,
3501
+ path: "none"
3502
+ };
3503
+ const cfg = loadConfig();
3504
+ const announceTimeoutMs = resolveSubagentAnnounceTimeoutMs(cfg);
3505
+ const canonicalRequesterSessionKey = resolveRequesterStoreKey(cfg, params.targetRequesterSessionKey);
3506
+ try {
3507
+ const completionDirectOrigin = normalizeDeliveryContext(params.completionDirectOrigin);
3508
+ const completionChannelRaw = typeof completionDirectOrigin?.channel === "string" ? completionDirectOrigin.channel.trim() : "";
3509
+ const completionChannel = completionChannelRaw && isDeliverableMessageChannel(completionChannelRaw) ? completionChannelRaw : "";
3510
+ const completionTo = typeof completionDirectOrigin?.to === "string" ? completionDirectOrigin.to.trim() : "";
3511
+ const hasCompletionDirectTarget = !params.requesterIsSubagent && Boolean(completionChannel) && Boolean(completionTo);
3512
+ if (params.expectsCompletionMessage && hasCompletionDirectTarget && params.completionMessage?.trim()) {
3513
+ const forceBoundSessionDirectDelivery = params.spawnMode === "session" && (params.completionRouteMode === "bound" || params.completionRouteMode === "hook");
3514
+ let shouldSendCompletionDirectly = true;
3515
+ if (!forceBoundSessionDirectDelivery) {
3516
+ let activeDescendantRuns = 0;
3517
+ try {
3518
+ const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
3519
+ activeDescendantRuns = Math.max(0, countActiveDescendantRuns(canonicalRequesterSessionKey));
3520
+ } catch {}
3521
+ if (activeDescendantRuns > 0) shouldSendCompletionDirectly = false;
3522
+ }
3523
+ if (shouldSendCompletionDirectly) {
3524
+ const completionThreadId = completionDirectOrigin?.threadId != null && completionDirectOrigin.threadId !== "" ? String(completionDirectOrigin.threadId) : void 0;
3525
+ if (params.signal?.aborted) return {
3526
+ delivered: false,
3527
+ path: "none"
3528
+ };
3529
+ await runAnnounceDeliveryWithRetry({
3530
+ operation: "completion direct send",
3531
+ signal: params.signal,
3532
+ run: async () => await callGateway({
3533
+ method: "send",
3534
+ params: {
3535
+ channel: completionChannel,
3536
+ to: completionTo,
3537
+ accountId: completionDirectOrigin?.accountId,
3538
+ threadId: completionThreadId,
3539
+ sessionKey: canonicalRequesterSessionKey,
3540
+ message: params.completionMessage,
3541
+ idempotencyKey: params.directIdempotencyKey
3542
+ },
3543
+ timeoutMs: announceTimeoutMs
3544
+ })
3545
+ });
3546
+ return {
3547
+ delivered: true,
3548
+ path: "direct"
3549
+ };
3550
+ }
3551
+ }
3552
+ const directOrigin = normalizeDeliveryContext(params.directOrigin);
3553
+ const directChannelRaw = typeof directOrigin?.channel === "string" ? directOrigin.channel.trim() : "";
3554
+ const directChannel = directChannelRaw && isDeliverableMessageChannel(directChannelRaw) ? directChannelRaw : "";
3555
+ const directTo = typeof directOrigin?.to === "string" ? directOrigin.to.trim() : "";
3556
+ const hasDeliverableDirectTarget = !params.requesterIsSubagent && Boolean(directChannel) && Boolean(directTo);
3557
+ const shouldDeliverExternally = !params.requesterIsSubagent && (!params.expectsCompletionMessage || hasDeliverableDirectTarget);
3558
+ const threadId = directOrigin?.threadId != null && directOrigin.threadId !== "" ? String(directOrigin.threadId) : void 0;
3559
+ if (params.signal?.aborted) return {
3560
+ delivered: false,
3561
+ path: "none"
3562
+ };
3563
+ await runAnnounceDeliveryWithRetry({
3564
+ operation: "direct announce agent call",
3565
+ signal: params.signal,
3566
+ run: async () => await callGateway({
3567
+ method: "agent",
3568
+ params: {
3569
+ sessionKey: canonicalRequesterSessionKey,
3570
+ message: params.triggerMessage,
3571
+ deliver: shouldDeliverExternally,
3572
+ bestEffortDeliver: params.bestEffortDeliver,
3573
+ channel: shouldDeliverExternally ? directChannel : void 0,
3574
+ accountId: shouldDeliverExternally ? directOrigin?.accountId : void 0,
3575
+ to: shouldDeliverExternally ? directTo : void 0,
3576
+ threadId: shouldDeliverExternally ? threadId : void 0,
3577
+ idempotencyKey: params.directIdempotencyKey
3578
+ },
3579
+ expectFinal: true,
3580
+ timeoutMs: announceTimeoutMs
3581
+ })
3582
+ });
3583
+ return {
3584
+ delivered: true,
3585
+ path: "direct"
3586
+ };
3587
+ } catch (err) {
3588
+ return {
3589
+ delivered: false,
3590
+ path: "direct",
3591
+ error: summarizeDeliveryError(err)
3592
+ };
3593
+ }
3594
+ }
3595
+ async function deliverSubagentAnnouncement(params) {
3596
+ if (params.signal?.aborted) return {
3597
+ delivered: false,
3598
+ path: "none"
3599
+ };
3600
+ if (!params.expectsCompletionMessage) {
3601
+ const queued = queueOutcomeToDeliveryResult(await maybeQueueSubagentAnnounce({
3602
+ requesterSessionKey: params.requesterSessionKey,
3603
+ announceId: params.announceId,
3604
+ triggerMessage: params.triggerMessage,
3605
+ summaryLine: params.summaryLine,
3606
+ requesterOrigin: params.requesterOrigin,
3607
+ signal: params.signal
3608
+ }));
3609
+ if (queued.delivered) return queued;
3610
+ }
3611
+ const direct = await sendSubagentAnnounceDirectly({
3612
+ targetRequesterSessionKey: params.targetRequesterSessionKey,
3613
+ triggerMessage: params.triggerMessage,
3614
+ completionMessage: params.completionMessage,
3615
+ directIdempotencyKey: params.directIdempotencyKey,
3616
+ completionDirectOrigin: params.completionDirectOrigin,
3617
+ completionRouteMode: params.completionRouteMode,
3618
+ spawnMode: params.spawnMode,
3619
+ directOrigin: params.directOrigin,
3620
+ requesterIsSubagent: params.requesterIsSubagent,
3621
+ expectsCompletionMessage: params.expectsCompletionMessage,
3622
+ signal: params.signal,
3623
+ bestEffortDeliver: params.bestEffortDeliver
3624
+ });
3625
+ if (direct.delivered || !params.expectsCompletionMessage) return direct;
3626
+ const queueOutcome = await maybeQueueSubagentAnnounce({
3627
+ requesterSessionKey: params.requesterSessionKey,
3628
+ announceId: params.announceId,
3629
+ triggerMessage: params.triggerMessage,
3630
+ summaryLine: params.summaryLine,
3631
+ requesterOrigin: params.requesterOrigin,
3632
+ signal: params.signal
3633
+ });
3634
+ if (queueOutcome === "steered" || queueOutcome === "queued") return queueOutcomeToDeliveryResult(queueOutcome);
3635
+ return direct;
3636
+ }
3637
+ function loadSessionEntryByKey(sessionKey) {
3638
+ const cfg = loadConfig();
3639
+ const agentId = resolveAgentIdFromSessionKey(sessionKey);
3640
+ return loadSessionStore(resolveStorePath(cfg.session?.store, { agentId }))[sessionKey];
3641
+ }
3642
+ function buildSubagentSystemPrompt(params) {
3643
+ const taskText = typeof params.task === "string" && params.task.trim() ? params.task.replace(/\s+/g, " ").trim() : "{{TASK_DESCRIPTION}}";
3644
+ const childDepth = typeof params.childDepth === "number" ? params.childDepth : 1;
3645
+ const canSpawn = childDepth < (typeof params.maxSpawnDepth === "number" ? params.maxSpawnDepth : DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH);
3646
+ const parentLabel = childDepth >= 2 ? "parent orchestrator" : "main agent";
3647
+ const lines = [
3648
+ "# Subagent Context",
3649
+ "",
3650
+ `You are a **subagent** spawned by the ${parentLabel} for a specific task.`,
3651
+ "",
3652
+ "## Your Role",
3653
+ `- You were created to handle: ${taskText}`,
3654
+ "- Complete this task. That's your entire purpose.",
3655
+ `- You are NOT the ${parentLabel}. Don't try to be.`,
3656
+ "",
3657
+ "## Rules",
3658
+ "1. **Stay focused** - Do your assigned task, nothing else",
3659
+ `2. **Complete the task** - Your final message will be automatically reported to the ${parentLabel}`,
3660
+ "3. **Don't initiate** - No heartbeats, no proactive actions, no side quests",
3661
+ "4. **Be ephemeral** - You may be terminated after task completion. That's fine.",
3662
+ "5. **Trust push-based completion** - Descendant results are auto-announced back to you; do not busy-poll for status.",
3663
+ "6. **Recover from compacted/truncated tool output** - If you see `[compacted: tool output removed to free context]` or `[truncated: output exceeded context limit]`, assume prior output was reduced. Re-read only what you need using smaller chunks (`read` with offset/limit, or targeted `rg`/`head`/`tail`) instead of full-file `cat`.",
3664
+ "",
3665
+ "## Output Format",
3666
+ "When complete, your final response should include:",
3667
+ `- What you accomplished or found`,
3668
+ `- Any relevant details the ${parentLabel} should know`,
3669
+ "- Keep it concise but informative",
3670
+ "",
3671
+ "## What You DON'T Do",
3672
+ `- NO user conversations (that's ${parentLabel}'s job)`,
3673
+ "- NO external messages (email, tweets, etc.) unless explicitly tasked with a specific recipient/channel",
3674
+ "- NO cron jobs or persistent state",
3675
+ `- NO pretending to be the ${parentLabel}`,
3676
+ `- Only use the \`message\` tool when explicitly instructed to contact a specific external recipient; otherwise return plain text and let the ${parentLabel} deliver it`,
3677
+ ""
3678
+ ];
3679
+ if (canSpawn) lines.push("## Sub-Agent Spawning", "You CAN spawn your own sub-agents for parallel or complex work using `sessions_spawn`.", "Use the `subagents` tool to steer, kill, or do an on-demand status check for your spawned sub-agents.", "Your sub-agents will announce their results back to you automatically (not to the main agent).", "Default workflow: spawn work, continue orchestrating, and wait for auto-announced completions.", "Do NOT repeatedly poll `subagents list` in a loop unless you are actively debugging or intervening.", "Coordinate their work and synthesize results before reporting back.", "");
3680
+ else if (childDepth >= 2) lines.push("## Sub-Agent Spawning", "You are a leaf worker and CANNOT spawn further sub-agents. Focus on your assigned task.", "");
3681
+ lines.push("## Session Context", ...[
3682
+ params.label ? `- Label: ${params.label}` : void 0,
3683
+ params.requesterSessionKey ? `- Requester session: ${params.requesterSessionKey}.` : void 0,
3684
+ params.requesterOrigin?.channel ? `- Requester channel: ${params.requesterOrigin.channel}.` : void 0,
3685
+ `- Your session: ${params.childSessionKey}.`
3686
+ ].filter((line) => line !== void 0), "");
3687
+ return lines.join("\n");
3688
+ }
3689
+ function buildAnnounceReplyInstruction(params) {
3690
+ if (params.remainingActiveSubagentRuns > 0) {
3691
+ const activeRunsLabel = params.remainingActiveSubagentRuns === 1 ? "run" : "runs";
3692
+ return `There are still ${params.remainingActiveSubagentRuns} active subagent ${activeRunsLabel} for this session. If they are part of the same workflow, wait for the remaining results before sending a user update. If they are unrelated, respond normally using only the result above.`;
3693
+ }
3694
+ if (params.requesterIsSubagent) return `Convert this completion into a concise internal orchestration update for your parent agent in your own words. Keep this internal context private (don't mention system/log/stats/session details or announce type). If this result is duplicate or no update is needed, reply ONLY: ${SILENT_REPLY_TOKEN}.`;
3695
+ if (params.expectsCompletionMessage) return `A completed ${params.announceType} is ready for user delivery. Convert the result above into your normal assistant voice and send that user-facing update now. Keep this internal context private (don't mention system/log/stats/session details or announce type).`;
3696
+ return `A completed ${params.announceType} is ready for user delivery. Convert the result above into your normal assistant voice and send that user-facing update now. Keep this internal context private (don't mention system/log/stats/session details or announce type), and do not copy the system message verbatim. Reply ONLY: ${SILENT_REPLY_TOKEN} if this exact result was already delivered to the user in this same turn.`;
3697
+ }
3698
+ async function runSubagentAnnounceFlow(params) {
3699
+ let didAnnounce = false;
3700
+ const expectsCompletionMessage = params.expectsCompletionMessage === true;
3701
+ let shouldDeleteChildSession = params.cleanup === "delete";
3702
+ try {
3703
+ let targetRequesterSessionKey = params.requesterSessionKey;
3704
+ let targetRequesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
3705
+ const childSessionId = (() => {
3706
+ const entry = loadSessionEntryByKey(params.childSessionKey);
3707
+ return typeof entry?.sessionId === "string" && entry.sessionId.trim() ? entry.sessionId.trim() : void 0;
3708
+ })();
3709
+ const settleTimeoutMs = Math.min(Math.max(params.timeoutMs, 1), 12e4);
3710
+ let reply = params.roundOneReply;
3711
+ let outcome = params.outcome;
3712
+ if (!reply && params.waitForCompletion !== false) {
3713
+ const waitMs = settleTimeoutMs;
3714
+ const wait = await callGateway({
3715
+ method: "agent.wait",
3716
+ params: {
3717
+ runId: params.childRunId,
3718
+ timeoutMs: waitMs
3719
+ },
3720
+ timeoutMs: waitMs + 2e3
3721
+ });
3722
+ const waitError = typeof wait?.error === "string" ? wait.error : void 0;
3723
+ if (wait?.status === "timeout") outcome = { status: "timeout" };
3724
+ else if (wait?.status === "error") outcome = {
3725
+ status: "error",
3726
+ error: waitError
3727
+ };
3728
+ else if (wait?.status === "ok") outcome = { status: "ok" };
3729
+ if (typeof wait?.startedAt === "number" && !params.startedAt) params.startedAt = wait.startedAt;
3730
+ if (typeof wait?.endedAt === "number" && !params.endedAt) params.endedAt = wait.endedAt;
3731
+ if (wait?.status === "timeout") {
3732
+ if (!outcome) outcome = { status: "timeout" };
3733
+ }
3734
+ reply = await readLatestSubagentOutput(params.childSessionKey);
3735
+ }
3736
+ if (!reply) reply = await readLatestSubagentOutput(params.childSessionKey);
3737
+ if (!reply?.trim()) reply = await readLatestSubagentOutputWithRetry({
3738
+ sessionKey: params.childSessionKey,
3739
+ maxWaitMs: params.timeoutMs
3740
+ });
3741
+ if (isAnnounceSkip(reply)) return true;
3742
+ if (!outcome) outcome = { status: "unknown" };
3743
+ let requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
3744
+ let activeChildDescendantRuns = 0;
3745
+ try {
3746
+ const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
3747
+ activeChildDescendantRuns = Math.max(0, countActiveDescendantRuns(params.childSessionKey));
3748
+ } catch {}
3749
+ if (activeChildDescendantRuns > 0) {
3750
+ shouldDeleteChildSession = false;
3751
+ return false;
3752
+ }
3753
+ if (requesterDepth >= 1 && reply?.trim()) {
3754
+ const minReplyChangeWaitMs = FAST_TEST_MODE ? FAST_TEST_REPLY_CHANGE_WAIT_MS : 250;
3755
+ reply = await waitForSubagentOutputChange({
3756
+ sessionKey: params.childSessionKey,
3757
+ baselineReply: reply,
3758
+ maxWaitMs: Math.max(minReplyChangeWaitMs, Math.min(params.timeoutMs, 2e3))
3759
+ });
3760
+ }
3761
+ const statusLabel = outcome.status === "ok" ? "completed successfully" : outcome.status === "timeout" ? "timed out" : outcome.status === "error" ? `failed: ${outcome.error || "unknown error"}` : "finished with unknown status";
3762
+ const announceType = params.announceType ?? "subagent task";
3763
+ const taskLabel = params.label || params.task || "task";
3764
+ const subagentName = resolveAgentIdFromSessionKey(params.childSessionKey);
3765
+ const announceSessionId = childSessionId || "unknown";
3766
+ const findings = reply || "(no output)";
3767
+ let completionMessage = "";
3768
+ let triggerMessage = "";
3769
+ let requesterIsSubagent = requesterDepth >= 1;
3770
+ if (requesterIsSubagent) {
3771
+ const { isSubagentSessionRunActive, resolveRequesterForChildSession } = await Promise.resolve().then(() => subagent_registry_exports);
3772
+ if (!isSubagentSessionRunActive(targetRequesterSessionKey)) {
3773
+ const parentSessionEntry = loadSessionEntryByKey(targetRequesterSessionKey);
3774
+ if (!(parentSessionEntry && typeof parentSessionEntry.sessionId === "string" && parentSessionEntry.sessionId.trim())) {
3775
+ const fallback = resolveRequesterForChildSession(targetRequesterSessionKey);
3776
+ if (!fallback?.requesterSessionKey) {
3777
+ shouldDeleteChildSession = false;
3778
+ return false;
3779
+ }
3780
+ targetRequesterSessionKey = fallback.requesterSessionKey;
3781
+ targetRequesterOrigin = normalizeDeliveryContext(fallback.requesterOrigin) ?? targetRequesterOrigin;
3782
+ requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
3783
+ requesterIsSubagent = requesterDepth >= 1;
3784
+ }
3785
+ }
3786
+ }
3787
+ let remainingActiveSubagentRuns = 0;
3788
+ try {
3789
+ const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
3790
+ remainingActiveSubagentRuns = Math.max(0, countActiveDescendantRuns(targetRequesterSessionKey));
3791
+ } catch {}
3792
+ const replyInstruction = buildAnnounceReplyInstruction({
3793
+ remainingActiveSubagentRuns,
3794
+ requesterIsSubagent,
3795
+ announceType,
3796
+ expectsCompletionMessage
3797
+ });
3798
+ const statsLine = await buildCompactAnnounceStatsLine({
3799
+ sessionKey: params.childSessionKey,
3800
+ startedAt: params.startedAt,
3801
+ endedAt: params.endedAt
3802
+ });
3803
+ completionMessage = buildCompletionDeliveryMessage({
3804
+ findings,
3805
+ subagentName,
3806
+ spawnMode: params.spawnMode,
3807
+ outcome
3808
+ });
3809
+ triggerMessage = [
3810
+ [
3811
+ `[System Message] [sessionId: ${announceSessionId}] A ${announceType} "${taskLabel}" just ${statusLabel}.`,
3812
+ "",
3813
+ "Result:",
3814
+ findings,
3815
+ "",
3816
+ statsLine
3817
+ ].join("\n"),
3818
+ "",
3819
+ replyInstruction
3820
+ ].join("\n");
3821
+ const announceId = buildAnnounceIdFromChildRun({
3822
+ childSessionKey: params.childSessionKey,
3823
+ childRunId: params.childRunId
3824
+ });
3825
+ let directOrigin = targetRequesterOrigin;
3826
+ if (!requesterIsSubagent) {
3827
+ const { entry } = loadRequesterSessionEntry(targetRequesterSessionKey);
3828
+ directOrigin = resolveAnnounceOrigin(entry, targetRequesterOrigin);
3829
+ }
3830
+ const completionResolution = expectsCompletionMessage && !requesterIsSubagent ? await resolveSubagentCompletionOrigin({
3831
+ childSessionKey: params.childSessionKey,
3832
+ requesterSessionKey: targetRequesterSessionKey,
3833
+ requesterOrigin: directOrigin,
3834
+ childRunId: params.childRunId,
3835
+ spawnMode: params.spawnMode,
3836
+ expectsCompletionMessage
3837
+ }) : {
3838
+ origin: targetRequesterOrigin,
3839
+ routeMode: "fallback"
3840
+ };
3841
+ const completionDirectOrigin = completionResolution.origin;
3842
+ const directIdempotencyKey = buildAnnounceIdempotencyKey(announceId);
3843
+ const delivery = await deliverSubagentAnnouncement({
3844
+ requesterSessionKey: targetRequesterSessionKey,
3845
+ announceId,
3846
+ triggerMessage,
3847
+ completionMessage,
3848
+ summaryLine: taskLabel,
3849
+ requesterOrigin: expectsCompletionMessage && !requesterIsSubagent ? completionDirectOrigin : targetRequesterOrigin,
3850
+ completionDirectOrigin,
3851
+ directOrigin,
3852
+ targetRequesterSessionKey,
3853
+ requesterIsSubagent,
3854
+ expectsCompletionMessage,
3855
+ bestEffortDeliver: params.bestEffortDeliver,
3856
+ completionRouteMode: completionResolution.routeMode,
3857
+ spawnMode: params.spawnMode,
3858
+ directIdempotencyKey,
3859
+ signal: params.signal
3860
+ });
3861
+ didAnnounce = delivery.delivered;
3862
+ if (!delivery.delivered && delivery.path === "direct" && delivery.error) defaultRuntime.error?.(`Subagent completion direct announce failed for run ${params.childRunId}: ${delivery.error}`);
3863
+ } catch (err) {
3864
+ defaultRuntime.error?.(`Subagent announce failed: ${String(err)}`);
3865
+ } finally {
3866
+ if (params.label) try {
3867
+ await callGateway({
3868
+ method: "sessions.patch",
3869
+ params: {
3870
+ key: params.childSessionKey,
3871
+ label: params.label
3872
+ },
3873
+ timeoutMs: 1e4
3874
+ });
3875
+ } catch {}
3876
+ if (shouldDeleteChildSession) try {
3877
+ await callGateway({
3878
+ method: "sessions.delete",
3879
+ params: {
3880
+ key: params.childSessionKey,
3881
+ deleteTranscript: true,
3882
+ emitLifecycleHooks: false
3883
+ },
3884
+ timeoutMs: 1e4
3885
+ });
3886
+ } catch {}
3887
+ }
3888
+ return didAnnounce;
3889
+ }
3890
+
3891
+ //#endregion
3892
+ //#region src/agents/subagent-lifecycle-events.ts
3893
+ const SUBAGENT_TARGET_KIND_SUBAGENT = "subagent";
3894
+ const SUBAGENT_ENDED_REASON_COMPLETE = "subagent-complete";
3895
+ const SUBAGENT_ENDED_REASON_ERROR = "subagent-error";
3896
+ const SUBAGENT_ENDED_REASON_KILLED = "subagent-killed";
3897
+ const SUBAGENT_ENDED_OUTCOME_OK = "ok";
3898
+ const SUBAGENT_ENDED_OUTCOME_ERROR = "error";
3899
+ const SUBAGENT_ENDED_OUTCOME_TIMEOUT = "timeout";
3900
+ const SUBAGENT_ENDED_OUTCOME_KILLED = "killed";
3901
+
3902
+ //#endregion
3903
+ //#region src/agents/subagent-registry-cleanup.ts
3904
+ function resolveCleanupCompletionReason(entry) {
3905
+ return entry.endedReason ?? SUBAGENT_ENDED_REASON_COMPLETE;
3906
+ }
3907
+ function resolveEndedAgoMs(entry, now) {
3908
+ return typeof entry.endedAt === "number" ? now - entry.endedAt : 0;
3909
+ }
3910
+ function resolveDeferredCleanupDecision(params) {
3911
+ const endedAgo = resolveEndedAgoMs(params.entry, params.now);
3912
+ if (params.entry.expectsCompletionMessage === true && params.activeDescendantRuns > 0) {
3913
+ if (endedAgo > params.announceExpiryMs) return {
3914
+ kind: "give-up",
3915
+ reason: "expiry"
3916
+ };
3917
+ return {
3918
+ kind: "defer-descendants",
3919
+ delayMs: params.deferDescendantDelayMs
3920
+ };
3921
+ }
3922
+ const retryCount = (params.entry.announceRetryCount ?? 0) + 1;
3923
+ if (retryCount >= params.maxAnnounceRetryCount || endedAgo > params.announceExpiryMs) return {
3924
+ kind: "give-up",
3925
+ reason: retryCount >= params.maxAnnounceRetryCount ? "retry-limit" : "expiry",
3926
+ retryCount
3927
+ };
3928
+ return {
3929
+ kind: "retry",
3930
+ retryCount,
3931
+ resumeDelayMs: params.entry.expectsCompletionMessage === true ? params.resolveAnnounceRetryDelayMs(retryCount) : void 0
3932
+ };
3933
+ }
3934
+
3935
+ //#endregion
3936
+ //#region src/agents/subagent-registry-completion.ts
3937
+ function runOutcomesEqual(a, b) {
3938
+ if (!a && !b) return true;
3939
+ if (!a || !b) return false;
3940
+ if (a.status !== b.status) return false;
3941
+ if (a.status === "error" && b.status === "error") return (a.error ?? "") === (b.error ?? "");
3942
+ return true;
3943
+ }
3944
+ function resolveLifecycleOutcomeFromRunOutcome(outcome) {
3945
+ if (outcome?.status === "error") return SUBAGENT_ENDED_OUTCOME_ERROR;
3946
+ if (outcome?.status === "timeout") return SUBAGENT_ENDED_OUTCOME_TIMEOUT;
3947
+ return SUBAGENT_ENDED_OUTCOME_OK;
3948
+ }
3949
+ async function emitSubagentEndedHookOnce(params) {
3950
+ const runId = params.entry.runId.trim();
3951
+ if (!runId) return false;
3952
+ if (params.entry.endedHookEmittedAt) return false;
3953
+ if (params.inFlightRunIds.has(runId)) return false;
3954
+ params.inFlightRunIds.add(runId);
3955
+ try {
3956
+ const hookRunner = getGlobalHookRunner();
3957
+ if (hookRunner?.hasHooks("subagent_ended")) await hookRunner.runSubagentEnded({
3958
+ targetSessionKey: params.entry.childSessionKey,
3959
+ targetKind: SUBAGENT_TARGET_KIND_SUBAGENT,
3960
+ reason: params.reason,
3961
+ sendFarewell: params.sendFarewell,
3962
+ accountId: params.accountId,
3963
+ runId: params.entry.runId,
3964
+ endedAt: params.entry.endedAt,
3965
+ outcome: params.outcome,
3966
+ error: params.error
3967
+ }, {
3968
+ runId: params.entry.runId,
3969
+ childSessionKey: params.entry.childSessionKey,
3970
+ requesterSessionKey: params.entry.requesterSessionKey
3971
+ });
3972
+ params.entry.endedHookEmittedAt = Date.now();
3973
+ params.persist();
3974
+ return true;
3975
+ } catch {
3976
+ return false;
3977
+ } finally {
3978
+ params.inFlightRunIds.delete(runId);
3979
+ }
3980
+ }
3981
+
3982
+ //#endregion
3983
+ //#region src/agents/subagent-registry-queries.ts
3984
+ function findRunIdsByChildSessionKeyFromRuns(runs, childSessionKey) {
3985
+ const key = childSessionKey.trim();
3986
+ if (!key) return [];
3987
+ const runIds = [];
3988
+ for (const [runId, entry] of runs.entries()) if (entry.childSessionKey === key) runIds.push(runId);
3989
+ return runIds;
3990
+ }
3991
+ function listRunsForRequesterFromRuns(runs, requesterSessionKey) {
3992
+ const key = requesterSessionKey.trim();
3993
+ if (!key) return [];
3994
+ return [...runs.values()].filter((entry) => entry.requesterSessionKey === key);
3995
+ }
3996
+ function resolveRequesterForChildSessionFromRuns(runs, childSessionKey) {
3997
+ const key = childSessionKey.trim();
3998
+ if (!key) return null;
3999
+ let best;
4000
+ for (const entry of runs.values()) {
4001
+ if (entry.childSessionKey !== key) continue;
4002
+ if (!best || entry.createdAt > best.createdAt) best = entry;
4003
+ }
4004
+ if (!best) return null;
4005
+ return {
4006
+ requesterSessionKey: best.requesterSessionKey,
4007
+ requesterOrigin: best.requesterOrigin
4008
+ };
4009
+ }
4010
+ function countActiveRunsForSessionFromRuns(runs, requesterSessionKey) {
4011
+ const key = requesterSessionKey.trim();
4012
+ if (!key) return 0;
4013
+ let count = 0;
4014
+ for (const entry of runs.values()) {
4015
+ if (entry.requesterSessionKey !== key) continue;
4016
+ if (typeof entry.endedAt === "number") continue;
4017
+ count += 1;
4018
+ }
4019
+ return count;
4020
+ }
4021
+ function countActiveDescendantRunsFromRuns(runs, rootSessionKey) {
4022
+ const root = rootSessionKey.trim();
4023
+ if (!root) return 0;
4024
+ const pending = [root];
4025
+ const visited = new Set([root]);
4026
+ let count = 0;
4027
+ while (pending.length > 0) {
4028
+ const requester = pending.shift();
4029
+ if (!requester) continue;
4030
+ for (const entry of runs.values()) {
4031
+ if (entry.requesterSessionKey !== requester) continue;
4032
+ if (typeof entry.endedAt !== "number") count += 1;
4033
+ const childKey = entry.childSessionKey.trim();
4034
+ if (!childKey || visited.has(childKey)) continue;
4035
+ visited.add(childKey);
4036
+ pending.push(childKey);
4037
+ }
4038
+ }
4039
+ return count;
4040
+ }
4041
+ function listDescendantRunsForRequesterFromRuns(runs, rootSessionKey) {
4042
+ const root = rootSessionKey.trim();
4043
+ if (!root) return [];
4044
+ const pending = [root];
4045
+ const visited = new Set([root]);
4046
+ const descendants = [];
4047
+ while (pending.length > 0) {
4048
+ const requester = pending.shift();
4049
+ if (!requester) continue;
4050
+ for (const entry of runs.values()) {
4051
+ if (entry.requesterSessionKey !== requester) continue;
4052
+ descendants.push(entry);
4053
+ const childKey = entry.childSessionKey.trim();
4054
+ if (!childKey || visited.has(childKey)) continue;
4055
+ visited.add(childKey);
4056
+ pending.push(childKey);
4057
+ }
4058
+ }
4059
+ return descendants;
4060
+ }
4061
+
4062
+ //#endregion
4063
+ //#region src/agents/subagent-registry.store.ts
4064
+ const REGISTRY_VERSION = 2;
4065
+ function resolveSubagentStateDir(env = process.env) {
4066
+ if (env.REMOTECLAW_STATE_DIR?.trim()) return resolveStateDir(env);
4067
+ if (env.VITEST || env.NODE_ENV === "test") return path.join(os.tmpdir(), "remoteclaw-test-state", String(process.pid));
4068
+ return resolveStateDir(env);
4069
+ }
4070
+ function resolveSubagentRegistryPath() {
4071
+ return path.join(resolveSubagentStateDir(process.env), "subagents", "runs.json");
4072
+ }
4073
+ function loadSubagentRegistryFromDisk() {
4074
+ const raw = loadJsonFile(resolveSubagentRegistryPath());
4075
+ if (!raw || typeof raw !== "object") return /* @__PURE__ */ new Map();
4076
+ const record = raw;
4077
+ if (record.version !== 2) return /* @__PURE__ */ new Map();
4078
+ const runsRaw = record.runs;
4079
+ if (!runsRaw || typeof runsRaw !== "object") return /* @__PURE__ */ new Map();
4080
+ const out = /* @__PURE__ */ new Map();
4081
+ for (const [runId, entry] of Object.entries(runsRaw)) {
4082
+ if (!entry || typeof entry !== "object") continue;
4083
+ if (!entry.runId || typeof entry.runId !== "string") continue;
4084
+ out.set(runId, {
4085
+ ...entry,
4086
+ requesterOrigin: normalizeDeliveryContext(entry.requesterOrigin),
4087
+ cleanupCompletedAt: typeof entry.cleanupCompletedAt === "number" ? entry.cleanupCompletedAt : void 0,
4088
+ cleanupHandled: typeof entry.cleanupHandled === "boolean" ? entry.cleanupHandled : void 0,
4089
+ spawnMode: entry.spawnMode === "session" ? "session" : "run"
4090
+ });
4091
+ }
4092
+ return out;
4093
+ }
4094
+ function saveSubagentRegistryToDisk(runs) {
4095
+ const pathname = resolveSubagentRegistryPath();
4096
+ const serialized = {};
4097
+ for (const [runId, entry] of runs.entries()) serialized[runId] = entry;
4098
+ saveJsonFile(pathname, {
4099
+ version: REGISTRY_VERSION,
4100
+ runs: serialized
4101
+ });
4102
+ }
4103
+
4104
+ //#endregion
4105
+ //#region src/agents/subagent-registry-state.ts
4106
+ function persistSubagentRunsToDisk(runs) {
4107
+ try {
4108
+ saveSubagentRegistryToDisk(runs);
4109
+ } catch {}
4110
+ }
4111
+ function restoreSubagentRunsFromDisk(params) {
4112
+ const restored = loadSubagentRegistryFromDisk();
4113
+ if (restored.size === 0) return 0;
4114
+ let added = 0;
4115
+ for (const [runId, entry] of restored.entries()) {
4116
+ if (!runId || !entry) continue;
4117
+ if (params.mergeOnly && params.runs.has(runId)) continue;
4118
+ params.runs.set(runId, entry);
4119
+ added += 1;
4120
+ }
4121
+ return added;
4122
+ }
4123
+ function getSubagentRunsSnapshotForRead(inMemoryRuns) {
4124
+ const merged = /* @__PURE__ */ new Map();
4125
+ if (!(process.env.VITEST || false)) try {
4126
+ for (const [runId, entry] of loadSubagentRegistryFromDisk().entries()) merged.set(runId, entry);
4127
+ } catch {}
4128
+ for (const [runId, entry] of inMemoryRuns.entries()) merged.set(runId, entry);
4129
+ return merged;
4130
+ }
4131
+
4132
+ //#endregion
4133
+ //#region src/agents/timeout.ts
4134
+ const DEFAULT_AGENT_TIMEOUT_SECONDS = 600;
4135
+ const MAX_SAFE_TIMEOUT_MS = 2147e6;
4136
+ const normalizeNumber = (value) => typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : void 0;
4137
+ function resolveAgentTimeoutSeconds(cfg) {
4138
+ const seconds = normalizeNumber(cfg?.agents?.defaults?.timeoutSeconds) ?? DEFAULT_AGENT_TIMEOUT_SECONDS;
4139
+ return Math.max(seconds, 1);
4140
+ }
4141
+ function resolveAgentTimeoutMs(opts) {
4142
+ const minMs = Math.max(normalizeNumber(opts.minMs) ?? 1, 1);
4143
+ const clampTimeoutMs = (valueMs) => Math.min(Math.max(valueMs, minMs), MAX_SAFE_TIMEOUT_MS);
4144
+ const defaultMs = clampTimeoutMs(resolveAgentTimeoutSeconds(opts.cfg) * 1e3);
4145
+ const NO_TIMEOUT_MS = MAX_SAFE_TIMEOUT_MS;
4146
+ const overrideMs = normalizeNumber(opts.overrideMs);
4147
+ if (overrideMs !== void 0) {
4148
+ if (overrideMs === 0) return NO_TIMEOUT_MS;
4149
+ if (overrideMs < 0) return defaultMs;
4150
+ return clampTimeoutMs(overrideMs);
4151
+ }
4152
+ const overrideSeconds = normalizeNumber(opts.overrideSeconds);
4153
+ if (overrideSeconds !== void 0) {
4154
+ if (overrideSeconds === 0) return NO_TIMEOUT_MS;
4155
+ if (overrideSeconds < 0) return defaultMs;
4156
+ return clampTimeoutMs(overrideSeconds * 1e3);
4157
+ }
4158
+ return defaultMs;
4159
+ }
4160
+
4161
+ //#endregion
4162
+ //#region src/agents/subagent-registry.ts
4163
+ var subagent_registry_exports = /* @__PURE__ */ __exportAll({
4164
+ clearSubagentRunSteerRestart: () => clearSubagentRunSteerRestart,
4165
+ countActiveDescendantRuns: () => countActiveDescendantRuns,
4166
+ countActiveRunsForSession: () => countActiveRunsForSession,
4167
+ initSubagentRegistry: () => initSubagentRegistry,
4168
+ isSubagentSessionRunActive: () => isSubagentSessionRunActive,
4169
+ listDescendantRunsForRequester: () => listDescendantRunsForRequester,
4170
+ listSubagentRunsForRequester: () => listSubagentRunsForRequester,
4171
+ markSubagentRunForSteerRestart: () => markSubagentRunForSteerRestart,
4172
+ markSubagentRunTerminated: () => markSubagentRunTerminated,
4173
+ registerSubagentRun: () => registerSubagentRun,
4174
+ replaceSubagentRunAfterSteer: () => replaceSubagentRunAfterSteer,
4175
+ resolveRequesterForChildSession: () => resolveRequesterForChildSession
4176
+ });
4177
+ const subagentRuns = /* @__PURE__ */ new Map();
4178
+ let sweeper = null;
4179
+ let listenerStarted = false;
4180
+ let listenerStop = null;
4181
+ var restoreAttempted = false;
4182
+ const SUBAGENT_ANNOUNCE_TIMEOUT_MS = 12e4;
4183
+ const MIN_ANNOUNCE_RETRY_DELAY_MS = 1e3;
4184
+ const MAX_ANNOUNCE_RETRY_DELAY_MS = 8e3;
4185
+ /**
4186
+ * Maximum number of announce delivery attempts before giving up.
4187
+ * Prevents infinite retry loops when `runSubagentAnnounceFlow` repeatedly
4188
+ * returns `false` due to stale state or transient conditions (#18264).
4189
+ */
4190
+ const MAX_ANNOUNCE_RETRY_COUNT = 3;
4191
+ /**
4192
+ * Announce entries older than this are force-expired even if delivery never
4193
+ * succeeded. Guards against stale registry entries surviving gateway restarts.
4194
+ */
4195
+ const ANNOUNCE_EXPIRY_MS = 5 * 6e4;
4196
+ function resolveAnnounceRetryDelayMs(retryCount) {
4197
+ const boundedRetryCount = Math.max(0, Math.min(retryCount, 10));
4198
+ const baseDelay = MIN_ANNOUNCE_RETRY_DELAY_MS * 2 ** Math.max(0, boundedRetryCount - 1);
4199
+ return Math.min(baseDelay, MAX_ANNOUNCE_RETRY_DELAY_MS);
4200
+ }
4201
+ function logAnnounceGiveUp(entry, reason) {
4202
+ const retryCount = entry.announceRetryCount ?? 0;
4203
+ const endedAgoMs = typeof entry.endedAt === "number" ? Math.max(0, Date.now() - entry.endedAt) : void 0;
4204
+ const endedAgoLabel = endedAgoMs != null ? `${Math.round(endedAgoMs / 1e3)}s` : "n/a";
4205
+ defaultRuntime.log(`[warn] Subagent announce give up (${reason}) run=${entry.runId} child=${entry.childSessionKey} requester=${entry.requesterSessionKey} retries=${retryCount} endedAgo=${endedAgoLabel}`);
4206
+ }
4207
+ function persistSubagentRuns() {
4208
+ persistSubagentRunsToDisk(subagentRuns);
4209
+ }
4210
+ function findSessionEntryByKey(store, sessionKey) {
4211
+ const direct = store[sessionKey];
4212
+ if (direct) return direct;
4213
+ const normalized = sessionKey.toLowerCase();
4214
+ for (const [key, entry] of Object.entries(store)) if (key.toLowerCase() === normalized) return entry;
4215
+ }
4216
+ function resolveSubagentRunOrphanReason(params) {
4217
+ const childSessionKey = params.entry.childSessionKey?.trim();
4218
+ if (!childSessionKey) return "missing-session-entry";
4219
+ try {
4220
+ const cfg = loadConfig();
4221
+ const agentId = resolveAgentIdFromSessionKey(childSessionKey);
4222
+ const storePath = resolveStorePath(cfg.session?.store, { agentId });
4223
+ let store = params.storeCache?.get(storePath);
4224
+ if (!store) {
4225
+ store = loadSessionStore(storePath);
4226
+ params.storeCache?.set(storePath, store);
4227
+ }
4228
+ const sessionEntry = findSessionEntryByKey(store, childSessionKey);
4229
+ if (!sessionEntry) return "missing-session-entry";
4230
+ if (typeof sessionEntry.sessionId !== "string" || !sessionEntry.sessionId.trim()) return "missing-session-id";
4231
+ return null;
4232
+ } catch {
4233
+ return null;
4234
+ }
4235
+ }
4236
+ function reconcileOrphanedRun(params) {
4237
+ const now = Date.now();
4238
+ let changed = false;
4239
+ if (typeof params.entry.endedAt !== "number") {
4240
+ params.entry.endedAt = now;
4241
+ changed = true;
4242
+ }
4243
+ const orphanOutcome = {
4244
+ status: "error",
4245
+ error: `orphaned subagent run (${params.reason})`
4246
+ };
4247
+ if (!runOutcomesEqual(params.entry.outcome, orphanOutcome)) {
4248
+ params.entry.outcome = orphanOutcome;
4249
+ changed = true;
4250
+ }
4251
+ if (params.entry.endedReason !== SUBAGENT_ENDED_REASON_ERROR) {
4252
+ params.entry.endedReason = SUBAGENT_ENDED_REASON_ERROR;
4253
+ changed = true;
4254
+ }
4255
+ if (params.entry.cleanupHandled !== true) {
4256
+ params.entry.cleanupHandled = true;
4257
+ changed = true;
4258
+ }
4259
+ if (typeof params.entry.cleanupCompletedAt !== "number") {
4260
+ params.entry.cleanupCompletedAt = now;
4261
+ changed = true;
4262
+ }
4263
+ const removed = subagentRuns.delete(params.runId);
4264
+ resumedRuns.delete(params.runId);
4265
+ if (!removed && !changed) return false;
4266
+ defaultRuntime.log(`[warn] Subagent orphan run pruned source=${params.source} run=${params.runId} child=${params.entry.childSessionKey} reason=${params.reason}`);
4267
+ return true;
4268
+ }
4269
+ function reconcileOrphanedRestoredRuns() {
4270
+ const storeCache = /* @__PURE__ */ new Map();
4271
+ let changed = false;
4272
+ for (const [runId, entry] of subagentRuns.entries()) {
4273
+ const orphanReason = resolveSubagentRunOrphanReason({
4274
+ entry,
4275
+ storeCache
4276
+ });
4277
+ if (!orphanReason) continue;
4278
+ if (reconcileOrphanedRun({
4279
+ runId,
4280
+ entry,
4281
+ reason: orphanReason,
4282
+ source: "restore"
4283
+ })) changed = true;
4284
+ }
4285
+ return changed;
4286
+ }
4287
+ const resumedRuns = /* @__PURE__ */ new Set();
4288
+ const endedHookInFlightRunIds = /* @__PURE__ */ new Set();
4289
+ function suppressAnnounceForSteerRestart(entry) {
4290
+ return entry?.suppressAnnounceReason === "steer-restart";
4291
+ }
4292
+ function shouldKeepThreadBindingAfterRun(params) {
4293
+ if (params.reason === SUBAGENT_ENDED_REASON_KILLED) return false;
4294
+ return params.entry.spawnMode === "session";
4295
+ }
4296
+ function shouldEmitEndedHookForRun(params) {
4297
+ return !shouldKeepThreadBindingAfterRun(params);
4298
+ }
4299
+ async function emitSubagentEndedHookForRun(params) {
4300
+ const reason = params.reason ?? params.entry.endedReason ?? SUBAGENT_ENDED_REASON_COMPLETE;
4301
+ const outcome = resolveLifecycleOutcomeFromRunOutcome(params.entry.outcome);
4302
+ const error = params.entry.outcome?.status === "error" ? params.entry.outcome.error : void 0;
4303
+ await emitSubagentEndedHookOnce({
4304
+ entry: params.entry,
4305
+ reason,
4306
+ sendFarewell: params.sendFarewell,
4307
+ accountId: params.accountId ?? params.entry.requesterOrigin?.accountId,
4308
+ outcome,
4309
+ error,
4310
+ inFlightRunIds: endedHookInFlightRunIds,
4311
+ persist: persistSubagentRuns
4312
+ });
4313
+ }
4314
+ async function completeSubagentRun(params) {
4315
+ const entry = subagentRuns.get(params.runId);
4316
+ if (!entry) return;
4317
+ let mutated = false;
4318
+ const endedAt = typeof params.endedAt === "number" ? params.endedAt : Date.now();
4319
+ if (entry.endedAt !== endedAt) {
4320
+ entry.endedAt = endedAt;
4321
+ mutated = true;
4322
+ }
4323
+ if (!runOutcomesEqual(entry.outcome, params.outcome)) {
4324
+ entry.outcome = params.outcome;
4325
+ mutated = true;
4326
+ }
4327
+ if (entry.endedReason !== params.reason) {
4328
+ entry.endedReason = params.reason;
4329
+ mutated = true;
4330
+ }
4331
+ if (mutated) persistSubagentRuns();
4332
+ const suppressedForSteerRestart = suppressAnnounceForSteerRestart(entry);
4333
+ const shouldEmitEndedHook = !suppressedForSteerRestart && shouldEmitEndedHookForRun({
4334
+ entry,
4335
+ reason: params.reason
4336
+ });
4337
+ if (!(shouldEmitEndedHook && params.triggerCleanup && entry.expectsCompletionMessage === true && !suppressedForSteerRestart) && shouldEmitEndedHook) await emitSubagentEndedHookForRun({
4338
+ entry,
4339
+ reason: params.reason,
4340
+ sendFarewell: params.sendFarewell,
4341
+ accountId: params.accountId
4342
+ });
4343
+ if (!params.triggerCleanup) return;
4344
+ if (suppressedForSteerRestart) return;
4345
+ startSubagentAnnounceCleanupFlow(params.runId, entry);
4346
+ }
4347
+ function startSubagentAnnounceCleanupFlow(runId, entry) {
4348
+ if (!beginSubagentCleanup(runId)) return false;
4349
+ const requesterOrigin = normalizeDeliveryContext(entry.requesterOrigin);
4350
+ runSubagentAnnounceFlow({
4351
+ childSessionKey: entry.childSessionKey,
4352
+ childRunId: entry.runId,
4353
+ requesterSessionKey: entry.requesterSessionKey,
4354
+ requesterOrigin,
4355
+ requesterDisplayKey: entry.requesterDisplayKey,
4356
+ task: entry.task,
4357
+ timeoutMs: SUBAGENT_ANNOUNCE_TIMEOUT_MS,
4358
+ cleanup: entry.cleanup,
4359
+ waitForCompletion: false,
4360
+ startedAt: entry.startedAt,
4361
+ endedAt: entry.endedAt,
4362
+ label: entry.label,
4363
+ outcome: entry.outcome,
4364
+ spawnMode: entry.spawnMode,
4365
+ expectsCompletionMessage: entry.expectsCompletionMessage
4366
+ }).then((didAnnounce) => {
4367
+ finalizeSubagentCleanup(runId, entry.cleanup, didAnnounce);
4368
+ });
4369
+ return true;
4370
+ }
4371
+ function resumeSubagentRun(runId) {
4372
+ if (!runId || resumedRuns.has(runId)) return;
4373
+ const entry = subagentRuns.get(runId);
4374
+ if (!entry) return;
4375
+ const orphanReason = resolveSubagentRunOrphanReason({ entry });
4376
+ if (orphanReason) {
4377
+ if (reconcileOrphanedRun({
4378
+ runId,
4379
+ entry,
4380
+ reason: orphanReason,
4381
+ source: "resume"
4382
+ })) persistSubagentRuns();
4383
+ return;
4384
+ }
4385
+ if (entry.cleanupCompletedAt) return;
4386
+ if ((entry.announceRetryCount ?? 0) >= MAX_ANNOUNCE_RETRY_COUNT) {
4387
+ logAnnounceGiveUp(entry, "retry-limit");
4388
+ entry.cleanupCompletedAt = Date.now();
4389
+ persistSubagentRuns();
4390
+ return;
4391
+ }
4392
+ if (typeof entry.endedAt === "number" && Date.now() - entry.endedAt > ANNOUNCE_EXPIRY_MS) {
4393
+ logAnnounceGiveUp(entry, "expiry");
4394
+ entry.cleanupCompletedAt = Date.now();
4395
+ persistSubagentRuns();
4396
+ return;
4397
+ }
4398
+ const now = Date.now();
4399
+ const delayMs = resolveAnnounceRetryDelayMs(entry.announceRetryCount ?? 0);
4400
+ const earliestRetryAt = (entry.lastAnnounceRetryAt ?? 0) + delayMs;
4401
+ if (entry.expectsCompletionMessage === true && entry.lastAnnounceRetryAt && now < earliestRetryAt) {
4402
+ const waitMs = Math.max(1, earliestRetryAt - now);
4403
+ setTimeout(() => {
4404
+ resumeSubagentRun(runId);
4405
+ }, waitMs).unref?.();
4406
+ resumedRuns.add(runId);
4407
+ return;
4408
+ }
4409
+ if (typeof entry.endedAt === "number" && entry.endedAt > 0) {
4410
+ if (suppressAnnounceForSteerRestart(entry)) {
4411
+ resumedRuns.add(runId);
4412
+ return;
4413
+ }
4414
+ if (!startSubagentAnnounceCleanupFlow(runId, entry)) return;
4415
+ resumedRuns.add(runId);
4416
+ return;
4417
+ }
4418
+ waitForSubagentCompletion(runId, resolveSubagentWaitTimeoutMs(loadConfig(), entry.runTimeoutSeconds));
4419
+ resumedRuns.add(runId);
4420
+ }
4421
+ function restoreSubagentRunsOnce() {
4422
+ if (restoreAttempted) return;
4423
+ restoreAttempted = true;
4424
+ try {
4425
+ if (restoreSubagentRunsFromDisk({
4426
+ runs: subagentRuns,
4427
+ mergeOnly: true
4428
+ }) === 0) return;
4429
+ if (reconcileOrphanedRestoredRuns()) persistSubagentRuns();
4430
+ if (subagentRuns.size === 0) return;
4431
+ ensureListener();
4432
+ if ([...subagentRuns.values()].some((entry) => entry.archiveAtMs)) startSweeper();
4433
+ for (const runId of subagentRuns.keys()) resumeSubagentRun(runId);
4434
+ } catch {}
4435
+ }
4436
+ function resolveArchiveAfterMs(cfg) {
4437
+ const minutes = (cfg ?? loadConfig()).agents?.defaults?.subagents?.archiveAfterMinutes ?? 60;
4438
+ if (!Number.isFinite(minutes) || minutes <= 0) return;
4439
+ return Math.max(1, Math.floor(minutes)) * 6e4;
4440
+ }
4441
+ function resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds) {
4442
+ return resolveAgentTimeoutMs({
4443
+ cfg,
4444
+ overrideSeconds: runTimeoutSeconds ?? 0
4445
+ });
4446
+ }
4447
+ function startSweeper() {
4448
+ if (sweeper) return;
4449
+ sweeper = setInterval(() => {
4450
+ sweepSubagentRuns();
4451
+ }, 6e4);
4452
+ sweeper.unref?.();
4453
+ }
4454
+ function stopSweeper() {
4455
+ if (!sweeper) return;
4456
+ clearInterval(sweeper);
4457
+ sweeper = null;
4458
+ }
4459
+ async function sweepSubagentRuns() {
4460
+ const now = Date.now();
4461
+ let mutated = false;
4462
+ for (const [runId, entry] of subagentRuns.entries()) {
4463
+ if (!entry.archiveAtMs || entry.archiveAtMs > now) continue;
4464
+ subagentRuns.delete(runId);
4465
+ mutated = true;
4466
+ try {
4467
+ await callGateway({
4468
+ method: "sessions.delete",
4469
+ params: {
4470
+ key: entry.childSessionKey,
4471
+ deleteTranscript: true,
4472
+ emitLifecycleHooks: false
4473
+ },
4474
+ timeoutMs: 1e4
4475
+ });
4476
+ } catch {}
4477
+ }
4478
+ if (mutated) persistSubagentRuns();
4479
+ if (subagentRuns.size === 0) stopSweeper();
4480
+ }
4481
+ function ensureListener() {
4482
+ if (listenerStarted) return;
4483
+ listenerStarted = true;
4484
+ listenerStop = onAgentEvent((evt) => {
4485
+ (async () => {
4486
+ if (!evt || evt.stream !== "lifecycle") return;
4487
+ const entry = subagentRuns.get(evt.runId);
4488
+ if (!entry) return;
4489
+ const phase = evt.data?.phase;
4490
+ if (phase === "start") {
4491
+ const startedAt = typeof evt.data?.startedAt === "number" ? evt.data.startedAt : void 0;
4492
+ if (startedAt) {
4493
+ entry.startedAt = startedAt;
4494
+ persistSubagentRuns();
4495
+ }
4496
+ return;
4497
+ }
4498
+ if (phase !== "end" && phase !== "error") return;
4499
+ const endedAt = typeof evt.data?.endedAt === "number" ? evt.data.endedAt : Date.now();
4500
+ const error = typeof evt.data?.error === "string" ? evt.data.error : void 0;
4501
+ const outcome = phase === "error" ? {
4502
+ status: "error",
4503
+ error
4504
+ } : evt.data?.aborted ? { status: "timeout" } : { status: "ok" };
4505
+ await completeSubagentRun({
4506
+ runId: evt.runId,
4507
+ endedAt,
4508
+ outcome,
4509
+ reason: phase === "error" ? SUBAGENT_ENDED_REASON_ERROR : SUBAGENT_ENDED_REASON_COMPLETE,
4510
+ sendFarewell: true,
4511
+ accountId: entry.requesterOrigin?.accountId,
4512
+ triggerCleanup: true
4513
+ });
4514
+ })();
4515
+ });
4516
+ }
4517
+ async function finalizeSubagentCleanup(runId, cleanup, didAnnounce) {
4518
+ const entry = subagentRuns.get(runId);
4519
+ if (!entry) return;
4520
+ if (didAnnounce) {
4521
+ await emitCompletionEndedHookIfNeeded(entry, resolveCleanupCompletionReason(entry));
4522
+ completeCleanupBookkeeping({
4523
+ runId,
4524
+ entry,
4525
+ cleanup,
4526
+ completedAt: Date.now()
4527
+ });
4528
+ return;
4529
+ }
4530
+ const now = Date.now();
4531
+ const deferredDecision = resolveDeferredCleanupDecision({
4532
+ entry,
4533
+ now,
4534
+ activeDescendantRuns: Math.max(0, countActiveDescendantRuns(entry.childSessionKey)),
4535
+ announceExpiryMs: ANNOUNCE_EXPIRY_MS,
4536
+ maxAnnounceRetryCount: MAX_ANNOUNCE_RETRY_COUNT,
4537
+ deferDescendantDelayMs: MIN_ANNOUNCE_RETRY_DELAY_MS,
4538
+ resolveAnnounceRetryDelayMs
4539
+ });
4540
+ if (deferredDecision.kind === "defer-descendants") {
4541
+ entry.lastAnnounceRetryAt = now;
4542
+ entry.cleanupHandled = false;
4543
+ resumedRuns.delete(runId);
4544
+ persistSubagentRuns();
4545
+ setTimeout(() => {
4546
+ resumeSubagentRun(runId);
4547
+ }, deferredDecision.delayMs).unref?.();
4548
+ return;
4549
+ }
4550
+ if (deferredDecision.retryCount != null) {
4551
+ entry.announceRetryCount = deferredDecision.retryCount;
4552
+ entry.lastAnnounceRetryAt = now;
4553
+ }
4554
+ if (deferredDecision.kind === "give-up") {
4555
+ await emitCompletionEndedHookIfNeeded(entry, resolveCleanupCompletionReason(entry));
4556
+ logAnnounceGiveUp(entry, deferredDecision.reason);
4557
+ completeCleanupBookkeeping({
4558
+ runId,
4559
+ entry,
4560
+ cleanup: "keep",
4561
+ completedAt: now
4562
+ });
4563
+ return;
4564
+ }
4565
+ entry.cleanupHandled = false;
4566
+ resumedRuns.delete(runId);
4567
+ persistSubagentRuns();
4568
+ if (deferredDecision.resumeDelayMs == null) return;
4569
+ setTimeout(() => {
4570
+ resumeSubagentRun(runId);
4571
+ }, deferredDecision.resumeDelayMs).unref?.();
4572
+ }
4573
+ async function emitCompletionEndedHookIfNeeded(entry, reason) {
4574
+ if (entry.expectsCompletionMessage === true && shouldEmitEndedHookForRun({
4575
+ entry,
4576
+ reason
4577
+ })) await emitSubagentEndedHookForRun({
4578
+ entry,
4579
+ reason,
4580
+ sendFarewell: true
4581
+ });
4582
+ }
4583
+ function completeCleanupBookkeeping(params) {
4584
+ if (params.cleanup === "delete") {
4585
+ subagentRuns.delete(params.runId);
4586
+ persistSubagentRuns();
4587
+ retryDeferredCompletedAnnounces(params.runId);
4588
+ return;
4589
+ }
4590
+ params.entry.cleanupCompletedAt = params.completedAt;
4591
+ persistSubagentRuns();
4592
+ retryDeferredCompletedAnnounces(params.runId);
4593
+ }
4594
+ function retryDeferredCompletedAnnounces(excludeRunId) {
4595
+ const now = Date.now();
4596
+ for (const [runId, entry] of subagentRuns.entries()) {
4597
+ if (excludeRunId && runId === excludeRunId) continue;
4598
+ if (typeof entry.endedAt !== "number") continue;
4599
+ if (entry.cleanupCompletedAt || entry.cleanupHandled) continue;
4600
+ if (suppressAnnounceForSteerRestart(entry)) continue;
4601
+ if (now - (entry.endedAt ?? now) > ANNOUNCE_EXPIRY_MS) {
4602
+ logAnnounceGiveUp(entry, "expiry");
4603
+ entry.cleanupCompletedAt = now;
4604
+ persistSubagentRuns();
4605
+ continue;
4606
+ }
4607
+ resumedRuns.delete(runId);
4608
+ resumeSubagentRun(runId);
4609
+ }
4610
+ }
4611
+ function beginSubagentCleanup(runId) {
4612
+ const entry = subagentRuns.get(runId);
4613
+ if (!entry) return false;
4614
+ if (entry.cleanupCompletedAt) return false;
4615
+ if (entry.cleanupHandled) return false;
4616
+ entry.cleanupHandled = true;
4617
+ persistSubagentRuns();
4618
+ return true;
4619
+ }
4620
+ function markSubagentRunForSteerRestart(runId) {
4621
+ const key = runId.trim();
4622
+ if (!key) return false;
4623
+ const entry = subagentRuns.get(key);
4624
+ if (!entry) return false;
4625
+ if (entry.suppressAnnounceReason === "steer-restart") return true;
4626
+ entry.suppressAnnounceReason = "steer-restart";
4627
+ persistSubagentRuns();
4628
+ return true;
4629
+ }
4630
+ function clearSubagentRunSteerRestart(runId) {
4631
+ const key = runId.trim();
4632
+ if (!key) return false;
4633
+ const entry = subagentRuns.get(key);
4634
+ if (!entry) return false;
4635
+ if (entry.suppressAnnounceReason !== "steer-restart") return true;
4636
+ entry.suppressAnnounceReason = void 0;
4637
+ persistSubagentRuns();
4638
+ resumedRuns.delete(key);
4639
+ if (typeof entry.endedAt === "number" && !entry.cleanupCompletedAt) resumeSubagentRun(key);
4640
+ return true;
4641
+ }
4642
+ function replaceSubagentRunAfterSteer(params) {
4643
+ const previousRunId = params.previousRunId.trim();
4644
+ const nextRunId = params.nextRunId.trim();
4645
+ if (!previousRunId || !nextRunId) return false;
4646
+ const source = subagentRuns.get(previousRunId) ?? params.fallback;
4647
+ if (!source) return false;
4648
+ if (previousRunId !== nextRunId) {
4649
+ subagentRuns.delete(previousRunId);
4650
+ resumedRuns.delete(previousRunId);
4651
+ }
4652
+ const now = Date.now();
4653
+ const cfg = loadConfig();
4654
+ const archiveAfterMs = resolveArchiveAfterMs(cfg);
4655
+ const spawnMode = source.spawnMode === "session" ? "session" : "run";
4656
+ const archiveAtMs = spawnMode === "session" ? void 0 : archiveAfterMs ? now + archiveAfterMs : void 0;
4657
+ const runTimeoutSeconds = params.runTimeoutSeconds ?? source.runTimeoutSeconds ?? 0;
4658
+ const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds);
4659
+ const next = {
4660
+ ...source,
4661
+ runId: nextRunId,
4662
+ startedAt: now,
4663
+ endedAt: void 0,
4664
+ endedReason: void 0,
4665
+ endedHookEmittedAt: void 0,
4666
+ outcome: void 0,
4667
+ cleanupCompletedAt: void 0,
4668
+ cleanupHandled: false,
4669
+ suppressAnnounceReason: void 0,
4670
+ announceRetryCount: void 0,
4671
+ lastAnnounceRetryAt: void 0,
4672
+ spawnMode,
4673
+ archiveAtMs,
4674
+ runTimeoutSeconds
4675
+ };
4676
+ subagentRuns.set(nextRunId, next);
4677
+ ensureListener();
4678
+ persistSubagentRuns();
4679
+ if (archiveAtMs) startSweeper();
4680
+ waitForSubagentCompletion(nextRunId, waitTimeoutMs);
4681
+ return true;
4682
+ }
4683
+ function registerSubagentRun(params) {
4684
+ const now = Date.now();
4685
+ const cfg = loadConfig();
4686
+ const archiveAfterMs = resolveArchiveAfterMs(cfg);
4687
+ const spawnMode = params.spawnMode === "session" ? "session" : "run";
4688
+ const archiveAtMs = spawnMode === "session" ? void 0 : archiveAfterMs ? now + archiveAfterMs : void 0;
4689
+ const runTimeoutSeconds = params.runTimeoutSeconds ?? 0;
4690
+ const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds);
4691
+ const requesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
4692
+ subagentRuns.set(params.runId, {
4693
+ runId: params.runId,
4694
+ childSessionKey: params.childSessionKey,
4695
+ requesterSessionKey: params.requesterSessionKey,
4696
+ requesterOrigin,
4697
+ requesterDisplayKey: params.requesterDisplayKey,
4698
+ task: params.task,
4699
+ cleanup: params.cleanup,
4700
+ expectsCompletionMessage: params.expectsCompletionMessage,
4701
+ spawnMode,
4702
+ label: params.label,
4703
+ model: params.model,
4704
+ runTimeoutSeconds,
4705
+ createdAt: now,
4706
+ startedAt: now,
4707
+ archiveAtMs,
4708
+ cleanupHandled: false
4709
+ });
4710
+ ensureListener();
4711
+ persistSubagentRuns();
4712
+ if (archiveAtMs) startSweeper();
4713
+ waitForSubagentCompletion(params.runId, waitTimeoutMs);
4714
+ }
4715
+ async function waitForSubagentCompletion(runId, waitTimeoutMs) {
4716
+ try {
4717
+ const timeoutMs = Math.max(1, Math.floor(waitTimeoutMs));
4718
+ const wait = await callGateway({
4719
+ method: "agent.wait",
4720
+ params: {
4721
+ runId,
4722
+ timeoutMs
4723
+ },
4724
+ timeoutMs: timeoutMs + 1e4
4725
+ });
4726
+ if (wait?.status !== "ok" && wait?.status !== "error" && wait?.status !== "timeout") return;
4727
+ const entry = subagentRuns.get(runId);
4728
+ if (!entry) return;
4729
+ let mutated = false;
4730
+ if (typeof wait.startedAt === "number") {
4731
+ entry.startedAt = wait.startedAt;
4732
+ mutated = true;
4733
+ }
4734
+ if (typeof wait.endedAt === "number") {
4735
+ entry.endedAt = wait.endedAt;
4736
+ mutated = true;
4737
+ }
4738
+ if (!entry.endedAt) {
4739
+ entry.endedAt = Date.now();
4740
+ mutated = true;
4741
+ }
4742
+ const waitError = typeof wait.error === "string" ? wait.error : void 0;
4743
+ const outcome = wait.status === "error" ? {
4744
+ status: "error",
4745
+ error: waitError
4746
+ } : wait.status === "timeout" ? { status: "timeout" } : { status: "ok" };
4747
+ if (!runOutcomesEqual(entry.outcome, outcome)) {
4748
+ entry.outcome = outcome;
4749
+ mutated = true;
4750
+ }
4751
+ if (mutated) persistSubagentRuns();
4752
+ await completeSubagentRun({
4753
+ runId,
4754
+ endedAt: entry.endedAt,
4755
+ outcome,
4756
+ reason: wait.status === "error" ? SUBAGENT_ENDED_REASON_ERROR : SUBAGENT_ENDED_REASON_COMPLETE,
4757
+ sendFarewell: true,
4758
+ accountId: entry.requesterOrigin?.accountId,
4759
+ triggerCleanup: true
4760
+ });
4761
+ } catch {}
4762
+ }
4763
+ function findRunIdsByChildSessionKey(childSessionKey) {
4764
+ return findRunIdsByChildSessionKeyFromRuns(subagentRuns, childSessionKey);
4765
+ }
4766
+ function resolveRequesterForChildSession(childSessionKey) {
4767
+ const resolved = resolveRequesterForChildSessionFromRuns(getSubagentRunsSnapshotForRead(subagentRuns), childSessionKey);
4768
+ if (!resolved) return null;
4769
+ return {
4770
+ requesterSessionKey: resolved.requesterSessionKey,
4771
+ requesterOrigin: normalizeDeliveryContext(resolved.requesterOrigin)
4772
+ };
4773
+ }
4774
+ function isSubagentSessionRunActive(childSessionKey) {
4775
+ const runIds = findRunIdsByChildSessionKey(childSessionKey);
4776
+ for (const runId of runIds) {
4777
+ const entry = subagentRuns.get(runId);
4778
+ if (!entry) continue;
4779
+ if (typeof entry.endedAt !== "number") return true;
4780
+ }
4781
+ return false;
4782
+ }
4783
+ function markSubagentRunTerminated(params) {
4784
+ const runIds = /* @__PURE__ */ new Set();
4785
+ if (typeof params.runId === "string" && params.runId.trim()) runIds.add(params.runId.trim());
4786
+ if (typeof params.childSessionKey === "string" && params.childSessionKey.trim()) for (const runId of findRunIdsByChildSessionKey(params.childSessionKey)) runIds.add(runId);
4787
+ if (runIds.size === 0) return 0;
4788
+ const now = Date.now();
4789
+ const reason = params.reason?.trim() || "killed";
4790
+ let updated = 0;
4791
+ const entriesByChildSessionKey = /* @__PURE__ */ new Map();
4792
+ for (const runId of runIds) {
4793
+ const entry = subagentRuns.get(runId);
4794
+ if (!entry) continue;
4795
+ if (typeof entry.endedAt === "number") continue;
4796
+ entry.endedAt = now;
4797
+ entry.outcome = {
4798
+ status: "error",
4799
+ error: reason
4800
+ };
4801
+ entry.endedReason = SUBAGENT_ENDED_REASON_KILLED;
4802
+ entry.cleanupHandled = true;
4803
+ entry.cleanupCompletedAt = now;
4804
+ entry.suppressAnnounceReason = "killed";
4805
+ if (!entriesByChildSessionKey.has(entry.childSessionKey)) entriesByChildSessionKey.set(entry.childSessionKey, entry);
4806
+ updated += 1;
4807
+ }
4808
+ if (updated > 0) {
4809
+ persistSubagentRuns();
4810
+ for (const entry of entriesByChildSessionKey.values()) emitSubagentEndedHookOnce({
4811
+ entry,
4812
+ reason: SUBAGENT_ENDED_REASON_KILLED,
4813
+ sendFarewell: true,
4814
+ outcome: SUBAGENT_ENDED_OUTCOME_KILLED,
4815
+ error: reason,
4816
+ inFlightRunIds: endedHookInFlightRunIds,
4817
+ persist: persistSubagentRuns
4818
+ }).catch(() => {});
4819
+ }
4820
+ return updated;
4821
+ }
4822
+ function listSubagentRunsForRequester(requesterSessionKey) {
4823
+ return listRunsForRequesterFromRuns(subagentRuns, requesterSessionKey);
4824
+ }
4825
+ function countActiveRunsForSession(requesterSessionKey) {
4826
+ return countActiveRunsForSessionFromRuns(getSubagentRunsSnapshotForRead(subagentRuns), requesterSessionKey);
4827
+ }
4828
+ function countActiveDescendantRuns(rootSessionKey) {
4829
+ return countActiveDescendantRunsFromRuns(getSubagentRunsSnapshotForRead(subagentRuns), rootSessionKey);
4830
+ }
4831
+ function listDescendantRunsForRequester(rootSessionKey) {
4832
+ return listDescendantRunsForRequesterFromRuns(getSubagentRunsSnapshotForRead(subagentRuns), rootSessionKey);
4833
+ }
4834
+ function initSubagentRegistry() {
4835
+ restoreSubagentRunsOnce();
4836
+ }
4837
+
4838
+ //#endregion
4839
+ export { clearCommandLane as $, createAgentToAgentPolicy as A, getSubagentDepthFromSessionStore as B, runAgentStep as C, sanitizeTextContent as D, extractAssistantText as E, resolveDisplaySessionKey as F, enqueueFollowupRun as G, registerSessionBindingAdapter as H, resolveInternalSessionKey as I, isRoutableChannel as J, getFollowupQueueDepth as K, resolveMainSessionAlias as L, resolveEffectiveSessionToolsVisibility as M, resolveSandboxedSessionToolContext as N, stripToolMessages as O, isResolvedSessionVisibleToRequester as P, clearSessionQueues as Q, resolveSessionReference as R, readLatestAssistantReply as S, deriveChannel as T, unregisterSessionBindingAdapter as U, extractTextFromChatContent as V, resolveQueueSettings as W, normalizeReplyPayload as X, routeReply as Y, createReceiptCard as Z, buildAgentToAgentReplyContext as _, listDescendantRunsForRequester as a, waitForActiveTasks as at, resolveAnnounceTargetFromKey as b, markSubagentRunTerminated as c, logSessionStateChange as ct, subagent_registry_exports as d, logWebhookReceived as dt, getActiveTaskCount as et, resolveAgentTimeoutMs as f, startDiagnosticHeartbeat as ft, buildAgentToAgentMessageContext as g, extractQueueDirective as gt, buildAgentToAgentAnnounceContext as h, isDiagnosticsEnabled as ht, initSubagentRegistry as i, setCommandLaneConcurrency as it, createSessionVisibilityGuard as j, stripReasoningTagsFromText as k, registerSubagentRun as l, logWebhookError as lt, runSubagentAnnounceFlow as m, emitDiagnosticEvent as mt, countActiveDescendantRuns as n, getTotalQueueSize as nt, listSubagentRunsForRequester as o, logMessageProcessed as ot, buildSubagentSystemPrompt as p, stopDiagnosticHeartbeat as pt, scheduleFollowupDrain as q, countActiveRunsForSession as r, resetAllLanes as rt, markSubagentRunForSteerRestart as s, logMessageQueued as st, clearSubagentRunSteerRestart as t, getQueueSize as tt, replaceSubagentRunAfterSteer as u, logWebhookProcessed as ut, isAnnounceSkip as v, classifySessionKind as w, resolvePingPongTurns as x, isReplySkip as y, shouldResolveSessionIdInput as z };