remoteclaw 0.1.0-next.da482d8 → 0.1.0-next.db8a792

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 (1020) hide show
  1. package/dist/accounts-BZ2kR_Ij.js +47 -0
  2. package/dist/accounts-Bi4rFQG5.js +272 -0
  3. package/dist/accounts-Bpk-loA6.js +47 -0
  4. package/dist/accounts-D1CBpsaa.js +32 -0
  5. package/dist/accounts-DAdUdbPk.js +36 -0
  6. package/dist/accounts-WYyfAiie.js +270 -0
  7. package/dist/accounts-zQKMwnvt.js +36 -0
  8. package/dist/ack-reactions-B1l-vKPr.js +621 -0
  9. package/dist/ack-reactions-BnG0DLMu.js +621 -0
  10. package/dist/acp-cli-Btx71t69.js +1319 -0
  11. package/dist/acp-cli-DVQMjl0p.js +1324 -0
  12. package/dist/active-listener-BfN4RKlA.js +37 -0
  13. package/dist/active-listener-Bq7ckjOV.js +37 -0
  14. package/dist/agent-D2IwuL6g.js +688 -0
  15. package/dist/agent-WaE2mXI1.js +687 -0
  16. package/dist/agent-helpers-BcaiJFiG.js +400 -0
  17. package/dist/agent-scope-DVvX_nkQ.js +116 -0
  18. package/dist/agents-BwnT7jca.js +760 -0
  19. package/dist/agents.config-Dorm30BQ.js +116 -0
  20. package/dist/audio-B1lTyRqS.js +43 -0
  21. package/dist/audio-e0dFnrn8.js +43 -0
  22. package/dist/audit-DZvqycbG.js +3150 -0
  23. package/dist/audit-Mit73dYD.js +3150 -0
  24. package/dist/auth-C-XX0Tdt.js +314 -0
  25. package/dist/auth-D8--b01l.js +315 -0
  26. package/dist/auth-DJ7XEBDO.js +448 -0
  27. package/dist/auth-otyjXf9l.js +448 -0
  28. package/dist/banner-DSE-i7gH.js +294 -0
  29. package/dist/binaries-BSjilwX-.js +13 -0
  30. package/dist/bindings-DFTxQj8x.js +69 -0
  31. package/dist/bonjour-discovery-BnxTMHRd.js +378 -0
  32. package/dist/bonjour-discovery-CVJYHT3g.js +378 -0
  33. package/dist/boot/handler.js +28 -44
  34. package/dist/browser-cli-BR2pZWTC.js +1694 -0
  35. package/dist/browser-cli-I0kfR7FV.js +1690 -0
  36. package/dist/build-info.json +3 -3
  37. package/dist/call-Ck7ysmEl.js +517 -0
  38. package/dist/call-MN6mCJEB.js +518 -0
  39. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  40. package/dist/catalog-Bt9EM4sK.js +185 -0
  41. package/dist/catalog-BtUvWKd9.js +185 -0
  42. package/dist/channel-account-context-BLQq9NKz.js +133 -0
  43. package/dist/channel-account-context-CaCzVa76.js +133 -0
  44. package/dist/channel-activity-BatlvP_U.js +292 -0
  45. package/dist/channel-activity-DHVMMb2x.js +94 -0
  46. package/dist/channel-activity-DtRx3b0W.js +94 -0
  47. package/dist/channel-options-C6kT3nXB.js +32 -0
  48. package/dist/channel-options-CbgR_vsp.js +33 -0
  49. package/dist/channel-selection-CzbrpDPd.js +51 -0
  50. package/dist/channel-selection-Xv5UFxOx.js +51 -0
  51. package/dist/channel-web-DfDokU69.js +2134 -0
  52. package/dist/channel-web-DtvksSuY.js +2132 -0
  53. package/dist/channels-cli-BmdCVX6O.js +1435 -0
  54. package/dist/channels-cli-CrAZpaiN.js +1439 -0
  55. package/dist/channels-status-issues-B77y-TLr.js +18 -0
  56. package/dist/channels-status-issues-COECL8nx.js +18 -0
  57. package/dist/chrome-Cr5wmMk8.js +1733 -0
  58. package/dist/chrome-YBrnJN-g.js +1732 -0
  59. package/dist/chunk-CrfQ_O--.js +341 -0
  60. package/dist/chunk-DFBUmlXU.js +341 -0
  61. package/dist/clack-prompter-CFNKgQXx.js +122 -0
  62. package/dist/clack-prompter-DDlR2e34.js +121 -0
  63. package/dist/cli/daemon-cli.js +1 -1
  64. package/dist/cli-BbOinSy6.js +130 -0
  65. package/dist/cli-DuvHXQ5h.js +134 -0
  66. package/dist/client-BZeatr3g.js +2316 -0
  67. package/dist/client-Bc9JFAwL.js +2316 -0
  68. package/dist/clipboard-Com-8GBg.js +31 -0
  69. package/dist/clipboard-J_9AABIu.js +31 -0
  70. package/dist/command-format-CMAQa4dB.js +32 -0
  71. package/dist/command-format-KkslAzwV.js +18 -0
  72. package/dist/command-logger/handler.js +1 -1
  73. package/dist/command-registry-BJnVtHo0.js +215 -0
  74. package/dist/commands-ijxtne0J.js +41 -0
  75. package/dist/commands-kZtQfqDl.js +41 -0
  76. package/dist/commands-registry-BrBtH2_B.js +891 -0
  77. package/dist/commands-registry-xZoSouba.js +892 -0
  78. package/dist/common-6D7nhDP-.js +156 -0
  79. package/dist/common-B4cjsvqP.js +156 -0
  80. package/dist/completion-cli-CpUq9QC3.js +452 -0
  81. package/dist/completion-cli-De4umD_N.js +452 -0
  82. package/dist/config-C_WcTz_O.js +4231 -0
  83. package/dist/config-DfcqHTH-.js +4229 -0
  84. package/dist/config-cli-C7rq2n_m.js +243 -0
  85. package/dist/config-cli-VToCKln2.js +247 -0
  86. package/dist/config-guard-BlAcGEao.js +75 -0
  87. package/dist/config-guard-C-h_KIeI.js +99 -0
  88. package/dist/config-validation-C0YXR2dY.js +18 -0
  89. package/dist/config-validation-DDYBTmxT.js +18 -0
  90. package/dist/configure-Bkre1zEB.js +891 -0
  91. package/dist/configure-ifuEamRQ.js +889 -0
  92. package/dist/control-auth-DK6cIBzl.js +397 -0
  93. package/dist/control-auth-DQ8bfDMk.js +397 -0
  94. package/dist/control-ui-assets-DLEWfed6.js +186 -0
  95. package/dist/control-ui-assets-DVhkAyhv.js +186 -0
  96. package/dist/conversation-label-HuHoShPF.js +36 -0
  97. package/dist/conversation-label-L0QTtKji.js +36 -0
  98. package/dist/cron-cli-DnxnTi83.js +498 -0
  99. package/dist/cron-cli-yqcBkqZT.js +494 -0
  100. package/dist/daemon-cli-CmQYq8uO.js +735 -0
  101. package/dist/daemon-cli-_OIRoswC.js +737 -0
  102. package/dist/daemon-cli.js +34 -69
  103. package/dist/daemon-install-BEgffqDj.js +56 -0
  104. package/dist/daemon-install-DAorzotp.js +60 -0
  105. package/dist/daemon-install-helpers-B82uvJjJ.js +504 -0
  106. package/dist/daemon-install-helpers-BhL2Gh4l.js +504 -0
  107. package/dist/deliver-CCvDBk5c.js +481 -0
  108. package/dist/deliver-CqKw0wFi.js +481 -0
  109. package/dist/delivery-queue-CK7VnUJf.js +244 -0
  110. package/dist/delivery-queue-DMeQchpT.js +244 -0
  111. package/dist/devices-cli-C6UAfRV_.js +323 -0
  112. package/dist/devices-cli-Le-isdZB.js +319 -0
  113. package/dist/diagnostics-BhFwk6F3.js +35 -0
  114. package/dist/diagnostics-BtaQtaVR.js +35 -0
  115. package/dist/directory-cli-BqMfX5og.js +220 -0
  116. package/dist/directory-cli-DD72TTD4.js +224 -0
  117. package/dist/dispatcher-BLC2WYZv.js +173 -0
  118. package/dist/dispatcher-Cm2FAG_D.js +174 -0
  119. package/dist/dm-policy-shared-DOzpxMHC.js +22 -0
  120. package/dist/dm-policy-shared-DZY0f1bR.js +22 -0
  121. package/dist/dns-cli-BgsNg-bn.js +203 -0
  122. package/dist/dns-cli-CdMU5yuG.js +199 -0
  123. package/dist/dock-ByrYnLiz.js +929 -0
  124. package/dist/dock-CpNmmysM.js +928 -0
  125. package/dist/doctor-completion-BPeaRbmd.js +92 -0
  126. package/dist/doctor-completion-CfOyGJd3.js +92 -0
  127. package/dist/doctor-config-flow-DMyTycn7.js +1935 -0
  128. package/dist/doctor-config-flow-DoMu-pTm.js +1934 -0
  129. package/dist/enable-D5KetMo7.js +59 -0
  130. package/dist/entry.js +61 -1
  131. package/dist/env-BJ36dSrx.js +60 -0
  132. package/dist/errors-BfONuT95.js +35 -0
  133. package/dist/errors-_DSePI1C.js +35 -0
  134. package/dist/exec-DkFE7lqU.js +164 -0
  135. package/dist/exec-mY96dhIg.js +164 -0
  136. package/dist/extensionAPI.js +112 -76
  137. package/dist/fetch-B3EQXbTa.js +67 -0
  138. package/dist/fetch-BPeSHPvr.js +281 -0
  139. package/dist/fetch-BQ7HvRwe.js +67 -0
  140. package/dist/fetch-CbGTzJ8L.js +281 -0
  141. package/dist/fetch-CfIaWynF.js +67 -0
  142. package/dist/file-lock-BHfqppLm.js +107 -0
  143. package/dist/file-lock-CCBpdPM_.js +107 -0
  144. package/dist/fs-safe-BcEpbVjc.js +88 -0
  145. package/dist/fs-safe-S3Zvbabd.js +98 -0
  146. package/dist/gateway-cli-BXipRcsU.js +24602 -0
  147. package/dist/gateway-cli-Bv2K3rXx.js +24606 -0
  148. package/dist/gateway-rpc-BHnd7P1q.js +28 -0
  149. package/dist/gateway-rpc-COEQDswS.js +28 -0
  150. package/dist/gmail-setup-utils-BpdKFe3P.js +423 -0
  151. package/dist/gmail-setup-utils-CqbWr0Kq.js +422 -0
  152. package/dist/health-1ero5j64.js +1414 -0
  153. package/dist/health-ioP2au7j.js +1417 -0
  154. package/dist/heartbeat-visibility-C88L-_f2.js +125 -0
  155. package/dist/heartbeat-visibility-Dk_Q02qX.js +125 -0
  156. package/dist/hook-runner-global-BztoD8lu.js +527 -0
  157. package/dist/hooks-cli-B8D9DzRR.js +1226 -0
  158. package/dist/hooks-cli-rZ3GOXag.js +1222 -0
  159. package/dist/image-ops-Cx1ym2Hi.js +354 -0
  160. package/dist/image-ops-DWytvdh_.js +354 -0
  161. package/dist/import-CTUBsy7D.js +604 -0
  162. package/dist/import-cBp4f62k.js +606 -0
  163. package/dist/inbound-context-COwswi8z.js +68 -0
  164. package/dist/inbound-context-ChcNR30g.js +68 -0
  165. package/dist/index.js +127 -102
  166. package/dist/inspect-BsS3_z-x.js +286 -0
  167. package/dist/inspect-drfsUSIW.js +286 -0
  168. package/dist/installs-BFmmM5Zd.js +325 -0
  169. package/dist/installs-DA7SG0Tx.js +325 -0
  170. package/dist/ipv4-BZGSwnH4.js +46 -0
  171. package/dist/ipv4-DsOgHE0B.js +46 -0
  172. package/dist/ir-R3Pk8Cv8.js +972 -0
  173. package/dist/lifecycle-core-BZMeOT7u.js +474 -0
  174. package/dist/lifecycle-core-C6-_Gts0.js +476 -0
  175. package/dist/loader-CJ2UHqV7.js +22414 -0
  176. package/dist/loader-dEFvmwXu.js +22411 -0
  177. package/dist/logger-9I2fg5mr.js +49 -0
  178. package/dist/login-D9uJTyEv.js +62 -0
  179. package/dist/login-DTh702_w.js +61 -0
  180. package/dist/login-qr-BKsmW6XI.js +325 -0
  181. package/dist/login-qr-SOXdIR58.js +329 -0
  182. package/dist/logs-cli-BshJBHZQ.js +236 -0
  183. package/dist/logs-cli-Ckh-BBTT.js +240 -0
  184. package/dist/markdown-tables-Cfz7zDXI.js +29 -0
  185. package/dist/markdown-tables-DeFSK6aY.js +29 -0
  186. package/dist/media-BD2cZGXT.js +971 -0
  187. package/dist/media-CjvpnJmQ.js +10388 -0
  188. package/dist/message-action-names-CZHrHMRE.js +2520 -0
  189. package/dist/message-action-names-CiZ-0Smk.js +2520 -0
  190. package/dist/message-channel-EMCYRaxk.js +91 -0
  191. package/dist/mime-1E7nn9IU.js +146 -0
  192. package/dist/mime-mSgQeDnC.js +146 -0
  193. package/dist/net-Cg8AQeke.js +225 -0
  194. package/dist/net-DMh1m8AZ.js +225 -0
  195. package/dist/node-cli-BJ5CCbqx.js +1462 -0
  196. package/dist/node-cli-wYYhAs8x.js +1458 -0
  197. package/dist/node-service-CkwVlcey.js +67 -0
  198. package/dist/node-service-DTVW9YJh.js +67 -0
  199. package/dist/nodes-cli-CMFYLD1o.js +1346 -0
  200. package/dist/nodes-cli-DC2zUx3f.js +1350 -0
  201. package/dist/nodes-screen-6pXv1lYa.js +250 -0
  202. package/dist/nodes-screen-CTIZKksn.js +250 -0
  203. package/dist/note-CMELkPJN.js +92 -0
  204. package/dist/npm-registry-spec-BiJI7Rkr.js +786 -0
  205. package/dist/npm-registry-spec-Dza35Ig4.js +786 -0
  206. package/dist/npm-resolution-CUQGDty4.js +86 -0
  207. package/dist/npm-resolution-CwbZK9AI.js +86 -0
  208. package/dist/onboard-8Qd9lU8x.js +649 -0
  209. package/dist/onboard-Q3cY65m8.js +647 -0
  210. package/dist/onboard-auth-BUzYDEqf.js +211 -0
  211. package/dist/onboard-auth-DcVXyd-Z.js +207 -0
  212. package/dist/onboard-channels-BFHuA-AU.js +2548 -0
  213. package/dist/onboard-channels-DVrPP_ie.js +2547 -0
  214. package/dist/onboard-helpers-B-bBSsyR.js +363 -0
  215. package/dist/onboard-helpers-YsCa-sAt.js +364 -0
  216. package/dist/onboard-remote-BWFcuEOD.js +127 -0
  217. package/dist/onboard-remote-C0THuDTK.js +127 -0
  218. package/dist/onboarding-B31lnOPp.js +586 -0
  219. package/dist/onboarding-DmN_qC8e.js +588 -0
  220. package/dist/onboarding.finalize-DGD0PA-D.js +402 -0
  221. package/dist/onboarding.finalize-DNIb3meE.js +404 -0
  222. package/dist/onboarding.gateway-config-BaeIuA62.js +195 -0
  223. package/dist/onboarding.gateway-config-DMV2Odzr.js +201 -0
  224. package/dist/outbound-BdxBHDax.js +220 -0
  225. package/dist/outbound-D-Y9rMgB.js +221 -0
  226. package/dist/outbound-attachment-CvZ04r5k.js +18 -0
  227. package/dist/outbound-attachment-DYa1asB5.js +18 -0
  228. package/dist/outbound-attachment-DgUpk7Uh.js +18 -0
  229. package/dist/pairing-cli-BxTv78V7.js +125 -0
  230. package/dist/pairing-cli-CxUCzNUc.js +129 -0
  231. package/dist/pairing-labels-DVO6NJr0.js +9 -0
  232. package/dist/pairing-labels-D_pD8Cag.js +9 -0
  233. package/dist/pairing-store-Bu9pVlkO.js +459 -0
  234. package/dist/pairing-store-CWaGbAGi.js +460 -0
  235. package/dist/path-env-RsuO6yO-.js +89 -0
  236. package/dist/path-env-_my-d_iR.js +89 -0
  237. package/dist/path-safety-CfiVyVz7.js +14 -0
  238. package/dist/path-safety-D-wLK4pV.js +14 -0
  239. package/dist/plugin-auto-enable-CW01H36W.js +301 -0
  240. package/dist/plugin-auto-enable-CeHhBLCU.js +302 -0
  241. package/dist/plugin-registry-CWL37HnB.js +33 -0
  242. package/dist/plugin-registry-ELliiumZ.js +33 -0
  243. package/dist/plugin-sdk/auth/provider-auth.d.ts +0 -6
  244. package/dist/plugin-sdk/auto-reply/reply/agent-runner-utils.d.ts +9 -29
  245. package/dist/plugin-sdk/auto-reply/reply/commands-status.d.ts +0 -2
  246. package/dist/plugin-sdk/auto-reply/reply/commands-subagents/shared.d.ts +1 -1
  247. package/dist/plugin-sdk/auto-reply/reply/queue/types.d.ts +0 -2
  248. package/dist/plugin-sdk/auto-reply/status.d.ts +0 -4
  249. package/dist/plugin-sdk/auto-reply/templating.d.ts +0 -4
  250. package/dist/plugin-sdk/config/sessions/types.d.ts +0 -2
  251. package/dist/plugin-sdk/config/types.tools.d.ts +1 -59
  252. package/dist/plugin-sdk/config/types.tts.d.ts +2 -1
  253. package/dist/plugin-sdk/config/zod-schema.agent-runtime.d.ts +0 -177
  254. package/dist/plugin-sdk/config/zod-schema.core.d.ts +2 -230
  255. package/dist/plugin-sdk/config/zod-schema.d.ts +3 -192
  256. package/dist/plugin-sdk/config/zod-schema.providers-core.d.ts +3 -15
  257. package/dist/plugin-sdk/config/zod-schema.providers.d.ts +2 -10
  258. package/dist/plugin-sdk/config/zod-schema.session.d.ts +1 -5
  259. package/dist/plugin-sdk/gateway/protocol/index.d.ts +5 -5
  260. package/dist/plugin-sdk/index.js +72 -142
  261. package/dist/plugin-sdk/middleware/cli-runtime-base.d.ts +6 -0
  262. package/dist/plugin-sdk/middleware/runtimes/claude.d.ts +6 -0
  263. package/dist/plugin-sdk/middleware/runtimes/codex.d.ts +2 -2
  264. package/dist/plugin-sdk/plugin-sdk/index.d.ts +2 -0
  265. package/dist/plugin-sdk/plugins/manifest-registry.d.ts +2 -0
  266. package/dist/plugin-sdk/plugins/manifest.d.ts +2 -0
  267. package/dist/plugin-sdk/plugins/registry.d.ts +18 -0
  268. package/dist/plugin-sdk/plugins/types.d.ts +4 -0
  269. package/dist/plugin-sdk/stt/preflight.d.ts +2 -4
  270. package/dist/plugin-sdk/stt/providers/index.d.ts +1 -1
  271. package/dist/plugin-sdk/stt/providers/shared.d.ts +20 -1
  272. package/dist/plugin-sdk/tts/providers/edge.d.ts +2 -0
  273. package/dist/plugin-sdk/tts/providers/elevenlabs.d.ts +2 -0
  274. package/dist/plugin-sdk/tts/providers/index.d.ts +4 -0
  275. package/dist/plugin-sdk/tts/providers/openai.d.ts +2 -0
  276. package/dist/plugin-sdk/tts/tts.d.ts +13 -5
  277. package/dist/plugin-sdk/tts/types.d.ts +21 -0
  278. package/dist/plugins-DExsdlTp.js +455 -0
  279. package/dist/plugins-DdMgSc_b.js +453 -0
  280. package/dist/plugins-cli-DqBWiT_G.js +806 -0
  281. package/dist/plugins-cli-KQEzhU6P.js +802 -0
  282. package/dist/ports-CL0pXAXO.js +96 -0
  283. package/dist/ports-CRI-HSZx.js +370 -0
  284. package/dist/ports-DiQFcKUB.js +316 -0
  285. package/dist/ports-HRurfPIr.js +96 -0
  286. package/dist/preflight-6QRqxWh7.js +667 -0
  287. package/dist/preflight-DDZjr5KD.js +667 -0
  288. package/dist/program-DmhbOJj3.js +249 -0
  289. package/dist/program-context-PPMzZ6Gu.js +474 -0
  290. package/dist/prompt-select-styled-CmSWunD8.js +1669 -0
  291. package/dist/prompt-select-styled-PfxT9zl9.js +1672 -0
  292. package/dist/provider-auth-CfdnLqh3.js +187 -0
  293. package/dist/provider-auth-gpHOMUBP.js +187 -0
  294. package/dist/provider-dispatcher-D4eY8LZW.js +659 -0
  295. package/dist/provider-dispatcher-D5Q7M15D.js +660 -0
  296. package/dist/push-apns-BNwVMXX9.js +713 -0
  297. package/dist/push-apns-BszVkcZK.js +711 -0
  298. package/dist/pw-ai-Bdb3zrBM.js +1911 -0
  299. package/dist/pw-ai-BvcvEdGs.js +1908 -0
  300. package/dist/qr-cli-BBgk2ci1.js +349 -0
  301. package/dist/qr-cli-BLzVrhia.js +353 -0
  302. package/dist/redact-snapshot-CyBDcb_a.js +1966 -0
  303. package/dist/redact-snapshot-D9oPMqA-.js +1966 -0
  304. package/dist/register.agent-CAhKX3Ft.js +1019 -0
  305. package/dist/register.agent-RKHXtLLm.js +291 -0
  306. package/dist/register.configure-CW6XRGxV.js +129 -0
  307. package/dist/register.configure-dvrKc0j7.js +134 -0
  308. package/dist/register.import-CRLOolHv.js +31 -0
  309. package/dist/register.import-dhDEj7Om.js +29 -0
  310. package/dist/register.maintenance-EAhr1tJ9.js +500 -0
  311. package/dist/register.maintenance-lWz4v90u.js +502 -0
  312. package/dist/register.message-DyWkwUIU.js +690 -0
  313. package/dist/register.message-bl2Khz6c.js +686 -0
  314. package/dist/register.onboard-BAozmeei.js +97 -0
  315. package/dist/register.onboard-Da9hWQR1.js +93 -0
  316. package/dist/register.setup-DVrQWLoF.js +117 -0
  317. package/dist/register.setup-DbiLuuqg.js +113 -0
  318. package/dist/register.status-health-sessions-CA8ApUkH.js +668 -0
  319. package/dist/register.status-health-sessions-lGszs-NJ.js +428 -0
  320. package/dist/register.subclis-C-lqMygb.js +267 -0
  321. package/dist/replies-BTC1z8j0.js +136 -0
  322. package/dist/replies-BhlnuFp0.js +136 -0
  323. package/dist/reply-DZMooMoq.js +12880 -0
  324. package/dist/reply-directives-C0-hYyAt.js +182 -0
  325. package/dist/reply-directives-C_CGXLBJ.js +182 -0
  326. package/dist/reply-payloads-BospFSPI.js +527 -0
  327. package/dist/reply-prefix-DDgh77yy.js +37 -0
  328. package/dist/reply-prefix-DwKZPZyG.js +37 -0
  329. package/dist/reply-yGEQ0UW4.js +12877 -0
  330. package/dist/resolve-route-B73QhBIl.js +249 -0
  331. package/dist/resolve-route-DckdRbW8.js +249 -0
  332. package/dist/response-prefix-template-x5RBQnEy.js +134 -0
  333. package/dist/retry-CDrH81GP.js +77 -0
  334. package/dist/run-main-D869n5qf.js +307 -0
  335. package/dist/secure-random-CxzxAnMS.js +44 -0
  336. package/dist/security-cli-CfqosyUf.js +487 -0
  337. package/dist/security-cli-DMZun6gO.js +482 -0
  338. package/dist/send-3wvngctD.js +547 -0
  339. package/dist/send-AY7Fs5ky.js +374 -0
  340. package/dist/send-BSWD4Kr_.js +2245 -0
  341. package/dist/send-BT4HhTLm.js +349 -0
  342. package/dist/send-BvuxToC8.js +2245 -0
  343. package/dist/send-CaUxFvu0.js +492 -0
  344. package/dist/send-CiBRE4OY.js +1178 -0
  345. package/dist/send-Cidd4lQn.js +11 -0
  346. package/dist/send-Cq_Db9wG.js +1779 -0
  347. package/dist/send-DBFcxDPm.js +1776 -0
  348. package/dist/send-DUha0nIz.js +492 -0
  349. package/dist/send-DgYBI05s.js +332 -0
  350. package/dist/send-Dnf5bISH.js +426 -0
  351. package/dist/send-NcQk6UH1.js +547 -0
  352. package/dist/send-Og0-IMee.js +29 -0
  353. package/dist/send-oCN80Pl2.js +349 -0
  354. package/dist/server-DoGGLeP3.js +202 -0
  355. package/dist/server-V7G9FG2A.js +206 -0
  356. package/dist/server-lifecycle-CSWpSlvn.js +2437 -0
  357. package/dist/server-lifecycle-Cal8hBP1.js +2437 -0
  358. package/dist/server-node-events-DSee6jSG.js +394 -0
  359. package/dist/server-node-events-DbQWkU3M.js +390 -0
  360. package/dist/service-Duw0xMJX.js +670 -0
  361. package/dist/service-SRcnA1Am.js +670 -0
  362. package/dist/session-BLcfWX5_.js +170 -0
  363. package/dist/session-CQwkaAs-.js +170 -0
  364. package/dist/session-cost-usage-C-UcrvL4.js +627 -0
  365. package/dist/session-cost-usage-Dg3dzS0E.js +627 -0
  366. package/dist/session-dirs-D6mFEF90.js +318 -0
  367. package/dist/session-dirs-DVsG6e7L.js +318 -0
  368. package/dist/session-utils-C6522g3D.js +622 -0
  369. package/dist/session-utils-Dq2BJyVy.js +622 -0
  370. package/dist/sessions-CNkj4Eq8.js +247 -0
  371. package/dist/sessions-DDIoP7Rl.js +2569 -0
  372. package/dist/shell-env-D8nXPDbP.js +163 -0
  373. package/dist/ssrf-7I3FUHpm.js +183 -0
  374. package/dist/ssrf-DZi4qw5c.js +183 -0
  375. package/dist/status-CrAe8ZYt.js +1983 -0
  376. package/dist/status-DetRJxvZ.js +1979 -0
  377. package/dist/status.update-DquSK3p7.js +449 -0
  378. package/dist/status.update-iABAY3iW.js +449 -0
  379. package/dist/store-Bnm6zwaq.js +2571 -0
  380. package/dist/store-CVkGKjWm.js +64 -0
  381. package/dist/store-D_gpBpAW.js +64 -0
  382. package/dist/store-mxh63FBa.js +53 -0
  383. package/dist/subagent-registry-DNAz7Heu.js +4856 -0
  384. package/dist/subagent-registry-Dhz6HC4Z.js +4854 -0
  385. package/dist/subsystem-DGSHVL8I.js +1081 -0
  386. package/dist/subsystem-m7RSGQoR.js +1196 -0
  387. package/dist/system-cli-ByVDF6p8.js +77 -0
  388. package/dist/system-cli-CERb89Bl.js +73 -0
  389. package/dist/systemd-CSUtfsJx.js +547 -0
  390. package/dist/systemd-hints-BCxkQemJ.js +278 -0
  391. package/dist/systemd-hints-ef7m-7ZH.js +278 -0
  392. package/dist/systemd-linger-CWLgT0Wr.js +75 -0
  393. package/dist/systemd-linger-DT0E7YET.js +75 -0
  394. package/dist/systemd-tS61V4ao.js +547 -0
  395. package/dist/tables-DED01JNI.js +55 -0
  396. package/dist/tables-K3rOiGaJ.js +55 -0
  397. package/dist/tables-NcsXz3r_.js +55 -0
  398. package/dist/tailnet-CEudzG0i.js +40 -0
  399. package/dist/tailnet-D66Y5zC7.js +40 -0
  400. package/dist/tailscale-DjSRjPA-.js +230 -0
  401. package/dist/tailscale-DngZHD9L.js +230 -0
  402. package/dist/targets-BOpYPsGM.js +2545 -0
  403. package/dist/targets-BVsxzQh1.js +220 -0
  404. package/dist/targets-C99szk_e.js +114 -0
  405. package/dist/targets-CA4zx5G4.js +650 -0
  406. package/dist/targets-CTNm3bJ8.js +2544 -0
  407. package/dist/targets-DpmQjetK.js +53 -0
  408. package/dist/targets-Q-YGeAqu.js +650 -0
  409. package/dist/targets-rdWlC6Y-.js +53 -0
  410. package/dist/tool-display-Br6mwaJc.js +785 -0
  411. package/dist/tool-display-CLBf5cRa.js +785 -0
  412. package/dist/tool-images-DB4f57XK.js +263 -0
  413. package/dist/tool-images-kloBqxqK.js +263 -0
  414. package/dist/trash-B32LfX0l.js +125 -0
  415. package/dist/trash-SlUJxKO7.js +125 -0
  416. package/dist/tui-CHOtFK6k.js +3282 -0
  417. package/dist/tui-D4yiSpop.js +3282 -0
  418. package/dist/tui-cli-CzrjmAMZ.js +66 -0
  419. package/dist/tui-cli-Dpbs2QW_.js +62 -0
  420. package/dist/update-B5nYVxpc.js +349 -0
  421. package/dist/update-Bs3HhSnE.js +349 -0
  422. package/dist/update-cli-D_yz9Kyz.js +1147 -0
  423. package/dist/update-cli-DdfwNAsA.js +1149 -0
  424. package/dist/usage-BVyabt5E.js +5421 -0
  425. package/dist/voice-credentials-CI4VgB6u.js +46 -0
  426. package/dist/voice-credentials-l_d_gZiG.js +46 -0
  427. package/dist/web-B5xSAAH2.js +74 -0
  428. package/dist/web-Cc4tDVO9.js +3067 -0
  429. package/dist/web-Cdp9_IUk.js +79 -0
  430. package/dist/webhooks-cli-BDPcBkZL.js +330 -0
  431. package/dist/webhooks-cli-sRfsNesg.js +334 -0
  432. package/dist/whatsapp-actions-BGZXdWiP.js +125 -0
  433. package/dist/whatsapp-actions-HdmZu8oU.js +130 -0
  434. package/dist/workspace-D5LAl41l.js +449 -0
  435. package/dist/workspace-DRYGbrDM.js +447 -0
  436. package/dist/zod-schema-C8gEV0uz.js +2739 -0
  437. package/dist/zod-schema-CCUbW_Si.js +2739 -0
  438. package/package.json +1 -1
  439. package/dist/accounts-Aqbb2_Fn.js +0 -270
  440. package/dist/accounts-Bo2bX8jP.js +0 -272
  441. package/dist/accounts-D3fAPVzU.js +0 -36
  442. package/dist/accounts-DUEDngp6.js +0 -32
  443. package/dist/accounts-DZmv4bXS.js +0 -47
  444. package/dist/accounts-DmB4SVPK.js +0 -47
  445. package/dist/accounts-DtkyfvwR.js +0 -36
  446. package/dist/ack-reactions-Bvfy17SM.js +0 -446
  447. package/dist/ack-reactions-DYU8uhcz.js +0 -446
  448. package/dist/acp-cli-DVXhDMc6.js +0 -1324
  449. package/dist/acp-cli-QBL4_qcW.js +0 -1319
  450. package/dist/active-listener-CwxZ24bZ.js +0 -37
  451. package/dist/active-listener-v2sItamh.js +0 -37
  452. package/dist/agent-BisC5WZ6.js +0 -704
  453. package/dist/agent-Bqdrc0AK.js +0 -703
  454. package/dist/agent-helpers-BSGqeJr-.js +0 -400
  455. package/dist/agent-scope-_ND_-bJy.js +0 -116
  456. package/dist/agents-khSbraAA.js +0 -760
  457. package/dist/agents.config-D8gLHPWo.js +0 -116
  458. package/dist/audio-BIvUsncf.js +0 -43
  459. package/dist/audio-CQ8TfmVN.js +0 -43
  460. package/dist/audit-C0x7Cm6K.js +0 -3150
  461. package/dist/audit-CAY-uzWP.js +0 -3150
  462. package/dist/auth-DGqCLaQq.js +0 -448
  463. package/dist/auth-DLTRySEi.js +0 -314
  464. package/dist/auth-Drf91ntw.js +0 -315
  465. package/dist/auth-ku2khJyQ.js +0 -448
  466. package/dist/banner-txHC40UW.js +0 -294
  467. package/dist/binaries-BTvHIrCr.js +0 -13
  468. package/dist/bindings-DsWJQVKh.js +0 -69
  469. package/dist/bonjour-discovery-BElR62fH.js +0 -378
  470. package/dist/bonjour-discovery-C8XyVsjb.js +0 -378
  471. package/dist/browser-cli-DxJew43l.js +0 -1694
  472. package/dist/browser-cli-p0nakrjO.js +0 -1690
  473. package/dist/call-BrTmlOx3.js +0 -518
  474. package/dist/call-ChdUdwb4.js +0 -517
  475. package/dist/catalog-DTlcfTT9.js +0 -185
  476. package/dist/catalog-PixZqhZK.js +0 -185
  477. package/dist/channel-account-context-BO245Tcn.js +0 -133
  478. package/dist/channel-account-context-BgK0hm-I.js +0 -133
  479. package/dist/channel-activity-B0qlUR5e.js +0 -292
  480. package/dist/channel-activity-C-L6rDrQ.js +0 -94
  481. package/dist/channel-activity-DdgLBZ7M.js +0 -94
  482. package/dist/channel-options-CjlvAHSH.js +0 -32
  483. package/dist/channel-options-DpjP7qQf.js +0 -33
  484. package/dist/channel-selection-DW21dXB1.js +0 -51
  485. package/dist/channel-selection-wK_6S2Ku.js +0 -51
  486. package/dist/channel-web-COTkzJBt.js +0 -2136
  487. package/dist/channel-web-DUz5bn9h.js +0 -2134
  488. package/dist/channels-cli-D8RS8g2Q.js +0 -1438
  489. package/dist/channels-cli-X_8rENR6.js +0 -1434
  490. package/dist/channels-status-issues-B6I2l7Sm.js +0 -18
  491. package/dist/channels-status-issues-DhDH2fWp.js +0 -18
  492. package/dist/chrome-Dqtq7zCc.js +0 -1733
  493. package/dist/chrome-XeSY99Z_.js +0 -1732
  494. package/dist/chunk-CWD_zrz_.js +0 -341
  495. package/dist/chunk-LUabyS9k.js +0 -341
  496. package/dist/clack-prompter-fAgbvPW4.js +0 -122
  497. package/dist/clack-prompter-kf9qTN5p.js +0 -121
  498. package/dist/cli-BjPLpuZR.js +0 -133
  499. package/dist/cli-fFyOTtkD.js +0 -129
  500. package/dist/client-B9u3JdT_.js +0 -2316
  501. package/dist/client-DEEOhx0w.js +0 -2316
  502. package/dist/clipboard-B2nstLx7.js +0 -31
  503. package/dist/clipboard-C8QI9fes.js +0 -31
  504. package/dist/command-format-D0vKipG9.js +0 -32
  505. package/dist/command-format-LFmgWzKJ.js +0 -18
  506. package/dist/command-registry-BsPaMI53.js +0 -215
  507. package/dist/commands-BAYwlS3d.js +0 -41
  508. package/dist/commands-D842kCjj.js +0 -41
  509. package/dist/commands-registry-Cg2GTT2J.js +0 -892
  510. package/dist/commands-registry-Yz-uV5oG.js +0 -891
  511. package/dist/common-B67cBSew.js +0 -156
  512. package/dist/common-DEoiTqOr.js +0 -156
  513. package/dist/completion-cli-BO5mIPLa.js +0 -452
  514. package/dist/completion-cli-z9a6MVgr.js +0 -452
  515. package/dist/config-CAa0rZSx.js +0 -4225
  516. package/dist/config-W0w-gi2j.js +0 -4223
  517. package/dist/config-cli-DdRue35G.js +0 -243
  518. package/dist/config-cli-uOwxu5AC.js +0 -247
  519. package/dist/config-guard-BI85dxHR.js +0 -99
  520. package/dist/config-guard-DQqnigKh.js +0 -75
  521. package/dist/config-validation-D-h4LHyA.js +0 -18
  522. package/dist/config-validation-Df_kroIQ.js +0 -18
  523. package/dist/configure-B7ChPbXv.js +0 -891
  524. package/dist/configure-QspkIXME.js +0 -889
  525. package/dist/control-auth-BrBr2xb8.js +0 -397
  526. package/dist/control-auth-CehjYKnL.js +0 -397
  527. package/dist/control-ui-assets-D8F383Mo.js +0 -186
  528. package/dist/control-ui-assets-DYKtRIm0.js +0 -186
  529. package/dist/conversation-label-Bn5j3lUT.js +0 -36
  530. package/dist/conversation-label-CDH4rKMG.js +0 -36
  531. package/dist/cron-cli-DVzDHzAX.js +0 -494
  532. package/dist/cron-cli-gkH2qKM4.js +0 -498
  533. package/dist/daemon-cli-BTdNO1vH.js +0 -737
  534. package/dist/daemon-cli-DNNqI2LD.js +0 -735
  535. package/dist/daemon-install-CaEHG92p.js +0 -56
  536. package/dist/daemon-install-DbpDSDfW.js +0 -60
  537. package/dist/daemon-install-helpers-DjE_WnlY.js +0 -504
  538. package/dist/daemon-install-helpers-DocTUxqQ.js +0 -504
  539. package/dist/deliver-CDcL8ok6.js +0 -481
  540. package/dist/deliver-CS8JsevV.js +0 -481
  541. package/dist/delivery-queue-CTaYZQ_8.js +0 -244
  542. package/dist/delivery-queue-DMZ7mH8P.js +0 -244
  543. package/dist/devices-cli-BBJ4His-.js +0 -319
  544. package/dist/devices-cli-DHSJSFW1.js +0 -323
  545. package/dist/diagnostics-BSvCaLNs.js +0 -35
  546. package/dist/diagnostics-mWFAsFeo.js +0 -35
  547. package/dist/directory-cli-C-oHD_XE.js +0 -224
  548. package/dist/directory-cli-Cw99VGvr.js +0 -220
  549. package/dist/dispatcher-C8d1NNLZ.js +0 -174
  550. package/dist/dispatcher-DY6Ga60j.js +0 -173
  551. package/dist/dm-policy-shared-CRQ-Wr5g.js +0 -22
  552. package/dist/dm-policy-shared-CXXf2ltd.js +0 -22
  553. package/dist/dns-cli-BOqx9qo1.js +0 -199
  554. package/dist/dns-cli-WfqSC3JU.js +0 -203
  555. package/dist/dock-Big-J2VN.js +0 -929
  556. package/dist/dock-Cj4PKiUh.js +0 -928
  557. package/dist/doctor-completion-hYqcZ7IE.js +0 -92
  558. package/dist/doctor-completion-nxQQ5bEw.js +0 -92
  559. package/dist/doctor-config-flow-BUuADMDa.js +0 -1935
  560. package/dist/doctor-config-flow-yOUpQC2B.js +0 -1934
  561. package/dist/enable-DC9V0nTO.js +0 -59
  562. package/dist/env-B3zr72vQ.js +0 -60
  563. package/dist/errors-CdmXrBic.js +0 -35
  564. package/dist/errors-Cr_NbOb4.js +0 -35
  565. package/dist/exec-D_s-zAtY.js +0 -164
  566. package/dist/exec-Zz6eJ6YU.js +0 -164
  567. package/dist/fetch-BIZkXB5i.js +0 -67
  568. package/dist/fetch-DRVdxxEj.js +0 -67
  569. package/dist/fetch-DTR2MlOk.js +0 -67
  570. package/dist/file-lock-6NXMPZTT.js +0 -107
  571. package/dist/file-lock-C_KRlR7M.js +0 -107
  572. package/dist/fs-safe-DZHpH7TI.js +0 -98
  573. package/dist/fs-safe-vm3JMUkq.js +0 -88
  574. package/dist/gateway-cli-DEW-Ukmc.js +0 -24351
  575. package/dist/gateway-cli-DQYcZCOV.js +0 -24347
  576. package/dist/gateway-rpc-BCFkQPa2.js +0 -28
  577. package/dist/gateway-rpc-DOgYbsOG.js +0 -28
  578. package/dist/gmail-setup-utils-DMeA1UM1.js +0 -423
  579. package/dist/gmail-setup-utils-FHWSAur3.js +0 -422
  580. package/dist/health-BrLNGkZV.js +0 -1414
  581. package/dist/health-C8p9mnfl.js +0 -1417
  582. package/dist/heartbeat-visibility-CJVdaMZF.js +0 -125
  583. package/dist/heartbeat-visibility-DwK1UL0t.js +0 -125
  584. package/dist/hook-runner-global-C0DFQmQw.js +0 -527
  585. package/dist/hooks-cli-DEKi-tbA.js +0 -1221
  586. package/dist/hooks-cli-FndXPMD3.js +0 -1225
  587. package/dist/image-ops-B9ofmzSq.js +0 -354
  588. package/dist/image-ops-CMuvRsMY.js +0 -354
  589. package/dist/import-BH13F5mT.js +0 -606
  590. package/dist/import-D8HVcDqO.js +0 -604
  591. package/dist/inbound-context-BLy-G2Eq.js +0 -68
  592. package/dist/inbound-context-CmmmT8IP.js +0 -68
  593. package/dist/inbound-path-policy-BdmTOUka.js +0 -90
  594. package/dist/inbound-path-policy-BurOAu44.js +0 -90
  595. package/dist/inspect-nW8LAukU.js +0 -286
  596. package/dist/inspect-xy2EHy8G.js +0 -286
  597. package/dist/installs-CpfHmKY1.js +0 -325
  598. package/dist/installs-DebiMrGj.js +0 -325
  599. package/dist/ipv4-ysiNGssl.js +0 -46
  600. package/dist/ipv4-zc_Hfvbp.js +0 -46
  601. package/dist/ir-CaxTklDC.js +0 -940
  602. package/dist/lifecycle-core-Z5SScMlU.js +0 -476
  603. package/dist/lifecycle-core-pPwYSt7m.js +0 -474
  604. package/dist/loader-BapIdJyx.js +0 -22404
  605. package/dist/loader-BdAToyDH.js +0 -22401
  606. package/dist/local-roots-CrJ_Jv_G.js +0 -314
  607. package/dist/local-roots-n_Y4iYwb.js +0 -313
  608. package/dist/logger-B8yHnzPl.js +0 -49
  609. package/dist/login-C99fsB0N.js +0 -61
  610. package/dist/login-cLvGPjeO.js +0 -62
  611. package/dist/login-qr-CGqRFwgl.js +0 -329
  612. package/dist/login-qr-dnY5DC2C.js +0 -325
  613. package/dist/logs-cli-Bda7xY4N.js +0 -236
  614. package/dist/logs-cli-HzR-vnpD.js +0 -240
  615. package/dist/markdown-tables-58Hq__7K.js +0 -29
  616. package/dist/markdown-tables-GFEX0OR6.js +0 -29
  617. package/dist/media-CFsyXs3H.js +0 -940
  618. package/dist/media-Du5SHtnp.js +0 -10452
  619. package/dist/message-action-names-BfuEvR6j.js +0 -2521
  620. package/dist/message-action-names-CVBkpOLt.js +0 -2521
  621. package/dist/message-channel-FMNRI5Ax.js +0 -91
  622. package/dist/mime-AuIDUZPG.js +0 -149
  623. package/dist/mime-Cqg1jjia.js +0 -149
  624. package/dist/net-BEFkF-nI.js +0 -225
  625. package/dist/net-CNsUGiSw.js +0 -225
  626. package/dist/node-cli-Bu-InsO9.js +0 -1462
  627. package/dist/node-cli-DE7Pm7Fr.js +0 -1458
  628. package/dist/node-service-CumFZc9L.js +0 -67
  629. package/dist/node-service-DY1gG06I.js +0 -67
  630. package/dist/nodes-cli-B5aAExN0.js +0 -1350
  631. package/dist/nodes-cli-eKRqlKuO.js +0 -1346
  632. package/dist/nodes-screen-B3Sij1uT.js +0 -250
  633. package/dist/nodes-screen-DEvpoFmH.js +0 -250
  634. package/dist/note-CPFJCWJJ.js +0 -92
  635. package/dist/npm-registry-spec-BgMtTHvq.js +0 -786
  636. package/dist/npm-registry-spec-Dz3z1Zpd.js +0 -786
  637. package/dist/npm-resolution-Buio63BQ.js +0 -86
  638. package/dist/npm-resolution-gH1zHW2a.js +0 -86
  639. package/dist/onboard-BSf6qJWk.js +0 -647
  640. package/dist/onboard-V-SsZRk-.js +0 -649
  641. package/dist/onboard-auth-C_wHkop1.js +0 -207
  642. package/dist/onboard-auth-CkCBLvTg.js +0 -211
  643. package/dist/onboard-channels-DQTGPC18.js +0 -2548
  644. package/dist/onboard-channels-DSDQfR0u.js +0 -2547
  645. package/dist/onboard-helpers-Q7M6vdzh.js +0 -363
  646. package/dist/onboard-helpers-SCO3k5Y8.js +0 -364
  647. package/dist/onboard-remote-Co2hv1AD.js +0 -127
  648. package/dist/onboard-remote-Dl3BFSg2.js +0 -127
  649. package/dist/onboarding-B0bJfZ20.js +0 -588
  650. package/dist/onboarding-CeBR9OBi.js +0 -586
  651. package/dist/onboarding.finalize-BPgfWPB9.js +0 -404
  652. package/dist/onboarding.finalize-BmfLvNPJ.js +0 -402
  653. package/dist/onboarding.gateway-config-BL0Q7Wpg.js +0 -201
  654. package/dist/onboarding.gateway-config-D2QsXMYO.js +0 -195
  655. package/dist/outbound-CcaPcetn.js +0 -220
  656. package/dist/outbound-CeiW8z3a.js +0 -221
  657. package/dist/outbound-attachment-BIvFb3Is.js +0 -18
  658. package/dist/outbound-attachment-Bfm5-JYe.js +0 -18
  659. package/dist/outbound-attachment-CZ7zoYxB.js +0 -18
  660. package/dist/pairing-cli-CgX79ujL.js +0 -125
  661. package/dist/pairing-cli-DvbbXFgC.js +0 -129
  662. package/dist/pairing-labels-3wDxaApH.js +0 -9
  663. package/dist/pairing-labels-DCbWnbWk.js +0 -9
  664. package/dist/pairing-store-CdY7iRS0.js +0 -459
  665. package/dist/pairing-store-DykkYpQ7.js +0 -460
  666. package/dist/path-env-Cqo5LZmw.js +0 -89
  667. package/dist/path-env-GTM4HXCN.js +0 -89
  668. package/dist/path-safety-CXKAVpMp.js +0 -14
  669. package/dist/path-safety-DGB91qBk.js +0 -14
  670. package/dist/plugin-auto-enable-C6FPGg_-.js +0 -301
  671. package/dist/plugin-auto-enable-L8eOc8iC.js +0 -302
  672. package/dist/plugin-registry-CHlaWZD7.js +0 -33
  673. package/dist/plugin-registry-DQdMze4z.js +0 -33
  674. package/dist/plugin-sdk/auth/session-override.d.ts +0 -17
  675. package/dist/plugin-sdk/auto-reply/reply/directive-handling.auth.d.ts +0 -18
  676. package/dist/plugin-sdk/link-understanding/apply.d.ts +0 -10
  677. package/dist/plugin-sdk/link-understanding/defaults.d.ts +0 -2
  678. package/dist/plugin-sdk/link-understanding/detect.d.ts +0 -3
  679. package/dist/plugin-sdk/link-understanding/format.d.ts +0 -4
  680. package/dist/plugin-sdk/link-understanding/runner.d.ts +0 -11
  681. package/dist/plugin-sdk/media/input-files.d.ts +0 -95
  682. package/dist/plugin-sdk/media-understanding/apply.d.ts +0 -19
  683. package/dist/plugin-sdk/media-understanding/attachments.d.ts +0 -49
  684. package/dist/plugin-sdk/media-understanding/concurrency.d.ts +0 -1
  685. package/dist/plugin-sdk/media-understanding/defaults.d.ts +0 -11
  686. package/dist/plugin-sdk/media-understanding/errors.d.ts +0 -6
  687. package/dist/plugin-sdk/media-understanding/format.d.ts +0 -7
  688. package/dist/plugin-sdk/media-understanding/fs.d.ts +0 -1
  689. package/dist/plugin-sdk/media-understanding/output-extract.d.ts +0 -2
  690. package/dist/plugin-sdk/media-understanding/providers/anthropic/index.d.ts +0 -2
  691. package/dist/plugin-sdk/media-understanding/providers/deepgram/audio.d.ts +0 -1
  692. package/dist/plugin-sdk/media-understanding/providers/deepgram/index.d.ts +0 -2
  693. package/dist/plugin-sdk/media-understanding/providers/google/audio.d.ts +0 -1
  694. package/dist/plugin-sdk/media-understanding/providers/google/index.d.ts +0 -2
  695. package/dist/plugin-sdk/media-understanding/providers/google/video.d.ts +0 -3
  696. package/dist/plugin-sdk/media-understanding/providers/groq/index.d.ts +0 -2
  697. package/dist/plugin-sdk/media-understanding/providers/index.d.ts +0 -4
  698. package/dist/plugin-sdk/media-understanding/providers/minimax/index.d.ts +0 -2
  699. package/dist/plugin-sdk/media-understanding/providers/mistral/index.d.ts +0 -2
  700. package/dist/plugin-sdk/media-understanding/providers/moonshot/index.d.ts +0 -2
  701. package/dist/plugin-sdk/media-understanding/providers/moonshot/video.d.ts +0 -3
  702. package/dist/plugin-sdk/media-understanding/providers/openai/audio.d.ts +0 -1
  703. package/dist/plugin-sdk/media-understanding/providers/openai/index.d.ts +0 -2
  704. package/dist/plugin-sdk/media-understanding/providers/shared.d.ts +0 -20
  705. package/dist/plugin-sdk/media-understanding/providers/zai/index.d.ts +0 -2
  706. package/dist/plugin-sdk/media-understanding/resolve.d.ts +0 -44
  707. package/dist/plugin-sdk/media-understanding/runner.d.ts +0 -34
  708. package/dist/plugin-sdk/media-understanding/runner.entries.d.ts +0 -33
  709. package/dist/plugin-sdk/media-understanding/scope.d.ts +0 -9
  710. package/dist/plugin-sdk/media-understanding/types.d.ts +0 -59
  711. package/dist/plugin-sdk/media-understanding/video.d.ts +0 -2
  712. package/dist/plugin-sdk/utils/mask-api-key.d.ts +0 -1
  713. package/dist/plugin-sdk/utils/run-with-concurrency.d.ts +0 -11
  714. package/dist/plugins-7B167wIj.js +0 -453
  715. package/dist/plugins-BRHOfy1Z.js +0 -455
  716. package/dist/plugins-cli--I43zIaS.js +0 -797
  717. package/dist/plugins-cli-DIxMbY9I.js +0 -801
  718. package/dist/ports-BS8kQkd9.js +0 -96
  719. package/dist/ports-CAqyeQYZ.js +0 -316
  720. package/dist/ports-CTUgXF2d.js +0 -96
  721. package/dist/ports-DqfnVnCw.js +0 -370
  722. package/dist/preflight-CaRJtknt.js +0 -64
  723. package/dist/preflight-DeDRKMx4.js +0 -68
  724. package/dist/program-context-9dv7ClZz.js +0 -474
  725. package/dist/program-wVSvyiD-.js +0 -248
  726. package/dist/prompt-select-styled-BE_4W66Z.js +0 -1672
  727. package/dist/prompt-select-styled-BTPf06Os.js +0 -1669
  728. package/dist/provider-dispatcher-VZWITjmt.js +0 -660
  729. package/dist/provider-dispatcher-zYYGo00g.js +0 -659
  730. package/dist/push-apns-Cj0Ryn18.js +0 -713
  731. package/dist/push-apns-fFfYCqda.js +0 -711
  732. package/dist/pw-ai-CnN2sITD.js +0 -1908
  733. package/dist/pw-ai-fnX3cecw.js +0 -1911
  734. package/dist/qr-cli-CriPg41m.js +0 -349
  735. package/dist/qr-cli-DSURqD0D.js +0 -353
  736. package/dist/redact-snapshot-BecRL_h6.js +0 -2016
  737. package/dist/redact-snapshot-pTdzSrex.js +0 -2016
  738. package/dist/register.agent-B5_1XatO.js +0 -290
  739. package/dist/register.agent-Dba3CYyo.js +0 -1018
  740. package/dist/register.configure-DmwHGsPG.js +0 -128
  741. package/dist/register.configure-DrPlgBqB.js +0 -133
  742. package/dist/register.import-CPQqqdje.js +0 -31
  743. package/dist/register.import-D1UaH1QV.js +0 -29
  744. package/dist/register.maintenance-D76tiF4W.js +0 -501
  745. package/dist/register.maintenance-hUriFBfi.js +0 -499
  746. package/dist/register.message--VzmF3u4.js +0 -685
  747. package/dist/register.message-itNWUdvP.js +0 -689
  748. package/dist/register.onboard-Co8D908b.js +0 -93
  749. package/dist/register.onboard-q8JzWtuv.js +0 -97
  750. package/dist/register.setup-Djc6jZTc.js +0 -113
  751. package/dist/register.setup-hhPii4O7.js +0 -117
  752. package/dist/register.status-health-sessions-C1FhACQB.js +0 -668
  753. package/dist/register.status-health-sessions-DcUegHcH.js +0 -428
  754. package/dist/register.subclis-DAfihpBz.js +0 -267
  755. package/dist/replies-IpiCq1Ht.js +0 -136
  756. package/dist/replies-LSx_XhsP.js +0 -136
  757. package/dist/reply-D0CLqcBY.js +0 -13718
  758. package/dist/reply-Djq8ghfI.js +0 -13715
  759. package/dist/reply-directives-Cz7622Qx.js +0 -182
  760. package/dist/reply-directives-ssnaPNiU.js +0 -182
  761. package/dist/reply-payloads-CQMtrphw.js +0 -527
  762. package/dist/reply-prefix-CWcAZKhE.js +0 -37
  763. package/dist/reply-prefix-Drq7Pf3A.js +0 -37
  764. package/dist/resolve-route-B8uIc2H3.js +0 -249
  765. package/dist/resolve-route-C8ooNlI4.js +0 -249
  766. package/dist/response-prefix-template-DPOggmPO.js +0 -134
  767. package/dist/retry-BdhJlZQI.js +0 -77
  768. package/dist/run-main-B-Cb62fC.js +0 -306
  769. package/dist/runner-DUnmgjJ8.js +0 -2394
  770. package/dist/runner-EobZIrDt.js +0 -2394
  771. package/dist/secure-random-B5qmFc3N.js +0 -44
  772. package/dist/security-cli-05blEYyC.js +0 -482
  773. package/dist/security-cli-DYbt8duB.js +0 -487
  774. package/dist/send-7O3-bRtl.js +0 -547
  775. package/dist/send-9Huf62k3.js +0 -2245
  776. package/dist/send-B9mIJdUo.js +0 -547
  777. package/dist/send-Bj0RXr-a.js +0 -492
  778. package/dist/send-BzkAsn7K.js +0 -29
  779. package/dist/send-CXFhFLP9.js +0 -11
  780. package/dist/send-Ce_BDa8P.js +0 -349
  781. package/dist/send-ChvasRSh.js +0 -1779
  782. package/dist/send-Cl5BhbnF.js +0 -426
  783. package/dist/send-CpebTvM6.js +0 -374
  784. package/dist/send-DWf7BCPe.js +0 -492
  785. package/dist/send-DX8QSuSI.js +0 -1174
  786. package/dist/send-DZRn6PT2.js +0 -332
  787. package/dist/send-Dd2_MykI.js +0 -2245
  788. package/dist/send-IJaUAa8H.js +0 -1776
  789. package/dist/send-vvZXksNU.js +0 -349
  790. package/dist/server-BrzR9JmX.js +0 -206
  791. package/dist/server-_h27-uP_.js +0 -202
  792. package/dist/server-lifecycle-CUdA6Far.js +0 -2437
  793. package/dist/server-lifecycle-DQZWL8iP.js +0 -2437
  794. package/dist/server-node-events-DgB1z2Cx.js +0 -392
  795. package/dist/server-node-events-DtvPfM1I.js +0 -396
  796. package/dist/service-9le8AnC-.js +0 -670
  797. package/dist/service-Drb0kx6I.js +0 -670
  798. package/dist/session-BIAOl5QR.js +0 -170
  799. package/dist/session-Wu00pCn_.js +0 -170
  800. package/dist/session-cost-usage-7plmOKbs.js +0 -627
  801. package/dist/session-cost-usage-CPFxBFUg.js +0 -627
  802. package/dist/session-dirs-CfIrIJxG.js +0 -318
  803. package/dist/session-dirs-DlPpWt5Q.js +0 -318
  804. package/dist/session-utils-Sd9w4vc1.js +0 -622
  805. package/dist/session-utils-iL47hYmZ.js +0 -622
  806. package/dist/sessions-6pKQ3gN3.js +0 -247
  807. package/dist/sessions-ZRmCDdj1.js +0 -2569
  808. package/dist/shell-env-DYZq9PqC.js +0 -163
  809. package/dist/ssrf-B-rF_tZB.js +0 -183
  810. package/dist/ssrf-DJW14Wkh.js +0 -183
  811. package/dist/status-CTRQCXRj.js +0 -1979
  812. package/dist/status-Y67xsH93.js +0 -1983
  813. package/dist/status.update-DlBReI5-.js +0 -449
  814. package/dist/status.update-v7fEQ7R9.js +0 -449
  815. package/dist/store-B5989JkX.js +0 -64
  816. package/dist/store-BgtgYJoX.js +0 -53
  817. package/dist/store-DCrrxHyS.js +0 -2571
  818. package/dist/store-Ql6vAcsg.js +0 -64
  819. package/dist/subagent-registry-BGknZEUI.js +0 -4856
  820. package/dist/subagent-registry-CWeRBjfn.js +0 -4854
  821. package/dist/subsystem-Ct6qOOqZ.js +0 -1079
  822. package/dist/subsystem-PQ64_nsu.js +0 -1136
  823. package/dist/system-cli-CmO-4Rju.js +0 -77
  824. package/dist/system-cli-VBsa18K6.js +0 -73
  825. package/dist/systemd-CqFpK30Y.js +0 -547
  826. package/dist/systemd-fK9AV5bP.js +0 -547
  827. package/dist/systemd-hints-D3rr0j14.js +0 -278
  828. package/dist/systemd-hints-DNOSRaqA.js +0 -278
  829. package/dist/systemd-linger-B907NVVy.js +0 -75
  830. package/dist/systemd-linger-wYksBbM7.js +0 -75
  831. package/dist/tables-Boxa9MJH.js +0 -55
  832. package/dist/tables-CO_kxD0e.js +0 -55
  833. package/dist/tables-WZp8Vt9n.js +0 -55
  834. package/dist/tailnet-CfZhpSnt.js +0 -40
  835. package/dist/tailnet-D0NV0tRJ.js +0 -40
  836. package/dist/tailscale-B__xvMjA.js +0 -230
  837. package/dist/tailscale-q_ZrxUCc.js +0 -230
  838. package/dist/targets-B4rMyQFJ.js +0 -53
  839. package/dist/targets-BHYLCv06.js +0 -2534
  840. package/dist/targets-BjWhDMJM.js +0 -650
  841. package/dist/targets-BnpMZZC_.js +0 -120
  842. package/dist/targets-CHwGDIgO.js +0 -650
  843. package/dist/targets-DIDKlfKI.js +0 -220
  844. package/dist/targets-bqjVeCnF.js +0 -2535
  845. package/dist/targets-mqj9GNg1.js +0 -53
  846. package/dist/tool-display-C0hpLmkw.js +0 -785
  847. package/dist/tool-display-CQTRHo3Z.js +0 -785
  848. package/dist/tool-images-BYY11Gw3.js +0 -263
  849. package/dist/tool-images-CnJ0R8Fo.js +0 -263
  850. package/dist/trash-C0mjnHuW.js +0 -125
  851. package/dist/trash-Cgwc9mLD.js +0 -125
  852. package/dist/tui-9cJnR1dN.js +0 -3282
  853. package/dist/tui-BR3egaFJ.js +0 -3282
  854. package/dist/tui-cli-BYpkhE6J.js +0 -66
  855. package/dist/tui-cli-DndeZyup.js +0 -62
  856. package/dist/update-BJVdkzk7.js +0 -349
  857. package/dist/update-DjI6KTA5.js +0 -349
  858. package/dist/update-cli-B7Rl2Qr2.js +0 -1146
  859. package/dist/update-cli-CFk_jqUm.js +0 -1148
  860. package/dist/usage-CFv4a1Nf.js +0 -5448
  861. package/dist/voice-credentials-D59RcLbl.js +0 -45
  862. package/dist/voice-credentials-fjA7GShF.js +0 -45
  863. package/dist/web-Bs1td8Qw.js +0 -79
  864. package/dist/web-CSiw--Px.js +0 -3070
  865. package/dist/web-jRTtDiNf.js +0 -74
  866. package/dist/webhooks-cli-0yQha2yj.js +0 -334
  867. package/dist/webhooks-cli-ula0bTX-.js +0 -330
  868. package/dist/whatsapp-actions-3NdzsNg1.js +0 -130
  869. package/dist/whatsapp-actions-y_1vjkYY.js +0 -125
  870. package/dist/workspace-BT3X-qCZ.js +0 -449
  871. package/dist/workspace-D5hHXubL.js +0 -447
  872. package/dist/zod-schema-CbqZAIYy.js +0 -2696
  873. package/dist/zod-schema-YGQJEcnj.js +0 -2696
  874. /package/dist/{account-lookup-BOCzCnir.js → account-lookup-CIY_RKhi.js} +0 -0
  875. /package/dist/{account-lookup-C0ndrpt-.js → account-lookup-DGscKBsr.js} +0 -0
  876. /package/dist/{agent-helpers-eEHy5uX2.js → agent-helpers-D83kfcF9.js} +0 -0
  877. /package/dist/{agents.config-BgDBcY4h.js → agents.config-BPe_hkMn.js} +0 -0
  878. /package/dist/{api-Cd_7aESj.js → api-D8QQo5bc.js} +0 -0
  879. /package/dist/{api-DJ_oWYus.js → api-GywrnwRm.js} +0 -0
  880. /package/dist/{argv-BY8EVMTP.js → argv-DW4MYBdJ.js} +0 -0
  881. /package/dist/{bindings-Dr0bGRst.js → bindings-BpL4pISF.js} +0 -0
  882. /package/dist/{brew-CmTYeZk1.js → brew-CBsS-Vq1.js} +0 -0
  883. /package/dist/{brew-V4lMBeE3.js → brew-Clw9vXhE.js} +0 -0
  884. /package/dist/{chat-envelope-CrM0X4sl.js → chat-envelope-CY1yvCc-.js} +0 -0
  885. /package/dist/{chat-envelope-BIujl9Cj.js → chat-envelope-DUMcMMB2.js} +0 -0
  886. /package/dist/{chat-type-CH3W-zKy.js → chat-type-BKe459rw.js} +0 -0
  887. /package/dist/{chat-type-DyovJwCt.js → chat-type-CE6cJOyt.js} +0 -0
  888. /package/dist/{cleanup-utils-CNwlTKyR.js → cleanup-utils-365rf8YN.js} +0 -0
  889. /package/dist/{cleanup-utils-gNzIs9yk.js → cleanup-utils-rqUXvR3Z.js} +0 -0
  890. /package/dist/{cli-name-3MdfbvIR.js → cli-name-7Gb97Vyl.js} +0 -0
  891. /package/dist/{cli-name-CRLBidNP.js → cli-name-Yv30OygA.js} +0 -0
  892. /package/dist/{cli-utils-5ZIfXAfM.js → cli-utils-5W6ugvN5.js} +0 -0
  893. /package/dist/{cli-utils-BUOtyfnU.js → cli-utils-CZJacPS2.js} +0 -0
  894. /package/dist/{client-D5m46AuY.js → client-DQ-Nh-rV.js} +0 -0
  895. /package/dist/{client-DFyI5I0n.js → client-Fi2k2G9Z.js} +0 -0
  896. /package/dist/{command-options-Cn2fc1Of.js → command-options-CXHYeogR.js} +0 -0
  897. /package/dist/{command-options-D2nN4AXX.js → command-options-Cx6evn0x.js} +0 -0
  898. /package/dist/{config-eval-CU2G7a83.js → config-eval-DU_v_3lY.js} +0 -0
  899. /package/dist/{config-eval-BCKpAS_K.js → config-eval-V26Gl6eZ.js} +0 -0
  900. /package/dist/{constants-CRGAZ2ow.js → constants-C7gkSGRE.js} +0 -0
  901. /package/dist/{constants-BAZuhSRm.js → constants-DAiBiWlI.js} +0 -0
  902. /package/dist/{constants-DoYLsBmv.js → constants-DOnQraOP.js} +0 -0
  903. /package/dist/{constants-BBVTjb1j.js → constants-DQxqJVLu.js} +0 -0
  904. /package/dist/{credentials-DMAWNZdV.js → credentials-BHWUBHMd.js} +0 -0
  905. /package/dist/{credentials-Dmc3H-jd.js → credentials-DG0tD6-e.js} +0 -0
  906. /package/dist/{daemon-runtime-CzFI2dPw.js → daemon-runtime-B7Tmba31.js} +0 -0
  907. /package/dist/{daemon-runtime-aQhinwSL.js → daemon-runtime-KyXiP2ib.js} +0 -0
  908. /package/dist/{dangerous-name-matching-BlTBBZns.js → dangerous-name-matching-B4MRPcn-.js} +0 -0
  909. /package/dist/{dangerous-tools-BRmbBvRf.js → dangerous-tools-CIPZZJoN.js} +0 -0
  910. /package/dist/{dangerous-tools-E1i3IoxZ.js → dangerous-tools-D-GNbdpV.js} +0 -0
  911. /package/dist/{fetch-timeout-DBRRPNBi.js → fetch-timeout-CPe2rPLq.js} +0 -0
  912. /package/dist/{fetch-timeout-l_6RdoMw.js → fetch-timeout-DkT3EnRA.js} +0 -0
  913. /package/dist/{file-identity-BnGA6wyc.js → file-identity-C8MIb5lb.js} +0 -0
  914. /package/dist/{format-duration-B-Uv5nOi.js → format-duration-Cd7SCued.js} +0 -0
  915. /package/dist/{format-duration-D1M3Zxu6.js → format-duration-Oj8pTbYL.js} +0 -0
  916. /package/dist/{format-relative-Cywx6ldk.js → format-relative-8dpVUfzZ.js} +0 -0
  917. /package/dist/{format-relative-DcQZUAYl.js → format-relative-BMNeqaxW.js} +0 -0
  918. /package/dist/{health-format-CL2Xq92A.js → health-format-CwLlmYSK.js} +0 -0
  919. /package/dist/{health-format-CVgQD-z9.js → health-format-CycFH5Sj.js} +0 -0
  920. /package/dist/{heartbeat-wake-DLxQm6-U.js → heartbeat-wake-D6Lt5YUk.js} +0 -0
  921. /package/dist/{heartbeat-wake-DjsTDzF3.js → heartbeat-wake-uZkAP-tP.js} +0 -0
  922. /package/dist/{help-format-DM6-OBt-.js → help-format-B0YIbosn.js} +0 -0
  923. /package/dist/{help-format-CJQ7APRn.js → help-format-GeOPYD_A.js} +0 -0
  924. /package/dist/{helpers-BER76F_2.js → helpers-6_MYSJEW.js} +0 -0
  925. /package/dist/{helpers-DSMIGYx2.js → helpers-703bXVlF.js} +0 -0
  926. /package/dist/{helpers-D-r6yhnI.js → helpers-p_u0Gnj_.js} +0 -0
  927. /package/dist/{input-provenance-BgfeDgck.js → input-provenance-C4nlFv5Y.js} +0 -0
  928. /package/dist/{input-provenance-xUsSMOsz.js → input-provenance-duDehu0D.js} +0 -0
  929. /package/dist/{ip-BAhS4rY2.js → ip-BFJnbRh9.js} +0 -0
  930. /package/dist/{ip-BUhsZdJu.js → ip-D0zgNmBV.js} +0 -0
  931. /package/dist/{is-main-BmHYGRhd.js → is-main-BE1Jih91.js} +0 -0
  932. /package/dist/{json-file-B5WEJJye.js → json-file-CsV03dh-.js} +0 -0
  933. /package/dist/{json-file-Dbg7nZg1.js → json-file-CtQKYRLl.js} +0 -0
  934. /package/dist/{json-files-BFGbyEzL.js → json-files-B2yMsppu.js} +0 -0
  935. /package/dist/{json-files-CfhnuGaC.js → json-files-BYH8U7Mx.js} +0 -0
  936. /package/dist/{lanes-4FoQemog.js → lanes-BWL_LwXG.js} +0 -0
  937. /package/dist/{lanes-BhdzrAIa.js → lanes-cHJ5arWg.js} +0 -0
  938. /package/dist/{links-CwTlzaPe.js → links-BFtUmGLH.js} +0 -0
  939. /package/dist/{links-D5vtq30Q.js → links-BNjLUJ9U.js} +0 -0
  940. /package/dist/{location-50gaJF5Z.js → location-BC45kOxc.js} +0 -0
  941. /package/dist/{location-Qo8Ii1zo.js → location-BUhzov-a.js} +0 -0
  942. /package/dist/{logger-IA_Dr_BT.js → logger-1QWMF9Hc.js} +0 -0
  943. /package/dist/{logger-nEdVxm5D.js → logger-BWMPnILd.js} +0 -0
  944. /package/dist/{logger-O6JX52kK.js → logger-Liu31nEU.js} +0 -0
  945. /package/dist/{logging-FctZEleJ.js → logging-CtbzyUjs.js} +0 -0
  946. /package/dist/{logging-BiuZwq5D.js → logging-DJFQvfGD.js} +0 -0
  947. /package/dist/{logging-Bs1VqVFL.js → logging-JiRrQn2_.js} +0 -0
  948. /package/dist/{logging-JZEg5nDp.js → logging-kuFzZMsG.js} +0 -0
  949. /package/dist/{message-channel-tuc9CdEw.js → message-channel-DOyKgFu8.js} +0 -0
  950. /package/dist/{mutable-allowlist-detectors-CtKavajp.js → mutable-allowlist-detectors-4m-Kc8Kn.js} +0 -0
  951. /package/dist/{mutable-allowlist-detectors-TCG6mnbz.js → mutable-allowlist-detectors-BECxOoKX.js} +0 -0
  952. /package/dist/{onboard-config-BxfgUqk6.js → onboard-config-C9so5ggC.js} +0 -0
  953. /package/dist/{onboard-config-DNzlo8Cg.js → onboard-config-oXID97rS.js} +0 -0
  954. /package/dist/{parse-log-line-CT0H1-oQ.js → parse-log-line-BtFI563v.js} +0 -0
  955. /package/dist/{parse-log-line-pij_xhtE.js → parse-log-line-COptqka7.js} +0 -0
  956. /package/dist/{parse-timeout-CvODy9RC.js → parse-timeout-BpphuwYl.js} +0 -0
  957. /package/dist/{path-guards-DOpzcMXz.js → path-guards-DJteVA0d.js} +0 -0
  958. /package/dist/{path-guards-DipYoPVw.js → path-guards-DVRUJZVN.js} +0 -0
  959. /package/dist/plugin-sdk/{media-understanding → stt}/providers/google/inline-data.d.ts +0 -0
  960. /package/dist/{plugins-allowlist-Bcqe9Gd8.js → plugins-allowlist-Clt6dsY6.js} +0 -0
  961. /package/dist/{polls-DQrR-qT3.js → polls-C5xr-8pM.js} +0 -0
  962. /package/dist/{polls-ybwcqkWt.js → polls-DXd67TD8.js} +0 -0
  963. /package/dist/{ports-lsof-CDyv5GJd.js → ports-lsof-xWMTWvMQ.js} +0 -0
  964. /package/dist/{process-scoped-map-BwUkYFQV.js → process-scoped-map-C7KeadUK.js} +0 -0
  965. /package/dist/{process-scoped-map-_zxf_kLz.js → process-scoped-map-CQ1C5MbT.js} +0 -0
  966. /package/dist/{program-context-CG-t6Yp-.js → program-context-LuBAPt4y.js} +0 -0
  967. /package/dist/{progress-DRLmcFiG.js → progress-C-hTn2yV.js} +0 -0
  968. /package/dist/{progress-BOdRbOHD.js → progress-ChmZpgvt.js} +0 -0
  969. /package/dist/{prompt-WEkXwIMT.js → prompt-BXeXEH0o.js} +0 -0
  970. /package/dist/{prompt-BRGfic91.js → prompt-C31r0R5I.js} +0 -0
  971. /package/dist/{prompt-style-B4Cq4PyQ.js → prompt-style-BcM-VSMx.js} +0 -0
  972. /package/dist/{proxy-BMJL0Qog.js → proxy-dRhp8Ykw.js} +0 -0
  973. /package/dist/{pw-ai-state-CwXeO5d0.js → pw-ai-state-CjfcKQoO.js} +0 -0
  974. /package/dist/{pw-ai-state-DaISdsXY.js → pw-ai-state-DfjyEttO.js} +0 -0
  975. /package/dist/{redact-gXuh8MFk.js → redact-D975G-N6.js} +0 -0
  976. /package/dist/{redact-CqWx9rpK.js → redact-Dx1Fue21.js} +0 -0
  977. /package/dist/{redact-identifier-BJOQDEj0.js → redact-identifier-Bqj_YiPd.js} +0 -0
  978. /package/dist/{redact-identifier-DR54qsoT.js → redact-identifier-HyK89Sod.js} +0 -0
  979. /package/dist/{remoteclaw-root-CgNyrbxc.js → remoteclaw-root-B1iQBmbi.js} +0 -0
  980. /package/dist/{remoteclaw-root-u8dAeHID.js → remoteclaw-root-BmYwCzQN.js} +0 -0
  981. /package/dist/{render-CDCvpfhh.js → render-BvFSFJZW.js} +0 -0
  982. /package/dist/{render-CJl4GK1B.js → render-flG67HhW.js} +0 -0
  983. /package/dist/{response-prefix-template-D3ZcJP4E.js → response-prefix-template-DDvbVpx6.js} +0 -0
  984. /package/dist/{retry-cXXk2j6_.js → retry-CByUYDAZ.js} +0 -0
  985. /package/dist/{retry-B19gMxS7.js → retry-oNE3cBeG.js} +0 -0
  986. /package/dist/{runtime-guard-BS55uiSW.js → runtime-guard-CqNug-FG.js} +0 -0
  987. /package/dist/{runtime-guard-CK80eucm.js → runtime-guard-DAHXelsb.js} +0 -0
  988. /package/dist/{runtime-status-BhW7hP_U.js → runtime-status-CM4rzyfO.js} +0 -0
  989. /package/dist/{runtime-status-hFVEC3wO.js → runtime-status-DJYthOLz.js} +0 -0
  990. /package/dist/{secret-equal-CJzes24Z.js → secret-equal-1-dwi8DL.js} +0 -0
  991. /package/dist/{secret-equal-CQAmGfGc.js → secret-equal-CXJEZiWb.js} +0 -0
  992. /package/dist/{secure-random-B3f7Ri2X.js → secure-random-Ba4Y5xG5.js} +0 -0
  993. /package/dist/{secure-random-BkZFG9cd.js → secure-random-C6AVByhV.js} +0 -0
  994. /package/dist/{stagger-B-_Wnofy.js → stagger-CjeisVRF.js} +0 -0
  995. /package/dist/{stagger-B2ORDHsP.js → stagger-vkvpUmOz.js} +0 -0
  996. /package/dist/{status-C6YNwimj.js → status-DNLnVQZ4.js} +0 -0
  997. /package/dist/{status-yrDGXYZM.js → status-DZhl73dM.js} +0 -0
  998. /package/dist/{strip-inbound-meta-0cvL6itU.js → strip-inbound-meta-C3Cwe_ZO.js} +0 -0
  999. /package/dist/{strip-inbound-meta-DjKcSFaW.js → strip-inbound-meta-DuDjnGjC.js} +0 -0
  1000. /package/dist/{table-ByMyHTh_.js → table-B9zSN_7D.js} +0 -0
  1001. /package/dist/{table-C-dba-5-.js → table-j8Ayarot.js} +0 -0
  1002. /package/dist/{target-errors-DJVRKFcU.js → target-errors-ChjvOMuV.js} +0 -0
  1003. /package/dist/{target-errors-GZXDqlUu.js → target-errors-Dn4aykSV.js} +0 -0
  1004. /package/dist/{targets-B_d_1z3N.js → targets-BtGRUQMa.js} +0 -0
  1005. /package/dist/{targets-DOJXjN1U.js → targets-CE4AYRI9.js} +0 -0
  1006. /package/dist/{targets-D01MJGnh.js → targets-DlufWCmy.js} +0 -0
  1007. /package/dist/{targets-WSwPflb6.js → targets-akvAerZF.js} +0 -0
  1008. /package/dist/{text-format-DarxU3JH.js → text-format-VSogn9Yq.js} +0 -0
  1009. /package/dist/{text-format-mr5bZq0f.js → text-format-xeHt9ywT.js} +0 -0
  1010. /package/dist/{thinking-BqJmU6Zp.js → thinking-B171Rc3-.js} +0 -0
  1011. /package/dist/{tokens-C8yGxAcR.js → tokens-B-jmvNR9.js} +0 -0
  1012. /package/dist/{tokens-DAFBx5qr.js → tokens-kTLGxaAF.js} +0 -0
  1013. /package/dist/{usage-BXi79Rq6.js → usage-CRJFqYf8.js} +0 -0
  1014. /package/dist/{usage-C1lHaofV.js → usage-Txvb0Iq2.js} +0 -0
  1015. /package/dist/{usage-format-CD5jsZY1.js → usage-format-70DvrseE.js} +0 -0
  1016. /package/dist/{usage-format-CRVpDVj1.js → usage-format-Bs8DkQtr.js} +0 -0
  1017. /package/dist/{widearea-dns-C-0P7TRi.js → widearea-dns-BOgHvO4O.js} +0 -0
  1018. /package/dist/{widearea-dns-DFZMcfLf.js → widearea-dns-CGhfClCr.js} +0 -0
  1019. /package/dist/{workspace-BJCKO8Ns.js → workspace-DhUqtMK_.js} +0 -0
  1020. /package/dist/{wsl-kFaeW76c.js → wsl-Cs-gowFJ.js} +0 -0
@@ -1,4854 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-Cbj13DAv.js";
2
- import { _ as defaultRuntime, k as normalizeChannelId, o as createSubsystemLogger, qt as resolveStateDir } from "./entry.js";
3
- import { Y as DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH, i as loadConfig } from "./config-W0w-gi2j.js";
4
- import { C as parseAgentSessionKey, S as isSubagentSessionKey, b as isAcpSessionKey, c as normalizeMainKey, h as normalizeAccountId, l as resolveAgentIdFromSessionKey, y as getSubagentDepth } from "./session-key-BF-9YzxC.js";
5
- import { s as parseDurationMs } from "./zod-schema-YGQJEcnj.js";
6
- import { c as resolveDefaultAgentId, l as resolveSessionAgentId } from "./agent-scope-CJW7vnF8.js";
7
- import { a as isInternalMessageChannel, c as normalizeMessageChannel, n as isDeliverableMessageChannel, t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-tuc9CdEw.js";
8
- import { Y as resolveMainSessionKey, b as mergeDeliveryContext, l as loadSessionStore, x as normalizeDeliveryContext, y as deliveryContextFromSession } from "./sessions-ZRmCDdj1.js";
9
- import { r as normalizeChannelId$1, t as getChannelPlugin } from "./plugins-7B167wIj.js";
10
- import { m as resolveStorePath } from "./chat-envelope-CrM0X4sl.js";
11
- import { n as callGateway } from "./call-ChdUdwb4.js";
12
- import { r as CommandLane, s as onAgentEvent, t as AGENT_LANE_NESTED } from "./lanes-4FoQemog.js";
13
- import { a as resolveEffectiveMessagesConfig, n as resolveResponsePrefixTemplate } from "./response-prefix-template-D3ZcJP4E.js";
14
- import { s as sanitizeUserFacingText } from "./agent-helpers-eEHy5uX2.js";
15
- import { r as isSilentReplyText, t as SILENT_REPLY_TOKEN } from "./tokens-C8yGxAcR.js";
16
- import { t as getGlobalHookRunner, u as shouldSuppressReasoningPayload } from "./hook-runner-global-C0DFQmQw.js";
17
- import { n as saveJsonFile, t as loadJsonFile } from "./json-file-B5WEJJye.js";
18
- import os from "node:os";
19
- import path from "node:path";
20
- import fs from "node:fs";
21
- import JSON5 from "json5";
22
- import crypto from "node:crypto";
23
-
24
- //#region src/utils/queue-helpers.ts
25
- function clearQueueSummaryState(state) {
26
- state.droppedCount = 0;
27
- state.summaryLines = [];
28
- }
29
- function previewQueueSummaryPrompt(params) {
30
- return buildQueueSummaryPrompt({
31
- state: {
32
- dropPolicy: params.state.dropPolicy,
33
- droppedCount: params.state.droppedCount,
34
- summaryLines: [...params.state.summaryLines]
35
- },
36
- noun: params.noun,
37
- title: params.title
38
- });
39
- }
40
- function applyQueueRuntimeSettings(params) {
41
- params.target.mode = params.settings.mode;
42
- params.target.debounceMs = typeof params.settings.debounceMs === "number" ? Math.max(0, params.settings.debounceMs) : params.target.debounceMs;
43
- params.target.cap = typeof params.settings.cap === "number" && params.settings.cap > 0 ? Math.floor(params.settings.cap) : params.target.cap;
44
- params.target.dropPolicy = params.settings.dropPolicy ?? params.target.dropPolicy;
45
- }
46
- function elideQueueText(text, limit = 140) {
47
- if (text.length <= limit) return text;
48
- return `${text.slice(0, Math.max(0, limit - 1)).trimEnd()}…`;
49
- }
50
- function buildQueueSummaryLine(text, limit = 160) {
51
- return elideQueueText(text.replace(/\s+/g, " ").trim(), limit);
52
- }
53
- function shouldSkipQueueItem(params) {
54
- if (!params.dedupe) return false;
55
- return params.dedupe(params.item, params.items);
56
- }
57
- function applyQueueDropPolicy(params) {
58
- const cap = params.queue.cap;
59
- if (cap <= 0 || params.queue.items.length < cap) return true;
60
- if (params.queue.dropPolicy === "new") return false;
61
- const dropCount = params.queue.items.length - cap + 1;
62
- const dropped = params.queue.items.splice(0, dropCount);
63
- if (params.queue.dropPolicy === "summarize") {
64
- for (const item of dropped) {
65
- params.queue.droppedCount += 1;
66
- params.queue.summaryLines.push(buildQueueSummaryLine(params.summarize(item)));
67
- }
68
- const limit = Math.max(0, params.summaryLimit ?? cap);
69
- while (params.queue.summaryLines.length > limit) params.queue.summaryLines.shift();
70
- }
71
- return true;
72
- }
73
- function waitForQueueDebounce(queue) {
74
- if (process.env.REMOTECLAW_TEST_FAST === "1") return Promise.resolve();
75
- const debounceMs = Math.max(0, queue.debounceMs);
76
- if (debounceMs <= 0) return Promise.resolve();
77
- return new Promise((resolve) => {
78
- const check = () => {
79
- const since = Date.now() - queue.lastEnqueuedAt;
80
- if (since >= debounceMs) {
81
- resolve();
82
- return;
83
- }
84
- setTimeout(check, debounceMs - since);
85
- };
86
- check();
87
- });
88
- }
89
- function beginQueueDrain(map, key) {
90
- const queue = map.get(key);
91
- if (!queue || queue.draining) return;
92
- queue.draining = true;
93
- return queue;
94
- }
95
- async function drainNextQueueItem(items, run) {
96
- const next = items[0];
97
- if (!next) return false;
98
- await run(next);
99
- items.shift();
100
- return true;
101
- }
102
- async function drainCollectItemIfNeeded(params) {
103
- if (!params.forceIndividualCollect && !params.isCrossChannel) return "skipped";
104
- if (params.isCrossChannel) params.setForceIndividualCollect?.(true);
105
- return await drainNextQueueItem(params.items, params.run) ? "drained" : "empty";
106
- }
107
- async function drainCollectQueueStep(params) {
108
- return await drainCollectItemIfNeeded({
109
- forceIndividualCollect: params.collectState.forceIndividualCollect,
110
- isCrossChannel: params.isCrossChannel,
111
- setForceIndividualCollect: (next) => {
112
- params.collectState.forceIndividualCollect = next;
113
- },
114
- items: params.items,
115
- run: params.run
116
- });
117
- }
118
- function buildQueueSummaryPrompt(params) {
119
- if (params.state.dropPolicy !== "summarize" || params.state.droppedCount <= 0) return;
120
- const noun = params.noun;
121
- const lines = [params.title ?? `[Queue overflow] Dropped ${params.state.droppedCount} ${noun}${params.state.droppedCount === 1 ? "" : "s"} due to cap.`];
122
- if (params.state.summaryLines.length > 0) {
123
- lines.push("Summary:");
124
- for (const line of params.state.summaryLines) lines.push(`- ${line}`);
125
- }
126
- clearQueueSummaryState(params.state);
127
- return lines.join("\n");
128
- }
129
- function buildCollectPrompt(params) {
130
- const blocks = [params.title];
131
- if (params.summary) blocks.push(params.summary);
132
- params.items.forEach((item, idx) => {
133
- blocks.push(params.renderItem(item, idx));
134
- });
135
- return blocks.join("\n\n");
136
- }
137
- function hasCrossChannelItems(items, resolveKey) {
138
- const keys = /* @__PURE__ */ new Set();
139
- let hasUnkeyed = false;
140
- for (const item of items) {
141
- const resolved = resolveKey(item);
142
- if (resolved.cross) return true;
143
- if (!resolved.key) {
144
- hasUnkeyed = true;
145
- continue;
146
- }
147
- keys.add(resolved.key);
148
- }
149
- if (keys.size === 0) return false;
150
- if (hasUnkeyed) return true;
151
- return keys.size > 1;
152
- }
153
-
154
- //#endregion
155
- //#region src/auto-reply/reply/directive-parsing.ts
156
- function skipDirectiveArgPrefix(raw) {
157
- let i = 0;
158
- const len = raw.length;
159
- while (i < len && /\s/.test(raw[i])) i += 1;
160
- if (raw[i] === ":") {
161
- i += 1;
162
- while (i < len && /\s/.test(raw[i])) i += 1;
163
- }
164
- return i;
165
- }
166
- function takeDirectiveToken(raw, startIndex) {
167
- let i = startIndex;
168
- const len = raw.length;
169
- while (i < len && /\s/.test(raw[i])) i += 1;
170
- if (i >= len) return {
171
- token: null,
172
- nextIndex: i
173
- };
174
- const start = i;
175
- while (i < len && !/\s/.test(raw[i])) i += 1;
176
- if (start === i) return {
177
- token: null,
178
- nextIndex: i
179
- };
180
- const token = raw.slice(start, i);
181
- while (i < len && /\s/.test(raw[i])) i += 1;
182
- return {
183
- token,
184
- nextIndex: i
185
- };
186
- }
187
-
188
- //#endregion
189
- //#region src/auto-reply/reply/queue/normalize.ts
190
- function normalizeQueueMode(raw) {
191
- if (!raw) return;
192
- const cleaned = raw.trim().toLowerCase();
193
- if (cleaned === "queue" || cleaned === "queued") return "steer";
194
- if (cleaned === "interrupt" || cleaned === "interrupts" || cleaned === "abort") return "interrupt";
195
- if (cleaned === "steer" || cleaned === "steering") return "steer";
196
- if (cleaned === "followup" || cleaned === "follow-ups" || cleaned === "followups") return "followup";
197
- if (cleaned === "collect" || cleaned === "coalesce") return "collect";
198
- if (cleaned === "steer+backlog" || cleaned === "steer-backlog" || cleaned === "steer_backlog") return "steer-backlog";
199
- }
200
- function normalizeQueueDropPolicy(raw) {
201
- if (!raw) return;
202
- const cleaned = raw.trim().toLowerCase();
203
- if (cleaned === "old" || cleaned === "oldest") return "old";
204
- if (cleaned === "new" || cleaned === "newest") return "new";
205
- if (cleaned === "summarize" || cleaned === "summary") return "summarize";
206
- }
207
-
208
- //#endregion
209
- //#region src/auto-reply/reply/queue/directive.ts
210
- function parseQueueDebounce(raw) {
211
- if (!raw) return;
212
- try {
213
- const parsed = parseDurationMs(raw.trim(), { defaultUnit: "ms" });
214
- if (!parsed || parsed < 0) return;
215
- return Math.round(parsed);
216
- } catch {
217
- return;
218
- }
219
- }
220
- function parseQueueCap(raw) {
221
- if (!raw) return;
222
- const num = Number(raw);
223
- if (!Number.isFinite(num)) return;
224
- const cap = Math.floor(num);
225
- if (cap < 1) return;
226
- return cap;
227
- }
228
- function parseQueueDirectiveArgs(raw) {
229
- const len = raw.length;
230
- let i = skipDirectiveArgPrefix(raw);
231
- let consumed = i;
232
- let queueMode;
233
- let queueReset = false;
234
- let rawMode;
235
- let debounceMs;
236
- let cap;
237
- let dropPolicy;
238
- let rawDebounce;
239
- let rawCap;
240
- let rawDrop;
241
- let hasOptions = false;
242
- const takeToken = () => {
243
- const res = takeDirectiveToken(raw, i);
244
- i = res.nextIndex;
245
- return res.token;
246
- };
247
- while (i < len) {
248
- const token = takeToken();
249
- if (!token) break;
250
- const lowered = token.trim().toLowerCase();
251
- if (lowered === "default" || lowered === "reset" || lowered === "clear") {
252
- queueReset = true;
253
- consumed = i;
254
- break;
255
- }
256
- if (lowered.startsWith("debounce:") || lowered.startsWith("debounce=")) {
257
- rawDebounce = token.split(/[:=]/)[1] ?? "";
258
- debounceMs = parseQueueDebounce(rawDebounce);
259
- hasOptions = true;
260
- consumed = i;
261
- continue;
262
- }
263
- if (lowered.startsWith("cap:") || lowered.startsWith("cap=")) {
264
- rawCap = token.split(/[:=]/)[1] ?? "";
265
- cap = parseQueueCap(rawCap);
266
- hasOptions = true;
267
- consumed = i;
268
- continue;
269
- }
270
- if (lowered.startsWith("drop:") || lowered.startsWith("drop=")) {
271
- rawDrop = token.split(/[:=]/)[1] ?? "";
272
- dropPolicy = normalizeQueueDropPolicy(rawDrop);
273
- hasOptions = true;
274
- consumed = i;
275
- continue;
276
- }
277
- const mode = normalizeQueueMode(token);
278
- if (mode) {
279
- queueMode = mode;
280
- rawMode = token;
281
- consumed = i;
282
- continue;
283
- }
284
- break;
285
- }
286
- return {
287
- consumed,
288
- queueMode,
289
- queueReset,
290
- rawMode,
291
- debounceMs,
292
- cap,
293
- dropPolicy,
294
- rawDebounce,
295
- rawCap,
296
- rawDrop,
297
- hasOptions
298
- };
299
- }
300
- function extractQueueDirective(body) {
301
- if (!body) return {
302
- cleaned: "",
303
- hasDirective: false,
304
- queueReset: false,
305
- hasOptions: false
306
- };
307
- const match = /(?:^|\s)\/queue(?=$|\s|:)/i.exec(body);
308
- if (!match) return {
309
- cleaned: body.trim(),
310
- hasDirective: false,
311
- queueReset: false,
312
- hasOptions: false
313
- };
314
- const start = match.index + match[0].indexOf("/queue");
315
- const argsStart = start + 6;
316
- const parsed = parseQueueDirectiveArgs(body.slice(argsStart));
317
- return {
318
- cleaned: `${body.slice(0, start)} ${body.slice(argsStart + parsed.consumed)}`.replace(/\s+/g, " ").trim(),
319
- queueMode: parsed.queueMode,
320
- queueReset: parsed.queueReset,
321
- rawMode: parsed.rawMode,
322
- debounceMs: parsed.debounceMs,
323
- cap: parsed.cap,
324
- dropPolicy: parsed.dropPolicy,
325
- rawDebounce: parsed.rawDebounce,
326
- rawCap: parsed.rawCap,
327
- rawDrop: parsed.rawDrop,
328
- hasDirective: true,
329
- hasOptions: parsed.hasOptions
330
- };
331
- }
332
-
333
- //#endregion
334
- //#region src/infra/diagnostic-events.ts
335
- function getDiagnosticEventsState() {
336
- const globalStore = globalThis;
337
- if (!globalStore.__remoteclawDiagnosticEventsState) globalStore.__remoteclawDiagnosticEventsState = {
338
- seq: 0,
339
- listeners: /* @__PURE__ */ new Set(),
340
- dispatchDepth: 0
341
- };
342
- return globalStore.__remoteclawDiagnosticEventsState;
343
- }
344
- function isDiagnosticsEnabled(config) {
345
- return config?.diagnostics?.enabled === true;
346
- }
347
- function emitDiagnosticEvent(event) {
348
- const state = getDiagnosticEventsState();
349
- if (state.dispatchDepth > 100) {
350
- console.error(`[diagnostic-events] recursion guard tripped at depth=${state.dispatchDepth}, dropping type=${event.type}`);
351
- return;
352
- }
353
- const enriched = {
354
- ...event,
355
- seq: state.seq += 1,
356
- ts: Date.now()
357
- };
358
- state.dispatchDepth += 1;
359
- for (const listener of state.listeners) try {
360
- listener(enriched);
361
- } catch (err) {
362
- const errorMessage = err instanceof Error ? err.stack ?? err.message : typeof err === "string" ? err : String(err);
363
- console.error(`[diagnostic-events] listener error type=${enriched.type} seq=${enriched.seq}: ${errorMessage}`);
364
- }
365
- state.dispatchDepth -= 1;
366
- }
367
-
368
- //#endregion
369
- //#region src/logging/diagnostic-session-state.ts
370
- const diagnosticSessionStates = /* @__PURE__ */ new Map();
371
- const SESSION_STATE_TTL_MS = 1800 * 1e3;
372
- const SESSION_STATE_PRUNE_INTERVAL_MS = 60 * 1e3;
373
- const SESSION_STATE_MAX_ENTRIES = 2e3;
374
- let lastSessionPruneAt = 0;
375
- function pruneDiagnosticSessionStates(now = Date.now(), force = false) {
376
- const shouldPruneForSize = diagnosticSessionStates.size > SESSION_STATE_MAX_ENTRIES;
377
- if (!force && !shouldPruneForSize && now - lastSessionPruneAt < SESSION_STATE_PRUNE_INTERVAL_MS) return;
378
- lastSessionPruneAt = now;
379
- for (const [key, state] of diagnosticSessionStates.entries()) {
380
- const ageMs = now - state.lastActivity;
381
- if (state.state === "idle" && state.queueDepth <= 0 && ageMs > SESSION_STATE_TTL_MS) diagnosticSessionStates.delete(key);
382
- }
383
- if (diagnosticSessionStates.size <= SESSION_STATE_MAX_ENTRIES) return;
384
- const excess = diagnosticSessionStates.size - SESSION_STATE_MAX_ENTRIES;
385
- const ordered = Array.from(diagnosticSessionStates.entries()).toSorted((a, b) => a[1].lastActivity - b[1].lastActivity);
386
- for (let i = 0; i < excess; i += 1) {
387
- const key = ordered[i]?.[0];
388
- if (!key) break;
389
- diagnosticSessionStates.delete(key);
390
- }
391
- }
392
- function resolveSessionKey({ sessionKey, sessionId }) {
393
- return sessionKey ?? sessionId ?? "unknown";
394
- }
395
- function findStateBySessionId(sessionId) {
396
- for (const state of diagnosticSessionStates.values()) if (state.sessionId === sessionId) return state;
397
- }
398
- function getDiagnosticSessionState(ref) {
399
- pruneDiagnosticSessionStates();
400
- const key = resolveSessionKey(ref);
401
- const existing = diagnosticSessionStates.get(key) ?? (ref.sessionId && findStateBySessionId(ref.sessionId));
402
- if (existing) {
403
- if (ref.sessionId) existing.sessionId = ref.sessionId;
404
- if (ref.sessionKey) existing.sessionKey = ref.sessionKey;
405
- return existing;
406
- }
407
- const created = {
408
- sessionId: ref.sessionId,
409
- sessionKey: ref.sessionKey,
410
- lastActivity: Date.now(),
411
- state: "idle",
412
- queueDepth: 0
413
- };
414
- diagnosticSessionStates.set(key, created);
415
- pruneDiagnosticSessionStates(Date.now(), true);
416
- return created;
417
- }
418
-
419
- //#endregion
420
- //#region src/logging/diagnostic.ts
421
- const diag = createSubsystemLogger("diagnostic");
422
- const webhookStats = {
423
- received: 0,
424
- processed: 0,
425
- errors: 0,
426
- lastReceived: 0
427
- };
428
- let lastActivityAt = 0;
429
- function markActivity() {
430
- lastActivityAt = Date.now();
431
- }
432
- function logWebhookReceived(params) {
433
- webhookStats.received += 1;
434
- webhookStats.lastReceived = Date.now();
435
- if (diag.isEnabled("debug")) diag.debug(`webhook received: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} total=${webhookStats.received}`);
436
- emitDiagnosticEvent({
437
- type: "webhook.received",
438
- channel: params.channel,
439
- updateType: params.updateType,
440
- chatId: params.chatId
441
- });
442
- markActivity();
443
- }
444
- function logWebhookProcessed(params) {
445
- webhookStats.processed += 1;
446
- if (diag.isEnabled("debug")) diag.debug(`webhook processed: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} duration=${params.durationMs ?? 0}ms processed=${webhookStats.processed}`);
447
- emitDiagnosticEvent({
448
- type: "webhook.processed",
449
- channel: params.channel,
450
- updateType: params.updateType,
451
- chatId: params.chatId,
452
- durationMs: params.durationMs
453
- });
454
- markActivity();
455
- }
456
- function logWebhookError(params) {
457
- webhookStats.errors += 1;
458
- diag.error(`webhook error: channel=${params.channel} type=${params.updateType ?? "unknown"} chatId=${params.chatId ?? "unknown"} error="${params.error}" errors=${webhookStats.errors}`);
459
- emitDiagnosticEvent({
460
- type: "webhook.error",
461
- channel: params.channel,
462
- updateType: params.updateType,
463
- chatId: params.chatId,
464
- error: params.error
465
- });
466
- markActivity();
467
- }
468
- function logMessageQueued(params) {
469
- const state = getDiagnosticSessionState(params);
470
- state.queueDepth += 1;
471
- state.lastActivity = Date.now();
472
- if (diag.isEnabled("debug")) diag.debug(`message queued: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} source=${params.source} queueDepth=${state.queueDepth} sessionState=${state.state}`);
473
- emitDiagnosticEvent({
474
- type: "message.queued",
475
- sessionId: state.sessionId,
476
- sessionKey: state.sessionKey,
477
- channel: params.channel,
478
- source: params.source,
479
- queueDepth: state.queueDepth
480
- });
481
- markActivity();
482
- }
483
- function logMessageProcessed(params) {
484
- if (params.outcome === "error" ? diag.isEnabled("error") : diag.isEnabled("debug")) {
485
- const payload = `message processed: channel=${params.channel} chatId=${params.chatId ?? "unknown"} messageId=${params.messageId ?? "unknown"} sessionId=${params.sessionId ?? "unknown"} sessionKey=${params.sessionKey ?? "unknown"} outcome=${params.outcome} duration=${params.durationMs ?? 0}ms${params.reason ? ` reason=${params.reason}` : ""}${params.error ? ` error="${params.error}"` : ""}`;
486
- if (params.outcome === "error") diag.error(payload);
487
- else diag.debug(payload);
488
- }
489
- emitDiagnosticEvent({
490
- type: "message.processed",
491
- channel: params.channel,
492
- chatId: params.chatId,
493
- messageId: params.messageId,
494
- sessionId: params.sessionId,
495
- sessionKey: params.sessionKey,
496
- durationMs: params.durationMs,
497
- outcome: params.outcome,
498
- reason: params.reason,
499
- error: params.error
500
- });
501
- markActivity();
502
- }
503
- function logSessionStateChange(params) {
504
- const state = getDiagnosticSessionState(params);
505
- const isProbeSession = state.sessionId?.startsWith("probe-") ?? false;
506
- const prevState = state.state;
507
- state.state = params.state;
508
- state.lastActivity = Date.now();
509
- if (params.state === "idle") state.queueDepth = Math.max(0, state.queueDepth - 1);
510
- if (!isProbeSession && diag.isEnabled("debug")) diag.debug(`session state: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} prev=${prevState} new=${params.state} reason="${params.reason ?? ""}" queueDepth=${state.queueDepth}`);
511
- emitDiagnosticEvent({
512
- type: "session.state",
513
- sessionId: state.sessionId,
514
- sessionKey: state.sessionKey,
515
- prevState,
516
- state: params.state,
517
- reason: params.reason,
518
- queueDepth: state.queueDepth
519
- });
520
- markActivity();
521
- }
522
- function logSessionStuck(params) {
523
- const state = getDiagnosticSessionState(params);
524
- diag.warn(`stuck session: sessionId=${state.sessionId ?? "unknown"} sessionKey=${state.sessionKey ?? "unknown"} state=${params.state} age=${Math.round(params.ageMs / 1e3)}s queueDepth=${state.queueDepth}`);
525
- emitDiagnosticEvent({
526
- type: "session.stuck",
527
- sessionId: state.sessionId,
528
- sessionKey: state.sessionKey,
529
- state: params.state,
530
- ageMs: params.ageMs,
531
- queueDepth: state.queueDepth
532
- });
533
- markActivity();
534
- }
535
- function logLaneDequeue(lane, waitMs, queueSize) {
536
- diag.debug(`lane dequeue: lane=${lane} waitMs=${waitMs} queueSize=${queueSize}`);
537
- emitDiagnosticEvent({
538
- type: "queue.lane.dequeue",
539
- lane,
540
- queueSize,
541
- waitMs
542
- });
543
- markActivity();
544
- }
545
- let heartbeatInterval = null;
546
- function startDiagnosticHeartbeat() {
547
- if (heartbeatInterval) return;
548
- heartbeatInterval = setInterval(() => {
549
- const now = Date.now();
550
- pruneDiagnosticSessionStates(now, true);
551
- const activeCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "processing").length;
552
- const waitingCount = Array.from(diagnosticSessionStates.values()).filter((s) => s.state === "waiting").length;
553
- const totalQueued = Array.from(diagnosticSessionStates.values()).reduce((sum, s) => sum + s.queueDepth, 0);
554
- if (!(lastActivityAt > 0 || webhookStats.received > 0 || activeCount > 0 || waitingCount > 0 || totalQueued > 0)) return;
555
- if (now - lastActivityAt > 12e4 && activeCount === 0 && waitingCount === 0) return;
556
- diag.debug(`heartbeat: webhooks=${webhookStats.received}/${webhookStats.processed}/${webhookStats.errors} active=${activeCount} waiting=${waitingCount} queued=${totalQueued}`);
557
- emitDiagnosticEvent({
558
- type: "diagnostic.heartbeat",
559
- webhooks: {
560
- received: webhookStats.received,
561
- processed: webhookStats.processed,
562
- errors: webhookStats.errors
563
- },
564
- active: activeCount,
565
- waiting: waitingCount,
566
- queued: totalQueued
567
- });
568
- for (const [, state] of diagnosticSessionStates) {
569
- const ageMs = now - state.lastActivity;
570
- if (state.state === "processing" && ageMs > 12e4) logSessionStuck({
571
- sessionId: state.sessionId,
572
- sessionKey: state.sessionKey,
573
- state: state.state,
574
- ageMs
575
- });
576
- }
577
- }, 3e4);
578
- heartbeatInterval.unref?.();
579
- }
580
- function stopDiagnosticHeartbeat() {
581
- if (heartbeatInterval) {
582
- clearInterval(heartbeatInterval);
583
- heartbeatInterval = null;
584
- }
585
- }
586
-
587
- //#endregion
588
- //#region src/process/command-queue.ts
589
- /**
590
- * Dedicated error type thrown when a queued command is rejected because
591
- * its lane was cleared. Callers that fire-and-forget enqueued tasks can
592
- * catch (or ignore) this specific type to avoid unhandled-rejection noise.
593
- */
594
- var CommandLaneClearedError = class extends Error {
595
- constructor(lane) {
596
- super(lane ? `Command lane "${lane}" cleared` : "Command lane cleared");
597
- this.name = "CommandLaneClearedError";
598
- }
599
- };
600
- const lanes = /* @__PURE__ */ new Map();
601
- let nextTaskId = 1;
602
- function getLaneState(lane) {
603
- const existing = lanes.get(lane);
604
- if (existing) return existing;
605
- const created = {
606
- lane,
607
- queue: [],
608
- activeTaskIds: /* @__PURE__ */ new Set(),
609
- maxConcurrent: 1,
610
- draining: false,
611
- generation: 0
612
- };
613
- lanes.set(lane, created);
614
- return created;
615
- }
616
- function completeTask(state, taskId, taskGeneration) {
617
- if (taskGeneration !== state.generation) return false;
618
- state.activeTaskIds.delete(taskId);
619
- return true;
620
- }
621
- function drainLane(lane) {
622
- const state = getLaneState(lane);
623
- if (state.draining) return;
624
- state.draining = true;
625
- const pump = () => {
626
- while (state.activeTaskIds.size < state.maxConcurrent && state.queue.length > 0) {
627
- const entry = state.queue.shift();
628
- const waitedMs = Date.now() - entry.enqueuedAt;
629
- if (waitedMs >= entry.warnAfterMs) {
630
- entry.onWait?.(waitedMs, state.queue.length);
631
- diag.warn(`lane wait exceeded: lane=${lane} waitedMs=${waitedMs} queueAhead=${state.queue.length}`);
632
- }
633
- logLaneDequeue(lane, waitedMs, state.queue.length);
634
- const taskId = nextTaskId++;
635
- const taskGeneration = state.generation;
636
- state.activeTaskIds.add(taskId);
637
- (async () => {
638
- const startTime = Date.now();
639
- try {
640
- const result = await entry.task();
641
- if (completeTask(state, taskId, taskGeneration)) {
642
- diag.debug(`lane task done: lane=${lane} durationMs=${Date.now() - startTime} active=${state.activeTaskIds.size} queued=${state.queue.length}`);
643
- pump();
644
- }
645
- entry.resolve(result);
646
- } catch (err) {
647
- const completedCurrentGeneration = completeTask(state, taskId, taskGeneration);
648
- if (!(lane.startsWith("auth-probe:") || lane.startsWith("session:probe-"))) diag.error(`lane task error: lane=${lane} durationMs=${Date.now() - startTime} error="${String(err)}"`);
649
- if (completedCurrentGeneration) pump();
650
- entry.reject(err);
651
- }
652
- })();
653
- }
654
- state.draining = false;
655
- };
656
- pump();
657
- }
658
- function setCommandLaneConcurrency(lane, maxConcurrent) {
659
- const cleaned = lane.trim() || CommandLane.Main;
660
- const state = getLaneState(cleaned);
661
- state.maxConcurrent = Math.max(1, Math.floor(maxConcurrent));
662
- drainLane(cleaned);
663
- }
664
- function getQueueSize(lane = CommandLane.Main) {
665
- const resolved = lane.trim() || CommandLane.Main;
666
- const state = lanes.get(resolved);
667
- if (!state) return 0;
668
- return state.queue.length + state.activeTaskIds.size;
669
- }
670
- function getTotalQueueSize() {
671
- let total = 0;
672
- for (const s of lanes.values()) total += s.queue.length + s.activeTaskIds.size;
673
- return total;
674
- }
675
- function clearCommandLane(lane = CommandLane.Main) {
676
- const cleaned = lane.trim() || CommandLane.Main;
677
- const state = lanes.get(cleaned);
678
- if (!state) return 0;
679
- const removed = state.queue.length;
680
- const pending = state.queue.splice(0);
681
- for (const entry of pending) entry.reject(new CommandLaneClearedError(cleaned));
682
- return removed;
683
- }
684
- /**
685
- * Reset all lane runtime state to idle. Used after SIGUSR1 in-process
686
- * restarts where interrupted tasks' finally blocks may not run, leaving
687
- * stale active task IDs that permanently block new work from draining.
688
- *
689
- * Bumps lane generation and clears execution counters so stale completions
690
- * from old in-flight tasks are ignored. Queued entries are intentionally
691
- * preserved — they represent pending user work that should still execute
692
- * after restart.
693
- *
694
- * After resetting, drains any lanes that still have queued entries so
695
- * preserved work is pumped immediately rather than waiting for a future
696
- * `enqueueCommandInLane()` call (which may never come).
697
- */
698
- function resetAllLanes() {
699
- const lanesToDrain = [];
700
- for (const state of lanes.values()) {
701
- state.generation += 1;
702
- state.activeTaskIds.clear();
703
- state.draining = false;
704
- if (state.queue.length > 0) lanesToDrain.push(state.lane);
705
- }
706
- for (const lane of lanesToDrain) drainLane(lane);
707
- }
708
- /**
709
- * Returns the total number of actively executing tasks across all lanes
710
- * (excludes queued-but-not-started entries).
711
- */
712
- function getActiveTaskCount() {
713
- let total = 0;
714
- for (const s of lanes.values()) total += s.activeTaskIds.size;
715
- return total;
716
- }
717
- /**
718
- * Wait for all currently active tasks across all lanes to finish.
719
- * Polls at a short interval; resolves when no tasks are active or
720
- * when `timeoutMs` elapses (whichever comes first).
721
- *
722
- * New tasks enqueued after this call are ignored — only tasks that are
723
- * already executing are waited on.
724
- */
725
- function waitForActiveTasks(timeoutMs) {
726
- const POLL_INTERVAL_MS = 50;
727
- const deadline = Date.now() + timeoutMs;
728
- const activeAtStart = /* @__PURE__ */ new Set();
729
- for (const state of lanes.values()) for (const taskId of state.activeTaskIds) activeAtStart.add(taskId);
730
- return new Promise((resolve) => {
731
- const check = () => {
732
- if (activeAtStart.size === 0) {
733
- resolve({ drained: true });
734
- return;
735
- }
736
- let hasPending = false;
737
- for (const state of lanes.values()) {
738
- for (const taskId of state.activeTaskIds) if (activeAtStart.has(taskId)) {
739
- hasPending = true;
740
- break;
741
- }
742
- if (hasPending) break;
743
- }
744
- if (!hasPending) {
745
- resolve({ drained: true });
746
- return;
747
- }
748
- if (Date.now() >= deadline) {
749
- resolve({ drained: false });
750
- return;
751
- }
752
- setTimeout(check, POLL_INTERVAL_MS);
753
- };
754
- check();
755
- });
756
- }
757
-
758
- //#endregion
759
- //#region src/auto-reply/reply/queue/state.ts
760
- const DEFAULT_QUEUE_DEBOUNCE_MS = 1e3;
761
- const DEFAULT_QUEUE_CAP = 20;
762
- const DEFAULT_QUEUE_DROP = "summarize";
763
- const FOLLOWUP_QUEUES = /* @__PURE__ */ new Map();
764
- function getExistingFollowupQueue(key) {
765
- const cleaned = key.trim();
766
- if (!cleaned) return;
767
- return FOLLOWUP_QUEUES.get(cleaned);
768
- }
769
- function getFollowupQueue(key, settings) {
770
- const existing = FOLLOWUP_QUEUES.get(key);
771
- if (existing) {
772
- applyQueueRuntimeSettings({
773
- target: existing,
774
- settings
775
- });
776
- return existing;
777
- }
778
- const created = {
779
- items: [],
780
- draining: false,
781
- lastEnqueuedAt: 0,
782
- mode: settings.mode,
783
- debounceMs: typeof settings.debounceMs === "number" ? Math.max(0, settings.debounceMs) : DEFAULT_QUEUE_DEBOUNCE_MS,
784
- cap: typeof settings.cap === "number" && settings.cap > 0 ? Math.floor(settings.cap) : DEFAULT_QUEUE_CAP,
785
- dropPolicy: settings.dropPolicy ?? DEFAULT_QUEUE_DROP,
786
- droppedCount: 0,
787
- summaryLines: []
788
- };
789
- applyQueueRuntimeSettings({
790
- target: created,
791
- settings
792
- });
793
- FOLLOWUP_QUEUES.set(key, created);
794
- return created;
795
- }
796
- function clearFollowupQueue(key) {
797
- const cleaned = key.trim();
798
- const queue = getExistingFollowupQueue(cleaned);
799
- if (!queue) return 0;
800
- const cleared = queue.items.length + queue.droppedCount;
801
- queue.items.length = 0;
802
- queue.droppedCount = 0;
803
- queue.summaryLines = [];
804
- queue.lastRun = void 0;
805
- queue.lastEnqueuedAt = 0;
806
- FOLLOWUP_QUEUES.delete(cleaned);
807
- return cleared;
808
- }
809
-
810
- //#endregion
811
- //#region src/auto-reply/reply/queue/cleanup.ts
812
- function clearSessionQueues(keys) {
813
- const seen = /* @__PURE__ */ new Set();
814
- let followupCleared = 0;
815
- let laneCleared = 0;
816
- const clearedKeys = [];
817
- for (const key of keys) {
818
- const cleaned = key?.trim();
819
- if (!cleaned || seen.has(cleaned)) continue;
820
- seen.add(cleaned);
821
- clearedKeys.push(cleaned);
822
- followupCleared += clearFollowupQueue(cleaned);
823
- laneCleared += clearCommandLane("default");
824
- }
825
- return {
826
- followupCleared,
827
- laneCleared,
828
- keys: clearedKeys
829
- };
830
- }
831
-
832
- //#endregion
833
- //#region src/line/flex-templates/common.ts
834
- function attachFooterText(bubble, footer) {
835
- bubble.footer = {
836
- type: "box",
837
- layout: "vertical",
838
- contents: [{
839
- type: "text",
840
- text: footer,
841
- size: "xs",
842
- color: "#AAAAAA",
843
- wrap: true,
844
- align: "center"
845
- }],
846
- paddingAll: "lg",
847
- backgroundColor: "#FAFAFA"
848
- };
849
- }
850
-
851
- //#endregion
852
- //#region src/line/flex-templates/schedule-cards.ts
853
- function buildTitleSubtitleHeader(params) {
854
- const { title, subtitle } = params;
855
- const headerContents = [{
856
- type: "text",
857
- text: title,
858
- weight: "bold",
859
- size: "xl",
860
- color: "#111111",
861
- wrap: true
862
- }];
863
- if (subtitle) headerContents.push({
864
- type: "text",
865
- text: subtitle,
866
- size: "sm",
867
- color: "#888888",
868
- margin: "sm",
869
- wrap: true
870
- });
871
- return headerContents;
872
- }
873
- function buildCardHeaderSections(headerContents) {
874
- return [{
875
- type: "box",
876
- layout: "vertical",
877
- contents: headerContents,
878
- paddingBottom: "lg"
879
- }, {
880
- type: "separator",
881
- color: "#EEEEEE"
882
- }];
883
- }
884
- function createMegaBubbleWithFooter(params) {
885
- const bubble = {
886
- type: "bubble",
887
- size: "mega",
888
- body: {
889
- type: "box",
890
- layout: "vertical",
891
- contents: params.bodyContents,
892
- paddingAll: "xl",
893
- backgroundColor: "#FFFFFF"
894
- }
895
- };
896
- if (params.footer) attachFooterText(bubble, params.footer);
897
- return bubble;
898
- }
899
- /**
900
- * Create a receipt/summary card (for orders, transactions, data tables)
901
- *
902
- * Editorial design: Clean table layout with alternating row backgrounds,
903
- * prominent total section, and clear visual hierarchy.
904
- */
905
- function createReceiptCard(params) {
906
- const { title, subtitle, items, total, footer } = params;
907
- const itemRows = items.slice(0, 12).map((item, index) => ({
908
- type: "box",
909
- layout: "horizontal",
910
- contents: [{
911
- type: "text",
912
- text: item.name,
913
- size: "sm",
914
- color: item.highlight ? "#111111" : "#666666",
915
- weight: item.highlight ? "bold" : "regular",
916
- flex: 3,
917
- wrap: true
918
- }, {
919
- type: "text",
920
- text: item.value,
921
- size: "sm",
922
- color: item.highlight ? "#06C755" : "#333333",
923
- weight: item.highlight ? "bold" : "regular",
924
- flex: 2,
925
- align: "end",
926
- wrap: true
927
- }],
928
- paddingAll: "md",
929
- backgroundColor: index % 2 === 0 ? "#FFFFFF" : "#FAFAFA"
930
- }));
931
- const bodyContents = [...buildCardHeaderSections(buildTitleSubtitleHeader({
932
- title,
933
- subtitle
934
- })), {
935
- type: "box",
936
- layout: "vertical",
937
- contents: itemRows,
938
- margin: "md",
939
- cornerRadius: "md",
940
- borderWidth: "light",
941
- borderColor: "#EEEEEE"
942
- }];
943
- if (total) bodyContents.push({
944
- type: "box",
945
- layout: "horizontal",
946
- contents: [{
947
- type: "text",
948
- text: total.label,
949
- size: "lg",
950
- weight: "bold",
951
- color: "#111111",
952
- flex: 2
953
- }, {
954
- type: "text",
955
- text: total.value,
956
- size: "xl",
957
- weight: "bold",
958
- color: "#06C755",
959
- flex: 2,
960
- align: "end"
961
- }],
962
- margin: "xl",
963
- paddingAll: "lg",
964
- backgroundColor: "#F0FDF4",
965
- cornerRadius: "lg"
966
- });
967
- return createMegaBubbleWithFooter({
968
- bodyContents,
969
- footer
970
- });
971
- }
972
- /**
973
- * Create a calendar event card (for meetings, appointments, reminders)
974
- *
975
- * Editorial design: Date as hero, strong typographic hierarchy,
976
- * color-blocked zones, full text wrapping for readability.
977
- */
978
- function createEventCard(params) {
979
- const { title, date, time, location, description, calendar, isAllDay, action } = params;
980
- const dateBlock = {
981
- type: "box",
982
- layout: "vertical",
983
- contents: [{
984
- type: "text",
985
- text: date.toUpperCase(),
986
- size: "sm",
987
- weight: "bold",
988
- color: "#06C755",
989
- wrap: true
990
- }, {
991
- type: "text",
992
- text: isAllDay ? "ALL DAY" : time ?? "",
993
- size: "xxl",
994
- weight: "bold",
995
- color: "#111111",
996
- wrap: true,
997
- margin: "xs"
998
- }],
999
- paddingBottom: "lg",
1000
- borderWidth: "none"
1001
- };
1002
- if (!time && !isAllDay) dateBlock.contents = [{
1003
- type: "text",
1004
- text: date,
1005
- size: "xl",
1006
- weight: "bold",
1007
- color: "#111111",
1008
- wrap: true
1009
- }];
1010
- const bodyContents = [dateBlock, {
1011
- type: "box",
1012
- layout: "horizontal",
1013
- contents: [{
1014
- type: "box",
1015
- layout: "vertical",
1016
- contents: [],
1017
- width: "4px",
1018
- backgroundColor: "#06C755",
1019
- cornerRadius: "2px"
1020
- }, {
1021
- type: "box",
1022
- layout: "vertical",
1023
- contents: [{
1024
- type: "text",
1025
- text: title,
1026
- size: "lg",
1027
- weight: "bold",
1028
- color: "#1a1a1a",
1029
- wrap: true
1030
- }, ...calendar ? [{
1031
- type: "text",
1032
- text: calendar,
1033
- size: "xs",
1034
- color: "#888888",
1035
- margin: "sm",
1036
- wrap: true
1037
- }] : []],
1038
- flex: 1,
1039
- paddingStart: "lg"
1040
- }],
1041
- paddingTop: "lg",
1042
- paddingBottom: "lg",
1043
- borderWidth: "light",
1044
- borderColor: "#EEEEEE"
1045
- }];
1046
- if (location || description) {
1047
- const detailItems = [];
1048
- if (location) detailItems.push({
1049
- type: "box",
1050
- layout: "horizontal",
1051
- contents: [{
1052
- type: "text",
1053
- text: "📍",
1054
- size: "sm",
1055
- flex: 0
1056
- }, {
1057
- type: "text",
1058
- text: location,
1059
- size: "sm",
1060
- color: "#444444",
1061
- margin: "md",
1062
- flex: 1,
1063
- wrap: true
1064
- }],
1065
- alignItems: "flex-start"
1066
- });
1067
- if (description) detailItems.push({
1068
- type: "text",
1069
- text: description,
1070
- size: "sm",
1071
- color: "#666666",
1072
- wrap: true,
1073
- margin: location ? "lg" : "none"
1074
- });
1075
- bodyContents.push({
1076
- type: "box",
1077
- layout: "vertical",
1078
- contents: detailItems,
1079
- margin: "lg",
1080
- paddingAll: "lg",
1081
- backgroundColor: "#F8F9FA",
1082
- cornerRadius: "lg"
1083
- });
1084
- }
1085
- return {
1086
- type: "bubble",
1087
- size: "mega",
1088
- body: {
1089
- type: "box",
1090
- layout: "vertical",
1091
- contents: bodyContents,
1092
- paddingAll: "xl",
1093
- backgroundColor: "#FFFFFF",
1094
- action
1095
- }
1096
- };
1097
- }
1098
- /**
1099
- * Create a calendar agenda card showing multiple events
1100
- *
1101
- * Editorial timeline design: Time-focused left column with event details
1102
- * on the right. Visual accent bars indicate event priority/recency.
1103
- */
1104
- function createAgendaCard(params) {
1105
- const { title, subtitle, events, footer } = params;
1106
- const headerContents = buildTitleSubtitleHeader({
1107
- title,
1108
- subtitle
1109
- });
1110
- const eventItems = events.slice(0, 6).map((event, index) => {
1111
- const isActive = event.isNow || index === 0;
1112
- const accentColor = isActive ? "#06C755" : "#E5E5E5";
1113
- const timeColumn = {
1114
- type: "box",
1115
- layout: "vertical",
1116
- contents: [{
1117
- type: "text",
1118
- text: event.time ?? "—",
1119
- size: "sm",
1120
- weight: isActive ? "bold" : "regular",
1121
- color: isActive ? "#06C755" : "#666666",
1122
- align: "end",
1123
- wrap: true
1124
- }],
1125
- width: "65px",
1126
- justifyContent: "flex-start"
1127
- };
1128
- const dotColumn = {
1129
- type: "box",
1130
- layout: "vertical",
1131
- contents: [{
1132
- type: "box",
1133
- layout: "vertical",
1134
- contents: [],
1135
- width: "10px",
1136
- height: "10px",
1137
- backgroundColor: accentColor,
1138
- cornerRadius: "5px"
1139
- }],
1140
- width: "24px",
1141
- alignItems: "center",
1142
- justifyContent: "flex-start",
1143
- paddingTop: "xs"
1144
- };
1145
- const detailContents = [{
1146
- type: "text",
1147
- text: event.title,
1148
- size: "md",
1149
- weight: "bold",
1150
- color: "#1a1a1a",
1151
- wrap: true
1152
- }];
1153
- const secondaryParts = [];
1154
- if (event.location) secondaryParts.push(event.location);
1155
- if (event.calendar) secondaryParts.push(event.calendar);
1156
- if (secondaryParts.length > 0) detailContents.push({
1157
- type: "text",
1158
- text: secondaryParts.join(" · "),
1159
- size: "xs",
1160
- color: "#888888",
1161
- wrap: true,
1162
- margin: "xs"
1163
- });
1164
- return {
1165
- type: "box",
1166
- layout: "horizontal",
1167
- contents: [
1168
- timeColumn,
1169
- dotColumn,
1170
- {
1171
- type: "box",
1172
- layout: "vertical",
1173
- contents: detailContents,
1174
- flex: 1
1175
- }
1176
- ],
1177
- margin: index > 0 ? "xl" : void 0,
1178
- alignItems: "flex-start"
1179
- };
1180
- });
1181
- return createMegaBubbleWithFooter({
1182
- bodyContents: [...buildCardHeaderSections(headerContents), {
1183
- type: "box",
1184
- layout: "vertical",
1185
- contents: eventItems,
1186
- paddingTop: "xl"
1187
- }],
1188
- footer
1189
- });
1190
- }
1191
-
1192
- //#endregion
1193
- //#region src/line/flex-templates/media-control-cards.ts
1194
- /**
1195
- * Create a media player card for Sonos, Spotify, Apple Music, etc.
1196
- *
1197
- * Editorial design: Album art hero with gradient overlay for text,
1198
- * prominent now-playing indicator, refined playback controls.
1199
- */
1200
- function createMediaPlayerCard(params) {
1201
- const { title, subtitle, source, imageUrl, isPlaying, progress, controls, extraActions } = params;
1202
- const trackInfo = [{
1203
- type: "text",
1204
- text: title,
1205
- weight: "bold",
1206
- size: "xl",
1207
- color: "#111111",
1208
- wrap: true
1209
- }];
1210
- if (subtitle) trackInfo.push({
1211
- type: "text",
1212
- text: subtitle,
1213
- size: "md",
1214
- color: "#666666",
1215
- wrap: true,
1216
- margin: "sm"
1217
- });
1218
- const statusItems = [];
1219
- if (isPlaying !== void 0) statusItems.push({
1220
- type: "box",
1221
- layout: "horizontal",
1222
- contents: [{
1223
- type: "box",
1224
- layout: "vertical",
1225
- contents: [],
1226
- width: "8px",
1227
- height: "8px",
1228
- backgroundColor: isPlaying ? "#06C755" : "#CCCCCC",
1229
- cornerRadius: "4px"
1230
- }, {
1231
- type: "text",
1232
- text: isPlaying ? "Now Playing" : "Paused",
1233
- size: "xs",
1234
- color: isPlaying ? "#06C755" : "#888888",
1235
- weight: "bold",
1236
- margin: "sm"
1237
- }],
1238
- alignItems: "center"
1239
- });
1240
- if (source) statusItems.push({
1241
- type: "text",
1242
- text: source,
1243
- size: "xs",
1244
- color: "#AAAAAA",
1245
- margin: statusItems.length > 0 ? "lg" : void 0
1246
- });
1247
- if (progress) statusItems.push({
1248
- type: "text",
1249
- text: progress,
1250
- size: "xs",
1251
- color: "#888888",
1252
- align: "end",
1253
- flex: 1
1254
- });
1255
- const bodyContents = [{
1256
- type: "box",
1257
- layout: "vertical",
1258
- contents: trackInfo
1259
- }];
1260
- if (statusItems.length > 0) bodyContents.push({
1261
- type: "box",
1262
- layout: "horizontal",
1263
- contents: statusItems,
1264
- margin: "lg",
1265
- alignItems: "center"
1266
- });
1267
- const bubble = {
1268
- type: "bubble",
1269
- size: "mega",
1270
- body: {
1271
- type: "box",
1272
- layout: "vertical",
1273
- contents: bodyContents,
1274
- paddingAll: "xl",
1275
- backgroundColor: "#FFFFFF"
1276
- }
1277
- };
1278
- if (imageUrl) bubble.hero = {
1279
- type: "image",
1280
- url: imageUrl,
1281
- size: "full",
1282
- aspectRatio: "1:1",
1283
- aspectMode: "cover"
1284
- };
1285
- if (controls || extraActions?.length) {
1286
- const footerContents = [];
1287
- if (controls) {
1288
- const controlButtons = [];
1289
- if (controls.previous) controlButtons.push({
1290
- type: "button",
1291
- action: {
1292
- type: "postback",
1293
- label: "⏮",
1294
- data: controls.previous.data
1295
- },
1296
- style: "secondary",
1297
- flex: 1,
1298
- height: "sm"
1299
- });
1300
- if (controls.play) controlButtons.push({
1301
- type: "button",
1302
- action: {
1303
- type: "postback",
1304
- label: "▶",
1305
- data: controls.play.data
1306
- },
1307
- style: isPlaying ? "secondary" : "primary",
1308
- flex: 1,
1309
- height: "sm",
1310
- margin: controls.previous ? "md" : void 0
1311
- });
1312
- if (controls.pause) controlButtons.push({
1313
- type: "button",
1314
- action: {
1315
- type: "postback",
1316
- label: "⏸",
1317
- data: controls.pause.data
1318
- },
1319
- style: isPlaying ? "primary" : "secondary",
1320
- flex: 1,
1321
- height: "sm",
1322
- margin: controlButtons.length > 0 ? "md" : void 0
1323
- });
1324
- if (controls.next) controlButtons.push({
1325
- type: "button",
1326
- action: {
1327
- type: "postback",
1328
- label: "⏭",
1329
- data: controls.next.data
1330
- },
1331
- style: "secondary",
1332
- flex: 1,
1333
- height: "sm",
1334
- margin: controlButtons.length > 0 ? "md" : void 0
1335
- });
1336
- if (controlButtons.length > 0) footerContents.push({
1337
- type: "box",
1338
- layout: "horizontal",
1339
- contents: controlButtons
1340
- });
1341
- }
1342
- if (extraActions?.length) footerContents.push({
1343
- type: "box",
1344
- layout: "horizontal",
1345
- contents: extraActions.slice(0, 2).map((action, index) => ({
1346
- type: "button",
1347
- action: {
1348
- type: "postback",
1349
- label: action.label.slice(0, 15),
1350
- data: action.data
1351
- },
1352
- style: "secondary",
1353
- flex: 1,
1354
- height: "sm",
1355
- margin: index > 0 ? "md" : void 0
1356
- })),
1357
- margin: "md"
1358
- });
1359
- if (footerContents.length > 0) bubble.footer = {
1360
- type: "box",
1361
- layout: "vertical",
1362
- contents: footerContents,
1363
- paddingAll: "lg",
1364
- backgroundColor: "#FAFAFA"
1365
- };
1366
- }
1367
- return bubble;
1368
- }
1369
- /**
1370
- * Create an Apple TV remote card with a D-pad and control rows.
1371
- */
1372
- function createAppleTvRemoteCard(params) {
1373
- const { deviceName, status, actionData } = params;
1374
- const headerContents = [{
1375
- type: "text",
1376
- text: deviceName,
1377
- weight: "bold",
1378
- size: "xl",
1379
- color: "#111111",
1380
- wrap: true
1381
- }];
1382
- if (status) headerContents.push({
1383
- type: "text",
1384
- text: status,
1385
- size: "sm",
1386
- color: "#666666",
1387
- wrap: true,
1388
- margin: "sm"
1389
- });
1390
- const makeButton = (label, data, style = "secondary") => ({
1391
- type: "button",
1392
- action: {
1393
- type: "postback",
1394
- label,
1395
- data
1396
- },
1397
- style,
1398
- height: "sm",
1399
- flex: 1
1400
- });
1401
- const dpadRows = [
1402
- {
1403
- type: "box",
1404
- layout: "horizontal",
1405
- contents: [
1406
- { type: "filler" },
1407
- makeButton("↑", actionData.up),
1408
- { type: "filler" }
1409
- ]
1410
- },
1411
- {
1412
- type: "box",
1413
- layout: "horizontal",
1414
- contents: [
1415
- makeButton("←", actionData.left),
1416
- makeButton("OK", actionData.select, "primary"),
1417
- makeButton("→", actionData.right)
1418
- ],
1419
- margin: "md"
1420
- },
1421
- {
1422
- type: "box",
1423
- layout: "horizontal",
1424
- contents: [
1425
- { type: "filler" },
1426
- makeButton("↓", actionData.down),
1427
- { type: "filler" }
1428
- ],
1429
- margin: "md"
1430
- }
1431
- ];
1432
- const menuRow = {
1433
- type: "box",
1434
- layout: "horizontal",
1435
- contents: [makeButton("Menu", actionData.menu), makeButton("Home", actionData.home)],
1436
- margin: "lg"
1437
- };
1438
- const playbackRow = {
1439
- type: "box",
1440
- layout: "horizontal",
1441
- contents: [makeButton("Play", actionData.play), makeButton("Pause", actionData.pause)],
1442
- margin: "md"
1443
- };
1444
- const volumeRow = {
1445
- type: "box",
1446
- layout: "horizontal",
1447
- contents: [
1448
- makeButton("Vol +", actionData.volumeUp),
1449
- makeButton("Mute", actionData.mute),
1450
- makeButton("Vol -", actionData.volumeDown)
1451
- ],
1452
- margin: "md"
1453
- };
1454
- return {
1455
- type: "bubble",
1456
- size: "mega",
1457
- body: {
1458
- type: "box",
1459
- layout: "vertical",
1460
- contents: [
1461
- {
1462
- type: "box",
1463
- layout: "vertical",
1464
- contents: headerContents
1465
- },
1466
- {
1467
- type: "separator",
1468
- margin: "lg",
1469
- color: "#EEEEEE"
1470
- },
1471
- ...dpadRows,
1472
- menuRow,
1473
- playbackRow,
1474
- volumeRow
1475
- ],
1476
- paddingAll: "xl",
1477
- backgroundColor: "#FFFFFF"
1478
- }
1479
- };
1480
- }
1481
- /**
1482
- * Create a device control card for Apple TV, smart home devices, etc.
1483
- *
1484
- * Editorial design: Device-focused header with status indicator,
1485
- * clean control grid with clear visual hierarchy.
1486
- */
1487
- function createDeviceControlCard(params) {
1488
- const { deviceName, deviceType, status, isOnline, imageUrl, controls } = params;
1489
- const headerContents = [{
1490
- type: "box",
1491
- layout: "horizontal",
1492
- contents: [{
1493
- type: "box",
1494
- layout: "vertical",
1495
- contents: [],
1496
- width: "10px",
1497
- height: "10px",
1498
- backgroundColor: isOnline !== false ? "#06C755" : "#FF5555",
1499
- cornerRadius: "5px"
1500
- }, {
1501
- type: "text",
1502
- text: deviceName,
1503
- weight: "bold",
1504
- size: "xl",
1505
- color: "#111111",
1506
- wrap: true,
1507
- flex: 1,
1508
- margin: "md"
1509
- }],
1510
- alignItems: "center"
1511
- }];
1512
- if (deviceType) headerContents.push({
1513
- type: "text",
1514
- text: deviceType,
1515
- size: "sm",
1516
- color: "#888888",
1517
- margin: "sm"
1518
- });
1519
- if (status) headerContents.push({
1520
- type: "box",
1521
- layout: "vertical",
1522
- contents: [{
1523
- type: "text",
1524
- text: status,
1525
- size: "sm",
1526
- color: "#444444",
1527
- wrap: true
1528
- }],
1529
- margin: "lg",
1530
- paddingAll: "md",
1531
- backgroundColor: "#F8F9FA",
1532
- cornerRadius: "md"
1533
- });
1534
- const bubble = {
1535
- type: "bubble",
1536
- size: "mega",
1537
- body: {
1538
- type: "box",
1539
- layout: "vertical",
1540
- contents: headerContents,
1541
- paddingAll: "xl",
1542
- backgroundColor: "#FFFFFF"
1543
- }
1544
- };
1545
- if (imageUrl) bubble.hero = {
1546
- type: "image",
1547
- url: imageUrl,
1548
- size: "full",
1549
- aspectRatio: "16:9",
1550
- aspectMode: "cover"
1551
- };
1552
- if (controls.length > 0) {
1553
- const rows = [];
1554
- const limitedControls = controls.slice(0, 6);
1555
- for (let i = 0; i < limitedControls.length; i += 2) {
1556
- const rowButtons = [];
1557
- for (let j = i; j < Math.min(i + 2, limitedControls.length); j++) {
1558
- const ctrl = limitedControls[j];
1559
- const buttonLabel = ctrl.icon ? `${ctrl.icon} ${ctrl.label}` : ctrl.label;
1560
- rowButtons.push({
1561
- type: "button",
1562
- action: {
1563
- type: "postback",
1564
- label: buttonLabel.slice(0, 18),
1565
- data: ctrl.data
1566
- },
1567
- style: ctrl.style ?? "secondary",
1568
- flex: 1,
1569
- height: "sm",
1570
- margin: j > i ? "md" : void 0
1571
- });
1572
- }
1573
- if (rowButtons.length === 1) rowButtons.push({ type: "filler" });
1574
- rows.push({
1575
- type: "box",
1576
- layout: "horizontal",
1577
- contents: rowButtons,
1578
- margin: i > 0 ? "md" : void 0
1579
- });
1580
- }
1581
- bubble.footer = {
1582
- type: "box",
1583
- layout: "vertical",
1584
- contents: rows,
1585
- paddingAll: "lg",
1586
- backgroundColor: "#FAFAFA"
1587
- };
1588
- }
1589
- return bubble;
1590
- }
1591
-
1592
- //#endregion
1593
- //#region src/auto-reply/reply/line-directives.ts
1594
- /**
1595
- * Parse LINE-specific directives from text and extract them into ReplyPayload fields.
1596
- *
1597
- * Supported directives:
1598
- * - [[quick_replies: option1, option2, option3]]
1599
- * - [[location: title | address | latitude | longitude]]
1600
- * - [[confirm: question | yes_label | no_label]]
1601
- * - [[buttons: title | text | btn1:data1, btn2:data2]]
1602
- * - [[media_player: title | artist | source | imageUrl | playing/paused]]
1603
- * - [[event: title | date | time | location | description]]
1604
- * - [[agenda: title | event1_title:event1_time, event2_title:event2_time, ...]]
1605
- * - [[device: name | type | status | ctrl1:data1, ctrl2:data2]]
1606
- * - [[appletv_remote: name | status]]
1607
- *
1608
- * Returns the modified payload with directives removed from text and fields populated.
1609
- */
1610
- function parseLineDirectives(payload) {
1611
- let text = payload.text;
1612
- if (!text) return payload;
1613
- const result = { ...payload };
1614
- const lineData = { ...result.channelData?.line };
1615
- const toSlug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "device";
1616
- const lineActionData = (action, extras) => {
1617
- const base = [`line.action=${encodeURIComponent(action)}`];
1618
- if (extras) for (const [key, value] of Object.entries(extras)) base.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
1619
- return base.join("&");
1620
- };
1621
- const quickRepliesMatch = text.match(/\[\[quick_replies:\s*([^\]]+)\]\]/i);
1622
- if (quickRepliesMatch) {
1623
- const options = quickRepliesMatch[1].split(",").map((s) => s.trim()).filter(Boolean);
1624
- if (options.length > 0) lineData.quickReplies = [...lineData.quickReplies || [], ...options];
1625
- text = text.replace(quickRepliesMatch[0], "").trim();
1626
- }
1627
- const locationMatch = text.match(/\[\[location:\s*([^\]]+)\]\]/i);
1628
- if (locationMatch && !lineData.location) {
1629
- const parts = locationMatch[1].split("|").map((s) => s.trim());
1630
- if (parts.length >= 4) {
1631
- const [title, address, latStr, lonStr] = parts;
1632
- const latitude = parseFloat(latStr);
1633
- const longitude = parseFloat(lonStr);
1634
- if (!isNaN(latitude) && !isNaN(longitude)) lineData.location = {
1635
- title: title || "Location",
1636
- address: address || "",
1637
- latitude,
1638
- longitude
1639
- };
1640
- }
1641
- text = text.replace(locationMatch[0], "").trim();
1642
- }
1643
- const confirmMatch = text.match(/\[\[confirm:\s*([^\]]+)\]\]/i);
1644
- if (confirmMatch && !lineData.templateMessage) {
1645
- const parts = confirmMatch[1].split("|").map((s) => s.trim());
1646
- if (parts.length >= 3) {
1647
- const [question, yesPart, noPart] = parts;
1648
- const [yesLabel, yesData] = yesPart.includes(":") ? yesPart.split(":").map((s) => s.trim()) : [yesPart, yesPart.toLowerCase()];
1649
- const [noLabel, noData] = noPart.includes(":") ? noPart.split(":").map((s) => s.trim()) : [noPart, noPart.toLowerCase()];
1650
- lineData.templateMessage = {
1651
- type: "confirm",
1652
- text: question,
1653
- confirmLabel: yesLabel,
1654
- confirmData: yesData,
1655
- cancelLabel: noLabel,
1656
- cancelData: noData,
1657
- altText: question
1658
- };
1659
- }
1660
- text = text.replace(confirmMatch[0], "").trim();
1661
- }
1662
- const buttonsMatch = text.match(/\[\[buttons:\s*([^\]]+)\]\]/i);
1663
- if (buttonsMatch && !lineData.templateMessage) {
1664
- const parts = buttonsMatch[1].split("|").map((s) => s.trim());
1665
- if (parts.length >= 3) {
1666
- const [title, bodyText, actionsStr] = parts;
1667
- const actions = actionsStr.split(",").map((actionStr) => {
1668
- const trimmed = actionStr.trim();
1669
- const colonIndex = (() => {
1670
- const index = trimmed.indexOf(":");
1671
- if (index === -1) return -1;
1672
- const lower = trimmed.toLowerCase();
1673
- if (lower.startsWith("http://") || lower.startsWith("https://")) return -1;
1674
- return index;
1675
- })();
1676
- let label;
1677
- let data;
1678
- if (colonIndex === -1) {
1679
- label = trimmed;
1680
- data = trimmed;
1681
- } else {
1682
- label = trimmed.slice(0, colonIndex).trim();
1683
- data = trimmed.slice(colonIndex + 1).trim();
1684
- }
1685
- if (data.startsWith("http://") || data.startsWith("https://")) return {
1686
- type: "uri",
1687
- label,
1688
- uri: data
1689
- };
1690
- if (data.includes("=")) return {
1691
- type: "postback",
1692
- label,
1693
- data
1694
- };
1695
- return {
1696
- type: "message",
1697
- label,
1698
- data: data || label
1699
- };
1700
- });
1701
- if (actions.length > 0) lineData.templateMessage = {
1702
- type: "buttons",
1703
- title,
1704
- text: bodyText,
1705
- actions: actions.slice(0, 4),
1706
- altText: `${title}: ${bodyText}`
1707
- };
1708
- }
1709
- text = text.replace(buttonsMatch[0], "").trim();
1710
- }
1711
- const mediaPlayerMatch = text.match(/\[\[media_player:\s*([^\]]+)\]\]/i);
1712
- if (mediaPlayerMatch && !lineData.flexMessage) {
1713
- const parts = mediaPlayerMatch[1].split("|").map((s) => s.trim());
1714
- if (parts.length >= 1) {
1715
- const [title, artist, source, imageUrl, statusStr] = parts;
1716
- const isPlaying = statusStr?.toLowerCase() === "playing";
1717
- const validImageUrl = imageUrl?.startsWith("https://") ? imageUrl : void 0;
1718
- const deviceKey = toSlug(source || title || "media");
1719
- const card = createMediaPlayerCard({
1720
- title: title || "Unknown Track",
1721
- subtitle: artist || void 0,
1722
- source: source || void 0,
1723
- imageUrl: validImageUrl,
1724
- isPlaying: statusStr ? isPlaying : void 0,
1725
- controls: {
1726
- previous: { data: lineActionData("previous", { "line.device": deviceKey }) },
1727
- play: { data: lineActionData("play", { "line.device": deviceKey }) },
1728
- pause: { data: lineActionData("pause", { "line.device": deviceKey }) },
1729
- next: { data: lineActionData("next", { "line.device": deviceKey }) }
1730
- }
1731
- });
1732
- lineData.flexMessage = {
1733
- altText: `🎵 ${title}${artist ? ` - ${artist}` : ""}`,
1734
- contents: card
1735
- };
1736
- }
1737
- text = text.replace(mediaPlayerMatch[0], "").trim();
1738
- }
1739
- const eventMatch = text.match(/\[\[event:\s*([^\]]+)\]\]/i);
1740
- if (eventMatch && !lineData.flexMessage) {
1741
- const parts = eventMatch[1].split("|").map((s) => s.trim());
1742
- if (parts.length >= 2) {
1743
- const [title, date, time, location, description] = parts;
1744
- const card = createEventCard({
1745
- title: title || "Event",
1746
- date: date || "TBD",
1747
- time: time || void 0,
1748
- location: location || void 0,
1749
- description: description || void 0
1750
- });
1751
- lineData.flexMessage = {
1752
- altText: `📅 ${title} - ${date}${time ? ` ${time}` : ""}`,
1753
- contents: card
1754
- };
1755
- }
1756
- text = text.replace(eventMatch[0], "").trim();
1757
- }
1758
- const appleTvMatch = text.match(/\[\[appletv_remote:\s*([^\]]+)\]\]/i);
1759
- if (appleTvMatch && !lineData.flexMessage) {
1760
- const parts = appleTvMatch[1].split("|").map((s) => s.trim());
1761
- if (parts.length >= 1) {
1762
- const [deviceName, status] = parts;
1763
- const deviceKey = toSlug(deviceName || "apple_tv");
1764
- const card = createAppleTvRemoteCard({
1765
- deviceName: deviceName || "Apple TV",
1766
- status: status || void 0,
1767
- actionData: {
1768
- up: lineActionData("up", { "line.device": deviceKey }),
1769
- down: lineActionData("down", { "line.device": deviceKey }),
1770
- left: lineActionData("left", { "line.device": deviceKey }),
1771
- right: lineActionData("right", { "line.device": deviceKey }),
1772
- select: lineActionData("select", { "line.device": deviceKey }),
1773
- menu: lineActionData("menu", { "line.device": deviceKey }),
1774
- home: lineActionData("home", { "line.device": deviceKey }),
1775
- play: lineActionData("play", { "line.device": deviceKey }),
1776
- pause: lineActionData("pause", { "line.device": deviceKey }),
1777
- volumeUp: lineActionData("volume_up", { "line.device": deviceKey }),
1778
- volumeDown: lineActionData("volume_down", { "line.device": deviceKey }),
1779
- mute: lineActionData("mute", { "line.device": deviceKey })
1780
- }
1781
- });
1782
- lineData.flexMessage = {
1783
- altText: `📺 ${deviceName || "Apple TV"} Remote`,
1784
- contents: card
1785
- };
1786
- }
1787
- text = text.replace(appleTvMatch[0], "").trim();
1788
- }
1789
- const agendaMatch = text.match(/\[\[agenda:\s*([^\]]+)\]\]/i);
1790
- if (agendaMatch && !lineData.flexMessage) {
1791
- const parts = agendaMatch[1].split("|").map((s) => s.trim());
1792
- if (parts.length >= 2) {
1793
- const [title, eventsStr] = parts;
1794
- const events = eventsStr.split(",").map((eventStr) => {
1795
- const trimmed = eventStr.trim();
1796
- const colonIdx = trimmed.lastIndexOf(":");
1797
- if (colonIdx > 0) return {
1798
- title: trimmed.slice(0, colonIdx).trim(),
1799
- time: trimmed.slice(colonIdx + 1).trim()
1800
- };
1801
- return { title: trimmed };
1802
- });
1803
- const card = createAgendaCard({
1804
- title: title || "Agenda",
1805
- events
1806
- });
1807
- lineData.flexMessage = {
1808
- altText: `📋 ${title} (${events.length} events)`,
1809
- contents: card
1810
- };
1811
- }
1812
- text = text.replace(agendaMatch[0], "").trim();
1813
- }
1814
- const deviceMatch = text.match(/\[\[device:\s*([^\]]+)\]\]/i);
1815
- if (deviceMatch && !lineData.flexMessage) {
1816
- const parts = deviceMatch[1].split("|").map((s) => s.trim());
1817
- if (parts.length >= 1) {
1818
- const [deviceName, deviceType, status, controlsStr] = parts;
1819
- const deviceKey = toSlug(deviceName || "device");
1820
- const controls = controlsStr ? controlsStr.split(",").map((ctrlStr) => {
1821
- const [label, data] = ctrlStr.split(":").map((s) => s.trim());
1822
- return {
1823
- label,
1824
- data: lineActionData(data || label.toLowerCase().replace(/\s+/g, "_"), { "line.device": deviceKey })
1825
- };
1826
- }) : [];
1827
- const card = createDeviceControlCard({
1828
- deviceName: deviceName || "Device",
1829
- deviceType: deviceType || void 0,
1830
- status: status || void 0,
1831
- controls
1832
- });
1833
- lineData.flexMessage = {
1834
- altText: `📱 ${deviceName}${status ? `: ${status}` : ""}`,
1835
- contents: card
1836
- };
1837
- }
1838
- text = text.replace(deviceMatch[0], "").trim();
1839
- }
1840
- text = text.replace(/\n{3,}/g, "\n\n").trim();
1841
- result.text = text || void 0;
1842
- if (Object.keys(lineData).length > 0) result.channelData = {
1843
- ...result.channelData,
1844
- line: lineData
1845
- };
1846
- return result;
1847
- }
1848
- /**
1849
- * Check if text contains any LINE directives
1850
- */
1851
- function hasLineDirectives(text) {
1852
- return /\[\[(quick_replies|location|confirm|buttons|media_player|event|agenda|device|appletv_remote):/i.test(text);
1853
- }
1854
-
1855
- //#endregion
1856
- //#region src/auto-reply/reply/normalize-reply.ts
1857
- function normalizeReplyPayload(payload, opts = {}) {
1858
- const hasMedia = Boolean(payload.mediaUrl || (payload.mediaUrls?.length ?? 0) > 0);
1859
- const hasChannelData = Boolean(payload.channelData && Object.keys(payload.channelData).length > 0);
1860
- const trimmed = payload.text?.trim() ?? "";
1861
- if (!trimmed && !hasMedia && !hasChannelData) {
1862
- opts.onSkip?.("empty");
1863
- return null;
1864
- }
1865
- const silentToken = opts.silentToken ?? SILENT_REPLY_TOKEN;
1866
- let text = payload.text ?? void 0;
1867
- if (text && isSilentReplyText(text, silentToken)) {
1868
- if (!hasMedia && !hasChannelData) {
1869
- opts.onSkip?.("silent");
1870
- return null;
1871
- }
1872
- text = "";
1873
- }
1874
- if (text && !trimmed) text = "";
1875
- if (text) text = sanitizeUserFacingText(text, { errorContext: Boolean(payload.isError) });
1876
- if (!text?.trim() && !hasMedia && !hasChannelData) {
1877
- opts.onSkip?.("empty");
1878
- return null;
1879
- }
1880
- let enrichedPayload = {
1881
- ...payload,
1882
- text
1883
- };
1884
- if (text && hasLineDirectives(text)) {
1885
- enrichedPayload = parseLineDirectives(enrichedPayload);
1886
- text = enrichedPayload.text;
1887
- }
1888
- const effectivePrefix = opts.responsePrefixContext ? resolveResponsePrefixTemplate(opts.responsePrefix, opts.responsePrefixContext) : opts.responsePrefix;
1889
- if (effectivePrefix && text && !text.startsWith(effectivePrefix)) text = `${effectivePrefix} ${text}`;
1890
- return {
1891
- ...enrichedPayload,
1892
- text
1893
- };
1894
- }
1895
-
1896
- //#endregion
1897
- //#region src/auto-reply/reply/route-reply.ts
1898
- /**
1899
- * Provider-agnostic reply router.
1900
- *
1901
- * Routes replies to the originating channel based on OriginatingChannel/OriginatingTo
1902
- * instead of using the session's lastChannel. This ensures replies go back to the
1903
- * provider where the message originated, even when the main session is shared
1904
- * across multiple providers.
1905
- */
1906
- /**
1907
- * Routes a reply payload to the specified channel.
1908
- *
1909
- * This function provides a unified interface for sending messages to any
1910
- * supported provider. It's used by the followup queue to route replies
1911
- * back to the originating channel when OriginatingChannel/OriginatingTo
1912
- * are set.
1913
- */
1914
- async function routeReply(params) {
1915
- const { payload, channel, to, accountId, threadId, cfg, abortSignal } = params;
1916
- if (shouldSuppressReasoningPayload(payload)) return { ok: true };
1917
- const normalizedChannel = normalizeMessageChannel(channel);
1918
- const resolvedAgentId = params.sessionKey ? resolveSessionAgentId({
1919
- sessionKey: params.sessionKey,
1920
- config: cfg
1921
- }) : void 0;
1922
- const normalized = normalizeReplyPayload(payload, { responsePrefix: params.sessionKey ? resolveEffectiveMessagesConfig(cfg, resolvedAgentId ?? resolveSessionAgentId({ config: cfg }), {
1923
- channel: normalizedChannel,
1924
- accountId
1925
- }).responsePrefix : cfg.messages?.responsePrefix === "auto" ? void 0 : cfg.messages?.responsePrefix });
1926
- if (!normalized) return { ok: true };
1927
- let text = normalized.text ?? "";
1928
- let mediaUrls = (normalized.mediaUrls?.filter(Boolean) ?? []).length ? normalized.mediaUrls?.filter(Boolean) : normalized.mediaUrl ? [normalized.mediaUrl] : [];
1929
- const replyToId = normalized.replyToId;
1930
- if (!text.trim() && mediaUrls.length === 0) return { ok: true };
1931
- if (channel === INTERNAL_MESSAGE_CHANNEL) return {
1932
- ok: false,
1933
- error: "Webchat routing not supported for queued replies"
1934
- };
1935
- const channelId = normalizeChannelId$1(channel) ?? null;
1936
- if (!channelId) return {
1937
- ok: false,
1938
- error: `Unknown channel: ${String(channel)}`
1939
- };
1940
- if (abortSignal?.aborted) return {
1941
- ok: false,
1942
- error: "Reply routing aborted"
1943
- };
1944
- const resolvedReplyToId = replyToId ?? (channelId === "slack" && threadId != null && threadId !== "" ? String(threadId) : void 0);
1945
- const resolvedThreadId = channelId === "slack" ? null : threadId ?? null;
1946
- try {
1947
- const { deliverOutboundPayloads } = await import("./deliver-CS8JsevV.js").then((n) => n.n);
1948
- return {
1949
- ok: true,
1950
- messageId: (await deliverOutboundPayloads({
1951
- cfg,
1952
- channel: channelId,
1953
- to,
1954
- accountId: accountId ?? void 0,
1955
- payloads: [normalized],
1956
- replyToId: resolvedReplyToId ?? null,
1957
- threadId: resolvedThreadId,
1958
- agentId: resolvedAgentId,
1959
- abortSignal,
1960
- mirror: params.mirror !== false && params.sessionKey ? {
1961
- sessionKey: params.sessionKey,
1962
- agentId: resolvedAgentId,
1963
- text,
1964
- mediaUrls
1965
- } : void 0
1966
- })).at(-1)?.messageId
1967
- };
1968
- } catch (err) {
1969
- return {
1970
- ok: false,
1971
- error: `Failed to route reply to ${channel}: ${err instanceof Error ? err.message : String(err)}`
1972
- };
1973
- }
1974
- }
1975
- /**
1976
- * Checks if a channel type is routable via routeReply.
1977
- *
1978
- * Some channels (webchat) require special handling and cannot be routed through
1979
- * this generic interface.
1980
- */
1981
- function isRoutableChannel(channel) {
1982
- if (!channel || channel === INTERNAL_MESSAGE_CHANNEL) return false;
1983
- return normalizeChannelId$1(channel) !== null;
1984
- }
1985
-
1986
- //#endregion
1987
- //#region src/auto-reply/reply/queue/drain.ts
1988
- function resolveOriginRoutingMetadata(items) {
1989
- return {
1990
- originatingChannel: items.find((item) => item.originatingChannel)?.originatingChannel,
1991
- originatingTo: items.find((item) => item.originatingTo)?.originatingTo,
1992
- originatingAccountId: items.find((item) => item.originatingAccountId)?.originatingAccountId,
1993
- originatingThreadId: items.find((item) => item.originatingThreadId != null && item.originatingThreadId !== "")?.originatingThreadId
1994
- };
1995
- }
1996
- function resolveCrossChannelKey(item) {
1997
- const { originatingChannel: channel, originatingTo: to, originatingAccountId: accountId } = item;
1998
- const threadId = item.originatingThreadId;
1999
- if (!channel && !to && !accountId && (threadId == null || threadId === "")) return {};
2000
- if (!isRoutableChannel(channel) || !to) return { cross: true };
2001
- return { key: [
2002
- channel,
2003
- to,
2004
- accountId || "",
2005
- threadId != null && threadId !== "" ? String(threadId) : ""
2006
- ].join("|") };
2007
- }
2008
- function scheduleFollowupDrain(key, runFollowup) {
2009
- const queue = beginQueueDrain(FOLLOWUP_QUEUES, key);
2010
- if (!queue) return;
2011
- (async () => {
2012
- try {
2013
- const collectState = { forceIndividualCollect: false };
2014
- while (queue.items.length > 0 || queue.droppedCount > 0) {
2015
- await waitForQueueDebounce(queue);
2016
- if (queue.mode === "collect") {
2017
- const collectDrainResult = await drainCollectQueueStep({
2018
- collectState,
2019
- isCrossChannel: hasCrossChannelItems(queue.items, resolveCrossChannelKey),
2020
- items: queue.items,
2021
- run: runFollowup
2022
- });
2023
- if (collectDrainResult === "empty") break;
2024
- if (collectDrainResult === "drained") continue;
2025
- const items = queue.items.slice();
2026
- const summary = previewQueueSummaryPrompt({
2027
- state: queue,
2028
- noun: "message"
2029
- });
2030
- const run = items.at(-1)?.run ?? queue.lastRun;
2031
- if (!run) break;
2032
- const routing = resolveOriginRoutingMetadata(items);
2033
- await runFollowup({
2034
- prompt: buildCollectPrompt({
2035
- title: "[Queued messages while agent was busy]",
2036
- items,
2037
- summary,
2038
- renderItem: (item, idx) => `---\nQueued #${idx + 1}\n${item.prompt}`.trim()
2039
- }),
2040
- run,
2041
- enqueuedAt: Date.now(),
2042
- ...routing
2043
- });
2044
- queue.items.splice(0, items.length);
2045
- if (summary) clearQueueSummaryState(queue);
2046
- continue;
2047
- }
2048
- const summaryPrompt = previewQueueSummaryPrompt({
2049
- state: queue,
2050
- noun: "message"
2051
- });
2052
- if (summaryPrompt) {
2053
- const run = queue.lastRun;
2054
- if (!run) break;
2055
- if (!await drainNextQueueItem(queue.items, async (item) => {
2056
- await runFollowup({
2057
- prompt: summaryPrompt,
2058
- run,
2059
- enqueuedAt: Date.now(),
2060
- originatingChannel: item.originatingChannel,
2061
- originatingTo: item.originatingTo,
2062
- originatingAccountId: item.originatingAccountId,
2063
- originatingThreadId: item.originatingThreadId
2064
- });
2065
- })) break;
2066
- clearQueueSummaryState(queue);
2067
- continue;
2068
- }
2069
- if (!await drainNextQueueItem(queue.items, runFollowup)) break;
2070
- }
2071
- } catch (err) {
2072
- queue.lastEnqueuedAt = Date.now();
2073
- defaultRuntime.error?.(`followup queue drain failed for ${key}: ${String(err)}`);
2074
- } finally {
2075
- queue.draining = false;
2076
- if (queue.items.length === 0 && queue.droppedCount === 0) FOLLOWUP_QUEUES.delete(key);
2077
- else scheduleFollowupDrain(key, runFollowup);
2078
- }
2079
- })();
2080
- }
2081
-
2082
- //#endregion
2083
- //#region src/auto-reply/reply/queue/enqueue.ts
2084
- function isRunAlreadyQueued(run, items, allowPromptFallback = false) {
2085
- const hasSameRouting = (item) => item.originatingChannel === run.originatingChannel && item.originatingTo === run.originatingTo && item.originatingAccountId === run.originatingAccountId && item.originatingThreadId === run.originatingThreadId;
2086
- const messageId = run.messageId?.trim();
2087
- if (messageId) return items.some((item) => item.messageId?.trim() === messageId && hasSameRouting(item));
2088
- if (!allowPromptFallback) return false;
2089
- return items.some((item) => item.prompt === run.prompt && hasSameRouting(item));
2090
- }
2091
- function enqueueFollowupRun(key, run, settings, dedupeMode = "message-id") {
2092
- const queue = getFollowupQueue(key, settings);
2093
- const dedupe = dedupeMode === "none" ? void 0 : (item, items) => isRunAlreadyQueued(item, items, dedupeMode === "prompt");
2094
- if (shouldSkipQueueItem({
2095
- item: run,
2096
- items: queue.items,
2097
- dedupe
2098
- })) return false;
2099
- queue.lastEnqueuedAt = Date.now();
2100
- queue.lastRun = run.run;
2101
- if (!applyQueueDropPolicy({
2102
- queue,
2103
- summarize: (item) => item.summaryLine?.trim() || item.prompt.trim()
2104
- })) return false;
2105
- queue.items.push(run);
2106
- return true;
2107
- }
2108
- function getFollowupQueueDepth(key) {
2109
- const queue = getExistingFollowupQueue(key);
2110
- if (!queue) return 0;
2111
- return queue.items.length;
2112
- }
2113
-
2114
- //#endregion
2115
- //#region src/auto-reply/reply/queue/settings.ts
2116
- function defaultQueueModeForChannel(_channel) {
2117
- return "collect";
2118
- }
2119
- /** Resolve per-channel debounce override from debounceMsByChannel map. */
2120
- function resolveChannelDebounce(byChannel, channelKey) {
2121
- if (!channelKey || !byChannel) return;
2122
- const value = byChannel[channelKey];
2123
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
2124
- }
2125
- function resolvePluginDebounce(channelKey) {
2126
- if (!channelKey) return;
2127
- const value = getChannelPlugin(channelKey)?.defaults?.queue?.debounceMs;
2128
- return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : void 0;
2129
- }
2130
- function resolveQueueSettings(params) {
2131
- const channelKey = params.channel?.trim().toLowerCase();
2132
- const queueCfg = params.cfg.messages?.queue;
2133
- const providerModeRaw = channelKey && queueCfg?.byChannel ? queueCfg.byChannel[channelKey] : void 0;
2134
- const resolvedMode = params.inlineMode ?? normalizeQueueMode(params.sessionEntry?.queueMode) ?? normalizeQueueMode(providerModeRaw) ?? normalizeQueueMode(queueCfg?.mode) ?? defaultQueueModeForChannel(channelKey);
2135
- const debounceRaw = params.inlineOptions?.debounceMs ?? params.sessionEntry?.queueDebounceMs ?? resolveChannelDebounce(queueCfg?.debounceMsByChannel, channelKey) ?? resolvePluginDebounce(channelKey) ?? queueCfg?.debounceMs ?? DEFAULT_QUEUE_DEBOUNCE_MS;
2136
- const capRaw = params.inlineOptions?.cap ?? params.sessionEntry?.queueCap ?? queueCfg?.cap ?? DEFAULT_QUEUE_CAP;
2137
- const dropRaw = params.inlineOptions?.dropPolicy ?? params.sessionEntry?.queueDrop ?? normalizeQueueDropPolicy(queueCfg?.drop) ?? DEFAULT_QUEUE_DROP;
2138
- return {
2139
- mode: resolvedMode,
2140
- debounceMs: typeof debounceRaw === "number" ? Math.max(0, debounceRaw) : void 0,
2141
- cap: typeof capRaw === "number" ? Math.max(1, Math.floor(capRaw)) : void 0,
2142
- dropPolicy: dropRaw
2143
- };
2144
- }
2145
-
2146
- //#endregion
2147
- //#region src/infra/outbound/session-binding-service.ts
2148
- function normalizeConversationRef(ref) {
2149
- return {
2150
- channel: ref.channel.trim().toLowerCase(),
2151
- accountId: normalizeAccountId(ref.accountId),
2152
- conversationId: ref.conversationId.trim(),
2153
- parentConversationId: ref.parentConversationId?.trim() || void 0
2154
- };
2155
- }
2156
- function toAdapterKey(params) {
2157
- return `${params.channel.trim().toLowerCase()}:${normalizeAccountId(params.accountId)}`;
2158
- }
2159
- const ADAPTERS_BY_CHANNEL_ACCOUNT = /* @__PURE__ */ new Map();
2160
- function registerSessionBindingAdapter(adapter) {
2161
- const key = toAdapterKey({
2162
- channel: adapter.channel,
2163
- accountId: adapter.accountId
2164
- });
2165
- ADAPTERS_BY_CHANNEL_ACCOUNT.set(key, {
2166
- ...adapter,
2167
- channel: adapter.channel.trim().toLowerCase(),
2168
- accountId: normalizeAccountId(adapter.accountId)
2169
- });
2170
- }
2171
- function unregisterSessionBindingAdapter(params) {
2172
- ADAPTERS_BY_CHANNEL_ACCOUNT.delete(toAdapterKey(params));
2173
- }
2174
- function resolveAdapterForConversation(ref) {
2175
- const normalized = normalizeConversationRef(ref);
2176
- const key = toAdapterKey({
2177
- channel: normalized.channel,
2178
- accountId: normalized.accountId
2179
- });
2180
- return ADAPTERS_BY_CHANNEL_ACCOUNT.get(key) ?? null;
2181
- }
2182
- function dedupeBindings(records) {
2183
- const byId = /* @__PURE__ */ new Map();
2184
- for (const record of records) {
2185
- if (!record?.bindingId) continue;
2186
- byId.set(record.bindingId, record);
2187
- }
2188
- return [...byId.values()];
2189
- }
2190
- function createDefaultSessionBindingService() {
2191
- return {
2192
- bind: async (input) => {
2193
- const normalizedConversation = normalizeConversationRef(input.conversation);
2194
- const adapter = resolveAdapterForConversation(normalizedConversation);
2195
- if (!adapter?.bind) throw new Error(`Session binding adapter unavailable for ${normalizedConversation.channel}:${normalizedConversation.accountId}`);
2196
- const bound = await adapter.bind({
2197
- ...input,
2198
- conversation: normalizedConversation
2199
- });
2200
- if (!bound) throw new Error("Session binding adapter failed to bind target conversation");
2201
- return bound;
2202
- },
2203
- listBySession: (targetSessionKey) => {
2204
- const key = targetSessionKey.trim();
2205
- if (!key) return [];
2206
- const results = [];
2207
- for (const adapter of ADAPTERS_BY_CHANNEL_ACCOUNT.values()) {
2208
- const entries = adapter.listBySession(key);
2209
- if (entries.length > 0) results.push(...entries);
2210
- }
2211
- return dedupeBindings(results);
2212
- },
2213
- resolveByConversation: (ref) => {
2214
- const normalized = normalizeConversationRef(ref);
2215
- if (!normalized.channel || !normalized.conversationId) return null;
2216
- const adapter = resolveAdapterForConversation(normalized);
2217
- if (!adapter) return null;
2218
- return adapter.resolveByConversation(normalized);
2219
- },
2220
- touch: (bindingId, at) => {
2221
- const normalizedBindingId = bindingId.trim();
2222
- if (!normalizedBindingId) return;
2223
- for (const adapter of ADAPTERS_BY_CHANNEL_ACCOUNT.values()) adapter.touch?.(normalizedBindingId, at);
2224
- },
2225
- unbind: async (input) => {
2226
- const removed = [];
2227
- for (const adapter of ADAPTERS_BY_CHANNEL_ACCOUNT.values()) {
2228
- if (!adapter.unbind) continue;
2229
- const entries = await adapter.unbind(input);
2230
- if (entries.length > 0) removed.push(...entries);
2231
- }
2232
- return dedupeBindings(removed);
2233
- }
2234
- };
2235
- }
2236
- const DEFAULT_SESSION_BINDING_SERVICE = createDefaultSessionBindingService();
2237
- function getSessionBindingService() {
2238
- return DEFAULT_SESSION_BINDING_SERVICE;
2239
- }
2240
-
2241
- //#endregion
2242
- //#region src/infra/outbound/bound-delivery-router.ts
2243
- function isActiveBinding(record) {
2244
- return record.status === "active";
2245
- }
2246
- function resolveBindingForRequester(requester, bindings) {
2247
- const matchingChannelAccount = bindings.filter((entry) => entry.conversation.channel === requester.channel && entry.conversation.accountId === requester.accountId);
2248
- if (matchingChannelAccount.length === 0) return null;
2249
- const exactConversation = matchingChannelAccount.find((entry) => entry.conversation.conversationId === requester.conversationId);
2250
- if (exactConversation) return exactConversation;
2251
- if (matchingChannelAccount.length === 1) return matchingChannelAccount[0] ?? null;
2252
- return null;
2253
- }
2254
- function createBoundDeliveryRouter(service = getSessionBindingService()) {
2255
- return { resolveDestination: (input) => {
2256
- const targetSessionKey = input.targetSessionKey.trim();
2257
- if (!targetSessionKey) return {
2258
- binding: null,
2259
- mode: "fallback",
2260
- reason: "missing-target-session"
2261
- };
2262
- const activeBindings = service.listBySession(targetSessionKey).filter(isActiveBinding);
2263
- if (activeBindings.length === 0) return {
2264
- binding: null,
2265
- mode: "fallback",
2266
- reason: "no-active-binding"
2267
- };
2268
- if (!input.requester) {
2269
- if (activeBindings.length === 1) return {
2270
- binding: activeBindings[0] ?? null,
2271
- mode: "bound",
2272
- reason: "single-active-binding"
2273
- };
2274
- return {
2275
- binding: null,
2276
- mode: "fallback",
2277
- reason: "ambiguous-without-requester"
2278
- };
2279
- }
2280
- const requester = {
2281
- channel: input.requester.channel.trim().toLowerCase(),
2282
- accountId: input.requester.accountId.trim(),
2283
- conversationId: input.requester.conversationId.trim(),
2284
- parentConversationId: input.requester.parentConversationId?.trim() || void 0
2285
- };
2286
- if (!requester.channel || !requester.conversationId) return {
2287
- binding: null,
2288
- mode: "fallback",
2289
- reason: "invalid-requester"
2290
- };
2291
- const fromRequester = resolveBindingForRequester(requester, activeBindings);
2292
- if (fromRequester) return {
2293
- binding: fromRequester,
2294
- mode: "bound",
2295
- reason: "requester-match"
2296
- };
2297
- if (activeBindings.length === 1 && !input.failClosed) return {
2298
- binding: activeBindings[0] ?? null,
2299
- mode: "bound",
2300
- reason: "single-active-binding-fallback"
2301
- };
2302
- return {
2303
- binding: null,
2304
- mode: "fallback",
2305
- reason: "no-requester-match"
2306
- };
2307
- } };
2308
- }
2309
-
2310
- //#endregion
2311
- //#region src/shared/chat-content.ts
2312
- function extractTextFromChatContent(content, opts) {
2313
- const normalize = opts?.normalizeText ?? ((text) => text.replace(/\s+/g, " ").trim());
2314
- const joinWith = opts?.joinWith ?? " ";
2315
- if (typeof content === "string") {
2316
- const normalized = normalize(opts?.sanitizeText ? opts.sanitizeText(content) : content);
2317
- return normalized ? normalized : null;
2318
- }
2319
- if (!Array.isArray(content)) return null;
2320
- const chunks = [];
2321
- for (const block of content) {
2322
- if (!block || typeof block !== "object") continue;
2323
- if (block.type !== "text") continue;
2324
- const text = block.text;
2325
- if (typeof text !== "string") continue;
2326
- const value = opts?.sanitizeText ? opts.sanitizeText(text) : text;
2327
- if (value.trim()) chunks.push(value);
2328
- }
2329
- const joined = normalize(chunks.join(joinWith));
2330
- return joined ? joined : null;
2331
- }
2332
-
2333
- //#endregion
2334
- //#region src/agents/announce-idempotency.ts
2335
- function buildAnnounceIdFromChildRun(params) {
2336
- return `v1:${params.childSessionKey}:${params.childRunId}`;
2337
- }
2338
- function buildAnnounceIdempotencyKey(announceId) {
2339
- return `announce:${announceId}`;
2340
- }
2341
-
2342
- //#endregion
2343
- //#region src/agents/subagent-depth.ts
2344
- function normalizeSpawnDepth(value) {
2345
- if (typeof value === "number") return Number.isInteger(value) && value >= 0 ? value : void 0;
2346
- if (typeof value === "string") {
2347
- const trimmed = value.trim();
2348
- if (!trimmed) return;
2349
- const numeric = Number(trimmed);
2350
- return Number.isInteger(numeric) && numeric >= 0 ? numeric : void 0;
2351
- }
2352
- }
2353
- function normalizeSessionKey(value) {
2354
- if (typeof value !== "string") return;
2355
- return value.trim() || void 0;
2356
- }
2357
- function readSessionStore(storePath) {
2358
- try {
2359
- const raw = fs.readFileSync(storePath, "utf-8");
2360
- const parsed = JSON5.parse(raw);
2361
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
2362
- } catch {}
2363
- return {};
2364
- }
2365
- function buildKeyCandidates(rawKey, cfg) {
2366
- if (!cfg) return [rawKey];
2367
- if (rawKey === "global" || rawKey === "unknown") return [rawKey];
2368
- if (parseAgentSessionKey(rawKey)) return [rawKey];
2369
- const prefixed = `agent:${resolveDefaultAgentId(cfg)}:${rawKey}`;
2370
- return prefixed === rawKey ? [rawKey] : [rawKey, prefixed];
2371
- }
2372
- function findEntryBySessionId(store, sessionId) {
2373
- const normalizedSessionId = normalizeSessionKey(sessionId);
2374
- if (!normalizedSessionId) return;
2375
- for (const entry of Object.values(store)) {
2376
- const candidateSessionId = normalizeSessionKey(entry?.sessionId);
2377
- if (candidateSessionId && candidateSessionId === normalizedSessionId) return entry;
2378
- }
2379
- }
2380
- function resolveEntryForSessionKey(params) {
2381
- const candidates = buildKeyCandidates(params.sessionKey, params.cfg);
2382
- if (params.store) {
2383
- for (const key of candidates) {
2384
- const entry = params.store[key];
2385
- if (entry) return entry;
2386
- }
2387
- return findEntryBySessionId(params.store, params.sessionKey);
2388
- }
2389
- if (!params.cfg) return;
2390
- for (const key of candidates) {
2391
- const parsed = parseAgentSessionKey(key);
2392
- if (!parsed?.agentId) continue;
2393
- const storePath = resolveStorePath(params.cfg.session?.store, { agentId: parsed.agentId });
2394
- let store = params.cache.get(storePath);
2395
- if (!store) {
2396
- store = readSessionStore(storePath);
2397
- params.cache.set(storePath, store);
2398
- }
2399
- const entry = store[key] ?? findEntryBySessionId(store, params.sessionKey);
2400
- if (entry) return entry;
2401
- }
2402
- }
2403
- function getSubagentDepthFromSessionStore(sessionKey, opts) {
2404
- const raw = (sessionKey ?? "").trim();
2405
- const fallbackDepth = getSubagentDepth(raw);
2406
- if (!raw) return fallbackDepth;
2407
- const cache = /* @__PURE__ */ new Map();
2408
- const visited = /* @__PURE__ */ new Set();
2409
- const depthFromStore = (key) => {
2410
- const normalizedKey = normalizeSessionKey(key);
2411
- if (!normalizedKey) return;
2412
- if (visited.has(normalizedKey)) return;
2413
- visited.add(normalizedKey);
2414
- const entry = resolveEntryForSessionKey({
2415
- sessionKey: normalizedKey,
2416
- cfg: opts?.cfg,
2417
- store: opts?.store,
2418
- cache
2419
- });
2420
- const storedDepth = normalizeSpawnDepth(entry?.spawnDepth);
2421
- if (storedDepth !== void 0) return storedDepth;
2422
- const spawnedBy = normalizeSessionKey(entry?.spawnedBy);
2423
- if (!spawnedBy) return;
2424
- const parentDepth = depthFromStore(spawnedBy);
2425
- if (parentDepth !== void 0) return parentDepth + 1;
2426
- return getSubagentDepth(spawnedBy) + 1;
2427
- };
2428
- return depthFromStore(raw) ?? fallbackDepth;
2429
- }
2430
-
2431
- //#endregion
2432
- //#region src/agents/tools/sessions-resolution.ts
2433
- function resolveMainSessionAlias(cfg) {
2434
- const mainKey = normalizeMainKey(cfg.session?.mainKey);
2435
- const scope = cfg.session?.scope ?? "per-sender";
2436
- return {
2437
- mainKey,
2438
- alias: scope === "global" ? "global" : mainKey,
2439
- scope
2440
- };
2441
- }
2442
- function resolveDisplaySessionKey(params) {
2443
- if (params.key === params.alias) return "main";
2444
- if (params.key === params.mainKey) return "main";
2445
- return params.key;
2446
- }
2447
- function resolveInternalSessionKey(params) {
2448
- if (params.key === "main") return params.alias;
2449
- return params.key;
2450
- }
2451
- async function listSpawnedSessionKeys(params) {
2452
- const limit = typeof params.limit === "number" && Number.isFinite(params.limit) ? Math.max(1, Math.floor(params.limit)) : 500;
2453
- try {
2454
- const list = await callGateway({
2455
- method: "sessions.list",
2456
- params: {
2457
- includeGlobal: false,
2458
- includeUnknown: false,
2459
- limit,
2460
- spawnedBy: params.requesterSessionKey
2461
- }
2462
- });
2463
- const keys = (Array.isArray(list?.sessions) ? list.sessions : []).map((entry) => typeof entry?.key === "string" ? entry.key : "").map((value) => value.trim()).filter(Boolean);
2464
- return new Set(keys);
2465
- } catch {
2466
- return /* @__PURE__ */ new Set();
2467
- }
2468
- }
2469
- async function isRequesterSpawnedSessionVisible(params) {
2470
- if (params.requesterSessionKey === params.targetSessionKey) return true;
2471
- return (await listSpawnedSessionKeys({
2472
- requesterSessionKey: params.requesterSessionKey,
2473
- limit: params.limit
2474
- })).has(params.targetSessionKey);
2475
- }
2476
- function shouldVerifyRequesterSpawnedSessionVisibility(params) {
2477
- return params.restrictToSpawned && !params.resolvedViaSessionId && params.requesterSessionKey !== params.targetSessionKey;
2478
- }
2479
- async function isResolvedSessionVisibleToRequester(params) {
2480
- if (!shouldVerifyRequesterSpawnedSessionVisibility({
2481
- requesterSessionKey: params.requesterSessionKey,
2482
- targetSessionKey: params.targetSessionKey,
2483
- restrictToSpawned: params.restrictToSpawned,
2484
- resolvedViaSessionId: params.resolvedViaSessionId
2485
- })) return true;
2486
- return await isRequesterSpawnedSessionVisible({
2487
- requesterSessionKey: params.requesterSessionKey,
2488
- targetSessionKey: params.targetSessionKey,
2489
- limit: params.limit
2490
- });
2491
- }
2492
- const SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2493
- function looksLikeSessionId(value) {
2494
- return SESSION_ID_RE.test(value.trim());
2495
- }
2496
- function looksLikeSessionKey(value) {
2497
- const raw = value.trim();
2498
- if (!raw) return false;
2499
- if (raw === "main" || raw === "global" || raw === "unknown") return true;
2500
- if (isAcpSessionKey(raw)) return true;
2501
- if (raw.startsWith("agent:")) return true;
2502
- if (raw.startsWith("cron:") || raw.startsWith("hook:")) return true;
2503
- if (raw.startsWith("node-") || raw.startsWith("node:")) return true;
2504
- if (raw.includes(":group:") || raw.includes(":channel:")) return true;
2505
- return false;
2506
- }
2507
- function shouldResolveSessionIdInput(value) {
2508
- return looksLikeSessionId(value) || !looksLikeSessionKey(value);
2509
- }
2510
- async function resolveSessionKeyFromSessionId(params) {
2511
- try {
2512
- const result = await callGateway({
2513
- method: "sessions.resolve",
2514
- params: {
2515
- sessionId: params.sessionId,
2516
- spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0,
2517
- includeGlobal: !params.restrictToSpawned,
2518
- includeUnknown: !params.restrictToSpawned
2519
- }
2520
- });
2521
- const key = typeof result?.key === "string" ? result.key.trim() : "";
2522
- if (!key) throw new Error(`Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`);
2523
- return {
2524
- ok: true,
2525
- key,
2526
- displayKey: resolveDisplaySessionKey({
2527
- key,
2528
- alias: params.alias,
2529
- mainKey: params.mainKey
2530
- }),
2531
- resolvedViaSessionId: true
2532
- };
2533
- } catch (err) {
2534
- if (params.restrictToSpawned) return {
2535
- ok: false,
2536
- status: "forbidden",
2537
- error: `Session not visible from this sandboxed agent session: ${params.sessionId}`
2538
- };
2539
- return {
2540
- ok: false,
2541
- status: "error",
2542
- error: (err instanceof Error ? err.message : String(err)) || `Session not found: ${params.sessionId} (use the full sessionKey from sessions_list)`
2543
- };
2544
- }
2545
- }
2546
- async function resolveSessionKeyFromKey(params) {
2547
- try {
2548
- const result = await callGateway({
2549
- method: "sessions.resolve",
2550
- params: {
2551
- key: params.key,
2552
- spawnedBy: params.restrictToSpawned ? params.requesterInternalKey : void 0
2553
- }
2554
- });
2555
- const key = typeof result?.key === "string" ? result.key.trim() : "";
2556
- if (!key) return null;
2557
- return {
2558
- ok: true,
2559
- key,
2560
- displayKey: resolveDisplaySessionKey({
2561
- key,
2562
- alias: params.alias,
2563
- mainKey: params.mainKey
2564
- }),
2565
- resolvedViaSessionId: false
2566
- };
2567
- } catch {
2568
- return null;
2569
- }
2570
- }
2571
- async function resolveSessionReference(params) {
2572
- const raw = params.sessionKey.trim();
2573
- if (shouldResolveSessionIdInput(raw)) {
2574
- const resolvedByKey = await resolveSessionKeyFromKey({
2575
- key: raw,
2576
- alias: params.alias,
2577
- mainKey: params.mainKey,
2578
- requesterInternalKey: params.requesterInternalKey,
2579
- restrictToSpawned: params.restrictToSpawned
2580
- });
2581
- if (resolvedByKey) return resolvedByKey;
2582
- return await resolveSessionKeyFromSessionId({
2583
- sessionId: raw,
2584
- alias: params.alias,
2585
- mainKey: params.mainKey,
2586
- requesterInternalKey: params.requesterInternalKey,
2587
- restrictToSpawned: params.restrictToSpawned
2588
- });
2589
- }
2590
- const resolvedKey = resolveInternalSessionKey({
2591
- key: raw,
2592
- alias: params.alias,
2593
- mainKey: params.mainKey
2594
- });
2595
- return {
2596
- ok: true,
2597
- key: resolvedKey,
2598
- displayKey: resolveDisplaySessionKey({
2599
- key: resolvedKey,
2600
- alias: params.alias,
2601
- mainKey: params.mainKey
2602
- }),
2603
- resolvedViaSessionId: false
2604
- };
2605
- }
2606
-
2607
- //#endregion
2608
- //#region src/agents/tools/sessions-access.ts
2609
- function resolveSessionToolsVisibility(cfg) {
2610
- const raw = cfg.tools?.sessions?.visibility;
2611
- const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
2612
- if (value === "self" || value === "tree" || value === "agent" || value === "all") return value;
2613
- return "tree";
2614
- }
2615
- function resolveEffectiveSessionToolsVisibility(params) {
2616
- const visibility = resolveSessionToolsVisibility(params.cfg);
2617
- if (!params.sandboxed) return visibility;
2618
- if ((params.cfg.agents?.defaults?.sandbox?.sessionToolsVisibility ?? "spawned") === "spawned" && visibility !== "tree") return "tree";
2619
- return visibility;
2620
- }
2621
- function resolveSandboxSessionToolsVisibility(cfg) {
2622
- return cfg.agents?.defaults?.sandbox?.sessionToolsVisibility ?? "spawned";
2623
- }
2624
- function resolveSandboxedSessionToolContext(params) {
2625
- const { mainKey, alias } = resolveMainSessionAlias(params.cfg);
2626
- const visibility = resolveSandboxSessionToolsVisibility(params.cfg);
2627
- const requesterInternalKey = typeof params.agentSessionKey === "string" && params.agentSessionKey.trim() ? resolveInternalSessionKey({
2628
- key: params.agentSessionKey,
2629
- alias,
2630
- mainKey
2631
- }) : void 0;
2632
- return {
2633
- mainKey,
2634
- alias,
2635
- visibility,
2636
- requesterInternalKey,
2637
- effectiveRequesterKey: requesterInternalKey ?? alias,
2638
- restrictToSpawned: params.sandboxed === true && visibility === "spawned" && !!requesterInternalKey && !isSubagentSessionKey(requesterInternalKey)
2639
- };
2640
- }
2641
- function createAgentToAgentPolicy(cfg) {
2642
- const routingA2A = cfg.tools?.agentToAgent;
2643
- const enabled = routingA2A?.enabled === true;
2644
- const allowPatterns = Array.isArray(routingA2A?.allow) ? routingA2A.allow : [];
2645
- const matchesAllow = (agentId) => {
2646
- if (allowPatterns.length === 0) return true;
2647
- return allowPatterns.some((pattern) => {
2648
- const raw = String(pattern ?? "").trim();
2649
- if (!raw) return false;
2650
- if (raw === "*") return true;
2651
- if (!raw.includes("*")) return raw === agentId;
2652
- const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2653
- return new RegExp(`^${escaped.replaceAll("\\*", ".*")}$`, "i").test(agentId);
2654
- });
2655
- };
2656
- const isAllowed = (requesterAgentId, targetAgentId) => {
2657
- if (requesterAgentId === targetAgentId) return true;
2658
- if (!enabled) return false;
2659
- return matchesAllow(requesterAgentId) && matchesAllow(targetAgentId);
2660
- };
2661
- return {
2662
- enabled,
2663
- matchesAllow,
2664
- isAllowed
2665
- };
2666
- }
2667
- function actionPrefix(action) {
2668
- if (action === "history") return "Session history";
2669
- if (action === "send") return "Session send";
2670
- return "Session list";
2671
- }
2672
- function a2aDisabledMessage(action) {
2673
- if (action === "history") return "Agent-to-agent history is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent access.";
2674
- if (action === "send") return "Agent-to-agent messaging is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent sends.";
2675
- return "Agent-to-agent listing is disabled. Set tools.agentToAgent.enabled=true to allow cross-agent visibility.";
2676
- }
2677
- function a2aDeniedMessage(action) {
2678
- if (action === "history") return "Agent-to-agent history denied by tools.agentToAgent.allow.";
2679
- if (action === "send") return "Agent-to-agent messaging denied by tools.agentToAgent.allow.";
2680
- return "Agent-to-agent listing denied by tools.agentToAgent.allow.";
2681
- }
2682
- function crossVisibilityMessage(action) {
2683
- if (action === "history") return "Session history visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
2684
- if (action === "send") return "Session send visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
2685
- return "Session list visibility is restricted. Set tools.sessions.visibility=all to allow cross-agent access.";
2686
- }
2687
- function selfVisibilityMessage(action) {
2688
- return `${actionPrefix(action)} visibility is restricted to the current session (tools.sessions.visibility=self).`;
2689
- }
2690
- function treeVisibilityMessage(action) {
2691
- return `${actionPrefix(action)} visibility is restricted to the current session tree (tools.sessions.visibility=tree).`;
2692
- }
2693
- async function createSessionVisibilityGuard(params) {
2694
- const requesterAgentId = resolveAgentIdFromSessionKey(params.requesterSessionKey);
2695
- const spawnedKeys = params.visibility === "tree" ? await listSpawnedSessionKeys({ requesterSessionKey: params.requesterSessionKey }) : null;
2696
- const check = (targetSessionKey) => {
2697
- const targetAgentId = resolveAgentIdFromSessionKey(targetSessionKey);
2698
- if (targetAgentId !== requesterAgentId) {
2699
- if (params.visibility !== "all") return {
2700
- allowed: false,
2701
- status: "forbidden",
2702
- error: crossVisibilityMessage(params.action)
2703
- };
2704
- if (!params.a2aPolicy.enabled) return {
2705
- allowed: false,
2706
- status: "forbidden",
2707
- error: a2aDisabledMessage(params.action)
2708
- };
2709
- if (!params.a2aPolicy.isAllowed(requesterAgentId, targetAgentId)) return {
2710
- allowed: false,
2711
- status: "forbidden",
2712
- error: a2aDeniedMessage(params.action)
2713
- };
2714
- return { allowed: true };
2715
- }
2716
- if (params.visibility === "self" && targetSessionKey !== params.requesterSessionKey) return {
2717
- allowed: false,
2718
- status: "forbidden",
2719
- error: selfVisibilityMessage(params.action)
2720
- };
2721
- if (params.visibility === "tree" && targetSessionKey !== params.requesterSessionKey && !spawnedKeys?.has(targetSessionKey)) return {
2722
- allowed: false,
2723
- status: "forbidden",
2724
- error: treeVisibilityMessage(params.action)
2725
- };
2726
- return { allowed: true };
2727
- };
2728
- return { check };
2729
- }
2730
-
2731
- //#endregion
2732
- //#region src/shared/text/code-regions.ts
2733
- function findCodeRegions(text) {
2734
- const regions = [];
2735
- for (const match of text.matchAll(/(^|\n)(```|~~~)[^\n]*\n[\s\S]*?(?:\n\2(?:\n|$)|$)/g)) {
2736
- const start = (match.index ?? 0) + match[1].length;
2737
- regions.push({
2738
- start,
2739
- end: start + match[0].length - match[1].length
2740
- });
2741
- }
2742
- for (const match of text.matchAll(/`+[^`]+`+/g)) {
2743
- const start = match.index ?? 0;
2744
- const end = start + match[0].length;
2745
- if (!regions.some((r) => start >= r.start && end <= r.end)) regions.push({
2746
- start,
2747
- end
2748
- });
2749
- }
2750
- regions.sort((a, b) => a.start - b.start);
2751
- return regions;
2752
- }
2753
- function isInsideCode(pos, regions) {
2754
- return regions.some((r) => pos >= r.start && pos < r.end);
2755
- }
2756
-
2757
- //#endregion
2758
- //#region src/shared/text/reasoning-tags.ts
2759
- const QUICK_TAG_RE = /<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|final)\b/i;
2760
- const FINAL_TAG_RE = /<\s*\/?\s*final\b[^<>]*>/gi;
2761
- const THINKING_TAG_RE = /<\s*(\/?)\s*(?:think(?:ing)?|thought|antthinking)\b[^<>]*>/gi;
2762
- function applyTrim(value, mode) {
2763
- if (mode === "none") return value;
2764
- if (mode === "start") return value.trimStart();
2765
- return value.trim();
2766
- }
2767
- function stripReasoningTagsFromText(text, options) {
2768
- if (!text) return text;
2769
- if (!QUICK_TAG_RE.test(text)) return text;
2770
- const mode = options?.mode ?? "strict";
2771
- const trimMode = options?.trim ?? "both";
2772
- let cleaned = text;
2773
- if (FINAL_TAG_RE.test(cleaned)) {
2774
- FINAL_TAG_RE.lastIndex = 0;
2775
- const finalMatches = [];
2776
- const preCodeRegions = findCodeRegions(cleaned);
2777
- for (const match of cleaned.matchAll(FINAL_TAG_RE)) {
2778
- const start = match.index ?? 0;
2779
- finalMatches.push({
2780
- start,
2781
- length: match[0].length,
2782
- inCode: isInsideCode(start, preCodeRegions)
2783
- });
2784
- }
2785
- for (let i = finalMatches.length - 1; i >= 0; i--) {
2786
- const m = finalMatches[i];
2787
- if (!m.inCode) cleaned = cleaned.slice(0, m.start) + cleaned.slice(m.start + m.length);
2788
- }
2789
- } else FINAL_TAG_RE.lastIndex = 0;
2790
- const codeRegions = findCodeRegions(cleaned);
2791
- THINKING_TAG_RE.lastIndex = 0;
2792
- let result = "";
2793
- let lastIndex = 0;
2794
- let inThinking = false;
2795
- for (const match of cleaned.matchAll(THINKING_TAG_RE)) {
2796
- const idx = match.index ?? 0;
2797
- const isClose = match[1] === "/";
2798
- if (isInsideCode(idx, codeRegions)) continue;
2799
- if (!inThinking) {
2800
- result += cleaned.slice(lastIndex, idx);
2801
- if (!isClose) inThinking = true;
2802
- } else if (isClose) inThinking = false;
2803
- lastIndex = idx + match[0].length;
2804
- }
2805
- if (!inThinking || mode === "preserve") result += cleaned.slice(lastIndex);
2806
- return applyTrim(result, trimMode);
2807
- }
2808
-
2809
- //#endregion
2810
- //#region src/agents/agent-utils.ts
2811
- /**
2812
- * Strip malformed Minimax tool invocations that leak into text content.
2813
- * Minimax sometimes embeds tool calls as XML in text blocks instead of
2814
- * proper structured tool calls. This removes:
2815
- * - <invoke name="...">...</invoke> blocks
2816
- * - </minimax:tool_call> closing tags
2817
- */
2818
- function stripMinimaxToolCallXml(text) {
2819
- if (!text) return text;
2820
- if (!/minimax:tool_call/i.test(text)) return text;
2821
- let cleaned = text.replace(/<invoke\b[^>]*>[\s\S]*?<\/invoke>/gi, "");
2822
- cleaned = cleaned.replace(/<\/?minimax:tool_call>/gi, "");
2823
- return cleaned;
2824
- }
2825
- /**
2826
- * Strip downgraded tool call text representations that leak into text content.
2827
- * When replaying history to Gemini, tool calls without `thought_signature` are
2828
- * downgraded to text blocks like `[Tool Call: name (ID: ...)]`. These should
2829
- * not be shown to users.
2830
- */
2831
- function stripDowngradedToolCallText(text) {
2832
- if (!text) return text;
2833
- if (!/\[Tool (?:Call|Result)/i.test(text) && !/\[Historical context/i.test(text)) return text;
2834
- const consumeJsonish = (input, start, options) => {
2835
- const { allowLeadingNewlines = false } = options ?? {};
2836
- let index = start;
2837
- while (index < input.length) {
2838
- const ch = input[index];
2839
- if (ch === " " || ch === " ") {
2840
- index += 1;
2841
- continue;
2842
- }
2843
- if (allowLeadingNewlines && (ch === "\n" || ch === "\r")) {
2844
- index += 1;
2845
- continue;
2846
- }
2847
- break;
2848
- }
2849
- if (index >= input.length) return null;
2850
- const startChar = input[index];
2851
- if (startChar === "{" || startChar === "[") {
2852
- let depth = 0;
2853
- let inString = false;
2854
- let escape = false;
2855
- for (let i = index; i < input.length; i += 1) {
2856
- const ch = input[i];
2857
- if (inString) {
2858
- if (escape) escape = false;
2859
- else if (ch === "\\") escape = true;
2860
- else if (ch === "\"") inString = false;
2861
- continue;
2862
- }
2863
- if (ch === "\"") {
2864
- inString = true;
2865
- continue;
2866
- }
2867
- if (ch === "{" || ch === "[") {
2868
- depth += 1;
2869
- continue;
2870
- }
2871
- if (ch === "}" || ch === "]") {
2872
- depth -= 1;
2873
- if (depth === 0) return i + 1;
2874
- }
2875
- }
2876
- return null;
2877
- }
2878
- if (startChar === "\"") {
2879
- let escape = false;
2880
- for (let i = index + 1; i < input.length; i += 1) {
2881
- const ch = input[i];
2882
- if (escape) {
2883
- escape = false;
2884
- continue;
2885
- }
2886
- if (ch === "\\") {
2887
- escape = true;
2888
- continue;
2889
- }
2890
- if (ch === "\"") return i + 1;
2891
- }
2892
- return null;
2893
- }
2894
- let end = index;
2895
- while (end < input.length && input[end] !== "\n" && input[end] !== "\r") end += 1;
2896
- return end;
2897
- };
2898
- const stripToolCalls = (input) => {
2899
- const markerRe = /\[Tool Call:[^\]]*\]/gi;
2900
- let result = "";
2901
- let cursor = 0;
2902
- for (const match of input.matchAll(markerRe)) {
2903
- const start = match.index ?? 0;
2904
- if (start < cursor) continue;
2905
- result += input.slice(cursor, start);
2906
- let index = start + match[0].length;
2907
- while (index < input.length && (input[index] === " " || input[index] === " ")) index += 1;
2908
- if (input[index] === "\r") {
2909
- index += 1;
2910
- if (input[index] === "\n") index += 1;
2911
- } else if (input[index] === "\n") index += 1;
2912
- while (index < input.length && (input[index] === " " || input[index] === " ")) index += 1;
2913
- if (input.slice(index, index + 9).toLowerCase() === "arguments") {
2914
- index += 9;
2915
- if (input[index] === ":") index += 1;
2916
- if (input[index] === " ") index += 1;
2917
- const end = consumeJsonish(input, index, { allowLeadingNewlines: true });
2918
- if (end !== null) index = end;
2919
- }
2920
- if ((input[index] === "\n" || input[index] === "\r") && (result.endsWith("\n") || result.endsWith("\r") || result.length === 0)) {
2921
- if (input[index] === "\r") index += 1;
2922
- if (input[index] === "\n") index += 1;
2923
- }
2924
- cursor = index;
2925
- }
2926
- result += input.slice(cursor);
2927
- return result;
2928
- };
2929
- let cleaned = stripToolCalls(text);
2930
- cleaned = cleaned.replace(/\[Tool Result for ID[^\]]*\]\n?[\s\S]*?(?=\n*\[Tool |\n*$)/gi, "");
2931
- cleaned = cleaned.replace(/\[Historical context:[^\]]*\]\n?/gi, "");
2932
- return cleaned.trim();
2933
- }
2934
- /**
2935
- * Strip thinking tags and their content from text.
2936
- * This is a safety net for cases where the model outputs <think> tags
2937
- * that slip through other filtering mechanisms.
2938
- */
2939
- function stripThinkingTagsFromText(text) {
2940
- return stripReasoningTagsFromText(text, {
2941
- mode: "strict",
2942
- trim: "both"
2943
- });
2944
- }
2945
-
2946
- //#endregion
2947
- //#region src/agents/tools/sessions-helpers.ts
2948
- function normalizeKey(value) {
2949
- const trimmed = value?.trim();
2950
- return trimmed ? trimmed : void 0;
2951
- }
2952
- function classifySessionKind(params) {
2953
- const key = params.key;
2954
- if (key === params.alias || key === params.mainKey) return "main";
2955
- if (key.startsWith("cron:")) return "cron";
2956
- if (key.startsWith("hook:")) return "hook";
2957
- if (key.startsWith("node-") || key.startsWith("node:")) return "node";
2958
- if (params.gatewayKind === "group") return "group";
2959
- if (key.includes(":group:") || key.includes(":channel:")) return "group";
2960
- return "other";
2961
- }
2962
- function deriveChannel(params) {
2963
- if (params.kind === "cron" || params.kind === "hook" || params.kind === "node") return "internal";
2964
- const channel = normalizeKey(params.channel ?? void 0);
2965
- if (channel) return channel;
2966
- const lastChannel = normalizeKey(params.lastChannel ?? void 0);
2967
- if (lastChannel) return lastChannel;
2968
- const parts = params.key.split(":").filter(Boolean);
2969
- if (parts.length >= 3 && (parts[1] === "group" || parts[1] === "channel")) return parts[0];
2970
- return "unknown";
2971
- }
2972
- function stripToolMessages(messages) {
2973
- return messages.filter((msg) => {
2974
- if (!msg || typeof msg !== "object") return true;
2975
- const role = msg.role;
2976
- return role !== "toolResult" && role !== "tool";
2977
- });
2978
- }
2979
- /**
2980
- * Sanitize text content to strip tool call markers and thinking tags.
2981
- * This ensures user-facing text doesn't leak internal tool representations.
2982
- */
2983
- function sanitizeTextContent(text) {
2984
- if (!text) return text;
2985
- return stripThinkingTagsFromText(stripDowngradedToolCallText(stripMinimaxToolCallXml(text)));
2986
- }
2987
- function extractAssistantText(message) {
2988
- if (!message || typeof message !== "object") return;
2989
- if (message.role !== "assistant") return;
2990
- const content = message.content;
2991
- if (!Array.isArray(content)) return;
2992
- const joined = extractTextFromChatContent(content, {
2993
- sanitizeText: sanitizeTextContent,
2994
- joinWith: "",
2995
- normalizeText: (text) => text.trim()
2996
- }) ?? "";
2997
- const stopReason = message.stopReason;
2998
- const errorMessage = message.errorMessage;
2999
- const errorContext = stopReason === "error" || typeof errorMessage === "string" && Boolean(errorMessage.trim());
3000
- return joined ? sanitizeUserFacingText(joined, { errorContext }) : void 0;
3001
- }
3002
-
3003
- //#endregion
3004
- //#region src/agents/tools/agent-step.ts
3005
- async function readLatestAssistantReply(params) {
3006
- const history = await callGateway({
3007
- method: "chat.history",
3008
- params: {
3009
- sessionKey: params.sessionKey,
3010
- limit: params.limit ?? 50
3011
- }
3012
- });
3013
- const filtered = stripToolMessages(Array.isArray(history?.messages) ? history.messages : []);
3014
- for (let i = filtered.length - 1; i >= 0; i -= 1) {
3015
- const candidate = filtered[i];
3016
- if (!candidate || typeof candidate !== "object") continue;
3017
- if (candidate.role !== "assistant") continue;
3018
- const text = extractAssistantText(candidate);
3019
- if (!text?.trim()) continue;
3020
- return text;
3021
- }
3022
- }
3023
- async function runAgentStep(params) {
3024
- const stepIdem = crypto.randomUUID();
3025
- const response = await callGateway({
3026
- method: "agent",
3027
- params: {
3028
- message: params.message,
3029
- sessionKey: params.sessionKey,
3030
- idempotencyKey: stepIdem,
3031
- deliver: false,
3032
- channel: params.channel ?? INTERNAL_MESSAGE_CHANNEL,
3033
- lane: params.lane ?? AGENT_LANE_NESTED,
3034
- extraSystemPrompt: params.extraSystemPrompt,
3035
- inputProvenance: {
3036
- kind: "inter_session",
3037
- sourceSessionKey: params.sourceSessionKey,
3038
- sourceChannel: params.sourceChannel,
3039
- sourceTool: params.sourceTool ?? "sessions_send"
3040
- }
3041
- },
3042
- timeoutMs: 1e4
3043
- });
3044
- const resolvedRunId = (typeof response?.runId === "string" && response.runId ? response.runId : "") || stepIdem;
3045
- const stepWaitMs = Math.min(params.timeoutMs, 6e4);
3046
- if ((await callGateway({
3047
- method: "agent.wait",
3048
- params: {
3049
- runId: resolvedRunId,
3050
- timeoutMs: stepWaitMs
3051
- },
3052
- timeoutMs: stepWaitMs + 2e3
3053
- }))?.status !== "ok") return;
3054
- return await readLatestAssistantReply({ sessionKey: params.sessionKey });
3055
- }
3056
-
3057
- //#endregion
3058
- //#region src/agents/tools/sessions-send-helpers.ts
3059
- const ANNOUNCE_SKIP_TOKEN = "ANNOUNCE_SKIP";
3060
- const REPLY_SKIP_TOKEN = "REPLY_SKIP";
3061
- const DEFAULT_PING_PONG_TURNS = 5;
3062
- const MAX_PING_PONG_TURNS = 5;
3063
- function resolveAnnounceTargetFromKey(sessionKey) {
3064
- const rawParts = sessionKey.split(":").filter(Boolean);
3065
- const parts = rawParts.length >= 3 && rawParts[0] === "agent" ? rawParts.slice(2) : rawParts;
3066
- if (parts.length < 3) return null;
3067
- const [channelRaw, kind, ...rest] = parts;
3068
- if (kind !== "group" && kind !== "channel") return null;
3069
- let threadId;
3070
- const restJoined = rest.join(":");
3071
- const topicMatch = restJoined.match(/:topic:(\d+)$/);
3072
- const threadMatch = restJoined.match(/:thread:(\d+)$/);
3073
- const match = topicMatch || threadMatch;
3074
- if (match) threadId = match[1];
3075
- const id = match ? restJoined.replace(/:(topic|thread):\d+$/, "") : restJoined.trim();
3076
- if (!id) return null;
3077
- if (!channelRaw) return null;
3078
- const normalizedChannel = normalizeChannelId$1(channelRaw) ?? normalizeChannelId(channelRaw);
3079
- const channel = normalizedChannel ?? channelRaw.toLowerCase();
3080
- const kindTarget = (() => {
3081
- if (!normalizedChannel) return id;
3082
- if (normalizedChannel === "discord" || normalizedChannel === "slack") return `channel:${id}`;
3083
- return kind === "channel" ? `channel:${id}` : `group:${id}`;
3084
- })();
3085
- return {
3086
- channel,
3087
- to: (normalizedChannel ? getChannelPlugin(normalizedChannel)?.messaging?.normalizeTarget?.(kindTarget) : void 0) ?? kindTarget,
3088
- threadId
3089
- };
3090
- }
3091
- function buildAgentToAgentMessageContext(params) {
3092
- return [
3093
- "Agent-to-agent message context:",
3094
- params.requesterSessionKey ? `Agent 1 (requester) session: ${params.requesterSessionKey}.` : void 0,
3095
- params.requesterChannel ? `Agent 1 (requester) channel: ${params.requesterChannel}.` : void 0,
3096
- `Agent 2 (target) session: ${params.targetSessionKey}.`
3097
- ].filter(Boolean).join("\n");
3098
- }
3099
- function buildAgentToAgentReplyContext(params) {
3100
- return [
3101
- "Agent-to-agent reply step:",
3102
- `Current agent: ${params.currentRole === "requester" ? "Agent 1 (requester)" : "Agent 2 (target)"}.`,
3103
- `Turn ${params.turn} of ${params.maxTurns}.`,
3104
- params.requesterSessionKey ? `Agent 1 (requester) session: ${params.requesterSessionKey}.` : void 0,
3105
- params.requesterChannel ? `Agent 1 (requester) channel: ${params.requesterChannel}.` : void 0,
3106
- `Agent 2 (target) session: ${params.targetSessionKey}.`,
3107
- params.targetChannel ? `Agent 2 (target) channel: ${params.targetChannel}.` : void 0,
3108
- `If you want to stop the ping-pong, reply exactly "${REPLY_SKIP_TOKEN}".`
3109
- ].filter(Boolean).join("\n");
3110
- }
3111
- function buildAgentToAgentAnnounceContext(params) {
3112
- return [
3113
- "Agent-to-agent announce step:",
3114
- params.requesterSessionKey ? `Agent 1 (requester) session: ${params.requesterSessionKey}.` : void 0,
3115
- params.requesterChannel ? `Agent 1 (requester) channel: ${params.requesterChannel}.` : void 0,
3116
- `Agent 2 (target) session: ${params.targetSessionKey}.`,
3117
- params.targetChannel ? `Agent 2 (target) channel: ${params.targetChannel}.` : void 0,
3118
- `Original request: ${params.originalMessage}`,
3119
- params.roundOneReply ? `Round 1 reply: ${params.roundOneReply}` : "Round 1 reply: (not available).",
3120
- params.latestReply ? `Latest reply: ${params.latestReply}` : "Latest reply: (not available).",
3121
- `If you want to remain silent, reply exactly "${ANNOUNCE_SKIP_TOKEN}".`,
3122
- "Any other reply will be posted to the target channel.",
3123
- "After this reply, the agent-to-agent conversation is over."
3124
- ].filter(Boolean).join("\n");
3125
- }
3126
- function isAnnounceSkip(text) {
3127
- return (text ?? "").trim() === ANNOUNCE_SKIP_TOKEN;
3128
- }
3129
- function isReplySkip(text) {
3130
- return (text ?? "").trim() === REPLY_SKIP_TOKEN;
3131
- }
3132
- function resolvePingPongTurns(cfg) {
3133
- const raw = cfg?.session?.agentToAgent?.maxPingPongTurns;
3134
- const fallback = DEFAULT_PING_PONG_TURNS;
3135
- if (typeof raw !== "number" || !Number.isFinite(raw)) return fallback;
3136
- const rounded = Math.floor(raw);
3137
- return Math.max(0, Math.min(MAX_PING_PONG_TURNS, rounded));
3138
- }
3139
-
3140
- //#endregion
3141
- //#region src/agents/subagent-announce.ts
3142
- const FAST_TEST_MODE = process.env.REMOTECLAW_TEST_FAST === "1";
3143
- const FAST_TEST_RETRY_INTERVAL_MS = 8;
3144
- const FAST_TEST_REPLY_CHANGE_WAIT_MS = 20;
3145
- const DEFAULT_SUBAGENT_ANNOUNCE_TIMEOUT_MS = 6e4;
3146
- const MAX_TIMER_SAFE_TIMEOUT_MS = 2147e6;
3147
- const DIRECT_ANNOUNCE_TRANSIENT_RETRY_DELAYS_MS = FAST_TEST_MODE ? [
3148
- 8,
3149
- 16,
3150
- 32
3151
- ] : [
3152
- 5e3,
3153
- 1e4,
3154
- 2e4
3155
- ];
3156
- function resolveSubagentAnnounceTimeoutMs(cfg) {
3157
- const configured = cfg.agents?.defaults?.subagents?.announceTimeoutMs;
3158
- if (typeof configured !== "number" || !Number.isFinite(configured)) return DEFAULT_SUBAGENT_ANNOUNCE_TIMEOUT_MS;
3159
- return Math.min(Math.max(1, Math.floor(configured)), MAX_TIMER_SAFE_TIMEOUT_MS);
3160
- }
3161
- function buildCompletionDeliveryMessage(params) {
3162
- const findingsText = params.findings.trim();
3163
- if (isAnnounceSkip(findingsText)) return "";
3164
- const hasFindings = findingsText.length > 0 && findingsText !== "(no output)";
3165
- const header = (() => {
3166
- if (params.outcome?.status === "error") return params.spawnMode === "session" ? `❌ Subagent ${params.subagentName} failed this task (session remains active)` : `❌ Subagent ${params.subagentName} failed`;
3167
- if (params.outcome?.status === "timeout") return params.spawnMode === "session" ? `⏱️ Subagent ${params.subagentName} timed out on this task (session remains active)` : `⏱️ Subagent ${params.subagentName} timed out`;
3168
- return params.spawnMode === "session" ? `✅ Subagent ${params.subagentName} completed this task (session remains active)` : `✅ Subagent ${params.subagentName} finished`;
3169
- })();
3170
- if (!hasFindings) return header;
3171
- return `${header}\n\n${findingsText}`;
3172
- }
3173
- function summarizeDeliveryError(error) {
3174
- if (error instanceof Error) return error.message || "error";
3175
- if (typeof error === "string") return error;
3176
- if (error === void 0 || error === null) return "unknown error";
3177
- try {
3178
- return JSON.stringify(error);
3179
- } catch {
3180
- return "error";
3181
- }
3182
- }
3183
- const TRANSIENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS = [
3184
- /\berrorcode=unavailable\b/i,
3185
- /\bstatus\s*[:=]\s*"?unavailable\b/i,
3186
- /\bUNAVAILABLE\b/,
3187
- /no active .* listener/i,
3188
- /gateway not connected/i,
3189
- /gateway closed \(1006/i,
3190
- /gateway timeout/i,
3191
- /\b(econnreset|econnrefused|etimedout|enotfound|ehostunreach|network error)\b/i
3192
- ];
3193
- const PERMANENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS = [
3194
- /unsupported channel/i,
3195
- /unknown channel/i,
3196
- /chat not found/i,
3197
- /user not found/i,
3198
- /bot was blocked by the user/i,
3199
- /forbidden: bot was kicked/i,
3200
- /recipient is not a valid/i,
3201
- /outbound not configured for channel/i
3202
- ];
3203
- function isTransientAnnounceDeliveryError(error) {
3204
- const message = summarizeDeliveryError(error);
3205
- if (!message) return false;
3206
- if (PERMANENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS.some((re) => re.test(message))) return false;
3207
- return TRANSIENT_ANNOUNCE_DELIVERY_ERROR_PATTERNS.some((re) => re.test(message));
3208
- }
3209
- async function waitForAnnounceRetryDelay(ms, signal) {
3210
- if (ms <= 0) return;
3211
- if (!signal) {
3212
- await new Promise((resolve) => setTimeout(resolve, ms));
3213
- return;
3214
- }
3215
- if (signal.aborted) return;
3216
- await new Promise((resolve) => {
3217
- const timer = setTimeout(() => {
3218
- signal.removeEventListener("abort", onAbort);
3219
- resolve();
3220
- }, ms);
3221
- const onAbort = () => {
3222
- clearTimeout(timer);
3223
- signal.removeEventListener("abort", onAbort);
3224
- resolve();
3225
- };
3226
- signal.addEventListener("abort", onAbort, { once: true });
3227
- });
3228
- }
3229
- async function runAnnounceDeliveryWithRetry(params) {
3230
- let retryIndex = 0;
3231
- for (;;) {
3232
- if (params.signal?.aborted) throw new Error("announce delivery aborted");
3233
- try {
3234
- return await params.run();
3235
- } catch (err) {
3236
- const delayMs = DIRECT_ANNOUNCE_TRANSIENT_RETRY_DELAYS_MS[retryIndex];
3237
- if (delayMs == null || !isTransientAnnounceDeliveryError(err) || params.signal?.aborted) throw err;
3238
- const nextAttempt = retryIndex + 2;
3239
- const maxAttempts = DIRECT_ANNOUNCE_TRANSIENT_RETRY_DELAYS_MS.length + 1;
3240
- defaultRuntime.log(`[warn] Subagent announce ${params.operation} transient failure, retrying ${nextAttempt}/${maxAttempts} in ${Math.round(delayMs / 1e3)}s: ${summarizeDeliveryError(err)}`);
3241
- retryIndex += 1;
3242
- await waitForAnnounceRetryDelay(delayMs, params.signal);
3243
- }
3244
- }
3245
- }
3246
- function extractToolResultText(content) {
3247
- if (typeof content === "string") return sanitizeTextContent(content);
3248
- if (content && typeof content === "object" && !Array.isArray(content)) {
3249
- const obj = content;
3250
- if (typeof obj.text === "string") return sanitizeTextContent(obj.text);
3251
- if (typeof obj.output === "string") return sanitizeTextContent(obj.output);
3252
- if (typeof obj.content === "string") return sanitizeTextContent(obj.content);
3253
- if (typeof obj.result === "string") return sanitizeTextContent(obj.result);
3254
- if (typeof obj.error === "string") return sanitizeTextContent(obj.error);
3255
- if (typeof obj.summary === "string") return sanitizeTextContent(obj.summary);
3256
- }
3257
- if (!Array.isArray(content)) return "";
3258
- return extractTextFromChatContent(content, {
3259
- sanitizeText: sanitizeTextContent,
3260
- normalizeText: (text) => text,
3261
- joinWith: "\n"
3262
- })?.trim() ?? "";
3263
- }
3264
- function extractInlineTextContent(content) {
3265
- if (!Array.isArray(content)) return "";
3266
- return extractTextFromChatContent(content, {
3267
- sanitizeText: sanitizeTextContent,
3268
- normalizeText: (text) => text.trim(),
3269
- joinWith: ""
3270
- }) ?? "";
3271
- }
3272
- function extractSubagentOutputText(message) {
3273
- if (!message || typeof message !== "object") return "";
3274
- const role = message.role;
3275
- const content = message.content;
3276
- if (role === "assistant") {
3277
- const assistantText = extractAssistantText(message);
3278
- if (assistantText) return assistantText;
3279
- if (typeof content === "string") return sanitizeTextContent(content);
3280
- if (Array.isArray(content)) return extractInlineTextContent(content);
3281
- return "";
3282
- }
3283
- if (role === "toolResult" || role === "tool") return extractToolResultText(message.content);
3284
- if (role == null) {
3285
- if (typeof content === "string") return sanitizeTextContent(content);
3286
- if (Array.isArray(content)) return extractInlineTextContent(content);
3287
- }
3288
- return "";
3289
- }
3290
- async function readLatestSubagentOutput(sessionKey) {
3291
- try {
3292
- const latestAssistant = await readLatestAssistantReply({
3293
- sessionKey,
3294
- limit: 50
3295
- });
3296
- if (latestAssistant?.trim()) return latestAssistant;
3297
- } catch {}
3298
- const history = await callGateway({
3299
- method: "chat.history",
3300
- params: {
3301
- sessionKey,
3302
- limit: 50
3303
- }
3304
- });
3305
- const messages = Array.isArray(history?.messages) ? history.messages : [];
3306
- for (let i = messages.length - 1; i >= 0; i -= 1) {
3307
- const msg = messages[i];
3308
- const text = extractSubagentOutputText(msg);
3309
- if (text) return text;
3310
- }
3311
- }
3312
- async function readLatestSubagentOutputWithRetry(params) {
3313
- const RETRY_INTERVAL_MS = FAST_TEST_MODE ? FAST_TEST_RETRY_INTERVAL_MS : 100;
3314
- const deadline = Date.now() + Math.max(0, Math.min(params.maxWaitMs, 15e3));
3315
- let result;
3316
- while (Date.now() < deadline) {
3317
- result = await readLatestSubagentOutput(params.sessionKey);
3318
- if (result?.trim()) return result;
3319
- await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL_MS));
3320
- }
3321
- return result;
3322
- }
3323
- async function waitForSubagentOutputChange(params) {
3324
- const baseline = params.baselineReply.trim();
3325
- if (!baseline) return params.baselineReply;
3326
- const RETRY_INTERVAL_MS = FAST_TEST_MODE ? FAST_TEST_RETRY_INTERVAL_MS : 100;
3327
- const deadline = Date.now() + Math.max(0, Math.min(params.maxWaitMs, 5e3));
3328
- let latest = params.baselineReply;
3329
- while (Date.now() < deadline) {
3330
- const next = await readLatestSubagentOutput(params.sessionKey);
3331
- if (next?.trim()) {
3332
- latest = next;
3333
- if (next.trim() !== baseline) return next;
3334
- }
3335
- await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL_MS));
3336
- }
3337
- return latest;
3338
- }
3339
- function formatDurationShort(valueMs) {
3340
- if (!valueMs || !Number.isFinite(valueMs) || valueMs <= 0) return "n/a";
3341
- const totalSeconds = Math.round(valueMs / 1e3);
3342
- const hours = Math.floor(totalSeconds / 3600);
3343
- const minutes = Math.floor(totalSeconds % 3600 / 60);
3344
- const seconds = totalSeconds % 60;
3345
- if (hours > 0) return `${hours}h${minutes}m`;
3346
- if (minutes > 0) return `${minutes}m${seconds}s`;
3347
- return `${seconds}s`;
3348
- }
3349
- function formatTokenCount(value) {
3350
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return "0";
3351
- if (value >= 1e6) return `${(value / 1e6).toFixed(1)}m`;
3352
- if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
3353
- return String(Math.round(value));
3354
- }
3355
- async function buildCompactAnnounceStatsLine(params) {
3356
- const cfg = loadConfig();
3357
- const agentId = resolveAgentIdFromSessionKey(params.sessionKey);
3358
- const storePath = resolveStorePath(cfg.session?.store, { agentId });
3359
- let entry = loadSessionStore(storePath)[params.sessionKey];
3360
- const tokenWaitAttempts = FAST_TEST_MODE ? 1 : 3;
3361
- for (let attempt = 0; attempt < tokenWaitAttempts; attempt += 1) {
3362
- if (typeof entry?.inputTokens === "number" || typeof entry?.outputTokens === "number" || typeof entry?.totalTokens === "number") break;
3363
- if (!FAST_TEST_MODE) await new Promise((resolve) => setTimeout(resolve, 150));
3364
- entry = loadSessionStore(storePath)[params.sessionKey];
3365
- }
3366
- const input = typeof entry?.inputTokens === "number" ? entry.inputTokens : 0;
3367
- const output = typeof entry?.outputTokens === "number" ? entry.outputTokens : 0;
3368
- const ioTotal = input + output;
3369
- const promptCache = typeof entry?.totalTokens === "number" ? entry.totalTokens : void 0;
3370
- const parts = [`runtime ${formatDurationShort(typeof params.startedAt === "number" && typeof params.endedAt === "number" ? Math.max(0, params.endedAt - params.startedAt) : void 0)}`, `tokens ${formatTokenCount(ioTotal)} (in ${formatTokenCount(input)} / out ${formatTokenCount(output)})`];
3371
- if (typeof promptCache === "number" && promptCache > ioTotal) parts.push(`prompt/cache ${formatTokenCount(promptCache)}`);
3372
- return `Stats: ${parts.join(" • ")}`;
3373
- }
3374
- function resolveAnnounceOrigin(entry, requesterOrigin) {
3375
- const normalizedRequester = normalizeDeliveryContext(requesterOrigin);
3376
- const normalizedEntry = deliveryContextFromSession(entry);
3377
- if (normalizedRequester?.channel && isInternalMessageChannel(normalizedRequester.channel)) return mergeDeliveryContext({
3378
- accountId: normalizedRequester.accountId,
3379
- threadId: normalizedRequester.threadId
3380
- }, normalizedEntry);
3381
- return mergeDeliveryContext(normalizedRequester, normalizedRequester?.to && normalizedRequester.threadId == null && normalizedEntry?.threadId != null ? (() => {
3382
- const { threadId: _ignore, ...rest } = normalizedEntry;
3383
- return rest;
3384
- })() : normalizedEntry);
3385
- }
3386
- async function resolveSubagentCompletionOrigin(params) {
3387
- const requesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
3388
- const requesterConversation = (() => {
3389
- const channel = requesterOrigin?.channel?.trim().toLowerCase();
3390
- const to = requesterOrigin?.to?.trim();
3391
- const accountId = normalizeAccountId(requesterOrigin?.accountId);
3392
- const conversationId = (requesterOrigin?.threadId != null && requesterOrigin.threadId !== "" ? String(requesterOrigin.threadId).trim() : void 0) || (to?.startsWith("channel:") ? to.slice(8) : "");
3393
- if (!channel || !conversationId) return;
3394
- return {
3395
- channel,
3396
- accountId,
3397
- conversationId
3398
- };
3399
- })();
3400
- const route = createBoundDeliveryRouter().resolveDestination({
3401
- eventKind: "task_completion",
3402
- targetSessionKey: params.childSessionKey,
3403
- requester: requesterConversation,
3404
- failClosed: false
3405
- });
3406
- if (route.mode === "bound" && route.binding) return {
3407
- origin: mergeDeliveryContext({
3408
- channel: route.binding.conversation.channel,
3409
- accountId: route.binding.conversation.accountId,
3410
- to: `channel:${route.binding.conversation.conversationId}`,
3411
- threadId: route.binding.conversation.conversationId
3412
- }, requesterOrigin),
3413
- routeMode: "bound"
3414
- };
3415
- const hookRunner = getGlobalHookRunner();
3416
- if (!hookRunner?.hasHooks("subagent_delivery_target")) return {
3417
- origin: requesterOrigin,
3418
- routeMode: "fallback"
3419
- };
3420
- try {
3421
- const hookOrigin = normalizeDeliveryContext((await hookRunner.runSubagentDeliveryTarget({
3422
- childSessionKey: params.childSessionKey,
3423
- requesterSessionKey: params.requesterSessionKey,
3424
- requesterOrigin,
3425
- childRunId: params.childRunId,
3426
- spawnMode: params.spawnMode,
3427
- expectsCompletionMessage: params.expectsCompletionMessage
3428
- }, {
3429
- runId: params.childRunId,
3430
- childSessionKey: params.childSessionKey,
3431
- requesterSessionKey: params.requesterSessionKey
3432
- }))?.origin);
3433
- if (!hookOrigin) return {
3434
- origin: requesterOrigin,
3435
- routeMode: "fallback"
3436
- };
3437
- if (hookOrigin.channel && !isDeliverableMessageChannel(hookOrigin.channel)) return {
3438
- origin: requesterOrigin,
3439
- routeMode: "fallback"
3440
- };
3441
- return {
3442
- origin: mergeDeliveryContext(hookOrigin, requesterOrigin),
3443
- routeMode: "hook"
3444
- };
3445
- } catch {
3446
- return {
3447
- origin: requesterOrigin,
3448
- routeMode: "fallback"
3449
- };
3450
- }
3451
- }
3452
- function resolveRequesterStoreKey(cfg, requesterSessionKey) {
3453
- const raw = (requesterSessionKey ?? "").trim();
3454
- if (!raw) return raw;
3455
- if (raw === "global" || raw === "unknown") return raw;
3456
- if (raw.startsWith("agent:")) return raw;
3457
- const mainKey = normalizeMainKey(cfg.session?.mainKey);
3458
- if (raw === "main" || raw === mainKey) return resolveMainSessionKey(cfg);
3459
- return `agent:${resolveAgentIdFromSessionKey(raw)}:${raw}`;
3460
- }
3461
- function loadRequesterSessionEntry(requesterSessionKey) {
3462
- const cfg = loadConfig();
3463
- const canonicalKey = resolveRequesterStoreKey(cfg, requesterSessionKey);
3464
- const agentId = resolveAgentIdFromSessionKey(canonicalKey);
3465
- return {
3466
- cfg,
3467
- entry: loadSessionStore(resolveStorePath(cfg.session?.store, { agentId }))[canonicalKey],
3468
- canonicalKey
3469
- };
3470
- }
3471
- async function maybeQueueSubagentAnnounce(params) {
3472
- if (params.signal?.aborted) return "none";
3473
- const { cfg, entry } = loadRequesterSessionEntry(params.requesterSessionKey);
3474
- resolveRequesterStoreKey(cfg, params.requesterSessionKey);
3475
- if (!entry?.sessionId) return "none";
3476
- const queueSettings = resolveQueueSettings({
3477
- cfg,
3478
- channel: entry?.channel ?? entry?.lastChannel,
3479
- sessionEntry: entry
3480
- });
3481
- queueSettings.mode === "followup" || queueSettings.mode === "collect" || queueSettings.mode === "steer-backlog" || queueSettings.mode;
3482
- return "none";
3483
- }
3484
- function queueOutcomeToDeliveryResult(outcome) {
3485
- if (outcome === "steered") return {
3486
- delivered: true,
3487
- path: "steered"
3488
- };
3489
- if (outcome === "queued") return {
3490
- delivered: true,
3491
- path: "queued"
3492
- };
3493
- return {
3494
- delivered: false,
3495
- path: "none"
3496
- };
3497
- }
3498
- async function sendSubagentAnnounceDirectly(params) {
3499
- if (params.signal?.aborted) return {
3500
- delivered: false,
3501
- path: "none"
3502
- };
3503
- const cfg = loadConfig();
3504
- const announceTimeoutMs = resolveSubagentAnnounceTimeoutMs(cfg);
3505
- const canonicalRequesterSessionKey = resolveRequesterStoreKey(cfg, params.targetRequesterSessionKey);
3506
- try {
3507
- const completionDirectOrigin = normalizeDeliveryContext(params.completionDirectOrigin);
3508
- const completionChannelRaw = typeof completionDirectOrigin?.channel === "string" ? completionDirectOrigin.channel.trim() : "";
3509
- const completionChannel = completionChannelRaw && isDeliverableMessageChannel(completionChannelRaw) ? completionChannelRaw : "";
3510
- const completionTo = typeof completionDirectOrigin?.to === "string" ? completionDirectOrigin.to.trim() : "";
3511
- const hasCompletionDirectTarget = !params.requesterIsSubagent && Boolean(completionChannel) && Boolean(completionTo);
3512
- if (params.expectsCompletionMessage && hasCompletionDirectTarget && params.completionMessage?.trim()) {
3513
- const forceBoundSessionDirectDelivery = params.spawnMode === "session" && (params.completionRouteMode === "bound" || params.completionRouteMode === "hook");
3514
- let shouldSendCompletionDirectly = true;
3515
- if (!forceBoundSessionDirectDelivery) {
3516
- let activeDescendantRuns = 0;
3517
- try {
3518
- const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
3519
- activeDescendantRuns = Math.max(0, countActiveDescendantRuns(canonicalRequesterSessionKey));
3520
- } catch {}
3521
- if (activeDescendantRuns > 0) shouldSendCompletionDirectly = false;
3522
- }
3523
- if (shouldSendCompletionDirectly) {
3524
- const completionThreadId = completionDirectOrigin?.threadId != null && completionDirectOrigin.threadId !== "" ? String(completionDirectOrigin.threadId) : void 0;
3525
- if (params.signal?.aborted) return {
3526
- delivered: false,
3527
- path: "none"
3528
- };
3529
- await runAnnounceDeliveryWithRetry({
3530
- operation: "completion direct send",
3531
- signal: params.signal,
3532
- run: async () => await callGateway({
3533
- method: "send",
3534
- params: {
3535
- channel: completionChannel,
3536
- to: completionTo,
3537
- accountId: completionDirectOrigin?.accountId,
3538
- threadId: completionThreadId,
3539
- sessionKey: canonicalRequesterSessionKey,
3540
- message: params.completionMessage,
3541
- idempotencyKey: params.directIdempotencyKey
3542
- },
3543
- timeoutMs: announceTimeoutMs
3544
- })
3545
- });
3546
- return {
3547
- delivered: true,
3548
- path: "direct"
3549
- };
3550
- }
3551
- }
3552
- const directOrigin = normalizeDeliveryContext(params.directOrigin);
3553
- const directChannelRaw = typeof directOrigin?.channel === "string" ? directOrigin.channel.trim() : "";
3554
- const directChannel = directChannelRaw && isDeliverableMessageChannel(directChannelRaw) ? directChannelRaw : "";
3555
- const directTo = typeof directOrigin?.to === "string" ? directOrigin.to.trim() : "";
3556
- const hasDeliverableDirectTarget = !params.requesterIsSubagent && Boolean(directChannel) && Boolean(directTo);
3557
- const shouldDeliverExternally = !params.requesterIsSubagent && (!params.expectsCompletionMessage || hasDeliverableDirectTarget);
3558
- const threadId = directOrigin?.threadId != null && directOrigin.threadId !== "" ? String(directOrigin.threadId) : void 0;
3559
- if (params.signal?.aborted) return {
3560
- delivered: false,
3561
- path: "none"
3562
- };
3563
- await runAnnounceDeliveryWithRetry({
3564
- operation: "direct announce agent call",
3565
- signal: params.signal,
3566
- run: async () => await callGateway({
3567
- method: "agent",
3568
- params: {
3569
- sessionKey: canonicalRequesterSessionKey,
3570
- message: params.triggerMessage,
3571
- deliver: shouldDeliverExternally,
3572
- bestEffortDeliver: params.bestEffortDeliver,
3573
- channel: shouldDeliverExternally ? directChannel : void 0,
3574
- accountId: shouldDeliverExternally ? directOrigin?.accountId : void 0,
3575
- to: shouldDeliverExternally ? directTo : void 0,
3576
- threadId: shouldDeliverExternally ? threadId : void 0,
3577
- idempotencyKey: params.directIdempotencyKey
3578
- },
3579
- expectFinal: true,
3580
- timeoutMs: announceTimeoutMs
3581
- })
3582
- });
3583
- return {
3584
- delivered: true,
3585
- path: "direct"
3586
- };
3587
- } catch (err) {
3588
- return {
3589
- delivered: false,
3590
- path: "direct",
3591
- error: summarizeDeliveryError(err)
3592
- };
3593
- }
3594
- }
3595
- async function deliverSubagentAnnouncement(params) {
3596
- if (params.signal?.aborted) return {
3597
- delivered: false,
3598
- path: "none"
3599
- };
3600
- if (!params.expectsCompletionMessage) {
3601
- const queued = queueOutcomeToDeliveryResult(await maybeQueueSubagentAnnounce({
3602
- requesterSessionKey: params.requesterSessionKey,
3603
- announceId: params.announceId,
3604
- triggerMessage: params.triggerMessage,
3605
- summaryLine: params.summaryLine,
3606
- requesterOrigin: params.requesterOrigin,
3607
- signal: params.signal
3608
- }));
3609
- if (queued.delivered) return queued;
3610
- }
3611
- const direct = await sendSubagentAnnounceDirectly({
3612
- targetRequesterSessionKey: params.targetRequesterSessionKey,
3613
- triggerMessage: params.triggerMessage,
3614
- completionMessage: params.completionMessage,
3615
- directIdempotencyKey: params.directIdempotencyKey,
3616
- completionDirectOrigin: params.completionDirectOrigin,
3617
- completionRouteMode: params.completionRouteMode,
3618
- spawnMode: params.spawnMode,
3619
- directOrigin: params.directOrigin,
3620
- requesterIsSubagent: params.requesterIsSubagent,
3621
- expectsCompletionMessage: params.expectsCompletionMessage,
3622
- signal: params.signal,
3623
- bestEffortDeliver: params.bestEffortDeliver
3624
- });
3625
- if (direct.delivered || !params.expectsCompletionMessage) return direct;
3626
- const queueOutcome = await maybeQueueSubagentAnnounce({
3627
- requesterSessionKey: params.requesterSessionKey,
3628
- announceId: params.announceId,
3629
- triggerMessage: params.triggerMessage,
3630
- summaryLine: params.summaryLine,
3631
- requesterOrigin: params.requesterOrigin,
3632
- signal: params.signal
3633
- });
3634
- if (queueOutcome === "steered" || queueOutcome === "queued") return queueOutcomeToDeliveryResult(queueOutcome);
3635
- return direct;
3636
- }
3637
- function loadSessionEntryByKey(sessionKey) {
3638
- const cfg = loadConfig();
3639
- const agentId = resolveAgentIdFromSessionKey(sessionKey);
3640
- return loadSessionStore(resolveStorePath(cfg.session?.store, { agentId }))[sessionKey];
3641
- }
3642
- function buildSubagentSystemPrompt(params) {
3643
- const taskText = typeof params.task === "string" && params.task.trim() ? params.task.replace(/\s+/g, " ").trim() : "{{TASK_DESCRIPTION}}";
3644
- const childDepth = typeof params.childDepth === "number" ? params.childDepth : 1;
3645
- const canSpawn = childDepth < (typeof params.maxSpawnDepth === "number" ? params.maxSpawnDepth : DEFAULT_SUBAGENT_MAX_SPAWN_DEPTH);
3646
- const parentLabel = childDepth >= 2 ? "parent orchestrator" : "main agent";
3647
- const lines = [
3648
- "# Subagent Context",
3649
- "",
3650
- `You are a **subagent** spawned by the ${parentLabel} for a specific task.`,
3651
- "",
3652
- "## Your Role",
3653
- `- You were created to handle: ${taskText}`,
3654
- "- Complete this task. That's your entire purpose.",
3655
- `- You are NOT the ${parentLabel}. Don't try to be.`,
3656
- "",
3657
- "## Rules",
3658
- "1. **Stay focused** - Do your assigned task, nothing else",
3659
- `2. **Complete the task** - Your final message will be automatically reported to the ${parentLabel}`,
3660
- "3. **Don't initiate** - No heartbeats, no proactive actions, no side quests",
3661
- "4. **Be ephemeral** - You may be terminated after task completion. That's fine.",
3662
- "5. **Trust push-based completion** - Descendant results are auto-announced back to you; do not busy-poll for status.",
3663
- "6. **Recover from compacted/truncated tool output** - If you see `[compacted: tool output removed to free context]` or `[truncated: output exceeded context limit]`, assume prior output was reduced. Re-read only what you need using smaller chunks (`read` with offset/limit, or targeted `rg`/`head`/`tail`) instead of full-file `cat`.",
3664
- "",
3665
- "## Output Format",
3666
- "When complete, your final response should include:",
3667
- `- What you accomplished or found`,
3668
- `- Any relevant details the ${parentLabel} should know`,
3669
- "- Keep it concise but informative",
3670
- "",
3671
- "## What You DON'T Do",
3672
- `- NO user conversations (that's ${parentLabel}'s job)`,
3673
- "- NO external messages (email, tweets, etc.) unless explicitly tasked with a specific recipient/channel",
3674
- "- NO cron jobs or persistent state",
3675
- `- NO pretending to be the ${parentLabel}`,
3676
- `- Only use the \`message\` tool when explicitly instructed to contact a specific external recipient; otherwise return plain text and let the ${parentLabel} deliver it`,
3677
- ""
3678
- ];
3679
- if (canSpawn) lines.push("## Sub-Agent Spawning", "You CAN spawn your own sub-agents for parallel or complex work using `sessions_spawn`.", "Use the `subagents` tool to steer, kill, or do an on-demand status check for your spawned sub-agents.", "Your sub-agents will announce their results back to you automatically (not to the main agent).", "Default workflow: spawn work, continue orchestrating, and wait for auto-announced completions.", "Do NOT repeatedly poll `subagents list` in a loop unless you are actively debugging or intervening.", "Coordinate their work and synthesize results before reporting back.", "");
3680
- else if (childDepth >= 2) lines.push("## Sub-Agent Spawning", "You are a leaf worker and CANNOT spawn further sub-agents. Focus on your assigned task.", "");
3681
- lines.push("## Session Context", ...[
3682
- params.label ? `- Label: ${params.label}` : void 0,
3683
- params.requesterSessionKey ? `- Requester session: ${params.requesterSessionKey}.` : void 0,
3684
- params.requesterOrigin?.channel ? `- Requester channel: ${params.requesterOrigin.channel}.` : void 0,
3685
- `- Your session: ${params.childSessionKey}.`
3686
- ].filter((line) => line !== void 0), "");
3687
- return lines.join("\n");
3688
- }
3689
- function buildAnnounceReplyInstruction(params) {
3690
- if (params.remainingActiveSubagentRuns > 0) {
3691
- const activeRunsLabel = params.remainingActiveSubagentRuns === 1 ? "run" : "runs";
3692
- return `There are still ${params.remainingActiveSubagentRuns} active subagent ${activeRunsLabel} for this session. If they are part of the same workflow, wait for the remaining results before sending a user update. If they are unrelated, respond normally using only the result above.`;
3693
- }
3694
- if (params.requesterIsSubagent) return `Convert this completion into a concise internal orchestration update for your parent agent in your own words. Keep this internal context private (don't mention system/log/stats/session details or announce type). If this result is duplicate or no update is needed, reply ONLY: ${SILENT_REPLY_TOKEN}.`;
3695
- if (params.expectsCompletionMessage) return `A completed ${params.announceType} is ready for user delivery. Convert the result above into your normal assistant voice and send that user-facing update now. Keep this internal context private (don't mention system/log/stats/session details or announce type).`;
3696
- return `A completed ${params.announceType} is ready for user delivery. Convert the result above into your normal assistant voice and send that user-facing update now. Keep this internal context private (don't mention system/log/stats/session details or announce type), and do not copy the system message verbatim. Reply ONLY: ${SILENT_REPLY_TOKEN} if this exact result was already delivered to the user in this same turn.`;
3697
- }
3698
- async function runSubagentAnnounceFlow(params) {
3699
- let didAnnounce = false;
3700
- const expectsCompletionMessage = params.expectsCompletionMessage === true;
3701
- let shouldDeleteChildSession = params.cleanup === "delete";
3702
- try {
3703
- let targetRequesterSessionKey = params.requesterSessionKey;
3704
- let targetRequesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
3705
- const childSessionId = (() => {
3706
- const entry = loadSessionEntryByKey(params.childSessionKey);
3707
- return typeof entry?.sessionId === "string" && entry.sessionId.trim() ? entry.sessionId.trim() : void 0;
3708
- })();
3709
- const settleTimeoutMs = Math.min(Math.max(params.timeoutMs, 1), 12e4);
3710
- let reply = params.roundOneReply;
3711
- let outcome = params.outcome;
3712
- if (!reply && params.waitForCompletion !== false) {
3713
- const waitMs = settleTimeoutMs;
3714
- const wait = await callGateway({
3715
- method: "agent.wait",
3716
- params: {
3717
- runId: params.childRunId,
3718
- timeoutMs: waitMs
3719
- },
3720
- timeoutMs: waitMs + 2e3
3721
- });
3722
- const waitError = typeof wait?.error === "string" ? wait.error : void 0;
3723
- if (wait?.status === "timeout") outcome = { status: "timeout" };
3724
- else if (wait?.status === "error") outcome = {
3725
- status: "error",
3726
- error: waitError
3727
- };
3728
- else if (wait?.status === "ok") outcome = { status: "ok" };
3729
- if (typeof wait?.startedAt === "number" && !params.startedAt) params.startedAt = wait.startedAt;
3730
- if (typeof wait?.endedAt === "number" && !params.endedAt) params.endedAt = wait.endedAt;
3731
- if (wait?.status === "timeout") {
3732
- if (!outcome) outcome = { status: "timeout" };
3733
- }
3734
- reply = await readLatestSubagentOutput(params.childSessionKey);
3735
- }
3736
- if (!reply) reply = await readLatestSubagentOutput(params.childSessionKey);
3737
- if (!reply?.trim()) reply = await readLatestSubagentOutputWithRetry({
3738
- sessionKey: params.childSessionKey,
3739
- maxWaitMs: params.timeoutMs
3740
- });
3741
- if (isAnnounceSkip(reply)) return true;
3742
- if (!outcome) outcome = { status: "unknown" };
3743
- let requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
3744
- let activeChildDescendantRuns = 0;
3745
- try {
3746
- const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
3747
- activeChildDescendantRuns = Math.max(0, countActiveDescendantRuns(params.childSessionKey));
3748
- } catch {}
3749
- if (activeChildDescendantRuns > 0) {
3750
- shouldDeleteChildSession = false;
3751
- return false;
3752
- }
3753
- if (requesterDepth >= 1 && reply?.trim()) {
3754
- const minReplyChangeWaitMs = FAST_TEST_MODE ? FAST_TEST_REPLY_CHANGE_WAIT_MS : 250;
3755
- reply = await waitForSubagentOutputChange({
3756
- sessionKey: params.childSessionKey,
3757
- baselineReply: reply,
3758
- maxWaitMs: Math.max(minReplyChangeWaitMs, Math.min(params.timeoutMs, 2e3))
3759
- });
3760
- }
3761
- const statusLabel = outcome.status === "ok" ? "completed successfully" : outcome.status === "timeout" ? "timed out" : outcome.status === "error" ? `failed: ${outcome.error || "unknown error"}` : "finished with unknown status";
3762
- const announceType = params.announceType ?? "subagent task";
3763
- const taskLabel = params.label || params.task || "task";
3764
- const subagentName = resolveAgentIdFromSessionKey(params.childSessionKey);
3765
- const announceSessionId = childSessionId || "unknown";
3766
- const findings = reply || "(no output)";
3767
- let completionMessage = "";
3768
- let triggerMessage = "";
3769
- let requesterIsSubagent = requesterDepth >= 1;
3770
- if (requesterIsSubagent) {
3771
- const { isSubagentSessionRunActive, resolveRequesterForChildSession } = await Promise.resolve().then(() => subagent_registry_exports);
3772
- if (!isSubagentSessionRunActive(targetRequesterSessionKey)) {
3773
- const parentSessionEntry = loadSessionEntryByKey(targetRequesterSessionKey);
3774
- if (!(parentSessionEntry && typeof parentSessionEntry.sessionId === "string" && parentSessionEntry.sessionId.trim())) {
3775
- const fallback = resolveRequesterForChildSession(targetRequesterSessionKey);
3776
- if (!fallback?.requesterSessionKey) {
3777
- shouldDeleteChildSession = false;
3778
- return false;
3779
- }
3780
- targetRequesterSessionKey = fallback.requesterSessionKey;
3781
- targetRequesterOrigin = normalizeDeliveryContext(fallback.requesterOrigin) ?? targetRequesterOrigin;
3782
- requesterDepth = getSubagentDepthFromSessionStore(targetRequesterSessionKey);
3783
- requesterIsSubagent = requesterDepth >= 1;
3784
- }
3785
- }
3786
- }
3787
- let remainingActiveSubagentRuns = 0;
3788
- try {
3789
- const { countActiveDescendantRuns } = await Promise.resolve().then(() => subagent_registry_exports);
3790
- remainingActiveSubagentRuns = Math.max(0, countActiveDescendantRuns(targetRequesterSessionKey));
3791
- } catch {}
3792
- const replyInstruction = buildAnnounceReplyInstruction({
3793
- remainingActiveSubagentRuns,
3794
- requesterIsSubagent,
3795
- announceType,
3796
- expectsCompletionMessage
3797
- });
3798
- const statsLine = await buildCompactAnnounceStatsLine({
3799
- sessionKey: params.childSessionKey,
3800
- startedAt: params.startedAt,
3801
- endedAt: params.endedAt
3802
- });
3803
- completionMessage = buildCompletionDeliveryMessage({
3804
- findings,
3805
- subagentName,
3806
- spawnMode: params.spawnMode,
3807
- outcome
3808
- });
3809
- triggerMessage = [
3810
- [
3811
- `[System Message] [sessionId: ${announceSessionId}] A ${announceType} "${taskLabel}" just ${statusLabel}.`,
3812
- "",
3813
- "Result:",
3814
- findings,
3815
- "",
3816
- statsLine
3817
- ].join("\n"),
3818
- "",
3819
- replyInstruction
3820
- ].join("\n");
3821
- const announceId = buildAnnounceIdFromChildRun({
3822
- childSessionKey: params.childSessionKey,
3823
- childRunId: params.childRunId
3824
- });
3825
- let directOrigin = targetRequesterOrigin;
3826
- if (!requesterIsSubagent) {
3827
- const { entry } = loadRequesterSessionEntry(targetRequesterSessionKey);
3828
- directOrigin = resolveAnnounceOrigin(entry, targetRequesterOrigin);
3829
- }
3830
- const completionResolution = expectsCompletionMessage && !requesterIsSubagent ? await resolveSubagentCompletionOrigin({
3831
- childSessionKey: params.childSessionKey,
3832
- requesterSessionKey: targetRequesterSessionKey,
3833
- requesterOrigin: directOrigin,
3834
- childRunId: params.childRunId,
3835
- spawnMode: params.spawnMode,
3836
- expectsCompletionMessage
3837
- }) : {
3838
- origin: targetRequesterOrigin,
3839
- routeMode: "fallback"
3840
- };
3841
- const completionDirectOrigin = completionResolution.origin;
3842
- const directIdempotencyKey = buildAnnounceIdempotencyKey(announceId);
3843
- const delivery = await deliverSubagentAnnouncement({
3844
- requesterSessionKey: targetRequesterSessionKey,
3845
- announceId,
3846
- triggerMessage,
3847
- completionMessage,
3848
- summaryLine: taskLabel,
3849
- requesterOrigin: expectsCompletionMessage && !requesterIsSubagent ? completionDirectOrigin : targetRequesterOrigin,
3850
- completionDirectOrigin,
3851
- directOrigin,
3852
- targetRequesterSessionKey,
3853
- requesterIsSubagent,
3854
- expectsCompletionMessage,
3855
- bestEffortDeliver: params.bestEffortDeliver,
3856
- completionRouteMode: completionResolution.routeMode,
3857
- spawnMode: params.spawnMode,
3858
- directIdempotencyKey,
3859
- signal: params.signal
3860
- });
3861
- didAnnounce = delivery.delivered;
3862
- if (!delivery.delivered && delivery.path === "direct" && delivery.error) defaultRuntime.error?.(`Subagent completion direct announce failed for run ${params.childRunId}: ${delivery.error}`);
3863
- } catch (err) {
3864
- defaultRuntime.error?.(`Subagent announce failed: ${String(err)}`);
3865
- } finally {
3866
- if (params.label) try {
3867
- await callGateway({
3868
- method: "sessions.patch",
3869
- params: {
3870
- key: params.childSessionKey,
3871
- label: params.label
3872
- },
3873
- timeoutMs: 1e4
3874
- });
3875
- } catch {}
3876
- if (shouldDeleteChildSession) try {
3877
- await callGateway({
3878
- method: "sessions.delete",
3879
- params: {
3880
- key: params.childSessionKey,
3881
- deleteTranscript: true,
3882
- emitLifecycleHooks: false
3883
- },
3884
- timeoutMs: 1e4
3885
- });
3886
- } catch {}
3887
- }
3888
- return didAnnounce;
3889
- }
3890
-
3891
- //#endregion
3892
- //#region src/agents/subagent-lifecycle-events.ts
3893
- const SUBAGENT_TARGET_KIND_SUBAGENT = "subagent";
3894
- const SUBAGENT_ENDED_REASON_COMPLETE = "subagent-complete";
3895
- const SUBAGENT_ENDED_REASON_ERROR = "subagent-error";
3896
- const SUBAGENT_ENDED_REASON_KILLED = "subagent-killed";
3897
- const SUBAGENT_ENDED_OUTCOME_OK = "ok";
3898
- const SUBAGENT_ENDED_OUTCOME_ERROR = "error";
3899
- const SUBAGENT_ENDED_OUTCOME_TIMEOUT = "timeout";
3900
- const SUBAGENT_ENDED_OUTCOME_KILLED = "killed";
3901
-
3902
- //#endregion
3903
- //#region src/agents/subagent-registry-cleanup.ts
3904
- function resolveCleanupCompletionReason(entry) {
3905
- return entry.endedReason ?? SUBAGENT_ENDED_REASON_COMPLETE;
3906
- }
3907
- function resolveEndedAgoMs(entry, now) {
3908
- return typeof entry.endedAt === "number" ? now - entry.endedAt : 0;
3909
- }
3910
- function resolveDeferredCleanupDecision(params) {
3911
- const endedAgo = resolveEndedAgoMs(params.entry, params.now);
3912
- if (params.entry.expectsCompletionMessage === true && params.activeDescendantRuns > 0) {
3913
- if (endedAgo > params.announceExpiryMs) return {
3914
- kind: "give-up",
3915
- reason: "expiry"
3916
- };
3917
- return {
3918
- kind: "defer-descendants",
3919
- delayMs: params.deferDescendantDelayMs
3920
- };
3921
- }
3922
- const retryCount = (params.entry.announceRetryCount ?? 0) + 1;
3923
- if (retryCount >= params.maxAnnounceRetryCount || endedAgo > params.announceExpiryMs) return {
3924
- kind: "give-up",
3925
- reason: retryCount >= params.maxAnnounceRetryCount ? "retry-limit" : "expiry",
3926
- retryCount
3927
- };
3928
- return {
3929
- kind: "retry",
3930
- retryCount,
3931
- resumeDelayMs: params.entry.expectsCompletionMessage === true ? params.resolveAnnounceRetryDelayMs(retryCount) : void 0
3932
- };
3933
- }
3934
-
3935
- //#endregion
3936
- //#region src/agents/subagent-registry-completion.ts
3937
- function runOutcomesEqual(a, b) {
3938
- if (!a && !b) return true;
3939
- if (!a || !b) return false;
3940
- if (a.status !== b.status) return false;
3941
- if (a.status === "error" && b.status === "error") return (a.error ?? "") === (b.error ?? "");
3942
- return true;
3943
- }
3944
- function resolveLifecycleOutcomeFromRunOutcome(outcome) {
3945
- if (outcome?.status === "error") return SUBAGENT_ENDED_OUTCOME_ERROR;
3946
- if (outcome?.status === "timeout") return SUBAGENT_ENDED_OUTCOME_TIMEOUT;
3947
- return SUBAGENT_ENDED_OUTCOME_OK;
3948
- }
3949
- async function emitSubagentEndedHookOnce(params) {
3950
- const runId = params.entry.runId.trim();
3951
- if (!runId) return false;
3952
- if (params.entry.endedHookEmittedAt) return false;
3953
- if (params.inFlightRunIds.has(runId)) return false;
3954
- params.inFlightRunIds.add(runId);
3955
- try {
3956
- const hookRunner = getGlobalHookRunner();
3957
- if (hookRunner?.hasHooks("subagent_ended")) await hookRunner.runSubagentEnded({
3958
- targetSessionKey: params.entry.childSessionKey,
3959
- targetKind: SUBAGENT_TARGET_KIND_SUBAGENT,
3960
- reason: params.reason,
3961
- sendFarewell: params.sendFarewell,
3962
- accountId: params.accountId,
3963
- runId: params.entry.runId,
3964
- endedAt: params.entry.endedAt,
3965
- outcome: params.outcome,
3966
- error: params.error
3967
- }, {
3968
- runId: params.entry.runId,
3969
- childSessionKey: params.entry.childSessionKey,
3970
- requesterSessionKey: params.entry.requesterSessionKey
3971
- });
3972
- params.entry.endedHookEmittedAt = Date.now();
3973
- params.persist();
3974
- return true;
3975
- } catch {
3976
- return false;
3977
- } finally {
3978
- params.inFlightRunIds.delete(runId);
3979
- }
3980
- }
3981
-
3982
- //#endregion
3983
- //#region src/agents/subagent-registry-queries.ts
3984
- function findRunIdsByChildSessionKeyFromRuns(runs, childSessionKey) {
3985
- const key = childSessionKey.trim();
3986
- if (!key) return [];
3987
- const runIds = [];
3988
- for (const [runId, entry] of runs.entries()) if (entry.childSessionKey === key) runIds.push(runId);
3989
- return runIds;
3990
- }
3991
- function listRunsForRequesterFromRuns(runs, requesterSessionKey) {
3992
- const key = requesterSessionKey.trim();
3993
- if (!key) return [];
3994
- return [...runs.values()].filter((entry) => entry.requesterSessionKey === key);
3995
- }
3996
- function resolveRequesterForChildSessionFromRuns(runs, childSessionKey) {
3997
- const key = childSessionKey.trim();
3998
- if (!key) return null;
3999
- let best;
4000
- for (const entry of runs.values()) {
4001
- if (entry.childSessionKey !== key) continue;
4002
- if (!best || entry.createdAt > best.createdAt) best = entry;
4003
- }
4004
- if (!best) return null;
4005
- return {
4006
- requesterSessionKey: best.requesterSessionKey,
4007
- requesterOrigin: best.requesterOrigin
4008
- };
4009
- }
4010
- function countActiveRunsForSessionFromRuns(runs, requesterSessionKey) {
4011
- const key = requesterSessionKey.trim();
4012
- if (!key) return 0;
4013
- let count = 0;
4014
- for (const entry of runs.values()) {
4015
- if (entry.requesterSessionKey !== key) continue;
4016
- if (typeof entry.endedAt === "number") continue;
4017
- count += 1;
4018
- }
4019
- return count;
4020
- }
4021
- function countActiveDescendantRunsFromRuns(runs, rootSessionKey) {
4022
- const root = rootSessionKey.trim();
4023
- if (!root) return 0;
4024
- const pending = [root];
4025
- const visited = new Set([root]);
4026
- let count = 0;
4027
- while (pending.length > 0) {
4028
- const requester = pending.shift();
4029
- if (!requester) continue;
4030
- for (const entry of runs.values()) {
4031
- if (entry.requesterSessionKey !== requester) continue;
4032
- if (typeof entry.endedAt !== "number") count += 1;
4033
- const childKey = entry.childSessionKey.trim();
4034
- if (!childKey || visited.has(childKey)) continue;
4035
- visited.add(childKey);
4036
- pending.push(childKey);
4037
- }
4038
- }
4039
- return count;
4040
- }
4041
- function listDescendantRunsForRequesterFromRuns(runs, rootSessionKey) {
4042
- const root = rootSessionKey.trim();
4043
- if (!root) return [];
4044
- const pending = [root];
4045
- const visited = new Set([root]);
4046
- const descendants = [];
4047
- while (pending.length > 0) {
4048
- const requester = pending.shift();
4049
- if (!requester) continue;
4050
- for (const entry of runs.values()) {
4051
- if (entry.requesterSessionKey !== requester) continue;
4052
- descendants.push(entry);
4053
- const childKey = entry.childSessionKey.trim();
4054
- if (!childKey || visited.has(childKey)) continue;
4055
- visited.add(childKey);
4056
- pending.push(childKey);
4057
- }
4058
- }
4059
- return descendants;
4060
- }
4061
-
4062
- //#endregion
4063
- //#region src/agents/subagent-registry.store.ts
4064
- const REGISTRY_VERSION = 2;
4065
- function resolveSubagentStateDir(env = process.env) {
4066
- if (env.REMOTECLAW_STATE_DIR?.trim()) return resolveStateDir(env);
4067
- if (env.VITEST || env.NODE_ENV === "test") return path.join(os.tmpdir(), "remoteclaw-test-state", String(process.pid));
4068
- return resolveStateDir(env);
4069
- }
4070
- function resolveSubagentRegistryPath() {
4071
- return path.join(resolveSubagentStateDir(process.env), "subagents", "runs.json");
4072
- }
4073
- function loadSubagentRegistryFromDisk() {
4074
- const raw = loadJsonFile(resolveSubagentRegistryPath());
4075
- if (!raw || typeof raw !== "object") return /* @__PURE__ */ new Map();
4076
- const record = raw;
4077
- if (record.version !== 1 && record.version !== 2) return /* @__PURE__ */ new Map();
4078
- const runsRaw = record.runs;
4079
- if (!runsRaw || typeof runsRaw !== "object") return /* @__PURE__ */ new Map();
4080
- const out = /* @__PURE__ */ new Map();
4081
- const isLegacy = record.version === 1;
4082
- let migrated = false;
4083
- for (const [runId, entry] of Object.entries(runsRaw)) {
4084
- if (!entry || typeof entry !== "object") continue;
4085
- const typed = entry;
4086
- if (!typed.runId || typeof typed.runId !== "string") continue;
4087
- const legacyCompletedAt = isLegacy && typeof typed.announceCompletedAt === "number" ? typed.announceCompletedAt : void 0;
4088
- const cleanupCompletedAt = typeof typed.cleanupCompletedAt === "number" ? typed.cleanupCompletedAt : legacyCompletedAt;
4089
- const cleanupHandled = typeof typed.cleanupHandled === "boolean" ? typed.cleanupHandled : isLegacy ? Boolean(typed.announceHandled ?? cleanupCompletedAt) : void 0;
4090
- const requesterOrigin = normalizeDeliveryContext(typed.requesterOrigin ?? {
4091
- channel: typeof typed.requesterChannel === "string" ? typed.requesterChannel : void 0,
4092
- accountId: typeof typed.requesterAccountId === "string" ? typed.requesterAccountId : void 0
4093
- });
4094
- const { announceCompletedAt: _announceCompletedAt, announceHandled: _announceHandled, requesterChannel: _channel, requesterAccountId: _accountId, ...rest } = typed;
4095
- out.set(runId, {
4096
- ...rest,
4097
- requesterOrigin,
4098
- cleanupCompletedAt,
4099
- cleanupHandled,
4100
- spawnMode: typed.spawnMode === "session" ? "session" : "run"
4101
- });
4102
- if (isLegacy) migrated = true;
4103
- }
4104
- if (migrated) try {
4105
- saveSubagentRegistryToDisk(out);
4106
- } catch {}
4107
- return out;
4108
- }
4109
- function saveSubagentRegistryToDisk(runs) {
4110
- const pathname = resolveSubagentRegistryPath();
4111
- const serialized = {};
4112
- for (const [runId, entry] of runs.entries()) serialized[runId] = entry;
4113
- saveJsonFile(pathname, {
4114
- version: REGISTRY_VERSION,
4115
- runs: serialized
4116
- });
4117
- }
4118
-
4119
- //#endregion
4120
- //#region src/agents/subagent-registry-state.ts
4121
- function persistSubagentRunsToDisk(runs) {
4122
- try {
4123
- saveSubagentRegistryToDisk(runs);
4124
- } catch {}
4125
- }
4126
- function restoreSubagentRunsFromDisk(params) {
4127
- const restored = loadSubagentRegistryFromDisk();
4128
- if (restored.size === 0) return 0;
4129
- let added = 0;
4130
- for (const [runId, entry] of restored.entries()) {
4131
- if (!runId || !entry) continue;
4132
- if (params.mergeOnly && params.runs.has(runId)) continue;
4133
- params.runs.set(runId, entry);
4134
- added += 1;
4135
- }
4136
- return added;
4137
- }
4138
- function getSubagentRunsSnapshotForRead(inMemoryRuns) {
4139
- const merged = /* @__PURE__ */ new Map();
4140
- if (!(process.env.VITEST || false)) try {
4141
- for (const [runId, entry] of loadSubagentRegistryFromDisk().entries()) merged.set(runId, entry);
4142
- } catch {}
4143
- for (const [runId, entry] of inMemoryRuns.entries()) merged.set(runId, entry);
4144
- return merged;
4145
- }
4146
-
4147
- //#endregion
4148
- //#region src/agents/timeout.ts
4149
- const DEFAULT_AGENT_TIMEOUT_SECONDS = 600;
4150
- const MAX_SAFE_TIMEOUT_MS = 2147e6;
4151
- const normalizeNumber = (value) => typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : void 0;
4152
- function resolveAgentTimeoutSeconds(cfg) {
4153
- const seconds = normalizeNumber(cfg?.agents?.defaults?.timeoutSeconds) ?? DEFAULT_AGENT_TIMEOUT_SECONDS;
4154
- return Math.max(seconds, 1);
4155
- }
4156
- function resolveAgentTimeoutMs(opts) {
4157
- const minMs = Math.max(normalizeNumber(opts.minMs) ?? 1, 1);
4158
- const clampTimeoutMs = (valueMs) => Math.min(Math.max(valueMs, minMs), MAX_SAFE_TIMEOUT_MS);
4159
- const defaultMs = clampTimeoutMs(resolveAgentTimeoutSeconds(opts.cfg) * 1e3);
4160
- const NO_TIMEOUT_MS = MAX_SAFE_TIMEOUT_MS;
4161
- const overrideMs = normalizeNumber(opts.overrideMs);
4162
- if (overrideMs !== void 0) {
4163
- if (overrideMs === 0) return NO_TIMEOUT_MS;
4164
- if (overrideMs < 0) return defaultMs;
4165
- return clampTimeoutMs(overrideMs);
4166
- }
4167
- const overrideSeconds = normalizeNumber(opts.overrideSeconds);
4168
- if (overrideSeconds !== void 0) {
4169
- if (overrideSeconds === 0) return NO_TIMEOUT_MS;
4170
- if (overrideSeconds < 0) return defaultMs;
4171
- return clampTimeoutMs(overrideSeconds * 1e3);
4172
- }
4173
- return defaultMs;
4174
- }
4175
-
4176
- //#endregion
4177
- //#region src/agents/subagent-registry.ts
4178
- var subagent_registry_exports = /* @__PURE__ */ __exportAll({
4179
- clearSubagentRunSteerRestart: () => clearSubagentRunSteerRestart,
4180
- countActiveDescendantRuns: () => countActiveDescendantRuns,
4181
- countActiveRunsForSession: () => countActiveRunsForSession,
4182
- initSubagentRegistry: () => initSubagentRegistry,
4183
- isSubagentSessionRunActive: () => isSubagentSessionRunActive,
4184
- listDescendantRunsForRequester: () => listDescendantRunsForRequester,
4185
- listSubagentRunsForRequester: () => listSubagentRunsForRequester,
4186
- markSubagentRunForSteerRestart: () => markSubagentRunForSteerRestart,
4187
- markSubagentRunTerminated: () => markSubagentRunTerminated,
4188
- registerSubagentRun: () => registerSubagentRun,
4189
- replaceSubagentRunAfterSteer: () => replaceSubagentRunAfterSteer,
4190
- resolveRequesterForChildSession: () => resolveRequesterForChildSession
4191
- });
4192
- const subagentRuns = /* @__PURE__ */ new Map();
4193
- let sweeper = null;
4194
- let listenerStarted = false;
4195
- let listenerStop = null;
4196
- var restoreAttempted = false;
4197
- const SUBAGENT_ANNOUNCE_TIMEOUT_MS = 12e4;
4198
- const MIN_ANNOUNCE_RETRY_DELAY_MS = 1e3;
4199
- const MAX_ANNOUNCE_RETRY_DELAY_MS = 8e3;
4200
- /**
4201
- * Maximum number of announce delivery attempts before giving up.
4202
- * Prevents infinite retry loops when `runSubagentAnnounceFlow` repeatedly
4203
- * returns `false` due to stale state or transient conditions (#18264).
4204
- */
4205
- const MAX_ANNOUNCE_RETRY_COUNT = 3;
4206
- /**
4207
- * Announce entries older than this are force-expired even if delivery never
4208
- * succeeded. Guards against stale registry entries surviving gateway restarts.
4209
- */
4210
- const ANNOUNCE_EXPIRY_MS = 5 * 6e4;
4211
- function resolveAnnounceRetryDelayMs(retryCount) {
4212
- const boundedRetryCount = Math.max(0, Math.min(retryCount, 10));
4213
- const baseDelay = MIN_ANNOUNCE_RETRY_DELAY_MS * 2 ** Math.max(0, boundedRetryCount - 1);
4214
- return Math.min(baseDelay, MAX_ANNOUNCE_RETRY_DELAY_MS);
4215
- }
4216
- function logAnnounceGiveUp(entry, reason) {
4217
- const retryCount = entry.announceRetryCount ?? 0;
4218
- const endedAgoMs = typeof entry.endedAt === "number" ? Math.max(0, Date.now() - entry.endedAt) : void 0;
4219
- const endedAgoLabel = endedAgoMs != null ? `${Math.round(endedAgoMs / 1e3)}s` : "n/a";
4220
- defaultRuntime.log(`[warn] Subagent announce give up (${reason}) run=${entry.runId} child=${entry.childSessionKey} requester=${entry.requesterSessionKey} retries=${retryCount} endedAgo=${endedAgoLabel}`);
4221
- }
4222
- function persistSubagentRuns() {
4223
- persistSubagentRunsToDisk(subagentRuns);
4224
- }
4225
- function findSessionEntryByKey(store, sessionKey) {
4226
- const direct = store[sessionKey];
4227
- if (direct) return direct;
4228
- const normalized = sessionKey.toLowerCase();
4229
- for (const [key, entry] of Object.entries(store)) if (key.toLowerCase() === normalized) return entry;
4230
- }
4231
- function resolveSubagentRunOrphanReason(params) {
4232
- const childSessionKey = params.entry.childSessionKey?.trim();
4233
- if (!childSessionKey) return "missing-session-entry";
4234
- try {
4235
- const cfg = loadConfig();
4236
- const agentId = resolveAgentIdFromSessionKey(childSessionKey);
4237
- const storePath = resolveStorePath(cfg.session?.store, { agentId });
4238
- let store = params.storeCache?.get(storePath);
4239
- if (!store) {
4240
- store = loadSessionStore(storePath);
4241
- params.storeCache?.set(storePath, store);
4242
- }
4243
- const sessionEntry = findSessionEntryByKey(store, childSessionKey);
4244
- if (!sessionEntry) return "missing-session-entry";
4245
- if (typeof sessionEntry.sessionId !== "string" || !sessionEntry.sessionId.trim()) return "missing-session-id";
4246
- return null;
4247
- } catch {
4248
- return null;
4249
- }
4250
- }
4251
- function reconcileOrphanedRun(params) {
4252
- const now = Date.now();
4253
- let changed = false;
4254
- if (typeof params.entry.endedAt !== "number") {
4255
- params.entry.endedAt = now;
4256
- changed = true;
4257
- }
4258
- const orphanOutcome = {
4259
- status: "error",
4260
- error: `orphaned subagent run (${params.reason})`
4261
- };
4262
- if (!runOutcomesEqual(params.entry.outcome, orphanOutcome)) {
4263
- params.entry.outcome = orphanOutcome;
4264
- changed = true;
4265
- }
4266
- if (params.entry.endedReason !== SUBAGENT_ENDED_REASON_ERROR) {
4267
- params.entry.endedReason = SUBAGENT_ENDED_REASON_ERROR;
4268
- changed = true;
4269
- }
4270
- if (params.entry.cleanupHandled !== true) {
4271
- params.entry.cleanupHandled = true;
4272
- changed = true;
4273
- }
4274
- if (typeof params.entry.cleanupCompletedAt !== "number") {
4275
- params.entry.cleanupCompletedAt = now;
4276
- changed = true;
4277
- }
4278
- const removed = subagentRuns.delete(params.runId);
4279
- resumedRuns.delete(params.runId);
4280
- if (!removed && !changed) return false;
4281
- defaultRuntime.log(`[warn] Subagent orphan run pruned source=${params.source} run=${params.runId} child=${params.entry.childSessionKey} reason=${params.reason}`);
4282
- return true;
4283
- }
4284
- function reconcileOrphanedRestoredRuns() {
4285
- const storeCache = /* @__PURE__ */ new Map();
4286
- let changed = false;
4287
- for (const [runId, entry] of subagentRuns.entries()) {
4288
- const orphanReason = resolveSubagentRunOrphanReason({
4289
- entry,
4290
- storeCache
4291
- });
4292
- if (!orphanReason) continue;
4293
- if (reconcileOrphanedRun({
4294
- runId,
4295
- entry,
4296
- reason: orphanReason,
4297
- source: "restore"
4298
- })) changed = true;
4299
- }
4300
- return changed;
4301
- }
4302
- const resumedRuns = /* @__PURE__ */ new Set();
4303
- const endedHookInFlightRunIds = /* @__PURE__ */ new Set();
4304
- function suppressAnnounceForSteerRestart(entry) {
4305
- return entry?.suppressAnnounceReason === "steer-restart";
4306
- }
4307
- function shouldKeepThreadBindingAfterRun(params) {
4308
- if (params.reason === SUBAGENT_ENDED_REASON_KILLED) return false;
4309
- return params.entry.spawnMode === "session";
4310
- }
4311
- function shouldEmitEndedHookForRun(params) {
4312
- return !shouldKeepThreadBindingAfterRun(params);
4313
- }
4314
- async function emitSubagentEndedHookForRun(params) {
4315
- const reason = params.reason ?? params.entry.endedReason ?? SUBAGENT_ENDED_REASON_COMPLETE;
4316
- const outcome = resolveLifecycleOutcomeFromRunOutcome(params.entry.outcome);
4317
- const error = params.entry.outcome?.status === "error" ? params.entry.outcome.error : void 0;
4318
- await emitSubagentEndedHookOnce({
4319
- entry: params.entry,
4320
- reason,
4321
- sendFarewell: params.sendFarewell,
4322
- accountId: params.accountId ?? params.entry.requesterOrigin?.accountId,
4323
- outcome,
4324
- error,
4325
- inFlightRunIds: endedHookInFlightRunIds,
4326
- persist: persistSubagentRuns
4327
- });
4328
- }
4329
- async function completeSubagentRun(params) {
4330
- const entry = subagentRuns.get(params.runId);
4331
- if (!entry) return;
4332
- let mutated = false;
4333
- const endedAt = typeof params.endedAt === "number" ? params.endedAt : Date.now();
4334
- if (entry.endedAt !== endedAt) {
4335
- entry.endedAt = endedAt;
4336
- mutated = true;
4337
- }
4338
- if (!runOutcomesEqual(entry.outcome, params.outcome)) {
4339
- entry.outcome = params.outcome;
4340
- mutated = true;
4341
- }
4342
- if (entry.endedReason !== params.reason) {
4343
- entry.endedReason = params.reason;
4344
- mutated = true;
4345
- }
4346
- if (mutated) persistSubagentRuns();
4347
- const suppressedForSteerRestart = suppressAnnounceForSteerRestart(entry);
4348
- const shouldEmitEndedHook = !suppressedForSteerRestart && shouldEmitEndedHookForRun({
4349
- entry,
4350
- reason: params.reason
4351
- });
4352
- if (!(shouldEmitEndedHook && params.triggerCleanup && entry.expectsCompletionMessage === true && !suppressedForSteerRestart) && shouldEmitEndedHook) await emitSubagentEndedHookForRun({
4353
- entry,
4354
- reason: params.reason,
4355
- sendFarewell: params.sendFarewell,
4356
- accountId: params.accountId
4357
- });
4358
- if (!params.triggerCleanup) return;
4359
- if (suppressedForSteerRestart) return;
4360
- startSubagentAnnounceCleanupFlow(params.runId, entry);
4361
- }
4362
- function startSubagentAnnounceCleanupFlow(runId, entry) {
4363
- if (!beginSubagentCleanup(runId)) return false;
4364
- const requesterOrigin = normalizeDeliveryContext(entry.requesterOrigin);
4365
- runSubagentAnnounceFlow({
4366
- childSessionKey: entry.childSessionKey,
4367
- childRunId: entry.runId,
4368
- requesterSessionKey: entry.requesterSessionKey,
4369
- requesterOrigin,
4370
- requesterDisplayKey: entry.requesterDisplayKey,
4371
- task: entry.task,
4372
- timeoutMs: SUBAGENT_ANNOUNCE_TIMEOUT_MS,
4373
- cleanup: entry.cleanup,
4374
- waitForCompletion: false,
4375
- startedAt: entry.startedAt,
4376
- endedAt: entry.endedAt,
4377
- label: entry.label,
4378
- outcome: entry.outcome,
4379
- spawnMode: entry.spawnMode,
4380
- expectsCompletionMessage: entry.expectsCompletionMessage
4381
- }).then((didAnnounce) => {
4382
- finalizeSubagentCleanup(runId, entry.cleanup, didAnnounce);
4383
- });
4384
- return true;
4385
- }
4386
- function resumeSubagentRun(runId) {
4387
- if (!runId || resumedRuns.has(runId)) return;
4388
- const entry = subagentRuns.get(runId);
4389
- if (!entry) return;
4390
- const orphanReason = resolveSubagentRunOrphanReason({ entry });
4391
- if (orphanReason) {
4392
- if (reconcileOrphanedRun({
4393
- runId,
4394
- entry,
4395
- reason: orphanReason,
4396
- source: "resume"
4397
- })) persistSubagentRuns();
4398
- return;
4399
- }
4400
- if (entry.cleanupCompletedAt) return;
4401
- if ((entry.announceRetryCount ?? 0) >= MAX_ANNOUNCE_RETRY_COUNT) {
4402
- logAnnounceGiveUp(entry, "retry-limit");
4403
- entry.cleanupCompletedAt = Date.now();
4404
- persistSubagentRuns();
4405
- return;
4406
- }
4407
- if (typeof entry.endedAt === "number" && Date.now() - entry.endedAt > ANNOUNCE_EXPIRY_MS) {
4408
- logAnnounceGiveUp(entry, "expiry");
4409
- entry.cleanupCompletedAt = Date.now();
4410
- persistSubagentRuns();
4411
- return;
4412
- }
4413
- const now = Date.now();
4414
- const delayMs = resolveAnnounceRetryDelayMs(entry.announceRetryCount ?? 0);
4415
- const earliestRetryAt = (entry.lastAnnounceRetryAt ?? 0) + delayMs;
4416
- if (entry.expectsCompletionMessage === true && entry.lastAnnounceRetryAt && now < earliestRetryAt) {
4417
- const waitMs = Math.max(1, earliestRetryAt - now);
4418
- setTimeout(() => {
4419
- resumeSubagentRun(runId);
4420
- }, waitMs).unref?.();
4421
- resumedRuns.add(runId);
4422
- return;
4423
- }
4424
- if (typeof entry.endedAt === "number" && entry.endedAt > 0) {
4425
- if (suppressAnnounceForSteerRestart(entry)) {
4426
- resumedRuns.add(runId);
4427
- return;
4428
- }
4429
- if (!startSubagentAnnounceCleanupFlow(runId, entry)) return;
4430
- resumedRuns.add(runId);
4431
- return;
4432
- }
4433
- waitForSubagentCompletion(runId, resolveSubagentWaitTimeoutMs(loadConfig(), entry.runTimeoutSeconds));
4434
- resumedRuns.add(runId);
4435
- }
4436
- function restoreSubagentRunsOnce() {
4437
- if (restoreAttempted) return;
4438
- restoreAttempted = true;
4439
- try {
4440
- if (restoreSubagentRunsFromDisk({
4441
- runs: subagentRuns,
4442
- mergeOnly: true
4443
- }) === 0) return;
4444
- if (reconcileOrphanedRestoredRuns()) persistSubagentRuns();
4445
- if (subagentRuns.size === 0) return;
4446
- ensureListener();
4447
- if ([...subagentRuns.values()].some((entry) => entry.archiveAtMs)) startSweeper();
4448
- for (const runId of subagentRuns.keys()) resumeSubagentRun(runId);
4449
- } catch {}
4450
- }
4451
- function resolveArchiveAfterMs(cfg) {
4452
- const minutes = (cfg ?? loadConfig()).agents?.defaults?.subagents?.archiveAfterMinutes ?? 60;
4453
- if (!Number.isFinite(minutes) || minutes <= 0) return;
4454
- return Math.max(1, Math.floor(minutes)) * 6e4;
4455
- }
4456
- function resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds) {
4457
- return resolveAgentTimeoutMs({
4458
- cfg,
4459
- overrideSeconds: runTimeoutSeconds ?? 0
4460
- });
4461
- }
4462
- function startSweeper() {
4463
- if (sweeper) return;
4464
- sweeper = setInterval(() => {
4465
- sweepSubagentRuns();
4466
- }, 6e4);
4467
- sweeper.unref?.();
4468
- }
4469
- function stopSweeper() {
4470
- if (!sweeper) return;
4471
- clearInterval(sweeper);
4472
- sweeper = null;
4473
- }
4474
- async function sweepSubagentRuns() {
4475
- const now = Date.now();
4476
- let mutated = false;
4477
- for (const [runId, entry] of subagentRuns.entries()) {
4478
- if (!entry.archiveAtMs || entry.archiveAtMs > now) continue;
4479
- subagentRuns.delete(runId);
4480
- mutated = true;
4481
- try {
4482
- await callGateway({
4483
- method: "sessions.delete",
4484
- params: {
4485
- key: entry.childSessionKey,
4486
- deleteTranscript: true,
4487
- emitLifecycleHooks: false
4488
- },
4489
- timeoutMs: 1e4
4490
- });
4491
- } catch {}
4492
- }
4493
- if (mutated) persistSubagentRuns();
4494
- if (subagentRuns.size === 0) stopSweeper();
4495
- }
4496
- function ensureListener() {
4497
- if (listenerStarted) return;
4498
- listenerStarted = true;
4499
- listenerStop = onAgentEvent((evt) => {
4500
- (async () => {
4501
- if (!evt || evt.stream !== "lifecycle") return;
4502
- const entry = subagentRuns.get(evt.runId);
4503
- if (!entry) return;
4504
- const phase = evt.data?.phase;
4505
- if (phase === "start") {
4506
- const startedAt = typeof evt.data?.startedAt === "number" ? evt.data.startedAt : void 0;
4507
- if (startedAt) {
4508
- entry.startedAt = startedAt;
4509
- persistSubagentRuns();
4510
- }
4511
- return;
4512
- }
4513
- if (phase !== "end" && phase !== "error") return;
4514
- const endedAt = typeof evt.data?.endedAt === "number" ? evt.data.endedAt : Date.now();
4515
- const error = typeof evt.data?.error === "string" ? evt.data.error : void 0;
4516
- const outcome = phase === "error" ? {
4517
- status: "error",
4518
- error
4519
- } : evt.data?.aborted ? { status: "timeout" } : { status: "ok" };
4520
- await completeSubagentRun({
4521
- runId: evt.runId,
4522
- endedAt,
4523
- outcome,
4524
- reason: phase === "error" ? SUBAGENT_ENDED_REASON_ERROR : SUBAGENT_ENDED_REASON_COMPLETE,
4525
- sendFarewell: true,
4526
- accountId: entry.requesterOrigin?.accountId,
4527
- triggerCleanup: true
4528
- });
4529
- })();
4530
- });
4531
- }
4532
- async function finalizeSubagentCleanup(runId, cleanup, didAnnounce) {
4533
- const entry = subagentRuns.get(runId);
4534
- if (!entry) return;
4535
- if (didAnnounce) {
4536
- await emitCompletionEndedHookIfNeeded(entry, resolveCleanupCompletionReason(entry));
4537
- completeCleanupBookkeeping({
4538
- runId,
4539
- entry,
4540
- cleanup,
4541
- completedAt: Date.now()
4542
- });
4543
- return;
4544
- }
4545
- const now = Date.now();
4546
- const deferredDecision = resolveDeferredCleanupDecision({
4547
- entry,
4548
- now,
4549
- activeDescendantRuns: Math.max(0, countActiveDescendantRuns(entry.childSessionKey)),
4550
- announceExpiryMs: ANNOUNCE_EXPIRY_MS,
4551
- maxAnnounceRetryCount: MAX_ANNOUNCE_RETRY_COUNT,
4552
- deferDescendantDelayMs: MIN_ANNOUNCE_RETRY_DELAY_MS,
4553
- resolveAnnounceRetryDelayMs
4554
- });
4555
- if (deferredDecision.kind === "defer-descendants") {
4556
- entry.lastAnnounceRetryAt = now;
4557
- entry.cleanupHandled = false;
4558
- resumedRuns.delete(runId);
4559
- persistSubagentRuns();
4560
- setTimeout(() => {
4561
- resumeSubagentRun(runId);
4562
- }, deferredDecision.delayMs).unref?.();
4563
- return;
4564
- }
4565
- if (deferredDecision.retryCount != null) {
4566
- entry.announceRetryCount = deferredDecision.retryCount;
4567
- entry.lastAnnounceRetryAt = now;
4568
- }
4569
- if (deferredDecision.kind === "give-up") {
4570
- await emitCompletionEndedHookIfNeeded(entry, resolveCleanupCompletionReason(entry));
4571
- logAnnounceGiveUp(entry, deferredDecision.reason);
4572
- completeCleanupBookkeeping({
4573
- runId,
4574
- entry,
4575
- cleanup: "keep",
4576
- completedAt: now
4577
- });
4578
- return;
4579
- }
4580
- entry.cleanupHandled = false;
4581
- resumedRuns.delete(runId);
4582
- persistSubagentRuns();
4583
- if (deferredDecision.resumeDelayMs == null) return;
4584
- setTimeout(() => {
4585
- resumeSubagentRun(runId);
4586
- }, deferredDecision.resumeDelayMs).unref?.();
4587
- }
4588
- async function emitCompletionEndedHookIfNeeded(entry, reason) {
4589
- if (entry.expectsCompletionMessage === true && shouldEmitEndedHookForRun({
4590
- entry,
4591
- reason
4592
- })) await emitSubagentEndedHookForRun({
4593
- entry,
4594
- reason,
4595
- sendFarewell: true
4596
- });
4597
- }
4598
- function completeCleanupBookkeeping(params) {
4599
- if (params.cleanup === "delete") {
4600
- subagentRuns.delete(params.runId);
4601
- persistSubagentRuns();
4602
- retryDeferredCompletedAnnounces(params.runId);
4603
- return;
4604
- }
4605
- params.entry.cleanupCompletedAt = params.completedAt;
4606
- persistSubagentRuns();
4607
- retryDeferredCompletedAnnounces(params.runId);
4608
- }
4609
- function retryDeferredCompletedAnnounces(excludeRunId) {
4610
- const now = Date.now();
4611
- for (const [runId, entry] of subagentRuns.entries()) {
4612
- if (excludeRunId && runId === excludeRunId) continue;
4613
- if (typeof entry.endedAt !== "number") continue;
4614
- if (entry.cleanupCompletedAt || entry.cleanupHandled) continue;
4615
- if (suppressAnnounceForSteerRestart(entry)) continue;
4616
- if (now - (entry.endedAt ?? now) > ANNOUNCE_EXPIRY_MS) {
4617
- logAnnounceGiveUp(entry, "expiry");
4618
- entry.cleanupCompletedAt = now;
4619
- persistSubagentRuns();
4620
- continue;
4621
- }
4622
- resumedRuns.delete(runId);
4623
- resumeSubagentRun(runId);
4624
- }
4625
- }
4626
- function beginSubagentCleanup(runId) {
4627
- const entry = subagentRuns.get(runId);
4628
- if (!entry) return false;
4629
- if (entry.cleanupCompletedAt) return false;
4630
- if (entry.cleanupHandled) return false;
4631
- entry.cleanupHandled = true;
4632
- persistSubagentRuns();
4633
- return true;
4634
- }
4635
- function markSubagentRunForSteerRestart(runId) {
4636
- const key = runId.trim();
4637
- if (!key) return false;
4638
- const entry = subagentRuns.get(key);
4639
- if (!entry) return false;
4640
- if (entry.suppressAnnounceReason === "steer-restart") return true;
4641
- entry.suppressAnnounceReason = "steer-restart";
4642
- persistSubagentRuns();
4643
- return true;
4644
- }
4645
- function clearSubagentRunSteerRestart(runId) {
4646
- const key = runId.trim();
4647
- if (!key) return false;
4648
- const entry = subagentRuns.get(key);
4649
- if (!entry) return false;
4650
- if (entry.suppressAnnounceReason !== "steer-restart") return true;
4651
- entry.suppressAnnounceReason = void 0;
4652
- persistSubagentRuns();
4653
- resumedRuns.delete(key);
4654
- if (typeof entry.endedAt === "number" && !entry.cleanupCompletedAt) resumeSubagentRun(key);
4655
- return true;
4656
- }
4657
- function replaceSubagentRunAfterSteer(params) {
4658
- const previousRunId = params.previousRunId.trim();
4659
- const nextRunId = params.nextRunId.trim();
4660
- if (!previousRunId || !nextRunId) return false;
4661
- const source = subagentRuns.get(previousRunId) ?? params.fallback;
4662
- if (!source) return false;
4663
- if (previousRunId !== nextRunId) {
4664
- subagentRuns.delete(previousRunId);
4665
- resumedRuns.delete(previousRunId);
4666
- }
4667
- const now = Date.now();
4668
- const cfg = loadConfig();
4669
- const archiveAfterMs = resolveArchiveAfterMs(cfg);
4670
- const spawnMode = source.spawnMode === "session" ? "session" : "run";
4671
- const archiveAtMs = spawnMode === "session" ? void 0 : archiveAfterMs ? now + archiveAfterMs : void 0;
4672
- const runTimeoutSeconds = params.runTimeoutSeconds ?? source.runTimeoutSeconds ?? 0;
4673
- const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds);
4674
- const next = {
4675
- ...source,
4676
- runId: nextRunId,
4677
- startedAt: now,
4678
- endedAt: void 0,
4679
- endedReason: void 0,
4680
- endedHookEmittedAt: void 0,
4681
- outcome: void 0,
4682
- cleanupCompletedAt: void 0,
4683
- cleanupHandled: false,
4684
- suppressAnnounceReason: void 0,
4685
- announceRetryCount: void 0,
4686
- lastAnnounceRetryAt: void 0,
4687
- spawnMode,
4688
- archiveAtMs,
4689
- runTimeoutSeconds
4690
- };
4691
- subagentRuns.set(nextRunId, next);
4692
- ensureListener();
4693
- persistSubagentRuns();
4694
- if (archiveAtMs) startSweeper();
4695
- waitForSubagentCompletion(nextRunId, waitTimeoutMs);
4696
- return true;
4697
- }
4698
- function registerSubagentRun(params) {
4699
- const now = Date.now();
4700
- const cfg = loadConfig();
4701
- const archiveAfterMs = resolveArchiveAfterMs(cfg);
4702
- const spawnMode = params.spawnMode === "session" ? "session" : "run";
4703
- const archiveAtMs = spawnMode === "session" ? void 0 : archiveAfterMs ? now + archiveAfterMs : void 0;
4704
- const runTimeoutSeconds = params.runTimeoutSeconds ?? 0;
4705
- const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, runTimeoutSeconds);
4706
- const requesterOrigin = normalizeDeliveryContext(params.requesterOrigin);
4707
- subagentRuns.set(params.runId, {
4708
- runId: params.runId,
4709
- childSessionKey: params.childSessionKey,
4710
- requesterSessionKey: params.requesterSessionKey,
4711
- requesterOrigin,
4712
- requesterDisplayKey: params.requesterDisplayKey,
4713
- task: params.task,
4714
- cleanup: params.cleanup,
4715
- expectsCompletionMessage: params.expectsCompletionMessage,
4716
- spawnMode,
4717
- label: params.label,
4718
- model: params.model,
4719
- runTimeoutSeconds,
4720
- createdAt: now,
4721
- startedAt: now,
4722
- archiveAtMs,
4723
- cleanupHandled: false
4724
- });
4725
- ensureListener();
4726
- persistSubagentRuns();
4727
- if (archiveAtMs) startSweeper();
4728
- waitForSubagentCompletion(params.runId, waitTimeoutMs);
4729
- }
4730
- async function waitForSubagentCompletion(runId, waitTimeoutMs) {
4731
- try {
4732
- const timeoutMs = Math.max(1, Math.floor(waitTimeoutMs));
4733
- const wait = await callGateway({
4734
- method: "agent.wait",
4735
- params: {
4736
- runId,
4737
- timeoutMs
4738
- },
4739
- timeoutMs: timeoutMs + 1e4
4740
- });
4741
- if (wait?.status !== "ok" && wait?.status !== "error" && wait?.status !== "timeout") return;
4742
- const entry = subagentRuns.get(runId);
4743
- if (!entry) return;
4744
- let mutated = false;
4745
- if (typeof wait.startedAt === "number") {
4746
- entry.startedAt = wait.startedAt;
4747
- mutated = true;
4748
- }
4749
- if (typeof wait.endedAt === "number") {
4750
- entry.endedAt = wait.endedAt;
4751
- mutated = true;
4752
- }
4753
- if (!entry.endedAt) {
4754
- entry.endedAt = Date.now();
4755
- mutated = true;
4756
- }
4757
- const waitError = typeof wait.error === "string" ? wait.error : void 0;
4758
- const outcome = wait.status === "error" ? {
4759
- status: "error",
4760
- error: waitError
4761
- } : wait.status === "timeout" ? { status: "timeout" } : { status: "ok" };
4762
- if (!runOutcomesEqual(entry.outcome, outcome)) {
4763
- entry.outcome = outcome;
4764
- mutated = true;
4765
- }
4766
- if (mutated) persistSubagentRuns();
4767
- await completeSubagentRun({
4768
- runId,
4769
- endedAt: entry.endedAt,
4770
- outcome,
4771
- reason: wait.status === "error" ? SUBAGENT_ENDED_REASON_ERROR : SUBAGENT_ENDED_REASON_COMPLETE,
4772
- sendFarewell: true,
4773
- accountId: entry.requesterOrigin?.accountId,
4774
- triggerCleanup: true
4775
- });
4776
- } catch {}
4777
- }
4778
- function findRunIdsByChildSessionKey(childSessionKey) {
4779
- return findRunIdsByChildSessionKeyFromRuns(subagentRuns, childSessionKey);
4780
- }
4781
- function resolveRequesterForChildSession(childSessionKey) {
4782
- const resolved = resolveRequesterForChildSessionFromRuns(getSubagentRunsSnapshotForRead(subagentRuns), childSessionKey);
4783
- if (!resolved) return null;
4784
- return {
4785
- requesterSessionKey: resolved.requesterSessionKey,
4786
- requesterOrigin: normalizeDeliveryContext(resolved.requesterOrigin)
4787
- };
4788
- }
4789
- function isSubagentSessionRunActive(childSessionKey) {
4790
- const runIds = findRunIdsByChildSessionKey(childSessionKey);
4791
- for (const runId of runIds) {
4792
- const entry = subagentRuns.get(runId);
4793
- if (!entry) continue;
4794
- if (typeof entry.endedAt !== "number") return true;
4795
- }
4796
- return false;
4797
- }
4798
- function markSubagentRunTerminated(params) {
4799
- const runIds = /* @__PURE__ */ new Set();
4800
- if (typeof params.runId === "string" && params.runId.trim()) runIds.add(params.runId.trim());
4801
- if (typeof params.childSessionKey === "string" && params.childSessionKey.trim()) for (const runId of findRunIdsByChildSessionKey(params.childSessionKey)) runIds.add(runId);
4802
- if (runIds.size === 0) return 0;
4803
- const now = Date.now();
4804
- const reason = params.reason?.trim() || "killed";
4805
- let updated = 0;
4806
- const entriesByChildSessionKey = /* @__PURE__ */ new Map();
4807
- for (const runId of runIds) {
4808
- const entry = subagentRuns.get(runId);
4809
- if (!entry) continue;
4810
- if (typeof entry.endedAt === "number") continue;
4811
- entry.endedAt = now;
4812
- entry.outcome = {
4813
- status: "error",
4814
- error: reason
4815
- };
4816
- entry.endedReason = SUBAGENT_ENDED_REASON_KILLED;
4817
- entry.cleanupHandled = true;
4818
- entry.cleanupCompletedAt = now;
4819
- entry.suppressAnnounceReason = "killed";
4820
- if (!entriesByChildSessionKey.has(entry.childSessionKey)) entriesByChildSessionKey.set(entry.childSessionKey, entry);
4821
- updated += 1;
4822
- }
4823
- if (updated > 0) {
4824
- persistSubagentRuns();
4825
- for (const entry of entriesByChildSessionKey.values()) emitSubagentEndedHookOnce({
4826
- entry,
4827
- reason: SUBAGENT_ENDED_REASON_KILLED,
4828
- sendFarewell: true,
4829
- outcome: SUBAGENT_ENDED_OUTCOME_KILLED,
4830
- error: reason,
4831
- inFlightRunIds: endedHookInFlightRunIds,
4832
- persist: persistSubagentRuns
4833
- }).catch(() => {});
4834
- }
4835
- return updated;
4836
- }
4837
- function listSubagentRunsForRequester(requesterSessionKey) {
4838
- return listRunsForRequesterFromRuns(subagentRuns, requesterSessionKey);
4839
- }
4840
- function countActiveRunsForSession(requesterSessionKey) {
4841
- return countActiveRunsForSessionFromRuns(getSubagentRunsSnapshotForRead(subagentRuns), requesterSessionKey);
4842
- }
4843
- function countActiveDescendantRuns(rootSessionKey) {
4844
- return countActiveDescendantRunsFromRuns(getSubagentRunsSnapshotForRead(subagentRuns), rootSessionKey);
4845
- }
4846
- function listDescendantRunsForRequester(rootSessionKey) {
4847
- return listDescendantRunsForRequesterFromRuns(getSubagentRunsSnapshotForRead(subagentRuns), rootSessionKey);
4848
- }
4849
- function initSubagentRegistry() {
4850
- restoreSubagentRunsOnce();
4851
- }
4852
-
4853
- //#endregion
4854
- export { clearCommandLane as $, createAgentToAgentPolicy as A, getSubagentDepthFromSessionStore as B, runAgentStep as C, sanitizeTextContent as D, extractAssistantText as E, resolveDisplaySessionKey as F, enqueueFollowupRun as G, registerSessionBindingAdapter as H, resolveInternalSessionKey as I, isRoutableChannel as J, getFollowupQueueDepth as K, resolveMainSessionAlias as L, resolveEffectiveSessionToolsVisibility as M, resolveSandboxedSessionToolContext as N, stripToolMessages as O, isResolvedSessionVisibleToRequester as P, clearSessionQueues as Q, resolveSessionReference as R, readLatestAssistantReply as S, deriveChannel as T, unregisterSessionBindingAdapter as U, extractTextFromChatContent as V, resolveQueueSettings as W, normalizeReplyPayload as X, routeReply as Y, createReceiptCard as Z, buildAgentToAgentReplyContext as _, listDescendantRunsForRequester as a, waitForActiveTasks as at, resolveAnnounceTargetFromKey as b, markSubagentRunTerminated as c, logSessionStateChange as ct, subagent_registry_exports as d, logWebhookReceived as dt, getActiveTaskCount as et, resolveAgentTimeoutMs as f, startDiagnosticHeartbeat as ft, buildAgentToAgentMessageContext as g, extractQueueDirective as gt, buildAgentToAgentAnnounceContext as h, isDiagnosticsEnabled as ht, initSubagentRegistry as i, setCommandLaneConcurrency as it, createSessionVisibilityGuard as j, stripReasoningTagsFromText as k, registerSubagentRun as l, logWebhookError as lt, runSubagentAnnounceFlow as m, emitDiagnosticEvent as mt, countActiveDescendantRuns as n, getTotalQueueSize as nt, listSubagentRunsForRequester as o, logMessageProcessed as ot, buildSubagentSystemPrompt as p, stopDiagnosticHeartbeat as pt, scheduleFollowupDrain as q, countActiveRunsForSession as r, resetAllLanes as rt, markSubagentRunForSteerRestart as s, logMessageQueued as st, clearSubagentRunSteerRestart as t, getQueueSize as tt, replaceSubagentRunAfterSteer as u, logWebhookProcessed as ut, isAnnounceSkip as v, classifySessionKind as w, resolvePingPongTurns as x, isReplySkip as y, shouldResolveSessionIdInput as z };