@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
@@ -1,2759 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
- import { $ as resolveStateDir, h as defaultRuntime, o as createSubsystemLogger } from "./entry.js";
3
- import { S as saveJsonFile, x as loadJsonFile } from "./auth-profiles-DxI8L7bs.js";
4
- import { _ as isAcpSessionKey, d as resolveAgentIdFromSessionKey, g as getSubagentDepth, u as normalizeMainKey, x as parseAgentSessionKey } from "./session-key-BGiG_JcT.js";
5
- import { c as resolveDefaultAgentId, l as resolveSessionAgentId, n as resolveAgentConfig } from "./agent-scope-OZi7lb8S.js";
6
- import { i as loadConfig, m as parseDurationMs } from "./config-C8rUDJXY.js";
7
- import { n as callGateway } from "./call-BAHvlu2G.js";
8
- import { l as normalizeMessageChannel, t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-w4F2b2F6.js";
9
- import { _ as waitForEmbeddedPiRunEnd, c as stripHeartbeatToken, f as isEmbeddedPiRunActive, h as resolveEmbeddedSessionLane, l as CommandLane, m as queueEmbeddedPiMessage, n as AGENT_LANE_NESTED, t as resolveAgentTimeoutMs, x as onAgentEvent } from "./timeout-CswI_K-U.js";
10
- import { A as deliveryContextFromSession, M as mergeDeliveryContext, N as normalizeDeliveryContext, S as resolveMainSessionKey, i as loadSessionStore, j as deliveryContextKey } from "./sessions-DcXpzig0.js";
11
- import { r as normalizeChannelId, t as getChannelPlugin } from "./plugins-CDJw924T.js";
12
- import { n as SILENT_REPLY_TOKEN, r as isSilentReplyText, t as HEARTBEAT_TOKEN } from "./tokens-C-X7wDKj.js";
13
- import { c as resolveStorePath } from "./paths-CxRf2rBG.js";
14
- import os from "node:os";
15
- import path from "node:path";
16
- import fs from "node:fs";
17
- import JSON5 from "json5";
18
- import crypto from "node:crypto";
19
-
20
- //#region src/utils/queue-helpers.ts
21
- function elideQueueText(text, limit = 140) {
22
- if (text.length <= limit) return text;
23
- return `${text.slice(0, Math.max(0, limit - 1)).trimEnd()}…`;
24
- }
25
- function buildQueueSummaryLine(text, limit = 160) {
26
- return elideQueueText(text.replace(/\s+/g, " ").trim(), limit);
27
- }
28
- function shouldSkipQueueItem(params) {
29
- if (!params.dedupe) return false;
30
- return params.dedupe(params.item, params.items);
31
- }
32
- function applyQueueDropPolicy(params) {
33
- const cap = params.queue.cap;
34
- if (cap <= 0 || params.queue.items.length < cap) return true;
35
- if (params.queue.dropPolicy === "new") return false;
36
- const dropCount = params.queue.items.length - cap + 1;
37
- const dropped = params.queue.items.splice(0, dropCount);
38
- if (params.queue.dropPolicy === "summarize") {
39
- for (const item of dropped) {
40
- params.queue.droppedCount += 1;
41
- params.queue.summaryLines.push(buildQueueSummaryLine(params.summarize(item)));
42
- }
43
- const limit = Math.max(0, params.summaryLimit ?? cap);
44
- while (params.queue.summaryLines.length > limit) params.queue.summaryLines.shift();
45
- }
46
- return true;
47
- }
48
- function waitForQueueDebounce(queue) {
49
- const debounceMs = Math.max(0, queue.debounceMs);
50
- if (debounceMs <= 0) return Promise.resolve();
51
- return new Promise((resolve) => {
52
- const check = () => {
53
- const since = Date.now() - queue.lastEnqueuedAt;
54
- if (since >= debounceMs) {
55
- resolve();
56
- return;
57
- }
58
- setTimeout(check, debounceMs - since);
59
- };
60
- check();
61
- });
62
- }
63
- function buildQueueSummaryPrompt(params) {
64
- if (params.state.dropPolicy !== "summarize" || params.state.droppedCount <= 0) return;
65
- const noun = params.noun;
66
- const lines = [params.title ?? `[Queue overflow] Dropped ${params.state.droppedCount} ${noun}${params.state.droppedCount === 1 ? "" : "s"} due to cap.`];
67
- if (params.state.summaryLines.length > 0) {
68
- lines.push("Summary:");
69
- for (const line of params.state.summaryLines) lines.push(`- ${line}`);
70
- }
71
- params.state.droppedCount = 0;
72
- params.state.summaryLines = [];
73
- return lines.join("\n");
74
- }
75
- function buildCollectPrompt(params) {
76
- const blocks = [params.title];
77
- if (params.summary) blocks.push(params.summary);
78
- params.items.forEach((item, idx) => {
79
- blocks.push(params.renderItem(item, idx));
80
- });
81
- return blocks.join("\n\n");
82
- }
83
- function hasCrossChannelItems(items, resolveKey) {
84
- const keys = /* @__PURE__ */ new Set();
85
- let hasUnkeyed = false;
86
- for (const item of items) {
87
- const resolved = resolveKey(item);
88
- if (resolved.cross) return true;
89
- if (!resolved.key) {
90
- hasUnkeyed = true;
91
- continue;
92
- }
93
- keys.add(resolved.key);
94
- }
95
- if (keys.size === 0) return false;
96
- if (hasUnkeyed) return true;
97
- return keys.size > 1;
98
- }
99
-
100
- //#endregion
101
- //#region src/agents/subagent-announce-queue.ts
102
- const ANNOUNCE_QUEUES = /* @__PURE__ */ new Map();
103
- function previewQueueSummaryPrompt$1(queue) {
104
- return buildQueueSummaryPrompt({
105
- state: {
106
- dropPolicy: queue.dropPolicy,
107
- droppedCount: queue.droppedCount,
108
- summaryLines: [...queue.summaryLines]
109
- },
110
- noun: "announce"
111
- });
112
- }
113
- function clearQueueSummaryState$1(queue) {
114
- queue.droppedCount = 0;
115
- queue.summaryLines = [];
116
- }
117
- function getAnnounceQueue(key, settings, send) {
118
- const existing = ANNOUNCE_QUEUES.get(key);
119
- if (existing) {
120
- existing.mode = settings.mode;
121
- existing.debounceMs = typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : existing.debounceMs;
122
- existing.cap = typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : existing.cap;
123
- existing.dropPolicy = settings.dropPolicy ?? existing.dropPolicy;
124
- existing.send = send;
125
- return existing;
126
- }
127
- const created = {
128
- items: [],
129
- draining: false,
130
- lastEnqueuedAt: 0,
131
- mode: settings.mode,
132
- debounceMs: typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : 1e3,
133
- cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : 20,
134
- dropPolicy: settings.dropPolicy ?? "summarize",
135
- droppedCount: 0,
136
- summaryLines: [],
137
- send
138
- };
139
- ANNOUNCE_QUEUES.set(key, created);
140
- return created;
141
- }
142
- function scheduleAnnounceDrain(key) {
143
- const queue = ANNOUNCE_QUEUES.get(key);
144
- if (!queue || queue.draining) return;
145
- queue.draining = true;
146
- (async () => {
147
- try {
148
- let forceIndividualCollect = false;
149
- while (queue.items.length > 0 || queue.droppedCount > 0) {
150
- await waitForQueueDebounce(queue);
151
- if (queue.mode === "collect") {
152
- if (forceIndividualCollect) {
153
- const next = queue.items[0];
154
- if (!next) break;
155
- await queue.send(next);
156
- queue.items.shift();
157
- continue;
158
- }
159
- if (hasCrossChannelItems(queue.items, (item) => {
160
- if (!item.origin) return {};
161
- if (!item.originKey) return { cross: true };
162
- return { key: item.originKey };
163
- })) {
164
- forceIndividualCollect = true;
165
- const next = queue.items[0];
166
- if (!next) break;
167
- await queue.send(next);
168
- queue.items.shift();
169
- continue;
170
- }
171
- const items = queue.items.slice();
172
- const summary = previewQueueSummaryPrompt$1(queue);
173
- const prompt = buildCollectPrompt({
174
- title: "[Queued announce messages while agent was busy]",
175
- items,
176
- summary,
177
- renderItem: (item, idx) => `---\nQueued #${idx + 1}\n${item.prompt}`.trim()
178
- });
179
- const last = items.at(-1);
180
- if (!last) break;
181
- await queue.send({
182
- ...last,
183
- prompt
184
- });
185
- queue.items.splice(0, items.length);
186
- if (summary) clearQueueSummaryState$1(queue);
187
- continue;
188
- }
189
- const summaryPrompt = previewQueueSummaryPrompt$1(queue);
190
- if (summaryPrompt) {
191
- const next = queue.items[0];
192
- if (!next) break;
193
- await queue.send({
194
- ...next,
195
- prompt: summaryPrompt
196
- });
197
- queue.items.shift();
198
- clearQueueSummaryState$1(queue);
199
- continue;
200
- }
201
- const next = queue.items[0];
202
- if (!next) break;
203
- await queue.send(next);
204
- queue.items.shift();
205
- }
206
- } catch (err) {
207
- queue.lastEnqueuedAt = Date.now();
208
- defaultRuntime.error?.(`announce queue drain failed for ${key}: ${String(err)}`);
209
- } finally {
210
- queue.draining = false;
211
- if (queue.items.length === 0 && queue.droppedCount === 0) ANNOUNCE_QUEUES.delete(key);
212
- else scheduleAnnounceDrain(key);
213
- }
214
- })();
215
- }
216
- function enqueueAnnounce(params) {
217
- const queue = getAnnounceQueue(params.key, params.settings, params.send);
218
- queue.lastEnqueuedAt = Date.now();
219
- if (!applyQueueDropPolicy({
220
- queue,
221
- summarize: (item) => item.summaryLine?.trim() || item.prompt.trim()
222
- })) {
223
- if (queue.dropPolicy === "new") scheduleAnnounceDrain(params.key);
224
- return false;
225
- }
226
- const origin = normalizeDeliveryContext(params.item.origin);
227
- const originKey = deliveryContextKey(origin);
228
- queue.items.push({
229
- ...params.item,
230
- origin,
231
- originKey
232
- });
233
- scheduleAnnounceDrain(params.key);
234
- return true;
235
- }
236
-
237
- //#endregion
238
- //#region src/auto-reply/reply/directive-parsing.ts
239
- function skipDirectiveArgPrefix(raw) {
240
- let i = 0;
241
- const len = raw.length;
242
- while (i < len && /\s/.test(raw[i])) i += 1;
243
- if (raw[i] === ":") {
244
- i += 1;
245
- while (i < len && /\s/.test(raw[i])) i += 1;
246
- }
247
- return i;
248
- }
249
- function takeDirectiveToken(raw, startIndex) {
250
- let i = startIndex;
251
- const len = raw.length;
252
- while (i < len && /\s/.test(raw[i])) i += 1;
253
- if (i >= len) return {
254
- token: null,
255
- nextIndex: i
256
- };
257
- const start = i;
258
- while (i < len && !/\s/.test(raw[i])) i += 1;
259
- if (start === i) return {
260
- token: null,
261
- nextIndex: i
262
- };
263
- const token = raw.slice(start, i);
264
- while (i < len && /\s/.test(raw[i])) i += 1;
265
- return {
266
- token,
267
- nextIndex: i
268
- };
269
- }
270
-
271
- //#endregion
272
- //#region src/auto-reply/reply/queue/normalize.ts
273
- function normalizeQueueMode(raw) {
274
- if (!raw) return;
275
- const cleaned = raw.trim().toLowerCase();
276
- if (cleaned === "queue" || cleaned === "queued") return "steer";
277
- if (cleaned === "interrupt" || cleaned === "interrupts" || cleaned === "abort") return "interrupt";
278
- if (cleaned === "steer" || cleaned === "steering") return "steer";
279
- if (cleaned === "followup" || cleaned === "follow-ups" || cleaned === "followups") return "followup";
280
- if (cleaned === "collect" || cleaned === "coalesce") return "collect";
281
- if (cleaned === "steer+backlog" || cleaned === "steer-backlog" || cleaned === "steer_backlog") return "steer-backlog";
282
- }
283
- function normalizeQueueDropPolicy(raw) {
284
- if (!raw) return;
285
- const cleaned = raw.trim().toLowerCase();
286
- if (cleaned === "old" || cleaned === "oldest") return "old";
287
- if (cleaned === "new" || cleaned === "newest") return "new";
288
- if (cleaned === "summarize" || cleaned === "summary") return "summarize";
289
- }
290
-
291
- //#endregion
292
- //#region src/auto-reply/reply/queue/directive.ts
293
- function parseQueueDebounce(raw) {
294
- if (!raw) return;
295
- try {
296
- const parsed = parseDurationMs(raw.trim(), { defaultUnit: "ms" });
297
- if (!parsed || parsed < 0) return;
298
- return Math.round(parsed);
299
- } catch {
300
- return;
301
- }
302
- }
303
- function parseQueueCap(raw) {
304
- if (!raw) return;
305
- const num = Number(raw);
306
- if (!Number.isFinite(num)) return;
307
- const cap = Math.floor(num);
308
- if (cap < 1) return;
309
- return cap;
310
- }
311
- function parseQueueDirectiveArgs(raw) {
312
- const len = raw.length;
313
- let i = skipDirectiveArgPrefix(raw);
314
- let consumed = i;
315
- let queueMode;
316
- let queueReset = false;
317
- let rawMode;
318
- let debounceMs;
319
- let cap;
320
- let dropPolicy;
321
- let rawDebounce;
322
- let rawCap;
323
- let rawDrop;
324
- let hasOptions = false;
325
- const takeToken = () => {
326
- const res = takeDirectiveToken(raw, i);
327
- i = res.nextIndex;
328
- return res.token;
329
- };
330
- while (i < len) {
331
- const token = takeToken();
332
- if (!token) break;
333
- const lowered = token.trim().toLowerCase();
334
- if (lowered === "default" || lowered === "reset" || lowered === "clear") {
335
- queueReset = true;
336
- consumed = i;
337
- break;
338
- }
339
- if (lowered.startsWith("debounce:") || lowered.startsWith("debounce=")) {
340
- rawDebounce = token.split(/[:=]/)[1] ?? "";
341
- debounceMs = parseQueueDebounce(rawDebounce);
342
- hasOptions = true;
343
- consumed = i;
344
- continue;
345
- }
346
- if (lowered.startsWith("cap:") || lowered.startsWith("cap=")) {
347
- rawCap = token.split(/[:=]/)[1] ?? "";
348
- cap = parseQueueCap(rawCap);
349
- hasOptions = true;
350
- consumed = i;
351
- continue;
352
- }
353
- if (lowered.startsWith("drop:") || lowered.startsWith("drop=")) {
354
- rawDrop = token.split(/[:=]/)[1] ?? "";
355
- dropPolicy = normalizeQueueDropPolicy(rawDrop);
356
- hasOptions = true;
357
- consumed = i;
358
- continue;
359
- }
360
- const mode = normalizeQueueMode(token);
361
- if (mode) {
362
- queueMode = mode;
363
- rawMode = token;
364
- consumed = i;
365
- continue;
366
- }
367
- break;
368
- }
369
- return {
370
- consumed,
371
- queueMode,
372
- queueReset,
373
- rawMode,
374
- debounceMs,
375
- cap,
376
- dropPolicy,
377
- rawDebounce,
378
- rawCap,
379
- rawDrop,
380
- hasOptions
381
- };
382
- }
383
- function extractQueueDirective(body) {
384
- if (!body) return {
385
- cleaned: "",
386
- hasDirective: false,
387
- queueReset: false,
388
- hasOptions: false
389
- };
390
- const match = /(?:^|\s)\/queue(?=$|\s|:)/i.exec(body);
391
- if (!match) return {
392
- cleaned: body.trim(),
393
- hasDirective: false,
394
- queueReset: false,
395
- hasOptions: false
396
- };
397
- const start = match.index + match[0].indexOf("/queue");
398
- const argsStart = start + 6;
399
- const parsed = parseQueueDirectiveArgs(body.slice(argsStart));
400
- return {
401
- cleaned: `${body.slice(0, start)} ${body.slice(argsStart + parsed.consumed)}`.replace(/\s+/g, " ").trim(),
402
- queueMode: parsed.queueMode,
403
- queueReset: parsed.queueReset,
404
- rawMode: parsed.rawMode,
405
- debounceMs: parsed.debounceMs,
406
- cap: parsed.cap,
407
- dropPolicy: parsed.dropPolicy,
408
- rawDebounce: parsed.rawDebounce,
409
- rawCap: parsed.rawCap,
410
- rawDrop: parsed.rawDrop,
411
- hasDirective: true,
412
- hasOptions: parsed.hasOptions
413
- };
414
- }
415
-
416
- //#endregion
417
- //#region src/infra/diagnostic-events.ts
418
- let seq = 0;
419
- const listeners = /* @__PURE__ */ new Set();
420
- function isDiagnosticsEnabled(config) {
421
- return config?.diagnostics?.enabled === true;
422
- }
423
- function emitDiagnosticEvent(event) {
424
- const enriched = {
425
- ...event,
426
- seq: seq += 1,
427
- ts: Date.now()
428
- };
429
- for (const listener of listeners) try {
430
- listener(enriched);
431
- } catch {}
432
- }
433
-
434
- //#endregion
435
- //#region src/logging/diagnostic-session-state.ts
436
- const diagnosticSessionStates = /* @__PURE__ */ new Map();
437
- const SESSION_STATE_TTL_MS = 1800 * 1e3;
438
- const SESSION_STATE_PRUNE_INTERVAL_MS = 60 * 1e3;
439
- const SESSION_STATE_MAX_ENTRIES = 2e3;
440
- let lastSessionPruneAt = 0;
441
- function pruneDiagnosticSessionStates(now = Date.now(), force = false) {
442
- const shouldPruneForSize = diagnosticSessionStates.size > SESSION_STATE_MAX_ENTRIES;
443
- if (!force && !shouldPruneForSize && now - lastSessionPruneAt < SESSION_STATE_PRUNE_INTERVAL_MS) return;
444
- lastSessionPruneAt = now;
445
- for (const [key, state] of diagnosticSessionStates.entries()) {
446
- const ageMs = now - state.lastActivity;
447
- if (state.state === "idle" && state.queueDepth <= 0 && ageMs > SESSION_STATE_TTL_MS) diagnosticSessionStates.delete(key);
448
- }
449
- if (diagnosticSessionStates.size <= SESSION_STATE_MAX_ENTRIES) return;
450
- const excess = diagnosticSessionStates.size - SESSION_STATE_MAX_ENTRIES;
451
- const ordered = Array.from(diagnosticSessionStates.entries()).toSorted((a, b) => a[1].lastActivity - b[1].lastActivity);
452
- for (let i = 0; i < excess; i += 1) {
453
- const key = ordered[i]?.[0];
454
- if (!key) break;
455
- diagnosticSessionStates.delete(key);
456
- }
457
- }
458
- function resolveSessionKey({ sessionKey, sessionId }) {
459
- return sessionKey ?? sessionId ?? "unknown";
460
- }
461
- function getDiagnosticSessionState(ref) {
462
- pruneDiagnosticSessionStates();
463
- const key = resolveSessionKey(ref);
464
- const existing = diagnosticSessionStates.get(key);
465
- if (existing) {
466
- if (ref.sessionId) existing.sessionId = ref.sessionId;
467
- if (ref.sessionKey) existing.sessionKey = ref.sessionKey;
468
- return existing;
469
- }
470
- const created = {
471
- sessionId: ref.sessionId,
472
- sessionKey: ref.sessionKey,
473
- lastActivity: Date.now(),
474
- state: "idle",
475
- queueDepth: 0
476
- };
477
- diagnosticSessionStates.set(key, created);
478
- pruneDiagnosticSessionStates(Date.now(), true);
479
- return created;
480
- }
481
-
482
- //#endregion
483
- //#region src/logging/diagnostic.ts
484
- const diag = createSubsystemLogger("diagnostic");
485
- const webhookStats = {
486
- received: 0,
487
- processed: 0,
488
- errors: 0,
489
- lastReceived: 0
490
- };
491
- let lastActivityAt = 0;
492
- function markActivity() {
493
- lastActivityAt = Date.now();
494
- }
495
- function logMessageQueued(params) {
496
- const state = getDiagnosticSessionState(params);
497
- state.queueDepth += 1;
498
- state.lastActivity = Date.now();
499
- 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}`);
500
- emitDiagnosticEvent({
501
- type: "message.queued",
502
- sessionId: state.sessionId,
503
- sessionKey: state.sessionKey,
504
- channel: params.channel,
505
- source: params.source,
506
- queueDepth: state.queueDepth
507
- });
508
- markActivity();
509
- }
510
- function logMessageProcessed(params) {
511
- if (params.outcome === "error" ? diag.isEnabled("error") : diag.isEnabled("debug")) {
512
- 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}"` : ""}`;
513
- if (params.outcome === "error") diag.error(payload);
514
- else diag.debug(payload);
515
- }
516
- emitDiagnosticEvent({
517
- type: "message.processed",
518
- channel: params.channel,
519
- chatId: params.chatId,
520
- messageId: params.messageId,
521
- sessionId: params.sessionId,
522
- sessionKey: params.sessionKey,
523
- durationMs: params.durationMs,
524
- outcome: params.outcome,
525
- reason: params.reason,
526
- error: params.error
527
- });
528
- markActivity();
529
- }
530
- function logSessionStateChange(params) {
531
- const state = getDiagnosticSessionState(params);
532
- const isProbeSession = state.sessionId?.startsWith("probe-") ?? false;
533
- const prevState = state.state;
534
- state.state = params.state;
535
- state.lastActivity = Date.now();
536
- if (params.state === "idle") state.queueDepth = Math.max(0, state.queueDepth - 1);
537
- 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}`);
538
- emitDiagnosticEvent({
539
- type: "session.state",
540
- sessionId: state.sessionId,
541
- sessionKey: state.sessionKey,
542
- prevState,
543
- state: params.state,
544
- reason: params.reason,
545
- queueDepth: state.queueDepth
546
- });
547
- markActivity();
548
- }
549
- function logSessionStuck(params) {
550
- const state = getDiagnosticSessionState(params);
551
- 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}`);
552
- emitDiagnosticEvent({
553
- type: "session.stuck",
554
- sessionId: state.sessionId,
555
- sessionKey: state.sessionKey,
556
- state: params.state,
557
- ageMs: params.ageMs,
558
- queueDepth: state.queueDepth
559
- });
560
- markActivity();
561
- }
562
- function logLaneDequeue(lane, waitMs, queueSize) {
563
- diag.debug(`lane dequeue: lane=${lane} waitMs=${waitMs} queueSize=${queueSize}`);
564
- emitDiagnosticEvent({
565
- type: "queue.lane.dequeue",
566
- lane,
567
- queueSize,
568
- waitMs
569
- });
570
- markActivity();
571
- }
572
- let heartbeatInterval = null;
573
- function startDiagnosticHeartbeat() {
574
- if (heartbeatInterval) return;
575
- heartbeatInterval = setInterval(() => {
576
- const now = Date.now();
577
- pruneDiagnosticSessionStates(now, true);
578
- const activeCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "processing").length;
579
- const waitingCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "waiting").length;
580
- const totalQueued = Array.from(diagnosticSessionStates.values()).reduce((sum, s) => sum + s.queueDepth, 0);
581
- if (!(lastActivityAt > 0 || webhookStats.received > 0 || activeCount > 0 || waitingCount > 0 || totalQueued > 0)) return;
582
- if (now - lastActivityAt > 12e4 && activeCount === 0 && waitingCount === 0) return;
583
- diag.debug(`heartbeat: webhooks=${webhookStats.received}/${webhookStats.processed}/${webhookStats.errors} active=${activeCount} waiting=${waitingCount} queued=${totalQueued}`);
584
- emitDiagnosticEvent({
585
- type: "diagnostic.heartbeat",
586
- webhooks: {
587
- received: webhookStats.received,
588
- processed: webhookStats.processed,
589
- errors: webhookStats.errors
590
- },
591
- active: activeCount,
592
- waiting: waitingCount,
593
- queued: totalQueued
594
- });
595
- for (const [, state] of diagnosticSessionStates) {
596
- const ageMs = now - state.lastActivity;
597
- if (state.state === "processing" && ageMs > 12e4) logSessionStuck({
598
- sessionId: state.sessionId,
599
- sessionKey: state.sessionKey,
600
- state: state.state,
601
- ageMs
602
- });
603
- }
604
- }, 3e4);
605
- heartbeatInterval.unref?.();
606
- }
607
- function stopDiagnosticHeartbeat() {
608
- if (heartbeatInterval) {
609
- clearInterval(heartbeatInterval);
610
- heartbeatInterval = null;
611
- }
612
- }
613
-
614
- //#endregion
615
- //#region src/process/command-queue.ts
616
- /**
617
- * Dedicated error type thrown when a queued command is rejected because
618
- * its lane was cleared. Callers that fire-and-forget enqueued tasks can
619
- * catch (or ignore) this specific type to avoid unhandled-rejection noise.
620
- */
621
- var CommandLaneClearedError = class extends Error {
622
- constructor(lane) {
623
- super(lane ? `Command lane "${lane}" cleared` : "Command lane cleared");
624
- this.name = "CommandLaneClearedError";
625
- }
626
- };
627
- const lanes = /* @__PURE__ */ new Map();
628
- let nextTaskId = 1;
629
- function getLaneState(lane) {
630
- const existing = lanes.get(lane);
631
- if (existing) return existing;
632
- const created = {
633
- lane,
634
- queue: [],
635
- activeTaskIds: /* @__PURE__ */ new Set(),
636
- maxConcurrent: 1,
637
- draining: false,
638
- generation: 0
639
- };
640
- lanes.set(lane, created);
641
- return created;
642
- }
643
- function completeTask(state, taskId, taskGeneration) {
644
- if (taskGeneration !== state.generation) return false;
645
- state.activeTaskIds.delete(taskId);
646
- return true;
647
- }
648
- function drainLane(lane) {
649
- const state = getLaneState(lane);
650
- if (state.draining) return;
651
- state.draining = true;
652
- const pump = () => {
653
- while (state.activeTaskIds.size < state.maxConcurrent && state.queue.length > 0) {
654
- const entry = state.queue.shift();
655
- const waitedMs = Date.now() - entry.enqueuedAt;
656
- if (waitedMs >= entry.warnAfterMs) {
657
- entry.onWait?.(waitedMs, state.queue.length);
658
- diag.warn(`lane wait exceeded: lane=${lane} waitedMs=${waitedMs} queueAhead=${state.queue.length}`);
659
- }
660
- logLaneDequeue(lane, waitedMs, state.queue.length);
661
- const taskId = nextTaskId++;
662
- const taskGeneration = state.generation;
663
- state.activeTaskIds.add(taskId);
664
- (async () => {
665
- const startTime = Date.now();
666
- try {
667
- const result = await entry.task();
668
- if (completeTask(state, taskId, taskGeneration)) {
669
- diag.debug(`lane task done: lane=${lane} durationMs=${Date.now() - startTime} active=${state.activeTaskIds.size} queued=${state.queue.length}`);
670
- pump();
671
- }
672
- entry.resolve(result);
673
- } catch (err) {
674
- const completedCurrentGeneration = completeTask(state, taskId, taskGeneration);
675
- if (!(lane.startsWith("auth-probe:") || lane.startsWith("session:probe-"))) diag.error(`lane task error: lane=${lane} durationMs=${Date.now() - startTime} error="${String(err)}"`);
676
- if (completedCurrentGeneration) pump();
677
- entry.reject(err);
678
- }
679
- })();
680
- }
681
- state.draining = false;
682
- };
683
- pump();
684
- }
685
- function setCommandLaneConcurrency(lane, maxConcurrent) {
686
- const cleaned = lane.trim() || CommandLane.Main;
687
- const state = getLaneState(cleaned);
688
- state.maxConcurrent = Math.max(1, Math.floor(maxConcurrent));
689
- drainLane(cleaned);
690
- }
691
- function getQueueSize(lane = CommandLane.Main) {
692
- const resolved = lane.trim() || CommandLane.Main;
693
- const state = lanes.get(resolved);
694
- if (!state) return 0;
695
- return state.queue.length + state.activeTaskIds.size;
696
- }
697
- function getTotalQueueSize() {
698
- let total = 0;
699
- for (const s of lanes.values()) total += s.queue.length + s.activeTaskIds.size;
700
- return total;
701
- }
702
- function clearCommandLane(lane = CommandLane.Main) {
703
- const cleaned = lane.trim() || CommandLane.Main;
704
- const state = lanes.get(cleaned);
705
- if (!state) return 0;
706
- const removed = state.queue.length;
707
- const pending = state.queue.splice(0);
708
- for (const entry of pending) entry.reject(new CommandLaneClearedError(cleaned));
709
- return removed;
710
- }
711
- /**
712
- * Reset all lane runtime state to idle. Used after SIGUSR1 in-process
713
- * restarts where interrupted tasks' finally blocks may not run, leaving
714
- * stale active task IDs that permanently block new work from draining.
715
- *
716
- * Bumps lane generation and clears execution counters so stale completions
717
- * from old in-flight tasks are ignored. Queued entries are intentionally
718
- * preserved — they represent pending user work that should still execute
719
- * after restart.
720
- *
721
- * After resetting, drains any lanes that still have queued entries so
722
- * preserved work is pumped immediately rather than waiting for a future
723
- * `enqueueCommandInLane()` call (which may never come).
724
- */
725
- function resetAllLanes() {
726
- const lanesToDrain = [];
727
- for (const state of lanes.values()) {
728
- state.generation += 1;
729
- state.activeTaskIds.clear();
730
- state.draining = false;
731
- if (state.queue.length > 0) lanesToDrain.push(state.lane);
732
- }
733
- for (const lane of lanesToDrain) drainLane(lane);
734
- }
735
- /**
736
- * Returns the total number of actively executing tasks across all lanes
737
- * (excludes queued-but-not-started entries).
738
- */
739
- function getActiveTaskCount() {
740
- let total = 0;
741
- for (const s of lanes.values()) total += s.activeTaskIds.size;
742
- return total;
743
- }
744
- /**
745
- * Wait for all currently active tasks across all lanes to finish.
746
- * Polls at a short interval; resolves when no tasks are active or
747
- * when `timeoutMs` elapses (whichever comes first).
748
- *
749
- * New tasks enqueued after this call are ignored — only tasks that are
750
- * already executing are waited on.
751
- */
752
- function waitForActiveTasks(timeoutMs) {
753
- const POLL_INTERVAL_MS = 50;
754
- const deadline = Date.now() + timeoutMs;
755
- const activeAtStart = /* @__PURE__ */ new Set();
756
- for (const state of lanes.values()) for (const taskId of state.activeTaskIds) activeAtStart.add(taskId);
757
- return new Promise((resolve) => {
758
- const check = () => {
759
- if (activeAtStart.size === 0) {
760
- resolve({ drained: true });
761
- return;
762
- }
763
- let hasPending = false;
764
- for (const state of lanes.values()) {
765
- for (const taskId of state.activeTaskIds) if (activeAtStart.has(taskId)) {
766
- hasPending = true;
767
- break;
768
- }
769
- if (hasPending) break;
770
- }
771
- if (!hasPending) {
772
- resolve({ drained: true });
773
- return;
774
- }
775
- if (Date.now() >= deadline) {
776
- resolve({ drained: false });
777
- return;
778
- }
779
- setTimeout(check, POLL_INTERVAL_MS);
780
- };
781
- check();
782
- });
783
- }
784
-
785
- //#endregion
786
- //#region src/auto-reply/reply/queue/state.ts
787
- const DEFAULT_QUEUE_DEBOUNCE_MS = 1e3;
788
- const DEFAULT_QUEUE_CAP = 20;
789
- const DEFAULT_QUEUE_DROP = "summarize";
790
- const FOLLOWUP_QUEUES = /* @__PURE__ */ new Map();
791
- function getFollowupQueue(key, settings) {
792
- const existing = FOLLOWUP_QUEUES.get(key);
793
- if (existing) {
794
- existing.mode = settings.mode;
795
- existing.debounceMs = typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : existing.debounceMs;
796
- existing.cap = typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : existing.cap;
797
- existing.dropPolicy = settings.dropPolicy ?? existing.dropPolicy;
798
- return existing;
799
- }
800
- const created = {
801
- items: [],
802
- draining: false,
803
- lastEnqueuedAt: 0,
804
- mode: settings.mode,
805
- debounceMs: typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : DEFAULT_QUEUE_DEBOUNCE_MS,
806
- cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : DEFAULT_QUEUE_CAP,
807
- dropPolicy: settings.dropPolicy ?? DEFAULT_QUEUE_DROP,
808
- droppedCount: 0,
809
- summaryLines: []
810
- };
811
- FOLLOWUP_QUEUES.set(key, created);
812
- return created;
813
- }
814
- function clearFollowupQueue(key) {
815
- const cleaned = key.trim();
816
- if (!cleaned) return 0;
817
- const queue = FOLLOWUP_QUEUES.get(cleaned);
818
- if (!queue) return 0;
819
- const cleared = queue.items.length + queue.droppedCount;
820
- queue.items.length = 0;
821
- queue.droppedCount = 0;
822
- queue.summaryLines = [];
823
- queue.lastRun = void 0;
824
- queue.lastEnqueuedAt = 0;
825
- FOLLOWUP_QUEUES.delete(cleaned);
826
- return cleared;
827
- }
828
-
829
- //#endregion
830
- //#region src/auto-reply/reply/queue/cleanup.ts
831
- function clearSessionQueues(keys) {
832
- const seen = /* @__PURE__ */ new Set();
833
- let followupCleared = 0;
834
- let laneCleared = 0;
835
- const clearedKeys = [];
836
- for (const key of keys) {
837
- const cleaned = key?.trim();
838
- if (!cleaned || seen.has(cleaned)) continue;
839
- seen.add(cleaned);
840
- clearedKeys.push(cleaned);
841
- followupCleared += clearFollowupQueue(cleaned);
842
- laneCleared += clearCommandLane(resolveEmbeddedSessionLane(cleaned));
843
- }
844
- return {
845
- followupCleared,
846
- laneCleared,
847
- keys: clearedKeys
848
- };
849
- }
850
-
851
- //#endregion
852
- //#region src/agents/identity.ts
853
- function resolveAgentIdentity(cfg, agentId) {
854
- return resolveAgentConfig(cfg, agentId)?.identity;
855
- }
856
- function resolveIdentityNamePrefix(cfg, agentId) {
857
- const name = resolveAgentIdentity(cfg, agentId)?.name?.trim();
858
- if (!name) return;
859
- return `[${name}]`;
860
- }
861
- /** Returns just the identity name (without brackets) for template context. */
862
- function resolveIdentityName(cfg, agentId) {
863
- return resolveAgentIdentity(cfg, agentId)?.name?.trim() || void 0;
864
- }
865
- function resolveMessagePrefix(cfg, agentId, opts) {
866
- const configured = opts?.configured ?? cfg.messages?.messagePrefix;
867
- if (configured !== void 0) return configured;
868
- if (opts?.hasAllowFrom === true) return "";
869
- return resolveIdentityNamePrefix(cfg, agentId) ?? opts?.fallback ?? "[anima]";
870
- }
871
- /** Helper to extract a channel config value by dynamic key. */
872
- function getChannelConfig(cfg, channel) {
873
- const value = cfg.channels?.[channel];
874
- return typeof value === "object" && value !== null ? value : void 0;
875
- }
876
- function resolveResponsePrefix(cfg, agentId, opts) {
877
- if (opts?.channel && opts?.accountId) {
878
- const accountPrefix = (getChannelConfig(cfg, opts.channel)?.accounts)?.[opts.accountId]?.responsePrefix;
879
- if (accountPrefix !== void 0) {
880
- if (accountPrefix === "auto") return resolveIdentityNamePrefix(cfg, agentId);
881
- return accountPrefix;
882
- }
883
- }
884
- if (opts?.channel) {
885
- const channelPrefix = getChannelConfig(cfg, opts.channel)?.responsePrefix;
886
- if (channelPrefix !== void 0) {
887
- if (channelPrefix === "auto") return resolveIdentityNamePrefix(cfg, agentId);
888
- return channelPrefix;
889
- }
890
- }
891
- const configured = cfg.messages?.responsePrefix;
892
- if (configured !== void 0) {
893
- if (configured === "auto") return resolveIdentityNamePrefix(cfg, agentId);
894
- return configured;
895
- }
896
- }
897
- function resolveEffectiveMessagesConfig(cfg, agentId, opts) {
898
- return {
899
- messagePrefix: resolveMessagePrefix(cfg, agentId, {
900
- hasAllowFrom: opts?.hasAllowFrom,
901
- fallback: opts?.fallbackMessagePrefix
902
- }),
903
- responsePrefix: resolveResponsePrefix(cfg, agentId, {
904
- channel: opts?.channel,
905
- accountId: opts?.accountId
906
- })
907
- };
908
- }
909
- function resolveHumanDelayConfig(cfg, agentId) {
910
- const defaults = cfg.agents?.defaults?.humanDelay;
911
- const overrides = resolveAgentConfig(cfg, agentId)?.humanDelay;
912
- if (!defaults && !overrides) return;
913
- return {
914
- mode: overrides?.mode ?? defaults?.mode,
915
- minMs: overrides?.minMs ?? defaults?.minMs,
916
- maxMs: overrides?.maxMs ?? defaults?.maxMs
917
- };
918
- }
919
-
920
- //#endregion
921
- //#region src/auto-reply/reply/line-directives.ts
922
- /**
923
- * Parse LINE-specific directives from text and extract them into ReplyPayload fields.
924
- *
925
- * Supported directives:
926
- * - [[quick_replies: option1, option2, option3]]
927
- * - [[location: title | address | latitude | longitude]]
928
- * - [[confirm: question | yes_label | no_label]]
929
- * - [[buttons: title | text | btn1:data1, btn2:data2]]
930
- * - [[media_player: title | artist | source | imageUrl | playing/paused]]
931
- * - [[event: title | date | time | location | description]]
932
- * - [[agenda: title | event1_title:event1_time, event2_title:event2_time, ...]]
933
- * - [[device: name | type | status | ctrl1:data1, ctrl2:data2]]
934
- * - [[appletv_remote: name | status]]
935
- *
936
- * Returns the modified payload with directives removed from text and fields populated.
937
- */
938
- function parseLineDirectives(payload) {
939
- let text = payload.text;
940
- if (!text) return payload;
941
- const result = { ...payload };
942
- const lineData = { ...result.channelData?.line };
943
- const toSlug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "device";
944
- const lineActionData = (action, extras) => {
945
- const base = [`line.action=${encodeURIComponent(action)}`];
946
- if (extras) for (const [key, value] of Object.entries(extras)) base.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
947
- return base.join("&");
948
- };
949
- const quickRepliesMatch = text.match(/\[\[quick_replies:\s*([^\]]+)\]\]/i);
950
- if (quickRepliesMatch) {
951
- const options = quickRepliesMatch[1].split(",").map((s) => s.trim()).filter(Boolean);
952
- if (options.length > 0) lineData.quickReplies = [...lineData.quickReplies || [], ...options];
953
- text = text.replace(quickRepliesMatch[0], "").trim();
954
- }
955
- const locationMatch = text.match(/\[\[location:\s*([^\]]+)\]\]/i);
956
- if (locationMatch && !lineData.location) {
957
- const parts = locationMatch[1].split("|").map((s) => s.trim());
958
- if (parts.length >= 4) {
959
- const [title, address, latStr, lonStr] = parts;
960
- const latitude = parseFloat(latStr);
961
- const longitude = parseFloat(lonStr);
962
- if (!isNaN(latitude) && !isNaN(longitude)) lineData.location = {
963
- title: title || "Location",
964
- address: address || "",
965
- latitude,
966
- longitude
967
- };
968
- }
969
- text = text.replace(locationMatch[0], "").trim();
970
- }
971
- const confirmMatch = text.match(/\[\[confirm:\s*([^\]]+)\]\]/i);
972
- if (confirmMatch && !lineData.templateMessage) {
973
- const parts = confirmMatch[1].split("|").map((s) => s.trim());
974
- if (parts.length >= 3) {
975
- const [question, yesPart, noPart] = parts;
976
- const [yesLabel, yesData] = yesPart.includes(":") ? yesPart.split(":").map((s) => s.trim()) : [yesPart, yesPart.toLowerCase()];
977
- const [noLabel, noData] = noPart.includes(":") ? noPart.split(":").map((s) => s.trim()) : [noPart, noPart.toLowerCase()];
978
- lineData.templateMessage = {
979
- type: "confirm",
980
- text: question,
981
- confirmLabel: yesLabel,
982
- confirmData: yesData,
983
- cancelLabel: noLabel,
984
- cancelData: noData,
985
- altText: question
986
- };
987
- }
988
- text = text.replace(confirmMatch[0], "").trim();
989
- }
990
- const buttonsMatch = text.match(/\[\[buttons:\s*([^\]]+)\]\]/i);
991
- if (buttonsMatch && !lineData.templateMessage) {
992
- const parts = buttonsMatch[1].split("|").map((s) => s.trim());
993
- if (parts.length >= 3) {
994
- const [title, bodyText, actionsStr] = parts;
995
- const actions = actionsStr.split(",").map((actionStr) => {
996
- const trimmed = actionStr.trim();
997
- const colonIndex = (() => {
998
- const index = trimmed.indexOf(":");
999
- if (index === -1) return -1;
1000
- const lower = trimmed.toLowerCase();
1001
- if (lower.startsWith("http://") || lower.startsWith("https://")) return -1;
1002
- return index;
1003
- })();
1004
- let label;
1005
- let data;
1006
- if (colonIndex === -1) {
1007
- label = trimmed;
1008
- data = trimmed;
1009
- } else {
1010
- label = trimmed.slice(0, colonIndex).trim();
1011
- data = trimmed.slice(colonIndex + 1).trim();
1012
- }
1013
- if (data.startsWith("http://") || data.startsWith("https://")) return {
1014
- type: "uri",
1015
- label,
1016
- uri: data
1017
- };
1018
- if (data.includes("=")) return {
1019
- type: "postback",
1020
- label,
1021
- data
1022
- };
1023
- return {
1024
- type: "message",
1025
- label,
1026
- data: data || label
1027
- };
1028
- });
1029
- if (actions.length > 0) lineData.templateMessage = {
1030
- type: "buttons",
1031
- title,
1032
- text: bodyText,
1033
- actions: actions.slice(0, 4),
1034
- altText: `${title}: ${bodyText}`
1035
- };
1036
- }
1037
- text = text.replace(buttonsMatch[0], "").trim();
1038
- }
1039
- const mediaPlayerMatch = text.match(/\[\[media_player:\s*([^\]]+)\]\]/i);
1040
- if (mediaPlayerMatch && !lineData.flexMessage) {
1041
- const parts = mediaPlayerMatch[1].split("|").map((s) => s.trim());
1042
- if (parts.length >= 1) {
1043
- const [title, artist, source, imageUrl, statusStr] = parts;
1044
- const isPlaying = statusStr?.toLowerCase() === "playing";
1045
- const validImageUrl = imageUrl?.startsWith("https://") ? imageUrl : void 0;
1046
- const deviceKey = toSlug(source || title || "media");
1047
- const card = createMediaPlayerCard({
1048
- title: title || "Unknown Track",
1049
- subtitle: artist || void 0,
1050
- source: source || void 0,
1051
- imageUrl: validImageUrl,
1052
- isPlaying: statusStr ? isPlaying : void 0,
1053
- controls: {
1054
- previous: { data: lineActionData("previous", { "line.device": deviceKey }) },
1055
- play: { data: lineActionData("play", { "line.device": deviceKey }) },
1056
- pause: { data: lineActionData("pause", { "line.device": deviceKey }) },
1057
- next: { data: lineActionData("next", { "line.device": deviceKey }) }
1058
- }
1059
- });
1060
- lineData.flexMessage = {
1061
- altText: `🎵 ${title}${artist ? ` - ${artist}` : ""}`,
1062
- contents: card
1063
- };
1064
- }
1065
- text = text.replace(mediaPlayerMatch[0], "").trim();
1066
- }
1067
- const eventMatch = text.match(/\[\[event:\s*([^\]]+)\]\]/i);
1068
- if (eventMatch && !lineData.flexMessage) {
1069
- const parts = eventMatch[1].split("|").map((s) => s.trim());
1070
- if (parts.length >= 2) {
1071
- const [title, date, time, location, description] = parts;
1072
- const card = createEventCard({
1073
- title: title || "Event",
1074
- date: date || "TBD",
1075
- time: time || void 0,
1076
- location: location || void 0,
1077
- description: description || void 0
1078
- });
1079
- lineData.flexMessage = {
1080
- altText: `📅 ${title} - ${date}${time ? ` ${time}` : ""}`,
1081
- contents: card
1082
- };
1083
- }
1084
- text = text.replace(eventMatch[0], "").trim();
1085
- }
1086
- const appleTvMatch = text.match(/\[\[appletv_remote:\s*([^\]]+)\]\]/i);
1087
- if (appleTvMatch && !lineData.flexMessage) {
1088
- const parts = appleTvMatch[1].split("|").map((s) => s.trim());
1089
- if (parts.length >= 1) {
1090
- const [deviceName, status] = parts;
1091
- const deviceKey = toSlug(deviceName || "apple_tv");
1092
- const card = createAppleTvRemoteCard({
1093
- deviceName: deviceName || "Apple TV",
1094
- status: status || void 0,
1095
- actionData: {
1096
- up: lineActionData("up", { "line.device": deviceKey }),
1097
- down: lineActionData("down", { "line.device": deviceKey }),
1098
- left: lineActionData("left", { "line.device": deviceKey }),
1099
- right: lineActionData("right", { "line.device": deviceKey }),
1100
- select: lineActionData("select", { "line.device": deviceKey }),
1101
- menu: lineActionData("menu", { "line.device": deviceKey }),
1102
- home: lineActionData("home", { "line.device": deviceKey }),
1103
- play: lineActionData("play", { "line.device": deviceKey }),
1104
- pause: lineActionData("pause", { "line.device": deviceKey }),
1105
- volumeUp: lineActionData("volume_up", { "line.device": deviceKey }),
1106
- volumeDown: lineActionData("volume_down", { "line.device": deviceKey }),
1107
- mute: lineActionData("mute", { "line.device": deviceKey })
1108
- }
1109
- });
1110
- lineData.flexMessage = {
1111
- altText: `📺 ${deviceName || "Apple TV"} Remote`,
1112
- contents: card
1113
- };
1114
- }
1115
- text = text.replace(appleTvMatch[0], "").trim();
1116
- }
1117
- const agendaMatch = text.match(/\[\[agenda:\s*([^\]]+)\]\]/i);
1118
- if (agendaMatch && !lineData.flexMessage) {
1119
- const parts = agendaMatch[1].split("|").map((s) => s.trim());
1120
- if (parts.length >= 2) {
1121
- const [title, eventsStr] = parts;
1122
- const events = eventsStr.split(",").map((eventStr) => {
1123
- const trimmed = eventStr.trim();
1124
- const colonIdx = trimmed.lastIndexOf(":");
1125
- if (colonIdx > 0) return {
1126
- title: trimmed.slice(0, colonIdx).trim(),
1127
- time: trimmed.slice(colonIdx + 1).trim()
1128
- };
1129
- return { title: trimmed };
1130
- });
1131
- const card = createAgendaCard({
1132
- title: title || "Agenda",
1133
- events
1134
- });
1135
- lineData.flexMessage = {
1136
- altText: `📋 ${title} (${events.length} events)`,
1137
- contents: card
1138
- };
1139
- }
1140
- text = text.replace(agendaMatch[0], "").trim();
1141
- }
1142
- const deviceMatch = text.match(/\[\[device:\s*([^\]]+)\]\]/i);
1143
- if (deviceMatch && !lineData.flexMessage) {
1144
- const parts = deviceMatch[1].split("|").map((s) => s.trim());
1145
- if (parts.length >= 1) {
1146
- const [deviceName, deviceType, status, controlsStr] = parts;
1147
- const deviceKey = toSlug(deviceName || "device");
1148
- const controls = controlsStr ? controlsStr.split(",").map((ctrlStr) => {
1149
- const [label, data] = ctrlStr.split(":").map((s) => s.trim());
1150
- return {
1151
- label,
1152
- data: lineActionData(data || label.toLowerCase().replace(/\s+/g, "_"), { "line.device": deviceKey })
1153
- };
1154
- }) : [];
1155
- const card = createDeviceControlCard({
1156
- deviceName: deviceName || "Device",
1157
- deviceType: deviceType || void 0,
1158
- status: status || void 0,
1159
- controls
1160
- });
1161
- lineData.flexMessage = {
1162
- altText: `📱 ${deviceName}${status ? `: ${status}` : ""}`,
1163
- contents: card
1164
- };
1165
- }
1166
- text = text.replace(deviceMatch[0], "").trim();
1167
- }
1168
- text = text.replace(/\n{3,}/g, "\n\n").trim();
1169
- result.text = text || void 0;
1170
- if (Object.keys(lineData).length > 0) result.channelData = {
1171
- ...result.channelData,
1172
- line: lineData
1173
- };
1174
- return result;
1175
- }
1176
- /**
1177
- * Check if text contains any LINE directives
1178
- */
1179
- function hasLineDirectives(text) {
1180
- return /\[\[(quick_replies|location|confirm|buttons|media_player|event|agenda|device|appletv_remote):/i.test(text);
1181
- }
1182
-
1183
- //#endregion
1184
- //#region src/auto-reply/reply/response-prefix-template.ts
1185
- const TEMPLATE_VAR_PATTERN = /\{([a-zA-Z][a-zA-Z0-9.]*)\}/g;
1186
- /**
1187
- * Interpolate template variables in a response prefix string.
1188
- *
1189
- * @param template - The template string with `{variable}` placeholders
1190
- * @param context - Context object with values for interpolation
1191
- * @returns The interpolated string, or undefined if template is undefined
1192
- *
1193
- * @example
1194
- * resolveResponsePrefixTemplate("[{model} | think:{thinkingLevel}]", {
1195
- * model: "gpt-5.2",
1196
- * thinkingLevel: "high"
1197
- * })
1198
- * // Returns: "[gpt-5.2 | think:high]"
1199
- */
1200
- function resolveResponsePrefixTemplate(template, context) {
1201
- if (!template) return;
1202
- return template.replace(TEMPLATE_VAR_PATTERN, (match, varName) => {
1203
- switch (varName.toLowerCase()) {
1204
- case "model": return context.model ?? match;
1205
- case "modelfull": return context.modelFull ?? match;
1206
- case "provider": return context.provider ?? match;
1207
- case "thinkinglevel":
1208
- case "think": return context.thinkingLevel ?? match;
1209
- case "identity.name":
1210
- case "identityname": return context.identityName ?? match;
1211
- default: return match;
1212
- }
1213
- });
1214
- }
1215
- /**
1216
- * Extract short model name from a full model string.
1217
- *
1218
- * Strips:
1219
- * - Provider prefix (e.g., "openai/" from "openai/gpt-5.2")
1220
- * - Date suffixes (e.g., "-20260205" from "claude-opus-4-6-20260205")
1221
- * - Common version suffixes (e.g., "-latest")
1222
- *
1223
- * @example
1224
- * extractShortModelName("openai-codex/gpt-5.2") // "gpt-5.2"
1225
- * extractShortModelName("claude-opus-4-6-20260205") // "claude-opus-4-6"
1226
- * extractShortModelName("gpt-5.2-latest") // "gpt-5.2"
1227
- */
1228
- function extractShortModelName(fullModel) {
1229
- const slash = fullModel.lastIndexOf("/");
1230
- return (slash >= 0 ? fullModel.slice(slash + 1) : fullModel).replace(/-\d{8}$/, "").replace(/-latest$/, "");
1231
- }
1232
-
1233
- //#endregion
1234
- //#region src/auto-reply/reply/normalize-reply.ts
1235
- function normalizeReplyPayload(payload, opts = {}) {
1236
- const hasMedia = Boolean(payload.mediaUrl || (payload.mediaUrls?.length ?? 0) > 0);
1237
- const hasChannelData = Boolean(payload.channelData && Object.keys(payload.channelData).length > 0);
1238
- const trimmed = payload.text?.trim() ?? "";
1239
- if (!trimmed && !hasMedia && !hasChannelData) {
1240
- opts.onSkip?.("empty");
1241
- return null;
1242
- }
1243
- const silentToken = opts.silentToken ?? SILENT_REPLY_TOKEN;
1244
- let text = payload.text ?? void 0;
1245
- if (text && isSilentReplyText(text, silentToken)) {
1246
- if (!hasMedia && !hasChannelData) {
1247
- opts.onSkip?.("silent");
1248
- return null;
1249
- }
1250
- text = "";
1251
- }
1252
- if (text && !trimmed) text = "";
1253
- if ((opts.stripHeartbeat ?? true) && text?.includes(HEARTBEAT_TOKEN)) {
1254
- const stripped = stripHeartbeatToken(text, { mode: "message" });
1255
- if (stripped.didStrip) opts.onHeartbeatStrip?.();
1256
- if (stripped.shouldSkip && !hasMedia && !hasChannelData) {
1257
- opts.onSkip?.("heartbeat");
1258
- return null;
1259
- }
1260
- text = stripped.text;
1261
- }
1262
- if (text) text = sanitizeUserFacingText$1(text, { errorContext: Boolean(payload.isError) });
1263
- if (!text?.trim() && !hasMedia && !hasChannelData) {
1264
- opts.onSkip?.("empty");
1265
- return null;
1266
- }
1267
- let enrichedPayload = {
1268
- ...payload,
1269
- text
1270
- };
1271
- if (text && hasLineDirectives(text)) {
1272
- enrichedPayload = parseLineDirectives(enrichedPayload);
1273
- text = enrichedPayload.text;
1274
- }
1275
- const effectivePrefix = opts.responsePrefixContext ? resolveResponsePrefixTemplate(opts.responsePrefix, opts.responsePrefixContext) : opts.responsePrefix;
1276
- if (effectivePrefix && text && text.trim() !== HEARTBEAT_TOKEN && !text.startsWith(effectivePrefix)) text = `${effectivePrefix} ${text}`;
1277
- return {
1278
- ...enrichedPayload,
1279
- text
1280
- };
1281
- }
1282
-
1283
- //#endregion
1284
- //#region src/auto-reply/reply/route-reply.ts
1285
- /**
1286
- * Routes a reply payload to the specified channel.
1287
- *
1288
- * This function provides a unified interface for sending messages to any
1289
- * supported provider. It's used by the followup queue to route replies
1290
- * back to the originating channel when OriginatingChannel/OriginatingTo
1291
- * are set.
1292
- */
1293
- async function routeReply(params) {
1294
- const { payload, channel, to, accountId, threadId, cfg, abortSignal } = params;
1295
- const normalizedChannel = normalizeMessageChannel(channel);
1296
- const normalized = normalizeReplyPayload(payload, { responsePrefix: params.sessionKey ? resolveEffectiveMessagesConfig(cfg, resolveSessionAgentId({
1297
- sessionKey: params.sessionKey,
1298
- config: cfg
1299
- }), {
1300
- channel: normalizedChannel,
1301
- accountId
1302
- }).responsePrefix : cfg.messages?.responsePrefix === "auto" ? void 0 : cfg.messages?.responsePrefix });
1303
- if (!normalized) return { ok: true };
1304
- let text = normalized.text ?? "";
1305
- let mediaUrls = (normalized.mediaUrls?.filter(Boolean) ?? []).length ? normalized.mediaUrls?.filter(Boolean) : normalized.mediaUrl ? [normalized.mediaUrl] : [];
1306
- const replyToId = normalized.replyToId;
1307
- if (!text.trim() && mediaUrls.length === 0) return { ok: true };
1308
- if (channel === INTERNAL_MESSAGE_CHANNEL) return {
1309
- ok: false,
1310
- error: "Webchat routing not supported for queued replies"
1311
- };
1312
- const channelId = normalizeChannelId(channel) ?? null;
1313
- if (!channelId) return {
1314
- ok: false,
1315
- error: `Unknown channel: ${String(channel)}`
1316
- };
1317
- if (abortSignal?.aborted) return {
1318
- ok: false,
1319
- error: "Reply routing aborted"
1320
- };
1321
- const resolvedReplyToId = replyToId ?? (channelId === "slack" && threadId != null && threadId !== "" ? String(threadId) : void 0);
1322
- const resolvedThreadId = channelId === "slack" ? null : threadId ?? null;
1323
- try {
1324
- const { deliverOutboundPayloads } = await import("./deliver-LiY5oL52.js").then((n) => n.n);
1325
- return {
1326
- ok: true,
1327
- messageId: (await deliverOutboundPayloads({
1328
- cfg,
1329
- channel: channelId,
1330
- to,
1331
- accountId: accountId ?? void 0,
1332
- payloads: [normalized],
1333
- replyToId: resolvedReplyToId ?? null,
1334
- threadId: resolvedThreadId,
1335
- abortSignal,
1336
- mirror: params.mirror !== false && params.sessionKey ? {
1337
- sessionKey: params.sessionKey,
1338
- agentId: resolveSessionAgentId({
1339
- sessionKey: params.sessionKey,
1340
- config: cfg
1341
- }),
1342
- text,
1343
- mediaUrls
1344
- } : void 0
1345
- })).at(-1)?.messageId
1346
- };
1347
- } catch (err) {
1348
- return {
1349
- ok: false,
1350
- error: `Failed to route reply to ${channel}: ${err instanceof Error ? err.message : String(err)}`
1351
- };
1352
- }
1353
- }
1354
- /**
1355
- * Checks if a channel type is routable via routeReply.
1356
- *
1357
- * Some channels (webchat) require special handling and cannot be routed through
1358
- * this generic interface.
1359
- */
1360
- function isRoutableChannel(channel) {
1361
- if (!channel || channel === INTERNAL_MESSAGE_CHANNEL) return false;
1362
- return normalizeChannelId(channel) !== null;
1363
- }
1364
-
1365
- //#endregion
1366
- //#region src/auto-reply/reply/queue/drain.ts
1367
- function previewQueueSummaryPrompt(queue) {
1368
- return buildQueueSummaryPrompt({
1369
- state: {
1370
- dropPolicy: queue.dropPolicy,
1371
- droppedCount: queue.droppedCount,
1372
- summaryLines: [...queue.summaryLines]
1373
- },
1374
- noun: "message"
1375
- });
1376
- }
1377
- function clearQueueSummaryState(queue) {
1378
- queue.droppedCount = 0;
1379
- queue.summaryLines = [];
1380
- }
1381
- function scheduleFollowupDrain(key, runFollowup) {
1382
- const queue = FOLLOWUP_QUEUES.get(key);
1383
- if (!queue || queue.draining) return;
1384
- queue.draining = true;
1385
- (async () => {
1386
- try {
1387
- let forceIndividualCollect = false;
1388
- while (queue.items.length > 0 || queue.droppedCount > 0) {
1389
- await waitForQueueDebounce(queue);
1390
- if (queue.mode === "collect") {
1391
- if (forceIndividualCollect) {
1392
- const next = queue.items[0];
1393
- if (!next) break;
1394
- await runFollowup(next);
1395
- queue.items.shift();
1396
- continue;
1397
- }
1398
- if (hasCrossChannelItems(queue.items, (item) => {
1399
- const channel = item.originatingChannel;
1400
- const to = item.originatingTo;
1401
- const accountId = item.originatingAccountId;
1402
- const threadId = item.originatingThreadId;
1403
- if (!channel && !to && !accountId && threadId == null) return {};
1404
- if (!isRoutableChannel(channel) || !to) return { cross: true };
1405
- return { key: [
1406
- channel,
1407
- to,
1408
- accountId || "",
1409
- threadId != null ? String(threadId) : ""
1410
- ].join("|") };
1411
- })) {
1412
- forceIndividualCollect = true;
1413
- const next = queue.items[0];
1414
- if (!next) break;
1415
- await runFollowup(next);
1416
- queue.items.shift();
1417
- continue;
1418
- }
1419
- const items = queue.items.slice();
1420
- const summary = previewQueueSummaryPrompt(queue);
1421
- const run = items.at(-1)?.run ?? queue.lastRun;
1422
- if (!run) break;
1423
- const originatingChannel = items.find((i) => i.originatingChannel)?.originatingChannel;
1424
- const originatingTo = items.find((i) => i.originatingTo)?.originatingTo;
1425
- const originatingAccountId = items.find((i) => i.originatingAccountId)?.originatingAccountId;
1426
- const originatingThreadId = items.find((i) => i.originatingThreadId != null)?.originatingThreadId;
1427
- await runFollowup({
1428
- prompt: buildCollectPrompt({
1429
- title: "[Queued messages while agent was busy]",
1430
- items,
1431
- summary,
1432
- renderItem: (item, idx) => `---\nQueued #${idx + 1}\n${item.prompt}`.trim()
1433
- }),
1434
- run,
1435
- enqueuedAt: Date.now(),
1436
- originatingChannel,
1437
- originatingTo,
1438
- originatingAccountId,
1439
- originatingThreadId
1440
- });
1441
- queue.items.splice(0, items.length);
1442
- if (summary) clearQueueSummaryState(queue);
1443
- continue;
1444
- }
1445
- const summaryPrompt = previewQueueSummaryPrompt(queue);
1446
- if (summaryPrompt) {
1447
- const run = queue.lastRun;
1448
- if (!run) break;
1449
- if (!queue.items[0]) break;
1450
- await runFollowup({
1451
- prompt: summaryPrompt,
1452
- run,
1453
- enqueuedAt: Date.now()
1454
- });
1455
- queue.items.shift();
1456
- clearQueueSummaryState(queue);
1457
- continue;
1458
- }
1459
- const next = queue.items[0];
1460
- if (!next) break;
1461
- await runFollowup(next);
1462
- queue.items.shift();
1463
- }
1464
- } catch (err) {
1465
- queue.lastEnqueuedAt = Date.now();
1466
- defaultRuntime.error?.(`followup queue drain failed for ${key}: ${String(err)}`);
1467
- } finally {
1468
- queue.draining = false;
1469
- if (queue.items.length === 0 && queue.droppedCount === 0) FOLLOWUP_QUEUES.delete(key);
1470
- else scheduleFollowupDrain(key, runFollowup);
1471
- }
1472
- })();
1473
- }
1474
-
1475
- //#endregion
1476
- //#region src/auto-reply/reply/queue/enqueue.ts
1477
- function isRunAlreadyQueued(run, items, allowPromptFallback = false) {
1478
- const hasSameRouting = (item) => item.originatingChannel === run.originatingChannel && item.originatingTo === run.originatingTo && item.originatingAccountId === run.originatingAccountId && item.originatingThreadId === run.originatingThreadId;
1479
- const messageId = run.messageId?.trim();
1480
- if (messageId) return items.some((item) => item.messageId?.trim() === messageId && hasSameRouting(item));
1481
- if (!allowPromptFallback) return false;
1482
- return items.some((item) => item.prompt === run.prompt && hasSameRouting(item));
1483
- }
1484
- function enqueueFollowupRun(key, run, settings, dedupeMode = "message-id") {
1485
- const queue = getFollowupQueue(key, settings);
1486
- const dedupe = dedupeMode === "none" ? void 0 : (item, items) => isRunAlreadyQueued(item, items, dedupeMode === "prompt");
1487
- if (shouldSkipQueueItem({
1488
- item: run,
1489
- items: queue.items,
1490
- dedupe
1491
- })) return false;
1492
- queue.lastEnqueuedAt = Date.now();
1493
- queue.lastRun = run.run;
1494
- if (!applyQueueDropPolicy({
1495
- queue,
1496
- summarize: (item) => item.summaryLine?.trim() || item.prompt.trim()
1497
- })) return false;
1498
- queue.items.push(run);
1499
- return true;
1500
- }
1501
- function getFollowupQueueDepth(key) {
1502
- const cleaned = key.trim();
1503
- if (!cleaned) return 0;
1504
- const queue = FOLLOWUP_QUEUES.get(cleaned);
1505
- if (!queue) return 0;
1506
- return queue.items.length;
1507
- }
1508
-
1509
- //#endregion
1510
- //#region src/auto-reply/reply/queue/settings.ts
1511
- function defaultQueueModeForChannel(_channel) {
1512
- return "collect";
1513
- }
1514
- /** Resolve per-channel debounce override from debounceMsByChannel map. */
1515
- function resolveChannelDebounce(byChannel, channelKey) {
1516
- if (!channelKey || !byChannel) return;
1517
- const value = byChannel[channelKey];
1518
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
1519
- }
1520
- function resolvePluginDebounce(channelKey) {
1521
- if (!channelKey) return;
1522
- const value = getChannelPlugin(channelKey)?.defaults?.queue?.debounceMs;
1523
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
1524
- }
1525
- function resolveQueueSettings(params) {
1526
- const channelKey = params.channel?.trim().toLowerCase();
1527
- const queueCfg = params.cfg.messages?.queue;
1528
- const providerModeRaw = channelKey && queueCfg?.byChannel ? queueCfg.byChannel[channelKey] : void 0;
1529
- const resolvedMode = params.inlineMode ?? normalizeQueueMode(params.sessionEntry?.queueMode) ?? normalizeQueueMode(providerModeRaw) ?? normalizeQueueMode(queueCfg?.mode) ?? defaultQueueModeForChannel(channelKey);
1530
- const debounceRaw = params.inlineOptions?.debounceMs ?? params.sessionEntry?.queueDebounceMs ?? resolveChannelDebounce(queueCfg?.debounceMsByChannel, channelKey) ?? resolvePluginDebounce(channelKey) ?? queueCfg?.debounceMs ?? DEFAULT_QUEUE_DEBOUNCE_MS;
1531
- const capRaw = params.inlineOptions?.cap ?? params.sessionEntry?.queueCap ?? queueCfg?.cap ?? DEFAULT_QUEUE_CAP;
1532
- const dropRaw = params.inlineOptions?.dropPolicy ?? params.sessionEntry?.queueDrop ?? normalizeQueueDropPolicy(queueCfg?.drop) ?? DEFAULT_QUEUE_DROP;
1533
- return {
1534
- mode: resolvedMode,
1535
- debounceMs: typeof debounceRaw === "number" ? Math.max(0, debounceRaw) : void 0,
1536
- cap: typeof capRaw === "number" ? Math.max(1, Math.floor(capRaw)) : void 0,
1537
- dropPolicy: dropRaw
1538
- };
1539
- }
1540
-
1541
- //#endregion
1542
- //#region src/agents/subagent-depth.ts
1543
- function normalizeSpawnDepth(value) {
1544
- if (typeof value === "number") return Number.isInteger(value) && value >= 0 ? value : void 0;
1545
- if (typeof value === "string") {
1546
- const trimmed = value.trim();
1547
- if (!trimmed) return;
1548
- const numeric = Number(trimmed);
1549
- return Number.isInteger(numeric) && numeric >= 0 ? numeric : void 0;
1550
- }
1551
- }
1552
- function normalizeSessionKey(value) {
1553
- if (typeof value !== "string") return;
1554
- return value.trim() || void 0;
1555
- }
1556
- function readSessionStore(storePath) {
1557
- try {
1558
- const raw = fs.readFileSync(storePath, "utf-8");
1559
- const parsed = JSON5.parse(raw);
1560
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1561
- } catch {}
1562
- return {};
1563
- }
1564
- function buildKeyCandidates(rawKey, cfg) {
1565
- if (!cfg) return [rawKey];
1566
- if (rawKey === "global" || rawKey === "unknown") return [rawKey];
1567
- if (parseAgentSessionKey(rawKey)) return [rawKey];
1568
- const prefixed = `agent:${resolveDefaultAgentId(cfg)}:${rawKey}`;
1569
- return prefixed === rawKey ? [rawKey] : [rawKey, prefixed];
1570
- }
1571
- function findEntryBySessionId(store, sessionId) {
1572
- const normalizedSessionId = normalizeSessionKey(sessionId);
1573
- if (!normalizedSessionId) return;
1574
- for (const entry of Object.values(store)) {
1575
- const candidateSessionId = normalizeSessionKey(entry?.sessionId);
1576
- if (candidateSessionId && candidateSessionId === normalizedSessionId) return entry;
1577
- }
1578
- }
1579
- function resolveEntryForSessionKey(params) {
1580
- const candidates = buildKeyCandidates(params.sessionKey, params.cfg);
1581
- if (params.store) {
1582
- for (const key of candidates) {
1583
- const entry = params.store[key];
1584
- if (entry) return entry;
1585
- }
1586
- return findEntryBySessionId(params.store, params.sessionKey);
1587
- }
1588
- if (!params.cfg) return;
1589
- for (const key of candidates) {
1590
- const parsed = parseAgentSessionKey(key);
1591
- if (!parsed?.agentId) continue;
1592
- const storePath = resolveStorePath(params.cfg.session?.store, { agentId: parsed.agentId });
1593
- let store = params.cache.get(storePath);
1594
- if (!store) {
1595
- store = readSessionStore(storePath);
1596
- params.cache.set(storePath, store);
1597
- }
1598
- const entry = store[key] ?? findEntryBySessionId(store, params.sessionKey);
1599
- if (entry) return entry;
1600
- }
1601
- }
1602
- function getSubagentDepthFromSessionStore(sessionKey, opts) {
1603
- const raw = (sessionKey ?? "").trim();
1604
- const fallbackDepth = getSubagentDepth(raw);
1605
- if (!raw) return fallbackDepth;
1606
- const cache = /* @__PURE__ */ new Map();
1607
- const visited = /* @__PURE__ */ new Set();
1608
- const depthFromStore = (key) => {
1609
- const normalizedKey = normalizeSessionKey(key);
1610
- if (!normalizedKey) return;
1611
- if (visited.has(normalizedKey)) return;
1612
- visited.add(normalizedKey);
1613
- const entry = resolveEntryForSessionKey({
1614
- sessionKey: normalizedKey,
1615
- cfg: opts?.cfg,
1616
- store: opts?.store,
1617
- cache
1618
- });
1619
- const storedDepth = normalizeSpawnDepth(entry?.spawnDepth);
1620
- if (storedDepth !== void 0) return storedDepth;
1621
- const spawnedBy = normalizeSessionKey(entry?.spawnedBy);
1622
- if (!spawnedBy) return;
1623
- const parentDepth = depthFromStore(spawnedBy);
1624
- if (parentDepth !== void 0) return parentDepth + 1;
1625
- return getSubagentDepth(spawnedBy) + 1;
1626
- };
1627
- return depthFromStore(raw) ?? fallbackDepth;
1628
- }
1629
-
1630
- //#endregion
1631
- //#region src/agents/tools/sessions-helpers.ts
1632
- function normalizeKey(value) {
1633
- const trimmed = value?.trim();
1634
- return trimmed ? trimmed : void 0;
1635
- }
1636
- function resolveMainSessionAlias(cfg) {
1637
- const mainKey = normalizeMainKey(cfg.session?.mainKey);
1638
- const scope = cfg.session?.scope ?? "per-sender";
1639
- return {
1640
- mainKey,
1641
- alias: scope === "global" ? "global" : mainKey,
1642
- scope
1643
- };
1644
- }
1645
- function resolveDisplaySessionKey(params) {
1646
- if (params.key === params.alias) return "main";
1647
- if (params.key === params.mainKey) return "main";
1648
- return params.key;
1649
- }
1650
- function resolveInternalSessionKey(params) {
1651
- if (params.key === "main") return params.alias;
1652
- return params.key;
1653
- }
1654
- function createAgentToAgentPolicy(cfg) {
1655
- const routingA2A = cfg.tools?.agentToAgent;
1656
- const enabled = routingA2A?.enabled === true;
1657
- const allowPatterns = Array.isArray(routingA2A?.allow) ? routingA2A.allow : [];
1658
- const matchesAllow = (agentId) => {
1659
- if (allowPatterns.length === 0) return true;
1660
- return allowPatterns.some((pattern) => {
1661
- const raw = String(pattern ?? "").trim();
1662
- if (!raw) return false;
1663
- if (raw === "*") return true;
1664
- if (!raw.includes("*")) return raw === agentId;
1665
- const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1666
- return new RegExp(`^${escaped.replaceAll("\\*", ".*")}$`, "i").test(agentId);
1667
- });
1668
- };
1669
- const isAllowed = (requesterAgentId, targetAgentId) => {
1670
- if (requesterAgentId === targetAgentId) return true;
1671
- if (!enabled) return false;
1672
- return matchesAllow(requesterAgentId) && matchesAllow(targetAgentId);
1673
- };
1674
- return {
1675
- enabled,
1676
- matchesAllow,
1677
- isAllowed
1678
- };
1679
- }
1680
- 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;
1681
- function looksLikeSessionId(value) {
1682
- return SESSION_ID_RE.test(value.trim());
1683
- }
1684
- function looksLikeSessionKey(value) {
1685
- const raw = value.trim();
1686
- if (!raw) return false;
1687
- if (raw === "main" || raw === "global" || raw === "unknown") return true;
1688
- if (isAcpSessionKey(raw)) return true;
1689
- if (raw.startsWith("agent:")) return true;
1690
- if (raw.startsWith("cron:") || raw.startsWith("hook:")) return true;
1691
- if (raw.startsWith("node-") || raw.startsWith("node:")) return true;
1692
- if (raw.includes(":group:") || raw.includes(":channel:")) return true;
1693
- return false;
1694
- }
1695
- function shouldResolveSessionIdInput(value) {
1696
- return looksLikeSessionId(value) || !looksLikeSessionKey(value);
1697
- }
1698
- async function resolveSessionKeyFromSessionId(params) {
1699
- try {
1700
- const result = await callGateway({
1701
- method: "sessions.resolve",
1702
- params: {
1703
- sessionId: params.sessionId,
1704
- spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0,
1705
- includeGlobal: !params.restrictToSpawned,
1706
- includeUnknown: !params.restrictToSpawned
1707
- }
1708
- });
1709
- const key = typeof result?.key === "string" ? result.key.trim() : "";
1710
- if (!key) throw new Error(`Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`);
1711
- return {
1712
- ok: true,
1713
- key,
1714
- displayKey: resolveDisplaySessionKey({
1715
- key,
1716
- alias: params.alias,
1717
- mainKey: params.mainKey
1718
- }),
1719
- resolvedViaSessionId: true
1720
- };
1721
- } catch (err) {
1722
- if (params.restrictToSpawned) return {
1723
- ok: false,
1724
- status: "forbidden",
1725
- error: `Session not visible from this sandboxed agent session: ${params.sessionId}`
1726
- };
1727
- return {
1728
- ok: false,
1729
- status: "error",
1730
- error: (err instanceof Error ? err.message : String(err)) || `Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`
1731
- };
1732
- }
1733
- }
1734
- async function resolveSessionKeyFromKey(params) {
1735
- try {
1736
- const result = await callGateway({
1737
- method: "sessions.resolve",
1738
- params: {
1739
- key: params.key,
1740
- spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0
1741
- }
1742
- });
1743
- const key = typeof result?.key === "string" ? result.key.trim() : "";
1744
- if (!key) return null;
1745
- return {
1746
- ok: true,
1747
- key,
1748
- displayKey: resolveDisplaySessionKey({
1749
- key,
1750
- alias: params.alias,
1751
- mainKey: params.mainKey
1752
- }),
1753
- resolvedViaSessionId: false
1754
- };
1755
- } catch {
1756
- return null;
1757
- }
1758
- }
1759
- async function resolveSessionReference(params) {
1760
- const raw = params.sessionKey.trim();
1761
- if (shouldResolveSessionIdInput(raw)) {
1762
- const resolvedByKey = await resolveSessionKeyFromKey({
1763
- key: raw,
1764
- alias: params.alias,
1765
- mainKey: params.mainKey,
1766
- requesterInternalKey: params.requesterInternalKey,
1767
- restrictToSpawned: params.restrictToSpawned
1768
- });
1769
- if (resolvedByKey) return resolvedByKey;
1770
- return await resolveSessionKeyFromSessionId({
1771
- sessionId: raw,
1772
- alias: params.alias,
1773
- mainKey: params.mainKey,
1774
- requesterInternalKey: params.requesterInternalKey,
1775
- restrictToSpawned: params.restrictToSpawned
1776
- });
1777
- }
1778
- const resolvedKey = resolveInternalSessionKey({
1779
- key: raw,
1780
- alias: params.alias,
1781
- mainKey: params.mainKey
1782
- });
1783
- return {
1784
- ok: true,
1785
- key: resolvedKey,
1786
- displayKey: resolveDisplaySessionKey({
1787
- key: resolvedKey,
1788
- alias: params.alias,
1789
- mainKey: params.mainKey
1790
- }),
1791
- resolvedViaSessionId: false
1792
- };
1793
- }
1794
- function classifySessionKind(params) {
1795
- const key = params.key;
1796
- if (key === params.alias || key === params.mainKey) return "main";
1797
- if (key.startsWith("cron:")) return "cron";
1798
- if (key.startsWith("hook:")) return "hook";
1799
- if (key.startsWith("node-") || key.startsWith("node:")) return "node";
1800
- if (params.gatewayKind === "group") return "group";
1801
- if (key.includes(":group:") || key.includes(":channel:")) return "group";
1802
- return "other";
1803
- }
1804
- function deriveChannel(params) {
1805
- if (params.kind === "cron" || params.kind === "hook" || params.kind === "node") return "internal";
1806
- const channel = normalizeKey(params.channel ?? void 0);
1807
- if (channel) return channel;
1808
- const lastChannel = normalizeKey(params.lastChannel ?? void 0);
1809
- if (lastChannel) return lastChannel;
1810
- const parts = params.key.split(":").filter(Boolean);
1811
- if (parts.length >= 3 && (parts[1] === "group" || parts[1] === "channel")) return parts[0];
1812
- return "unknown";
1813
- }
1814
- function stripToolMessages(messages) {
1815
- return messages.filter((msg) => {
1816
- if (!msg || typeof msg !== "object") return true;
1817
- return msg.role !== "toolResult";
1818
- });
1819
- }
1820
- /**
1821
- * Sanitize text content to strip tool call markers and thinking tags.
1822
- * This ensures user-facing text doesn't leak internal tool representations.
1823
- */
1824
- function sanitizeTextContent(text) {
1825
- if (!text) return text;
1826
- return stripThinkingTagsFromText(stripDowngradedToolCallText(stripMinimaxToolCallXml(text)));
1827
- }
1828
- function extractAssistantText(message) {
1829
- if (!message || typeof message !== "object") return;
1830
- if (message.role !== "assistant") return;
1831
- const content = message.content;
1832
- if (!Array.isArray(content)) return;
1833
- const chunks = [];
1834
- for (const block of content) {
1835
- if (!block || typeof block !== "object") continue;
1836
- if (block.type !== "text") continue;
1837
- const text = block.text;
1838
- if (typeof text === "string") {
1839
- const sanitized = sanitizeTextContent(text);
1840
- if (sanitized.trim()) chunks.push(sanitized);
1841
- }
1842
- }
1843
- const joined = chunks.join("").trim();
1844
- const stopReason = message.stopReason;
1845
- const errorMessage = message.errorMessage;
1846
- const errorContext = stopReason === "error" || typeof errorMessage === "string" && Boolean(errorMessage.trim());
1847
- return joined ? sanitizeUserFacingText(joined, { errorContext }) : void 0;
1848
- }
1849
-
1850
- //#endregion
1851
- //#region src/agents/tools/agent-step.ts
1852
- async function readLatestAssistantReply(params) {
1853
- const history = await callGateway({
1854
- method: "chat.history",
1855
- params: {
1856
- sessionKey: params.sessionKey,
1857
- limit: params.limit ?? 50
1858
- }
1859
- });
1860
- const filtered = stripToolMessages(Array.isArray(history?.messages) ? history.messages : []);
1861
- for (let i = filtered.length - 1; i >= 0; i -= 1) {
1862
- const candidate = filtered[i];
1863
- if (!candidate || typeof candidate !== "object") continue;
1864
- if (candidate.role !== "assistant") continue;
1865
- const text = extractAssistantText(candidate);
1866
- if (!text?.trim()) continue;
1867
- return text;
1868
- }
1869
- }
1870
- async function runAgentStep(params) {
1871
- const stepIdem = crypto.randomUUID();
1872
- const response = await callGateway({
1873
- method: "agent",
1874
- params: {
1875
- message: params.message,
1876
- sessionKey: params.sessionKey,
1877
- idempotencyKey: stepIdem,
1878
- deliver: false,
1879
- channel: params.channel ?? INTERNAL_MESSAGE_CHANNEL,
1880
- lane: params.lane ?? AGENT_LANE_NESTED,
1881
- extraSystemPrompt: params.extraSystemPrompt,
1882
- inputProvenance: {
1883
- kind: "inter_session",
1884
- sourceSessionKey: params.sourceSessionKey,
1885
- sourceChannel: params.sourceChannel,
1886
- sourceTool: params.sourceTool ?? "sessions_send"
1887
- }
1888
- },
1889
- timeoutMs: 1e4
1890
- });
1891
- const resolvedRunId = (typeof response?.runId === "string" && response.runId ? response.runId : "") || stepIdem;
1892
- const stepWaitMs = Math.min(params.timeoutMs, 6e4);
1893
- if ((await callGateway({
1894
- method: "agent.wait",
1895
- params: {
1896
- runId: resolvedRunId,
1897
- timeoutMs: stepWaitMs
1898
- },
1899
- timeoutMs: stepWaitMs + 2e3
1900
- }))?.status !== "ok") return;
1901
- return await readLatestAssistantReply({ sessionKey: params.sessionKey });
1902
- }
1903
-
1904
- //#endregion
1905
- //#region src/agents/subagent-announce.ts
1906
- function formatDurationShort(valueMs) {
1907
- if (!valueMs || !Number.isFinite(valueMs) || valueMs <= 0) return "n/a";
1908
- const totalSeconds = Math.round(valueMs / 1e3);
1909
- const hours = Math.floor(totalSeconds / 3600);
1910
- const minutes = Math.floor(totalSeconds % 3600 / 60);
1911
- const seconds = totalSeconds % 60;
1912
- if (hours > 0) return `${hours}h${minutes}m`;
1913
- if (minutes > 0) return `${minutes}m${seconds}s`;
1914
- return `${seconds}s`;
1915
- }
1916
- function formatTokenCount(value) {
1917
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return "0";
1918
- if (value >= 1e6) return `${(value / 1e6).toFixed(1)}m`;
1919
- if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
1920
- return String(Math.round(value));
1921
- }
1922
- async function buildCompactAnnounceStatsLine(params) {
1923
- const cfg = loadConfig();
1924
- const agentId = resolveAgentIdFromSessionKey(params.sessionKey);
1925
- const storePath = resolveStorePath(cfg.session?.store, { agentId });
1926
- let entry = loadSessionStore(storePath)[params.sessionKey];
1927
- for (let attempt = 0; attempt < 3; attempt += 1) {
1928
- if (typeof entry?.inputTokens === "number" || typeof entry?.outputTokens === "number" || typeof entry?.totalTokens === "number") break;
1929
- await new Promise((resolve) => setTimeout(resolve, 150));
1930
- entry = loadSessionStore(storePath)[params.sessionKey];
1931
- }
1932
- const input = typeof entry?.inputTokens === "number" ? entry.inputTokens : 0;
1933
- const output = typeof entry?.outputTokens === "number" ? entry.outputTokens : 0;
1934
- const ioTotal = input + output;
1935
- const promptCache = typeof entry?.totalTokens === "number" ? entry.totalTokens : void 0;
1936
- 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)})`];
1937
- if (typeof promptCache === "number" && promptCache > ioTotal) parts.push(`prompt/cache ${formatTokenCount(promptCache)}`);
1938
- return `Stats: ${parts.join(" • ")}`;
1939
- }
1940
- function resolveAnnounceOrigin(entry, requesterOrigin) {
1941
- return mergeDeliveryContext(requesterOrigin, deliveryContextFromSession(entry));
1942
- }
1943
- async function sendAnnounce(item) {
1944
- const requesterIsSubagent = getSubagentDepthFromSessionStore(item.sessionKey) >= 1;
1945
- const origin = item.origin;
1946
- const threadId = origin?.threadId != null && origin.threadId !== "" ? String(origin.threadId) : void 0;
1947
- await callGateway({
1948
- method: "agent",
1949
- params: {
1950
- sessionKey: item.sessionKey,
1951
- message: item.prompt,
1952
- channel: requesterIsSubagent ? void 0 : origin?.channel,
1953
- accountId: requesterIsSubagent ? void 0 : origin?.accountId,
1954
- to: requesterIsSubagent ? void 0 : origin?.to,
1955
- threadId: requesterIsSubagent ? void 0 : threadId,
1956
- deliver: !requesterIsSubagent,
1957
- idempotencyKey: crypto.randomUUID()
1958
- },
1959
- timeoutMs: 15e3
1960
- });
1961
- }
1962
- function resolveRequesterStoreKey(cfg, requesterSessionKey) {
1963
- const raw = requesterSessionKey.trim();
1964
- if (!raw) return raw;
1965
- if (raw === "global" || raw === "unknown") return raw;
1966
- if (raw.startsWith("agent:")) return raw;
1967
- const mainKey = normalizeMainKey(cfg.session?.mainKey);
1968
- if (raw === "main" || raw === mainKey) return resolveMainSessionKey(cfg);
1969
- return `agent:${resolveAgentIdFromSessionKey(raw)}:${raw}`;
1970
- }
1971
- function loadRequesterSessionEntry(requesterSessionKey) {
1972
- const cfg = loadConfig();
1973
- const canonicalKey = resolveRequesterStoreKey(cfg, requesterSessionKey);
1974
- const agentId = resolveAgentIdFromSessionKey(canonicalKey);
1975
- return {
1976
- cfg,
1977
- entry: loadSessionStore(resolveStorePath(cfg.session?.store, { agentId }))[canonicalKey],
1978
- canonicalKey
1979
- };
1980
- }
1981
- async function maybeQueueSubagentAnnounce(params) {
1982
- const { cfg, entry } = loadRequesterSessionEntry(params.requesterSessionKey);
1983
- const canonicalKey = resolveRequesterStoreKey(cfg, params.requesterSessionKey);
1984
- const sessionId = entry?.sessionId;
1985
- if (!sessionId) return "none";
1986
- const queueSettings = resolveQueueSettings({
1987
- cfg,
1988
- channel: entry?.channel ?? entry?.lastChannel,
1989
- sessionEntry: entry
1990
- });
1991
- const isActive = isEmbeddedPiRunActive(sessionId);
1992
- if (queueSettings.mode === "steer" || queueSettings.mode === "steer-backlog") {
1993
- if (/* @__PURE__ */ queueEmbeddedPiMessage(sessionId, params.triggerMessage)) return "steered";
1994
- }
1995
- const shouldFollowup = queueSettings.mode === "followup" || queueSettings.mode === "collect" || queueSettings.mode === "steer-backlog" || queueSettings.mode === "interrupt";
1996
- if (isActive && (shouldFollowup || queueSettings.mode === "steer")) {
1997
- const origin = resolveAnnounceOrigin(entry, params.requesterOrigin);
1998
- enqueueAnnounce({
1999
- key: canonicalKey,
2000
- item: {
2001
- prompt: params.triggerMessage,
2002
- summaryLine: params.summaryLine,
2003
- enqueuedAt: Date.now(),
2004
- sessionKey: canonicalKey,
2005
- origin
2006
- },
2007
- settings: queueSettings,
2008
- send: sendAnnounce
2009
- });
2010
- return "queued";
2011
- }
2012
- return "none";
2013
- }
2014
- function loadSessionEntryByKey(sessionKey) {
2015
- const cfg = loadConfig();
2016
- const agentId = resolveAgentIdFromSessionKey(sessionKey);
2017
- return loadSessionStore(resolveStorePath(cfg.session?.store, { agentId }))[sessionKey];
2018
- }
2019
- async function readLatestAssistantReplyWithRetry(params) {
2020
- const RETRY_INTERVAL_MS = 100;
2021
- let reply = params.initialReply?.trim() ? params.initialReply : void 0;
2022
- if (reply) return reply;
2023
- const deadline = Date.now() + Math.max(0, Math.min(params.maxWaitMs, 15e3));
2024
- while (Date.now() < deadline) {
2025
- await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL_MS));
2026
- const latest = await readLatestAssistantReply({ sessionKey: params.sessionKey });
2027
- if (latest?.trim()) return latest;
2028
- }
2029
- return reply;
2030
- }
2031
- function buildSubagentSystemPrompt(params) {
2032
- const taskText = typeof params.task === "string" && params.task.trim() ? params.task.replace(/\s+/g, " ").trim() : "{{TASK_DESCRIPTION}}";
2033
- const childDepth = typeof params.childDepth === "number" ? params.childDepth : 1;
2034
- const canSpawn = childDepth < (typeof params.maxSpawnDepth === "number" ? params.maxSpawnDepth : 1);
2035
- const parentLabel = childDepth >= 2 ? "parent orchestrator" : "main agent";
2036
- const lines = [
2037
- "# Subagent Context",
2038
- "",
2039
- `You are a **subagent** spawned by the ${parentLabel} for a specific task.`,
2040
- "",
2041
- "## Your Role",
2042
- `- You were created to handle: ${taskText}`,
2043
- "- Complete this task. That's your entire purpose.",
2044
- `- You are NOT the ${parentLabel}. Don't try to be.`,
2045
- "",
2046
- "## Rules",
2047
- "1. **Stay focused** - Do your assigned task, nothing else",
2048
- `2. **Complete the task** - Your final message will be automatically reported to the ${parentLabel}`,
2049
- "3. **Don't initiate** - No heartbeats, no proactive actions, no side quests",
2050
- "4. **Be ephemeral** - You may be terminated after task completion. That's fine.",
2051
- "5. **Trust push-based completion** - Descendant results are auto-announced back to you; do not busy-poll for status.",
2052
- "",
2053
- "## Output Format",
2054
- "When complete, your final response should include:",
2055
- `- What you accomplished or found`,
2056
- `- Any relevant details the ${parentLabel} should know`,
2057
- "- Keep it concise but informative",
2058
- "",
2059
- "## What You DON'T Do",
2060
- `- NO user conversations (that's ${parentLabel}'s job)`,
2061
- "- NO external messages (email, tweets, etc.) unless explicitly tasked with a specific recipient/channel",
2062
- "- NO cron jobs or persistent state",
2063
- `- NO pretending to be the ${parentLabel}`,
2064
- `- Only use the \`message\` tool when explicitly instructed to contact a specific external recipient; otherwise return plain text and let the ${parentLabel} deliver it`,
2065
- ""
2066
- ];
2067
- 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.", "");
2068
- 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.", "");
2069
- lines.push("## Session Context", ...[
2070
- params.label ? `- Label: ${params.label}` : void 0,
2071
- params.requesterSessionKey ? `- Requester session: ${params.requesterSessionKey}.` : void 0,
2072
- params.requesterOrigin?.channel ? `- Requester channel: ${params.requesterOrigin.channel}.` : void 0,
2073
- `- Your session: ${params.childSessionKey}.`
2074
- ].filter((line) => line !== void 0), "");
2075
- return lines.join("\n");
2076
- }
2077
- function buildAnnounceReplyInstruction(params) {
2078
- if (params.remainingActiveSubagentRuns > 0) {
2079
- const activeRunsLabel = params.remainingActiveSubagentRuns === 1 ? "run" : "runs";
2080
- 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.`;
2081
- }
2082
- 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.";
2083
- 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.`;
2084
- }
2085
- async function runSubagentAnnounceFlow(params) {
2086
- let didAnnounce = false;
2087
- let shouldDeleteChildSession = params.cleanup === "delete";
2088
- try {
2089
- let targetRequesterSessionKey = params.requesterSessionKey;
2090
- let targetRequesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
2091
- const childSessionId = (() => {
2092
- const entry = loadSessionEntryByKey(params.childSessionKey);
2093
- return typeof entry?.sessionId === "string" && entry.sessionId.trim() ? entry.sessionId.trim() : void 0;
2094
- })();
2095
- const settleTimeoutMs = Math.min(Math.max(params.timeoutMs, 1), 12e4);
2096
- let reply = params.roundOneReply;
2097
- let outcome = params.outcome;
2098
- if (childSessionId && isEmbeddedPiRunActive(childSessionId)) {
2099
- if (!await /* @__PURE__ */ waitForEmbeddedPiRunEnd(childSessionId, settleTimeoutMs) && isEmbeddedPiRunActive(childSessionId)) {
2100
- shouldDeleteChildSession = false;
2101
- return false;
2102
- }
2103
- }
2104
- if (!reply && params.waitForCompletion !== false) {
2105
- const waitMs = settleTimeoutMs;
2106
- const wait = await callGateway({
2107
- method: "agent.wait",
2108
- params: {
2109
- runId: params.childRunId,
2110
- timeoutMs: waitMs
2111
- },
2112
- timeoutMs: waitMs + 2e3
2113
- });
2114
- const waitError = typeof wait?.error === "string" ? wait.error : void 0;
2115
- if (wait?.status === "timeout") outcome = { status: "timeout" };
2116
- else if (wait?.status === "error") outcome = {
2117
- status: "error",
2118
- error: waitError
2119
- };
2120
- else if (wait?.status === "ok") outcome = { status: "ok" };
2121
- if (typeof wait?.startedAt === "number" && !params.startedAt) params.startedAt = wait.startedAt;
2122
- if (typeof wait?.endedAt === "number" && !params.endedAt) params.endedAt = wait.endedAt;
2123
- if (wait?.status === "timeout") {
2124
- if (!outcome) outcome = { status: "timeout" };
2125
- }
2126
- reply = await readLatestAssistantReply({ sessionKey: params.childSessionKey });
2127
- }
2128
- if (!reply) reply = await readLatestAssistantReply({ sessionKey: params.childSessionKey });
2129
- if (!reply?.trim()) reply = await readLatestAssistantReplyWithRetry({
2130
- sessionKey: params.childSessionKey,
2131
- initialReply: reply,
2132
- maxWaitMs: params.timeoutMs
2133
- });
2134
- if (!reply?.trim() && childSessionId && isEmbeddedPiRunActive(childSessionId)) {
2135
- shouldDeleteChildSession = false;
2136
- return false;
2137
- }
2138
- if (!outcome) outcome = { status: "unknown" };
2139
- let activeChildDescendantRuns = 0;
2140
- try {
2141
- const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
2142
- activeChildDescendantRuns = Math.max(0, countActiveDescendantRuns(params.childSessionKey));
2143
- } catch {}
2144
- if (activeChildDescendantRuns > 0) {
2145
- shouldDeleteChildSession = false;
2146
- return false;
2147
- }
2148
- const statusLabel = outcome.status === "ok" ? "completed successfully" : outcome.status === "timeout" ? "timed out" : outcome.status === "error" ? `failed: ${outcome.error || "unknown error"}` : "finished with unknown status";
2149
- const announceType = params.announceType ?? "subagent task";
2150
- const taskLabel = params.label || params.task || "task";
2151
- const announceSessionId = childSessionId || "unknown";
2152
- const findings = reply || "(no output)";
2153
- let triggerMessage = "";
2154
- let requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
2155
- let requesterIsSubagent = requesterDepth >= 1;
2156
- if (requesterIsSubagent) {
2157
- const { isSubagentSessionRunActive, resolveRequesterForChildSession } = await Promise.resolve().then(() => subagent_registry_exports);
2158
- if (!isSubagentSessionRunActive(targetRequesterSessionKey)) {
2159
- const fallback = resolveRequesterForChildSession(targetRequesterSessionKey);
2160
- if (!fallback?.requesterSessionKey) {
2161
- shouldDeleteChildSession = false;
2162
- return false;
2163
- }
2164
- targetRequesterSessionKey = fallback.requesterSessionKey;
2165
- targetRequesterOrigin = normalizeDeliveryContext(fallback.requesterOrigin) ?? targetRequesterOrigin;
2166
- requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
2167
- requesterIsSubagent = requesterDepth >= 1;
2168
- }
2169
- }
2170
- let remainingActiveSubagentRuns = 0;
2171
- try {
2172
- const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
2173
- remainingActiveSubagentRuns = Math.max(0, countActiveDescendantRuns(targetRequesterSessionKey));
2174
- } catch {}
2175
- const replyInstruction = buildAnnounceReplyInstruction({
2176
- remainingActiveSubagentRuns,
2177
- requesterIsSubagent,
2178
- announceType
2179
- });
2180
- const statsLine = await buildCompactAnnounceStatsLine({
2181
- sessionKey: params.childSessionKey,
2182
- startedAt: params.startedAt,
2183
- endedAt: params.endedAt
2184
- });
2185
- triggerMessage = [
2186
- `[System Message] [sessionId: ${announceSessionId}] A ${announceType} "${taskLabel}" just ${statusLabel}.`,
2187
- "",
2188
- "Result:",
2189
- findings,
2190
- "",
2191
- statsLine,
2192
- "",
2193
- replyInstruction
2194
- ].join("\n");
2195
- const queued = await maybeQueueSubagentAnnounce({
2196
- requesterSessionKey: targetRequesterSessionKey,
2197
- triggerMessage,
2198
- summaryLine: taskLabel,
2199
- requesterOrigin: targetRequesterOrigin
2200
- });
2201
- if (queued === "steered") {
2202
- didAnnounce = true;
2203
- return true;
2204
- }
2205
- if (queued === "queued") {
2206
- didAnnounce = true;
2207
- return true;
2208
- }
2209
- let directOrigin = targetRequesterOrigin;
2210
- if (!requesterIsSubagent && !directOrigin) {
2211
- const { entry } = loadRequesterSessionEntry(targetRequesterSessionKey);
2212
- directOrigin = deliveryContextFromSession(entry);
2213
- }
2214
- await callGateway({
2215
- method: "agent",
2216
- params: {
2217
- sessionKey: targetRequesterSessionKey,
2218
- message: triggerMessage,
2219
- deliver: !requesterIsSubagent,
2220
- channel: requesterIsSubagent ? void 0 : directOrigin?.channel,
2221
- accountId: requesterIsSubagent ? void 0 : directOrigin?.accountId,
2222
- to: requesterIsSubagent ? void 0 : directOrigin?.to,
2223
- threadId: !requesterIsSubagent && directOrigin?.threadId != null && directOrigin.threadId !== "" ? String(directOrigin.threadId) : void 0,
2224
- idempotencyKey: crypto.randomUUID()
2225
- },
2226
- expectFinal: true,
2227
- timeoutMs: 15e3
2228
- });
2229
- didAnnounce = true;
2230
- } catch (err) {
2231
- defaultRuntime.error?.(`Subagent announce failed: ${String(err)}`);
2232
- } finally {
2233
- if (params.label) try {
2234
- await callGateway({
2235
- method: "sessions.patch",
2236
- params: {
2237
- key: params.childSessionKey,
2238
- label: params.label
2239
- },
2240
- timeoutMs: 1e4
2241
- });
2242
- } catch {}
2243
- if (shouldDeleteChildSession) try {
2244
- await callGateway({
2245
- method: "sessions.delete",
2246
- params: {
2247
- key: params.childSessionKey,
2248
- deleteTranscript: true
2249
- },
2250
- timeoutMs: 1e4
2251
- });
2252
- } catch {}
2253
- }
2254
- return didAnnounce;
2255
- }
2256
-
2257
- //#endregion
2258
- //#region src/agents/subagent-registry.store.ts
2259
- const REGISTRY_VERSION = 2;
2260
- function resolveSubagentStateDir(env = process.env) {
2261
- if (env.ANIMA_STATE_DIR?.trim()) return resolveStateDir(env);
2262
- if (env.VITEST || env.NODE_ENV === "test") return path.join(os.tmpdir(), "anima-test-state", String(process.pid));
2263
- return resolveStateDir(env);
2264
- }
2265
- function resolveSubagentRegistryPath() {
2266
- return path.join(resolveSubagentStateDir(process.env), "subagents", "runs.json");
2267
- }
2268
- function loadSubagentRegistryFromDisk() {
2269
- const raw = loadJsonFile(resolveSubagentRegistryPath());
2270
- if (!raw || typeof raw !== "object") return /* @__PURE__ */ new Map();
2271
- const record = raw;
2272
- if (record.version !== 1 && record.version !== 2) return /* @__PURE__ */ new Map();
2273
- const runsRaw = record.runs;
2274
- if (!runsRaw || typeof runsRaw !== "object") return /* @__PURE__ */ new Map();
2275
- const out = /* @__PURE__ */ new Map();
2276
- const isLegacy = record.version === 1;
2277
- let migrated = false;
2278
- for (const [runId, entry] of Object.entries(runsRaw)) {
2279
- if (!entry || typeof entry !== "object") continue;
2280
- const typed = entry;
2281
- if (!typed.runId || typeof typed.runId !== "string") continue;
2282
- const legacyCompletedAt = isLegacy && typeof typed.announceCompletedAt === "number" ? typed.announceCompletedAt : void 0;
2283
- const cleanupCompletedAt = typeof typed.cleanupCompletedAt === "number" ? typed.cleanupCompletedAt : legacyCompletedAt;
2284
- const cleanupHandled = typeof typed.cleanupHandled === "boolean" ? typed.cleanupHandled : isLegacy ? Boolean(typed.announceHandled ?? cleanupCompletedAt) : void 0;
2285
- const requesterOrigin = normalizeDeliveryContext(typed.requesterOrigin ?? {
2286
- channel: typeof typed.requesterChannel === "string" ? typed.requesterChannel : void 0,
2287
- accountId: typeof typed.requesterAccountId === "string" ? typed.requesterAccountId : void 0
2288
- });
2289
- const { announceCompletedAt: _announceCompletedAt, announceHandled: _announceHandled, requesterChannel: _channel, requesterAccountId: _accountId, ...rest } = typed;
2290
- out.set(runId, {
2291
- ...rest,
2292
- requesterOrigin,
2293
- cleanupCompletedAt,
2294
- cleanupHandled
2295
- });
2296
- if (isLegacy) migrated = true;
2297
- }
2298
- if (migrated) try {
2299
- saveSubagentRegistryToDisk(out);
2300
- } catch {}
2301
- return out;
2302
- }
2303
- function saveSubagentRegistryToDisk(runs) {
2304
- const pathname = resolveSubagentRegistryPath();
2305
- const serialized = {};
2306
- for (const [runId, entry] of runs.entries()) serialized[runId] = entry;
2307
- saveJsonFile(pathname, {
2308
- version: REGISTRY_VERSION,
2309
- runs: serialized
2310
- });
2311
- }
2312
-
2313
- //#endregion
2314
- //#region src/agents/subagent-registry.ts
2315
- var subagent_registry_exports = /* @__PURE__ */ __exportAll({
2316
- clearSubagentRunSteerRestart: () => clearSubagentRunSteerRestart,
2317
- countActiveDescendantRuns: () => countActiveDescendantRuns,
2318
- countActiveRunsForSession: () => countActiveRunsForSession,
2319
- initSubagentRegistry: () => initSubagentRegistry,
2320
- isSubagentSessionRunActive: () => isSubagentSessionRunActive,
2321
- listDescendantRunsForRequester: () => listDescendantRunsForRequester,
2322
- listSubagentRunsForRequester: () => listSubagentRunsForRequester,
2323
- markSubagentRunForSteerRestart: () => markSubagentRunForSteerRestart,
2324
- markSubagentRunTerminated: () => markSubagentRunTerminated,
2325
- registerSubagentRun: () => registerSubagentRun,
2326
- replaceSubagentRunAfterSteer: () => replaceSubagentRunAfterSteer,
2327
- resolveRequesterForChildSession: () => resolveRequesterForChildSession
2328
- });
2329
- const subagentRuns = /* @__PURE__ */ new Map();
2330
- let sweeper = null;
2331
- let listenerStarted = false;
2332
- let listenerStop = null;
2333
- var restoreAttempted = false;
2334
- const SUBAGENT_ANNOUNCE_TIMEOUT_MS = 12e4;
2335
- function persistSubagentRuns() {
2336
- try {
2337
- saveSubagentRegistryToDisk(subagentRuns);
2338
- } catch {}
2339
- }
2340
- const resumedRuns = /* @__PURE__ */ new Set();
2341
- function suppressAnnounceForSteerRestart(entry) {
2342
- return entry?.suppressAnnounceReason === "steer-restart";
2343
- }
2344
- function startSubagentAnnounceCleanupFlow(runId, entry) {
2345
- if (!beginSubagentCleanup(runId)) return false;
2346
- const requesterOrigin = normalizeDeliveryContext(entry.requesterOrigin);
2347
- runSubagentAnnounceFlow({
2348
- childSessionKey: entry.childSessionKey,
2349
- childRunId: entry.runId,
2350
- requesterSessionKey: entry.requesterSessionKey,
2351
- requesterOrigin,
2352
- requesterDisplayKey: entry.requesterDisplayKey,
2353
- task: entry.task,
2354
- timeoutMs: SUBAGENT_ANNOUNCE_TIMEOUT_MS,
2355
- cleanup: entry.cleanup,
2356
- waitForCompletion: false,
2357
- startedAt: entry.startedAt,
2358
- endedAt: entry.endedAt,
2359
- label: entry.label,
2360
- outcome: entry.outcome
2361
- }).then((didAnnounce) => {
2362
- finalizeSubagentCleanup(runId, entry.cleanup, didAnnounce);
2363
- });
2364
- return true;
2365
- }
2366
- function resumeSubagentRun(runId) {
2367
- if (!runId || resumedRuns.has(runId)) return;
2368
- const entry = subagentRuns.get(runId);
2369
- if (!entry) return;
2370
- if (entry.cleanupCompletedAt) return;
2371
- if (typeof entry.endedAt === "number" && entry.endedAt > 0) {
2372
- if (suppressAnnounceForSteerRestart(entry)) {
2373
- resumedRuns.add(runId);
2374
- return;
2375
- }
2376
- if (!startSubagentAnnounceCleanupFlow(runId, entry)) return;
2377
- resumedRuns.add(runId);
2378
- return;
2379
- }
2380
- waitForSubagentCompletion(runId, resolveSubagentWaitTimeoutMs(loadConfig(), entry.runTimeoutSeconds));
2381
- resumedRuns.add(runId);
2382
- }
2383
- function restoreSubagentRunsOnce() {
2384
- if (restoreAttempted) return;
2385
- restoreAttempted = true;
2386
- try {
2387
- const restored = loadSubagentRegistryFromDisk();
2388
- if (restored.size === 0) return;
2389
- for (const [runId, entry] of restored.entries()) {
2390
- if (!runId || !entry) continue;
2391
- if (!subagentRuns.has(runId)) subagentRuns.set(runId, entry);
2392
- }
2393
- ensureListener();
2394
- if ([...subagentRuns.values()].some((entry) => entry.archiveAtMs)) startSweeper();
2395
- for (const runId of subagentRuns.keys()) resumeSubagentRun(runId);
2396
- } catch {}
2397
- }
2398
- function resolveArchiveAfterMs(cfg) {
2399
- const minutes = (cfg ?? loadConfig()).agents?.defaults?.subagents?.archiveAfterMinutes ?? 60;
2400
- if (!Number.isFinite(minutes) || minutes <= 0) return;
2401
- return Math.max(1, Math.floor(minutes)) * 6e4;
2402
- }
2403
- function resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds) {
2404
- return resolveAgentTimeoutMs({
2405
- cfg,
2406
- overrideSeconds: runTimeoutSeconds ?? 0
2407
- });
2408
- }
2409
- function startSweeper() {
2410
- if (sweeper) return;
2411
- sweeper = setInterval(() => {
2412
- sweepSubagentRuns();
2413
- }, 6e4);
2414
- sweeper.unref?.();
2415
- }
2416
- function stopSweeper() {
2417
- if (!sweeper) return;
2418
- clearInterval(sweeper);
2419
- sweeper = null;
2420
- }
2421
- async function sweepSubagentRuns() {
2422
- const now = Date.now();
2423
- let mutated = false;
2424
- for (const [runId, entry] of subagentRuns.entries()) {
2425
- if (!entry.archiveAtMs || entry.archiveAtMs > now) continue;
2426
- subagentRuns.delete(runId);
2427
- mutated = true;
2428
- try {
2429
- await callGateway({
2430
- method: "sessions.delete",
2431
- params: {
2432
- key: entry.childSessionKey,
2433
- deleteTranscript: true
2434
- },
2435
- timeoutMs: 1e4
2436
- });
2437
- } catch {}
2438
- }
2439
- if (mutated) persistSubagentRuns();
2440
- if (subagentRuns.size === 0) stopSweeper();
2441
- }
2442
- function ensureListener() {
2443
- if (listenerStarted) return;
2444
- listenerStarted = true;
2445
- listenerStop = onAgentEvent((evt) => {
2446
- if (!evt || evt.stream !== "lifecycle") return;
2447
- const entry = subagentRuns.get(evt.runId);
2448
- if (!entry) return;
2449
- const phase = evt.data?.phase;
2450
- if (phase === "start") {
2451
- const startedAt = typeof evt.data?.startedAt === "number" ? evt.data.startedAt : void 0;
2452
- if (startedAt) {
2453
- entry.startedAt = startedAt;
2454
- persistSubagentRuns();
2455
- }
2456
- return;
2457
- }
2458
- if (phase !== "end" && phase !== "error") return;
2459
- entry.endedAt = typeof evt.data?.endedAt === "number" ? evt.data.endedAt : Date.now();
2460
- if (phase === "error") entry.outcome = {
2461
- status: "error",
2462
- error: typeof evt.data?.error === "string" ? evt.data.error : void 0
2463
- };
2464
- else if (evt.data?.aborted) entry.outcome = { status: "timeout" };
2465
- else entry.outcome = { status: "ok" };
2466
- persistSubagentRuns();
2467
- if (suppressAnnounceForSteerRestart(entry)) return;
2468
- if (!startSubagentAnnounceCleanupFlow(evt.runId, entry)) return;
2469
- });
2470
- }
2471
- function finalizeSubagentCleanup(runId, cleanup, didAnnounce) {
2472
- const entry = subagentRuns.get(runId);
2473
- if (!entry) return;
2474
- if (!didAnnounce) {
2475
- entry.cleanupHandled = false;
2476
- resumedRuns.delete(runId);
2477
- persistSubagentRuns();
2478
- return;
2479
- }
2480
- if (cleanup === "delete") {
2481
- subagentRuns.delete(runId);
2482
- persistSubagentRuns();
2483
- retryDeferredCompletedAnnounces(runId);
2484
- return;
2485
- }
2486
- entry.cleanupCompletedAt = Date.now();
2487
- persistSubagentRuns();
2488
- retryDeferredCompletedAnnounces(runId);
2489
- }
2490
- function retryDeferredCompletedAnnounces(excludeRunId) {
2491
- for (const [runId, entry] of subagentRuns.entries()) {
2492
- if (excludeRunId && runId === excludeRunId) continue;
2493
- if (typeof entry.endedAt !== "number") continue;
2494
- if (entry.cleanupCompletedAt || entry.cleanupHandled) continue;
2495
- if (suppressAnnounceForSteerRestart(entry)) continue;
2496
- resumedRuns.delete(runId);
2497
- resumeSubagentRun(runId);
2498
- }
2499
- }
2500
- function beginSubagentCleanup(runId) {
2501
- const entry = subagentRuns.get(runId);
2502
- if (!entry) return false;
2503
- if (entry.cleanupCompletedAt) return false;
2504
- if (entry.cleanupHandled) return false;
2505
- entry.cleanupHandled = true;
2506
- persistSubagentRuns();
2507
- return true;
2508
- }
2509
- function markSubagentRunForSteerRestart(runId) {
2510
- const key = runId.trim();
2511
- if (!key) return false;
2512
- const entry = subagentRuns.get(key);
2513
- if (!entry) return false;
2514
- if (entry.suppressAnnounceReason === "steer-restart") return true;
2515
- entry.suppressAnnounceReason = "steer-restart";
2516
- persistSubagentRuns();
2517
- return true;
2518
- }
2519
- function clearSubagentRunSteerRestart(runId) {
2520
- const key = runId.trim();
2521
- if (!key) return false;
2522
- const entry = subagentRuns.get(key);
2523
- if (!entry) return false;
2524
- if (entry.suppressAnnounceReason !== "steer-restart") return true;
2525
- entry.suppressAnnounceReason = void 0;
2526
- persistSubagentRuns();
2527
- resumedRuns.delete(key);
2528
- if (typeof entry.endedAt === "number" && !entry.cleanupCompletedAt) resumeSubagentRun(key);
2529
- return true;
2530
- }
2531
- function replaceSubagentRunAfterSteer(params) {
2532
- const previousRunId = params.previousRunId.trim();
2533
- const nextRunId = params.nextRunId.trim();
2534
- if (!previousRunId || !nextRunId) return false;
2535
- const source = subagentRuns.get(previousRunId) ?? params.fallback;
2536
- if (!source) return false;
2537
- if (previousRunId !== nextRunId) {
2538
- subagentRuns.delete(previousRunId);
2539
- resumedRuns.delete(previousRunId);
2540
- }
2541
- const now = Date.now();
2542
- const cfg = loadConfig();
2543
- const archiveAfterMs = resolveArchiveAfterMs(cfg);
2544
- const archiveAtMs = archiveAfterMs ? now + archiveAfterMs : void 0;
2545
- const runTimeoutSeconds = params.runTimeoutSeconds ?? source.runTimeoutSeconds ?? 0;
2546
- const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds);
2547
- const next = {
2548
- ...source,
2549
- runId: nextRunId,
2550
- startedAt: now,
2551
- endedAt: void 0,
2552
- outcome: void 0,
2553
- cleanupCompletedAt: void 0,
2554
- cleanupHandled: false,
2555
- suppressAnnounceReason: void 0,
2556
- archiveAtMs,
2557
- runTimeoutSeconds
2558
- };
2559
- subagentRuns.set(nextRunId, next);
2560
- ensureListener();
2561
- persistSubagentRuns();
2562
- if (archiveAtMs) startSweeper();
2563
- waitForSubagentCompletion(nextRunId, waitTimeoutMs);
2564
- return true;
2565
- }
2566
- function registerSubagentRun(params) {
2567
- const now = Date.now();
2568
- const cfg = loadConfig();
2569
- const archiveAfterMs = resolveArchiveAfterMs(cfg);
2570
- const archiveAtMs = archiveAfterMs ? now + archiveAfterMs : void 0;
2571
- const runTimeoutSeconds = params.runTimeoutSeconds ?? 0;
2572
- const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds);
2573
- const requesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
2574
- subagentRuns.set(params.runId, {
2575
- runId: params.runId,
2576
- childSessionKey: params.childSessionKey,
2577
- requesterSessionKey: params.requesterSessionKey,
2578
- requesterOrigin,
2579
- requesterDisplayKey: params.requesterDisplayKey,
2580
- task: params.task,
2581
- cleanup: params.cleanup,
2582
- label: params.label,
2583
- model: params.model,
2584
- runTimeoutSeconds,
2585
- createdAt: now,
2586
- startedAt: now,
2587
- archiveAtMs,
2588
- cleanupHandled: false
2589
- });
2590
- ensureListener();
2591
- persistSubagentRuns();
2592
- if (archiveAfterMs) startSweeper();
2593
- waitForSubagentCompletion(params.runId, waitTimeoutMs);
2594
- }
2595
- async function waitForSubagentCompletion(runId, waitTimeoutMs) {
2596
- try {
2597
- const timeoutMs = Math.max(1, Math.floor(waitTimeoutMs));
2598
- const wait = await callGateway({
2599
- method: "agent.wait",
2600
- params: {
2601
- runId,
2602
- timeoutMs
2603
- },
2604
- timeoutMs: timeoutMs + 1e4
2605
- });
2606
- if (wait?.status !== "ok" && wait?.status !== "error" && wait?.status !== "timeout") return;
2607
- const entry = subagentRuns.get(runId);
2608
- if (!entry) return;
2609
- let mutated = false;
2610
- if (typeof wait.startedAt === "number") {
2611
- entry.startedAt = wait.startedAt;
2612
- mutated = true;
2613
- }
2614
- if (typeof wait.endedAt === "number") {
2615
- entry.endedAt = wait.endedAt;
2616
- mutated = true;
2617
- }
2618
- if (!entry.endedAt) {
2619
- entry.endedAt = Date.now();
2620
- mutated = true;
2621
- }
2622
- const waitError = typeof wait.error === "string" ? wait.error : void 0;
2623
- entry.outcome = wait.status === "error" ? {
2624
- status: "error",
2625
- error: waitError
2626
- } : wait.status === "timeout" ? { status: "timeout" } : { status: "ok" };
2627
- mutated = true;
2628
- if (mutated) persistSubagentRuns();
2629
- if (suppressAnnounceForSteerRestart(entry)) return;
2630
- if (!startSubagentAnnounceCleanupFlow(runId, entry)) return;
2631
- } catch {}
2632
- }
2633
- function findRunIdsByChildSessionKey(childSessionKey) {
2634
- const key = childSessionKey.trim();
2635
- if (!key) return [];
2636
- const runIds = [];
2637
- for (const [runId, entry] of subagentRuns.entries()) if (entry.childSessionKey === key) runIds.push(runId);
2638
- return runIds;
2639
- }
2640
- function getRunsSnapshotForRead() {
2641
- const merged = /* @__PURE__ */ new Map();
2642
- if (!(process.env.VITEST || false)) try {
2643
- for (const [runId, entry] of loadSubagentRegistryFromDisk().entries()) merged.set(runId, entry);
2644
- } catch {}
2645
- for (const [runId, entry] of subagentRuns.entries()) merged.set(runId, entry);
2646
- return merged;
2647
- }
2648
- function resolveRequesterForChildSession(childSessionKey) {
2649
- const key = childSessionKey.trim();
2650
- if (!key) return null;
2651
- let best;
2652
- for (const entry of getRunsSnapshotForRead().values()) {
2653
- if (entry.childSessionKey !== key) continue;
2654
- if (!best || entry.createdAt > best.createdAt) best = entry;
2655
- }
2656
- if (!best) return null;
2657
- return {
2658
- requesterSessionKey: best.requesterSessionKey,
2659
- requesterOrigin: normalizeDeliveryContext(best.requesterOrigin)
2660
- };
2661
- }
2662
- function isSubagentSessionRunActive(childSessionKey) {
2663
- const runIds = findRunIdsByChildSessionKey(childSessionKey);
2664
- for (const runId of runIds) {
2665
- const entry = subagentRuns.get(runId);
2666
- if (!entry) continue;
2667
- if (typeof entry.endedAt !== "number") return true;
2668
- }
2669
- return false;
2670
- }
2671
- function markSubagentRunTerminated(params) {
2672
- const runIds = /* @__PURE__ */ new Set();
2673
- if (typeof params.runId === "string" && params.runId.trim()) runIds.add(params.runId.trim());
2674
- if (typeof params.childSessionKey === "string" && params.childSessionKey.trim()) for (const runId of findRunIdsByChildSessionKey(params.childSessionKey)) runIds.add(runId);
2675
- if (runIds.size === 0) return 0;
2676
- const now = Date.now();
2677
- const reason = params.reason?.trim() || "killed";
2678
- let updated = 0;
2679
- for (const runId of runIds) {
2680
- const entry = subagentRuns.get(runId);
2681
- if (!entry) continue;
2682
- if (typeof entry.endedAt === "number") continue;
2683
- entry.endedAt = now;
2684
- entry.outcome = {
2685
- status: "error",
2686
- error: reason
2687
- };
2688
- entry.cleanupHandled = true;
2689
- entry.cleanupCompletedAt = now;
2690
- entry.suppressAnnounceReason = "killed";
2691
- updated += 1;
2692
- }
2693
- if (updated > 0) persistSubagentRuns();
2694
- return updated;
2695
- }
2696
- function listSubagentRunsForRequester(requesterSessionKey) {
2697
- const key = requesterSessionKey.trim();
2698
- if (!key) return [];
2699
- return [...subagentRuns.values()].filter((entry) => entry.requesterSessionKey === key);
2700
- }
2701
- function countActiveRunsForSession(requesterSessionKey) {
2702
- const key = requesterSessionKey.trim();
2703
- if (!key) return 0;
2704
- let count = 0;
2705
- for (const entry of getRunsSnapshotForRead().values()) {
2706
- if (entry.requesterSessionKey !== key) continue;
2707
- if (typeof entry.endedAt === "number") continue;
2708
- count += 1;
2709
- }
2710
- return count;
2711
- }
2712
- function countActiveDescendantRuns(rootSessionKey) {
2713
- const root = rootSessionKey.trim();
2714
- if (!root) return 0;
2715
- const runs = getRunsSnapshotForRead();
2716
- const pending = [root];
2717
- const visited = new Set([root]);
2718
- let count = 0;
2719
- while (pending.length > 0) {
2720
- const requester = pending.shift();
2721
- if (!requester) continue;
2722
- for (const entry of runs.values()) {
2723
- if (entry.requesterSessionKey !== requester) continue;
2724
- if (typeof entry.endedAt !== "number") count += 1;
2725
- const childKey = entry.childSessionKey.trim();
2726
- if (!childKey || visited.has(childKey)) continue;
2727
- visited.add(childKey);
2728
- pending.push(childKey);
2729
- }
2730
- }
2731
- return count;
2732
- }
2733
- function listDescendantRunsForRequester(rootSessionKey) {
2734
- const root = rootSessionKey.trim();
2735
- if (!root) return [];
2736
- const runs = getRunsSnapshotForRead();
2737
- const pending = [root];
2738
- const visited = new Set([root]);
2739
- const descendants = [];
2740
- while (pending.length > 0) {
2741
- const requester = pending.shift();
2742
- if (!requester) continue;
2743
- for (const entry of runs.values()) {
2744
- if (entry.requesterSessionKey !== requester) continue;
2745
- descendants.push(entry);
2746
- const childKey = entry.childSessionKey.trim();
2747
- if (!childKey || visited.has(childKey)) continue;
2748
- visited.add(childKey);
2749
- pending.push(childKey);
2750
- }
2751
- }
2752
- return descendants;
2753
- }
2754
- function initSubagentRegistry() {
2755
- restoreSubagentRunsOnce();
2756
- }
2757
-
2758
- //#endregion
2759
- 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 };