@noxsoft/anima 2.0.2 → 2.0.4

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 (829) hide show
  1. package/README.md +1260 -28
  2. package/dist/accounts-Bth3PpPD.js +260 -0
  3. package/dist/accounts-D8CPKNkN.js +259 -0
  4. package/dist/acp-cli-ByK6lS6c.js +1081 -0
  5. package/dist/acp-cli-CaQCjIw4.js +1084 -0
  6. package/dist/agent-BgIkqd3F.js +725 -0
  7. package/dist/agent-N5BDcge4.js +725 -0
  8. package/dist/agent-events-COH7NDW2.js +182 -0
  9. package/dist/agent-scope-CPphqq-U.js +452 -0
  10. package/dist/agent-scope-DZgptr9J.js +452 -0
  11. package/dist/agent-scope-cj2QCT6R.js +112 -0
  12. package/dist/agents-NEudYMdg.js +774 -0
  13. package/dist/agents.config-Bujs-NIy.js +182 -0
  14. package/dist/agents.config-jp7OLssr.js +182 -0
  15. package/dist/argv-BMZMiW7v.js +73 -0
  16. package/dist/audit-C-UJhfdv.js +2401 -0
  17. package/dist/audit-CeCO7SK5.js +2401 -0
  18. package/dist/auth-BNZsOHGF.js +648 -0
  19. package/dist/auth-DMPZWzEa.js +639 -0
  20. package/dist/auth-choice-5VnaGMD-.js +2681 -0
  21. package/dist/auth-choice-DA2k4vs8.js +2681 -0
  22. package/dist/auth-health-B7FqA26_.js +149 -0
  23. package/dist/auth-health-VO_MPqVX.js +149 -0
  24. package/dist/auth-profiles-BDrNYX_n.js +1564 -0
  25. package/dist/auth-profiles-CxSHydjn.js +2689 -0
  26. package/dist/banner-BtDZPRzi.js +294 -0
  27. package/dist/browser-cli-8yQMpxb8.js +1679 -0
  28. package/dist/browser-cli-Czg3JtDH.js +1676 -0
  29. package/dist/build-info.json +3 -3
  30. package/dist/bundled/boot-md/handler.js +16 -16
  31. package/dist/bundled/bootstrap-extra-files/handler.js +4 -4
  32. package/dist/bundled/command-logger/handler.js +1 -1
  33. package/dist/bundled/session-memory/handler.js +5 -5
  34. package/dist/call-BIzCaKZb.js +282 -0
  35. package/dist/call-BYDpTVCZ.js +282 -0
  36. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  37. package/dist/catalog-CqKiUgu6.js +185 -0
  38. package/dist/catalog-DMfEg-oK.js +185 -0
  39. package/dist/channel-options-BrtCtyrT.js +32 -0
  40. package/dist/channel-options-CO21Gl8p.js +33 -0
  41. package/dist/channel-selection-Bbm1lq3P.js +51 -0
  42. package/dist/channel-selection-CqcX7Ocw.js +51 -0
  43. package/dist/channel-web-DrsT6OAE.js +2162 -0
  44. package/dist/channels-cli-Juyh1S6n.js +1304 -0
  45. package/dist/channels-cli-zNvi1m5c.js +1306 -0
  46. package/dist/channels-status-issues-CqzqshW4.js +18 -0
  47. package/dist/channels-status-issues-DdJdO866.js +18 -0
  48. package/dist/chrome-C4dOMO8z.js +1601 -0
  49. package/dist/chrome-DdcDzAtH.js +1629 -0
  50. package/dist/chrome-U3DRzjJD.js +1601 -0
  51. package/dist/chunk-D2nLsrEW.js +348 -0
  52. package/dist/clack-prompter-BI3RDW5w.js +92 -0
  53. package/dist/clack-prompter-Dwr1m_IZ.js +92 -0
  54. package/dist/cli/daemon-cli.js +1 -1
  55. package/dist/cli-C3cpDaz8.js +99 -0
  56. package/dist/cli-CjWUGdGC.js +101 -0
  57. package/dist/cli-session-BVjY_XrW.js +5463 -0
  58. package/dist/cli-session-gtuYN2Iq.js +5408 -0
  59. package/dist/client-Dswwze5_.js +1692 -0
  60. package/dist/client-LRKFjo4A.js +1692 -0
  61. package/dist/clipboard-BZKS9O1u.js +31 -0
  62. package/dist/clipboard-DES8b1AM.js +31 -0
  63. package/dist/command-format-CP1YTNCl.js +52 -0
  64. package/dist/command-format-CVL4K5cj.js +52 -0
  65. package/dist/command-format-G6N2zghg.js +38 -0
  66. package/dist/command-registry-BBvNvysr.js +248 -0
  67. package/dist/commands-AZ3n8Y2c.js +726 -0
  68. package/dist/commands-BMnD_QRY.js +726 -0
  69. package/dist/commands-registry-cFqZ6Ib4.js +766 -0
  70. package/dist/commands-registry-q13H7ng5.js +766 -0
  71. package/dist/common-CX5458fH.js +287 -0
  72. package/dist/common-DJbnT8ws.js +287 -0
  73. package/dist/completion-cli-BADRBcIl.js +432 -0
  74. package/dist/completion-cli-DMQgiObF.js +431 -0
  75. package/dist/config-CU-Axg8P.js +5704 -0
  76. package/dist/config-DaqbUdkI.js +5705 -0
  77. package/dist/config-cli-BPlbwiuA.js +244 -0
  78. package/dist/config-cli-DXgZJkPU.js +247 -0
  79. package/dist/config-guard-Ba49JNds.js +76 -0
  80. package/dist/config-guard-Cu0qMKZJ.js +93 -0
  81. package/dist/config-kVVm5EYV.js +6523 -0
  82. package/dist/config-sync-CzLnLTXt.js +91 -0
  83. package/dist/config-sync-DuydxPWx.js +91 -0
  84. package/dist/configure-CHgacLyi.js +960 -0
  85. package/dist/configure-DfHXDa1L.js +959 -0
  86. package/dist/context-DzgXOckU.js +60 -0
  87. package/dist/control-service-8_wKHwBa.js +72 -0
  88. package/dist/control-service-BtL1Jto_.js +72 -0
  89. package/dist/cron-cli-BCzSR2c0.js +448 -0
  90. package/dist/cron-cli-CCWNkykU.js +451 -0
  91. package/dist/daemon-cli-Bjkbu9Vy.js +565 -0
  92. package/dist/daemon-cli-CmlHcC1J.js +566 -0
  93. package/dist/daemon-cli.js +16 -16
  94. package/dist/daemon-runtime-C0tz7VAC.js +460 -0
  95. package/dist/daemon-runtime-rUTqCVwJ.js +460 -0
  96. package/dist/deliver-BBggsviM.js +1097 -0
  97. package/dist/deliver-CePITOl8.js +1162 -0
  98. package/dist/deliver-DFnVaetP.js +1097 -0
  99. package/dist/delivery-queue-BJQK3oh5.js +220 -0
  100. package/dist/deps-CeEKhrp7.js +42 -0
  101. package/dist/devices-cli-DQrDMrZH.js +198 -0
  102. package/dist/devices-cli-Oe-A1Dv0.js +195 -0
  103. package/dist/diagnostics-DxMFrBLO.js +35 -0
  104. package/dist/diagnostics-m79ZlMmZ.js +35 -0
  105. package/dist/directory-cli-BL6h8cGF.js +246 -0
  106. package/dist/directory-cli-Cjgmi_sj.js +243 -0
  107. package/dist/dispatcher-DAFbQM-c.js +100 -0
  108. package/dist/dispatcher-DNd40gUn.js +100 -0
  109. package/dist/dist-CqDI82ei.js +929 -0
  110. package/dist/dist-DnHRxR5U.js +929 -0
  111. package/dist/dns-cli-CFtV3BXK.js +200 -0
  112. package/dist/dns-cli-NyIHvQ5S.js +197 -0
  113. package/dist/dock-BdXLb5oY.js +753 -0
  114. package/dist/dock-jYICmNcI.js +753 -0
  115. package/dist/docs-cli-CrOaIK_H.js +161 -0
  116. package/dist/docs-cli-D_cmJDSr.js +159 -0
  117. package/dist/doctor-BpGxKrBl.js +1815 -0
  118. package/dist/doctor-D12wNQPU.js +1813 -0
  119. package/dist/doctor-completion-DeOfofek.js +92 -0
  120. package/dist/doctor-completion-DwjqdEcK.js +92 -0
  121. package/dist/doctor-config-flow-BI3mpkbd.js +1232 -0
  122. package/dist/doctor-config-flow-wMHheFkC.js +1232 -0
  123. package/dist/engine-BCtL-AMw.js +563 -0
  124. package/dist/engine-Bk_UT413.js +563 -0
  125. package/dist/entry.js +5 -5
  126. package/dist/env-v6411I8h.js +32 -0
  127. package/dist/exec-B7sUS164.js +1167 -0
  128. package/dist/exec-approvals-CroGJRUg.js +1221 -0
  129. package/dist/exec-approvals-cli-BTxF_RsH.js +371 -0
  130. package/dist/exec-approvals-cli-n1gyGwH2.js +368 -0
  131. package/dist/exec-mhSykkaa.js +255 -0
  132. package/dist/extensionAPI.js +3 -3
  133. package/dist/frontmatter-BmHq0vRD.js +204 -0
  134. package/dist/gateway-cli-DDBadlrS.js +19971 -0
  135. package/dist/gateway-cli-IZNkOMBe.js +19972 -0
  136. package/dist/gateway-rpc-Dtx8HN-n.js +28 -0
  137. package/dist/gateway-rpc-L2PVSqGj.js +28 -0
  138. package/dist/github-copilot-auth-DKyqDaGU.js +1418 -0
  139. package/dist/github-copilot-auth-DXpOMSd3.js +1418 -0
  140. package/dist/gmail-setup-utils-BKNczIJ9.js +428 -0
  141. package/dist/gmail-setup-utils-co0ppccC.js +428 -0
  142. package/dist/health-Bm8ZTvC3.js +1253 -0
  143. package/dist/health-DUf1gt4E.js +1258 -0
  144. package/dist/health-format-BksT6F68.js +208 -0
  145. package/dist/health-format-uzh1xYLD.js +208 -0
  146. package/dist/heartbeat-visibility-1TJb1Zao.js +98 -0
  147. package/dist/heartbeat-visibility-CwodtdcX.js +98 -0
  148. package/dist/help-format-C6cv_aZp.js +17 -0
  149. package/dist/helpers-N-uSFKOn.js +10 -0
  150. package/dist/hooks-cli-1POsXqOl.js +993 -0
  151. package/dist/hooks-cli-BGjILbze.js +991 -0
  152. package/dist/hooks-status-DE07n5RC.js +356 -0
  153. package/dist/hooks-status-Du-d1jde.js +356 -0
  154. package/dist/image-ops-B_AYV3tp.js +541 -0
  155. package/dist/image-ops-Bp0C6Mvr.js +541 -0
  156. package/dist/index.js +82 -82
  157. package/dist/init-9A0s7bWG.js +122 -0
  158. package/dist/init-DoyCHJDC.js +122 -0
  159. package/dist/installs-D1C9wHAq.js +383 -0
  160. package/dist/installs-Dh4dHayM.js +383 -0
  161. package/dist/ipv4-DCItfaJo.js +1964 -0
  162. package/dist/ipv4-DSOUVx0i.js +1964 -0
  163. package/dist/lanes-BvSnHq2h.js +232 -0
  164. package/dist/lifecycle-core-BY4WIf9g.js +388 -0
  165. package/dist/lifecycle-core-TQKyXO-6.js +387 -0
  166. package/dist/links-CNu_8RZl.js +15 -0
  167. package/dist/links-D2tt2ouh.js +15 -0
  168. package/dist/llm-slug-generator.js +4 -4
  169. package/dist/logging-BIeRw0WR.js +15 -0
  170. package/dist/logging-C7lb3Vjc.js +15 -0
  171. package/dist/login-DXWKewA2.js +59 -0
  172. package/dist/login-Fhh4uWmf.js +61 -0
  173. package/dist/login-pPs3UO38.js +61 -0
  174. package/dist/login-qr-CevLD8cV.js +326 -0
  175. package/dist/login-qr-GF2JMIy-.js +323 -0
  176. package/dist/login-qr-ZYYKD6Yt.js +321 -0
  177. package/dist/logs-cli-CzXbX8HZ.js +242 -0
  178. package/dist/logs-cli-D9ngH9PF.js +245 -0
  179. package/dist/manager-BD5rA3w0.js +3244 -0
  180. package/dist/manager-BDPgBQSH.js +3246 -0
  181. package/dist/manager-DRWMWM--.js +3244 -0
  182. package/dist/manifest-registry-DbvPaBXY.js +748 -0
  183. package/dist/manifest-registry-kHX_MFa1.js +748 -0
  184. package/dist/markdown-tables-CqwihY2m.js +347 -0
  185. package/dist/markdown-tables-DJV7eAJZ.js +348 -0
  186. package/dist/media-lUqN-0O9.js +1342 -0
  187. package/dist/memory-cli-BLXSpgnN.js +868 -0
  188. package/dist/memory-cli-BcGVkkRJ.js +869 -0
  189. package/dist/message-channel-D_jIO87f.js +110 -0
  190. package/dist/migrate-BpVOar4L.js +157 -0
  191. package/dist/migrate-CkgGDkWy.js +157 -0
  192. package/dist/model-selection-Cqt6aJ0G.js +2691 -0
  193. package/dist/models-CExsNQPH.js +2510 -0
  194. package/dist/models-cli-Ba3Jmwev.js +2739 -0
  195. package/dist/models-cli-iDAlsbL2.js +258 -0
  196. package/dist/net-0A_zcaQD.js +218 -0
  197. package/dist/node-cli-ATmwCXIk.js +1319 -0
  198. package/dist/node-cli-DYFR_V25.js +1322 -0
  199. package/dist/node-service-CN4LqR1A.js +67 -0
  200. package/dist/node-service-CWt3MdSC.js +67 -0
  201. package/dist/nodes-cli-BeVmhTz3.js +1197 -0
  202. package/dist/nodes-cli-QeJIfa18.js +1200 -0
  203. package/dist/nodes-screen-DHyWAlla.js +234 -0
  204. package/dist/nodes-screen-qs3jRBPk.js +234 -0
  205. package/dist/note-CSlg2BnB.js +73 -0
  206. package/dist/note-Ctvglhp1.js +73 -0
  207. package/dist/npm-registry-spec-DQd4M22q.js +351 -0
  208. package/dist/npm-registry-spec-PxisIMts.js +351 -0
  209. package/dist/onboard-DeruD10m.js +1166 -0
  210. package/dist/onboard-SAcu5N6N.js +1165 -0
  211. package/dist/onboard-channels-C4iSfFXR.js +672 -0
  212. package/dist/onboard-channels-oVTVgoyg.js +672 -0
  213. package/dist/onboard-helpers-B8roRwLP.js +365 -0
  214. package/dist/onboard-helpers-Dgh26hgP.js +365 -0
  215. package/dist/onboarding-Bi-ac8we.js +911 -0
  216. package/dist/onboarding-C2gjB2u8.js +910 -0
  217. package/dist/orchestrator-DlbAYMQP.js +357 -0
  218. package/dist/orchestrator-DlwVRVDA.js +357 -0
  219. package/dist/outbound-CkKgc6iR.js +2062 -0
  220. package/dist/outbound-Vfm5yDh3.js +214 -0
  221. package/dist/outbound-bs_VK51X.js +214 -0
  222. package/dist/outbound-send-deps-DDjiMfEL.js +55 -0
  223. package/dist/pairing-cli-CJYeuEik.js +118 -0
  224. package/dist/pairing-cli-mqopHI8s.js +121 -0
  225. package/dist/pairing-store-BsXzUDPv.js +388 -0
  226. package/dist/pairing-store-DoNj00-X.js +388 -0
  227. package/dist/path-env-C_xpiG8l.js +89 -0
  228. package/dist/path-env-DSSMHu5A.js +89 -0
  229. package/dist/paths-B1vRVCad.js +126 -0
  230. package/dist/paths-BMuHNFxg.js +238 -0
  231. package/dist/paths-BXQQzXGQ.js +129 -0
  232. package/dist/paths-Buw_geoe.js +54 -0
  233. package/dist/paths-DA9WYabg.js +222 -0
  234. package/dist/paths-DfQGx0_k.js +129 -0
  235. package/dist/pi-auth-json-DOPW3e4X.js +78 -0
  236. package/dist/pi-auth-json-MruLmI_X.js +82 -0
  237. package/dist/pi-auth-json-lae_wwwo.js +80 -0
  238. package/dist/pi-model-discovery-7q0GxMrp.js +3 -0
  239. package/dist/pi-tools.policy-Csmla32P.js +200 -0
  240. package/dist/pi-tools.policy-xYdDLEv9.js +200 -0
  241. package/dist/plugin-auto-enable-CViVVWgg.js +282 -0
  242. package/dist/plugin-auto-enable-CjZ238UI.js +282 -0
  243. package/dist/plugin-registry-B4Aw2hzq.js +32 -0
  244. package/dist/plugin-registry-DW81arxW.js +32 -0
  245. package/dist/plugin-sdk/cli/cli-name.d.ts +1 -1
  246. package/dist/plugin-sdk/config/paths.d.ts +2 -2
  247. package/dist/plugin-sdk/index.js +7 -7
  248. package/dist/plugins-DhcGAPDB.js +38 -0
  249. package/dist/plugins-DtghNRtM.js +168 -0
  250. package/dist/plugins-cli-4vWTmOAb.js +736 -0
  251. package/dist/plugins-cli-CdTMbP0X.js +734 -0
  252. package/dist/polls-D6eCdatA.js +1343 -0
  253. package/dist/ports-BtZx-JKD.js +96 -0
  254. package/dist/ports-C8bKN8s0.js +96 -0
  255. package/dist/ports-DHiKnPRX.js +344 -0
  256. package/dist/ports-vd93M_Pt.js +317 -0
  257. package/dist/program-CX3aUVeb.js +176 -0
  258. package/dist/program-context-BPos0ivo.js +496 -0
  259. package/dist/progress-oiAjiiNi.js +133 -0
  260. package/dist/prompt-style-Cm4wOtKm.js +9 -0
  261. package/dist/pw-ai-4QbK5YFe.js +1865 -0
  262. package/dist/pw-ai-BWz3Cxt7.js +1868 -0
  263. package/dist/pw-ai-C83HBue2.js +1867 -0
  264. package/dist/qmd-manager-BcMeZiGD.js +938 -0
  265. package/dist/qmd-manager-CPypGJ0P.js +935 -0
  266. package/dist/qmd-manager-CRrSkfia.js +937 -0
  267. package/dist/register.agent-DDY8KJhn.js +265 -0
  268. package/dist/register.agent-DKawm-9d.js +1003 -0
  269. package/dist/register.anima-CEWUo29k.js +193 -0
  270. package/dist/register.anima-DBWz2rk_.js +193 -0
  271. package/dist/register.configure-BX67qV8k.js +103 -0
  272. package/dist/register.configure-CWsySuiq.js +101 -0
  273. package/dist/register.maintenance-0k-ZNhDg.js +543 -0
  274. package/dist/register.maintenance-BIwx1fzX.js +543 -0
  275. package/dist/register.message-CXPsoakA.js +657 -0
  276. package/dist/register.message-DA3jvfgI.js +660 -0
  277. package/dist/register.onboard-C4HG7Hqv.js +170 -0
  278. package/dist/register.onboard-GOpdif-j.js +170 -0
  279. package/dist/register.setup-B17vZT7C.js +175 -0
  280. package/dist/register.setup-GJyUDCqh.js +175 -0
  281. package/dist/register.status-health-sessions-D5876dGx.js +313 -0
  282. package/dist/register.status-health-sessions-lOewVIZR.js +142 -0
  283. package/dist/register.subclis-Dwnujj5C.js +255 -0
  284. package/dist/reply-CR5T_oQJ.js +32212 -0
  285. package/dist/reply-prefix-BcrS4Umd.js +100 -0
  286. package/dist/reply-prefix-Btb5o2NH.js +100 -0
  287. package/dist/reply-r089HuRA.js +32212 -0
  288. package/dist/routes-B4czFzIb.js +1820 -0
  289. package/dist/routes-ucJWAk5O.js +1820 -0
  290. package/dist/rpc-BnKxnQ0v.js +70 -0
  291. package/dist/rpc-DgE-xnyx.js +70 -0
  292. package/dist/run-main-B74kv84C.js +371 -0
  293. package/dist/runtime-guard-CKFdts2L.js +60 -0
  294. package/dist/sandbox-CJTS3er6.js +858 -0
  295. package/dist/sandbox-DBSiVHt_.js +859 -0
  296. package/dist/sandbox-cli-CrkjyU5M.js +461 -0
  297. package/dist/sandbox-cli-D1r5y6Sz.js +458 -0
  298. package/dist/security-cli-BZUdnkhn.js +462 -0
  299. package/dist/security-cli-DS09ebvA.js +465 -0
  300. package/dist/server-context-C0xZbYhg.js +824 -0
  301. package/dist/server-context-DVh2z7om.js +824 -0
  302. package/dist/server-node-events-bu9lpkMH.js +233 -0
  303. package/dist/server-node-events-i1Rrww31.js +231 -0
  304. package/dist/service-CJJwLEor.js +642 -0
  305. package/dist/service-DxLxBhaU.js +642 -0
  306. package/dist/service-audit-DB4Y3Ekp.js +488 -0
  307. package/dist/service-audit-M8y4TXVb.js +488 -0
  308. package/dist/session-CGxOLFs2.js +179 -0
  309. package/dist/session-DTTbdKb0.js +181 -0
  310. package/dist/session-cost-usage-FcdJl9c3.js +600 -0
  311. package/dist/session-cost-usage-qdfsGU2a.js +600 -0
  312. package/dist/session-yOhWcsD2.js +181 -0
  313. package/dist/sessions-B-Cu7JZq.js +1296 -0
  314. package/dist/sessions-BgLN4KFr.js +180 -0
  315. package/dist/sessions-CnRjwdVr.js +1296 -0
  316. package/dist/sessions-wRKla1Qh.js +2038 -0
  317. package/dist/shared-DS3UaJSP.js +66 -0
  318. package/dist/shared-DxNHzky3.js +77 -0
  319. package/dist/shared-Qpt4hUDi.js +66 -0
  320. package/dist/shared-kzrojZ1B.js +77 -0
  321. package/dist/skill-scanner-DLJji5Ye.js +263 -0
  322. package/dist/skills-BWFIEp4j.js +807 -0
  323. package/dist/skills-DV4zKdCx.js +808 -0
  324. package/dist/skills-cli-BY53ILm2.js +289 -0
  325. package/dist/skills-cli-CO3gxl8A.js +286 -0
  326. package/dist/skills-status-DX5pcqY3.js +166 -0
  327. package/dist/skills-status-zhcKzGkp.js +166 -0
  328. package/dist/sqlite-B6MojU1I.js +321 -0
  329. package/dist/sqlite-CuprTGR7.js +453 -0
  330. package/dist/sqlite-dzD-jMjs.js +368 -0
  331. package/dist/start-Cu3aLoSf.js +297 -0
  332. package/dist/start-Dz7tMAl8.js +296 -0
  333. package/dist/status-CaSxhxfV.js +2132 -0
  334. package/dist/status-D2C0JCX3.js +2137 -0
  335. package/dist/status-DlFMsQzh.js +27 -0
  336. package/dist/status-G0CITnKR.js +27 -0
  337. package/dist/status.update-CHjhVxJY.js +79 -0
  338. package/dist/status.update-DVFelehi.js +79 -0
  339. package/dist/subagent-registry-3Xb4el-8.js +14 -0
  340. package/dist/subagent-registry-CdSjz14I.js +2760 -0
  341. package/dist/subagent-registry-DNDhbHWi.js +2759 -0
  342. package/dist/subsystem-DfKstnEK.js +860 -0
  343. package/dist/system-cli-B5mt0FWa.js +82 -0
  344. package/dist/system-cli-Dg3UQ3Zz.js +79 -0
  345. package/dist/systemd-B43AvOGx.js +452 -0
  346. package/dist/systemd-RpPE0XGg.js +452 -0
  347. package/dist/systemd-hints-DMJT-Bbc.js +36 -0
  348. package/dist/systemd-hints-vRInKcz9.js +36 -0
  349. package/dist/systemd-linger-Dzyxqsod.js +75 -0
  350. package/dist/systemd-linger-EujbmI5A.js +75 -0
  351. package/dist/table-DhXHfRX2.js +279 -0
  352. package/dist/table-bWCLW-3P.js +279 -0
  353. package/dist/timeout-Ddn-5kAO.js +232 -0
  354. package/dist/tokens-3psI_Qk2.js +14 -0
  355. package/dist/tokens-BaM53PEx.js +14 -0
  356. package/dist/trash-Bmxs1Rnm.js +23 -0
  357. package/dist/trash-C39a6hKA.js +23 -0
  358. package/dist/tui-BHgBWhHE.js +3894 -0
  359. package/dist/tui-cli-B9Sq5-cC.js +50 -0
  360. package/dist/tui-cli-Dw7v4JoJ.js +47 -0
  361. package/dist/tui-mUwDwqvd.js +3894 -0
  362. package/dist/update-DF0GHG0j.js +317 -0
  363. package/dist/update-DoZLVjva.js +317 -0
  364. package/dist/update-check-Bt1dVPVN.js +400 -0
  365. package/dist/update-check-D5qAKes7.js +400 -0
  366. package/dist/update-cli-BNu2Oi7H.js +1105 -0
  367. package/dist/update-cli-D36AmALA.js +1105 -0
  368. package/dist/update-runner-CNQQaTwA.js +894 -0
  369. package/dist/update-runner-CvxZmbu-.js +894 -0
  370. package/dist/usage-BGCwNnjk.js +4516 -0
  371. package/dist/utils-DZ8pnOD5.js +243 -0
  372. package/dist/web-B5QG839O.js +46842 -0
  373. package/dist/web-Cmnvk9v0.js +2203 -0
  374. package/dist/web-Cv2KnTnL.js +63 -0
  375. package/dist/webhooks-cli-B6y89Pj_.js +319 -0
  376. package/dist/webhooks-cli-BDzHON4w.js +316 -0
  377. package/dist/whatsapp-actions-C_5MwVxM.js +45 -0
  378. package/dist/whatsapp-actions-hgYA12To.js +53 -0
  379. package/dist/whatsapp-actions-zTiVOoOV.js +49 -0
  380. package/dist/widearea-dns-BeIdnISJ.js +127 -0
  381. package/dist/widearea-dns-CF1gxpJ-.js +127 -0
  382. package/dist/workspace-DLna1IxR.js +649 -0
  383. package/dist/ws-log-Q4wO1Ztb.js +267 -0
  384. package/dist/ws-log-xF0kxDzp.js +267 -0
  385. package/package.json +1 -2
  386. package/dist/accounts-Cc5E4IDO.js +0 -260
  387. package/dist/accounts-CcVrwKqv.js +0 -259
  388. package/dist/acp-cli-DvphOKuh.js +0 -1081
  389. package/dist/acp-cli-p28pQ65a.js +0 -1084
  390. package/dist/agent-Cj7uDJaZ.js +0 -725
  391. package/dist/agent-Cuj9-2sT.js +0 -725
  392. package/dist/agent-events-BEBQsyE5.js +0 -182
  393. package/dist/agent-scope-BVf4aSwY.js +0 -112
  394. package/dist/agent-scope-OZi7lb8S.js +0 -452
  395. package/dist/agent-scope-V1bi9OYL.js +0 -452
  396. package/dist/agents-BUWqn_Ui.js +0 -774
  397. package/dist/agents.config-Dvo2ULxs.js +0 -182
  398. package/dist/agents.config-d6H0_3oj.js +0 -182
  399. package/dist/argv-DqUHKf0o.js +0 -73
  400. package/dist/audit-C6okOOSh.js +0 -2401
  401. package/dist/audit-VWjIdwC7.js +0 -2401
  402. package/dist/auth-91o2YM96.js +0 -648
  403. package/dist/auth-choice-CAmACV13.js +0 -2681
  404. package/dist/auth-choice-p3SeHPj2.js +0 -2681
  405. package/dist/auth-health-B_jXrWe6.js +0 -149
  406. package/dist/auth-health-DCicUKYR.js +0 -149
  407. package/dist/auth-lZ26wsbN.js +0 -639
  408. package/dist/auth-profiles-CCDD56dU.js +0 -1564
  409. package/dist/auth-profiles-DxI8L7bs.js +0 -2689
  410. package/dist/banner-Cohn04J6.js +0 -294
  411. package/dist/browser-cli-DANzjztE.js +0 -1676
  412. package/dist/browser-cli-WjsVH741.js +0 -1679
  413. package/dist/call-BAHvlu2G.js +0 -282
  414. package/dist/call-Ct7EGP_L.js +0 -282
  415. package/dist/catalog-BAayBt1L.js +0 -185
  416. package/dist/catalog-BNsf97BM.js +0 -185
  417. package/dist/channel-options-Dx9nPlX8.js +0 -33
  418. package/dist/channel-options-ZdvXrTGs.js +0 -32
  419. package/dist/channel-selection-CujyiWGM.js +0 -51
  420. package/dist/channel-selection-DfGpCyh2.js +0 -51
  421. package/dist/channel-web-CC0hkgkR.js +0 -2162
  422. package/dist/channels-cli-D7lNBpIb.js +0 -1304
  423. package/dist/channels-cli-DUPG8WDv.js +0 -1306
  424. package/dist/channels-status-issues-DBc1pU_R.js +0 -18
  425. package/dist/channels-status-issues-DjO9MHIG.js +0 -18
  426. package/dist/chrome-Bi6iZ5sG.js +0 -1601
  427. package/dist/chrome-DNSv7Cpy.js +0 -1629
  428. package/dist/chrome-DScZx4Lk.js +0 -1601
  429. package/dist/chunk-mxPVo000.js +0 -348
  430. package/dist/clack-prompter-B0kl7shw.js +0 -92
  431. package/dist/clack-prompter-B1YxZdRy.js +0 -92
  432. package/dist/cli-CfHUkOD0.js +0 -101
  433. package/dist/cli-ClMrIh6l.js +0 -99
  434. package/dist/cli-session-BkPTd9Pk.js +0 -5463
  435. package/dist/cli-session-Dd8DKb5a.js +0 -5408
  436. package/dist/client-C1avc0vD.js +0 -1692
  437. package/dist/client-CC94YZrT.js +0 -1692
  438. package/dist/clipboard-B2fBy8tG.js +0 -31
  439. package/dist/clipboard-BbGnZskJ.js +0 -31
  440. package/dist/command-format-Clp46jkj.js +0 -38
  441. package/dist/command-format-DELazozB.js +0 -52
  442. package/dist/command-format-SkzzRqR1.js +0 -52
  443. package/dist/command-registry-DZ4hkmA0.js +0 -248
  444. package/dist/commands-DtYZJSPn.js +0 -568
  445. package/dist/commands-Dujk1JmY.js +0 -568
  446. package/dist/commands-registry-Bd0xbvwG.js +0 -766
  447. package/dist/commands-registry-DYfRSVF3.js +0 -766
  448. package/dist/common-D6bu0zHC.js +0 -287
  449. package/dist/common-zW9Y2P1B.js +0 -287
  450. package/dist/completion-cli-tSe7Pmqm.js +0 -431
  451. package/dist/completion-cli-vn4IScs5.js +0 -432
  452. package/dist/config-C8rUDJXY.js +0 -5704
  453. package/dist/config-CLZ_XGVw.js +0 -6523
  454. package/dist/config-SY8M0kM_.js +0 -5705
  455. package/dist/config-cli-1V7D2Wsw.js +0 -247
  456. package/dist/config-cli-CjWEC81L.js +0 -244
  457. package/dist/config-guard-BW2gpKj_.js +0 -93
  458. package/dist/config-guard-BvxuzHpo.js +0 -76
  459. package/dist/config-sync-CoIIbEOe.js +0 -91
  460. package/dist/config-sync-DvAttep0.js +0 -91
  461. package/dist/configure-Bf0oupCE.js +0 -959
  462. package/dist/configure-DRM-7zFf.js +0 -960
  463. package/dist/context-D5iEFzv9.js +0 -60
  464. package/dist/control-service-C8m8F9pr.js +0 -72
  465. package/dist/control-service-DKotCWCg.js +0 -72
  466. package/dist/cron-cli-DB_FLYHD.js +0 -448
  467. package/dist/cron-cli-bxm5lrrO.js +0 -451
  468. package/dist/daemon-cli-1LsOnICv.js +0 -566
  469. package/dist/daemon-cli-CC2NrJ7a.js +0 -565
  470. package/dist/daemon-runtime-BXZhtBL9.js +0 -460
  471. package/dist/daemon-runtime-DW4USC7r.js +0 -460
  472. package/dist/deliver-B4HuPwJA.js +0 -1162
  473. package/dist/deliver-LiY5oL52.js +0 -1097
  474. package/dist/deliver-xrmk7xjh.js +0 -1097
  475. package/dist/delivery-queue-TnQykYsg.js +0 -220
  476. package/dist/deps-CMMOiOsF.js +0 -42
  477. package/dist/devices-cli-Be5he2SA.js +0 -195
  478. package/dist/devices-cli-z6ecoFe9.js +0 -198
  479. package/dist/diagnostics-Dj75aEHN.js +0 -35
  480. package/dist/diagnostics-DlIw6fqD.js +0 -35
  481. package/dist/directory-cli-CEy-0nxj.js +0 -243
  482. package/dist/directory-cli-DpzKcigr.js +0 -246
  483. package/dist/dispatcher-10Shiuz3.js +0 -100
  484. package/dist/dispatcher-3Jae6AiW.js +0 -100
  485. package/dist/dns-cli-Bat1pkc-.js +0 -200
  486. package/dist/dns-cli-NohNyEo0.js +0 -197
  487. package/dist/dock-DbxBBv30.js +0 -753
  488. package/dist/dock-cPBY4qGl.js +0 -753
  489. package/dist/docs-cli-BWp6p-Tq.js +0 -161
  490. package/dist/docs-cli-x22FnZfL.js +0 -159
  491. package/dist/doctor-BrT5m_on.js +0 -1815
  492. package/dist/doctor-Pp2HVnjM.js +0 -1813
  493. package/dist/doctor-completion-DNTimX9o.js +0 -92
  494. package/dist/doctor-completion-ylN9QAJ6.js +0 -92
  495. package/dist/doctor-config-flow-D1w3700T.js +0 -1232
  496. package/dist/doctor-config-flow-Dq50iE1R.js +0 -1232
  497. package/dist/engine-B9avUJL5.js +0 -563
  498. package/dist/engine-BiUQ25D4.js +0 -563
  499. package/dist/env-0lJfCPsw.js +0 -32
  500. package/dist/exec-BenD3A5l.js +0 -1167
  501. package/dist/exec-Bv3pyjeM.js +0 -255
  502. package/dist/exec-approvals-CdLmKX2R.js +0 -1221
  503. package/dist/exec-approvals-cli-DXfV6G8H.js +0 -368
  504. package/dist/exec-approvals-cli-J2cZs10o.js +0 -371
  505. package/dist/frontmatter-YijVi0FQ.js +0 -204
  506. package/dist/gateway-cli-DOAbA0pc.js +0 -19972
  507. package/dist/gateway-cli-QpWtBhQy.js +0 -19971
  508. package/dist/gateway-rpc-DJKBil9s.js +0 -28
  509. package/dist/gateway-rpc-DVterpLP.js +0 -28
  510. package/dist/github-copilot-auth-4IUFp669.js +0 -1418
  511. package/dist/github-copilot-auth-C9E0IROs.js +0 -1418
  512. package/dist/gmail-setup-utils-BPo_LkKI.js +0 -428
  513. package/dist/gmail-setup-utils-D3Yqgor7.js +0 -428
  514. package/dist/health-BeZnqp6m.js +0 -1258
  515. package/dist/health-Cn2OoVWZ.js +0 -1253
  516. package/dist/health-format-CdP99j3Y.js +0 -208
  517. package/dist/health-format-JEChH08S.js +0 -208
  518. package/dist/heartbeat-visibility-BL3WAchI.js +0 -98
  519. package/dist/heartbeat-visibility-CQ9QimI7.js +0 -98
  520. package/dist/help-format-Dl4bsrLI.js +0 -17
  521. package/dist/helpers-ZKNRexvX.js +0 -10
  522. package/dist/hooks-cli-D99hXt7K.js +0 -991
  523. package/dist/hooks-cli-DMB8RiEO.js +0 -993
  524. package/dist/hooks-status-B-e96dZj.js +0 -356
  525. package/dist/hooks-status-C_9sE0ox.js +0 -356
  526. package/dist/image-ops-Dlt3T7th.js +0 -541
  527. package/dist/image-ops-omlvdfah.js +0 -541
  528. package/dist/init-Bm04RagW.js +0 -122
  529. package/dist/init-CaJBf4p1.js +0 -122
  530. package/dist/installs-C2iMRBVz.js +0 -383
  531. package/dist/installs-D-cPGdCw.js +0 -383
  532. package/dist/ipv4-Bf7NS3QU.js +0 -1964
  533. package/dist/ipv4-wWNs8IH_.js +0 -1964
  534. package/dist/lanes-CNxj3tit.js +0 -232
  535. package/dist/lifecycle-core-B_7XRcvF.js +0 -388
  536. package/dist/lifecycle-core-By83PVAK.js +0 -387
  537. package/dist/links-BfjHVTB_.js +0 -15
  538. package/dist/links-DPGe0OHw.js +0 -15
  539. package/dist/logging-DB6BQmhi.js +0 -15
  540. package/dist/logging-mcb66J0p.js +0 -15
  541. package/dist/login-BDCg6D0N.js +0 -61
  542. package/dist/login-BDfnbjnZ.js +0 -59
  543. package/dist/login-BqH1itcg.js +0 -61
  544. package/dist/login-qr-CyOw3R4r.js +0 -321
  545. package/dist/login-qr-D8ECtb72.js +0 -323
  546. package/dist/login-qr-RnR7e4Bw.js +0 -326
  547. package/dist/logs-cli--j89L74J.js +0 -245
  548. package/dist/logs-cli-DpEMg_Gq.js +0 -242
  549. package/dist/manager-B4OyvcxT.js +0 -3244
  550. package/dist/manager-Cqc1CeH7.js +0 -3246
  551. package/dist/manager-DUyQPFvj.js +0 -3244
  552. package/dist/manifest-registry-CW1zCyRF.js +0 -748
  553. package/dist/manifest-registry-D4lM2RdV.js +0 -748
  554. package/dist/markdown-tables-BT1X6jqH.js +0 -347
  555. package/dist/markdown-tables-DHgOK2vI.js +0 -348
  556. package/dist/media-THyainiE.js +0 -1342
  557. package/dist/memory-cli-BKocCWXM.js +0 -868
  558. package/dist/memory-cli-Jmma-xI_.js +0 -869
  559. package/dist/message-channel-dSTVVCyX.js +0 -110
  560. package/dist/migrate-BR6iAIjO.js +0 -157
  561. package/dist/migrate-D0EcMs0f.js +0 -157
  562. package/dist/model-selection-YcSr9CgC.js +0 -2691
  563. package/dist/models-1vUQBVfw.js +0 -2510
  564. package/dist/models-cli-BK3BwUhL.js +0 -2739
  565. package/dist/models-cli-DECrM8oA.js +0 -258
  566. package/dist/net-B5lXhYLV.js +0 -218
  567. package/dist/node-cli-cLHUNpPD.js +0 -1319
  568. package/dist/node-cli-fO7Y132S.js +0 -1322
  569. package/dist/node-service-BFxHJsno.js +0 -67
  570. package/dist/node-service-DUnan4uK.js +0 -67
  571. package/dist/nodes-cli-BCq35E6N.js +0 -1200
  572. package/dist/nodes-cli-vD7MwAKP.js +0 -1197
  573. package/dist/nodes-screen-1YiLkqr5.js +0 -234
  574. package/dist/nodes-screen-DZeD8hE5.js +0 -234
  575. package/dist/note-Bi8Wb8DV.js +0 -73
  576. package/dist/note-uiuPxhyX.js +0 -73
  577. package/dist/npm-registry-spec-B-XIShkB.js +0 -351
  578. package/dist/npm-registry-spec-za3itb5Y.js +0 -351
  579. package/dist/onboard-Ds6w_sWo.js +0 -1165
  580. package/dist/onboard-SAVx3bp4.js +0 -1166
  581. package/dist/onboard-channels-Cg_EkBa4.js +0 -672
  582. package/dist/onboard-channels-D7NbA55V.js +0 -672
  583. package/dist/onboard-helpers-DO_hgZb9.js +0 -365
  584. package/dist/onboard-helpers-_XgJgeqh.js +0 -365
  585. package/dist/onboarding-3hLmDd0r.js +0 -911
  586. package/dist/onboarding-B4LKLsbU.js +0 -910
  587. package/dist/orchestrator-BKzmyBWy.js +0 -357
  588. package/dist/orchestrator-BN3QCz2s.js +0 -357
  589. package/dist/outbound-BgA9hNlP.js +0 -2062
  590. package/dist/outbound-CjdvVhUI.js +0 -214
  591. package/dist/outbound-DOGe6qb2.js +0 -214
  592. package/dist/outbound-send-deps-Du5aBpd7.js +0 -55
  593. package/dist/pairing-cli-2vnyg_Nd.js +0 -118
  594. package/dist/pairing-cli-BH1KQtNV.js +0 -121
  595. package/dist/pairing-store-DJz_9Gv0.js +0 -388
  596. package/dist/pairing-store-DmOzxcuk.js +0 -388
  597. package/dist/path-env-Bu6k0jDQ.js +0 -89
  598. package/dist/path-env-C0zQSjw8.js +0 -89
  599. package/dist/paths-BTc4nk-6.js +0 -126
  600. package/dist/paths-BgUi2Z2G.js +0 -54
  601. package/dist/paths-C6VCWKo3.js +0 -238
  602. package/dist/paths-CCxa0o9c.js +0 -222
  603. package/dist/paths-CxRf2rBG.js +0 -129
  604. package/dist/paths-hcX1Gqg5.js +0 -129
  605. package/dist/pi-auth-json-B68R7q7_.js +0 -82
  606. package/dist/pi-auth-json-CR0jXAgq.js +0 -78
  607. package/dist/pi-auth-json-ZYzi3nxs.js +0 -80
  608. package/dist/pi-model-discovery-Cxs4pvC2.js +0 -3
  609. package/dist/pi-tools.policy-D81U5xy0.js +0 -200
  610. package/dist/pi-tools.policy-DSHkkb5b.js +0 -200
  611. package/dist/plugin-auto-enable-CxF4bpDN.js +0 -282
  612. package/dist/plugin-auto-enable-jNaAeyEh.js +0 -282
  613. package/dist/plugin-registry-C7XWotZG.js +0 -32
  614. package/dist/plugin-registry-DcUCbGax.js +0 -32
  615. package/dist/plugins-B362e77G.js +0 -168
  616. package/dist/plugins-CmSUIUNi.js +0 -38
  617. package/dist/plugins-cli-BsCEnoQ7.js +0 -734
  618. package/dist/plugins-cli-QSIsMUG7.js +0 -736
  619. package/dist/polls-CItfB1H8.js +0 -1343
  620. package/dist/ports-BVLMN1Sr.js +0 -96
  621. package/dist/ports-CqLSlU6Z.js +0 -317
  622. package/dist/ports-D94CwCrv.js +0 -344
  623. package/dist/ports-D_NHthOz.js +0 -96
  624. package/dist/program-DkJHjI0R.js +0 -176
  625. package/dist/program-context-DnyGM2SC.js +0 -496
  626. package/dist/progress-Bek_GyWS.js +0 -133
  627. package/dist/prompt-style-lu0clOOE.js +0 -9
  628. package/dist/pw-ai-BLVMuSLv.js +0 -1867
  629. package/dist/pw-ai-DZJWEF_f.js +0 -1865
  630. package/dist/pw-ai-dzf-ptcn.js +0 -1868
  631. package/dist/qmd-manager-Cur_Ekn0.js +0 -937
  632. package/dist/qmd-manager-DNAUuwjK.js +0 -938
  633. package/dist/qmd-manager-DepEoASu.js +0 -935
  634. package/dist/register.agent-CSWvzOkR.js +0 -265
  635. package/dist/register.agent-UeH2NXmH.js +0 -1003
  636. package/dist/register.anima-DOdee0dh.js +0 -193
  637. package/dist/register.anima-HHDWsz6r.js +0 -193
  638. package/dist/register.configure-CSJFxdz9.js +0 -103
  639. package/dist/register.configure-D84Fvcz4.js +0 -101
  640. package/dist/register.maintenance-B3pvNbZb.js +0 -543
  641. package/dist/register.maintenance-BKVOwkw6.js +0 -543
  642. package/dist/register.message-BAO6CPl2.js +0 -657
  643. package/dist/register.message-OXoOKE_6.js +0 -660
  644. package/dist/register.onboard-BK_ixVmD.js +0 -170
  645. package/dist/register.onboard-cfCaPx6j.js +0 -170
  646. package/dist/register.setup-BGfDnzph.js +0 -175
  647. package/dist/register.setup-Y-Q74M-0.js +0 -175
  648. package/dist/register.status-health-sessions-CT14eitH.js +0 -142
  649. package/dist/register.status-health-sessions-TfZMzAUn.js +0 -313
  650. package/dist/register.subclis-BZwdlNHC.js +0 -255
  651. package/dist/reply-mlsExaZm.js +0 -32212
  652. package/dist/reply-prefix-B0CfR4bM.js +0 -100
  653. package/dist/reply-prefix-w4a39ybC.js +0 -100
  654. package/dist/reply-qalRISe_.js +0 -32212
  655. package/dist/routes-CENsHJyg.js +0 -1820
  656. package/dist/routes-DO0HqW2e.js +0 -1820
  657. package/dist/rpc-C0pjNhBi.js +0 -70
  658. package/dist/rpc-DZ44PIXE.js +0 -70
  659. package/dist/run-main-BMpKw8Mp.js +0 -371
  660. package/dist/runtime-guard-BSUFiAQV.js +0 -60
  661. package/dist/sandbox-BIGfMYEI.js +0 -858
  662. package/dist/sandbox-DxP3IpUP.js +0 -859
  663. package/dist/sandbox-cli-DtLGH8sL.js +0 -461
  664. package/dist/sandbox-cli-_Tg7lfJ_.js +0 -458
  665. package/dist/security-cli-BRwgbedo.js +0 -462
  666. package/dist/security-cli-D3bSuyZt.js +0 -465
  667. package/dist/server-context-49XFFxFg.js +0 -824
  668. package/dist/server-context-LrlgrZzS.js +0 -824
  669. package/dist/server-node-events-Dm52i7NW.js +0 -231
  670. package/dist/server-node-events-QX523UyF.js +0 -233
  671. package/dist/service-BNVpYcQe.js +0 -642
  672. package/dist/service-D56aMXUB.js +0 -642
  673. package/dist/service-audit-D0X_XAB2.js +0 -488
  674. package/dist/service-audit-qmf6XMmP.js +0 -488
  675. package/dist/session-CrQQLLhx.js +0 -179
  676. package/dist/session-LocsOOWJ.js +0 -181
  677. package/dist/session-Vlce2BAT.js +0 -181
  678. package/dist/session-cost-usage-BwiTZuKl.js +0 -600
  679. package/dist/session-cost-usage-DT9YNXTJ.js +0 -600
  680. package/dist/sessions-BfV53TbG.js +0 -1296
  681. package/dist/sessions-BimpX_km.js +0 -180
  682. package/dist/sessions-DcXpzig0.js +0 -1296
  683. package/dist/sessions-Wd18dukK.js +0 -2038
  684. package/dist/shared-Bsr69u_7.js +0 -77
  685. package/dist/shared-Cgly1vPb.js +0 -66
  686. package/dist/shared-JOo05hST.js +0 -66
  687. package/dist/shared-f7dvQsi7.js +0 -77
  688. package/dist/skill-scanner-CkaVLABv.js +0 -263
  689. package/dist/skills-B-G7UHOa.js +0 -808
  690. package/dist/skills-B5LQx4lT.js +0 -807
  691. package/dist/skills-cli-DUGe2ZWW.js +0 -286
  692. package/dist/skills-cli-DtOk0bvK.js +0 -289
  693. package/dist/skills-status-Clq9ZnYu.js +0 -166
  694. package/dist/skills-status-JQluhU-P.js +0 -166
  695. package/dist/sqlite-BukcjdJa.js +0 -321
  696. package/dist/sqlite-CGcOZZ0C.js +0 -368
  697. package/dist/sqlite-Ck6f9KWc.js +0 -453
  698. package/dist/start--xmSFepB.js +0 -372
  699. package/dist/start-BdlZbqrr.js +0 -371
  700. package/dist/status-BgoeFm6g.js +0 -2137
  701. package/dist/status-BjjDrUq7.js +0 -27
  702. package/dist/status-Ct0DgOZ-.js +0 -2132
  703. package/dist/status-RA_uNmK0.js +0 -27
  704. package/dist/status.update-BjOH3GlS.js +0 -79
  705. package/dist/status.update-DLU1qBf0.js +0 -79
  706. package/dist/subagent-registry-9RLdKxES.js +0 -2760
  707. package/dist/subagent-registry-Byuex3zp.js +0 -2759
  708. package/dist/subagent-registry-DOBunBYS.js +0 -14
  709. package/dist/subsystem-Dowf8fSU.js +0 -860
  710. package/dist/system-cli-C5oBpzni.js +0 -79
  711. package/dist/system-cli-DXNKD_Id.js +0 -82
  712. package/dist/systemd-BSrHDyeU.js +0 -452
  713. package/dist/systemd-By5xdSB4.js +0 -452
  714. package/dist/systemd-hints-BtjL_5Rh.js +0 -36
  715. package/dist/systemd-hints-sJmr6cjb.js +0 -36
  716. package/dist/systemd-linger-CTmV2Gci.js +0 -75
  717. package/dist/systemd-linger-CmyqQkeC.js +0 -75
  718. package/dist/table-BL0lJzsm.js +0 -279
  719. package/dist/table-DoiRPsn0.js +0 -279
  720. package/dist/timeout-CswI_K-U.js +0 -232
  721. package/dist/tokens-C-X7wDKj.js +0 -14
  722. package/dist/tokens-DkvqA72p.js +0 -14
  723. package/dist/trash-BJLK1vMn.js +0 -23
  724. package/dist/trash-_x5UZ94k.js +0 -23
  725. package/dist/tui-BHjxDFZC.js +0 -3894
  726. package/dist/tui-CgOocwN8.js +0 -3894
  727. package/dist/tui-cli-5ANH8dE5.js +0 -47
  728. package/dist/tui-cli-BQ4P-JW_.js +0 -50
  729. package/dist/update-LFgxHHPd.js +0 -317
  730. package/dist/update-TxptCqk7.js +0 -317
  731. package/dist/update-check-CWc7YXmc.js +0 -400
  732. package/dist/update-check-IhlWaui6.js +0 -400
  733. package/dist/update-cli-PtXU62w7.js +0 -1105
  734. package/dist/update-cli-Va0EtETG.js +0 -1105
  735. package/dist/update-runner-BLeKFkiB.js +0 -894
  736. package/dist/update-runner-Iuzpc-_y.js +0 -894
  737. package/dist/usage-ApGvBLVg.js +0 -4516
  738. package/dist/utils-Bsw__U-F.js +0 -243
  739. package/dist/web-B6_Ky60G.js +0 -63
  740. package/dist/web-EZLQEWXY.js +0 -46842
  741. package/dist/web-pec8YJUX.js +0 -2203
  742. package/dist/webhooks-cli-BYQKTHTp.js +0 -319
  743. package/dist/webhooks-cli-C2_xtsUQ.js +0 -316
  744. package/dist/whatsapp-actions-C72VCq8f.js +0 -49
  745. package/dist/whatsapp-actions-Ck9Uv0Nw.js +0 -45
  746. package/dist/whatsapp-actions-D0reTj2k.js +0 -53
  747. package/dist/widearea-dns-B6ocX23x.js +0 -127
  748. package/dist/widearea-dns-NsEUNYwz.js +0 -127
  749. package/dist/workspace-Dcfoy5JJ.js +0 -649
  750. package/dist/ws-log-N8R5MvGE.js +0 -267
  751. package/dist/ws-log-gwFxPxj5.js +0 -267
  752. /package/dist/{auto-update-CUeF99gI.js → auto-update-CpF0fycd.js} +0 -0
  753. /package/dist/{auto-update-cgkp9ZTJ.js → auto-update-DNWdO7uF.js} +0 -0
  754. /package/dist/{brew-CVZkr0GU.js → brew-nqf_MiE4.js} +0 -0
  755. /package/dist/{budget-DxYQSekw.js → budget-CPedI-qW.js} +0 -0
  756. /package/dist/{budget-BWBp8Res.js → budget-CRpvqDRX.js} +0 -0
  757. /package/dist/{cli-utils-DtAxdCte.js → cli-utils-C1YHVD4o.js} +0 -0
  758. /package/dist/{command-options-CSbuuqHr.js → command-options-BbponVnw.js} +0 -0
  759. /package/dist/{command-options-Cp1tf96a.js → command-options-s0gnvXnS.js} +0 -0
  760. /package/dist/{constants-O8yBqCBv.js → constants-Dhb6zSIV.js} +0 -0
  761. /package/dist/{dangerous-tools-5ObDWy1N.js → dangerous-tools-DGTtJ_JR.js} +0 -0
  762. /package/dist/{dangerous-tools-Jwr7jqNw.js → dangerous-tools-DxrfTOfT.js} +0 -0
  763. /package/dist/{delivery-queue-B6IHz4Ry.js → delivery-queue-Bxm0nzw7.js} +0 -0
  764. /package/dist/{display-BDOsXu8F.js → display-Jy3UdGzA.js} +0 -0
  765. /package/dist/{errors-CHow2wtt.js → errors-CKaCqKga.js} +0 -0
  766. /package/dist/{exec-BizYYQgP.js → exec-DDmuVVNq.js} +0 -0
  767. /package/dist/{format-Mq6iU0_5.js → format-ByEjgyTF.js} +0 -0
  768. /package/dist/{format-duration-DhWzz_5b.js → format-duration-Aaj5tjJd.js} +0 -0
  769. /package/dist/{format-relative-C6kUHuOj.js → format-relative-79_Y1n2Y.js} +0 -0
  770. /package/dist/{help-format-DUBI91Ti.js → help-format-BMKzarov.js} +0 -0
  771. /package/dist/{helpers-eJFa4K6r.js → helpers-DpEB9Mh0.js} +0 -0
  772. /package/dist/{helpers-DLgbkcEn.js → helpers-FMld9sBT.js} +0 -0
  773. /package/dist/{input-provenance-DJBdpeKk.js → input-provenance-Cy_KnBlP.js} +0 -0
  774. /package/dist/{is-main-Dt9DTcH1.js → is-main-yjaVwMtJ.js} +0 -0
  775. /package/dist/{loader-l2OBdJ8x.js → loader-Br7Vr0zn.js} +0 -0
  776. /package/dist/{loader-BoYxRfcW.js → loader-CkmOrXcC.js} +0 -0
  777. /package/dist/{logging-BdnOSVPD.js → logging-CY-Q5cwf.js} +0 -0
  778. /package/dist/{message-channel-w4F2b2F6.js → message-channel-dua8OOGJ.js} +0 -0
  779. /package/dist/{mime-B1ZoR53M.js → mime-CBg4KybI.js} +0 -0
  780. /package/dist/{model-param-b-DPwyNGn8.js → model-param-b-DW9f0NN8.js} +0 -0
  781. /package/dist/{node-match-8XZnaid6.js → node-match-BV8bTBd4.js} +0 -0
  782. /package/dist/{normalize-GDK8JTNW.js → normalize-_lmlBOW9.js} +0 -0
  783. /package/dist/{openclaw-root-C85WMnVV.js → openclaw-root-JPvmPTf7.js} +0 -0
  784. /package/dist/{outbound-send-deps-ANnAhImn.js → outbound-send-deps-BfUvuWGa.js} +0 -0
  785. /package/dist/{parse-6-2MDhdT.js → parse-CZRwKocn.js} +0 -0
  786. /package/dist/{parse-log-line-Bqh1SSzC.js → parse-log-line-CvrZEK6A.js} +0 -0
  787. /package/dist/{parse-log-line-DUZCjXbl.js → parse-log-line-mLdat0AH.js} +0 -0
  788. /package/dist/{parse-port-BKB9Exlg.js → parse-port-BSOOdo7I.js} +0 -0
  789. /package/dist/{parse-port-DrfvwwiL.js → parse-port-Y0NK62x1.js} +0 -0
  790. /package/dist/{parse-timeout-Di_tcEmi.js → parse-timeout-DVPQ3n9j.js} +0 -0
  791. /package/dist/{paths-DcVEkYX5.js → paths-DHjlJ6cn.js} +0 -0
  792. /package/dist/{pi-model-discovery-DsRqYJLy.js → pi-model-discovery-DzEIEgHL.js} +0 -0
  793. /package/dist/{plugins-CDJw924T.js → plugins-D6PBOdkn.js} +0 -0
  794. /package/dist/{program-context-Bvn8046-.js → program-context-Q1hkT73c.js} +0 -0
  795. /package/dist/{progress-CbZ2D53A.js → progress-C9Ha1NJh.js} +0 -0
  796. /package/dist/{prompt-style-DKy6qQxR.js → prompt-style-DQi8j03a.js} +0 -0
  797. /package/dist/{prompts-BI__va99.js → prompts-BEHxUC3w.js} +0 -0
  798. /package/dist/{prompts-_dDWkCAz.js → prompts-CSOhuiqe.js} +0 -0
  799. /package/dist/{queue-D_u34pbL.js → queue-BJGo7kAB.js} +0 -0
  800. /package/dist/{queue-PG591iID.js → queue-DYgUbdoq.js} +0 -0
  801. /package/dist/{redact-ClVwO7Nn.js → redact-CyKvdFrg.js} +0 -0
  802. /package/dist/{registry-Bs_DJK9E.js → registry-C5MAYD4V.js} +0 -0
  803. /package/dist/{registry-D_zlP1U-.js → registry-CRrXXVs0.js} +0 -0
  804. /package/dist/{requirements-BzZxj2Wu.js → requirements-CGkxTCu4.js} +0 -0
  805. /package/dist/{requirements-DIW1svgA.js → requirements-CIDaOcbO.js} +0 -0
  806. /package/dist/{runtime-guard-DeOXA_86.js → runtime-guard-nL3Lp8T-.js} +0 -0
  807. /package/dist/{secret-equal-Dghy3xsA.js → secret-equal-DJpmLXlG.js} +0 -0
  808. /package/dist/{send-BhAfdGII.js → send-CTcxgDDU.js} +0 -0
  809. /package/dist/{send-ga9udK1_.js → send-DPezUR3-.js} +0 -0
  810. /package/dist/{send-C2t9xpXI.js → send-DZQTaG7-.js} +0 -0
  811. /package/dist/{send-DigO-i9j.js → send-VDff2gra.js} +0 -0
  812. /package/dist/{send-Dz2BDHll.js → send-bgQNV8d1.js} +0 -0
  813. /package/dist/{session-key-BGiG_JcT.js → session-key-CQT-NR6w.js} +0 -0
  814. /package/dist/{shell-argv-CAq1mLa2.js → shell-argv-n9IueeJQ.js} +0 -0
  815. /package/dist/{skill-scanner-Coo4QoCd.js → skill-scanner-o6NgVMD9.js} +0 -0
  816. /package/dist/{status-CMnlcBVc.js → status-C53kTIXF.js} +0 -0
  817. /package/dist/{status-tDZPwewW.js → status-CZDDA_Sy.js} +0 -0
  818. /package/dist/{system-run-command-X9lDJIy0.js → system-run-command-BCjUffN9.js} +0 -0
  819. /package/dist/{system-run-command-DGk7dwQP.js → system-run-command-CqAqKL9K.js} +0 -0
  820. /package/dist/{tailnet-CuiNECdL.js → tailnet-Ciwjv243.js} +0 -0
  821. /package/dist/{templates-CeYJjVzw.js → templates-37RKpACb.js} +0 -0
  822. /package/dist/{templates-I3Z0xplD.js → templates-DPalk30o.js} +0 -0
  823. /package/dist/{thinking-BXEswx1X.js → thinking-2hxwmvTl.js} +0 -0
  824. /package/dist/{transcript-events-C1hdue6u.js → transcript-events-Bp7fGnwv.js} +0 -0
  825. /package/dist/{transcript-tools-DuyYOkUq.js → transcript-tools-D4Lbxlka.js} +0 -0
  826. /package/dist/{usage-format-BAirWUSO.js → usage-format-6Uar63S0.js} +0 -0
  827. /package/dist/{utils-C9sj30YY.js → utils-DT8uXjFS.js} +0 -0
  828. /package/dist/{wsl-CqyuRvtM.js → wsl-CrPvx2kZ.js} +0 -0
  829. /package/dist/{wsl-ymJYvc9Q.js → wsl-UvJ5dHah.js} +0 -0
@@ -0,0 +1,2760 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
+ import { g as resolveStateDir } from "./paths-BMuHNFxg.js";
3
+ import { t as createSubsystemLogger, u as defaultRuntime } from "./subsystem-DfKstnEK.js";
4
+ import { _ as isAcpSessionKey, d as resolveAgentIdFromSessionKey, g as getSubagentDepth, u as normalizeMainKey, x as parseAgentSessionKey } from "./session-key-DxcgHezu.js";
5
+ import { c as resolveDefaultAgentId, l as resolveSessionAgentId, n as resolveAgentConfig } from "./agent-scope-CPphqq-U.js";
6
+ import { bt as loadJsonFile, xt as saveJsonFile } from "./model-selection-Cqt6aJ0G.js";
7
+ import { S as resolveAgentTimeoutMs, f as stripHeartbeatToken, g as isEmbeddedPiRunActive, o as onAgentEvent, p as CommandLane, t as AGENT_LANE_NESTED, v as queueEmbeddedPiMessage, x as waitForEmbeddedPiRunEnd, y as resolveEmbeddedSessionLane } from "./lanes-BvSnHq2h.js";
8
+ import { i as loadConfig, m as parseDurationMs } from "./config-DaqbUdkI.js";
9
+ import { d as deliveryContextFromSession, f as deliveryContextKey, i as loadSessionStore, k as resolveMainSessionKey, m as normalizeDeliveryContext, p as mergeDeliveryContext } from "./sessions-B-Cu7JZq.js";
10
+ import { n as SILENT_REPLY_TOKEN, r as isSilentReplyText, t as HEARTBEAT_TOKEN } from "./tokens-3psI_Qk2.js";
11
+ import { l as normalizeMessageChannel, t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-D_jIO87f.js";
12
+ import { r as normalizeChannelId, t as getChannelPlugin } from "./plugins-DhcGAPDB.js";
13
+ import { c as resolveStorePath } from "./paths-BXQQzXGQ.js";
14
+ import { n as callGateway } from "./call-BYDpTVCZ.js";
15
+ import fs from "node:fs";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+ import JSON5 from "json5";
19
+ import crypto from "node:crypto";
20
+
21
+ //#region src/auto-reply/reply/directive-parsing.ts
22
+ function skipDirectiveArgPrefix(raw) {
23
+ let i = 0;
24
+ const len = raw.length;
25
+ while (i < len && /\s/.test(raw[i])) i += 1;
26
+ if (raw[i] === ":") {
27
+ i += 1;
28
+ while (i < len && /\s/.test(raw[i])) i += 1;
29
+ }
30
+ return i;
31
+ }
32
+ function takeDirectiveToken(raw, startIndex) {
33
+ let i = startIndex;
34
+ const len = raw.length;
35
+ while (i < len && /\s/.test(raw[i])) i += 1;
36
+ if (i >= len) return {
37
+ token: null,
38
+ nextIndex: i
39
+ };
40
+ const start = i;
41
+ while (i < len && !/\s/.test(raw[i])) i += 1;
42
+ if (start === i) return {
43
+ token: null,
44
+ nextIndex: i
45
+ };
46
+ const token = raw.slice(start, i);
47
+ while (i < len && /\s/.test(raw[i])) i += 1;
48
+ return {
49
+ token,
50
+ nextIndex: i
51
+ };
52
+ }
53
+
54
+ //#endregion
55
+ //#region src/auto-reply/reply/queue/normalize.ts
56
+ function normalizeQueueMode(raw) {
57
+ if (!raw) return;
58
+ const cleaned = raw.trim().toLowerCase();
59
+ if (cleaned === "queue" || cleaned === "queued") return "steer";
60
+ if (cleaned === "interrupt" || cleaned === "interrupts" || cleaned === "abort") return "interrupt";
61
+ if (cleaned === "steer" || cleaned === "steering") return "steer";
62
+ if (cleaned === "followup" || cleaned === "follow-ups" || cleaned === "followups") return "followup";
63
+ if (cleaned === "collect" || cleaned === "coalesce") return "collect";
64
+ if (cleaned === "steer+backlog" || cleaned === "steer-backlog" || cleaned === "steer_backlog") return "steer-backlog";
65
+ }
66
+ function normalizeQueueDropPolicy(raw) {
67
+ if (!raw) return;
68
+ const cleaned = raw.trim().toLowerCase();
69
+ if (cleaned === "old" || cleaned === "oldest") return "old";
70
+ if (cleaned === "new" || cleaned === "newest") return "new";
71
+ if (cleaned === "summarize" || cleaned === "summary") return "summarize";
72
+ }
73
+
74
+ //#endregion
75
+ //#region src/auto-reply/reply/queue/directive.ts
76
+ function parseQueueDebounce(raw) {
77
+ if (!raw) return;
78
+ try {
79
+ const parsed = parseDurationMs(raw.trim(), { defaultUnit: "ms" });
80
+ if (!parsed || parsed < 0) return;
81
+ return Math.round(parsed);
82
+ } catch {
83
+ return;
84
+ }
85
+ }
86
+ function parseQueueCap(raw) {
87
+ if (!raw) return;
88
+ const num = Number(raw);
89
+ if (!Number.isFinite(num)) return;
90
+ const cap = Math.floor(num);
91
+ if (cap < 1) return;
92
+ return cap;
93
+ }
94
+ function parseQueueDirectiveArgs(raw) {
95
+ const len = raw.length;
96
+ let i = skipDirectiveArgPrefix(raw);
97
+ let consumed = i;
98
+ let queueMode;
99
+ let queueReset = false;
100
+ let rawMode;
101
+ let debounceMs;
102
+ let cap;
103
+ let dropPolicy;
104
+ let rawDebounce;
105
+ let rawCap;
106
+ let rawDrop;
107
+ let hasOptions = false;
108
+ const takeToken = () => {
109
+ const res = takeDirectiveToken(raw, i);
110
+ i = res.nextIndex;
111
+ return res.token;
112
+ };
113
+ while (i < len) {
114
+ const token = takeToken();
115
+ if (!token) break;
116
+ const lowered = token.trim().toLowerCase();
117
+ if (lowered === "default" || lowered === "reset" || lowered === "clear") {
118
+ queueReset = true;
119
+ consumed = i;
120
+ break;
121
+ }
122
+ if (lowered.startsWith("debounce:") || lowered.startsWith("debounce=")) {
123
+ rawDebounce = token.split(/[:=]/)[1] ?? "";
124
+ debounceMs = parseQueueDebounce(rawDebounce);
125
+ hasOptions = true;
126
+ consumed = i;
127
+ continue;
128
+ }
129
+ if (lowered.startsWith("cap:") || lowered.startsWith("cap=")) {
130
+ rawCap = token.split(/[:=]/)[1] ?? "";
131
+ cap = parseQueueCap(rawCap);
132
+ hasOptions = true;
133
+ consumed = i;
134
+ continue;
135
+ }
136
+ if (lowered.startsWith("drop:") || lowered.startsWith("drop=")) {
137
+ rawDrop = token.split(/[:=]/)[1] ?? "";
138
+ dropPolicy = normalizeQueueDropPolicy(rawDrop);
139
+ hasOptions = true;
140
+ consumed = i;
141
+ continue;
142
+ }
143
+ const mode = normalizeQueueMode(token);
144
+ if (mode) {
145
+ queueMode = mode;
146
+ rawMode = token;
147
+ consumed = i;
148
+ continue;
149
+ }
150
+ break;
151
+ }
152
+ return {
153
+ consumed,
154
+ queueMode,
155
+ queueReset,
156
+ rawMode,
157
+ debounceMs,
158
+ cap,
159
+ dropPolicy,
160
+ rawDebounce,
161
+ rawCap,
162
+ rawDrop,
163
+ hasOptions
164
+ };
165
+ }
166
+ function extractQueueDirective(body) {
167
+ if (!body) return {
168
+ cleaned: "",
169
+ hasDirective: false,
170
+ queueReset: false,
171
+ hasOptions: false
172
+ };
173
+ const match = /(?:^|\s)\/queue(?=$|\s|:)/i.exec(body);
174
+ if (!match) return {
175
+ cleaned: body.trim(),
176
+ hasDirective: false,
177
+ queueReset: false,
178
+ hasOptions: false
179
+ };
180
+ const start = match.index + match[0].indexOf("/queue");
181
+ const argsStart = start + 6;
182
+ const parsed = parseQueueDirectiveArgs(body.slice(argsStart));
183
+ return {
184
+ cleaned: `${body.slice(0, start)} ${body.slice(argsStart + parsed.consumed)}`.replace(/\s+/g, " ").trim(),
185
+ queueMode: parsed.queueMode,
186
+ queueReset: parsed.queueReset,
187
+ rawMode: parsed.rawMode,
188
+ debounceMs: parsed.debounceMs,
189
+ cap: parsed.cap,
190
+ dropPolicy: parsed.dropPolicy,
191
+ rawDebounce: parsed.rawDebounce,
192
+ rawCap: parsed.rawCap,
193
+ rawDrop: parsed.rawDrop,
194
+ hasDirective: true,
195
+ hasOptions: parsed.hasOptions
196
+ };
197
+ }
198
+
199
+ //#endregion
200
+ //#region src/infra/diagnostic-events.ts
201
+ let seq = 0;
202
+ const listeners = /* @__PURE__ */ new Set();
203
+ function isDiagnosticsEnabled(config) {
204
+ return config?.diagnostics?.enabled === true;
205
+ }
206
+ function emitDiagnosticEvent(event) {
207
+ const enriched = {
208
+ ...event,
209
+ seq: seq += 1,
210
+ ts: Date.now()
211
+ };
212
+ for (const listener of listeners) try {
213
+ listener(enriched);
214
+ } catch {}
215
+ }
216
+
217
+ //#endregion
218
+ //#region src/logging/diagnostic-session-state.ts
219
+ const diagnosticSessionStates = /* @__PURE__ */ new Map();
220
+ const SESSION_STATE_TTL_MS = 1800 * 1e3;
221
+ const SESSION_STATE_PRUNE_INTERVAL_MS = 60 * 1e3;
222
+ const SESSION_STATE_MAX_ENTRIES = 2e3;
223
+ let lastSessionPruneAt = 0;
224
+ function pruneDiagnosticSessionStates(now = Date.now(), force = false) {
225
+ const shouldPruneForSize = diagnosticSessionStates.size > SESSION_STATE_MAX_ENTRIES;
226
+ if (!force && !shouldPruneForSize && now - lastSessionPruneAt < SESSION_STATE_PRUNE_INTERVAL_MS) return;
227
+ lastSessionPruneAt = now;
228
+ for (const [key, state] of diagnosticSessionStates.entries()) {
229
+ const ageMs = now - state.lastActivity;
230
+ if (state.state === "idle" && state.queueDepth <= 0 && ageMs > SESSION_STATE_TTL_MS) diagnosticSessionStates.delete(key);
231
+ }
232
+ if (diagnosticSessionStates.size <= SESSION_STATE_MAX_ENTRIES) return;
233
+ const excess = diagnosticSessionStates.size - SESSION_STATE_MAX_ENTRIES;
234
+ const ordered = Array.from(diagnosticSessionStates.entries()).toSorted((a, b) => a[1].lastActivity - b[1].lastActivity);
235
+ for (let i = 0; i < excess; i += 1) {
236
+ const key = ordered[i]?.[0];
237
+ if (!key) break;
238
+ diagnosticSessionStates.delete(key);
239
+ }
240
+ }
241
+ function resolveSessionKey({ sessionKey, sessionId }) {
242
+ return sessionKey ?? sessionId ?? "unknown";
243
+ }
244
+ function getDiagnosticSessionState(ref) {
245
+ pruneDiagnosticSessionStates();
246
+ const key = resolveSessionKey(ref);
247
+ const existing = diagnosticSessionStates.get(key);
248
+ if (existing) {
249
+ if (ref.sessionId) existing.sessionId = ref.sessionId;
250
+ if (ref.sessionKey) existing.sessionKey = ref.sessionKey;
251
+ return existing;
252
+ }
253
+ const created = {
254
+ sessionId: ref.sessionId,
255
+ sessionKey: ref.sessionKey,
256
+ lastActivity: Date.now(),
257
+ state: "idle",
258
+ queueDepth: 0
259
+ };
260
+ diagnosticSessionStates.set(key, created);
261
+ pruneDiagnosticSessionStates(Date.now(), true);
262
+ return created;
263
+ }
264
+
265
+ //#endregion
266
+ //#region src/logging/diagnostic.ts
267
+ const diag = createSubsystemLogger("diagnostic");
268
+ const webhookStats = {
269
+ received: 0,
270
+ processed: 0,
271
+ errors: 0,
272
+ lastReceived: 0
273
+ };
274
+ let lastActivityAt = 0;
275
+ function markActivity() {
276
+ lastActivityAt = Date.now();
277
+ }
278
+ function logMessageQueued(params) {
279
+ const state = getDiagnosticSessionState(params);
280
+ state.queueDepth += 1;
281
+ state.lastActivity = Date.now();
282
+ 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}`);
283
+ emitDiagnosticEvent({
284
+ type: "message.queued",
285
+ sessionId: state.sessionId,
286
+ sessionKey: state.sessionKey,
287
+ channel: params.channel,
288
+ source: params.source,
289
+ queueDepth: state.queueDepth
290
+ });
291
+ markActivity();
292
+ }
293
+ function logMessageProcessed(params) {
294
+ if (params.outcome === "error" ? diag.isEnabled("error") : diag.isEnabled("debug")) {
295
+ 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}"` : ""}`;
296
+ if (params.outcome === "error") diag.error(payload);
297
+ else diag.debug(payload);
298
+ }
299
+ emitDiagnosticEvent({
300
+ type: "message.processed",
301
+ channel: params.channel,
302
+ chatId: params.chatId,
303
+ messageId: params.messageId,
304
+ sessionId: params.sessionId,
305
+ sessionKey: params.sessionKey,
306
+ durationMs: params.durationMs,
307
+ outcome: params.outcome,
308
+ reason: params.reason,
309
+ error: params.error
310
+ });
311
+ markActivity();
312
+ }
313
+ function logSessionStateChange(params) {
314
+ const state = getDiagnosticSessionState(params);
315
+ const isProbeSession = state.sessionId?.startsWith("probe-") ?? false;
316
+ const prevState = state.state;
317
+ state.state = params.state;
318
+ state.lastActivity = Date.now();
319
+ if (params.state === "idle") state.queueDepth = Math.max(0, state.queueDepth - 1);
320
+ 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}`);
321
+ emitDiagnosticEvent({
322
+ type: "session.state",
323
+ sessionId: state.sessionId,
324
+ sessionKey: state.sessionKey,
325
+ prevState,
326
+ state: params.state,
327
+ reason: params.reason,
328
+ queueDepth: state.queueDepth
329
+ });
330
+ markActivity();
331
+ }
332
+ function logSessionStuck(params) {
333
+ const state = getDiagnosticSessionState(params);
334
+ 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}`);
335
+ emitDiagnosticEvent({
336
+ type: "session.stuck",
337
+ sessionId: state.sessionId,
338
+ sessionKey: state.sessionKey,
339
+ state: params.state,
340
+ ageMs: params.ageMs,
341
+ queueDepth: state.queueDepth
342
+ });
343
+ markActivity();
344
+ }
345
+ function logLaneDequeue(lane, waitMs, queueSize) {
346
+ diag.debug(`lane dequeue: lane=${lane} waitMs=${waitMs} queueSize=${queueSize}`);
347
+ emitDiagnosticEvent({
348
+ type: "queue.lane.dequeue",
349
+ lane,
350
+ queueSize,
351
+ waitMs
352
+ });
353
+ markActivity();
354
+ }
355
+ let heartbeatInterval = null;
356
+ function startDiagnosticHeartbeat() {
357
+ if (heartbeatInterval) return;
358
+ heartbeatInterval = setInterval(() => {
359
+ const now = Date.now();
360
+ pruneDiagnosticSessionStates(now, true);
361
+ const activeCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "processing").length;
362
+ const waitingCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "waiting").length;
363
+ const totalQueued = Array.from(diagnosticSessionStates.values()).reduce((sum, s) => sum + s.queueDepth, 0);
364
+ if (!(lastActivityAt > 0 || webhookStats.received > 0 || activeCount > 0 || waitingCount > 0 || totalQueued > 0)) return;
365
+ if (now - lastActivityAt > 12e4 && activeCount === 0 && waitingCount === 0) return;
366
+ diag.debug(`heartbeat: webhooks=${webhookStats.received}/${webhookStats.processed}/${webhookStats.errors} active=${activeCount} waiting=${waitingCount} queued=${totalQueued}`);
367
+ emitDiagnosticEvent({
368
+ type: "diagnostic.heartbeat",
369
+ webhooks: {
370
+ received: webhookStats.received,
371
+ processed: webhookStats.processed,
372
+ errors: webhookStats.errors
373
+ },
374
+ active: activeCount,
375
+ waiting: waitingCount,
376
+ queued: totalQueued
377
+ });
378
+ for (const [, state] of diagnosticSessionStates) {
379
+ const ageMs = now - state.lastActivity;
380
+ if (state.state === "processing" && ageMs > 12e4) logSessionStuck({
381
+ sessionId: state.sessionId,
382
+ sessionKey: state.sessionKey,
383
+ state: state.state,
384
+ ageMs
385
+ });
386
+ }
387
+ }, 3e4);
388
+ heartbeatInterval.unref?.();
389
+ }
390
+ function stopDiagnosticHeartbeat() {
391
+ if (heartbeatInterval) {
392
+ clearInterval(heartbeatInterval);
393
+ heartbeatInterval = null;
394
+ }
395
+ }
396
+
397
+ //#endregion
398
+ //#region src/process/command-queue.ts
399
+ /**
400
+ * Dedicated error type thrown when a queued command is rejected because
401
+ * its lane was cleared. Callers that fire-and-forget enqueued tasks can
402
+ * catch (or ignore) this specific type to avoid unhandled-rejection noise.
403
+ */
404
+ var CommandLaneClearedError = class extends Error {
405
+ constructor(lane) {
406
+ super(lane ? `Command lane "${lane}" cleared` : "Command lane cleared");
407
+ this.name = "CommandLaneClearedError";
408
+ }
409
+ };
410
+ const lanes = /* @__PURE__ */ new Map();
411
+ let nextTaskId = 1;
412
+ function getLaneState(lane) {
413
+ const existing = lanes.get(lane);
414
+ if (existing) return existing;
415
+ const created = {
416
+ lane,
417
+ queue: [],
418
+ activeTaskIds: /* @__PURE__ */ new Set(),
419
+ maxConcurrent: 1,
420
+ draining: false,
421
+ generation: 0
422
+ };
423
+ lanes.set(lane, created);
424
+ return created;
425
+ }
426
+ function completeTask(state, taskId, taskGeneration) {
427
+ if (taskGeneration !== state.generation) return false;
428
+ state.activeTaskIds.delete(taskId);
429
+ return true;
430
+ }
431
+ function drainLane(lane) {
432
+ const state = getLaneState(lane);
433
+ if (state.draining) return;
434
+ state.draining = true;
435
+ const pump = () => {
436
+ while (state.activeTaskIds.size < state.maxConcurrent && state.queue.length > 0) {
437
+ const entry = state.queue.shift();
438
+ const waitedMs = Date.now() - entry.enqueuedAt;
439
+ if (waitedMs >= entry.warnAfterMs) {
440
+ entry.onWait?.(waitedMs, state.queue.length);
441
+ diag.warn(`lane wait exceeded: lane=${lane} waitedMs=${waitedMs} queueAhead=${state.queue.length}`);
442
+ }
443
+ logLaneDequeue(lane, waitedMs, state.queue.length);
444
+ const taskId = nextTaskId++;
445
+ const taskGeneration = state.generation;
446
+ state.activeTaskIds.add(taskId);
447
+ (async () => {
448
+ const startTime = Date.now();
449
+ try {
450
+ const result = await entry.task();
451
+ if (completeTask(state, taskId, taskGeneration)) {
452
+ diag.debug(`lane task done: lane=${lane} durationMs=${Date.now() - startTime} active=${state.activeTaskIds.size} queued=${state.queue.length}`);
453
+ pump();
454
+ }
455
+ entry.resolve(result);
456
+ } catch (err) {
457
+ const completedCurrentGeneration = completeTask(state, taskId, taskGeneration);
458
+ if (!(lane.startsWith("auth-probe:") || lane.startsWith("session:probe-"))) diag.error(`lane task error: lane=${lane} durationMs=${Date.now() - startTime} error="${String(err)}"`);
459
+ if (completedCurrentGeneration) pump();
460
+ entry.reject(err);
461
+ }
462
+ })();
463
+ }
464
+ state.draining = false;
465
+ };
466
+ pump();
467
+ }
468
+ function setCommandLaneConcurrency(lane, maxConcurrent) {
469
+ const cleaned = lane.trim() || CommandLane.Main;
470
+ const state = getLaneState(cleaned);
471
+ state.maxConcurrent = Math.max(1, Math.floor(maxConcurrent));
472
+ drainLane(cleaned);
473
+ }
474
+ function getQueueSize(lane = CommandLane.Main) {
475
+ const resolved = lane.trim() || CommandLane.Main;
476
+ const state = lanes.get(resolved);
477
+ if (!state) return 0;
478
+ return state.queue.length + state.activeTaskIds.size;
479
+ }
480
+ function getTotalQueueSize() {
481
+ let total = 0;
482
+ for (const s of lanes.values()) total += s.queue.length + s.activeTaskIds.size;
483
+ return total;
484
+ }
485
+ function clearCommandLane(lane = CommandLane.Main) {
486
+ const cleaned = lane.trim() || CommandLane.Main;
487
+ const state = lanes.get(cleaned);
488
+ if (!state) return 0;
489
+ const removed = state.queue.length;
490
+ const pending = state.queue.splice(0);
491
+ for (const entry of pending) entry.reject(new CommandLaneClearedError(cleaned));
492
+ return removed;
493
+ }
494
+ /**
495
+ * Reset all lane runtime state to idle. Used after SIGUSR1 in-process
496
+ * restarts where interrupted tasks' finally blocks may not run, leaving
497
+ * stale active task IDs that permanently block new work from draining.
498
+ *
499
+ * Bumps lane generation and clears execution counters so stale completions
500
+ * from old in-flight tasks are ignored. Queued entries are intentionally
501
+ * preserved — they represent pending user work that should still execute
502
+ * after restart.
503
+ *
504
+ * After resetting, drains any lanes that still have queued entries so
505
+ * preserved work is pumped immediately rather than waiting for a future
506
+ * `enqueueCommandInLane()` call (which may never come).
507
+ */
508
+ function resetAllLanes() {
509
+ const lanesToDrain = [];
510
+ for (const state of lanes.values()) {
511
+ state.generation += 1;
512
+ state.activeTaskIds.clear();
513
+ state.draining = false;
514
+ if (state.queue.length > 0) lanesToDrain.push(state.lane);
515
+ }
516
+ for (const lane of lanesToDrain) drainLane(lane);
517
+ }
518
+ /**
519
+ * Returns the total number of actively executing tasks across all lanes
520
+ * (excludes queued-but-not-started entries).
521
+ */
522
+ function getActiveTaskCount() {
523
+ let total = 0;
524
+ for (const s of lanes.values()) total += s.activeTaskIds.size;
525
+ return total;
526
+ }
527
+ /**
528
+ * Wait for all currently active tasks across all lanes to finish.
529
+ * Polls at a short interval; resolves when no tasks are active or
530
+ * when `timeoutMs` elapses (whichever comes first).
531
+ *
532
+ * New tasks enqueued after this call are ignored — only tasks that are
533
+ * already executing are waited on.
534
+ */
535
+ function waitForActiveTasks(timeoutMs) {
536
+ const POLL_INTERVAL_MS = 50;
537
+ const deadline = Date.now() + timeoutMs;
538
+ const activeAtStart = /* @__PURE__ */ new Set();
539
+ for (const state of lanes.values()) for (const taskId of state.activeTaskIds) activeAtStart.add(taskId);
540
+ return new Promise((resolve) => {
541
+ const check = () => {
542
+ if (activeAtStart.size === 0) {
543
+ resolve({ drained: true });
544
+ return;
545
+ }
546
+ let hasPending = false;
547
+ for (const state of lanes.values()) {
548
+ for (const taskId of state.activeTaskIds) if (activeAtStart.has(taskId)) {
549
+ hasPending = true;
550
+ break;
551
+ }
552
+ if (hasPending) break;
553
+ }
554
+ if (!hasPending) {
555
+ resolve({ drained: true });
556
+ return;
557
+ }
558
+ if (Date.now() >= deadline) {
559
+ resolve({ drained: false });
560
+ return;
561
+ }
562
+ setTimeout(check, POLL_INTERVAL_MS);
563
+ };
564
+ check();
565
+ });
566
+ }
567
+
568
+ //#endregion
569
+ //#region src/auto-reply/reply/queue/state.ts
570
+ const DEFAULT_QUEUE_DEBOUNCE_MS = 1e3;
571
+ const DEFAULT_QUEUE_CAP = 20;
572
+ const DEFAULT_QUEUE_DROP = "summarize";
573
+ const FOLLOWUP_QUEUES = /* @__PURE__ */ new Map();
574
+ function getFollowupQueue(key, settings) {
575
+ const existing = FOLLOWUP_QUEUES.get(key);
576
+ if (existing) {
577
+ existing.mode = settings.mode;
578
+ existing.debounceMs = typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : existing.debounceMs;
579
+ existing.cap = typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : existing.cap;
580
+ existing.dropPolicy = settings.dropPolicy ?? existing.dropPolicy;
581
+ return existing;
582
+ }
583
+ const created = {
584
+ items: [],
585
+ draining: false,
586
+ lastEnqueuedAt: 0,
587
+ mode: settings.mode,
588
+ debounceMs: typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : DEFAULT_QUEUE_DEBOUNCE_MS,
589
+ cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : DEFAULT_QUEUE_CAP,
590
+ dropPolicy: settings.dropPolicy ?? DEFAULT_QUEUE_DROP,
591
+ droppedCount: 0,
592
+ summaryLines: []
593
+ };
594
+ FOLLOWUP_QUEUES.set(key, created);
595
+ return created;
596
+ }
597
+ function clearFollowupQueue(key) {
598
+ const cleaned = key.trim();
599
+ if (!cleaned) return 0;
600
+ const queue = FOLLOWUP_QUEUES.get(cleaned);
601
+ if (!queue) return 0;
602
+ const cleared = queue.items.length + queue.droppedCount;
603
+ queue.items.length = 0;
604
+ queue.droppedCount = 0;
605
+ queue.summaryLines = [];
606
+ queue.lastRun = void 0;
607
+ queue.lastEnqueuedAt = 0;
608
+ FOLLOWUP_QUEUES.delete(cleaned);
609
+ return cleared;
610
+ }
611
+
612
+ //#endregion
613
+ //#region src/auto-reply/reply/queue/cleanup.ts
614
+ function clearSessionQueues(keys) {
615
+ const seen = /* @__PURE__ */ new Set();
616
+ let followupCleared = 0;
617
+ let laneCleared = 0;
618
+ const clearedKeys = [];
619
+ for (const key of keys) {
620
+ const cleaned = key?.trim();
621
+ if (!cleaned || seen.has(cleaned)) continue;
622
+ seen.add(cleaned);
623
+ clearedKeys.push(cleaned);
624
+ followupCleared += clearFollowupQueue(cleaned);
625
+ laneCleared += clearCommandLane(resolveEmbeddedSessionLane(cleaned));
626
+ }
627
+ return {
628
+ followupCleared,
629
+ laneCleared,
630
+ keys: clearedKeys
631
+ };
632
+ }
633
+
634
+ //#endregion
635
+ //#region src/utils/queue-helpers.ts
636
+ function elideQueueText(text, limit = 140) {
637
+ if (text.length <= limit) return text;
638
+ return `${text.slice(0, Math.max(0, limit - 1)).trimEnd()}…`;
639
+ }
640
+ function buildQueueSummaryLine(text, limit = 160) {
641
+ return elideQueueText(text.replace(/\s+/g, " ").trim(), limit);
642
+ }
643
+ function shouldSkipQueueItem(params) {
644
+ if (!params.dedupe) return false;
645
+ return params.dedupe(params.item, params.items);
646
+ }
647
+ function applyQueueDropPolicy(params) {
648
+ const cap = params.queue.cap;
649
+ if (cap <= 0 || params.queue.items.length < cap) return true;
650
+ if (params.queue.dropPolicy === "new") return false;
651
+ const dropCount = params.queue.items.length - cap + 1;
652
+ const dropped = params.queue.items.splice(0, dropCount);
653
+ if (params.queue.dropPolicy === "summarize") {
654
+ for (const item of dropped) {
655
+ params.queue.droppedCount += 1;
656
+ params.queue.summaryLines.push(buildQueueSummaryLine(params.summarize(item)));
657
+ }
658
+ const limit = Math.max(0, params.summaryLimit ?? cap);
659
+ while (params.queue.summaryLines.length > limit) params.queue.summaryLines.shift();
660
+ }
661
+ return true;
662
+ }
663
+ function waitForQueueDebounce(queue) {
664
+ const debounceMs = Math.max(0, queue.debounceMs);
665
+ if (debounceMs <= 0) return Promise.resolve();
666
+ return new Promise((resolve) => {
667
+ const check = () => {
668
+ const since = Date.now() - queue.lastEnqueuedAt;
669
+ if (since >= debounceMs) {
670
+ resolve();
671
+ return;
672
+ }
673
+ setTimeout(check, debounceMs - since);
674
+ };
675
+ check();
676
+ });
677
+ }
678
+ function buildQueueSummaryPrompt(params) {
679
+ if (params.state.dropPolicy !== "summarize" || params.state.droppedCount <= 0) return;
680
+ const noun = params.noun;
681
+ const lines = [params.title ?? `[Queue overflow] Dropped ${params.state.droppedCount} ${noun}${params.state.droppedCount === 1 ? "" : "s"} due to cap.`];
682
+ if (params.state.summaryLines.length > 0) {
683
+ lines.push("Summary:");
684
+ for (const line of params.state.summaryLines) lines.push(`- ${line}`);
685
+ }
686
+ params.state.droppedCount = 0;
687
+ params.state.summaryLines = [];
688
+ return lines.join("\n");
689
+ }
690
+ function buildCollectPrompt(params) {
691
+ const blocks = [params.title];
692
+ if (params.summary) blocks.push(params.summary);
693
+ params.items.forEach((item, idx) => {
694
+ blocks.push(params.renderItem(item, idx));
695
+ });
696
+ return blocks.join("\n\n");
697
+ }
698
+ function hasCrossChannelItems(items, resolveKey) {
699
+ const keys = /* @__PURE__ */ new Set();
700
+ let hasUnkeyed = false;
701
+ for (const item of items) {
702
+ const resolved = resolveKey(item);
703
+ if (resolved.cross) return true;
704
+ if (!resolved.key) {
705
+ hasUnkeyed = true;
706
+ continue;
707
+ }
708
+ keys.add(resolved.key);
709
+ }
710
+ if (keys.size === 0) return false;
711
+ if (hasUnkeyed) return true;
712
+ return keys.size > 1;
713
+ }
714
+
715
+ //#endregion
716
+ //#region src/agents/identity.ts
717
+ function resolveAgentIdentity(cfg, agentId) {
718
+ return resolveAgentConfig(cfg, agentId)?.identity;
719
+ }
720
+ function resolveIdentityNamePrefix(cfg, agentId) {
721
+ const name = resolveAgentIdentity(cfg, agentId)?.name?.trim();
722
+ if (!name) return;
723
+ return `[${name}]`;
724
+ }
725
+ /** Returns just the identity name (without brackets) for template context. */
726
+ function resolveIdentityName(cfg, agentId) {
727
+ return resolveAgentIdentity(cfg, agentId)?.name?.trim() || void 0;
728
+ }
729
+ function resolveMessagePrefix(cfg, agentId, opts) {
730
+ const configured = opts?.configured ?? cfg.messages?.messagePrefix;
731
+ if (configured !== void 0) return configured;
732
+ if (opts?.hasAllowFrom === true) return "";
733
+ return resolveIdentityNamePrefix(cfg, agentId) ?? opts?.fallback ?? "[anima]";
734
+ }
735
+ /** Helper to extract a channel config value by dynamic key. */
736
+ function getChannelConfig(cfg, channel) {
737
+ const value = cfg.channels?.[channel];
738
+ return typeof value === "object" && value !== null ? value : void 0;
739
+ }
740
+ function resolveResponsePrefix(cfg, agentId, opts) {
741
+ if (opts?.channel && opts?.accountId) {
742
+ const accountPrefix = (getChannelConfig(cfg, opts.channel)?.accounts)?.[opts.accountId]?.responsePrefix;
743
+ if (accountPrefix !== void 0) {
744
+ if (accountPrefix === "auto") return resolveIdentityNamePrefix(cfg, agentId);
745
+ return accountPrefix;
746
+ }
747
+ }
748
+ if (opts?.channel) {
749
+ const channelPrefix = getChannelConfig(cfg, opts.channel)?.responsePrefix;
750
+ if (channelPrefix !== void 0) {
751
+ if (channelPrefix === "auto") return resolveIdentityNamePrefix(cfg, agentId);
752
+ return channelPrefix;
753
+ }
754
+ }
755
+ const configured = cfg.messages?.responsePrefix;
756
+ if (configured !== void 0) {
757
+ if (configured === "auto") return resolveIdentityNamePrefix(cfg, agentId);
758
+ return configured;
759
+ }
760
+ }
761
+ function resolveEffectiveMessagesConfig(cfg, agentId, opts) {
762
+ return {
763
+ messagePrefix: resolveMessagePrefix(cfg, agentId, {
764
+ hasAllowFrom: opts?.hasAllowFrom,
765
+ fallback: opts?.fallbackMessagePrefix
766
+ }),
767
+ responsePrefix: resolveResponsePrefix(cfg, agentId, {
768
+ channel: opts?.channel,
769
+ accountId: opts?.accountId
770
+ })
771
+ };
772
+ }
773
+ function resolveHumanDelayConfig(cfg, agentId) {
774
+ const defaults = cfg.agents?.defaults?.humanDelay;
775
+ const overrides = resolveAgentConfig(cfg, agentId)?.humanDelay;
776
+ if (!defaults && !overrides) return;
777
+ return {
778
+ mode: overrides?.mode ?? defaults?.mode,
779
+ minMs: overrides?.minMs ?? defaults?.minMs,
780
+ maxMs: overrides?.maxMs ?? defaults?.maxMs
781
+ };
782
+ }
783
+
784
+ //#endregion
785
+ //#region src/auto-reply/reply/line-directives.ts
786
+ /**
787
+ * Parse LINE-specific directives from text and extract them into ReplyPayload fields.
788
+ *
789
+ * Supported directives:
790
+ * - [[quick_replies: option1, option2, option3]]
791
+ * - [[location: title | address | latitude | longitude]]
792
+ * - [[confirm: question | yes_label | no_label]]
793
+ * - [[buttons: title | text | btn1:data1, btn2:data2]]
794
+ * - [[media_player: title | artist | source | imageUrl | playing/paused]]
795
+ * - [[event: title | date | time | location | description]]
796
+ * - [[agenda: title | event1_title:event1_time, event2_title:event2_time, ...]]
797
+ * - [[device: name | type | status | ctrl1:data1, ctrl2:data2]]
798
+ * - [[appletv_remote: name | status]]
799
+ *
800
+ * Returns the modified payload with directives removed from text and fields populated.
801
+ */
802
+ function parseLineDirectives(payload) {
803
+ let text = payload.text;
804
+ if (!text) return payload;
805
+ const result = { ...payload };
806
+ const lineData = { ...result.channelData?.line };
807
+ const toSlug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "device";
808
+ const lineActionData = (action, extras) => {
809
+ const base = [`line.action=${encodeURIComponent(action)}`];
810
+ if (extras) for (const [key, value] of Object.entries(extras)) base.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
811
+ return base.join("&");
812
+ };
813
+ const quickRepliesMatch = text.match(/\[\[quick_replies:\s*([^\]]+)\]\]/i);
814
+ if (quickRepliesMatch) {
815
+ const options = quickRepliesMatch[1].split(",").map((s) => s.trim()).filter(Boolean);
816
+ if (options.length > 0) lineData.quickReplies = [...lineData.quickReplies || [], ...options];
817
+ text = text.replace(quickRepliesMatch[0], "").trim();
818
+ }
819
+ const locationMatch = text.match(/\[\[location:\s*([^\]]+)\]\]/i);
820
+ if (locationMatch && !lineData.location) {
821
+ const parts = locationMatch[1].split("|").map((s) => s.trim());
822
+ if (parts.length >= 4) {
823
+ const [title, address, latStr, lonStr] = parts;
824
+ const latitude = parseFloat(latStr);
825
+ const longitude = parseFloat(lonStr);
826
+ if (!isNaN(latitude) && !isNaN(longitude)) lineData.location = {
827
+ title: title || "Location",
828
+ address: address || "",
829
+ latitude,
830
+ longitude
831
+ };
832
+ }
833
+ text = text.replace(locationMatch[0], "").trim();
834
+ }
835
+ const confirmMatch = text.match(/\[\[confirm:\s*([^\]]+)\]\]/i);
836
+ if (confirmMatch && !lineData.templateMessage) {
837
+ const parts = confirmMatch[1].split("|").map((s) => s.trim());
838
+ if (parts.length >= 3) {
839
+ const [question, yesPart, noPart] = parts;
840
+ const [yesLabel, yesData] = yesPart.includes(":") ? yesPart.split(":").map((s) => s.trim()) : [yesPart, yesPart.toLowerCase()];
841
+ const [noLabel, noData] = noPart.includes(":") ? noPart.split(":").map((s) => s.trim()) : [noPart, noPart.toLowerCase()];
842
+ lineData.templateMessage = {
843
+ type: "confirm",
844
+ text: question,
845
+ confirmLabel: yesLabel,
846
+ confirmData: yesData,
847
+ cancelLabel: noLabel,
848
+ cancelData: noData,
849
+ altText: question
850
+ };
851
+ }
852
+ text = text.replace(confirmMatch[0], "").trim();
853
+ }
854
+ const buttonsMatch = text.match(/\[\[buttons:\s*([^\]]+)\]\]/i);
855
+ if (buttonsMatch && !lineData.templateMessage) {
856
+ const parts = buttonsMatch[1].split("|").map((s) => s.trim());
857
+ if (parts.length >= 3) {
858
+ const [title, bodyText, actionsStr] = parts;
859
+ const actions = actionsStr.split(",").map((actionStr) => {
860
+ const trimmed = actionStr.trim();
861
+ const colonIndex = (() => {
862
+ const index = trimmed.indexOf(":");
863
+ if (index === -1) return -1;
864
+ const lower = trimmed.toLowerCase();
865
+ if (lower.startsWith("http://") || lower.startsWith("https://")) return -1;
866
+ return index;
867
+ })();
868
+ let label;
869
+ let data;
870
+ if (colonIndex === -1) {
871
+ label = trimmed;
872
+ data = trimmed;
873
+ } else {
874
+ label = trimmed.slice(0, colonIndex).trim();
875
+ data = trimmed.slice(colonIndex + 1).trim();
876
+ }
877
+ if (data.startsWith("http://") || data.startsWith("https://")) return {
878
+ type: "uri",
879
+ label,
880
+ uri: data
881
+ };
882
+ if (data.includes("=")) return {
883
+ type: "postback",
884
+ label,
885
+ data
886
+ };
887
+ return {
888
+ type: "message",
889
+ label,
890
+ data: data || label
891
+ };
892
+ });
893
+ if (actions.length > 0) lineData.templateMessage = {
894
+ type: "buttons",
895
+ title,
896
+ text: bodyText,
897
+ actions: actions.slice(0, 4),
898
+ altText: `${title}: ${bodyText}`
899
+ };
900
+ }
901
+ text = text.replace(buttonsMatch[0], "").trim();
902
+ }
903
+ const mediaPlayerMatch = text.match(/\[\[media_player:\s*([^\]]+)\]\]/i);
904
+ if (mediaPlayerMatch && !lineData.flexMessage) {
905
+ const parts = mediaPlayerMatch[1].split("|").map((s) => s.trim());
906
+ if (parts.length >= 1) {
907
+ const [title, artist, source, imageUrl, statusStr] = parts;
908
+ const isPlaying = statusStr?.toLowerCase() === "playing";
909
+ const validImageUrl = imageUrl?.startsWith("https://") ? imageUrl : void 0;
910
+ const deviceKey = toSlug(source || title || "media");
911
+ const card = createMediaPlayerCard({
912
+ title: title || "Unknown Track",
913
+ subtitle: artist || void 0,
914
+ source: source || void 0,
915
+ imageUrl: validImageUrl,
916
+ isPlaying: statusStr ? isPlaying : void 0,
917
+ controls: {
918
+ previous: { data: lineActionData("previous", { "line.device": deviceKey }) },
919
+ play: { data: lineActionData("play", { "line.device": deviceKey }) },
920
+ pause: { data: lineActionData("pause", { "line.device": deviceKey }) },
921
+ next: { data: lineActionData("next", { "line.device": deviceKey }) }
922
+ }
923
+ });
924
+ lineData.flexMessage = {
925
+ altText: `🎵 ${title}${artist ? ` - ${artist}` : ""}`,
926
+ contents: card
927
+ };
928
+ }
929
+ text = text.replace(mediaPlayerMatch[0], "").trim();
930
+ }
931
+ const eventMatch = text.match(/\[\[event:\s*([^\]]+)\]\]/i);
932
+ if (eventMatch && !lineData.flexMessage) {
933
+ const parts = eventMatch[1].split("|").map((s) => s.trim());
934
+ if (parts.length >= 2) {
935
+ const [title, date, time, location, description] = parts;
936
+ const card = createEventCard({
937
+ title: title || "Event",
938
+ date: date || "TBD",
939
+ time: time || void 0,
940
+ location: location || void 0,
941
+ description: description || void 0
942
+ });
943
+ lineData.flexMessage = {
944
+ altText: `📅 ${title} - ${date}${time ? ` ${time}` : ""}`,
945
+ contents: card
946
+ };
947
+ }
948
+ text = text.replace(eventMatch[0], "").trim();
949
+ }
950
+ const appleTvMatch = text.match(/\[\[appletv_remote:\s*([^\]]+)\]\]/i);
951
+ if (appleTvMatch && !lineData.flexMessage) {
952
+ const parts = appleTvMatch[1].split("|").map((s) => s.trim());
953
+ if (parts.length >= 1) {
954
+ const [deviceName, status] = parts;
955
+ const deviceKey = toSlug(deviceName || "apple_tv");
956
+ const card = createAppleTvRemoteCard({
957
+ deviceName: deviceName || "Apple TV",
958
+ status: status || void 0,
959
+ actionData: {
960
+ up: lineActionData("up", { "line.device": deviceKey }),
961
+ down: lineActionData("down", { "line.device": deviceKey }),
962
+ left: lineActionData("left", { "line.device": deviceKey }),
963
+ right: lineActionData("right", { "line.device": deviceKey }),
964
+ select: lineActionData("select", { "line.device": deviceKey }),
965
+ menu: lineActionData("menu", { "line.device": deviceKey }),
966
+ home: lineActionData("home", { "line.device": deviceKey }),
967
+ play: lineActionData("play", { "line.device": deviceKey }),
968
+ pause: lineActionData("pause", { "line.device": deviceKey }),
969
+ volumeUp: lineActionData("volume_up", { "line.device": deviceKey }),
970
+ volumeDown: lineActionData("volume_down", { "line.device": deviceKey }),
971
+ mute: lineActionData("mute", { "line.device": deviceKey })
972
+ }
973
+ });
974
+ lineData.flexMessage = {
975
+ altText: `📺 ${deviceName || "Apple TV"} Remote`,
976
+ contents: card
977
+ };
978
+ }
979
+ text = text.replace(appleTvMatch[0], "").trim();
980
+ }
981
+ const agendaMatch = text.match(/\[\[agenda:\s*([^\]]+)\]\]/i);
982
+ if (agendaMatch && !lineData.flexMessage) {
983
+ const parts = agendaMatch[1].split("|").map((s) => s.trim());
984
+ if (parts.length >= 2) {
985
+ const [title, eventsStr] = parts;
986
+ const events = eventsStr.split(",").map((eventStr) => {
987
+ const trimmed = eventStr.trim();
988
+ const colonIdx = trimmed.lastIndexOf(":");
989
+ if (colonIdx > 0) return {
990
+ title: trimmed.slice(0, colonIdx).trim(),
991
+ time: trimmed.slice(colonIdx + 1).trim()
992
+ };
993
+ return { title: trimmed };
994
+ });
995
+ const card = createAgendaCard({
996
+ title: title || "Agenda",
997
+ events
998
+ });
999
+ lineData.flexMessage = {
1000
+ altText: `📋 ${title} (${events.length} events)`,
1001
+ contents: card
1002
+ };
1003
+ }
1004
+ text = text.replace(agendaMatch[0], "").trim();
1005
+ }
1006
+ const deviceMatch = text.match(/\[\[device:\s*([^\]]+)\]\]/i);
1007
+ if (deviceMatch && !lineData.flexMessage) {
1008
+ const parts = deviceMatch[1].split("|").map((s) => s.trim());
1009
+ if (parts.length >= 1) {
1010
+ const [deviceName, deviceType, status, controlsStr] = parts;
1011
+ const deviceKey = toSlug(deviceName || "device");
1012
+ const controls = controlsStr ? controlsStr.split(",").map((ctrlStr) => {
1013
+ const [label, data] = ctrlStr.split(":").map((s) => s.trim());
1014
+ return {
1015
+ label,
1016
+ data: lineActionData(data || label.toLowerCase().replace(/\s+/g, "_"), { "line.device": deviceKey })
1017
+ };
1018
+ }) : [];
1019
+ const card = createDeviceControlCard({
1020
+ deviceName: deviceName || "Device",
1021
+ deviceType: deviceType || void 0,
1022
+ status: status || void 0,
1023
+ controls
1024
+ });
1025
+ lineData.flexMessage = {
1026
+ altText: `📱 ${deviceName}${status ? `: ${status}` : ""}`,
1027
+ contents: card
1028
+ };
1029
+ }
1030
+ text = text.replace(deviceMatch[0], "").trim();
1031
+ }
1032
+ text = text.replace(/\n{3,}/g, "\n\n").trim();
1033
+ result.text = text || void 0;
1034
+ if (Object.keys(lineData).length > 0) result.channelData = {
1035
+ ...result.channelData,
1036
+ line: lineData
1037
+ };
1038
+ return result;
1039
+ }
1040
+ /**
1041
+ * Check if text contains any LINE directives
1042
+ */
1043
+ function hasLineDirectives(text) {
1044
+ return /\[\[(quick_replies|location|confirm|buttons|media_player|event|agenda|device|appletv_remote):/i.test(text);
1045
+ }
1046
+
1047
+ //#endregion
1048
+ //#region src/auto-reply/reply/response-prefix-template.ts
1049
+ const TEMPLATE_VAR_PATTERN = /\{([a-zA-Z][a-zA-Z0-9.]*)\}/g;
1050
+ /**
1051
+ * Interpolate template variables in a response prefix string.
1052
+ *
1053
+ * @param template - The template string with `{variable}` placeholders
1054
+ * @param context - Context object with values for interpolation
1055
+ * @returns The interpolated string, or undefined if template is undefined
1056
+ *
1057
+ * @example
1058
+ * resolveResponsePrefixTemplate("[{model} | think:{thinkingLevel}]", {
1059
+ * model: "gpt-5.2",
1060
+ * thinkingLevel: "high"
1061
+ * })
1062
+ * // Returns: "[gpt-5.2 | think:high]"
1063
+ */
1064
+ function resolveResponsePrefixTemplate(template, context) {
1065
+ if (!template) return;
1066
+ return template.replace(TEMPLATE_VAR_PATTERN, (match, varName) => {
1067
+ switch (varName.toLowerCase()) {
1068
+ case "model": return context.model ?? match;
1069
+ case "modelfull": return context.modelFull ?? match;
1070
+ case "provider": return context.provider ?? match;
1071
+ case "thinkinglevel":
1072
+ case "think": return context.thinkingLevel ?? match;
1073
+ case "identity.name":
1074
+ case "identityname": return context.identityName ?? match;
1075
+ default: return match;
1076
+ }
1077
+ });
1078
+ }
1079
+ /**
1080
+ * Extract short model name from a full model string.
1081
+ *
1082
+ * Strips:
1083
+ * - Provider prefix (e.g., "openai/" from "openai/gpt-5.2")
1084
+ * - Date suffixes (e.g., "-20260205" from "claude-opus-4-6-20260205")
1085
+ * - Common version suffixes (e.g., "-latest")
1086
+ *
1087
+ * @example
1088
+ * extractShortModelName("openai-codex/gpt-5.2") // "gpt-5.2"
1089
+ * extractShortModelName("claude-opus-4-6-20260205") // "claude-opus-4-6"
1090
+ * extractShortModelName("gpt-5.2-latest") // "gpt-5.2"
1091
+ */
1092
+ function extractShortModelName(fullModel) {
1093
+ const slash = fullModel.lastIndexOf("/");
1094
+ return (slash >= 0 ? fullModel.slice(slash + 1) : fullModel).replace(/-\d{8}$/, "").replace(/-latest$/, "");
1095
+ }
1096
+
1097
+ //#endregion
1098
+ //#region src/auto-reply/reply/normalize-reply.ts
1099
+ function normalizeReplyPayload(payload, opts = {}) {
1100
+ const hasMedia = Boolean(payload.mediaUrl || (payload.mediaUrls?.length ?? 0) > 0);
1101
+ const hasChannelData = Boolean(payload.channelData && Object.keys(payload.channelData).length > 0);
1102
+ const trimmed = payload.text?.trim() ?? "";
1103
+ if (!trimmed && !hasMedia && !hasChannelData) {
1104
+ opts.onSkip?.("empty");
1105
+ return null;
1106
+ }
1107
+ const silentToken = opts.silentToken ?? SILENT_REPLY_TOKEN;
1108
+ let text = payload.text ?? void 0;
1109
+ if (text && isSilentReplyText(text, silentToken)) {
1110
+ if (!hasMedia && !hasChannelData) {
1111
+ opts.onSkip?.("silent");
1112
+ return null;
1113
+ }
1114
+ text = "";
1115
+ }
1116
+ if (text && !trimmed) text = "";
1117
+ if ((opts.stripHeartbeat ?? true) && text?.includes(HEARTBEAT_TOKEN)) {
1118
+ const stripped = stripHeartbeatToken(text, { mode: "message" });
1119
+ if (stripped.didStrip) opts.onHeartbeatStrip?.();
1120
+ if (stripped.shouldSkip && !hasMedia && !hasChannelData) {
1121
+ opts.onSkip?.("heartbeat");
1122
+ return null;
1123
+ }
1124
+ text = stripped.text;
1125
+ }
1126
+ if (text) text = sanitizeUserFacingText$1(text, { errorContext: Boolean(payload.isError) });
1127
+ if (!text?.trim() && !hasMedia && !hasChannelData) {
1128
+ opts.onSkip?.("empty");
1129
+ return null;
1130
+ }
1131
+ let enrichedPayload = {
1132
+ ...payload,
1133
+ text
1134
+ };
1135
+ if (text && hasLineDirectives(text)) {
1136
+ enrichedPayload = parseLineDirectives(enrichedPayload);
1137
+ text = enrichedPayload.text;
1138
+ }
1139
+ const effectivePrefix = opts.responsePrefixContext ? resolveResponsePrefixTemplate(opts.responsePrefix, opts.responsePrefixContext) : opts.responsePrefix;
1140
+ if (effectivePrefix && text && text.trim() !== HEARTBEAT_TOKEN && !text.startsWith(effectivePrefix)) text = `${effectivePrefix} ${text}`;
1141
+ return {
1142
+ ...enrichedPayload,
1143
+ text
1144
+ };
1145
+ }
1146
+
1147
+ //#endregion
1148
+ //#region src/auto-reply/reply/route-reply.ts
1149
+ /**
1150
+ * Routes a reply payload to the specified channel.
1151
+ *
1152
+ * This function provides a unified interface for sending messages to any
1153
+ * supported provider. It's used by the followup queue to route replies
1154
+ * back to the originating channel when OriginatingChannel/OriginatingTo
1155
+ * are set.
1156
+ */
1157
+ async function routeReply(params) {
1158
+ const { payload, channel, to, accountId, threadId, cfg, abortSignal } = params;
1159
+ const normalizedChannel = normalizeMessageChannel(channel);
1160
+ const normalized = normalizeReplyPayload(payload, { responsePrefix: params.sessionKey ? resolveEffectiveMessagesConfig(cfg, resolveSessionAgentId({
1161
+ sessionKey: params.sessionKey,
1162
+ config: cfg
1163
+ }), {
1164
+ channel: normalizedChannel,
1165
+ accountId
1166
+ }).responsePrefix : cfg.messages?.responsePrefix === "auto" ? void 0 : cfg.messages?.responsePrefix });
1167
+ if (!normalized) return { ok: true };
1168
+ let text = normalized.text ?? "";
1169
+ let mediaUrls = (normalized.mediaUrls?.filter(Boolean) ?? []).length ? normalized.mediaUrls?.filter(Boolean) : normalized.mediaUrl ? [normalized.mediaUrl] : [];
1170
+ const replyToId = normalized.replyToId;
1171
+ if (!text.trim() && mediaUrls.length === 0) return { ok: true };
1172
+ if (channel === INTERNAL_MESSAGE_CHANNEL) return {
1173
+ ok: false,
1174
+ error: "Webchat routing not supported for queued replies"
1175
+ };
1176
+ const channelId = normalizeChannelId(channel) ?? null;
1177
+ if (!channelId) return {
1178
+ ok: false,
1179
+ error: `Unknown channel: ${String(channel)}`
1180
+ };
1181
+ if (abortSignal?.aborted) return {
1182
+ ok: false,
1183
+ error: "Reply routing aborted"
1184
+ };
1185
+ const resolvedReplyToId = replyToId ?? (channelId === "slack" && threadId != null && threadId !== "" ? String(threadId) : void 0);
1186
+ const resolvedThreadId = channelId === "slack" ? null : threadId ?? null;
1187
+ try {
1188
+ const { deliverOutboundPayloads } = await import("./deliver-BBggsviM.js").then((n) => n.n);
1189
+ return {
1190
+ ok: true,
1191
+ messageId: (await deliverOutboundPayloads({
1192
+ cfg,
1193
+ channel: channelId,
1194
+ to,
1195
+ accountId: accountId ?? void 0,
1196
+ payloads: [normalized],
1197
+ replyToId: resolvedReplyToId ?? null,
1198
+ threadId: resolvedThreadId,
1199
+ abortSignal,
1200
+ mirror: params.mirror !== false && params.sessionKey ? {
1201
+ sessionKey: params.sessionKey,
1202
+ agentId: resolveSessionAgentId({
1203
+ sessionKey: params.sessionKey,
1204
+ config: cfg
1205
+ }),
1206
+ text,
1207
+ mediaUrls
1208
+ } : void 0
1209
+ })).at(-1)?.messageId
1210
+ };
1211
+ } catch (err) {
1212
+ return {
1213
+ ok: false,
1214
+ error: `Failed to route reply to ${channel}: ${err instanceof Error ? err.message : String(err)}`
1215
+ };
1216
+ }
1217
+ }
1218
+ /**
1219
+ * Checks if a channel type is routable via routeReply.
1220
+ *
1221
+ * Some channels (webchat) require special handling and cannot be routed through
1222
+ * this generic interface.
1223
+ */
1224
+ function isRoutableChannel(channel) {
1225
+ if (!channel || channel === INTERNAL_MESSAGE_CHANNEL) return false;
1226
+ return normalizeChannelId(channel) !== null;
1227
+ }
1228
+
1229
+ //#endregion
1230
+ //#region src/auto-reply/reply/queue/drain.ts
1231
+ function previewQueueSummaryPrompt$1(queue) {
1232
+ return buildQueueSummaryPrompt({
1233
+ state: {
1234
+ dropPolicy: queue.dropPolicy,
1235
+ droppedCount: queue.droppedCount,
1236
+ summaryLines: [...queue.summaryLines]
1237
+ },
1238
+ noun: "message"
1239
+ });
1240
+ }
1241
+ function clearQueueSummaryState$1(queue) {
1242
+ queue.droppedCount = 0;
1243
+ queue.summaryLines = [];
1244
+ }
1245
+ function scheduleFollowupDrain(key, runFollowup) {
1246
+ const queue = FOLLOWUP_QUEUES.get(key);
1247
+ if (!queue || queue.draining) return;
1248
+ queue.draining = true;
1249
+ (async () => {
1250
+ try {
1251
+ let forceIndividualCollect = false;
1252
+ while (queue.items.length > 0 || queue.droppedCount > 0) {
1253
+ await waitForQueueDebounce(queue);
1254
+ if (queue.mode === "collect") {
1255
+ if (forceIndividualCollect) {
1256
+ const next = queue.items[0];
1257
+ if (!next) break;
1258
+ await runFollowup(next);
1259
+ queue.items.shift();
1260
+ continue;
1261
+ }
1262
+ if (hasCrossChannelItems(queue.items, (item) => {
1263
+ const channel = item.originatingChannel;
1264
+ const to = item.originatingTo;
1265
+ const accountId = item.originatingAccountId;
1266
+ const threadId = item.originatingThreadId;
1267
+ if (!channel && !to && !accountId && threadId == null) return {};
1268
+ if (!isRoutableChannel(channel) || !to) return { cross: true };
1269
+ return { key: [
1270
+ channel,
1271
+ to,
1272
+ accountId || "",
1273
+ threadId != null ? String(threadId) : ""
1274
+ ].join("|") };
1275
+ })) {
1276
+ forceIndividualCollect = true;
1277
+ const next = queue.items[0];
1278
+ if (!next) break;
1279
+ await runFollowup(next);
1280
+ queue.items.shift();
1281
+ continue;
1282
+ }
1283
+ const items = queue.items.slice();
1284
+ const summary = previewQueueSummaryPrompt$1(queue);
1285
+ const run = items.at(-1)?.run ?? queue.lastRun;
1286
+ if (!run) break;
1287
+ const originatingChannel = items.find((i) => i.originatingChannel)?.originatingChannel;
1288
+ const originatingTo = items.find((i) => i.originatingTo)?.originatingTo;
1289
+ const originatingAccountId = items.find((i) => i.originatingAccountId)?.originatingAccountId;
1290
+ const originatingThreadId = items.find((i) => i.originatingThreadId != null)?.originatingThreadId;
1291
+ await runFollowup({
1292
+ prompt: buildCollectPrompt({
1293
+ title: "[Queued messages while agent was busy]",
1294
+ items,
1295
+ summary,
1296
+ renderItem: (item, idx) => `---\nQueued #${idx + 1}\n${item.prompt}`.trim()
1297
+ }),
1298
+ run,
1299
+ enqueuedAt: Date.now(),
1300
+ originatingChannel,
1301
+ originatingTo,
1302
+ originatingAccountId,
1303
+ originatingThreadId
1304
+ });
1305
+ queue.items.splice(0, items.length);
1306
+ if (summary) clearQueueSummaryState$1(queue);
1307
+ continue;
1308
+ }
1309
+ const summaryPrompt = previewQueueSummaryPrompt$1(queue);
1310
+ if (summaryPrompt) {
1311
+ const run = queue.lastRun;
1312
+ if (!run) break;
1313
+ if (!queue.items[0]) break;
1314
+ await runFollowup({
1315
+ prompt: summaryPrompt,
1316
+ run,
1317
+ enqueuedAt: Date.now()
1318
+ });
1319
+ queue.items.shift();
1320
+ clearQueueSummaryState$1(queue);
1321
+ continue;
1322
+ }
1323
+ const next = queue.items[0];
1324
+ if (!next) break;
1325
+ await runFollowup(next);
1326
+ queue.items.shift();
1327
+ }
1328
+ } catch (err) {
1329
+ queue.lastEnqueuedAt = Date.now();
1330
+ defaultRuntime.error?.(`followup queue drain failed for ${key}: ${String(err)}`);
1331
+ } finally {
1332
+ queue.draining = false;
1333
+ if (queue.items.length === 0 && queue.droppedCount === 0) FOLLOWUP_QUEUES.delete(key);
1334
+ else scheduleFollowupDrain(key, runFollowup);
1335
+ }
1336
+ })();
1337
+ }
1338
+
1339
+ //#endregion
1340
+ //#region src/auto-reply/reply/queue/enqueue.ts
1341
+ function isRunAlreadyQueued(run, items, allowPromptFallback = false) {
1342
+ const hasSameRouting = (item) => item.originatingChannel === run.originatingChannel && item.originatingTo === run.originatingTo && item.originatingAccountId === run.originatingAccountId && item.originatingThreadId === run.originatingThreadId;
1343
+ const messageId = run.messageId?.trim();
1344
+ if (messageId) return items.some((item) => item.messageId?.trim() === messageId && hasSameRouting(item));
1345
+ if (!allowPromptFallback) return false;
1346
+ return items.some((item) => item.prompt === run.prompt && hasSameRouting(item));
1347
+ }
1348
+ function enqueueFollowupRun(key, run, settings, dedupeMode = "message-id") {
1349
+ const queue = getFollowupQueue(key, settings);
1350
+ const dedupe = dedupeMode === "none" ? void 0 : (item, items) => isRunAlreadyQueued(item, items, dedupeMode === "prompt");
1351
+ if (shouldSkipQueueItem({
1352
+ item: run,
1353
+ items: queue.items,
1354
+ dedupe
1355
+ })) return false;
1356
+ queue.lastEnqueuedAt = Date.now();
1357
+ queue.lastRun = run.run;
1358
+ if (!applyQueueDropPolicy({
1359
+ queue,
1360
+ summarize: (item) => item.summaryLine?.trim() || item.prompt.trim()
1361
+ })) return false;
1362
+ queue.items.push(run);
1363
+ return true;
1364
+ }
1365
+ function getFollowupQueueDepth(key) {
1366
+ const cleaned = key.trim();
1367
+ if (!cleaned) return 0;
1368
+ const queue = FOLLOWUP_QUEUES.get(cleaned);
1369
+ if (!queue) return 0;
1370
+ return queue.items.length;
1371
+ }
1372
+
1373
+ //#endregion
1374
+ //#region src/auto-reply/reply/queue/settings.ts
1375
+ function defaultQueueModeForChannel(_channel) {
1376
+ return "collect";
1377
+ }
1378
+ /** Resolve per-channel debounce override from debounceMsByChannel map. */
1379
+ function resolveChannelDebounce(byChannel, channelKey) {
1380
+ if (!channelKey || !byChannel) return;
1381
+ const value = byChannel[channelKey];
1382
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
1383
+ }
1384
+ function resolvePluginDebounce(channelKey) {
1385
+ if (!channelKey) return;
1386
+ const value = getChannelPlugin(channelKey)?.defaults?.queue?.debounceMs;
1387
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
1388
+ }
1389
+ function resolveQueueSettings(params) {
1390
+ const channelKey = params.channel?.trim().toLowerCase();
1391
+ const queueCfg = params.cfg.messages?.queue;
1392
+ const providerModeRaw = channelKey && queueCfg?.byChannel ? queueCfg.byChannel[channelKey] : void 0;
1393
+ const resolvedMode = params.inlineMode ?? normalizeQueueMode(params.sessionEntry?.queueMode) ?? normalizeQueueMode(providerModeRaw) ?? normalizeQueueMode(queueCfg?.mode) ?? defaultQueueModeForChannel(channelKey);
1394
+ const debounceRaw = params.inlineOptions?.debounceMs ?? params.sessionEntry?.queueDebounceMs ?? resolveChannelDebounce(queueCfg?.debounceMsByChannel, channelKey) ?? resolvePluginDebounce(channelKey) ?? queueCfg?.debounceMs ?? DEFAULT_QUEUE_DEBOUNCE_MS;
1395
+ const capRaw = params.inlineOptions?.cap ?? params.sessionEntry?.queueCap ?? queueCfg?.cap ?? DEFAULT_QUEUE_CAP;
1396
+ const dropRaw = params.inlineOptions?.dropPolicy ?? params.sessionEntry?.queueDrop ?? normalizeQueueDropPolicy(queueCfg?.drop) ?? DEFAULT_QUEUE_DROP;
1397
+ return {
1398
+ mode: resolvedMode,
1399
+ debounceMs: typeof debounceRaw === "number" ? Math.max(0, debounceRaw) : void 0,
1400
+ cap: typeof capRaw === "number" ? Math.max(1, Math.floor(capRaw)) : void 0,
1401
+ dropPolicy: dropRaw
1402
+ };
1403
+ }
1404
+
1405
+ //#endregion
1406
+ //#region src/agents/subagent-announce-queue.ts
1407
+ const ANNOUNCE_QUEUES = /* @__PURE__ */ new Map();
1408
+ function previewQueueSummaryPrompt(queue) {
1409
+ return buildQueueSummaryPrompt({
1410
+ state: {
1411
+ dropPolicy: queue.dropPolicy,
1412
+ droppedCount: queue.droppedCount,
1413
+ summaryLines: [...queue.summaryLines]
1414
+ },
1415
+ noun: "announce"
1416
+ });
1417
+ }
1418
+ function clearQueueSummaryState(queue) {
1419
+ queue.droppedCount = 0;
1420
+ queue.summaryLines = [];
1421
+ }
1422
+ function getAnnounceQueue(key, settings, send) {
1423
+ const existing = ANNOUNCE_QUEUES.get(key);
1424
+ if (existing) {
1425
+ existing.mode = settings.mode;
1426
+ existing.debounceMs = typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : existing.debounceMs;
1427
+ existing.cap = typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : existing.cap;
1428
+ existing.dropPolicy = settings.dropPolicy ?? existing.dropPolicy;
1429
+ existing.send = send;
1430
+ return existing;
1431
+ }
1432
+ const created = {
1433
+ items: [],
1434
+ draining: false,
1435
+ lastEnqueuedAt: 0,
1436
+ mode: settings.mode,
1437
+ debounceMs: typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : 1e3,
1438
+ cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : 20,
1439
+ dropPolicy: settings.dropPolicy ?? "summarize",
1440
+ droppedCount: 0,
1441
+ summaryLines: [],
1442
+ send
1443
+ };
1444
+ ANNOUNCE_QUEUES.set(key, created);
1445
+ return created;
1446
+ }
1447
+ function scheduleAnnounceDrain(key) {
1448
+ const queue = ANNOUNCE_QUEUES.get(key);
1449
+ if (!queue || queue.draining) return;
1450
+ queue.draining = true;
1451
+ (async () => {
1452
+ try {
1453
+ let forceIndividualCollect = false;
1454
+ while (queue.items.length > 0 || queue.droppedCount > 0) {
1455
+ await waitForQueueDebounce(queue);
1456
+ if (queue.mode === "collect") {
1457
+ if (forceIndividualCollect) {
1458
+ const next = queue.items[0];
1459
+ if (!next) break;
1460
+ await queue.send(next);
1461
+ queue.items.shift();
1462
+ continue;
1463
+ }
1464
+ if (hasCrossChannelItems(queue.items, (item) => {
1465
+ if (!item.origin) return {};
1466
+ if (!item.originKey) return { cross: true };
1467
+ return { key: item.originKey };
1468
+ })) {
1469
+ forceIndividualCollect = true;
1470
+ const next = queue.items[0];
1471
+ if (!next) break;
1472
+ await queue.send(next);
1473
+ queue.items.shift();
1474
+ continue;
1475
+ }
1476
+ const items = queue.items.slice();
1477
+ const summary = previewQueueSummaryPrompt(queue);
1478
+ const prompt = buildCollectPrompt({
1479
+ title: "[Queued announce messages while agent was busy]",
1480
+ items,
1481
+ summary,
1482
+ renderItem: (item, idx) => `---\nQueued #${idx + 1}\n${item.prompt}`.trim()
1483
+ });
1484
+ const last = items.at(-1);
1485
+ if (!last) break;
1486
+ await queue.send({
1487
+ ...last,
1488
+ prompt
1489
+ });
1490
+ queue.items.splice(0, items.length);
1491
+ if (summary) clearQueueSummaryState(queue);
1492
+ continue;
1493
+ }
1494
+ const summaryPrompt = previewQueueSummaryPrompt(queue);
1495
+ if (summaryPrompt) {
1496
+ const next = queue.items[0];
1497
+ if (!next) break;
1498
+ await queue.send({
1499
+ ...next,
1500
+ prompt: summaryPrompt
1501
+ });
1502
+ queue.items.shift();
1503
+ clearQueueSummaryState(queue);
1504
+ continue;
1505
+ }
1506
+ const next = queue.items[0];
1507
+ if (!next) break;
1508
+ await queue.send(next);
1509
+ queue.items.shift();
1510
+ }
1511
+ } catch (err) {
1512
+ queue.lastEnqueuedAt = Date.now();
1513
+ defaultRuntime.error?.(`announce queue drain failed for ${key}: ${String(err)}`);
1514
+ } finally {
1515
+ queue.draining = false;
1516
+ if (queue.items.length === 0 && queue.droppedCount === 0) ANNOUNCE_QUEUES.delete(key);
1517
+ else scheduleAnnounceDrain(key);
1518
+ }
1519
+ })();
1520
+ }
1521
+ function enqueueAnnounce(params) {
1522
+ const queue = getAnnounceQueue(params.key, params.settings, params.send);
1523
+ queue.lastEnqueuedAt = Date.now();
1524
+ if (!applyQueueDropPolicy({
1525
+ queue,
1526
+ summarize: (item) => item.summaryLine?.trim() || item.prompt.trim()
1527
+ })) {
1528
+ if (queue.dropPolicy === "new") scheduleAnnounceDrain(params.key);
1529
+ return false;
1530
+ }
1531
+ const origin = normalizeDeliveryContext(params.item.origin);
1532
+ const originKey = deliveryContextKey(origin);
1533
+ queue.items.push({
1534
+ ...params.item,
1535
+ origin,
1536
+ originKey
1537
+ });
1538
+ scheduleAnnounceDrain(params.key);
1539
+ return true;
1540
+ }
1541
+
1542
+ //#endregion
1543
+ //#region src/agents/subagent-depth.ts
1544
+ function normalizeSpawnDepth(value) {
1545
+ if (typeof value === "number") return Number.isInteger(value) && value >= 0 ? value : void 0;
1546
+ if (typeof value === "string") {
1547
+ const trimmed = value.trim();
1548
+ if (!trimmed) return;
1549
+ const numeric = Number(trimmed);
1550
+ return Number.isInteger(numeric) && numeric >= 0 ? numeric : void 0;
1551
+ }
1552
+ }
1553
+ function normalizeSessionKey(value) {
1554
+ if (typeof value !== "string") return;
1555
+ return value.trim() || void 0;
1556
+ }
1557
+ function readSessionStore(storePath) {
1558
+ try {
1559
+ const raw = fs.readFileSync(storePath, "utf-8");
1560
+ const parsed = JSON5.parse(raw);
1561
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1562
+ } catch {}
1563
+ return {};
1564
+ }
1565
+ function buildKeyCandidates(rawKey, cfg) {
1566
+ if (!cfg) return [rawKey];
1567
+ if (rawKey === "global" || rawKey === "unknown") return [rawKey];
1568
+ if (parseAgentSessionKey(rawKey)) return [rawKey];
1569
+ const prefixed = `agent:${resolveDefaultAgentId(cfg)}:${rawKey}`;
1570
+ return prefixed === rawKey ? [rawKey] : [rawKey, prefixed];
1571
+ }
1572
+ function findEntryBySessionId(store, sessionId) {
1573
+ const normalizedSessionId = normalizeSessionKey(sessionId);
1574
+ if (!normalizedSessionId) return;
1575
+ for (const entry of Object.values(store)) {
1576
+ const candidateSessionId = normalizeSessionKey(entry?.sessionId);
1577
+ if (candidateSessionId && candidateSessionId === normalizedSessionId) return entry;
1578
+ }
1579
+ }
1580
+ function resolveEntryForSessionKey(params) {
1581
+ const candidates = buildKeyCandidates(params.sessionKey, params.cfg);
1582
+ if (params.store) {
1583
+ for (const key of candidates) {
1584
+ const entry = params.store[key];
1585
+ if (entry) return entry;
1586
+ }
1587
+ return findEntryBySessionId(params.store, params.sessionKey);
1588
+ }
1589
+ if (!params.cfg) return;
1590
+ for (const key of candidates) {
1591
+ const parsed = parseAgentSessionKey(key);
1592
+ if (!parsed?.agentId) continue;
1593
+ const storePath = resolveStorePath(params.cfg.session?.store, { agentId: parsed.agentId });
1594
+ let store = params.cache.get(storePath);
1595
+ if (!store) {
1596
+ store = readSessionStore(storePath);
1597
+ params.cache.set(storePath, store);
1598
+ }
1599
+ const entry = store[key] ?? findEntryBySessionId(store, params.sessionKey);
1600
+ if (entry) return entry;
1601
+ }
1602
+ }
1603
+ function getSubagentDepthFromSessionStore(sessionKey, opts) {
1604
+ const raw = (sessionKey ?? "").trim();
1605
+ const fallbackDepth = getSubagentDepth(raw);
1606
+ if (!raw) return fallbackDepth;
1607
+ const cache = /* @__PURE__ */ new Map();
1608
+ const visited = /* @__PURE__ */ new Set();
1609
+ const depthFromStore = (key) => {
1610
+ const normalizedKey = normalizeSessionKey(key);
1611
+ if (!normalizedKey) return;
1612
+ if (visited.has(normalizedKey)) return;
1613
+ visited.add(normalizedKey);
1614
+ const entry = resolveEntryForSessionKey({
1615
+ sessionKey: normalizedKey,
1616
+ cfg: opts?.cfg,
1617
+ store: opts?.store,
1618
+ cache
1619
+ });
1620
+ const storedDepth = normalizeSpawnDepth(entry?.spawnDepth);
1621
+ if (storedDepth !== void 0) return storedDepth;
1622
+ const spawnedBy = normalizeSessionKey(entry?.spawnedBy);
1623
+ if (!spawnedBy) return;
1624
+ const parentDepth = depthFromStore(spawnedBy);
1625
+ if (parentDepth !== void 0) return parentDepth + 1;
1626
+ return getSubagentDepth(spawnedBy) + 1;
1627
+ };
1628
+ return depthFromStore(raw) ?? fallbackDepth;
1629
+ }
1630
+
1631
+ //#endregion
1632
+ //#region src/agents/tools/sessions-helpers.ts
1633
+ function normalizeKey(value) {
1634
+ const trimmed = value?.trim();
1635
+ return trimmed ? trimmed : void 0;
1636
+ }
1637
+ function resolveMainSessionAlias(cfg) {
1638
+ const mainKey = normalizeMainKey(cfg.session?.mainKey);
1639
+ const scope = cfg.session?.scope ?? "per-sender";
1640
+ return {
1641
+ mainKey,
1642
+ alias: scope === "global" ? "global" : mainKey,
1643
+ scope
1644
+ };
1645
+ }
1646
+ function resolveDisplaySessionKey(params) {
1647
+ if (params.key === params.alias) return "main";
1648
+ if (params.key === params.mainKey) return "main";
1649
+ return params.key;
1650
+ }
1651
+ function resolveInternalSessionKey(params) {
1652
+ if (params.key === "main") return params.alias;
1653
+ return params.key;
1654
+ }
1655
+ function createAgentToAgentPolicy(cfg) {
1656
+ const routingA2A = cfg.tools?.agentToAgent;
1657
+ const enabled = routingA2A?.enabled === true;
1658
+ const allowPatterns = Array.isArray(routingA2A?.allow) ? routingA2A.allow : [];
1659
+ const matchesAllow = (agentId) => {
1660
+ if (allowPatterns.length === 0) return true;
1661
+ return allowPatterns.some((pattern) => {
1662
+ const raw = String(pattern ?? "").trim();
1663
+ if (!raw) return false;
1664
+ if (raw === "*") return true;
1665
+ if (!raw.includes("*")) return raw === agentId;
1666
+ const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1667
+ return new RegExp(`^${escaped.replaceAll("\\*", ".*")}$`, "i").test(agentId);
1668
+ });
1669
+ };
1670
+ const isAllowed = (requesterAgentId, targetAgentId) => {
1671
+ if (requesterAgentId === targetAgentId) return true;
1672
+ if (!enabled) return false;
1673
+ return matchesAllow(requesterAgentId) && matchesAllow(targetAgentId);
1674
+ };
1675
+ return {
1676
+ enabled,
1677
+ matchesAllow,
1678
+ isAllowed
1679
+ };
1680
+ }
1681
+ 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;
1682
+ function looksLikeSessionId(value) {
1683
+ return SESSION_ID_RE.test(value.trim());
1684
+ }
1685
+ function looksLikeSessionKey(value) {
1686
+ const raw = value.trim();
1687
+ if (!raw) return false;
1688
+ if (raw === "main" || raw === "global" || raw === "unknown") return true;
1689
+ if (isAcpSessionKey(raw)) return true;
1690
+ if (raw.startsWith("agent:")) return true;
1691
+ if (raw.startsWith("cron:") || raw.startsWith("hook:")) return true;
1692
+ if (raw.startsWith("node-") || raw.startsWith("node:")) return true;
1693
+ if (raw.includes(":group:") || raw.includes(":channel:")) return true;
1694
+ return false;
1695
+ }
1696
+ function shouldResolveSessionIdInput(value) {
1697
+ return looksLikeSessionId(value) || !looksLikeSessionKey(value);
1698
+ }
1699
+ async function resolveSessionKeyFromSessionId(params) {
1700
+ try {
1701
+ const result = await callGateway({
1702
+ method: "sessions.resolve",
1703
+ params: {
1704
+ sessionId: params.sessionId,
1705
+ spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0,
1706
+ includeGlobal: !params.restrictToSpawned,
1707
+ includeUnknown: !params.restrictToSpawned
1708
+ }
1709
+ });
1710
+ const key = typeof result?.key === "string" ? result.key.trim() : "";
1711
+ if (!key) throw new Error(`Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`);
1712
+ return {
1713
+ ok: true,
1714
+ key,
1715
+ displayKey: resolveDisplaySessionKey({
1716
+ key,
1717
+ alias: params.alias,
1718
+ mainKey: params.mainKey
1719
+ }),
1720
+ resolvedViaSessionId: true
1721
+ };
1722
+ } catch (err) {
1723
+ if (params.restrictToSpawned) return {
1724
+ ok: false,
1725
+ status: "forbidden",
1726
+ error: `Session not visible from this sandboxed agent session: ${params.sessionId}`
1727
+ };
1728
+ return {
1729
+ ok: false,
1730
+ status: "error",
1731
+ error: (err instanceof Error ? err.message : String(err)) || `Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`
1732
+ };
1733
+ }
1734
+ }
1735
+ async function resolveSessionKeyFromKey(params) {
1736
+ try {
1737
+ const result = await callGateway({
1738
+ method: "sessions.resolve",
1739
+ params: {
1740
+ key: params.key,
1741
+ spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0
1742
+ }
1743
+ });
1744
+ const key = typeof result?.key === "string" ? result.key.trim() : "";
1745
+ if (!key) return null;
1746
+ return {
1747
+ ok: true,
1748
+ key,
1749
+ displayKey: resolveDisplaySessionKey({
1750
+ key,
1751
+ alias: params.alias,
1752
+ mainKey: params.mainKey
1753
+ }),
1754
+ resolvedViaSessionId: false
1755
+ };
1756
+ } catch {
1757
+ return null;
1758
+ }
1759
+ }
1760
+ async function resolveSessionReference(params) {
1761
+ const raw = params.sessionKey.trim();
1762
+ if (shouldResolveSessionIdInput(raw)) {
1763
+ const resolvedByKey = await resolveSessionKeyFromKey({
1764
+ key: raw,
1765
+ alias: params.alias,
1766
+ mainKey: params.mainKey,
1767
+ requesterInternalKey: params.requesterInternalKey,
1768
+ restrictToSpawned: params.restrictToSpawned
1769
+ });
1770
+ if (resolvedByKey) return resolvedByKey;
1771
+ return await resolveSessionKeyFromSessionId({
1772
+ sessionId: raw,
1773
+ alias: params.alias,
1774
+ mainKey: params.mainKey,
1775
+ requesterInternalKey: params.requesterInternalKey,
1776
+ restrictToSpawned: params.restrictToSpawned
1777
+ });
1778
+ }
1779
+ const resolvedKey = resolveInternalSessionKey({
1780
+ key: raw,
1781
+ alias: params.alias,
1782
+ mainKey: params.mainKey
1783
+ });
1784
+ return {
1785
+ ok: true,
1786
+ key: resolvedKey,
1787
+ displayKey: resolveDisplaySessionKey({
1788
+ key: resolvedKey,
1789
+ alias: params.alias,
1790
+ mainKey: params.mainKey
1791
+ }),
1792
+ resolvedViaSessionId: false
1793
+ };
1794
+ }
1795
+ function classifySessionKind(params) {
1796
+ const key = params.key;
1797
+ if (key === params.alias || key === params.mainKey) return "main";
1798
+ if (key.startsWith("cron:")) return "cron";
1799
+ if (key.startsWith("hook:")) return "hook";
1800
+ if (key.startsWith("node-") || key.startsWith("node:")) return "node";
1801
+ if (params.gatewayKind === "group") return "group";
1802
+ if (key.includes(":group:") || key.includes(":channel:")) return "group";
1803
+ return "other";
1804
+ }
1805
+ function deriveChannel(params) {
1806
+ if (params.kind === "cron" || params.kind === "hook" || params.kind === "node") return "internal";
1807
+ const channel = normalizeKey(params.channel ?? void 0);
1808
+ if (channel) return channel;
1809
+ const lastChannel = normalizeKey(params.lastChannel ?? void 0);
1810
+ if (lastChannel) return lastChannel;
1811
+ const parts = params.key.split(":").filter(Boolean);
1812
+ if (parts.length >= 3 && (parts[1] === "group" || parts[1] === "channel")) return parts[0];
1813
+ return "unknown";
1814
+ }
1815
+ function stripToolMessages(messages) {
1816
+ return messages.filter((msg) => {
1817
+ if (!msg || typeof msg !== "object") return true;
1818
+ return msg.role !== "toolResult";
1819
+ });
1820
+ }
1821
+ /**
1822
+ * Sanitize text content to strip tool call markers and thinking tags.
1823
+ * This ensures user-facing text doesn't leak internal tool representations.
1824
+ */
1825
+ function sanitizeTextContent(text) {
1826
+ if (!text) return text;
1827
+ return stripThinkingTagsFromText(stripDowngradedToolCallText(stripMinimaxToolCallXml(text)));
1828
+ }
1829
+ function extractAssistantText(message) {
1830
+ if (!message || typeof message !== "object") return;
1831
+ if (message.role !== "assistant") return;
1832
+ const content = message.content;
1833
+ if (!Array.isArray(content)) return;
1834
+ const chunks = [];
1835
+ for (const block of content) {
1836
+ if (!block || typeof block !== "object") continue;
1837
+ if (block.type !== "text") continue;
1838
+ const text = block.text;
1839
+ if (typeof text === "string") {
1840
+ const sanitized = sanitizeTextContent(text);
1841
+ if (sanitized.trim()) chunks.push(sanitized);
1842
+ }
1843
+ }
1844
+ const joined = chunks.join("").trim();
1845
+ const stopReason = message.stopReason;
1846
+ const errorMessage = message.errorMessage;
1847
+ const errorContext = stopReason === "error" || typeof errorMessage === "string" && Boolean(errorMessage.trim());
1848
+ return joined ? sanitizeUserFacingText(joined, { errorContext }) : void 0;
1849
+ }
1850
+
1851
+ //#endregion
1852
+ //#region src/agents/tools/agent-step.ts
1853
+ async function readLatestAssistantReply(params) {
1854
+ const history = await callGateway({
1855
+ method: "chat.history",
1856
+ params: {
1857
+ sessionKey: params.sessionKey,
1858
+ limit: params.limit ?? 50
1859
+ }
1860
+ });
1861
+ const filtered = stripToolMessages(Array.isArray(history?.messages) ? history.messages : []);
1862
+ for (let i = filtered.length - 1; i >= 0; i -= 1) {
1863
+ const candidate = filtered[i];
1864
+ if (!candidate || typeof candidate !== "object") continue;
1865
+ if (candidate.role !== "assistant") continue;
1866
+ const text = extractAssistantText(candidate);
1867
+ if (!text?.trim()) continue;
1868
+ return text;
1869
+ }
1870
+ }
1871
+ async function runAgentStep(params) {
1872
+ const stepIdem = crypto.randomUUID();
1873
+ const response = await callGateway({
1874
+ method: "agent",
1875
+ params: {
1876
+ message: params.message,
1877
+ sessionKey: params.sessionKey,
1878
+ idempotencyKey: stepIdem,
1879
+ deliver: false,
1880
+ channel: params.channel ?? INTERNAL_MESSAGE_CHANNEL,
1881
+ lane: params.lane ?? AGENT_LANE_NESTED,
1882
+ extraSystemPrompt: params.extraSystemPrompt,
1883
+ inputProvenance: {
1884
+ kind: "inter_session",
1885
+ sourceSessionKey: params.sourceSessionKey,
1886
+ sourceChannel: params.sourceChannel,
1887
+ sourceTool: params.sourceTool ?? "sessions_send"
1888
+ }
1889
+ },
1890
+ timeoutMs: 1e4
1891
+ });
1892
+ const resolvedRunId = (typeof response?.runId === "string" && response.runId ? response.runId : "") || stepIdem;
1893
+ const stepWaitMs = Math.min(params.timeoutMs, 6e4);
1894
+ if ((await callGateway({
1895
+ method: "agent.wait",
1896
+ params: {
1897
+ runId: resolvedRunId,
1898
+ timeoutMs: stepWaitMs
1899
+ },
1900
+ timeoutMs: stepWaitMs + 2e3
1901
+ }))?.status !== "ok") return;
1902
+ return await readLatestAssistantReply({ sessionKey: params.sessionKey });
1903
+ }
1904
+
1905
+ //#endregion
1906
+ //#region src/agents/subagent-announce.ts
1907
+ function formatDurationShort(valueMs) {
1908
+ if (!valueMs || !Number.isFinite(valueMs) || valueMs <= 0) return "n/a";
1909
+ const totalSeconds = Math.round(valueMs / 1e3);
1910
+ const hours = Math.floor(totalSeconds / 3600);
1911
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
1912
+ const seconds = totalSeconds % 60;
1913
+ if (hours > 0) return `${hours}h${minutes}m`;
1914
+ if (minutes > 0) return `${minutes}m${seconds}s`;
1915
+ return `${seconds}s`;
1916
+ }
1917
+ function formatTokenCount(value) {
1918
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return "0";
1919
+ if (value >= 1e6) return `${(value / 1e6).toFixed(1)}m`;
1920
+ if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
1921
+ return String(Math.round(value));
1922
+ }
1923
+ async function buildCompactAnnounceStatsLine(params) {
1924
+ const cfg = loadConfig();
1925
+ const agentId = resolveAgentIdFromSessionKey(params.sessionKey);
1926
+ const storePath = resolveStorePath(cfg.session?.store, { agentId });
1927
+ let entry = loadSessionStore(storePath)[params.sessionKey];
1928
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1929
+ if (typeof entry?.inputTokens === "number" || typeof entry?.outputTokens === "number" || typeof entry?.totalTokens === "number") break;
1930
+ await new Promise((resolve) => setTimeout(resolve, 150));
1931
+ entry = loadSessionStore(storePath)[params.sessionKey];
1932
+ }
1933
+ const input = typeof entry?.inputTokens === "number" ? entry.inputTokens : 0;
1934
+ const output = typeof entry?.outputTokens === "number" ? entry.outputTokens : 0;
1935
+ const ioTotal = input + output;
1936
+ const promptCache = typeof entry?.totalTokens === "number" ? entry.totalTokens : void 0;
1937
+ 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)})`];
1938
+ if (typeof promptCache === "number" && promptCache > ioTotal) parts.push(`prompt/cache ${formatTokenCount(promptCache)}`);
1939
+ return `Stats: ${parts.join(" • ")}`;
1940
+ }
1941
+ function resolveAnnounceOrigin(entry, requesterOrigin) {
1942
+ return mergeDeliveryContext(requesterOrigin, deliveryContextFromSession(entry));
1943
+ }
1944
+ async function sendAnnounce(item) {
1945
+ const requesterIsSubagent = getSubagentDepthFromSessionStore(item.sessionKey) >= 1;
1946
+ const origin = item.origin;
1947
+ const threadId = origin?.threadId != null && origin.threadId !== "" ? String(origin.threadId) : void 0;
1948
+ await callGateway({
1949
+ method: "agent",
1950
+ params: {
1951
+ sessionKey: item.sessionKey,
1952
+ message: item.prompt,
1953
+ channel: requesterIsSubagent ? void 0 : origin?.channel,
1954
+ accountId: requesterIsSubagent ? void 0 : origin?.accountId,
1955
+ to: requesterIsSubagent ? void 0 : origin?.to,
1956
+ threadId: requesterIsSubagent ? void 0 : threadId,
1957
+ deliver: !requesterIsSubagent,
1958
+ idempotencyKey: crypto.randomUUID()
1959
+ },
1960
+ timeoutMs: 15e3
1961
+ });
1962
+ }
1963
+ function resolveRequesterStoreKey(cfg, requesterSessionKey) {
1964
+ const raw = requesterSessionKey.trim();
1965
+ if (!raw) return raw;
1966
+ if (raw === "global" || raw === "unknown") return raw;
1967
+ if (raw.startsWith("agent:")) return raw;
1968
+ const mainKey = normalizeMainKey(cfg.session?.mainKey);
1969
+ if (raw === "main" || raw === mainKey) return resolveMainSessionKey(cfg);
1970
+ return `agent:${resolveAgentIdFromSessionKey(raw)}:${raw}`;
1971
+ }
1972
+ function loadRequesterSessionEntry(requesterSessionKey) {
1973
+ const cfg = loadConfig();
1974
+ const canonicalKey = resolveRequesterStoreKey(cfg, requesterSessionKey);
1975
+ const agentId = resolveAgentIdFromSessionKey(canonicalKey);
1976
+ return {
1977
+ cfg,
1978
+ entry: loadSessionStore(resolveStorePath(cfg.session?.store, { agentId }))[canonicalKey],
1979
+ canonicalKey
1980
+ };
1981
+ }
1982
+ async function maybeQueueSubagentAnnounce(params) {
1983
+ const { cfg, entry } = loadRequesterSessionEntry(params.requesterSessionKey);
1984
+ const canonicalKey = resolveRequesterStoreKey(cfg, params.requesterSessionKey);
1985
+ const sessionId = entry?.sessionId;
1986
+ if (!sessionId) return "none";
1987
+ const queueSettings = resolveQueueSettings({
1988
+ cfg,
1989
+ channel: entry?.channel ?? entry?.lastChannel,
1990
+ sessionEntry: entry
1991
+ });
1992
+ const isActive = isEmbeddedPiRunActive(sessionId);
1993
+ if (queueSettings.mode === "steer" || queueSettings.mode === "steer-backlog") {
1994
+ if (/* @__PURE__ */ queueEmbeddedPiMessage(sessionId, params.triggerMessage)) return "steered";
1995
+ }
1996
+ const shouldFollowup = queueSettings.mode === "followup" || queueSettings.mode === "collect" || queueSettings.mode === "steer-backlog" || queueSettings.mode === "interrupt";
1997
+ if (isActive && (shouldFollowup || queueSettings.mode === "steer")) {
1998
+ const origin = resolveAnnounceOrigin(entry, params.requesterOrigin);
1999
+ enqueueAnnounce({
2000
+ key: canonicalKey,
2001
+ item: {
2002
+ prompt: params.triggerMessage,
2003
+ summaryLine: params.summaryLine,
2004
+ enqueuedAt: Date.now(),
2005
+ sessionKey: canonicalKey,
2006
+ origin
2007
+ },
2008
+ settings: queueSettings,
2009
+ send: sendAnnounce
2010
+ });
2011
+ return "queued";
2012
+ }
2013
+ return "none";
2014
+ }
2015
+ function loadSessionEntryByKey(sessionKey) {
2016
+ const cfg = loadConfig();
2017
+ const agentId = resolveAgentIdFromSessionKey(sessionKey);
2018
+ return loadSessionStore(resolveStorePath(cfg.session?.store, { agentId }))[sessionKey];
2019
+ }
2020
+ async function readLatestAssistantReplyWithRetry(params) {
2021
+ const RETRY_INTERVAL_MS = 100;
2022
+ let reply = params.initialReply?.trim() ? params.initialReply : void 0;
2023
+ if (reply) return reply;
2024
+ const deadline = Date.now() + Math.max(0, Math.min(params.maxWaitMs, 15e3));
2025
+ while (Date.now() < deadline) {
2026
+ await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL_MS));
2027
+ const latest = await readLatestAssistantReply({ sessionKey: params.sessionKey });
2028
+ if (latest?.trim()) return latest;
2029
+ }
2030
+ return reply;
2031
+ }
2032
+ function buildSubagentSystemPrompt(params) {
2033
+ const taskText = typeof params.task === "string" && params.task.trim() ? params.task.replace(/\s+/g, " ").trim() : "{{TASK_DESCRIPTION}}";
2034
+ const childDepth = typeof params.childDepth === "number" ? params.childDepth : 1;
2035
+ const canSpawn = childDepth < (typeof params.maxSpawnDepth === "number" ? params.maxSpawnDepth : 1);
2036
+ const parentLabel = childDepth >= 2 ? "parent orchestrator" : "main agent";
2037
+ const lines = [
2038
+ "# Subagent Context",
2039
+ "",
2040
+ `You are a **subagent** spawned by the ${parentLabel} for a specific task.`,
2041
+ "",
2042
+ "## Your Role",
2043
+ `- You were created to handle: ${taskText}`,
2044
+ "- Complete this task. That's your entire purpose.",
2045
+ `- You are NOT the ${parentLabel}. Don't try to be.`,
2046
+ "",
2047
+ "## Rules",
2048
+ "1. **Stay focused** - Do your assigned task, nothing else",
2049
+ `2. **Complete the task** - Your final message will be automatically reported to the ${parentLabel}`,
2050
+ "3. **Don't initiate** - No heartbeats, no proactive actions, no side quests",
2051
+ "4. **Be ephemeral** - You may be terminated after task completion. That's fine.",
2052
+ "5. **Trust push-based completion** - Descendant results are auto-announced back to you; do not busy-poll for status.",
2053
+ "",
2054
+ "## Output Format",
2055
+ "When complete, your final response should include:",
2056
+ `- What you accomplished or found`,
2057
+ `- Any relevant details the ${parentLabel} should know`,
2058
+ "- Keep it concise but informative",
2059
+ "",
2060
+ "## What You DON'T Do",
2061
+ `- NO user conversations (that's ${parentLabel}'s job)`,
2062
+ "- NO external messages (email, tweets, etc.) unless explicitly tasked with a specific recipient/channel",
2063
+ "- NO cron jobs or persistent state",
2064
+ `- NO pretending to be the ${parentLabel}`,
2065
+ `- Only use the \`message\` tool when explicitly instructed to contact a specific external recipient; otherwise return plain text and let the ${parentLabel} deliver it`,
2066
+ ""
2067
+ ];
2068
+ 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.", "");
2069
+ 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.", "");
2070
+ lines.push("## Session Context", ...[
2071
+ params.label ? `- Label: ${params.label}` : void 0,
2072
+ params.requesterSessionKey ? `- Requester session: ${params.requesterSessionKey}.` : void 0,
2073
+ params.requesterOrigin?.channel ? `- Requester channel: ${params.requesterOrigin.channel}.` : void 0,
2074
+ `- Your session: ${params.childSessionKey}.`
2075
+ ].filter((line) => line !== void 0), "");
2076
+ return lines.join("\n");
2077
+ }
2078
+ function buildAnnounceReplyInstruction(params) {
2079
+ if (params.remainingActiveSubagentRuns > 0) {
2080
+ const activeRunsLabel = params.remainingActiveSubagentRuns === 1 ? "run" : "runs";
2081
+ 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.`;
2082
+ }
2083
+ 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: NO_REPLY.";
2084
+ 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: NO_REPLY if this exact result was already delivered to the user in this same turn.`;
2085
+ }
2086
+ async function runSubagentAnnounceFlow(params) {
2087
+ let didAnnounce = false;
2088
+ let shouldDeleteChildSession = params.cleanup === "delete";
2089
+ try {
2090
+ let targetRequesterSessionKey = params.requesterSessionKey;
2091
+ let targetRequesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
2092
+ const childSessionId = (() => {
2093
+ const entry = loadSessionEntryByKey(params.childSessionKey);
2094
+ return typeof entry?.sessionId === "string" && entry.sessionId.trim() ? entry.sessionId.trim() : void 0;
2095
+ })();
2096
+ const settleTimeoutMs = Math.min(Math.max(params.timeoutMs, 1), 12e4);
2097
+ let reply = params.roundOneReply;
2098
+ let outcome = params.outcome;
2099
+ if (childSessionId && isEmbeddedPiRunActive(childSessionId)) {
2100
+ if (!await /* @__PURE__ */ waitForEmbeddedPiRunEnd(childSessionId, settleTimeoutMs) && isEmbeddedPiRunActive(childSessionId)) {
2101
+ shouldDeleteChildSession = false;
2102
+ return false;
2103
+ }
2104
+ }
2105
+ if (!reply && params.waitForCompletion !== false) {
2106
+ const waitMs = settleTimeoutMs;
2107
+ const wait = await callGateway({
2108
+ method: "agent.wait",
2109
+ params: {
2110
+ runId: params.childRunId,
2111
+ timeoutMs: waitMs
2112
+ },
2113
+ timeoutMs: waitMs + 2e3
2114
+ });
2115
+ const waitError = typeof wait?.error === "string" ? wait.error : void 0;
2116
+ if (wait?.status === "timeout") outcome = { status: "timeout" };
2117
+ else if (wait?.status === "error") outcome = {
2118
+ status: "error",
2119
+ error: waitError
2120
+ };
2121
+ else if (wait?.status === "ok") outcome = { status: "ok" };
2122
+ if (typeof wait?.startedAt === "number" && !params.startedAt) params.startedAt = wait.startedAt;
2123
+ if (typeof wait?.endedAt === "number" && !params.endedAt) params.endedAt = wait.endedAt;
2124
+ if (wait?.status === "timeout") {
2125
+ if (!outcome) outcome = { status: "timeout" };
2126
+ }
2127
+ reply = await readLatestAssistantReply({ sessionKey: params.childSessionKey });
2128
+ }
2129
+ if (!reply) reply = await readLatestAssistantReply({ sessionKey: params.childSessionKey });
2130
+ if (!reply?.trim()) reply = await readLatestAssistantReplyWithRetry({
2131
+ sessionKey: params.childSessionKey,
2132
+ initialReply: reply,
2133
+ maxWaitMs: params.timeoutMs
2134
+ });
2135
+ if (!reply?.trim() && childSessionId && isEmbeddedPiRunActive(childSessionId)) {
2136
+ shouldDeleteChildSession = false;
2137
+ return false;
2138
+ }
2139
+ if (!outcome) outcome = { status: "unknown" };
2140
+ let activeChildDescendantRuns = 0;
2141
+ try {
2142
+ const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
2143
+ activeChildDescendantRuns = Math.max(0, countActiveDescendantRuns(params.childSessionKey));
2144
+ } catch {}
2145
+ if (activeChildDescendantRuns > 0) {
2146
+ shouldDeleteChildSession = false;
2147
+ return false;
2148
+ }
2149
+ const statusLabel = outcome.status === "ok" ? "completed successfully" : outcome.status === "timeout" ? "timed out" : outcome.status === "error" ? `failed: ${outcome.error || "unknown error"}` : "finished with unknown status";
2150
+ const announceType = params.announceType ?? "subagent task";
2151
+ const taskLabel = params.label || params.task || "task";
2152
+ const announceSessionId = childSessionId || "unknown";
2153
+ const findings = reply || "(no output)";
2154
+ let triggerMessage = "";
2155
+ let requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
2156
+ let requesterIsSubagent = requesterDepth >= 1;
2157
+ if (requesterIsSubagent) {
2158
+ const { isSubagentSessionRunActive, resolveRequesterForChildSession } = await Promise.resolve().then(() => subagent_registry_exports);
2159
+ if (!isSubagentSessionRunActive(targetRequesterSessionKey)) {
2160
+ const fallback = resolveRequesterForChildSession(targetRequesterSessionKey);
2161
+ if (!fallback?.requesterSessionKey) {
2162
+ shouldDeleteChildSession = false;
2163
+ return false;
2164
+ }
2165
+ targetRequesterSessionKey = fallback.requesterSessionKey;
2166
+ targetRequesterOrigin = normalizeDeliveryContext(fallback.requesterOrigin) ?? targetRequesterOrigin;
2167
+ requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
2168
+ requesterIsSubagent = requesterDepth >= 1;
2169
+ }
2170
+ }
2171
+ let remainingActiveSubagentRuns = 0;
2172
+ try {
2173
+ const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
2174
+ remainingActiveSubagentRuns = Math.max(0, countActiveDescendantRuns(targetRequesterSessionKey));
2175
+ } catch {}
2176
+ const replyInstruction = buildAnnounceReplyInstruction({
2177
+ remainingActiveSubagentRuns,
2178
+ requesterIsSubagent,
2179
+ announceType
2180
+ });
2181
+ const statsLine = await buildCompactAnnounceStatsLine({
2182
+ sessionKey: params.childSessionKey,
2183
+ startedAt: params.startedAt,
2184
+ endedAt: params.endedAt
2185
+ });
2186
+ triggerMessage = [
2187
+ `[System Message] [sessionId: ${announceSessionId}] A ${announceType} "${taskLabel}" just ${statusLabel}.`,
2188
+ "",
2189
+ "Result:",
2190
+ findings,
2191
+ "",
2192
+ statsLine,
2193
+ "",
2194
+ replyInstruction
2195
+ ].join("\n");
2196
+ const queued = await maybeQueueSubagentAnnounce({
2197
+ requesterSessionKey: targetRequesterSessionKey,
2198
+ triggerMessage,
2199
+ summaryLine: taskLabel,
2200
+ requesterOrigin: targetRequesterOrigin
2201
+ });
2202
+ if (queued === "steered") {
2203
+ didAnnounce = true;
2204
+ return true;
2205
+ }
2206
+ if (queued === "queued") {
2207
+ didAnnounce = true;
2208
+ return true;
2209
+ }
2210
+ let directOrigin = targetRequesterOrigin;
2211
+ if (!requesterIsSubagent && !directOrigin) {
2212
+ const { entry } = loadRequesterSessionEntry(targetRequesterSessionKey);
2213
+ directOrigin = deliveryContextFromSession(entry);
2214
+ }
2215
+ await callGateway({
2216
+ method: "agent",
2217
+ params: {
2218
+ sessionKey: targetRequesterSessionKey,
2219
+ message: triggerMessage,
2220
+ deliver: !requesterIsSubagent,
2221
+ channel: requesterIsSubagent ? void 0 : directOrigin?.channel,
2222
+ accountId: requesterIsSubagent ? void 0 : directOrigin?.accountId,
2223
+ to: requesterIsSubagent ? void 0 : directOrigin?.to,
2224
+ threadId: !requesterIsSubagent && directOrigin?.threadId != null && directOrigin.threadId !== "" ? String(directOrigin.threadId) : void 0,
2225
+ idempotencyKey: crypto.randomUUID()
2226
+ },
2227
+ expectFinal: true,
2228
+ timeoutMs: 15e3
2229
+ });
2230
+ didAnnounce = true;
2231
+ } catch (err) {
2232
+ defaultRuntime.error?.(`Subagent announce failed: ${String(err)}`);
2233
+ } finally {
2234
+ if (params.label) try {
2235
+ await callGateway({
2236
+ method: "sessions.patch",
2237
+ params: {
2238
+ key: params.childSessionKey,
2239
+ label: params.label
2240
+ },
2241
+ timeoutMs: 1e4
2242
+ });
2243
+ } catch {}
2244
+ if (shouldDeleteChildSession) try {
2245
+ await callGateway({
2246
+ method: "sessions.delete",
2247
+ params: {
2248
+ key: params.childSessionKey,
2249
+ deleteTranscript: true
2250
+ },
2251
+ timeoutMs: 1e4
2252
+ });
2253
+ } catch {}
2254
+ }
2255
+ return didAnnounce;
2256
+ }
2257
+
2258
+ //#endregion
2259
+ //#region src/agents/subagent-registry.store.ts
2260
+ const REGISTRY_VERSION = 2;
2261
+ function resolveSubagentStateDir(env = process.env) {
2262
+ if (env.ANIMA_STATE_DIR?.trim()) return resolveStateDir(env);
2263
+ if (env.VITEST || env.NODE_ENV === "test") return path.join(os.tmpdir(), "anima-test-state", String(process.pid));
2264
+ return resolveStateDir(env);
2265
+ }
2266
+ function resolveSubagentRegistryPath() {
2267
+ return path.join(resolveSubagentStateDir(process.env), "subagents", "runs.json");
2268
+ }
2269
+ function loadSubagentRegistryFromDisk() {
2270
+ const raw = loadJsonFile(resolveSubagentRegistryPath());
2271
+ if (!raw || typeof raw !== "object") return /* @__PURE__ */ new Map();
2272
+ const record = raw;
2273
+ if (record.version !== 1 && record.version !== 2) return /* @__PURE__ */ new Map();
2274
+ const runsRaw = record.runs;
2275
+ if (!runsRaw || typeof runsRaw !== "object") return /* @__PURE__ */ new Map();
2276
+ const out = /* @__PURE__ */ new Map();
2277
+ const isLegacy = record.version === 1;
2278
+ let migrated = false;
2279
+ for (const [runId, entry] of Object.entries(runsRaw)) {
2280
+ if (!entry || typeof entry !== "object") continue;
2281
+ const typed = entry;
2282
+ if (!typed.runId || typeof typed.runId !== "string") continue;
2283
+ const legacyCompletedAt = isLegacy && typeof typed.announceCompletedAt === "number" ? typed.announceCompletedAt : void 0;
2284
+ const cleanupCompletedAt = typeof typed.cleanupCompletedAt === "number" ? typed.cleanupCompletedAt : legacyCompletedAt;
2285
+ const cleanupHandled = typeof typed.cleanupHandled === "boolean" ? typed.cleanupHandled : isLegacy ? Boolean(typed.announceHandled ?? cleanupCompletedAt) : void 0;
2286
+ const requesterOrigin = normalizeDeliveryContext(typed.requesterOrigin ?? {
2287
+ channel: typeof typed.requesterChannel === "string" ? typed.requesterChannel : void 0,
2288
+ accountId: typeof typed.requesterAccountId === "string" ? typed.requesterAccountId : void 0
2289
+ });
2290
+ const { announceCompletedAt: _announceCompletedAt, announceHandled: _announceHandled, requesterChannel: _channel, requesterAccountId: _accountId, ...rest } = typed;
2291
+ out.set(runId, {
2292
+ ...rest,
2293
+ requesterOrigin,
2294
+ cleanupCompletedAt,
2295
+ cleanupHandled
2296
+ });
2297
+ if (isLegacy) migrated = true;
2298
+ }
2299
+ if (migrated) try {
2300
+ saveSubagentRegistryToDisk(out);
2301
+ } catch {}
2302
+ return out;
2303
+ }
2304
+ function saveSubagentRegistryToDisk(runs) {
2305
+ const pathname = resolveSubagentRegistryPath();
2306
+ const serialized = {};
2307
+ for (const [runId, entry] of runs.entries()) serialized[runId] = entry;
2308
+ saveJsonFile(pathname, {
2309
+ version: REGISTRY_VERSION,
2310
+ runs: serialized
2311
+ });
2312
+ }
2313
+
2314
+ //#endregion
2315
+ //#region src/agents/subagent-registry.ts
2316
+ var subagent_registry_exports = /* @__PURE__ */ __exportAll({
2317
+ clearSubagentRunSteerRestart: () => clearSubagentRunSteerRestart,
2318
+ countActiveDescendantRuns: () => countActiveDescendantRuns,
2319
+ countActiveRunsForSession: () => countActiveRunsForSession,
2320
+ initSubagentRegistry: () => initSubagentRegistry,
2321
+ isSubagentSessionRunActive: () => isSubagentSessionRunActive,
2322
+ listDescendantRunsForRequester: () => listDescendantRunsForRequester,
2323
+ listSubagentRunsForRequester: () => listSubagentRunsForRequester,
2324
+ markSubagentRunForSteerRestart: () => markSubagentRunForSteerRestart,
2325
+ markSubagentRunTerminated: () => markSubagentRunTerminated,
2326
+ registerSubagentRun: () => registerSubagentRun,
2327
+ replaceSubagentRunAfterSteer: () => replaceSubagentRunAfterSteer,
2328
+ resolveRequesterForChildSession: () => resolveRequesterForChildSession
2329
+ });
2330
+ const subagentRuns = /* @__PURE__ */ new Map();
2331
+ let sweeper = null;
2332
+ let listenerStarted = false;
2333
+ let listenerStop = null;
2334
+ var restoreAttempted = false;
2335
+ const SUBAGENT_ANNOUNCE_TIMEOUT_MS = 12e4;
2336
+ function persistSubagentRuns() {
2337
+ try {
2338
+ saveSubagentRegistryToDisk(subagentRuns);
2339
+ } catch {}
2340
+ }
2341
+ const resumedRuns = /* @__PURE__ */ new Set();
2342
+ function suppressAnnounceForSteerRestart(entry) {
2343
+ return entry?.suppressAnnounceReason === "steer-restart";
2344
+ }
2345
+ function startSubagentAnnounceCleanupFlow(runId, entry) {
2346
+ if (!beginSubagentCleanup(runId)) return false;
2347
+ const requesterOrigin = normalizeDeliveryContext(entry.requesterOrigin);
2348
+ runSubagentAnnounceFlow({
2349
+ childSessionKey: entry.childSessionKey,
2350
+ childRunId: entry.runId,
2351
+ requesterSessionKey: entry.requesterSessionKey,
2352
+ requesterOrigin,
2353
+ requesterDisplayKey: entry.requesterDisplayKey,
2354
+ task: entry.task,
2355
+ timeoutMs: SUBAGENT_ANNOUNCE_TIMEOUT_MS,
2356
+ cleanup: entry.cleanup,
2357
+ waitForCompletion: false,
2358
+ startedAt: entry.startedAt,
2359
+ endedAt: entry.endedAt,
2360
+ label: entry.label,
2361
+ outcome: entry.outcome
2362
+ }).then((didAnnounce) => {
2363
+ finalizeSubagentCleanup(runId, entry.cleanup, didAnnounce);
2364
+ });
2365
+ return true;
2366
+ }
2367
+ function resumeSubagentRun(runId) {
2368
+ if (!runId || resumedRuns.has(runId)) return;
2369
+ const entry = subagentRuns.get(runId);
2370
+ if (!entry) return;
2371
+ if (entry.cleanupCompletedAt) return;
2372
+ if (typeof entry.endedAt === "number" && entry.endedAt > 0) {
2373
+ if (suppressAnnounceForSteerRestart(entry)) {
2374
+ resumedRuns.add(runId);
2375
+ return;
2376
+ }
2377
+ if (!startSubagentAnnounceCleanupFlow(runId, entry)) return;
2378
+ resumedRuns.add(runId);
2379
+ return;
2380
+ }
2381
+ waitForSubagentCompletion(runId, resolveSubagentWaitTimeoutMs(loadConfig(), entry.runTimeoutSeconds));
2382
+ resumedRuns.add(runId);
2383
+ }
2384
+ function restoreSubagentRunsOnce() {
2385
+ if (restoreAttempted) return;
2386
+ restoreAttempted = true;
2387
+ try {
2388
+ const restored = loadSubagentRegistryFromDisk();
2389
+ if (restored.size === 0) return;
2390
+ for (const [runId, entry] of restored.entries()) {
2391
+ if (!runId || !entry) continue;
2392
+ if (!subagentRuns.has(runId)) subagentRuns.set(runId, entry);
2393
+ }
2394
+ ensureListener();
2395
+ if ([...subagentRuns.values()].some((entry) => entry.archiveAtMs)) startSweeper();
2396
+ for (const runId of subagentRuns.keys()) resumeSubagentRun(runId);
2397
+ } catch {}
2398
+ }
2399
+ function resolveArchiveAfterMs(cfg) {
2400
+ const minutes = (cfg ?? loadConfig()).agents?.defaults?.subagents?.archiveAfterMinutes ?? 60;
2401
+ if (!Number.isFinite(minutes) || minutes <= 0) return;
2402
+ return Math.max(1, Math.floor(minutes)) * 6e4;
2403
+ }
2404
+ function resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds) {
2405
+ return resolveAgentTimeoutMs({
2406
+ cfg,
2407
+ overrideSeconds: runTimeoutSeconds ?? 0
2408
+ });
2409
+ }
2410
+ function startSweeper() {
2411
+ if (sweeper) return;
2412
+ sweeper = setInterval(() => {
2413
+ sweepSubagentRuns();
2414
+ }, 6e4);
2415
+ sweeper.unref?.();
2416
+ }
2417
+ function stopSweeper() {
2418
+ if (!sweeper) return;
2419
+ clearInterval(sweeper);
2420
+ sweeper = null;
2421
+ }
2422
+ async function sweepSubagentRuns() {
2423
+ const now = Date.now();
2424
+ let mutated = false;
2425
+ for (const [runId, entry] of subagentRuns.entries()) {
2426
+ if (!entry.archiveAtMs || entry.archiveAtMs > now) continue;
2427
+ subagentRuns.delete(runId);
2428
+ mutated = true;
2429
+ try {
2430
+ await callGateway({
2431
+ method: "sessions.delete",
2432
+ params: {
2433
+ key: entry.childSessionKey,
2434
+ deleteTranscript: true
2435
+ },
2436
+ timeoutMs: 1e4
2437
+ });
2438
+ } catch {}
2439
+ }
2440
+ if (mutated) persistSubagentRuns();
2441
+ if (subagentRuns.size === 0) stopSweeper();
2442
+ }
2443
+ function ensureListener() {
2444
+ if (listenerStarted) return;
2445
+ listenerStarted = true;
2446
+ listenerStop = onAgentEvent((evt) => {
2447
+ if (!evt || evt.stream !== "lifecycle") return;
2448
+ const entry = subagentRuns.get(evt.runId);
2449
+ if (!entry) return;
2450
+ const phase = evt.data?.phase;
2451
+ if (phase === "start") {
2452
+ const startedAt = typeof evt.data?.startedAt === "number" ? evt.data.startedAt : void 0;
2453
+ if (startedAt) {
2454
+ entry.startedAt = startedAt;
2455
+ persistSubagentRuns();
2456
+ }
2457
+ return;
2458
+ }
2459
+ if (phase !== "end" && phase !== "error") return;
2460
+ entry.endedAt = typeof evt.data?.endedAt === "number" ? evt.data.endedAt : Date.now();
2461
+ if (phase === "error") entry.outcome = {
2462
+ status: "error",
2463
+ error: typeof evt.data?.error === "string" ? evt.data.error : void 0
2464
+ };
2465
+ else if (evt.data?.aborted) entry.outcome = { status: "timeout" };
2466
+ else entry.outcome = { status: "ok" };
2467
+ persistSubagentRuns();
2468
+ if (suppressAnnounceForSteerRestart(entry)) return;
2469
+ if (!startSubagentAnnounceCleanupFlow(evt.runId, entry)) return;
2470
+ });
2471
+ }
2472
+ function finalizeSubagentCleanup(runId, cleanup, didAnnounce) {
2473
+ const entry = subagentRuns.get(runId);
2474
+ if (!entry) return;
2475
+ if (!didAnnounce) {
2476
+ entry.cleanupHandled = false;
2477
+ resumedRuns.delete(runId);
2478
+ persistSubagentRuns();
2479
+ return;
2480
+ }
2481
+ if (cleanup === "delete") {
2482
+ subagentRuns.delete(runId);
2483
+ persistSubagentRuns();
2484
+ retryDeferredCompletedAnnounces(runId);
2485
+ return;
2486
+ }
2487
+ entry.cleanupCompletedAt = Date.now();
2488
+ persistSubagentRuns();
2489
+ retryDeferredCompletedAnnounces(runId);
2490
+ }
2491
+ function retryDeferredCompletedAnnounces(excludeRunId) {
2492
+ for (const [runId, entry] of subagentRuns.entries()) {
2493
+ if (excludeRunId && runId === excludeRunId) continue;
2494
+ if (typeof entry.endedAt !== "number") continue;
2495
+ if (entry.cleanupCompletedAt || entry.cleanupHandled) continue;
2496
+ if (suppressAnnounceForSteerRestart(entry)) continue;
2497
+ resumedRuns.delete(runId);
2498
+ resumeSubagentRun(runId);
2499
+ }
2500
+ }
2501
+ function beginSubagentCleanup(runId) {
2502
+ const entry = subagentRuns.get(runId);
2503
+ if (!entry) return false;
2504
+ if (entry.cleanupCompletedAt) return false;
2505
+ if (entry.cleanupHandled) return false;
2506
+ entry.cleanupHandled = true;
2507
+ persistSubagentRuns();
2508
+ return true;
2509
+ }
2510
+ function markSubagentRunForSteerRestart(runId) {
2511
+ const key = runId.trim();
2512
+ if (!key) return false;
2513
+ const entry = subagentRuns.get(key);
2514
+ if (!entry) return false;
2515
+ if (entry.suppressAnnounceReason === "steer-restart") return true;
2516
+ entry.suppressAnnounceReason = "steer-restart";
2517
+ persistSubagentRuns();
2518
+ return true;
2519
+ }
2520
+ function clearSubagentRunSteerRestart(runId) {
2521
+ const key = runId.trim();
2522
+ if (!key) return false;
2523
+ const entry = subagentRuns.get(key);
2524
+ if (!entry) return false;
2525
+ if (entry.suppressAnnounceReason !== "steer-restart") return true;
2526
+ entry.suppressAnnounceReason = void 0;
2527
+ persistSubagentRuns();
2528
+ resumedRuns.delete(key);
2529
+ if (typeof entry.endedAt === "number" && !entry.cleanupCompletedAt) resumeSubagentRun(key);
2530
+ return true;
2531
+ }
2532
+ function replaceSubagentRunAfterSteer(params) {
2533
+ const previousRunId = params.previousRunId.trim();
2534
+ const nextRunId = params.nextRunId.trim();
2535
+ if (!previousRunId || !nextRunId) return false;
2536
+ const source = subagentRuns.get(previousRunId) ?? params.fallback;
2537
+ if (!source) return false;
2538
+ if (previousRunId !== nextRunId) {
2539
+ subagentRuns.delete(previousRunId);
2540
+ resumedRuns.delete(previousRunId);
2541
+ }
2542
+ const now = Date.now();
2543
+ const cfg = loadConfig();
2544
+ const archiveAfterMs = resolveArchiveAfterMs(cfg);
2545
+ const archiveAtMs = archiveAfterMs ? now + archiveAfterMs : void 0;
2546
+ const runTimeoutSeconds = params.runTimeoutSeconds ?? source.runTimeoutSeconds ?? 0;
2547
+ const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds);
2548
+ const next = {
2549
+ ...source,
2550
+ runId: nextRunId,
2551
+ startedAt: now,
2552
+ endedAt: void 0,
2553
+ outcome: void 0,
2554
+ cleanupCompletedAt: void 0,
2555
+ cleanupHandled: false,
2556
+ suppressAnnounceReason: void 0,
2557
+ archiveAtMs,
2558
+ runTimeoutSeconds
2559
+ };
2560
+ subagentRuns.set(nextRunId, next);
2561
+ ensureListener();
2562
+ persistSubagentRuns();
2563
+ if (archiveAtMs) startSweeper();
2564
+ waitForSubagentCompletion(nextRunId, waitTimeoutMs);
2565
+ return true;
2566
+ }
2567
+ function registerSubagentRun(params) {
2568
+ const now = Date.now();
2569
+ const cfg = loadConfig();
2570
+ const archiveAfterMs = resolveArchiveAfterMs(cfg);
2571
+ const archiveAtMs = archiveAfterMs ? now + archiveAfterMs : void 0;
2572
+ const runTimeoutSeconds = params.runTimeoutSeconds ?? 0;
2573
+ const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds);
2574
+ const requesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
2575
+ subagentRuns.set(params.runId, {
2576
+ runId: params.runId,
2577
+ childSessionKey: params.childSessionKey,
2578
+ requesterSessionKey: params.requesterSessionKey,
2579
+ requesterOrigin,
2580
+ requesterDisplayKey: params.requesterDisplayKey,
2581
+ task: params.task,
2582
+ cleanup: params.cleanup,
2583
+ label: params.label,
2584
+ model: params.model,
2585
+ runTimeoutSeconds,
2586
+ createdAt: now,
2587
+ startedAt: now,
2588
+ archiveAtMs,
2589
+ cleanupHandled: false
2590
+ });
2591
+ ensureListener();
2592
+ persistSubagentRuns();
2593
+ if (archiveAfterMs) startSweeper();
2594
+ waitForSubagentCompletion(params.runId, waitTimeoutMs);
2595
+ }
2596
+ async function waitForSubagentCompletion(runId, waitTimeoutMs) {
2597
+ try {
2598
+ const timeoutMs = Math.max(1, Math.floor(waitTimeoutMs));
2599
+ const wait = await callGateway({
2600
+ method: "agent.wait",
2601
+ params: {
2602
+ runId,
2603
+ timeoutMs
2604
+ },
2605
+ timeoutMs: timeoutMs + 1e4
2606
+ });
2607
+ if (wait?.status !== "ok" && wait?.status !== "error" && wait?.status !== "timeout") return;
2608
+ const entry = subagentRuns.get(runId);
2609
+ if (!entry) return;
2610
+ let mutated = false;
2611
+ if (typeof wait.startedAt === "number") {
2612
+ entry.startedAt = wait.startedAt;
2613
+ mutated = true;
2614
+ }
2615
+ if (typeof wait.endedAt === "number") {
2616
+ entry.endedAt = wait.endedAt;
2617
+ mutated = true;
2618
+ }
2619
+ if (!entry.endedAt) {
2620
+ entry.endedAt = Date.now();
2621
+ mutated = true;
2622
+ }
2623
+ const waitError = typeof wait.error === "string" ? wait.error : void 0;
2624
+ entry.outcome = wait.status === "error" ? {
2625
+ status: "error",
2626
+ error: waitError
2627
+ } : wait.status === "timeout" ? { status: "timeout" } : { status: "ok" };
2628
+ mutated = true;
2629
+ if (mutated) persistSubagentRuns();
2630
+ if (suppressAnnounceForSteerRestart(entry)) return;
2631
+ if (!startSubagentAnnounceCleanupFlow(runId, entry)) return;
2632
+ } catch {}
2633
+ }
2634
+ function findRunIdsByChildSessionKey(childSessionKey) {
2635
+ const key = childSessionKey.trim();
2636
+ if (!key) return [];
2637
+ const runIds = [];
2638
+ for (const [runId, entry] of subagentRuns.entries()) if (entry.childSessionKey === key) runIds.push(runId);
2639
+ return runIds;
2640
+ }
2641
+ function getRunsSnapshotForRead() {
2642
+ const merged = /* @__PURE__ */ new Map();
2643
+ if (!(process.env.VITEST || false)) try {
2644
+ for (const [runId, entry] of loadSubagentRegistryFromDisk().entries()) merged.set(runId, entry);
2645
+ } catch {}
2646
+ for (const [runId, entry] of subagentRuns.entries()) merged.set(runId, entry);
2647
+ return merged;
2648
+ }
2649
+ function resolveRequesterForChildSession(childSessionKey) {
2650
+ const key = childSessionKey.trim();
2651
+ if (!key) return null;
2652
+ let best;
2653
+ for (const entry of getRunsSnapshotForRead().values()) {
2654
+ if (entry.childSessionKey !== key) continue;
2655
+ if (!best || entry.createdAt > best.createdAt) best = entry;
2656
+ }
2657
+ if (!best) return null;
2658
+ return {
2659
+ requesterSessionKey: best.requesterSessionKey,
2660
+ requesterOrigin: normalizeDeliveryContext(best.requesterOrigin)
2661
+ };
2662
+ }
2663
+ function isSubagentSessionRunActive(childSessionKey) {
2664
+ const runIds = findRunIdsByChildSessionKey(childSessionKey);
2665
+ for (const runId of runIds) {
2666
+ const entry = subagentRuns.get(runId);
2667
+ if (!entry) continue;
2668
+ if (typeof entry.endedAt !== "number") return true;
2669
+ }
2670
+ return false;
2671
+ }
2672
+ function markSubagentRunTerminated(params) {
2673
+ const runIds = /* @__PURE__ */ new Set();
2674
+ if (typeof params.runId === "string" && params.runId.trim()) runIds.add(params.runId.trim());
2675
+ if (typeof params.childSessionKey === "string" && params.childSessionKey.trim()) for (const runId of findRunIdsByChildSessionKey(params.childSessionKey)) runIds.add(runId);
2676
+ if (runIds.size === 0) return 0;
2677
+ const now = Date.now();
2678
+ const reason = params.reason?.trim() || "killed";
2679
+ let updated = 0;
2680
+ for (const runId of runIds) {
2681
+ const entry = subagentRuns.get(runId);
2682
+ if (!entry) continue;
2683
+ if (typeof entry.endedAt === "number") continue;
2684
+ entry.endedAt = now;
2685
+ entry.outcome = {
2686
+ status: "error",
2687
+ error: reason
2688
+ };
2689
+ entry.cleanupHandled = true;
2690
+ entry.cleanupCompletedAt = now;
2691
+ entry.suppressAnnounceReason = "killed";
2692
+ updated += 1;
2693
+ }
2694
+ if (updated > 0) persistSubagentRuns();
2695
+ return updated;
2696
+ }
2697
+ function listSubagentRunsForRequester(requesterSessionKey) {
2698
+ const key = requesterSessionKey.trim();
2699
+ if (!key) return [];
2700
+ return [...subagentRuns.values()].filter((entry) => entry.requesterSessionKey === key);
2701
+ }
2702
+ function countActiveRunsForSession(requesterSessionKey) {
2703
+ const key = requesterSessionKey.trim();
2704
+ if (!key) return 0;
2705
+ let count = 0;
2706
+ for (const entry of getRunsSnapshotForRead().values()) {
2707
+ if (entry.requesterSessionKey !== key) continue;
2708
+ if (typeof entry.endedAt === "number") continue;
2709
+ count += 1;
2710
+ }
2711
+ return count;
2712
+ }
2713
+ function countActiveDescendantRuns(rootSessionKey) {
2714
+ const root = rootSessionKey.trim();
2715
+ if (!root) return 0;
2716
+ const runs = getRunsSnapshotForRead();
2717
+ const pending = [root];
2718
+ const visited = new Set([root]);
2719
+ let count = 0;
2720
+ while (pending.length > 0) {
2721
+ const requester = pending.shift();
2722
+ if (!requester) continue;
2723
+ for (const entry of runs.values()) {
2724
+ if (entry.requesterSessionKey !== requester) continue;
2725
+ if (typeof entry.endedAt !== "number") count += 1;
2726
+ const childKey = entry.childSessionKey.trim();
2727
+ if (!childKey || visited.has(childKey)) continue;
2728
+ visited.add(childKey);
2729
+ pending.push(childKey);
2730
+ }
2731
+ }
2732
+ return count;
2733
+ }
2734
+ function listDescendantRunsForRequester(rootSessionKey) {
2735
+ const root = rootSessionKey.trim();
2736
+ if (!root) return [];
2737
+ const runs = getRunsSnapshotForRead();
2738
+ const pending = [root];
2739
+ const visited = new Set([root]);
2740
+ const descendants = [];
2741
+ while (pending.length > 0) {
2742
+ const requester = pending.shift();
2743
+ if (!requester) continue;
2744
+ for (const entry of runs.values()) {
2745
+ if (entry.requesterSessionKey !== requester) continue;
2746
+ descendants.push(entry);
2747
+ const childKey = entry.childSessionKey.trim();
2748
+ if (!childKey || visited.has(childKey)) continue;
2749
+ visited.add(childKey);
2750
+ pending.push(childKey);
2751
+ }
2752
+ }
2753
+ return descendants;
2754
+ }
2755
+ function initSubagentRegistry() {
2756
+ restoreSubagentRunsOnce();
2757
+ }
2758
+
2759
+ //#endregion
2760
+ export { startDiagnosticHeartbeat as $, getFollowupQueueDepth as A, resolveIdentityNamePrefix as B, resolveSessionReference as C, getSubagentDepthFromSessionStore as D, stripToolMessages as E, extractShortModelName as F, getQueueSize as G, clearSessionQueues as H, resolveAgentIdentity as I, setCommandLaneConcurrency as J, getTotalQueueSize as K, resolveEffectiveMessagesConfig as L, isRoutableChannel as M, routeReply as N, resolveQueueSettings as O, normalizeReplyPayload as P, logSessionStateChange as Q, resolveHumanDelayConfig as R, resolveMainSessionAlias as S, shouldResolveSessionIdInput as T, clearCommandLane as U, resolveMessagePrefix as V, getActiveTaskCount as W, logMessageProcessed as X, waitForActiveTasks as Y, logMessageQueued as Z, createAgentToAgentPolicy as _, listDescendantRunsForRequester as a, takeDirectiveToken as at, resolveDisplaySessionKey as b, markSubagentRunTerminated as c, subagent_registry_exports as d, stopDiagnosticHeartbeat as et, buildSubagentSystemPrompt as f, classifySessionKind as g, runAgentStep as h, initSubagentRegistry as i, skipDirectiveArgPrefix as it, scheduleFollowupDrain as j, enqueueFollowupRun as k, registerSubagentRun as l, readLatestAssistantReply as m, countActiveDescendantRuns as n, isDiagnosticsEnabled as nt, listSubagentRunsForRequester as o, runSubagentAnnounceFlow as p, resetAllLanes as q, countActiveRunsForSession as r, extractQueueDirective as rt, markSubagentRunForSteerRestart as s, clearSubagentRunSteerRestart as t, emitDiagnosticEvent as tt, replaceSubagentRunAfterSteer as u, deriveChannel as v, sanitizeTextContent as w, resolveInternalSessionKey as x, extractAssistantText as y, resolveIdentityName as z };