remoteclaw 0.0.0 → 0.1.0-next.2abd2fa

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