@gaodefa/daocore 2026.5.86 → 2026.5.88

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 (1150) hide show
  1. package/dist/abort-DF_NBB7k.js +277 -0
  2. package/dist/abort.runtime-D4MkvEhQ.js +2 -0
  3. package/dist/abort.runtime.js +1 -1
  4. package/dist/account-inspect-BgTcq2xK.js +173 -0
  5. package/dist/accounts-B4A5OwEA.js +119 -0
  6. package/dist/accounts-BkS1Fh-0.js +107 -0
  7. package/dist/accounts-DF7-7Smq.js +107 -0
  8. package/dist/accounts-UL1OgSV7.js +2 -0
  9. package/dist/acp/control-plane/manager.d.ts +1 -2
  10. package/dist/acp-runtime-Cx2ACvcD.js +26 -0
  11. package/dist/acp-spawn-BGd_lmtE.js +2 -0
  12. package/dist/acp-spawn-BV0aSrgH.js +1275 -0
  13. package/dist/acp-stateful-target-driver-BZXAtm9O.js +89 -0
  14. package/dist/action-kill-CrabJ-6-.js +33 -0
  15. package/dist/action-runtime-BWOfmJe3.js +469 -0
  16. package/dist/action-runtime-api-Fr0Pcsql.js +2 -0
  17. package/dist/action-send-Cpl-x8ro.js +39 -0
  18. package/dist/action-spawn-DceGvU1M.js +47 -0
  19. package/dist/actions-Dx4zHx1-.js +161 -0
  20. package/dist/actions.runtime-CXgc7_sE.js +5 -0
  21. package/dist/agent-6f80KcUH.js +2 -0
  22. package/dist/agent-B2kAd5xV.js +3 -0
  23. package/dist/agent-command-COFQwKxZ.d.ts +141 -0
  24. package/dist/agent-command-DwGwELK0.js +1367 -0
  25. package/dist/agent-components.runtime-DJYuGMFi.js +10 -0
  26. package/dist/agent-components.runtime.js +1 -1
  27. package/dist/agent-harness-WlBoSv-g.d.ts +146 -0
  28. package/dist/agent-harness-runtime-D_wIHJVe.js +180 -0
  29. package/dist/agent-harness-task-runtime-ol_ltjHi.js +140 -0
  30. package/dist/agent-runner-execution-D5wMRx5h.js +1713 -0
  31. package/dist/agent-runner-utils-CLCfaT2K.js +266 -0
  32. package/dist/agent-runner.runtime-Igsb-Us4.js +3455 -0
  33. package/dist/agent-runner.runtime.js +1 -1
  34. package/dist/agent-runtime-tAPmASEK.js +229 -0
  35. package/dist/agent-via-gateway-CmOOhHWf.js +463 -0
  36. package/dist/api-BGUYfA7u.js +639 -0
  37. package/dist/api-Bb3jRMVp.js +3 -0
  38. package/dist/api-CDGKNega.js +6 -0
  39. package/dist/api-D-TLdpx5.js +2 -0
  40. package/dist/api-DXDbFZ7W.js +134 -0
  41. package/dist/api-o2EhTZRZ.js +2 -0
  42. package/dist/apply-BWXKR0_1.js +41 -0
  43. package/dist/apply-C3i3NucS.js +54 -0
  44. package/dist/approval-handler.runtime-DhzHxhOa.js +130 -0
  45. package/dist/assistant-SXZqrOD4.js +291 -0
  46. package/dist/attachment-normalize-DobdGk6t.js +225 -0
  47. package/dist/attempt-execution-BOV_h0-N.js +558 -0
  48. package/dist/attempt-execution.runtime-CXlw2E2H.js +3 -0
  49. package/dist/attempt-execution.runtime.js +1 -1
  50. package/dist/attempt-execution.shared-BUNB-ofJ.js +38 -0
  51. package/dist/attempt.prompt-helpers-DfgNBTYi.js +475 -0
  52. package/dist/attempt.tool-run-context-DdadqfC-.js +2094 -0
  53. package/dist/binding-routing-BYWsTgH4.js +113 -0
  54. package/dist/binding-targets-CDxkaXRY.js +121 -0
  55. package/dist/bot-BMJcaPAi.js +7894 -0
  56. package/dist/bot-deps-CNg_Zt2P.js +2 -0
  57. package/dist/bot-deps-FZotnMZO.js +747 -0
  58. package/dist/bot-message-context.runtime-C_OEKOE-.js +7 -0
  59. package/dist/bot-message-context.runtime.js +1 -1
  60. package/dist/bot-message-context.session.runtime-VbbwvU7y.js +12 -0
  61. package/dist/bot-message-context.session.runtime.js +1 -1
  62. package/dist/bot-native-commands.delivery.runtime-CuquGLAx.js +4 -0
  63. package/dist/bot-native-commands.delivery.runtime.js +1 -1
  64. package/dist/bot-native-commands.runtime-DtYCPjvW.js +13 -0
  65. package/dist/bot-native-commands.runtime.js +1 -1
  66. package/dist/bridge-server-B4pS54jd.js +113 -0
  67. package/dist/browser-cli-BHUdFJIS.js +230 -0
  68. package/dist/browser-cli-BWWH1Csp.js +2 -0
  69. package/dist/browser-cli-actions-input-1hfL1q3f.js +473 -0
  70. package/dist/browser-cli-actions-observe-Ctdz-Ocl.js +81 -0
  71. package/dist/browser-cli-debug-D4yOgAhy.js +137 -0
  72. package/dist/browser-cli-inspect-D6c28uLw.js +104 -0
  73. package/dist/browser-cli-manage-DoCDoOsO.js +443 -0
  74. package/dist/browser-cli-resize-Dgb5KdMO.js +26 -0
  75. package/dist/browser-cli-shared-C1LIiQyl.js +50 -0
  76. package/dist/browser-cli-state-CwIDB8-B.js +337 -0
  77. package/dist/browser-control-auth-COjZjE3L.js +2 -0
  78. package/dist/browser-profiles-D085C5gN.js +2 -0
  79. package/dist/browser-runtime-CKIOtwI9.js +384 -0
  80. package/dist/build-DHK6vRrC.js +257 -0
  81. package/dist/build-info.json +3 -3
  82. package/dist/bundled/boot-md/handler.js +2 -2
  83. package/dist/bundled/session-memory/handler.js +1 -1
  84. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  85. package/dist/capability-cli-DRrPaB5q.js +1782 -0
  86. package/dist/channel-B4huj9Kp.js +362 -0
  87. package/dist/channel-BLs4RYYL.js +1777 -0
  88. package/dist/channel-BnSrEvQt.js +238 -0
  89. package/dist/channel-BuEQnzVg.js +1556 -0
  90. package/dist/channel-CMIcwlip.js +955 -0
  91. package/dist/channel-CTTRs_4Q.js +376 -0
  92. package/dist/channel-Ceh4DhGf.js +808 -0
  93. package/dist/channel-CxzIiRo0.js +740 -0
  94. package/dist/channel-Czs81UUj.d.ts +427 -0
  95. package/dist/channel-DBe2Xwn9.js +1249 -0
  96. package/dist/channel-DOB2mltt.js +867 -0
  97. package/dist/channel-DU9qt3dX.js +481 -0
  98. package/dist/channel-DWCzQ-Po.js +562 -0
  99. package/dist/channel-Dha12xQd.js +2126 -0
  100. package/dist/channel-VJIcMa-M.js +508 -0
  101. package/dist/channel-WPOWimOu.js +1134 -0
  102. package/dist/channel-actions.runtime-bqHQHH3X.js +265 -0
  103. package/dist/channel-actions.runtime.js +1 -1
  104. package/dist/channel-core-m0EI5nTB.js +5 -0
  105. package/dist/channel-inbound-hFEolyVo.js +80 -0
  106. package/dist/channel-l10cAz1Q.js +1496 -0
  107. package/dist/channel-lifecycle-C4NrMjdz.d.ts +125 -0
  108. package/dist/channel-pairing-ndZVB-VX.d.ts +58 -0
  109. package/dist/channel-plugin-runtime-BMtJ1Wgj.js +998 -0
  110. package/dist/channel-runtime-TLiTFcI9.js +408 -0
  111. package/dist/channel-uLv7YV-J.js +653 -0
  112. package/dist/channel.runtime-3Aev2p4z.js +88 -0
  113. package/dist/channel.runtime-BBoj-2rR.js +2528 -0
  114. package/dist/channel.runtime-BHW11124.js +254 -0
  115. package/dist/channel.runtime-BO5IrBIY.js +652 -0
  116. package/dist/channel.runtime-C8L4S2Y3.js +109 -0
  117. package/dist/channel.runtime-D55LFe_S.js +21009 -0
  118. package/dist/channel.runtime-DUVRcCkd.js +1008 -0
  119. package/dist/channel.runtime-eAjrNDCs.js +733 -0
  120. package/dist/channel.runtime-ek9gTQao.js +4 -0
  121. package/dist/channel.setup-C4kFVZ9n.js +1098 -0
  122. package/dist/channel.setup-CG4h40nr.js +10 -0
  123. package/dist/channel.setup-t6GC0j9y.js +343 -0
  124. package/dist/chat-u7qZ4sNv.js +2666 -0
  125. package/dist/chrome-CcpklbxU.js +1503 -0
  126. package/dist/cli/run-main.js +5 -5
  127. package/dist/cli-DuN9_yOX.js +1341 -0
  128. package/dist/cli-compaction-_t3h1d1Y.js +347 -0
  129. package/dist/cli-metadata-CuQDanWu.js +22 -0
  130. package/dist/cli-runner-BICDg94b.js +2 -0
  131. package/dist/cli-runner-CeaLhAdU.js +540 -0
  132. package/dist/cli-runner.runtime-Ckyx1-nO.js +4 -0
  133. package/dist/cli-runner.runtime-ZsfkXp6T.js +3 -0
  134. package/dist/cli-runner.runtime.js +1 -1
  135. package/dist/cli-startup-metadata.json +8 -8
  136. package/dist/client-UnpX4vLL.js +650 -0
  137. package/dist/client-adapter-DXOFyLda.js +897 -0
  138. package/dist/client-factory-DvI4dWav.js +9 -0
  139. package/dist/command-auth--55vYozU.js +135 -0
  140. package/dist/command-handlers-luOY52Zj.js +1609 -0
  141. package/dist/command-registry-2ZPFOxQD.js +4 -0
  142. package/dist/command-registry-BnlVL4Z5.js +9 -0
  143. package/dist/command-registry-core-CY3_nsXj.js +110 -0
  144. package/dist/command-status.runtime-DlWcbk6f.js +90 -0
  145. package/dist/command-status.runtime.js +1 -1
  146. package/dist/commands-acp-1GcD7q5q.js +74 -0
  147. package/dist/commands-compact.runtime-DO9NBGsY.js +10 -0
  148. package/dist/commands-compact.runtime.js +1 -1
  149. package/dist/commands-handlers.runtime-CS9oLcTy.js +6154 -0
  150. package/dist/commands-handlers.runtime.js +1 -1
  151. package/dist/commands-status-B-VHaYH5.js +3 -0
  152. package/dist/commands-status-CD4lbvZe.js +16 -0
  153. package/dist/commands-status.runtime-B-VHaYH5.js +3 -0
  154. package/dist/commands-status.runtime.js +1 -1
  155. package/dist/commands-subagents-control.runtime-BW2wSGGB.js +2 -0
  156. package/dist/commands-subagents-control.runtime-DayCbQBi.js +3 -0
  157. package/dist/commands-subagents-control.runtime.js +1 -1
  158. package/dist/commands-system-prompt-Bu0-zdQV.js +162 -0
  159. package/dist/commands-system-prompt-DqzUrExG.js +2 -0
  160. package/dist/commands.runtime-Bi618hLG.js +176 -0
  161. package/dist/commands.runtime.js +1 -1
  162. package/dist/commitments/runtime.js +1 -1
  163. package/dist/compact-D6RF2ao-.js +480 -0
  164. package/dist/compact-DOHvJc9C.js +1141 -0
  165. package/dist/compact.runtime-BMV69fdx.js +12 -0
  166. package/dist/compact.runtime.js +1 -1
  167. package/dist/completion-cli-CKorRumh.js +315 -0
  168. package/dist/computer-use-QDwH-PSW.js +367 -0
  169. package/dist/config-D085C5gN.js +2 -0
  170. package/dist/config-kivtFwCd.js +373 -0
  171. package/dist/config-mutations-BEpZ3rYv.js +159 -0
  172. package/dist/context-engine-host-compat-BXoUGeB_.js +2 -0
  173. package/dist/context-engine-host-compat-CcCmD5o9.js +288 -0
  174. package/dist/context-engine-lifecycle-CwtbthA3.js +1274 -0
  175. package/dist/control-auth-wsG-pObJ.js +114 -0
  176. package/dist/control-service-DoSyDuPZ.js +145 -0
  177. package/dist/control-ui/apple-touch-icon.png +0 -0
  178. package/dist/control-ui/assets/agents-Dhs3H55s.js +1008 -0
  179. package/dist/control-ui/assets/ar-DmY3OKJ7.js +2 -0
  180. package/dist/control-ui/assets/channel-config-extras-DVKxDRoe.js +2 -0
  181. package/dist/control-ui/assets/channels-D0sTh9um.js +367 -0
  182. package/dist/control-ui/assets/cron-Bjs_HVS8.js +1013 -0
  183. package/dist/control-ui/assets/de-nNWCMyC9.js +2 -0
  184. package/dist/control-ui/assets/debug-DHEAFVCg.js +97 -0
  185. package/dist/control-ui/assets/es-BcdhLNdf.js +2 -0
  186. package/dist/control-ui/assets/fa-DbS2z7VZ.js +2 -0
  187. package/dist/control-ui/assets/fr-CBqvw0rY.js +2 -0
  188. package/dist/control-ui/assets/id-DXES9f6X.js +2 -0
  189. package/dist/control-ui/assets/index-BEC-6JL5.js +7387 -0
  190. package/dist/control-ui/assets/index-BimYwq-S.css +1 -0
  191. package/dist/control-ui/assets/instances-BwqBHtda.js +57 -0
  192. package/dist/control-ui/assets/it-DpT4ZVOU.js +2 -0
  193. package/dist/control-ui/assets/ja-JP-D8RXA_04.js +2 -0
  194. package/dist/control-ui/assets/ko-5en8VO8w.js +2 -0
  195. package/dist/control-ui/assets/logs-CmMuGVQg.js +74 -0
  196. package/dist/control-ui/assets/nl-Bb10QoRg.js +2 -0
  197. package/dist/control-ui/assets/nodes-CT5wsOuA.js +436 -0
  198. package/dist/control-ui/assets/pl-Y8UIOEIm.js +2 -0
  199. package/dist/control-ui/assets/preview-BBw3vauN.js +2 -0
  200. package/dist/control-ui/assets/pt-BR-DDsy5M68.js +2 -0
  201. package/dist/control-ui/assets/push-subscription-TTvs1whj.js +2 -0
  202. package/dist/control-ui/assets/sessions-_rCyOKmn.js +399 -0
  203. package/dist/control-ui/assets/skills-CIQu4JU-.js +314 -0
  204. package/dist/control-ui/assets/skills-shared-sMjN-BZW.js +11 -0
  205. package/dist/control-ui/assets/th-D_2DtFn6.js +2 -0
  206. package/dist/control-ui/assets/tr-DBsYZTmE.js +2 -0
  207. package/dist/control-ui/assets/uk-BUxHBc05.js +2 -0
  208. package/dist/control-ui/assets/vi-B67Eos5b.js +2 -0
  209. package/dist/control-ui/assets/zh-CN-CDrBrfT7.js +2 -0
  210. package/dist/control-ui/assets/zh-TW-CA4YEnf2.js +2 -0
  211. package/dist/control-ui/favicon-32.png +0 -0
  212. package/dist/control-ui/favicon-512.png +0 -0
  213. package/dist/control-ui/favicon.ico +0 -0
  214. package/dist/control-ui/favicon.svg +12 -0
  215. package/dist/control-ui/index.html +322 -0
  216. package/dist/control-ui/manifest.webmanifest +40 -0
  217. package/dist/control-ui/sw.js +2 -2
  218. package/dist/conversation-binding-runtime-vZQ351Yx.js +4 -0
  219. package/dist/conversation-runtime-DZztdc11.js +31 -0
  220. package/dist/core-CcQCE1PE.js +282 -0
  221. package/dist/core-api-Cn9nxEQY.js +5 -0
  222. package/dist/core-api-DJttT99e.js +2 -0
  223. package/dist/crestodian/crestodian.js +1 -1
  224. package/dist/crestodian/rescue-message.js +1 -1
  225. package/dist/crestodian-B77mGOnM.js +55 -0
  226. package/dist/daocore-tools-B2AoPxwu.js +11727 -0
  227. package/dist/delivery-DrO-hbmH.js +1002 -0
  228. package/dist/dialogue-xd9pIoHO.js +37 -0
  229. package/dist/dir-fetch-tool-CMJ9Pt6u.js +565 -0
  230. package/dist/dir-list-tool-BrTrO97I.js +100 -0
  231. package/dist/direct-dm-Dbxrg-M8.js +64 -0
  232. package/dist/directive-handling.fast-lane-Cm6q7myY.js +68 -0
  233. package/dist/directive-handling.impl-BW2_4S2v.js +818 -0
  234. package/dist/directive-handling.impl-DkMvyjSy.js +2 -0
  235. package/dist/directive-handling.model-selection-BBc-JgRD.js +122 -0
  236. package/dist/directive-handling.persist.runtime-ByZk594V.js +263 -0
  237. package/dist/directive-handling.persist.runtime.js +1 -1
  238. package/dist/dispatch-acp-transcript.runtime-t6_JeKwA.js +40 -0
  239. package/dist/dispatch-acp-transcript.runtime.js +1 -1
  240. package/dist/dispatch-acp.runtime-yf6pNdiB.js +18 -0
  241. package/dist/dispatch-acp.runtime.js +1 -1
  242. package/dist/dispatch-rpGfQmzk.js +1640 -0
  243. package/dist/doctor-Ce9osVgH.js +6 -0
  244. package/dist/doctor-Dl4rkbw8.js +2 -0
  245. package/dist/doctor-config-flow-IokiMPZL.js +1741 -0
  246. package/dist/doctor-core-checks-DPugZhrT.js +2 -0
  247. package/dist/doctor-core-checks-DTM0dPXV.js +573 -0
  248. package/dist/doctor-health-D9BF5XjZ.js +65 -0
  249. package/dist/doctor-health-contributions-CeAx5c5L.js +696 -0
  250. package/dist/doctor-lint-B3Ya8mmD.js +94 -0
  251. package/dist/doctor-state-integrity-B5aQjl2y.js +1231 -0
  252. package/dist/doctor-update-CGkyLrKv.js +58 -0
  253. package/dist/doctor-update-fix-CQ8qVhBX.js +107 -0
  254. package/dist/dynamic-tools-DZebai0O.js +486 -0
  255. package/dist/embedded-backend-BS79InDg.js +579 -0
  256. package/dist/embedded-gateway-stub.runtime-CsTs2-an.js +12 -0
  257. package/dist/embedded-gateway-stub.runtime.js +1 -1
  258. package/dist/exec-approvals-DSGilgX_.js +149 -0
  259. package/dist/extensionAPI.js +1 -1
  260. package/dist/extensions/active-memory/index.js +1 -1
  261. package/dist/extensions/admin-http-rpc/index.js +1 -1
  262. package/dist/extensions/anthropic/doctor-contract-api.d.ts +1 -1
  263. package/dist/extensions/browser/browser-bridge.js +1 -1
  264. package/dist/extensions/browser/browser-config.js +4 -4
  265. package/dist/extensions/browser/browser-control-auth.js +2 -2
  266. package/dist/extensions/browser/browser-doctor.js +2 -2
  267. package/dist/extensions/browser/browser-maintenance.js +1 -1
  268. package/dist/extensions/browser/browser-profiles.js +2 -2
  269. package/dist/extensions/browser/browser-runtime-api.js +11 -11
  270. package/dist/extensions/browser/cli-metadata.js +1 -1
  271. package/dist/extensions/browser/index.js +1 -1
  272. package/dist/extensions/browser/plugin-registration.js +1 -1
  273. package/dist/extensions/browser/register.runtime.js +4 -4
  274. package/dist/extensions/browser/runtime-api.js +13 -13
  275. package/dist/extensions/browser/test-support.d.ts +1 -1
  276. package/dist/extensions/canvas/index.js +1 -1
  277. package/dist/extensions/clickclack/api.js +2 -2
  278. package/dist/extensions/clickclack/channel-plugin-api.js +1 -1
  279. package/dist/extensions/clickclack/runtime-api.js +2 -2
  280. package/dist/extensions/device-pair/api.js +1 -1
  281. package/dist/extensions/device-pair/pair-command-approve.js +1 -1
  282. package/dist/extensions/file-transfer/index.js +4 -4
  283. package/dist/extensions/google/doctor-contract-api.d.ts +1 -1
  284. package/dist/extensions/image-generation-core/api.d.ts +1 -1
  285. package/dist/extensions/imessage/api.js +2 -2
  286. package/dist/extensions/imessage/channel-plugin-api.js +1 -1
  287. package/dist/extensions/imessage/message-tool-api.d.ts +1 -1
  288. package/dist/extensions/imessage/runtime-api.d.ts +1 -1
  289. package/dist/extensions/imessage/runtime-api.js +3 -3
  290. package/dist/extensions/irc/api.js +2 -2
  291. package/dist/extensions/irc/channel-plugin-api.js +1 -1
  292. package/dist/extensions/llm-task/index.js +1 -1
  293. package/dist/extensions/mattermost/api.js +1 -1
  294. package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
  295. package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
  296. package/dist/extensions/mattermost/policy-api.js +1 -1
  297. package/dist/extensions/mattermost/runtime-api.d.ts +7 -7
  298. package/dist/extensions/mattermost/runtime-api.js +2 -2
  299. package/dist/extensions/mattermost/slash-route-api.js +1 -1
  300. package/dist/extensions/memory-core/cli-metadata.js +1 -1
  301. package/dist/extensions/migrate-claude/apply.js +1 -1
  302. package/dist/extensions/migrate-claude/index.js +1 -1
  303. package/dist/extensions/migrate-claude/plan.js +1 -1
  304. package/dist/extensions/migrate-claude/provider.js +1 -1
  305. package/dist/extensions/migrate-claude/targets.js +1 -1
  306. package/dist/extensions/migrate-hermes/apply.js +1 -1
  307. package/dist/extensions/migrate-hermes/index.js +1 -1
  308. package/dist/extensions/migrate-hermes/model.js +1 -1
  309. package/dist/extensions/migrate-hermes/plan.js +1 -1
  310. package/dist/extensions/migrate-hermes/provider.js +1 -1
  311. package/dist/extensions/migrate-hermes/secrets.js +1 -1
  312. package/dist/extensions/migrate-hermes/targets.js +1 -1
  313. package/dist/extensions/policy/api.js +1 -1
  314. package/dist/extensions/policy/index.js +2 -2
  315. package/dist/extensions/signal/api.d.ts +1 -1
  316. package/dist/extensions/signal/api.js +6 -6
  317. package/dist/extensions/signal/channel-plugin-api.js +1 -1
  318. package/dist/extensions/signal/reaction-runtime-api.js +1 -1
  319. package/dist/extensions/signal/runtime-api.d.ts +2 -2
  320. package/dist/extensions/signal/runtime-api.js +7 -7
  321. package/dist/extensions/skill-workshop/api.js +1 -1
  322. package/dist/extensions/skill-workshop/index.js +2 -2
  323. package/dist/extensions/telegram/account-inspect-api.js +1 -1
  324. package/dist/extensions/telegram/api.d.ts +1 -1
  325. package/dist/extensions/telegram/api.js +11 -11
  326. package/dist/extensions/telegram/channel-plugin-api.js +2 -2
  327. package/dist/extensions/telegram/contract-api.js +3 -3
  328. package/dist/extensions/telegram/runtime-api.js +7 -7
  329. package/dist/extensions/telegram/security-audit-contract-api.js +1 -1
  330. package/dist/extensions/telegram/setup-plugin-api.js +1 -1
  331. package/dist/extensions/telegram/test-api.js +2 -2
  332. package/dist/extensions/video-generation-core/api.d.ts +1 -1
  333. package/dist/extensions/webhooks/api.js +1 -1
  334. package/dist/extensions/webhooks/index.js +1 -1
  335. package/dist/extensions/webhooks/runtime-api.d.ts +2 -2
  336. package/dist/extensions/xai/index.js +4 -4
  337. package/dist/extensions/xai/realtime-transcription-provider.js +1 -1
  338. package/dist/extensions/xai/speech-provider.js +1 -1
  339. package/dist/extensions/xai/test-api.js +1 -1
  340. package/dist/extensions/xai/tts.js +1 -1
  341. package/dist/extensions/xai/web-search.js +1 -1
  342. package/dist/extensions/xai/xai-oauth.js +1 -1
  343. package/dist/file-fetch-tool-QFQ7QZQ9.js +124 -0
  344. package/dist/file-write-tool-znIJ5MOE.js +127 -0
  345. package/dist/format-B3nq4sfa.js +1145 -0
  346. package/dist/gateway-cli-D5nQafQi.js +435 -0
  347. package/dist/gateway-method-runtime-BXmOAMxN.js +21 -0
  348. package/dist/get-reply-DZK53szF.js +4689 -0
  349. package/dist/get-reply-from-config.runtime-Kx4GwLAA.js +2 -0
  350. package/dist/get-reply-from-config.runtime.js +1 -1
  351. package/dist/graph-users-CNpoBMLI.js +1419 -0
  352. package/dist/group-access-B-lpiIoP.js +112 -0
  353. package/dist/handle-action.guild-admin-D7AInszH.js +288 -0
  354. package/dist/harness-BPTKe2TG.js +61 -0
  355. package/dist/health-BkXVkm2H.js +4 -0
  356. package/dist/heartbeat-runner-Dbddl21A.js +5 -0
  357. package/dist/heartbeat-runner.runtime-CDmb7D-Q.js +4 -0
  358. package/dist/heartbeat-runner.runtime.js +1 -1
  359. package/dist/hook-runtime-Cms52qXe.d.ts +107 -0
  360. package/dist/hooks-90WH7Tva.js +534 -0
  361. package/dist/inbound-direct-dm-runtime-bXneq4t0.js +2 -0
  362. package/dist/inbound-reply-dispatch-BVzOSvZX.js +148 -0
  363. package/dist/index.d.ts +1 -1
  364. package/dist/index.js +1 -1
  365. package/dist/init-DWgLcXq7.js +59 -0
  366. package/dist/inline-buttons-DtcEDZIV.js +40 -0
  367. package/dist/internal-events-D3SdlwzM.js +90 -0
  368. package/dist/isolated-agent-B9qCvLC4.js +1118 -0
  369. package/dist/isolated-agent-DaBWyrzI.js +2 -0
  370. package/dist/lifecycle-CfcTMzLT.js +571 -0
  371. package/dist/list.probe-aXBUfusA.js +449 -0
  372. package/dist/list.status-command-xrFMny0R.js +789 -0
  373. package/dist/llm-slug-generator-D5FE5osT.js +78 -0
  374. package/dist/llm-slug-generator.js +1 -1
  375. package/dist/local-dispatch.runtime-0dOK_rcW.js +9 -0
  376. package/dist/local-dispatch.runtime.js +1 -1
  377. package/dist/manager-CuzV3XAs.d.ts +205 -0
  378. package/dist/manager.runtime-pUdntZ2i.js +2714 -0
  379. package/dist/manager.runtime.js +1 -1
  380. package/dist/markdown-to-line-Cv0Gm132.js +811 -0
  381. package/dist/mcp-http-CaliRokB.js +555 -0
  382. package/dist/mcp-http-Dgcmuypw.js +2 -0
  383. package/dist/media-understanding-provider-Cu7iRaWL.js +339 -0
  384. package/dist/message-actions-BBiWyHuJ.js +145 -0
  385. package/dist/message-handler-VnxCCjy7.js +384 -0
  386. package/dist/message-handler-dNRhdkX3.js +1715 -0
  387. package/dist/message-handler.preflight-CREgYCNj.js +1125 -0
  388. package/dist/message-handler.process-DN93vvas.js +1484 -0
  389. package/dist/model-Bp-W7fVB.js +74 -0
  390. package/dist/model-selection-CXTwfi0m.js +272 -0
  391. package/dist/models-BF1vdgHr.js +2 -0
  392. package/dist/models-DvbokHz4.js +104 -0
  393. package/dist/models-cli-B_zT7frv.js +256 -0
  394. package/dist/monitor-BoW4qfGV.js +834 -0
  395. package/dist/monitor-Bs8KSKu7.js +60 -0
  396. package/dist/monitor-DHgHadUx.js +1370 -0
  397. package/dist/monitor-DX7Ya0rb.js +715 -0
  398. package/dist/monitor-DlzBuqhN.js +2788 -0
  399. package/dist/monitor-DnzcdtYh.js +1657 -0
  400. package/dist/monitor-DwwFCaSy.js +4377 -0
  401. package/dist/monitor-auth-BRF9yj8s.js +179 -0
  402. package/dist/monitor-m5zwJU51.js +2 -0
  403. package/dist/monitor-polling.runtime-DXMM7v9c.js +883 -0
  404. package/dist/monitor-polling.runtime.js +1 -1
  405. package/dist/monitor-webhook.runtime-vNDAo7Yq.js +387 -0
  406. package/dist/monitor-webhook.runtime.js +1 -1
  407. package/dist/monitor.account-DT1JC2fm.js +5233 -0
  408. package/dist/monitor.runtime-BUw4UbJN.js +2 -0
  409. package/dist/monitor.runtime.js +1 -1
  410. package/dist/monitor.webhook-IBx7ZFi4.js +180 -0
  411. package/dist/node-cli-sessions-BJW0oB3s.js +1228 -0
  412. package/dist/openai-http-BX-DFq23.js +824 -0
  413. package/dist/openresponses-http-BN6ztKxO.js +1173 -0
  414. package/dist/operations-DmaD-gxv.js +805 -0
  415. package/dist/outbound-adapter-v9Q4K2Bl.js +543 -0
  416. package/dist/outbound-session-route-BxhErAps.js +45 -0
  417. package/dist/outbound.runtime-ClUOK-Ir.js +2 -0
  418. package/dist/outbound.runtime.js +1 -1
  419. package/dist/pairing-challenge-EwSQYSud.d.ts +87 -0
  420. package/dist/pi-embedded-CG0u988w.js +4 -0
  421. package/dist/pi-embedded-D7UoOQFj.js +3796 -0
  422. package/dist/pi-embedded.runtime-CKNVJdm9.js +4 -0
  423. package/dist/pi-embedded.runtime.js +1 -1
  424. package/dist/pi-tools-DP7eGHq-.js +2413 -0
  425. package/dist/plan-BD5JNOvV.js +81 -0
  426. package/dist/plan-BSDlELnX.js +112 -0
  427. package/dist/plugin-4bygXnMD.js +12396 -0
  428. package/dist/plugin-app-cache-key-BfaJYLXl.js +46 -0
  429. package/dist/plugin-enabled-44kWBMek.js +233 -0
  430. package/dist/plugin-registration-DoD5ARyg.js +88 -0
  431. package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
  432. package/dist/plugin-sdk/acp-runtime-backend.js +1 -1
  433. package/dist/plugin-sdk/acp-runtime.js +2 -2
  434. package/dist/plugin-sdk/agent-harness-runtime.js +6 -6
  435. package/dist/plugin-sdk/agent-harness-task-runtime.js +1 -1
  436. package/dist/plugin-sdk/agent-harness.js +7 -7
  437. package/dist/plugin-sdk/agent-runtime.js +2 -2
  438. package/dist/plugin-sdk/channel-core.js +2 -2
  439. package/dist/plugin-sdk/channel-inbound.js +2 -2
  440. package/dist/plugin-sdk/channel-test-helpers.js +1 -1
  441. package/dist/plugin-sdk/command-auth.js +1 -1
  442. package/dist/plugin-sdk/command-status-runtime.js +1 -1
  443. package/dist/plugin-sdk/compat.js +1 -1
  444. package/dist/plugin-sdk/conversation-binding-runtime.js +2 -2
  445. package/dist/plugin-sdk/conversation-runtime.js +3 -3
  446. package/dist/plugin-sdk/core.js +2 -2
  447. package/dist/plugin-sdk/direct-dm.js +1 -1
  448. package/dist/plugin-sdk/gateway-method-runtime.js +1 -1
  449. package/dist/plugin-sdk/health.js +2 -2
  450. package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
  451. package/dist/plugin-sdk/index.js +1 -1
  452. package/dist/plugin-sdk/mattermost.js +1 -1
  453. package/dist/plugin-sdk/plugin-test-contracts.js +2 -2
  454. package/dist/plugin-sdk/provider-test-contracts.js +4 -4
  455. package/dist/plugin-sdk/reply-runtime.js +4 -4
  456. package/dist/plugin-sdk/scripts/lib/plugin-sdk-doc-metadata.d.ts +107 -0
  457. package/dist/plugin-sdk/src/commands/doctor.types.d.ts +1 -0
  458. package/dist/plugin-sdk/src/compat/legacy-names.d.ts +1 -1
  459. package/dist/plugin-sdk/src/plugins/manifest.d.ts +1 -1
  460. package/dist/plugin-sdk/testing.js +2 -2
  461. package/dist/plugin-sdk/zalouser.js +1 -1
  462. package/dist/plugin-service-CJqwjPRa.js +1229 -0
  463. package/dist/plugins/runtime/index.js +4 -4
  464. package/dist/policy-C2YDmnm2.js +138 -0
  465. package/dist/policy-CYBwtJmM.js +680 -0
  466. package/dist/prepare.runtime-B9SQyzSp.js +732 -0
  467. package/dist/prepare.runtime.js +1 -1
  468. package/dist/preview-warnings-DkMoGKdo.js +392 -0
  469. package/dist/probe-BYucGf4s.js +682 -0
  470. package/dist/probe-D8YoJ89r.js +2204 -0
  471. package/dist/probe-DKinNcah.js +47 -0
  472. package/dist/probe-DSYRrw81.js +2 -0
  473. package/dist/program-MtNU1_sG.js +131 -0
  474. package/dist/provider-26ZZeAkw.js +32 -0
  475. package/dist/provider-BtNK1WFZ.js +8735 -0
  476. package/dist/provider-CfJzlnOm.js +32 -0
  477. package/dist/provider-Dl-E4_a8.js +152 -0
  478. package/dist/provider-dispatcher-CAaa54DQ.js +22 -0
  479. package/dist/provider-dispatcher.runtime.js +1 -1
  480. package/dist/provider-session.runtime-DDMGL25I.js +9 -0
  481. package/dist/provider-session.runtime.js +1 -1
  482. package/dist/provider.runtime-CUdlREry.js +2 -0
  483. package/dist/provider.runtime.js +1 -1
  484. package/dist/public-surface-loader-iYUvHxzC.js +114 -0
  485. package/dist/pw-ai-DQjpZTSa.js +3029 -0
  486. package/dist/pw-role-snapshot-DgavoGdC.js +333 -0
  487. package/dist/reaction-level-uiCaLj0m.js +19 -0
  488. package/dist/reaction-runtime-api-ErmZKqXv.js +116 -0
  489. package/dist/realtime-transcription-provider-tLRMgcYk.js +205 -0
  490. package/dist/register-DxldPhbz.js +2178 -0
  491. package/dist/register.agent-B9171wFk.js +156 -0
  492. package/dist/register.crestodian-plvra03q.js +24 -0
  493. package/dist/register.maintenance-BLH-PhXR.js +105 -0
  494. package/dist/register.runtime-CnuNQn65.js +54 -0
  495. package/dist/register.subclis-C9TqTF1g.js +3 -0
  496. package/dist/register.subclis-core-B4RLAWNE.js +273 -0
  497. package/dist/register.subclis-zvycA0fS.js +31 -0
  498. package/dist/repair-sequencing-3Q95ftKn.js +640 -0
  499. package/dist/reply-delivery-BYtyofYM.js +196 -0
  500. package/dist/reply-runtime-P6EiRGYz.js +11 -0
  501. package/dist/reply.runtime-Kx4GwLAA.js +2 -0
  502. package/dist/reply.runtime.js +1 -1
  503. package/dist/request-B8_J1Hk5.js +54 -0
  504. package/dist/resolve-allowlist-BHhr7pGG.js +220 -0
  505. package/dist/result-fallback-classifier-v1BgnJLN.js +79 -0
  506. package/dist/route-Dl0ZJvrW.js +469 -0
  507. package/dist/route-resolution-mVRyzqn_.js +274 -0
  508. package/dist/routes-B8uiTXHO.js +3602 -0
  509. package/dist/routes-Bjw1nWyB.js +2 -0
  510. package/dist/run-attempt-DKRsY7Xs.js +7704 -0
  511. package/dist/run-command-Bs2y31Ew.js +2 -0
  512. package/dist/run-command-CBDF_cGB.js +23 -0
  513. package/dist/run-embedded.runtime-2GWQN_Qf.js +4 -0
  514. package/dist/run-embedded.runtime.js +1 -1
  515. package/dist/run-execution-cli.runtime-BEXMdwL2.js +4 -0
  516. package/dist/run-execution-cli.runtime.js +1 -1
  517. package/dist/run-executor.runtime.js +1 -1
  518. package/dist/run-rMTtvEMF.js +1163 -0
  519. package/dist/run-subagent-registry.runtime-CBmgh09W.js +2 -0
  520. package/dist/run-subagent-registry.runtime.js +1 -1
  521. package/dist/runtime-C3k-ZByi.d.ts +17 -0
  522. package/dist/runtime-DFBt4ZZw.js +1287 -0
  523. package/dist/runtime-DQV1yYF5.js +6179 -0
  524. package/dist/runtime-api-B6S-7TVS.js +3 -0
  525. package/dist/runtime-api-BLV9PO47.js +24 -0
  526. package/dist/runtime-api-BX1AvShq.js +17 -0
  527. package/dist/runtime-api-BnN22IWf.js +13 -0
  528. package/dist/runtime-api-BsmZgGnI.js +21 -0
  529. package/dist/runtime-api-CJ6x4Uuu.js +13 -0
  530. package/dist/runtime-api-DXCKXAYu.js +4 -0
  531. package/dist/runtime-api.actions-C9Jtoruo.js +3 -0
  532. package/dist/runtime-api.actions-CzDO06T7.d.ts +23 -0
  533. package/dist/runtime-api.monitor-slWfxEgT.js +6 -0
  534. package/dist/runtime-api.send-C_MjuzGA.d.ts +38 -0
  535. package/dist/runtime-api.send-D_auPJG_.js +4 -0
  536. package/dist/runtime-api.threads-BWzc1vrN.js +2 -0
  537. package/dist/runtime-channel-BOnbxldg.js +2 -0
  538. package/dist/runtime-channel-Dh45Bl_Q.js +150 -0
  539. package/dist/runtime-doctor-_yVIDUi3.d.ts +48 -0
  540. package/dist/runtime-embedded-pi.runtime-BVjCGIqB.js +2 -0
  541. package/dist/runtime-embedded-pi.runtime.js +1 -1
  542. package/dist/runtime-hYOWxRKE.js +438 -0
  543. package/dist/sanitize-outbound-CP-twYgG.js +127 -0
  544. package/dist/sdk-setup-tools-Cfh-ATXD.js +8 -0
  545. package/dist/secrets-DcQ7WBB-.js +113 -0
  546. package/dist/security-audit-CwMh7ULQ.js +118 -0
  547. package/dist/security-audit-yRC5cfp1.js +122 -0
  548. package/dist/security-audit.runtime-COitYvaV.js +2 -0
  549. package/dist/security-audit.runtime.js +1 -1
  550. package/dist/selection-C_swgArS.js +3 -0
  551. package/dist/selection-Cud_xC6-.js +16157 -0
  552. package/dist/send-BXTj6QIe.js +143 -0
  553. package/dist/send-Be-rQ3Py.js +1631 -0
  554. package/dist/send-CTDEXMPp.d.ts +231 -0
  555. package/dist/send-DaFuA5cD.d.ts +105 -0
  556. package/dist/send-DrSo2pTm.js +192 -0
  557. package/dist/send-un_jKNYG.js +2 -0
  558. package/dist/send.components-C0ugXCvj.js +500 -0
  559. package/dist/send.components-CaHcQCve.js +2 -0
  560. package/dist/send.runtime-CcGjdPIe.js +2 -0
  561. package/dist/send.runtime.js +1 -1
  562. package/dist/send.types-DU1uiiR9.d.ts +160 -0
  563. package/dist/server-Belw8J0P.js +24 -0
  564. package/dist/server-CbbbWl0g.js +73 -0
  565. package/dist/server-close.runtime.js +1 -1
  566. package/dist/server-context-D5PPz4pG.js +955 -0
  567. package/dist/server-context-DfiZrO39.js +2 -0
  568. package/dist/server-cron-B4uqojsc.js +2989 -0
  569. package/dist/server-cron-D5ofhC2R.js +2 -0
  570. package/dist/server-methods-BtrFcSCY.js +16499 -0
  571. package/dist/server-node-events-B7f6W47S.js +596 -0
  572. package/dist/server-plugin-bootstrap-CldF7ied.js +70 -0
  573. package/dist/server-plugins-BkRL48_Y.js +432 -0
  574. package/dist/server-reload-handlers-CmD463eg.js +714 -0
  575. package/dist/server-restart-sentinel-1-GltJOW.js +2 -0
  576. package/dist/server-restart-sentinel-BAc6ad7u.js +747 -0
  577. package/dist/server-runtime-services-DdDWPwwJ.js +2 -0
  578. package/dist/server-runtime-services-q4vtzdgR.js +267 -0
  579. package/dist/server-startup-plugins-RDIvIW1b.js +113 -0
  580. package/dist/server-startup-post-attach-B-Bcz1b8.js +716 -0
  581. package/dist/server-ws-runtime-ClfNa1gj.js +349 -0
  582. package/dist/server.impl-5A5eWz1g.js +2587 -0
  583. package/dist/service-BIi_LAz_.js +1446 -0
  584. package/dist/session-binding-DxgaaGZ8.js +219 -0
  585. package/dist/session-binding-SoSof-ir.js +2 -0
  586. package/dist/session-kill-http-CpA7WXXP.js +121 -0
  587. package/dist/session-reset-service-MBceWYbr.js +625 -0
  588. package/dist/session-route-SMerc1ZF.js +93 -0
  589. package/dist/session-status.runtime-C1MOnm-1.js +2 -0
  590. package/dist/session-status.runtime.js +1 -1
  591. package/dist/session-subagent-reactivation.runtime-Cca41-p8.js +2 -0
  592. package/dist/session-subagent-reactivation.runtime.js +1 -1
  593. package/dist/session-tab-registry-BL8A9tMR.js +521 -0
  594. package/dist/sessions-history-http-Cb21uPHU.js +430 -0
  595. package/dist/sessions.runtime-ClHkmNrd.js +2 -0
  596. package/dist/sessions.runtime.js +1 -1
  597. package/dist/setup-api-CwKuO7ZG.js +29 -0
  598. package/dist/setup-core-C8_XbMIV.js +174 -0
  599. package/dist/setup-surface-B3m7rAoM.js +405 -0
  600. package/dist/setup-surface-BstaBVou.js +320 -0
  601. package/dist/setup-surface-C5L8UmIu.js +221 -0
  602. package/dist/setup-surface-DwijXcOh.js +288 -0
  603. package/dist/shared-DemthgnG.js +121 -0
  604. package/dist/shared-client-CLvetNfK.js +2 -0
  605. package/dist/shared-client-CR88Qth4.js +629 -0
  606. package/dist/side-question-BKRlgFVG.js +683 -0
  607. package/dist/skill-tool-dispatch.runtime-Bsz4SNiK.js +143 -0
  608. package/dist/skill-tool-dispatch.runtime.js +1 -1
  609. package/dist/slash-state-Cbb2tkH9.js +2166 -0
  610. package/dist/speech-provider-hqhi426N.js +184 -0
  611. package/dist/src-wxYdKry6.js +4256 -0
  612. package/dist/startup-context-CidK9XK8.js +313 -0
  613. package/dist/status-subagents.runtime-DgYNfrbK.js +18 -0
  614. package/dist/status-subagents.runtime.js +1 -1
  615. package/dist/status-text-w43pGoDJ.js +296 -0
  616. package/dist/sticker-cache-BdIkkDGC.js +206 -0
  617. package/dist/sticker-vision.runtime-bmccn4BW.js +17 -0
  618. package/dist/sticker-vision.runtime.js +1 -1
  619. package/dist/subagent-announce-Cig5R7bU.js +354 -0
  620. package/dist/subagent-announce-delivery-DElem-jW.js +958 -0
  621. package/dist/subagent-control-Dx1qbt2M.js +508 -0
  622. package/dist/subagent-hooks-03ne_B1P.js +2 -0
  623. package/dist/subagent-hooks-BW4tdl1N.js +116 -0
  624. package/dist/subagent-hooks-BdADgqQH.js +2 -0
  625. package/dist/subagent-hooks-D5ZUfS0C.js +146 -0
  626. package/dist/subagent-hooks-DKEWsBSa.js +230 -0
  627. package/dist/subagent-hooks-api-BNJpIv9Q.js +23 -0
  628. package/dist/subagent-hooks-api-BXE-a9iQ.js +22 -0
  629. package/dist/subagent-hooks-api-w7wOpXSR.js +23 -0
  630. package/dist/subagent-hooks-kf263oYw.js +2 -0
  631. package/dist/subagent-orphan-recovery-TGLIuI1K.js +352 -0
  632. package/dist/subagent-registry-Bai39rEv.js +3 -0
  633. package/dist/subagent-registry-vgjMT_I1.js +2351 -0
  634. package/dist/subagent-registry.runtime.js +1 -1
  635. package/dist/subagent-session-cleanup-PEEQtuLS.js +525 -0
  636. package/dist/subagent-spawn-2TTDQg5Y.js +1164 -0
  637. package/dist/target-id-BgSzF2Lk.js +107 -0
  638. package/dist/targets-Bd9-WGJt.js +19 -0
  639. package/dist/targets-DxKwMzNB.js +44 -0
  640. package/dist/targets-DzdYRUSR.js +19 -0
  641. package/dist/task-registry-control.runtime.d.ts +1 -1
  642. package/dist/task-registry-control.runtime.js +1 -1
  643. package/dist/telegram/token.js +1 -1
  644. package/dist/test-fixtures-HY6a4nTW.d.ts +26 -0
  645. package/dist/testing-B6jLjq4r.js +267 -0
  646. package/dist/thread-bindings-BumrOVO8.js +571 -0
  647. package/dist/thread-bindings-C4yc8CZT.js +228 -0
  648. package/dist/thread-bindings-Dkeit03N.js +8 -0
  649. package/dist/thread-bindings-FVOv7g2T.js +232 -0
  650. package/dist/thread-bindings.discord-api-D83vw86t.js +187 -0
  651. package/dist/thread-bindings.manager-DEqfX4rc.js +2 -0
  652. package/dist/thread-bindings.manager-LOMmQ1pN.js +536 -0
  653. package/dist/thread-lifecycle-CGFgul5c.js +1614 -0
  654. package/dist/token-CoB7XxKt.js +134 -0
  655. package/dist/tool-CIfIAkxV.js +139 -0
  656. package/dist/tool-actions.runtime-BrVxKuRd.js +534 -0
  657. package/dist/tool-actions.runtime.js +1 -1
  658. package/dist/tool-resolution-BWdOXsX0.js +149 -0
  659. package/dist/tools-effective-inventory-CW8_FJBN.js +204 -0
  660. package/dist/tools-invoke-http-CYJCHpxL.js +67 -0
  661. package/dist/tools-invoke-shared-SnaEXvuz.js +200 -0
  662. package/dist/tts-5p3qPz-P.js +66 -0
  663. package/dist/tui-BYTSFA_c.js +4709 -0
  664. package/dist/tui-LOGspKbe.js +2 -0
  665. package/dist/tui-backend-C8nbqNLo.js +256 -0
  666. package/dist/tui-cli-C91LywYY.js +37 -0
  667. package/dist/typed-cases-BYRVKA1F.d.ts +68 -0
  668. package/dist/update-cli-DZuYe1aX.js +3665 -0
  669. package/dist/update-global-ucSOAIga.js +606 -0
  670. package/dist/update-runner-2pS-KlSn.js +1798 -0
  671. package/dist/vision-tools-mJMJD3Yw.js +1409 -0
  672. package/dist/web-search-BZgc3DQT.js +62 -0
  673. package/dist/web-search-provider.runtime-BgoF9yna.js +328 -0
  674. package/dist/web-search-provider.runtime-D1lmfAbp.js +2 -0
  675. package/dist/web-search-provider.runtime.js +1 -1
  676. package/dist/webhook-targets-DqetRJVn.d.ts +99 -0
  677. package/dist/xai-oauth-B-LPhpsk.js +479 -0
  678. package/dist/xai-user-agent-B0F4Hyt5.js +32 -0
  679. package/npm-shrinkwrap.json +2 -2
  680. package/package.json +1 -1
  681. package/dist/abort-BtS5AfJG.js +0 -277
  682. package/dist/abort.runtime-D211494J.js +0 -2
  683. package/dist/account-inspect-BqAxH1Q_.js +0 -173
  684. package/dist/accounts-2VYKksau.js +0 -107
  685. package/dist/accounts-B6aVCtty.js +0 -119
  686. package/dist/accounts-CE6mvWMC.js +0 -2
  687. package/dist/accounts-eprn8x0M.js +0 -107
  688. package/dist/acp-runtime-C_0NA0CS.js +0 -26
  689. package/dist/acp-spawn-CTmucfK5.js +0 -2
  690. package/dist/acp-spawn-DcTgPZQB.js +0 -1275
  691. package/dist/acp-stateful-target-driver-DVWNxIEX.js +0 -89
  692. package/dist/action-kill-C6NRFglx.js +0 -33
  693. package/dist/action-runtime-BaKOu7uV.js +0 -469
  694. package/dist/action-runtime-api-QC43ZgvC.js +0 -2
  695. package/dist/action-send-B790BH2g.js +0 -39
  696. package/dist/action-spawn-Dgf97JGp.js +0 -47
  697. package/dist/actions-DhY0Hqxd.js +0 -161
  698. package/dist/actions.runtime-BfdjoY4f.js +0 -5
  699. package/dist/agent-C1VC8waN.js +0 -3
  700. package/dist/agent-DuLat04d.js +0 -2
  701. package/dist/agent-command-BQ2JuYpP.js +0 -1367
  702. package/dist/agent-command-DQ1XgXqe.d.ts +0 -105
  703. package/dist/agent-components.runtime-BskyK1iq.js +0 -10
  704. package/dist/agent-harness-Bt_1zRJ1.d.ts +0 -146
  705. package/dist/agent-harness-runtime-l4d66klL.js +0 -180
  706. package/dist/agent-harness-task-runtime-D5vhG7mw.js +0 -140
  707. package/dist/agent-runner-execution-DKJ7YE9g.js +0 -1713
  708. package/dist/agent-runner-utils-BOJEvwHI.js +0 -266
  709. package/dist/agent-runner.runtime-BAC7XlZX.js +0 -3455
  710. package/dist/agent-runtime-D8J3kngS.js +0 -229
  711. package/dist/agent-via-gateway-BPZeOgET.js +0 -463
  712. package/dist/api-2J3KsQlI.js +0 -2
  713. package/dist/api-BNZFdrOx.js +0 -639
  714. package/dist/api-CQY8p5l4.js +0 -134
  715. package/dist/api-CdIYfiOh.js +0 -3
  716. package/dist/api-DaLfnqrr.js +0 -2
  717. package/dist/api-DzpDMEqm.js +0 -6
  718. package/dist/apply-DTkOJDSZ.js +0 -54
  719. package/dist/apply-DY6Ov6qF.js +0 -41
  720. package/dist/approval-handler.runtime-9W6kSKLn.js +0 -130
  721. package/dist/assistant-D338eQWk.js +0 -291
  722. package/dist/attachment-normalize-BaGndElX.js +0 -225
  723. package/dist/attempt-execution-aOkjnMht.js +0 -558
  724. package/dist/attempt-execution.runtime-lKPuGjsg.js +0 -3
  725. package/dist/attempt-execution.shared-lwEBnvQR.js +0 -38
  726. package/dist/attempt.prompt-helpers-BVDwNazv.js +0 -475
  727. package/dist/attempt.tool-run-context-DXgP_TxW.js +0 -2094
  728. package/dist/binding-routing-CA-u9MaB.js +0 -113
  729. package/dist/binding-targets-SGf9XyYl.js +0 -121
  730. package/dist/bot-C0uHsCiq.js +0 -7894
  731. package/dist/bot-deps-CfqgukPx.js +0 -747
  732. package/dist/bot-deps-D0dGR0Um.js +0 -2
  733. package/dist/bot-message-context.runtime-aqONyuCb.js +0 -7
  734. package/dist/bot-message-context.session.runtime-CYJpmbne.js +0 -12
  735. package/dist/bot-native-commands.delivery.runtime-DjCvDhXo.js +0 -4
  736. package/dist/bot-native-commands.runtime-CNDOgqnt.js +0 -13
  737. package/dist/bridge-server-DX39VTjh.js +0 -113
  738. package/dist/browser-cli-BM0neIBN.js +0 -2
  739. package/dist/browser-cli-TjkCzsOd.js +0 -230
  740. package/dist/browser-cli-actions-input-Crdngwmz.js +0 -473
  741. package/dist/browser-cli-actions-observe-CR0DTzDP.js +0 -81
  742. package/dist/browser-cli-debug-CC9OYHxx.js +0 -137
  743. package/dist/browser-cli-inspect-DVWu-CO3.js +0 -104
  744. package/dist/browser-cli-manage-BfSgA18U.js +0 -443
  745. package/dist/browser-cli-resize-ddNFsnFm.js +0 -26
  746. package/dist/browser-cli-shared-B_5TDXXY.js +0 -50
  747. package/dist/browser-cli-state-CnLWkvHn.js +0 -337
  748. package/dist/browser-control-auth-1gcUHgnp.js +0 -2
  749. package/dist/browser-profiles-BkIb0hYP.js +0 -2
  750. package/dist/browser-runtime-RQ9H-pQ2.js +0 -384
  751. package/dist/build-C3ote3YU.js +0 -257
  752. package/dist/capability-cli-D2fTtzuV.js +0 -1782
  753. package/dist/channel-BC3xWers.js +0 -808
  754. package/dist/channel-BJFPY0Kt.js +0 -376
  755. package/dist/channel-BMVs8cLm.js +0 -740
  756. package/dist/channel-BNmekEHv.js +0 -508
  757. package/dist/channel-BnPanYUC.js +0 -562
  758. package/dist/channel-BompXOlb.js +0 -1134
  759. package/dist/channel-BwdtLWWj.js +0 -1556
  760. package/dist/channel-CaugIi5d.js +0 -481
  761. package/dist/channel-D7LE0yXG.js +0 -653
  762. package/dist/channel-DBucF-mL.js +0 -1496
  763. package/dist/channel-DC98b13r.js +0 -238
  764. package/dist/channel-DGWSLAgs.js +0 -1249
  765. package/dist/channel-DHk6PKNy.js +0 -362
  766. package/dist/channel-Dqyy2G9y.js +0 -955
  767. package/dist/channel-Z-wTsii5.js +0 -1777
  768. package/dist/channel-_B9ZXRPx.js +0 -867
  769. package/dist/channel-actions.runtime-C3lWtJBL.js +0 -265
  770. package/dist/channel-cGJKLfJe.d.ts +0 -427
  771. package/dist/channel-core-B3Xqnnjw.js +0 -5
  772. package/dist/channel-inbound-BnUDIbdQ.js +0 -80
  773. package/dist/channel-lifecycle-BXdiTu_h.d.ts +0 -126
  774. package/dist/channel-pairing-qPwn6FAN.d.ts +0 -58
  775. package/dist/channel-plugin-runtime-CFKbI6Pu.js +0 -998
  776. package/dist/channel-runtime-BLFYOC-l.js +0 -408
  777. package/dist/channel-yBZ1hu-c.js +0 -2126
  778. package/dist/channel.runtime-BMBFwVOB.js +0 -1008
  779. package/dist/channel.runtime-BPaTa_4p.js +0 -4
  780. package/dist/channel.runtime-BiOmO6NR.js +0 -254
  781. package/dist/channel.runtime-BmwN1CYk.js +0 -652
  782. package/dist/channel.runtime-C5JA3DOQ.js +0 -21009
  783. package/dist/channel.runtime-CWmegcjl.js +0 -109
  784. package/dist/channel.runtime-DDs1y218.js +0 -733
  785. package/dist/channel.runtime-DJMJ7DxI.js +0 -88
  786. package/dist/channel.runtime-Dr7_P-K2.js +0 -2528
  787. package/dist/channel.setup-BRhsffda.js +0 -10
  788. package/dist/channel.setup-C74nA6R0.js +0 -343
  789. package/dist/channel.setup-RbyDP1dD.js +0 -1098
  790. package/dist/chat-CGdonziw.js +0 -2666
  791. package/dist/chrome-BbE0579R.js +0 -1503
  792. package/dist/cli-CJkC6ybf.js +0 -1341
  793. package/dist/cli-compaction-D7zwr6if.js +0 -347
  794. package/dist/cli-metadata-gL02qQsZ.js +0 -22
  795. package/dist/cli-runner-DTqOC0Ap.js +0 -540
  796. package/dist/cli-runner-DX7wbmT5.js +0 -2
  797. package/dist/cli-runner.runtime-CMFns61M.js +0 -4
  798. package/dist/cli-runner.runtime-DH0Kp9FZ.js +0 -3
  799. package/dist/client-B763Tol6.js +0 -650
  800. package/dist/client-adapter-WxKxH6x-.js +0 -897
  801. package/dist/client-factory-00sxHiJF.js +0 -9
  802. package/dist/command-auth-CXYQ5Z0j.js +0 -135
  803. package/dist/command-handlers-D1Ac0Dkj.js +0 -1609
  804. package/dist/command-registry-D2dsDDz5.js +0 -9
  805. package/dist/command-registry-Dih3NQG-.js +0 -4
  806. package/dist/command-registry-core-CjXOyB2J.js +0 -110
  807. package/dist/command-status.runtime-B0-uERwh.js +0 -90
  808. package/dist/commands-acp-pD2JpUSj.js +0 -74
  809. package/dist/commands-compact.runtime-V-TcIs65.js +0 -10
  810. package/dist/commands-handlers.runtime-5M-A0jiA.js +0 -6154
  811. package/dist/commands-status-Bm4dG6pI.js +0 -3
  812. package/dist/commands-status-qm4EnRyE.js +0 -16
  813. package/dist/commands-status.runtime-Bm4dG6pI.js +0 -3
  814. package/dist/commands-subagents-control.runtime-DI46smsH.js +0 -2
  815. package/dist/commands-subagents-control.runtime-rWDaFqzc.js +0 -3
  816. package/dist/commands-system-prompt-B4F4MOEY.js +0 -162
  817. package/dist/commands-system-prompt-jk5Mc_DP.js +0 -2
  818. package/dist/commands.runtime-Bc23O5Mi.js +0 -176
  819. package/dist/compact-CtN0DOvK.js +0 -480
  820. package/dist/compact-D1ChSGOh.js +0 -1141
  821. package/dist/compact.runtime-C7If8t90.js +0 -12
  822. package/dist/completion-cli-gXouR92c.js +0 -315
  823. package/dist/computer-use-CdO4BAyI.js +0 -367
  824. package/dist/config-BkIb0hYP.js +0 -2
  825. package/dist/config-dmYhst2s.js +0 -373
  826. package/dist/config-mutations-D2ETKy_j.js +0 -159
  827. package/dist/context-engine-host-compat-DgNqJwdY.js +0 -288
  828. package/dist/context-engine-host-compat-OWTQLkIP.js +0 -2
  829. package/dist/context-engine-lifecycle-CGVL8HdA.js +0 -1274
  830. package/dist/control-auth-BFMiW_62.js +0 -114
  831. package/dist/control-service-D7r7Quub.js +0 -145
  832. package/dist/conversation-binding-runtime-BW_4K8cX.js +0 -4
  833. package/dist/conversation-runtime-oIeuYAld.js +0 -31
  834. package/dist/core-Cqwgrdgs.js +0 -282
  835. package/dist/core-api-DI9CNhVz.js +0 -2
  836. package/dist/core-api-Dcj6myhZ.js +0 -5
  837. package/dist/crestodian-DVM5VVBT.js +0 -55
  838. package/dist/daocore-tools-bO6317PZ.js +0 -11727
  839. package/dist/delivery-BCvDWVt-.js +0 -1002
  840. package/dist/dialogue-D7jagbT_.js +0 -37
  841. package/dist/dir-fetch-tool-BT5EPw-5.js +0 -565
  842. package/dist/dir-list-tool-H_efDjDq.js +0 -100
  843. package/dist/direct-dm-D0B-QMik.js +0 -64
  844. package/dist/directive-handling.fast-lane-DsGCtBC-.js +0 -68
  845. package/dist/directive-handling.impl-C-1mgd9g.js +0 -2
  846. package/dist/directive-handling.impl-DumICYAp.js +0 -818
  847. package/dist/directive-handling.model-selection-BJZn2fo_.js +0 -122
  848. package/dist/directive-handling.persist.runtime-D62V2_9_.js +0 -263
  849. package/dist/dispatch-CnOOlfPn.js +0 -1640
  850. package/dist/dispatch-acp-transcript.runtime-DV_7Zl9P.js +0 -40
  851. package/dist/dispatch-acp.runtime-ATTViG-t.js +0 -18
  852. package/dist/doctor-8vhWy3Dw.js +0 -2
  853. package/dist/doctor-CKYTXvU7.js +0 -6
  854. package/dist/doctor-config-flow-B0Ilj0MM.js +0 -1741
  855. package/dist/doctor-core-checks-B0DeLp7M.js +0 -2
  856. package/dist/doctor-core-checks-NFFEe2qP.js +0 -573
  857. package/dist/doctor-health-BQDkMVRf.js +0 -65
  858. package/dist/doctor-health-contributions-BTtoe4Zy.js +0 -696
  859. package/dist/doctor-lint-CtjiT5S1.js +0 -94
  860. package/dist/doctor-state-integrity-C1p_aTX_.js +0 -1231
  861. package/dist/doctor-update-Dzr9Vt00.js +0 -58
  862. package/dist/doctor-update-fix-Dw80wTUs.js +0 -107
  863. package/dist/dynamic-tools-Cb1BxOUV.js +0 -486
  864. package/dist/embedded-backend-DIv3GabL.js +0 -579
  865. package/dist/embedded-gateway-stub.runtime-DqgU4q-g.js +0 -12
  866. package/dist/exec-approvals-ClOFMgg8.js +0 -149
  867. package/dist/file-fetch-tool-CIe7NhYV.js +0 -124
  868. package/dist/file-write-tool-DBpMRVuc.js +0 -127
  869. package/dist/format-DwlQcHW-.js +0 -1145
  870. package/dist/gateway-cli-B-RpSgut.js +0 -435
  871. package/dist/gateway-method-runtime-BblhHt-0.js +0 -21
  872. package/dist/get-reply-HRNSgWtJ.js +0 -4689
  873. package/dist/get-reply-from-config.runtime-D_IjyVEy.js +0 -2
  874. package/dist/graph-users-xOkVRyWa.js +0 -1419
  875. package/dist/group-access-5rOw40mA.js +0 -112
  876. package/dist/handle-action.guild-admin-3izRlfhG.js +0 -288
  877. package/dist/harness-DSATBx4q.js +0 -61
  878. package/dist/health-gXf5LPQE.js +0 -4
  879. package/dist/heartbeat-runner-BAl6rYJ4.js +0 -5
  880. package/dist/heartbeat-runner.runtime-BwR4hXGN.js +0 -4
  881. package/dist/hook-runtime-BBONf8H3.d.ts +0 -108
  882. package/dist/hooks-Ds30xkRl.js +0 -534
  883. package/dist/inbound-direct-dm-runtime-VLA3Sl_Y.js +0 -2
  884. package/dist/inbound-reply-dispatch-B1Yv-_Ol.js +0 -148
  885. package/dist/init-C94m6gc5.js +0 -59
  886. package/dist/inline-buttons-B48KLvRY.js +0 -40
  887. package/dist/internal-events-DH1wKI3W.js +0 -90
  888. package/dist/isolated-agent-BHtpDjQ3.js +0 -1118
  889. package/dist/isolated-agent-CQ8xLCdA.js +0 -2
  890. package/dist/lifecycle-J2_rGItq.js +0 -571
  891. package/dist/list.probe-CQkRrePt.js +0 -449
  892. package/dist/list.status-command-Dh4C_nmX.js +0 -789
  893. package/dist/llm-slug-generator-CuTyqyw9.js +0 -78
  894. package/dist/local-dispatch.runtime-DMFlGKN5.js +0 -9
  895. package/dist/manager-DWN3qo90.d.ts +0 -10
  896. package/dist/manager.core-BRd2_lqA.d.ts +0 -198
  897. package/dist/manager.runtime-ChEFeq5B.js +0 -2714
  898. package/dist/markdown-to-line-BXszL2cy.js +0 -811
  899. package/dist/mcp-http-BfLRPB10.js +0 -555
  900. package/dist/mcp-http-C4jMPkoA.js +0 -2
  901. package/dist/media-understanding-provider-By_IYDJy.js +0 -339
  902. package/dist/message-actions-CnGb9RhR.js +0 -145
  903. package/dist/message-handler-BczaNv3J.js +0 -384
  904. package/dist/message-handler-txIHUJJr.js +0 -1715
  905. package/dist/message-handler.preflight-DQ_XIRJD.js +0 -1125
  906. package/dist/message-handler.process-DW_BauDK.js +0 -1484
  907. package/dist/model-CzeDtlL2.js +0 -74
  908. package/dist/model-selection-DISTEWT3.js +0 -272
  909. package/dist/models-Cs632hpM.js +0 -104
  910. package/dist/models-DFdDefW_.js +0 -2
  911. package/dist/models-cli-CEJaAepl.js +0 -256
  912. package/dist/monitor-1sdwxltF.js +0 -2788
  913. package/dist/monitor-B3satZZM.js +0 -2
  914. package/dist/monitor-BjTf4-1k.js +0 -715
  915. package/dist/monitor-Blfd3oxm.js +0 -1370
  916. package/dist/monitor-CTBBctRZ.js +0 -60
  917. package/dist/monitor-DMs9Fc-I.js +0 -4377
  918. package/dist/monitor-Jaf6yIPY.js +0 -1657
  919. package/dist/monitor-QlSkTI6D.js +0 -834
  920. package/dist/monitor-auth-C1tksIdC.js +0 -179
  921. package/dist/monitor-polling.runtime-BfiQ9WKu.js +0 -883
  922. package/dist/monitor-webhook.runtime-DaN0Z6_6.js +0 -387
  923. package/dist/monitor.account-DXs-I96r.js +0 -5233
  924. package/dist/monitor.runtime-CfhDXAnn.js +0 -2
  925. package/dist/monitor.webhook-Dh2yCA0H.js +0 -180
  926. package/dist/node-cli-sessions-BRSHPLpR.js +0 -1228
  927. package/dist/openai-http-CJKcPRWW.js +0 -824
  928. package/dist/openresponses-http-BhyRvqJ0.js +0 -1173
  929. package/dist/operations-CL7dqxSs.js +0 -805
  930. package/dist/outbound-adapter-BzLFym-i.js +0 -543
  931. package/dist/outbound-session-route-do6mbRaF.js +0 -45
  932. package/dist/outbound.runtime-ClwB5soC.js +0 -2
  933. package/dist/pairing-store-Cfy_zHzi.d.ts +0 -87
  934. package/dist/pi-embedded-BtyxupRo.js +0 -3796
  935. package/dist/pi-embedded-DC6txKUX.js +0 -4
  936. package/dist/pi-embedded.runtime-CLGqbc8E.js +0 -4
  937. package/dist/pi-tools-BNtGWzuL.js +0 -2413
  938. package/dist/plan-BKvy4WrJ.js +0 -81
  939. package/dist/plan-DwVlQpE1.js +0 -112
  940. package/dist/plugin-CY0rEF7s.js +0 -12396
  941. package/dist/plugin-app-cache-key-DNUt0H7R.js +0 -46
  942. package/dist/plugin-enabled-Cyd8634I.js +0 -233
  943. package/dist/plugin-registration-B_-ymgPg.js +0 -88
  944. package/dist/plugin-service-Dxx-FdeS.js +0 -1229
  945. package/dist/policy-BXjjr3b_.js +0 -138
  946. package/dist/policy-cKo9Yeux.js +0 -680
  947. package/dist/prepare.runtime-DKbtJNij.js +0 -732
  948. package/dist/preview-warnings-B_dB0-nc.js +0 -392
  949. package/dist/probe-D02PTGyD.js +0 -47
  950. package/dist/probe-DywFeNCV.js +0 -682
  951. package/dist/probe-f3qP15_E.js +0 -2204
  952. package/dist/probe-sSNH7OtW.js +0 -2
  953. package/dist/program-CI-yGmHj.js +0 -131
  954. package/dist/provider-0MTK_A59.js +0 -32
  955. package/dist/provider-Bqz_XGo0.js +0 -8735
  956. package/dist/provider-DguV0rAM.js +0 -32
  957. package/dist/provider-Vf0kCR9H.js +0 -152
  958. package/dist/provider-dispatcher-DYgMXESe.js +0 -22
  959. package/dist/provider-session.runtime-DPLsI_az.js +0 -9
  960. package/dist/provider.runtime-Dqb234pz.js +0 -2
  961. package/dist/public-surface-loader-BFaumhij.js +0 -114
  962. package/dist/pw-ai-G5xV3oAx.js +0 -3029
  963. package/dist/pw-role-snapshot-Dx3HJBHP.js +0 -333
  964. package/dist/reaction-level-cwg9IPV-.js +0 -19
  965. package/dist/reaction-runtime-api-BO5tonA_.js +0 -116
  966. package/dist/realtime-transcription-provider-BPUt8lMk.js +0 -205
  967. package/dist/register-hPi-PJ7K.js +0 -2178
  968. package/dist/register.agent-C17wwmyB.js +0 -156
  969. package/dist/register.crestodian-BgN2eNeU.js +0 -24
  970. package/dist/register.maintenance-CZV43uUT.js +0 -105
  971. package/dist/register.runtime-B6KhmuJw.js +0 -54
  972. package/dist/register.subclis-By70wsLN.js +0 -31
  973. package/dist/register.subclis-D_XDgsMy.js +0 -3
  974. package/dist/register.subclis-core-CYi-wxpA.js +0 -273
  975. package/dist/repair-sequencing-ze6dXKp3.js +0 -640
  976. package/dist/reply-delivery-BRsL-nIn.js +0 -196
  977. package/dist/reply-runtime-DUv2dRp3.d.ts +0 -34
  978. package/dist/reply-runtime-hB7p7Uov.js +0 -11
  979. package/dist/reply.runtime-D_IjyVEy.js +0 -2
  980. package/dist/request-C6QBV_dA.js +0 -54
  981. package/dist/resolve-allowlist-zmvmVPzW.js +0 -220
  982. package/dist/result-fallback-classifier-hWTcOYyH.js +0 -79
  983. package/dist/route-BMCrq1SN.js +0 -469
  984. package/dist/route-resolution-nWgSniti.js +0 -274
  985. package/dist/routes-BXyfYxi-.js +0 -2
  986. package/dist/routes-CpMZFxzv.js +0 -3602
  987. package/dist/run-Bzp1cq1J.js +0 -1163
  988. package/dist/run-attempt-DMj1Q3oE.js +0 -7704
  989. package/dist/run-command-CbDBts53.js +0 -23
  990. package/dist/run-command-CrJ2mrht.js +0 -2
  991. package/dist/run-embedded.runtime-sD3O3k2K.js +0 -4
  992. package/dist/run-execution-cli.runtime-CG1zNse6.js +0 -4
  993. package/dist/run-subagent-registry.runtime-CGzIerQZ.js +0 -2
  994. package/dist/runtime-B0ZKPxxL.js +0 -6179
  995. package/dist/runtime-D21vC5Bd.d.ts +0 -17
  996. package/dist/runtime-Dh-KFKJv.js +0 -1287
  997. package/dist/runtime-api-9Xxm9K2E.js +0 -21
  998. package/dist/runtime-api-C2252PQ4.js +0 -4
  999. package/dist/runtime-api-Cl3W6JLB.js +0 -13
  1000. package/dist/runtime-api-CwyQGzrm.js +0 -24
  1001. package/dist/runtime-api-DQVZQ82e.js +0 -17
  1002. package/dist/runtime-api-Ksdts3J7.js +0 -13
  1003. package/dist/runtime-api-lHayJI0f.js +0 -3
  1004. package/dist/runtime-api.actions-CClxRuYx.d.ts +0 -23
  1005. package/dist/runtime-api.actions-CHH4JoFd.js +0 -3
  1006. package/dist/runtime-api.monitor-CuAnxOiA.js +0 -6
  1007. package/dist/runtime-api.send-C5Ndv4Sb.js +0 -4
  1008. package/dist/runtime-api.send-wXeDllRu.d.ts +0 -38
  1009. package/dist/runtime-api.threads-Car1xuWI.js +0 -2
  1010. package/dist/runtime-channel-PhHAbE3P.js +0 -2
  1011. package/dist/runtime-channel-ehNPdqhp.js +0 -150
  1012. package/dist/runtime-doctor-DVYwKwIT.d.ts +0 -47
  1013. package/dist/runtime-embedded-pi.runtime-BExQEON7.js +0 -2
  1014. package/dist/runtime-l-x1mIPp.js +0 -438
  1015. package/dist/sanitize-outbound-CINW3wBb.js +0 -127
  1016. package/dist/sdk-setup-tools-DotzY-Ff.js +0 -8
  1017. package/dist/secrets-BdWCp_pg.js +0 -113
  1018. package/dist/security-audit-BMS02wuX.js +0 -122
  1019. package/dist/security-audit-BXupNbYa.js +0 -118
  1020. package/dist/security-audit.runtime-CONAKFRk.js +0 -2
  1021. package/dist/selection-8iOGMBPh.js +0 -16157
  1022. package/dist/selection-D9-GNcGp.js +0 -3
  1023. package/dist/send-BsqMC7vV.js +0 -143
  1024. package/dist/send-ChUpwNpF.js +0 -2
  1025. package/dist/send-D92kiCYa.js +0 -192
  1026. package/dist/send-D95RJNJM.d.ts +0 -104
  1027. package/dist/send-DZ4YhPHH.d.ts +0 -231
  1028. package/dist/send-LSm52k6p.js +0 -1631
  1029. package/dist/send.components-D_1vDkKM.js +0 -2
  1030. package/dist/send.components-Scs0rrDy.js +0 -500
  1031. package/dist/send.runtime-BJbljin6.js +0 -2
  1032. package/dist/send.types-_f4omMzG.d.ts +0 -159
  1033. package/dist/server-BQ9wTpKB.js +0 -73
  1034. package/dist/server-CHWh_XGy.js +0 -24
  1035. package/dist/server-context-D42gG6GT.js +0 -2
  1036. package/dist/server-context-oRlMLKPz.js +0 -955
  1037. package/dist/server-cron-BpLzGXmi.js +0 -2
  1038. package/dist/server-cron-DFsVLz6k.js +0 -2989
  1039. package/dist/server-methods-CVgaE49L.js +0 -16499
  1040. package/dist/server-node-events-DmaGt81F.js +0 -596
  1041. package/dist/server-plugin-bootstrap-ypOUJ438.js +0 -70
  1042. package/dist/server-plugins-BVVgDSdq.d.ts +0 -1
  1043. package/dist/server-plugins-BZZxcYFZ.js +0 -432
  1044. package/dist/server-reload-handlers-Ccu2KW5E.js +0 -714
  1045. package/dist/server-restart-sentinel-Bud1fPG5.js +0 -2
  1046. package/dist/server-restart-sentinel-C4oYiDTT.js +0 -747
  1047. package/dist/server-runtime-services-BAlijw2O.js +0 -267
  1048. package/dist/server-runtime-services-BY8y-CAk.js +0 -2
  1049. package/dist/server-startup-plugins-utvxpVCl.js +0 -113
  1050. package/dist/server-startup-post-attach-C09QVu1D.js +0 -716
  1051. package/dist/server-ws-runtime-hgZQmILO.js +0 -349
  1052. package/dist/server.impl-btEzW7aF.js +0 -2587
  1053. package/dist/service-DYvUSJDx.js +0 -1446
  1054. package/dist/session-binding-Smi9h573.js +0 -219
  1055. package/dist/session-binding-vAzR408o.js +0 -2
  1056. package/dist/session-kill-http-HXI6hUDG.js +0 -121
  1057. package/dist/session-reset-service-CdqhH7XS.js +0 -625
  1058. package/dist/session-route-DX9HyYoG.js +0 -93
  1059. package/dist/session-status.runtime-B7dGtknj.js +0 -2
  1060. package/dist/session-subagent-reactivation.runtime-Dn-wvdjM.js +0 -2
  1061. package/dist/session-tab-registry-UN4VZE8a.js +0 -521
  1062. package/dist/sessions-history-http--Dgcvhb0.js +0 -430
  1063. package/dist/sessions.runtime-LnYxeKSP.js +0 -2
  1064. package/dist/setup-api-BfO7Ctmd.js +0 -29
  1065. package/dist/setup-core-DlCsv-9q.js +0 -174
  1066. package/dist/setup-surface-BDXmLycW.js +0 -221
  1067. package/dist/setup-surface-Bi-pZtB0.js +0 -405
  1068. package/dist/setup-surface-Bk9MdZ9I.js +0 -288
  1069. package/dist/setup-surface-m649hpou.js +0 -320
  1070. package/dist/shared-DwXuhcIz.js +0 -121
  1071. package/dist/shared-client-Cj3X4R8q.js +0 -2
  1072. package/dist/shared-client-D02xLLJg.js +0 -629
  1073. package/dist/side-question-DbsrGTKR.js +0 -683
  1074. package/dist/skill-tool-dispatch.runtime-CswUeFQB.js +0 -143
  1075. package/dist/slash-state-Br7bOIIy.js +0 -2166
  1076. package/dist/speech-provider-BHcOkoLn.js +0 -184
  1077. package/dist/src-DcIZ_w7l.js +0 -4256
  1078. package/dist/startup-context-BU3ZwnPZ.js +0 -313
  1079. package/dist/status-subagents.runtime-U9cVRB6A.js +0 -18
  1080. package/dist/status-text-DlZ-OoHI.js +0 -296
  1081. package/dist/sticker-cache-BfgCFMo_.js +0 -206
  1082. package/dist/sticker-vision.runtime-DYSdlJUC.js +0 -17
  1083. package/dist/subagent-announce-BntptirO.js +0 -354
  1084. package/dist/subagent-announce-delivery-6GUsisag.js +0 -958
  1085. package/dist/subagent-control-C7DSvkWz.js +0 -508
  1086. package/dist/subagent-hooks-4aumktTW.js +0 -2
  1087. package/dist/subagent-hooks-COUrrxEC.js +0 -2
  1088. package/dist/subagent-hooks-DUGDXbSM.js +0 -146
  1089. package/dist/subagent-hooks-DjDgoKjj.js +0 -230
  1090. package/dist/subagent-hooks-DjvL3k1b.js +0 -2
  1091. package/dist/subagent-hooks-api-BxfHMA2E.js +0 -22
  1092. package/dist/subagent-hooks-api-Cn7QkuFW.js +0 -23
  1093. package/dist/subagent-hooks-api-_lgvYj20.js +0 -23
  1094. package/dist/subagent-hooks-gWxlJnmo.js +0 -116
  1095. package/dist/subagent-orphan-recovery-CcAPcsDk.js +0 -352
  1096. package/dist/subagent-registry-BVVgDSdq.d.ts +0 -1
  1097. package/dist/subagent-registry-BsYF1Amv.js +0 -3
  1098. package/dist/subagent-registry-LC_Gic13.js +0 -2351
  1099. package/dist/subagent-registry-read-BVVgDSdq.d.ts +0 -1
  1100. package/dist/subagent-session-cleanup-6AY_7hyu.js +0 -525
  1101. package/dist/subagent-spawn-C2IO1E1i.js +0 -1164
  1102. package/dist/target-id-By34AE0b.js +0 -107
  1103. package/dist/targets-B40DzW6Y.js +0 -44
  1104. package/dist/targets-BttGNxRs.js +0 -19
  1105. package/dist/targets-C6bpLZdS.js +0 -19
  1106. package/dist/test-fixtures-xgg7UsEw.d.ts +0 -27
  1107. package/dist/test-support-BVVgDSdq.d.ts +0 -1
  1108. package/dist/testing-BzZIozrH.js +0 -267
  1109. package/dist/thread-bindings-CBiuE4G4.js +0 -228
  1110. package/dist/thread-bindings-CTJq5UHl.js +0 -232
  1111. package/dist/thread-bindings-bN9Ad5r9.js +0 -571
  1112. package/dist/thread-bindings-kXHwWthg.js +0 -8
  1113. package/dist/thread-bindings.discord-api-C8jkPA0w.js +0 -187
  1114. package/dist/thread-bindings.manager-BsFmjrbx.js +0 -536
  1115. package/dist/thread-bindings.manager-DfJgNAl6.js +0 -2
  1116. package/dist/thread-lifecycle-gR5OSLzh.js +0 -1614
  1117. package/dist/token-B2FhcBoz.js +0 -134
  1118. package/dist/tool-47nHlaiR.js +0 -139
  1119. package/dist/tool-actions.runtime-DwQ1lVPo.js +0 -534
  1120. package/dist/tool-resolution-DQej_E5w.js +0 -149
  1121. package/dist/tools-effective-inventory-CyXaSANM.js +0 -204
  1122. package/dist/tools-invoke-http-yo3HU4V6.js +0 -67
  1123. package/dist/tools-invoke-shared-LpV_xD9g.js +0 -200
  1124. package/dist/tts-E7ULNzl4.js +0 -66
  1125. package/dist/tui-B-wyN6wJ.js +0 -4709
  1126. package/dist/tui-CdI6yMis.js +0 -2
  1127. package/dist/tui-backend-CXej-4Er.js +0 -256
  1128. package/dist/tui-cli-wboa0AnA.js +0 -37
  1129. package/dist/typed-cases-v8PtmO3g.d.ts +0 -68
  1130. package/dist/update-cli-CGUsDh2T.js +0 -3665
  1131. package/dist/update-global-BbP9IhEf.js +0 -601
  1132. package/dist/update-runner-B54rgAmr.js +0 -1798
  1133. package/dist/vision-tools-wacIK5vr.js +0 -1409
  1134. package/dist/web-search-AMwc61Dr.js +0 -62
  1135. package/dist/web-search-provider.runtime-CNG2uQTF.js +0 -2
  1136. package/dist/web-search-provider.runtime-oBaJtm_S.js +0 -328
  1137. package/dist/webhook-targets-C9cJD_kB.d.ts +0 -99
  1138. package/dist/xai-oauth-DOqf2jTO.js +0 -479
  1139. package/dist/xai-user-agent-Dk71wEWd.js +0 -32
  1140. /package/dist/{acp-runtime-backend-4DfhM5M9.js → acp-runtime-backend-CxP454w8.js} +0 -0
  1141. /package/dist/{channel-actions-CYB0u2id.js → channel-actions-AudMk4Yk.js} +0 -0
  1142. /package/dist/{command-status-runtime-CPIRzAU6.js → command-status-runtime-BWRWzQv1.js} +0 -0
  1143. /package/dist/{delegate-DpQ2iXjn.js → delegate-CLZeP48P.js} +0 -0
  1144. /package/dist/{dispatch-acp-Bdp6i1Mz.js → dispatch-acp-BK0Zh3_p.js} +0 -0
  1145. /package/dist/{heartbeat-runner-Cx01gr5N.js → heartbeat-runner-BouutzYV.js} +0 -0
  1146. /package/dist/{library-BSsSuIcq.js → library-C-O719bG.js} +0 -0
  1147. /package/dist/{models-D6WT5XG82.d.ts → models-D6WT5XG8.d.ts} +0 -0
  1148. /package/dist/{run-executor.runtime-DwZVL5h6.js → run-executor.runtime-DF1Wol1i.js} +0 -0
  1149. /package/dist/{runtime-api-C7ToEUFX.d.ts → runtime-api-C7ToEUFX2.d.ts} +0 -0
  1150. /package/dist/{shared-DJ7fJ5uN.js → shared-BqbJdmuE.js} +0 -0
@@ -1,4377 +0,0 @@
1
- import { a as normalizeLowercaseStringOrEmpty, c as normalizeOptionalString, d as normalizeStringifiedOptionalString } from "./string-coerce-DyL154ka.js";
2
- import { b as escapeRegExp } from "./utils-CNnMhEDp.js";
3
- import { F as resolveSessionStoreEntry } from "./store-load-CM8N9kY-.js";
4
- import { a as getReplyPayloadTtsSupplement, n as buildTtsSupplementMediaPayload } from "./reply-payload-CiT5mlcY.js";
5
- import { i as writeJsonFileAtomically, n as readJsonFileWithFallback } from "./json-store-GaAZLixM.js";
6
- import { a as createChannelProgressDraftGate, c as formatChannelProgressDraftText, f as mergeChannelProgressDraftLine, i as buildChannelProgressDraftLineForEntry, o as formatChannelProgressDraftLine, p as normalizeChannelProgressDraftLineIdentity, s as formatChannelProgressDraftLineForEntry, u as isChannelProgressDraftWorkToolName, y as resolveChannelProgressDraftMaxLines } from "./channel-streaming-BBW2i40H.js";
7
- import { a as resolveInboundLastRouteSessionKey } from "./resolve-route-DM644egJ.js";
8
- import { c as defineStableChannelIngressIdentity, n as createChannelIngressResolver } from "./runtime-CGUAJWlF.js";
9
- import { a as warnMissingProviderGroupPolicyFallbackOnce, n as resolveAllowlistProviderRuntimeGroupPolicy, r as resolveDefaultGroupPolicy, t as GROUP_POLICY_BLOCKED_LABEL } from "./runtime-group-policy-CmZDlIwd.js";
10
- import { l as resolvePinnedMainDmOwnerFromAllowlist } from "./dm-policy-shared-OiZd1Sra.js";
11
- import { r as getAgentScopedMediaLocalRoots } from "./local-roots-DTtaSiSl.js";
12
- import { t as resolveAckReaction } from "./identity-mj7ULwMH.js";
13
- import { a as deliverWithFinalizableLivePreviewAdapter, n as createPreviewMessageReceipt, r as defineFinalizableLivePreviewAdapter } from "./live-CF0ee90S.js";
14
- import { c as resolveThreadBindingMaxAgeMsForChannel, o as resolveThreadBindingIdleTimeoutMsForChannel } from "./thread-bindings-policy-B6eVjk9L.js";
15
- import "./string-coerce-runtime-DcopKqDR.js";
16
- import "./routing-CMt5erhN.js";
17
- import { o as buildInboundHistoryFromEntries } from "./history-DYsbSN3R.js";
18
- import { n as createReplyPrefixOptions } from "./reply-prefix-pPkEIoYX.js";
19
- import { t as createTypingCallbacks } from "./typing-C657onUT.js";
20
- import { i as mergePairLoopGuardConfig } from "./pair-loop-guard-runtime-jabAgbOL.js";
21
- import { n as hasFinalChannelTurnDispatch } from "./dispatch-result-BM3RYtx4.js";
22
- import { t as evaluateSupplementalContextVisibility } from "./context-visibility-C9pX_aod.js";
23
- import { a as waitUntilAbort } from "./channel-lifecycle.core-CDt0hRZR.js";
24
- import { c as buildAllowlistResolutionSummary, d as patchAllowlistUsersInConfigEntries, f as summarizeMapping, l as canonicalizeAllowlistWithResolvedIds, s as addAllowlistUserEntriesFromConfigEntry } from "./allow-from-BsbZfqm-.js";
25
- import { n as isDangerousNameMatchingEnabled } from "./dangerous-name-matching-jjAiM0PK.js";
26
- import "./reply-history-Dr1yWscg.js";
27
- import { t as CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY } from "./approval-handler-adapter-runtime-uo1rB4v-.js";
28
- import { r as registerChannelRuntimeContext } from "./channel-runtime-context-DnHILMVu.js";
29
- import { t as resolveChannelContextVisibilityMode } from "./context-visibility-Si-TIKp_.js";
30
- import "./inbound-reply-dispatch-B1Yv-_Ol.js";
31
- import "./security-runtime-DfY3JFZ-.js";
32
- import { n as createTransportActivityStatusPatch, t as createConnectedChannelStatusPatch } from "./gateway-runtime-CVE8y-w2.js";
33
- import { n as logInboundDrop, r as logTypingFailure } from "./logging-Dr3f0mtP.js";
34
- import "./channel-feedback-DoSr1N_o.js";
35
- import { n as toLocationContext, t as formatLocationText } from "./location-B0jdizlz.js";
36
- import "./channel-lifecycle-DDnbT5P-.js";
37
- import "./channel-ingress-runtime-BS4mHyws.js";
38
- import "./channel-message-BaLrmuPN.js";
39
- import { t as loadSessionStore } from "./session-store-runtime-6Mgzwi0Q.js";
40
- import "./text-utility-runtime-C2BsP2Yq.js";
41
- import { t as isMatrixQualifiedUserId } from "./target-ids-1sTIwV96.js";
42
- import { a as resolveMatrixAccountConfig, i as resolveMatrixAccountAllowlistConfig } from "./account-config-wMhN5mBi.js";
43
- import { t as getMatrixRuntime } from "./runtime-ChnGj6Xz.js";
44
- import { n as resolveConfiguredMatrixBotUserIds } from "./accounts-DQa5og50.js";
45
- import { n as normalizeMatrixUserId, r as resolveMatrixAllowListMatch, t as normalizeMatrixAllowList } from "./allowlist-wB-C9Dsd.js";
46
- import { r as isMatrixNotFoundError, t as formatMatrixErrorMessage } from "./errors-BDE_mkHE.js";
47
- import { n as resolveMatrixRoomConfig, t as resolveMatrixStoredSessionMeta } from "./session-store-metadata-DsDaY9J0.js";
48
- import { i as resolveMatrixStateFilePath } from "./storage-xeGtUCQp.js";
49
- import { a as sendMessageMatrix, g as isPollStartType, h as isPollEventType, p as formatPollAsText, t as chunkMatrixText, v as parsePollStartContent } from "./send-DiWbR1fY.js";
50
- import { o as MATRIX_DAOCORE_FINALIZED_PREVIEW_KEY, r as promoteMatrixDirectRoomCandidate } from "./direct-management-BE4UOcoE.js";
51
- import { o as readJoinedMatrixMembers, r as isStrictDirectMembership, t as hasDirectMatrixMemberFlag } from "./direct-room-BifRU7rS.js";
52
- import { t as createMatrixThreadBindingManager } from "./thread-bindings-DDRSjebg.js";
53
- import { t as createAsyncLock } from "./async-lock-BcLS4KOc.js";
54
- import { n as LogService } from "./logger-B_3F-pg_.js";
55
- import { i as isMatrixMediaSizeLimitError, r as MatrixMediaSizeLimitError } from "./http-client-Cp9RYh0Z.js";
56
- import { i as throwIfMatrixStartupAborted, r as isMatrixStartupAbortError } from "./startup-abort-B-YL8CNT.js";
57
- import { n as isMatrixReadySyncState, r as isMatrixTerminalSyncState, t as isMatrixDisconnectedSyncState } from "./sync-state-CWbp0QSY.js";
58
- import { a as resolveMatrixMessageBody, i as resolveMatrixMessageAttachment, n as formatMatrixMediaUnavailableText, r as formatMatrixMessageText, s as fetchMatrixPollSnapshot, t as formatMatrixMediaTooLargeText } from "./media-text-BfTHKPLZ.js";
59
- import { n as setActiveMatrixClient } from "./active-client-oYl5IAAm.js";
60
- import { t as isBunRuntime } from "./runtime-BefyhPWv.js";
61
- import { n as resolveMatrixAuth, r as resolveMatrixAuthContext, t as backfillMatrixAuthDeviceIdAfterStartup } from "./config-Ga6iqQ4b.js";
62
- import { i as resolveSharedMatrixClient, n as releaseSharedClientInstance } from "./shared-CB-F6EAJ.js";
63
- import "./client-BIUHDRk1.js";
64
- import "./runtime-api-DQVZQ82e.js";
65
- import { t as resolveMatrixTargets } from "./resolve-targets-J3XI4rOm.js";
66
- import { t as formatMatrixEncryptedEventDisabledWarning } from "./encryption-guidance-x0hOzav7.js";
67
- import { a as EventType, i as resolveMatrixThreadRouting, n as resolveMatrixReplyToEventId, o as RelationType, r as resolveMatrixThreadRootId, t as resolveMatrixInboundRoute } from "./route-DJhNcnoM.js";
68
- import { format } from "node:util";
69
- //#region extensions/matrix/src/matrix/monitor/auto-join.ts
70
- function registerMatrixAutoJoin(params) {
71
- const { client, accountConfig, runtime } = params;
72
- const core = getMatrixRuntime();
73
- const logVerbose = (message) => {
74
- if (!core.logging.shouldLogVerbose()) return;
75
- runtime.log?.(message);
76
- };
77
- const autoJoin = accountConfig.autoJoin ?? "off";
78
- const rawAllowlist = (accountConfig.autoJoinAllowlist ?? []).map((entry) => normalizeStringifiedOptionalString(entry)).filter((entry) => Boolean(entry));
79
- const autoJoinAllowlist = new Set(rawAllowlist);
80
- const allowedRoomIds = new Set(rawAllowlist.filter((entry) => entry.startsWith("!")));
81
- const allowedAliases = rawAllowlist.filter((entry) => entry.startsWith("#"));
82
- const resolvedAliasRoomIds = /* @__PURE__ */ new Map();
83
- if (autoJoin === "off") return;
84
- if (autoJoin === "always") logVerbose("matrix: auto-join enabled for all invites");
85
- else logVerbose("matrix: auto-join enabled for allowlist invites");
86
- const resolveAllowedAliasRoomId = async (alias) => {
87
- if (resolvedAliasRoomIds.has(alias)) return resolvedAliasRoomIds.get(alias) ?? null;
88
- const resolved = await params.client.resolveRoom(alias);
89
- if (resolved) resolvedAliasRoomIds.set(alias, resolved);
90
- return resolved;
91
- };
92
- const resolveAllowedAliasRoomIds = async () => {
93
- return (await Promise.all(allowedAliases.map(async (alias) => {
94
- try {
95
- return await resolveAllowedAliasRoomId(alias);
96
- } catch (err) {
97
- runtime.error?.(`matrix: failed resolving allowlisted alias ${alias}: ${String(err)}`);
98
- return null;
99
- }
100
- }))).filter((roomId) => Boolean(roomId));
101
- };
102
- client.on("room.invite", async (roomId, _inviteEvent) => {
103
- if (autoJoin === "allowlist") {
104
- const allowedAliasRoomIds = await resolveAllowedAliasRoomIds();
105
- if (!(autoJoinAllowlist.has("*") || allowedRoomIds.has(roomId) || allowedAliasRoomIds.some((resolvedRoomId) => resolvedRoomId === roomId))) {
106
- logVerbose(`matrix: invite ignored (not in allowlist) room=${roomId}`);
107
- return;
108
- }
109
- }
110
- try {
111
- await client.joinRoom(roomId);
112
- logVerbose(`matrix: joined room ${roomId}`);
113
- } catch (err) {
114
- runtime.error?.(`matrix: failed to join room ${roomId}: ${String(err)}`);
115
- }
116
- });
117
- }
118
- //#endregion
119
- //#region extensions/matrix/src/matrix/monitor/config.ts
120
- function normalizeMatrixUserLookupEntry(raw) {
121
- return raw.replace(/^matrix:/i, "").replace(/^user:/i, "").trim();
122
- }
123
- function normalizeMatrixRoomLookupEntry(raw) {
124
- return raw.replace(/^matrix:/i, "").replace(/^(room|channel):/i, "").trim();
125
- }
126
- function filterResolvedMatrixAllowlistEntries(entries) {
127
- return entries.filter((entry) => {
128
- const trimmed = entry.trim();
129
- if (!trimmed) return false;
130
- if (trimmed === "*") return true;
131
- return isMatrixQualifiedUserId(normalizeMatrixUserLookupEntry(trimmed));
132
- });
133
- }
134
- function filterFailClosedMatrixAllowlistEntries(entries) {
135
- return entries.filter((entry) => entry.trim().length > 0);
136
- }
137
- function listResolvedMatrixAllowlistEntries(params) {
138
- const resolvedEntries = [];
139
- const seen = /* @__PURE__ */ new Set();
140
- for (const entry of params.entries) {
141
- const input = String(entry).trim();
142
- if (!input || seen.has(input)) continue;
143
- seen.add(input);
144
- const resolved = params.resolvedMap.get(input);
145
- if (!resolved?.resolved || !resolved.id) continue;
146
- const id = normalizeMatrixUserId(resolved.id);
147
- if (isMatrixQualifiedUserId(id)) resolvedEntries.push({
148
- input,
149
- id
150
- });
151
- }
152
- return resolvedEntries;
153
- }
154
- function normalizeConfiguredMatrixAllowlistEntries(entries) {
155
- const normalized = [];
156
- for (const entry of entries ?? []) {
157
- const trimmed = String(entry).trim();
158
- if (trimmed) normalized.push(trimmed);
159
- }
160
- return normalized;
161
- }
162
- function isMatrixDangerousNameMatchingEnabled(params) {
163
- return isDangerousNameMatchingEnabled(resolveMatrixAccountConfig({
164
- cfg: params.cfg,
165
- accountId: params.accountId
166
- }));
167
- }
168
- function addUniqueMatrixAllowlistEntry(params) {
169
- const trimmed = params.entry.trim();
170
- if (!trimmed) return;
171
- const key = trimmed.toLowerCase();
172
- if (params.seen.has(key)) return;
173
- params.seen.add(key);
174
- params.entries.push(trimmed);
175
- }
176
- function resolveStableMatrixMonitorUserEntries(entries) {
177
- const directMatches = [];
178
- for (const entry of entries) {
179
- const input = String(entry).trim();
180
- if (!input) continue;
181
- const query = normalizeMatrixUserLookupEntry(input);
182
- if (!query || query === "*") continue;
183
- directMatches.push(isMatrixQualifiedUserId(query) ? {
184
- input,
185
- resolved: true,
186
- id: normalizeMatrixUserId(query)
187
- } : {
188
- input,
189
- resolved: false
190
- });
191
- }
192
- return buildAllowlistResolutionSummary(directMatches);
193
- }
194
- function logStableMatrixAllowlistUnresolved(params) {
195
- if (params.unresolved.length === 0) return;
196
- summarizeMapping(params.label, [], params.unresolved, params.runtime);
197
- params.runtime.log?.(`${params.label} entries must be full Matrix IDs (example: @user:server). Unresolved entries will not match any sender. To match Matrix display names, set channels.matrix.dangerouslyAllowNameMatching=true.`);
198
- }
199
- function resolveStableMatrixMonitorUserAllowlist(params) {
200
- const allowList = params.allowList;
201
- const resolution = resolveStableMatrixMonitorUserEntries(allowList);
202
- const canonicalized = canonicalizeAllowlistWithResolvedIds({
203
- existing: allowList,
204
- resolvedMap: resolution.resolvedMap
205
- });
206
- logStableMatrixAllowlistUnresolved({
207
- label: params.label,
208
- unresolved: resolution.unresolved,
209
- runtime: params.runtime
210
- });
211
- return {
212
- entries: params.failClosedOnUnresolved ? filterFailClosedMatrixAllowlistEntries(canonicalized) : filterResolvedMatrixAllowlistEntries(canonicalized),
213
- resolvedEntries: listResolvedMatrixAllowlistEntries({
214
- entries: allowList,
215
- resolvedMap: resolution.resolvedMap
216
- })
217
- };
218
- }
219
- async function resolveMatrixMonitorUserEntries(params) {
220
- const directMatches = [];
221
- const pending = [];
222
- for (const entry of params.entries) {
223
- const input = String(entry).trim();
224
- if (!input) continue;
225
- const query = normalizeMatrixUserLookupEntry(input);
226
- if (!query || query === "*") continue;
227
- if (isMatrixQualifiedUserId(query)) {
228
- directMatches.push({
229
- input,
230
- resolved: true,
231
- id: normalizeMatrixUserId(query)
232
- });
233
- continue;
234
- }
235
- pending.push({
236
- input,
237
- query
238
- });
239
- }
240
- (pending.length === 0 ? [] : await params.resolveTargets({
241
- cfg: params.cfg,
242
- accountId: params.accountId,
243
- inputs: pending.map((entry) => entry.query),
244
- kind: "user",
245
- runtime: params.runtime
246
- })).forEach((entry, index) => {
247
- const source = pending[index];
248
- if (!source) return;
249
- directMatches.push({
250
- input: source.input,
251
- resolved: entry.resolved,
252
- id: entry.id ? normalizeMatrixUserId(entry.id) : void 0
253
- });
254
- });
255
- return buildAllowlistResolutionSummary(directMatches);
256
- }
257
- async function resolveMatrixMonitorUserAllowlist(params) {
258
- const allowList = (params.list ?? []).map(String);
259
- if (allowList.length === 0) return {
260
- entries: allowList,
261
- resolvedEntries: []
262
- };
263
- if (!isMatrixDangerousNameMatchingEnabled({
264
- cfg: params.cfg,
265
- accountId: params.accountId
266
- })) return resolveStableMatrixMonitorUserAllowlist({
267
- allowList,
268
- failClosedOnUnresolved: params.failClosedOnUnresolved,
269
- label: params.label,
270
- runtime: params.runtime
271
- });
272
- const resolution = await resolveMatrixMonitorUserEntries({
273
- cfg: params.cfg,
274
- accountId: params.accountId,
275
- entries: allowList,
276
- runtime: params.runtime,
277
- resolveTargets: params.resolveTargets
278
- });
279
- const canonicalized = canonicalizeAllowlistWithResolvedIds({
280
- existing: allowList,
281
- resolvedMap: resolution.resolvedMap
282
- });
283
- summarizeMapping(params.label, resolution.mapping, resolution.unresolved, params.runtime);
284
- if (resolution.unresolved.length > 0) params.runtime.log?.(`${params.label} entries must be full Matrix IDs (example: @user:server). Unresolved entries will not match any sender.`);
285
- return {
286
- entries: params.failClosedOnUnresolved ? filterFailClosedMatrixAllowlistEntries(canonicalized) : filterResolvedMatrixAllowlistEntries(canonicalized),
287
- resolvedEntries: listResolvedMatrixAllowlistEntries({
288
- entries: allowList,
289
- resolvedMap: resolution.resolvedMap
290
- })
291
- };
292
- }
293
- async function resolveMatrixMonitorLiveUserAllowlist(params) {
294
- const liveEntries = normalizeConfiguredMatrixAllowlistEntries(params.entries);
295
- if (liveEntries.length === 0) return [];
296
- const allowNameMatching = isMatrixDangerousNameMatchingEnabled({
297
- cfg: params.cfg,
298
- accountId: params.accountId
299
- });
300
- const effective = [];
301
- const seen = /* @__PURE__ */ new Set();
302
- const startupByInput = new Map((params.startupResolvedEntries ?? []).map((entry) => [entry.input, entry.id]));
303
- const pending = [];
304
- for (const entry of liveEntries) {
305
- const query = normalizeMatrixUserLookupEntry(entry);
306
- if (entry === "*") {
307
- addUniqueMatrixAllowlistEntry({
308
- entries: effective,
309
- seen,
310
- entry
311
- });
312
- continue;
313
- }
314
- if (isMatrixQualifiedUserId(query)) {
315
- addUniqueMatrixAllowlistEntry({
316
- entries: effective,
317
- seen,
318
- entry: normalizeMatrixUserId(query)
319
- });
320
- continue;
321
- }
322
- const startupId = startupByInput.get(entry);
323
- if (allowNameMatching && startupId) {
324
- addUniqueMatrixAllowlistEntry({
325
- entries: effective,
326
- seen,
327
- entry: startupId
328
- });
329
- continue;
330
- }
331
- if (allowNameMatching) {
332
- pending.push(entry);
333
- continue;
334
- }
335
- if (params.failClosedOnUnresolved) addUniqueMatrixAllowlistEntry({
336
- entries: effective,
337
- seen,
338
- entry
339
- });
340
- }
341
- if (pending.length === 0) return effective;
342
- const canonicalized = canonicalizeAllowlistWithResolvedIds({
343
- existing: pending,
344
- resolvedMap: (await resolveMatrixMonitorUserEntries({
345
- cfg: params.cfg,
346
- accountId: params.accountId,
347
- entries: pending,
348
- runtime: params.runtime,
349
- resolveTargets: params.resolveTargets ?? resolveMatrixTargets
350
- })).resolvedMap
351
- });
352
- const resolvedEntries = params.failClosedOnUnresolved ? filterFailClosedMatrixAllowlistEntries(canonicalized) : filterResolvedMatrixAllowlistEntries(canonicalized);
353
- for (const entry of resolvedEntries) addUniqueMatrixAllowlistEntry({
354
- entries: effective,
355
- seen,
356
- entry
357
- });
358
- return effective;
359
- }
360
- async function resolveMatrixMonitorRoomsConfig(params) {
361
- const roomsConfig = params.roomsConfig;
362
- if (!roomsConfig || Object.keys(roomsConfig).length === 0) return roomsConfig;
363
- const mapping = [];
364
- const unresolved = [];
365
- const nextRooms = {};
366
- const allowNameMatching = isMatrixDangerousNameMatchingEnabled({
367
- cfg: params.cfg,
368
- accountId: params.accountId
369
- });
370
- if (roomsConfig["*"]) nextRooms["*"] = roomsConfig["*"];
371
- const pending = [];
372
- for (const [entry, roomConfig] of Object.entries(roomsConfig)) {
373
- if (entry === "*") continue;
374
- const input = entry.trim();
375
- if (!input) continue;
376
- const cleaned = normalizeMatrixRoomLookupEntry(input);
377
- if (!cleaned) {
378
- unresolved.push(entry);
379
- continue;
380
- }
381
- if (cleaned.startsWith("!") && cleaned.includes(":")) {
382
- if (!nextRooms[cleaned]) nextRooms[cleaned] = roomConfig;
383
- if (cleaned !== input) mapping.push(`${input}→${cleaned}`);
384
- continue;
385
- }
386
- if (!cleaned.startsWith("#") && !allowNameMatching) {
387
- unresolved.push(input);
388
- continue;
389
- }
390
- pending.push({
391
- input,
392
- query: cleaned,
393
- config: roomConfig
394
- });
395
- }
396
- if (pending.length > 0) (await params.resolveTargets({
397
- cfg: params.cfg,
398
- accountId: params.accountId,
399
- inputs: pending.map((entry) => entry.query),
400
- kind: "group",
401
- runtime: params.runtime
402
- })).forEach((entry, index) => {
403
- const source = pending[index];
404
- if (!source) return;
405
- if (entry.resolved && entry.id) {
406
- const roomKey = normalizeMatrixRoomLookupEntry(entry.id);
407
- if (!nextRooms[roomKey]) nextRooms[roomKey] = source.config;
408
- mapping.push(`${source.input}→${roomKey}`);
409
- } else unresolved.push(source.input);
410
- });
411
- summarizeMapping("matrix rooms", mapping, unresolved, params.runtime);
412
- if (unresolved.length > 0) params.runtime.log?.("matrix rooms must be room IDs or aliases (example: !room:server or #alias:server). Unresolved entries are ignored.");
413
- const roomUsers = /* @__PURE__ */ new Set();
414
- for (const roomConfig of Object.values(nextRooms)) addAllowlistUserEntriesFromConfigEntry(roomUsers, roomConfig);
415
- if (roomUsers.size === 0) return nextRooms;
416
- if (!allowNameMatching) {
417
- const resolution = resolveStableMatrixMonitorUserEntries(Array.from(roomUsers));
418
- logStableMatrixAllowlistUnresolved({
419
- label: "matrix room users",
420
- unresolved: resolution.unresolved,
421
- runtime: params.runtime
422
- });
423
- return patchAllowlistUsersInConfigEntries({
424
- entries: nextRooms,
425
- resolvedMap: resolution.resolvedMap,
426
- strategy: "canonicalize"
427
- });
428
- }
429
- const resolution = await resolveMatrixMonitorUserEntries({
430
- cfg: params.cfg,
431
- accountId: params.accountId,
432
- entries: Array.from(roomUsers),
433
- runtime: params.runtime,
434
- resolveTargets: params.resolveTargets
435
- });
436
- summarizeMapping("matrix room users", resolution.mapping, resolution.unresolved, params.runtime);
437
- if (resolution.unresolved.length > 0) params.runtime.log?.("matrix room users entries must be full Matrix IDs (example: @user:server). Unresolved entries will not match any sender.");
438
- return patchAllowlistUsersInConfigEntries({
439
- entries: nextRooms,
440
- resolvedMap: resolution.resolvedMap,
441
- strategy: "canonicalize"
442
- });
443
- }
444
- async function resolveMatrixMonitorConfig(params) {
445
- const resolveTargets = params.resolveTargets ?? resolveMatrixTargets;
446
- const [allowFrom, groupAllowFrom, roomsConfig] = await Promise.all([
447
- resolveMatrixMonitorUserAllowlist({
448
- cfg: params.cfg,
449
- accountId: params.accountId,
450
- label: "matrix dm allowlist",
451
- list: params.allowFrom,
452
- runtime: params.runtime,
453
- resolveTargets
454
- }),
455
- resolveMatrixMonitorUserAllowlist({
456
- cfg: params.cfg,
457
- accountId: params.accountId,
458
- label: "matrix group allowlist",
459
- list: params.groupAllowFrom,
460
- failClosedOnUnresolved: true,
461
- runtime: params.runtime,
462
- resolveTargets
463
- }),
464
- resolveMatrixMonitorRoomsConfig({
465
- cfg: params.cfg,
466
- accountId: params.accountId,
467
- roomsConfig: params.roomsConfig,
468
- runtime: params.runtime,
469
- resolveTargets
470
- })
471
- ]);
472
- return {
473
- allowFrom: allowFrom.entries,
474
- allowFromResolvedEntries: allowFrom.resolvedEntries,
475
- groupAllowFrom: groupAllowFrom.entries,
476
- groupAllowFromResolvedEntries: groupAllowFrom.resolvedEntries,
477
- roomsConfig
478
- };
479
- }
480
- //#endregion
481
- //#region extensions/matrix/src/matrix/monitor/direct.ts
482
- const DM_CACHE_TTL_MS = 3e4;
483
- const RECENT_INVITE_TTL_MS = 3e4;
484
- const MAX_TRACKED_DM_ROOMS = 1024;
485
- const MAX_TRACKED_DM_MEMBER_FLAGS = 2048;
486
- function rememberBounded$1(map, key, value, maxSize = MAX_TRACKED_DM_ROOMS) {
487
- map.set(key, value);
488
- if (map.size > maxSize) {
489
- const oldest = map.keys().next().value;
490
- if (typeof oldest === "string") map.delete(oldest);
491
- }
492
- }
493
- function createDirectRoomTracker(client, opts = {}) {
494
- const log = opts.log ?? (() => {});
495
- let lastDmUpdateMs = 0;
496
- let hasSeededDmCache = false;
497
- let cachedSelfUserId = null;
498
- const joinedMembersCache = /* @__PURE__ */ new Map();
499
- const directMemberFlagCache = /* @__PURE__ */ new Map();
500
- const recentInviteCandidates = /* @__PURE__ */ new Map();
501
- const locallyPromotedDirectRooms = /* @__PURE__ */ new Map();
502
- const ensureSelfUserId = async () => {
503
- if (cachedSelfUserId) return cachedSelfUserId;
504
- try {
505
- cachedSelfUserId = await client.getUserId();
506
- } catch {
507
- cachedSelfUserId = null;
508
- }
509
- return cachedSelfUserId;
510
- };
511
- const refreshDmCache = async () => {
512
- const now = Date.now();
513
- if (now - lastDmUpdateMs < DM_CACHE_TTL_MS) return;
514
- lastDmUpdateMs = now;
515
- hasSeededDmCache = await client.dms.update() || hasSeededDmCache;
516
- };
517
- const resolveJoinedMembers = async (roomId) => {
518
- const cached = joinedMembersCache.get(roomId);
519
- const now = Date.now();
520
- if (cached && now - cached.ts < DM_CACHE_TTL_MS) return cached.members;
521
- try {
522
- const normalized = await readJoinedMatrixMembers(client, roomId);
523
- if (!normalized) throw new Error("membership unavailable");
524
- rememberBounded$1(joinedMembersCache, roomId, {
525
- members: normalized,
526
- ts: now
527
- });
528
- return normalized;
529
- } catch (err) {
530
- log(`matrix: dm member lookup failed room=${roomId} (${String(err)})`);
531
- return null;
532
- }
533
- };
534
- const resolveDirectMemberFlag = async (roomId, userId) => {
535
- const normalizedUserId = userId?.trim();
536
- if (!normalizedUserId) return null;
537
- const cacheKey = `${roomId}\n${normalizedUserId}`;
538
- const cached = directMemberFlagCache.get(cacheKey);
539
- const now = Date.now();
540
- if (cached && now - cached.ts < DM_CACHE_TTL_MS) return cached.isDirect;
541
- const isDirect = await hasDirectMatrixMemberFlag(client, roomId, normalizedUserId);
542
- rememberBounded$1(directMemberFlagCache, cacheKey, {
543
- isDirect,
544
- ts: now
545
- }, MAX_TRACKED_DM_MEMBER_FLAGS);
546
- return isDirect;
547
- };
548
- const hasRecentInviteCandidate = (roomId, remoteUserId) => {
549
- const normalizedRemoteUserId = remoteUserId?.trim();
550
- if (!normalizedRemoteUserId) return false;
551
- const cached = recentInviteCandidates.get(roomId);
552
- if (!cached) return false;
553
- if (Date.now() - cached.ts >= RECENT_INVITE_TTL_MS) {
554
- recentInviteCandidates.delete(roomId);
555
- return false;
556
- }
557
- return cached.remoteUserId === normalizedRemoteUserId;
558
- };
559
- const canPromoteRecentInvite = async (roomId) => {
560
- try {
561
- return await opts.canPromoteRecentInvite?.(roomId) ?? true;
562
- } catch (err) {
563
- log(`matrix: recent invite promotion veto failed room=${roomId} (${String(err)})`);
564
- return false;
565
- }
566
- };
567
- const canPromoteUnmappedStrictRoom = async (roomId) => {
568
- try {
569
- return await opts.canPromoteUnmappedStrictRoom?.(roomId) ?? false;
570
- } catch (err) {
571
- log(`matrix: unmapped strict room promotion veto failed room=${roomId} (${String(err)})`);
572
- return false;
573
- }
574
- };
575
- const shouldKeepLocallyPromotedDirectRoom = async (roomId) => {
576
- try {
577
- return await opts.shouldKeepLocallyPromotedDirectRoom?.(roomId);
578
- } catch (err) {
579
- log(`matrix: local promotion keep-check failed room=${roomId} (${String(err)})`);
580
- return;
581
- }
582
- };
583
- const isExplicitlyConfiguredRoom = async (roomId) => {
584
- try {
585
- return await opts.isExplicitlyConfiguredRoom?.(roomId) ?? false;
586
- } catch (err) {
587
- log(`matrix: configured room check failed room=${roomId} (${String(err)})`);
588
- return true;
589
- }
590
- };
591
- const hasLocallyPromotedDirectRoom = (roomId, remoteUserId) => {
592
- const normalizedRemoteUserId = remoteUserId?.trim();
593
- if (!normalizedRemoteUserId) return false;
594
- return locallyPromotedDirectRooms.get(roomId)?.remoteUserId === normalizedRemoteUserId;
595
- };
596
- const rememberLocallyPromotedDirectRoom = (roomId, remoteUserId) => {
597
- const normalizedRemoteUserId = remoteUserId.trim();
598
- if (!normalizedRemoteUserId) return;
599
- rememberBounded$1(locallyPromotedDirectRooms, roomId, { remoteUserId: normalizedRemoteUserId });
600
- };
601
- return {
602
- invalidateRoom: (roomId) => {
603
- joinedMembersCache.delete(roomId);
604
- for (const key of directMemberFlagCache.keys()) if (key.startsWith(`${roomId}\n`)) directMemberFlagCache.delete(key);
605
- lastDmUpdateMs = 0;
606
- log(`matrix: invalidated dm cache room=${roomId}`);
607
- },
608
- rememberInvite: (roomId, remoteUserId) => {
609
- const normalizedRemoteUserId = remoteUserId.trim();
610
- if (!normalizedRemoteUserId) return;
611
- rememberBounded$1(recentInviteCandidates, roomId, {
612
- remoteUserId: normalizedRemoteUserId,
613
- ts: Date.now()
614
- });
615
- log(`matrix: remembered invite candidate room=${roomId} sender=${normalizedRemoteUserId}`);
616
- },
617
- isDirectMessage: async (params) => {
618
- const { roomId, senderId } = params;
619
- if (await isExplicitlyConfiguredRoom(roomId)) {
620
- log(`matrix: dm rejected via explicit room config room=${roomId}`);
621
- return false;
622
- }
623
- const selfUserId = params.selfUserId ?? await ensureSelfUserId();
624
- const joinedMembers = await resolveJoinedMembers(roomId);
625
- const strictDirectMembership = isStrictDirectMembership({
626
- selfUserId,
627
- remoteUserId: senderId,
628
- joinedMembers
629
- });
630
- try {
631
- await refreshDmCache();
632
- } catch (err) {
633
- log(`matrix: dm cache refresh failed (${String(err)})`);
634
- }
635
- if (client.dms.isDm(roomId)) {
636
- if (strictDirectMembership) {
637
- log(`matrix: dm detected via m.direct room=${roomId}`);
638
- return true;
639
- }
640
- log(`matrix: ignoring stale m.direct classification room=${roomId}`);
641
- }
642
- if (strictDirectMembership) {
643
- const directViaSelf = await resolveDirectMemberFlag(roomId, selfUserId);
644
- if (directViaSelf === true) {
645
- log(`matrix: dm detected via member state room=${roomId}`);
646
- return true;
647
- }
648
- if (directViaSelf === false) {
649
- log(`matrix: dm rejected via member state room=${roomId}`);
650
- return false;
651
- }
652
- if (!hasSeededDmCache) {
653
- log(`matrix: dm detected via exact 2-member fallback before dm cache seed room=${roomId}`);
654
- return true;
655
- }
656
- if (hasLocallyPromotedDirectRoom(roomId, senderId)) {
657
- if (await shouldKeepLocallyPromotedDirectRoom(roomId) !== false) {
658
- log(`matrix: dm detected via local promotion room=${roomId}`);
659
- return true;
660
- }
661
- locallyPromotedDirectRooms.delete(roomId);
662
- log(`matrix: local promotion cleared room=${roomId}`);
663
- }
664
- if (hasRecentInviteCandidate(roomId, senderId) && await canPromoteRecentInvite(roomId)) {
665
- const promotion = await promoteMatrixDirectRoomCandidate({
666
- client,
667
- remoteUserId: senderId ?? "",
668
- roomId,
669
- selfUserId
670
- });
671
- if (promotion.classifyAsDirect) {
672
- rememberLocallyPromotedDirectRoom(roomId, senderId ?? "");
673
- log(`matrix: dm detected via recent invite room=${roomId} reason=${promotion.reason} repaired=${String(promotion.repaired)}`);
674
- return true;
675
- }
676
- }
677
- if (await canPromoteUnmappedStrictRoom(roomId)) {
678
- const promotion = await promoteMatrixDirectRoomCandidate({
679
- client,
680
- remoteUserId: senderId ?? "",
681
- roomId,
682
- selfUserId
683
- });
684
- if (promotion.classifyAsDirect) {
685
- rememberLocallyPromotedDirectRoom(roomId, senderId ?? "");
686
- log(`matrix: dm detected via per-room strict fallback room=${roomId} reason=${promotion.reason} repaired=${String(promotion.repaired)}`);
687
- return true;
688
- }
689
- }
690
- }
691
- log(`matrix: dm check room=${roomId} result=group members=${joinedMembers?.length ?? "unknown"}`);
692
- return false;
693
- }
694
- };
695
- }
696
- //#endregion
697
- //#region extensions/matrix/src/matrix/monitor/access-state.ts
698
- function normalizeMatrixEntry(raw) {
699
- return normalizeMatrixAllowList([raw ?? ""])[0] ?? null;
700
- }
701
- const matrixIngressIdentity = defineStableChannelIngressIdentity({
702
- key: "sender-id",
703
- normalize: normalizeMatrixEntry,
704
- matchEntry({ subject, entry }) {
705
- const senderId = subject.identifiers[0]?.value;
706
- return entry.value === "*" || resolveMatrixAllowListMatch({
707
- allowList: [entry.value],
708
- userId: senderId ?? ""
709
- }).allowed;
710
- }
711
- });
712
- function resolveMatrixGroupIngress(params) {
713
- if (params.groupPolicy === "disabled") return {
714
- groupPolicy: "disabled",
715
- groupAllowFrom: []
716
- };
717
- if (params.effectiveRoomUsers.length > 0) return {
718
- groupPolicy: "allowlist",
719
- groupAllowFrom: params.effectiveRoomUsers
720
- };
721
- if (params.groupPolicy === "allowlist" && params.effectiveGroupAllowFrom.length > 0) return {
722
- groupPolicy: "allowlist",
723
- groupAllowFrom: params.effectiveGroupAllowFrom
724
- };
725
- return {
726
- groupPolicy: "open",
727
- groupAllowFrom: []
728
- };
729
- }
730
- async function resolveMatrixMonitorAccessState(params) {
731
- const dmPolicy = params.dmPolicy ?? "pairing";
732
- const groupPolicy = params.groupPolicy ?? "open";
733
- const effectiveGroupAllowFrom = normalizeMatrixAllowList(params.groupAllowFrom);
734
- const effectiveRoomUsers = normalizeMatrixAllowList(params.roomUsers);
735
- const groupIngress = resolveMatrixGroupIngress({
736
- groupPolicy,
737
- effectiveGroupAllowFrom,
738
- effectiveRoomUsers
739
- });
740
- const accountId = params.accountId ?? "default";
741
- const eventKind = params.eventKind ?? "message";
742
- return {
743
- effectiveGroupAllowFrom,
744
- effectiveRoomUsers,
745
- messageIngress: await createChannelIngressResolver({
746
- channelId: "matrix",
747
- accountId,
748
- identity: matrixIngressIdentity,
749
- readStoreAllowFrom: async () => params.storeAllowFrom
750
- }).message({
751
- subject: { stableId: params.senderId },
752
- conversation: {
753
- kind: params.isRoom ? "group" : "direct",
754
- id: params.isRoom ? "matrix-room" : "matrix-dm"
755
- },
756
- event: {
757
- kind: eventKind,
758
- authMode: "inbound",
759
- mayPair: params.isRoom ? false : eventKind === "message"
760
- },
761
- dmPolicy,
762
- groupPolicy: params.isRoom ? groupIngress.groupPolicy : "disabled",
763
- policy: { groupAllowFromFallbackToAllowFrom: false },
764
- allowFrom: params.allowFrom,
765
- ...params.isRoom ? { groupAllowFrom: groupIngress.groupAllowFrom } : {}
766
- }),
767
- accountId,
768
- senderId: params.senderId,
769
- isRoom: params.isRoom
770
- };
771
- }
772
- async function resolveMatrixMonitorCommandAccess(state, params) {
773
- const commandAllowFrom = state.isRoom ? [] : state.messageIngress.senderAccess.effectiveAllowFrom;
774
- const commandGroupAllowFrom = state.effectiveRoomUsers.length > 0 ? state.effectiveRoomUsers : state.effectiveGroupAllowFrom;
775
- return (await createChannelIngressResolver({
776
- channelId: "matrix",
777
- accountId: state.accountId,
778
- identity: matrixIngressIdentity
779
- }).command({
780
- subject: { stableId: state.senderId },
781
- conversation: {
782
- kind: state.isRoom ? "group" : "direct",
783
- id: state.isRoom ? "matrix-room" : "matrix-dm"
784
- },
785
- dmPolicy: "allowlist",
786
- groupPolicy: "allowlist",
787
- policy: { groupAllowFromFallbackToAllowFrom: false },
788
- allowFrom: commandAllowFrom,
789
- groupAllowFrom: commandGroupAllowFrom,
790
- command: {
791
- useAccessGroups: params.useAccessGroups,
792
- allowTextCommands: params.allowTextCommands,
793
- hasControlCommand: params.hasControlCommand,
794
- groupOwnerAllowFrom: "none",
795
- commandGroupAllowFromFallbackToAllowFrom: false
796
- }
797
- })).commandAccess;
798
- }
799
- //#endregion
800
- //#region extensions/matrix/src/matrix/monitor/verification-utils.ts
801
- const VERIFICATION_EVENT_PREFIX = "m.key.verification.";
802
- const VERIFICATION_REQUEST_MSGTYPE = "m.key.verification.request";
803
- const VERIFICATION_NOTICE_PREFIXES = [
804
- "Matrix verification request received from ",
805
- "Matrix verification is ready with ",
806
- "Matrix verification started with ",
807
- "Matrix verification completed with ",
808
- "Matrix verification cancelled by ",
809
- "Matrix verification SAS with "
810
- ];
811
- function trimMaybeString$1(input) {
812
- return normalizeOptionalString(input) ?? "";
813
- }
814
- function isMatrixVerificationEventType(type) {
815
- return trimMaybeString$1(type).startsWith(VERIFICATION_EVENT_PREFIX);
816
- }
817
- function isMatrixVerificationRequestMsgType(msgtype) {
818
- return trimMaybeString$1(msgtype) === VERIFICATION_REQUEST_MSGTYPE;
819
- }
820
- function isMatrixVerificationNoticeBody(body) {
821
- const text = trimMaybeString$1(body);
822
- return VERIFICATION_NOTICE_PREFIXES.some((prefix) => text.startsWith(prefix));
823
- }
824
- function isMatrixVerificationRoomMessage(content) {
825
- return isMatrixVerificationRequestMsgType(content.msgtype) || trimMaybeString$1(content.msgtype) === "m.notice" && isMatrixVerificationNoticeBody(content.body);
826
- }
827
- const matrixVerificationConstants = {
828
- eventPrefix: VERIFICATION_EVENT_PREFIX,
829
- requestMsgtype: VERIFICATION_REQUEST_MSGTYPE
830
- };
831
- //#endregion
832
- //#region extensions/matrix/src/matrix/monitor/verification-events.ts
833
- const MAX_TRACKED_VERIFICATION_EVENTS = 1024;
834
- const SAS_NOTICE_RETRY_DELAY_MS = 750;
835
- const VERIFICATION_EVENT_STARTUP_GRACE_MS = 3e4;
836
- let matrixDirectRoomDepsPromise;
837
- async function loadMatrixDirectRoomDeps() {
838
- matrixDirectRoomDepsPromise ??= Promise.all([import("./direct-management-COFmFhJf.js"), import("./direct-room-o6lvHwv6.js")]).then(([directManagementModule, directRoomModule]) => ({
839
- inspectMatrixDirectRooms: directManagementModule.inspectMatrixDirectRooms,
840
- isStrictDirectRoom: directRoomModule.isStrictDirectRoom
841
- }));
842
- return await matrixDirectRoomDepsPromise;
843
- }
844
- function trimMaybeString(input) {
845
- if (typeof input !== "string") return null;
846
- const trimmed = input.trim();
847
- return trimmed.length > 0 ? trimmed : null;
848
- }
849
- function readVerificationSignal(event) {
850
- const type = trimMaybeString(event?.type) ?? "";
851
- const content = event?.content ?? {};
852
- const msgtype = trimMaybeString(content.msgtype) ?? "";
853
- const relatedEventId = trimMaybeString(content["m.relates_to"]?.event_id);
854
- const transactionId = trimMaybeString(content.transaction_id);
855
- if (type === EventType.RoomMessage && isMatrixVerificationRequestMsgType(msgtype)) return {
856
- stage: "request",
857
- flowId: trimMaybeString(event.event_id) ?? transactionId ?? relatedEventId
858
- };
859
- if (!isMatrixVerificationEventType(type)) return null;
860
- const flowId = transactionId ?? relatedEventId ?? trimMaybeString(event.event_id);
861
- if (type === `${matrixVerificationConstants.eventPrefix}request`) return {
862
- stage: "request",
863
- flowId
864
- };
865
- if (type === `${matrixVerificationConstants.eventPrefix}ready`) return {
866
- stage: "ready",
867
- flowId
868
- };
869
- if (type === "m.key.verification.start") return {
870
- stage: "start",
871
- flowId
872
- };
873
- if (type === "m.key.verification.cancel") return {
874
- stage: "cancel",
875
- flowId
876
- };
877
- if (type === "m.key.verification.done") return {
878
- stage: "done",
879
- flowId
880
- };
881
- return {
882
- stage: "other",
883
- flowId
884
- };
885
- }
886
- function formatVerificationStageNotice(params) {
887
- const { stage, senderId, event } = params;
888
- const content = event.content;
889
- switch (stage) {
890
- case "request": return `Matrix verification request received from ${senderId}. Open "Verify by emoji" in your Matrix client to continue.`;
891
- case "ready": return `Matrix verification is ready with ${senderId}. Choose "Verify by emoji" to reveal the emoji sequence.`;
892
- case "start": return `Matrix verification started with ${senderId}.`;
893
- case "done": return `Matrix verification completed with ${senderId}.`;
894
- case "cancel": {
895
- const code = trimMaybeString(content.code);
896
- const reason = trimMaybeString(content.reason);
897
- if (code && reason) return `Matrix verification cancelled by ${senderId} (${code}: ${reason}).`;
898
- if (reason) return `Matrix verification cancelled by ${senderId} (${reason}).`;
899
- return `Matrix verification cancelled by ${senderId}.`;
900
- }
901
- default: return null;
902
- }
903
- }
904
- function formatVerificationSasNotice(summary) {
905
- const sas = summary.sas;
906
- if (!sas) return null;
907
- const emojiLine = Array.isArray(sas.emoji) && sas.emoji.length > 0 ? `SAS emoji: ${sas.emoji.map(([emoji, name]) => `${trimMaybeString(emoji) ?? "?"} ${trimMaybeString(name) ?? "?"}`).join(" | ")}` : null;
908
- const decimalLine = Array.isArray(sas.decimal) && sas.decimal.length === 3 ? `SAS decimal: ${sas.decimal.join(" ")}` : null;
909
- if (!emojiLine && !decimalLine) return null;
910
- const lines = [`Matrix verification SAS with ${summary.otherUserId}:`];
911
- if (emojiLine) lines.push(emojiLine);
912
- if (decimalLine) lines.push(decimalLine);
913
- lines.push("If both sides match, choose 'They match' in your Matrix app.");
914
- return lines.join("\n");
915
- }
916
- function resolveVerificationFlowCandidates(params) {
917
- const { event, flowId } = params;
918
- const content = event.content;
919
- const candidates = /* @__PURE__ */ new Set();
920
- const add = (value) => {
921
- const normalized = trimMaybeString(value);
922
- if (normalized) candidates.add(normalized);
923
- };
924
- add(flowId);
925
- add(event.event_id);
926
- add(content.transaction_id);
927
- add(content["m.relates_to"]?.event_id);
928
- return Array.from(candidates);
929
- }
930
- function resolveSummaryRecency(summary) {
931
- const ts = Date.parse(summary.updatedAt ?? "");
932
- return Number.isFinite(ts) ? ts : 0;
933
- }
934
- function isActiveVerificationSummary(summary) {
935
- if (summary.completed === true) return false;
936
- if (summary.phaseName === "cancelled" || summary.phaseName === "done") return false;
937
- if (typeof summary.phase === "number" && summary.phase >= 4) return false;
938
- return true;
939
- }
940
- async function resolveVerificationSummaryForSignal(client, params) {
941
- if (!client.crypto) return null;
942
- await client.crypto.ensureVerificationDmTracked({
943
- roomId: params.roomId,
944
- userId: params.senderId
945
- }).catch(() => null);
946
- const list = await client.crypto.listVerifications();
947
- if (list.length === 0) return null;
948
- const candidates = resolveVerificationFlowCandidates({
949
- event: params.event,
950
- flowId: params.flowId
951
- });
952
- const byTransactionId = list.find((entry) => candidates.some((candidate) => entry.transactionId === candidate));
953
- if (byTransactionId) return byTransactionId;
954
- const { inspectMatrixDirectRooms, isStrictDirectRoom } = await loadMatrixDirectRoomDeps();
955
- const activeRoomId = trimMaybeString((await inspectMatrixDirectRooms({
956
- client,
957
- remoteUserId: params.senderId
958
- }).catch(() => null))?.activeRoomId);
959
- if (activeRoomId) {
960
- if (activeRoomId !== params.roomId) return null;
961
- } else if (!await isStrictDirectRoom({
962
- client,
963
- roomId: params.roomId,
964
- remoteUserId: params.senderId
965
- })) return null;
966
- const activeByUser = list.filter((entry) => entry.otherUserId === params.senderId && isActiveVerificationSummary(entry)).toSorted((a, b) => resolveSummaryRecency(b) - resolveSummaryRecency(a));
967
- const activeInRoom = activeByUser.filter((entry) => {
968
- return trimMaybeString(entry.roomId) === params.roomId;
969
- });
970
- if (activeInRoom.length > 0) return activeInRoom[0] ?? null;
971
- return activeByUser[0] ?? null;
972
- }
973
- async function resolveVerificationSasNoticeForSignal(client, params) {
974
- const summary = await resolveVerificationSummaryForSignal(client, params);
975
- const immediateNotice = summary && isActiveVerificationSummary(summary) ? formatVerificationSasNotice(summary) : null;
976
- if (immediateNotice || params.stage !== "ready" && params.stage !== "start") return {
977
- summary,
978
- sasNotice: immediateNotice
979
- };
980
- await new Promise((resolve) => setTimeout(resolve, params.sasNoticeRetryDelayMs ?? SAS_NOTICE_RETRY_DELAY_MS));
981
- const retriedSummary = await resolveVerificationSummaryForSignal(client, params);
982
- return {
983
- summary: retriedSummary,
984
- sasNotice: retriedSummary && isActiveVerificationSummary(retriedSummary) ? formatVerificationSasNotice(retriedSummary) : null
985
- };
986
- }
987
- function trackBounded(set, value) {
988
- if (!value || set.has(value)) return false;
989
- set.add(value);
990
- if (set.size > MAX_TRACKED_VERIFICATION_EVENTS) {
991
- const oldest = set.values().next().value;
992
- if (typeof oldest === "string") set.delete(oldest);
993
- }
994
- return true;
995
- }
996
- async function sendVerificationNotice(params) {
997
- const roomId = trimMaybeString(params.roomId);
998
- if (!roomId) return;
999
- try {
1000
- await params.client.sendMessage(roomId, {
1001
- msgtype: "m.notice",
1002
- body: params.body
1003
- });
1004
- } catch (err) {
1005
- params.logVerboseMessage(`matrix: failed sending verification notice room=${roomId}: ${String(err)}`);
1006
- }
1007
- }
1008
- async function isVerificationNoticeAuthorized(params) {
1009
- if (!params.dmEnabled || params.dmPolicy === "disabled") {
1010
- params.logVerboseMessage(`matrix: blocked verification sender ${params.senderId} (dmPolicy=${params.dmPolicy}, dmEnabled=${String(params.dmEnabled)})`);
1011
- return false;
1012
- }
1013
- const storeAllowFrom = params.dmPolicy !== "allowlist" && params.dmPolicy !== "open" ? await params.readStoreAllowFrom() : [];
1014
- if ((await resolveMatrixMonitorAccessState({
1015
- allowFrom: params.allowFrom,
1016
- storeAllowFrom,
1017
- dmPolicy: params.dmPolicy,
1018
- groupPolicy: "open",
1019
- groupAllowFrom: [],
1020
- roomUsers: [],
1021
- senderId: params.senderId,
1022
- isRoom: false
1023
- })).messageIngress.senderAccess.decision === "allow") return true;
1024
- params.logVerboseMessage(`matrix: blocked verification sender ${params.senderId} (dmPolicy=${params.dmPolicy})`);
1025
- return false;
1026
- }
1027
- function createMatrixVerificationEventRouter(params) {
1028
- const routerStartedAtMs = Date.now();
1029
- const routedVerificationEvents = /* @__PURE__ */ new Set();
1030
- const routedVerificationSasFingerprints = /* @__PURE__ */ new Set();
1031
- const routedVerificationStageNotices = /* @__PURE__ */ new Set();
1032
- const verificationFlowRooms = /* @__PURE__ */ new Map();
1033
- const verificationUserRooms = /* @__PURE__ */ new Map();
1034
- async function resolveActiveDirectRoomId(remoteUserId) {
1035
- const { inspectMatrixDirectRooms } = await loadMatrixDirectRoomDeps();
1036
- return trimMaybeString((await inspectMatrixDirectRooms({
1037
- client: params.client,
1038
- remoteUserId
1039
- }).catch(() => null))?.activeRoomId);
1040
- }
1041
- function shouldEmitVerificationEventNotice(event) {
1042
- const eventTs = typeof event.origin_server_ts === "number" && Number.isFinite(event.origin_server_ts) ? event.origin_server_ts : null;
1043
- if (eventTs === null) return true;
1044
- return eventTs >= routerStartedAtMs - VERIFICATION_EVENT_STARTUP_GRACE_MS;
1045
- }
1046
- function rememberVerificationRoom(roomId, event, flowId) {
1047
- for (const candidate of resolveVerificationFlowCandidates({
1048
- event,
1049
- flowId
1050
- })) {
1051
- verificationFlowRooms.set(candidate, roomId);
1052
- if (verificationFlowRooms.size > MAX_TRACKED_VERIFICATION_EVENTS) {
1053
- const oldest = verificationFlowRooms.keys().next().value;
1054
- if (typeof oldest === "string") verificationFlowRooms.delete(oldest);
1055
- }
1056
- }
1057
- }
1058
- function rememberVerificationUserRoom(remoteUserId, roomId) {
1059
- const normalizedUserId = trimMaybeString(remoteUserId);
1060
- const normalizedRoomId = trimMaybeString(roomId);
1061
- if (!normalizedUserId || !normalizedRoomId) return;
1062
- verificationUserRooms.delete(normalizedUserId);
1063
- verificationUserRooms.set(normalizedUserId, normalizedRoomId);
1064
- if (verificationUserRooms.size > MAX_TRACKED_VERIFICATION_EVENTS) {
1065
- const oldest = verificationUserRooms.keys().next().value;
1066
- if (typeof oldest === "string") verificationUserRooms.delete(oldest);
1067
- }
1068
- }
1069
- async function resolveSummaryRoomId(summary) {
1070
- const mappedRoomId = trimMaybeString(summary.roomId) ?? trimMaybeString(summary.transactionId ? verificationFlowRooms.get(summary.transactionId) : null) ?? trimMaybeString(verificationFlowRooms.get(summary.id));
1071
- if (mappedRoomId) return mappedRoomId;
1072
- const remoteUserId = trimMaybeString(summary.otherUserId);
1073
- if (!remoteUserId) return null;
1074
- const recentRoomId = trimMaybeString(verificationUserRooms.get(remoteUserId));
1075
- const activeRoomId = await resolveActiveDirectRoomId(remoteUserId);
1076
- if (recentRoomId && activeRoomId && recentRoomId === activeRoomId) return recentRoomId;
1077
- if (activeRoomId) return activeRoomId;
1078
- if (recentRoomId && await (await loadMatrixDirectRoomDeps()).isStrictDirectRoom({
1079
- client: params.client,
1080
- roomId: recentRoomId,
1081
- remoteUserId
1082
- })) return recentRoomId;
1083
- return null;
1084
- }
1085
- async function routeVerificationSummary(summary) {
1086
- const roomId = await resolveSummaryRoomId(summary);
1087
- if (!roomId || !isActiveVerificationSummary(summary)) return;
1088
- if (!await (await loadMatrixDirectRoomDeps()).isStrictDirectRoom({
1089
- client: params.client,
1090
- roomId,
1091
- remoteUserId: summary.otherUserId
1092
- })) {
1093
- params.logVerboseMessage(`matrix: ignoring verification summary outside strict DM room=${roomId} sender=${summary.otherUserId}`);
1094
- return;
1095
- }
1096
- if (!await isVerificationNoticeAuthorized({
1097
- senderId: summary.otherUserId,
1098
- allowFrom: params.allowFrom,
1099
- dmEnabled: params.dmEnabled,
1100
- dmPolicy: params.dmPolicy,
1101
- readStoreAllowFrom: params.readStoreAllowFrom,
1102
- logVerboseMessage: params.logVerboseMessage
1103
- })) return;
1104
- const sasNotice = formatVerificationSasNotice(summary);
1105
- if (!sasNotice) return;
1106
- if (!trackBounded(routedVerificationSasFingerprints, `${summary.id}:${JSON.stringify(summary.sas)}`)) return;
1107
- await sendVerificationNotice({
1108
- client: params.client,
1109
- roomId,
1110
- body: sasNotice,
1111
- logVerboseMessage: params.logVerboseMessage
1112
- });
1113
- }
1114
- function routeVerificationEvent(roomId, event) {
1115
- const senderId = trimMaybeString(event?.sender);
1116
- if (!senderId) return false;
1117
- const signal = readVerificationSignal(event);
1118
- if (!signal) return false;
1119
- rememberVerificationRoom(roomId, event, signal.flowId);
1120
- const routeTask = async () => {
1121
- if (!shouldEmitVerificationEventNotice(event)) {
1122
- params.logVerboseMessage(`matrix: ignoring historical verification event room=${roomId} id=${event.event_id ?? "unknown"} type=${event.type ?? "unknown"}`);
1123
- return;
1124
- }
1125
- const flowId = signal.flowId;
1126
- const sourceFingerprint = trimMaybeString(event?.event_id) ?? `${senderId}:${event.type}:${flowId ?? "none"}`;
1127
- if (!await (await loadMatrixDirectRoomDeps()).isStrictDirectRoom({
1128
- client: params.client,
1129
- roomId,
1130
- remoteUserId: senderId
1131
- })) {
1132
- params.logVerboseMessage(`matrix: ignoring verification event outside strict DM room=${roomId} sender=${senderId}`);
1133
- return;
1134
- }
1135
- if (!await isVerificationNoticeAuthorized({
1136
- senderId,
1137
- allowFrom: params.allowFrom,
1138
- dmEnabled: params.dmEnabled,
1139
- dmPolicy: params.dmPolicy,
1140
- readStoreAllowFrom: params.readStoreAllowFrom,
1141
- logVerboseMessage: params.logVerboseMessage
1142
- })) return;
1143
- rememberVerificationUserRoom(senderId, roomId);
1144
- if (!trackBounded(routedVerificationEvents, sourceFingerprint)) return;
1145
- const stageNotice = formatVerificationStageNotice({
1146
- stage: signal.stage,
1147
- senderId,
1148
- event
1149
- });
1150
- const { summary, sasNotice } = await resolveVerificationSasNoticeForSignal(params.client, {
1151
- roomId,
1152
- event,
1153
- senderId,
1154
- flowId,
1155
- stage: signal.stage,
1156
- sasNoticeRetryDelayMs: params.sasNoticeRetryDelayMs
1157
- }).catch(() => ({
1158
- summary: null,
1159
- sasNotice: null
1160
- }));
1161
- const notices = [];
1162
- if (stageNotice) {
1163
- if (trackBounded(routedVerificationStageNotices, `${roomId}:${senderId}:${flowId ?? sourceFingerprint}:${signal.stage}`)) notices.push(stageNotice);
1164
- }
1165
- if (summary && sasNotice) {
1166
- if (trackBounded(routedVerificationSasFingerprints, `${summary.id}:${JSON.stringify(summary.sas)}`)) notices.push(sasNotice);
1167
- }
1168
- if (notices.length === 0) return;
1169
- for (const body of notices) await sendVerificationNotice({
1170
- client: params.client,
1171
- roomId,
1172
- body,
1173
- logVerboseMessage: params.logVerboseMessage
1174
- });
1175
- };
1176
- if (params.runDetachedTask) params.runDetachedTask(`verification event handler room=${roomId} id=${event.event_id ?? "unknown"}`, routeTask);
1177
- else routeTask().catch((err) => {
1178
- params.logVerboseMessage(`matrix: failed routing verification event: ${String(err)}`);
1179
- });
1180
- return true;
1181
- }
1182
- return {
1183
- routeVerificationEvent,
1184
- routeVerificationSummary
1185
- };
1186
- }
1187
- //#endregion
1188
- //#region extensions/matrix/src/matrix/monitor/events.ts
1189
- const MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_WINDOW_MS = 2 * 6e4;
1190
- const MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_THRESHOLD = 3;
1191
- const MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_SAMPLE_LIMIT = 3;
1192
- function formatMatrixPostHealthySyncDecryptionHint(accountId) {
1193
- return `matrix: repeated fresh encrypted messages are still failing to decrypt after Matrix resumed healthy sync. This device may still be missing new room keys. Check 'daocore matrix verify status --verbose --account ${accountId}' and 'daocore matrix devices list --account ${accountId}'.`;
1194
- }
1195
- function isFreshPostHealthySyncDecryptFailure(params) {
1196
- const { event, healthySyncSinceMs, graceMs = 0, nowMs } = params;
1197
- if (typeof healthySyncSinceMs !== "number" || !Number.isFinite(healthySyncSinceMs)) return false;
1198
- const eventTs = event.origin_server_ts;
1199
- if (!Number.isFinite(eventTs) || eventTs <= 0) return false;
1200
- if (eventTs < healthySyncSinceMs + graceMs) return false;
1201
- if (eventTs > nowMs + 6e4) return false;
1202
- return true;
1203
- }
1204
- function createMatrixPostHealthySyncDecryptFailureTracker(params) {
1205
- let observations = [];
1206
- let warningEmitted = false;
1207
- let trackedHealthySyncSinceMs;
1208
- const resetObservations = () => {
1209
- observations = [];
1210
- warningEmitted = false;
1211
- };
1212
- const pruneObservations = (nowMs) => {
1213
- observations = observations.filter((entry) => nowMs - entry.eventTs <= MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_WINDOW_MS);
1214
- if (observations.length === 0) warningEmitted = false;
1215
- };
1216
- return { recordFailure(roomId, event, error) {
1217
- const nowMs = Date.now();
1218
- const healthySyncSinceMs = params.getHealthySyncSinceMs?.();
1219
- if (healthySyncSinceMs !== trackedHealthySyncSinceMs) {
1220
- trackedHealthySyncSinceMs = healthySyncSinceMs;
1221
- resetObservations();
1222
- }
1223
- if (!isFreshPostHealthySyncDecryptFailure({
1224
- event,
1225
- healthySyncSinceMs,
1226
- graceMs: params.startupGraceMs,
1227
- nowMs
1228
- })) return {
1229
- freshAfterHealthySync: false,
1230
- failureCount: 0
1231
- };
1232
- pruneObservations(nowMs);
1233
- const key = `${roomId}|${event.event_id}`;
1234
- if (!observations.some((entry) => entry.key === key)) observations.push({
1235
- key,
1236
- roomId,
1237
- eventId: event.event_id,
1238
- sender: typeof event.sender === "string" ? event.sender : null,
1239
- eventTs: event.origin_server_ts,
1240
- error: error.message
1241
- });
1242
- const failureCount = observations.length;
1243
- if (warningEmitted || failureCount < MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_THRESHOLD) return {
1244
- freshAfterHealthySync: true,
1245
- failureCount
1246
- };
1247
- warningEmitted = true;
1248
- const rooms = [...new Set(observations.map((entry) => entry.roomId))].slice(0, MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_SAMPLE_LIMIT);
1249
- const senders = [...new Set(observations.map((entry) => entry.sender).filter(Boolean))].slice(0, MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_SAMPLE_LIMIT);
1250
- const eventIds = observations.slice(-3).map((entry) => entry.eventId);
1251
- const latestError = observations.at(-1)?.error ?? error.message;
1252
- return {
1253
- freshAfterHealthySync: true,
1254
- failureCount,
1255
- warning: {
1256
- rooms,
1257
- roomCount: new Set(observations.map((entry) => entry.roomId)).size,
1258
- senders,
1259
- senderCount: new Set(observations.map((entry) => entry.sender).filter(Boolean)).size,
1260
- eventIds,
1261
- latestError,
1262
- windowMs: MATRIX_POST_HEALTHY_SYNC_DECRYPT_FAILURE_WINDOW_MS
1263
- }
1264
- };
1265
- } };
1266
- }
1267
- function formatMatrixSelfDecryptionHint(accountId) {
1268
- return `matrix: failed to decrypt a message from this same Matrix user. This usually means another Matrix device did not share the room key, or another DaoCore runtime is using the same account. Check 'daocore matrix verify status --verbose --account ${accountId}' and 'daocore matrix devices list --account ${accountId}'.`;
1269
- }
1270
- async function resolveMatrixSelfUserId(client, logVerboseMessage) {
1271
- if (typeof client.getUserId !== "function") return null;
1272
- try {
1273
- return await client.getUserId() ?? null;
1274
- } catch (err) {
1275
- logVerboseMessage(`matrix: failed resolving self user id for decrypt warning: ${String(err)}`);
1276
- return null;
1277
- }
1278
- }
1279
- function registerMatrixMonitorEvents(params) {
1280
- const { cfg, client, auth, allowFrom, dmEnabled, dmPolicy, readStoreAllowFrom, directTracker, logVerboseMessage, warnedEncryptedRooms, warnedCryptoMissingRooms, logger, startupGraceMs, getHealthySyncSinceMs, formatNativeDependencyHint, onRoomMessage, runDetachedTask, sasNoticeRetryDelayMs } = params;
1281
- const postHealthySyncDecryptFailureTracker = createMatrixPostHealthySyncDecryptFailureTracker({
1282
- getHealthySyncSinceMs,
1283
- startupGraceMs
1284
- });
1285
- const { routeVerificationEvent, routeVerificationSummary } = createMatrixVerificationEventRouter({
1286
- client,
1287
- allowFrom,
1288
- dmEnabled,
1289
- dmPolicy,
1290
- readStoreAllowFrom,
1291
- logVerboseMessage,
1292
- runDetachedTask,
1293
- sasNoticeRetryDelayMs
1294
- });
1295
- const runMonitorTask = (label, task) => {
1296
- if (runDetachedTask) return runDetachedTask(label, task);
1297
- return Promise.resolve().then(task).catch((error) => {
1298
- logVerboseMessage(`matrix: ${label} failed (${String(error)})`);
1299
- });
1300
- };
1301
- client.on("room.message", (roomId, event) => {
1302
- if (routeVerificationEvent(roomId, event)) return;
1303
- runMonitorTask(`room message handler room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1304
- await onRoomMessage(roomId, event);
1305
- });
1306
- });
1307
- client.on("room.encrypted_event", (roomId, event) => {
1308
- const eventId = event?.event_id ?? "unknown";
1309
- logVerboseMessage(`matrix: encrypted event room=${roomId} type=${event?.type ?? "unknown"} id=${eventId}`);
1310
- });
1311
- client.on("room.decrypted_event", (roomId, event) => {
1312
- const eventId = event?.event_id ?? "unknown";
1313
- const eventType = event?.type ?? "unknown";
1314
- logVerboseMessage(`matrix: decrypted event room=${roomId} type=${eventType} id=${eventId}`);
1315
- if (routeVerificationEvent(roomId, event)) return;
1316
- if (eventType !== EventType.RoomMessage) return;
1317
- runMonitorTask(`decrypted room message handler room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1318
- await onRoomMessage(roomId, event);
1319
- });
1320
- });
1321
- client.on("room.failed_decryption", async (roomId, event, error) => {
1322
- const failureState = postHealthySyncDecryptFailureTracker.recordFailure(roomId, event, error);
1323
- const selfUserId = await resolveMatrixSelfUserId(client, logVerboseMessage);
1324
- const sender = typeof event.sender === "string" ? event.sender : null;
1325
- const senderMatchesOwnUser = Boolean(selfUserId && sender && selfUserId === sender);
1326
- logger.warn(failureState.freshAfterHealthySync ? "Failed to decrypt fresh post-healthy-sync message" : "Failed to decrypt message", {
1327
- roomId,
1328
- eventId: event.event_id,
1329
- sender,
1330
- senderMatchesOwnUser,
1331
- error: error.message,
1332
- freshAfterHealthySync: failureState.freshAfterHealthySync,
1333
- ...failureState.freshAfterHealthySync ? { postHealthySyncFailureCount: failureState.failureCount } : {}
1334
- });
1335
- if (failureState.warning) logger.warn(formatMatrixPostHealthySyncDecryptionHint(auth.accountId), {
1336
- roomId,
1337
- eventId: event.event_id,
1338
- failureCount: failureState.failureCount,
1339
- roomCount: failureState.warning.roomCount,
1340
- rooms: failureState.warning.rooms,
1341
- senderCount: failureState.warning.senderCount,
1342
- senders: failureState.warning.senders,
1343
- sampleEventIds: failureState.warning.eventIds,
1344
- latestError: failureState.warning.latestError,
1345
- windowMs: failureState.warning.windowMs
1346
- });
1347
- if (senderMatchesOwnUser) logger.warn(formatMatrixSelfDecryptionHint(auth.accountId), {
1348
- roomId,
1349
- eventId: event.event_id,
1350
- sender
1351
- });
1352
- logVerboseMessage(`matrix: failed decrypt room=${roomId} id=${event.event_id ?? "unknown"} freshAfterHealthySync=${String(failureState.freshAfterHealthySync)} error=${error.message}`);
1353
- });
1354
- client.on("verification.summary", (summary) => {
1355
- runMonitorTask("verification summary handler", async () => {
1356
- await routeVerificationSummary(summary);
1357
- });
1358
- });
1359
- client.on("room.invite", (roomId, event) => {
1360
- directTracker?.invalidateRoom(roomId);
1361
- const eventId = event?.event_id ?? "unknown";
1362
- const sender = event?.sender ?? "unknown";
1363
- const invitee = normalizeOptionalString(event?.state_key) ?? "";
1364
- const senderIsInvitee = Boolean(invitee) && (normalizeOptionalString(event?.sender) ?? "") === invitee;
1365
- const isDirect = (event?.content)?.is_direct === true;
1366
- const rememberedSender = normalizeOptionalString(event?.sender);
1367
- if (rememberedSender && !senderIsInvitee) directTracker?.rememberInvite?.(roomId, rememberedSender);
1368
- logVerboseMessage(`matrix: invite room=${roomId} sender=${sender} direct=${String(isDirect)} id=${eventId}`);
1369
- });
1370
- client.on("room.join", (roomId, event) => {
1371
- directTracker?.invalidateRoom(roomId);
1372
- logVerboseMessage(`matrix: join room=${roomId} id=${event?.event_id ?? "unknown"}`);
1373
- });
1374
- client.on("room.event", (roomId, event) => {
1375
- const eventType = event?.type ?? "unknown";
1376
- if (eventType === EventType.RoomMessageEncrypted) {
1377
- logVerboseMessage(`matrix: encrypted raw event room=${roomId} id=${event?.event_id ?? "unknown"}`);
1378
- if (auth.encryption !== true && !warnedEncryptedRooms.has(roomId)) {
1379
- warnedEncryptedRooms.add(roomId);
1380
- const warning = formatMatrixEncryptedEventDisabledWarning(cfg, auth.accountId);
1381
- logger.warn(warning, { roomId });
1382
- }
1383
- if (auth.encryption === true && !client.crypto && !warnedCryptoMissingRooms.has(roomId)) {
1384
- warnedCryptoMissingRooms.add(roomId);
1385
- const warning = `matrix: encryption enabled but crypto is unavailable; ${formatNativeDependencyHint({
1386
- packageName: "@matrix-org/matrix-sdk-crypto-nodejs",
1387
- manager: "pnpm",
1388
- downloadCommand: "node node_modules/@matrix-org/matrix-sdk-crypto-nodejs/download-lib.js"
1389
- })}`;
1390
- logger.warn(warning, { roomId });
1391
- }
1392
- return;
1393
- }
1394
- if (eventType === EventType.RoomMember) {
1395
- directTracker?.invalidateRoom(roomId);
1396
- const membership = (event?.content)?.membership;
1397
- logVerboseMessage(`matrix: member event room=${roomId} stateKey=${event.state_key ?? ""} membership=${membership ?? "unknown"}`);
1398
- }
1399
- if (eventType === EventType.Reaction) {
1400
- runMonitorTask(`reaction handler room=${roomId} id=${event.event_id ?? "unknown"}`, async () => {
1401
- await onRoomMessage(roomId, event);
1402
- });
1403
- return;
1404
- }
1405
- routeVerificationEvent(roomId, event);
1406
- });
1407
- }
1408
- //#endregion
1409
- //#region extensions/matrix/src/matrix/monitor/ack-config.ts
1410
- function resolveMatrixAckReactionConfig(params) {
1411
- const matrixConfig = params.cfg.channels?.matrix;
1412
- const accountConfig = resolveMatrixAccountConfig({
1413
- cfg: params.cfg,
1414
- accountId: params.accountId
1415
- });
1416
- return {
1417
- ackReaction: resolveAckReaction(params.cfg, params.agentId, {
1418
- channel: "matrix",
1419
- accountId: params.accountId ?? void 0
1420
- }).trim(),
1421
- ackReactionScope: accountConfig.ackReactionScope ?? matrixConfig?.ackReactionScope ?? params.cfg.messages?.ackReactionScope ?? "group-mentions"
1422
- };
1423
- }
1424
- //#endregion
1425
- //#region extensions/matrix/src/matrix/monitor/location.ts
1426
- function decodeGeoUriParamValue(value) {
1427
- try {
1428
- return decodeURIComponent(value);
1429
- } catch {
1430
- return value;
1431
- }
1432
- }
1433
- function parseGeoUri(value) {
1434
- const trimmed = value.trim();
1435
- if (!trimmed) return null;
1436
- if (!normalizeLowercaseStringOrEmpty(trimmed).startsWith("geo:")) return null;
1437
- const [coordsPart, ...paramParts] = trimmed.slice(4).split(";");
1438
- const coords = coordsPart.split(",");
1439
- if (coords.length < 2) return null;
1440
- const latitude = Number.parseFloat(coords[0] ?? "");
1441
- const longitude = Number.parseFloat(coords[1] ?? "");
1442
- if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
1443
- const params = /* @__PURE__ */ new Map();
1444
- for (const part of paramParts) {
1445
- const segment = part.trim();
1446
- if (!segment) continue;
1447
- const eqIndex = segment.indexOf("=");
1448
- const rawKey = eqIndex === -1 ? segment : segment.slice(0, eqIndex);
1449
- const rawValue = eqIndex === -1 ? "" : segment.slice(eqIndex + 1);
1450
- const key = normalizeLowercaseStringOrEmpty(rawKey);
1451
- if (!key) continue;
1452
- const valuePart = rawValue.trim();
1453
- params.set(key, valuePart ? decodeGeoUriParamValue(valuePart) : "");
1454
- }
1455
- const accuracyRaw = params.get("u");
1456
- const accuracy = accuracyRaw ? Number.parseFloat(accuracyRaw) : void 0;
1457
- return {
1458
- latitude,
1459
- longitude,
1460
- accuracy: Number.isFinite(accuracy) ? accuracy : void 0
1461
- };
1462
- }
1463
- function resolveMatrixLocation(params) {
1464
- const { eventType, content } = params;
1465
- if (!(eventType === EventType.Location || eventType === EventType.RoomMessage && content.msgtype === EventType.Location)) return null;
1466
- const geoUri = normalizeOptionalString(content.geo_uri) ?? "";
1467
- if (!geoUri) return null;
1468
- const parsed = parseGeoUri(geoUri);
1469
- if (!parsed) return null;
1470
- const caption = normalizeOptionalString(content.body) ?? "";
1471
- const location = {
1472
- latitude: parsed.latitude,
1473
- longitude: parsed.longitude,
1474
- accuracy: parsed.accuracy,
1475
- caption: caption || void 0,
1476
- source: "pin",
1477
- isLive: false
1478
- };
1479
- return {
1480
- text: formatLocationText(location),
1481
- context: toLocationContext(location)
1482
- };
1483
- }
1484
- //#endregion
1485
- //#region extensions/matrix/src/matrix/monitor/media.ts
1486
- const MATRIX_MEDIA_DOWNLOAD_IDLE_TIMEOUT_MS = 3e4;
1487
- async function fetchMatrixMediaBuffer(params) {
1488
- try {
1489
- return { buffer: await params.client.downloadContent(params.mxcUrl, {
1490
- maxBytes: params.maxBytes,
1491
- readIdleTimeoutMs: MATRIX_MEDIA_DOWNLOAD_IDLE_TIMEOUT_MS
1492
- }) };
1493
- } catch (err) {
1494
- if (isMatrixMediaSizeLimitError(err)) throw err;
1495
- throw new Error(`Matrix media download failed: ${String(err)}`, { cause: err });
1496
- }
1497
- }
1498
- /**
1499
- * Download and decrypt encrypted media from a Matrix room.
1500
- * Uses the Matrix crypto adapter's decryptMedia helper.
1501
- */
1502
- async function fetchEncryptedMediaBuffer(params) {
1503
- if (!params.client.crypto) throw new Error("Cannot decrypt media: crypto not enabled");
1504
- const decrypted = await params.client.crypto.decryptMedia(params.file, {
1505
- maxBytes: params.maxBytes,
1506
- readIdleTimeoutMs: MATRIX_MEDIA_DOWNLOAD_IDLE_TIMEOUT_MS
1507
- });
1508
- if (decrypted.byteLength > params.maxBytes) throw new MatrixMediaSizeLimitError();
1509
- return { buffer: decrypted };
1510
- }
1511
- async function downloadMatrixMedia(params) {
1512
- let fetched;
1513
- if (typeof params.sizeBytes === "number" && params.sizeBytes > params.maxBytes) throw new MatrixMediaSizeLimitError();
1514
- if (params.file) fetched = await fetchEncryptedMediaBuffer({
1515
- client: params.client,
1516
- file: params.file,
1517
- maxBytes: params.maxBytes
1518
- });
1519
- else fetched = await fetchMatrixMediaBuffer({
1520
- client: params.client,
1521
- mxcUrl: params.mxcUrl,
1522
- maxBytes: params.maxBytes
1523
- });
1524
- if (!fetched) return null;
1525
- const headerType = params.contentType ?? void 0;
1526
- const saved = await getMatrixRuntime().channel.media.saveMediaBuffer(fetched.buffer, headerType, "inbound", params.maxBytes, params.originalFilename);
1527
- return {
1528
- path: saved.path,
1529
- contentType: saved.contentType,
1530
- placeholder: "[matrix media]"
1531
- };
1532
- }
1533
- //#endregion
1534
- //#region extensions/matrix/src/matrix/monitor/mentions.ts
1535
- const HTML_ENTITY_REPLACEMENTS = {
1536
- amp: "&",
1537
- apos: "'",
1538
- gt: ">",
1539
- lt: "<",
1540
- nbsp: " ",
1541
- quot: "\""
1542
- };
1543
- const MAX_UNICODE_SCALAR_VALUE = 1114111;
1544
- function decodeNumericHtmlEntity(match, rawValue, radix) {
1545
- const codePoint = Number.parseInt(rawValue, radix);
1546
- if (!Number.isSafeInteger(codePoint) || codePoint < 0 || codePoint > MAX_UNICODE_SCALAR_VALUE || codePoint >= 55296 && codePoint <= 57343) return match;
1547
- return String.fromCodePoint(codePoint);
1548
- }
1549
- function decodeHtmlEntities(value) {
1550
- return value.replace(/&(#x?[0-9a-f]+|\w+);/gi, (match, entity) => {
1551
- const normalized = normalizeLowercaseStringOrEmpty(entity);
1552
- if (normalized.startsWith("#x")) return decodeNumericHtmlEntity(match, normalized.slice(2), 16);
1553
- if (normalized.startsWith("#")) return decodeNumericHtmlEntity(match, normalized.slice(1), 10);
1554
- return HTML_ENTITY_REPLACEMENTS[normalized] ?? match;
1555
- });
1556
- }
1557
- function normalizeVisibleMentionText(value) {
1558
- return normalizeLowercaseStringOrEmpty(decodeHtmlEntities(value.replace(/<[^>]+>/g, " ").replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u206f]/g, "")).replace(/\s+/g, " "));
1559
- }
1560
- function extractVisibleMentionText(value) {
1561
- return normalizeVisibleMentionText(value ?? "");
1562
- }
1563
- function resolveMatrixUserLocalpart(userId) {
1564
- const trimmed = userId.trim();
1565
- if (!trimmed.startsWith("@")) return null;
1566
- const colonIndex = trimmed.indexOf(":");
1567
- if (colonIndex <= 1) return null;
1568
- return trimmed.slice(1, colonIndex).trim() || null;
1569
- }
1570
- function resolveMatrixMentionPrefixCandidates(params) {
1571
- const candidates = [];
1572
- const seen = /* @__PURE__ */ new Set();
1573
- const append = (candidate) => {
1574
- const trimmed = candidate?.trim();
1575
- if (!trimmed) return;
1576
- const normalized = normalizeLowercaseStringOrEmpty(trimmed);
1577
- if (seen.has(normalized)) return;
1578
- seen.add(normalized);
1579
- candidates.push(trimmed);
1580
- };
1581
- append(params.userId);
1582
- const localpart = params.userId ? resolveMatrixUserLocalpart(params.userId) : null;
1583
- append(localpart ? `@${localpart}` : null);
1584
- append(params.displayName);
1585
- append(params.displayName ? `@${params.displayName}` : null);
1586
- return candidates;
1587
- }
1588
- function stripMatchedMatrixMentionPrefix(text, pattern) {
1589
- const match = text.match(pattern);
1590
- if (!match) return null;
1591
- return text.slice(match[0].length).trimStart();
1592
- }
1593
- function stripNativeMatrixMentionPrefix(text, candidate) {
1594
- return stripMatchedMatrixMentionPrefix(text, new RegExp(`^\\s*${escapeRegExp(candidate)}(?:\\s*[:,])?(?:\\s+|$)`, "i"));
1595
- }
1596
- function stripRegexMatrixMentionPrefix(text, pattern) {
1597
- const flags = pattern.flags.replace(/[gy]/g, "");
1598
- return stripMatchedMatrixMentionPrefix(text, new RegExp(`^\\s*(?:${pattern.source})(?:\\s*[:,])?(?:\\s+|$)`, flags));
1599
- }
1600
- function stripMatrixMentionPrefix(params) {
1601
- const text = params.text;
1602
- if (!text) return text;
1603
- for (const candidate of resolveMatrixMentionPrefixCandidates(params)) {
1604
- const stripped = stripNativeMatrixMentionPrefix(text, candidate);
1605
- if (stripped !== null) return stripped;
1606
- }
1607
- for (const pattern of params.mentionRegexes ?? []) {
1608
- const stripped = stripRegexMatrixMentionPrefix(text, pattern);
1609
- if (stripped !== null) return stripped;
1610
- }
1611
- return text;
1612
- }
1613
- function isVisibleMentionLabel(params) {
1614
- const cleaned = extractVisibleMentionText(params.text);
1615
- if (!cleaned) return false;
1616
- if (params.mentionRegexes.some((pattern) => pattern.test(cleaned))) return true;
1617
- const localpart = resolveMatrixUserLocalpart(params.userId);
1618
- return [
1619
- extractVisibleMentionText(params.userId),
1620
- localpart ? extractVisibleMentionText(localpart) : null,
1621
- localpart ? extractVisibleMentionText(`@${localpart}`) : null,
1622
- params.displayName ? extractVisibleMentionText(params.displayName) : null,
1623
- params.displayName ? extractVisibleMentionText(`@${params.displayName}`) : null
1624
- ].filter((value) => Boolean(value)).includes(cleaned);
1625
- }
1626
- function hasVisibleRoomMention(value) {
1627
- const cleaned = extractVisibleMentionText(value);
1628
- return /(^|[^a-z0-9_])@room\b/i.test(cleaned);
1629
- }
1630
- /**
1631
- * Check if formatted_body contains a matrix.to link whose visible label still
1632
- * looks like a real mention for the given user. Do not trust href alone, since
1633
- * senders can hide arbitrary matrix.to links behind unrelated link text.
1634
- * Many Matrix clients (including Element) use HTML links in formatted_body instead of
1635
- * or in addition to the m.mentions field.
1636
- */
1637
- function checkFormattedBodyMention(params) {
1638
- if (!params.formattedBody || !params.userId) return false;
1639
- for (const match of params.formattedBody.matchAll(/<a\b[^>]*href=(["'])(https:\/\/matrix\.to\/#[^"']+)\1[^>]*>(.*?)<\/a>/gis)) {
1640
- const href = match[2];
1641
- const visibleLabel = match[3] ?? "";
1642
- if (!href) continue;
1643
- try {
1644
- const parsed = new URL(href);
1645
- if (decodeURIComponent(parsed.hash.replace(/^#\/?/, "").trim()) !== params.userId.trim()) continue;
1646
- if (isVisibleMentionLabel({
1647
- text: visibleLabel,
1648
- userId: params.userId,
1649
- mentionRegexes: params.mentionRegexes,
1650
- displayName: params.displayName
1651
- })) return true;
1652
- } catch {
1653
- continue;
1654
- }
1655
- }
1656
- return false;
1657
- }
1658
- function resolveMentions(params) {
1659
- const mentions = params.content["m.mentions"];
1660
- const mentionedUsers = Array.isArray(mentions?.user_ids) ? new Set(mentions.user_ids) : /* @__PURE__ */ new Set();
1661
- const textMentioned = getMatrixRuntime().channel.mentions.matchesMentionPatterns(params.text ?? "", params.mentionRegexes);
1662
- const visibleRoomMention = hasVisibleRoomMention(params.text) || hasVisibleRoomMention(params.content.formatted_body);
1663
- const mentionedInFormattedBody = params.userId ? checkFormattedBodyMention({
1664
- formattedBody: params.content.formatted_body,
1665
- userId: params.userId,
1666
- displayName: params.displayName,
1667
- mentionRegexes: params.mentionRegexes
1668
- }) : false;
1669
- const metadataBackedUserMention = Boolean(params.userId && mentionedUsers.has(params.userId) && (mentionedInFormattedBody || textMentioned));
1670
- const metadataBackedRoomMention = Boolean(mentions?.room) && visibleRoomMention;
1671
- const explicitMention = mentionedInFormattedBody || metadataBackedUserMention || metadataBackedRoomMention;
1672
- return {
1673
- wasMentioned: explicitMention || textMentioned || visibleRoomMention,
1674
- hasExplicitMention: explicitMention
1675
- };
1676
- }
1677
- //#endregion
1678
- //#region extensions/matrix/src/matrix/monitor/replies.ts
1679
- const THINKING_TAG_RE = /<\s*\/?\s*(?:think(?:ing)?|thought|antthinking)\b[^<>]*>/gi;
1680
- const THINKING_BLOCK_RE = /<\s*(?:think(?:ing)?|thought|antthinking)\b[^<>]*>[\s\S]*?<\s*\/\s*(?:think(?:ing)?|thought|antthinking)\s*>/gi;
1681
- function shouldSuppressReasoningReplyText(text) {
1682
- if (typeof text !== "string") return false;
1683
- const trimmedStart = text.trimStart();
1684
- if (!trimmedStart) return false;
1685
- if (normalizeLowercaseStringOrEmpty(trimmedStart).startsWith("reasoning:")) return true;
1686
- THINKING_TAG_RE.lastIndex = 0;
1687
- if (!THINKING_TAG_RE.test(text)) return false;
1688
- THINKING_BLOCK_RE.lastIndex = 0;
1689
- const withoutThinkingBlocks = text.replace(THINKING_BLOCK_RE, "");
1690
- THINKING_TAG_RE.lastIndex = 0;
1691
- return !withoutThinkingBlocks.replace(THINKING_TAG_RE, "").trim();
1692
- }
1693
- async function deliverMatrixReplies(params) {
1694
- const core = getMatrixRuntime();
1695
- const tableMode = params.tableMode ?? core.channel.text.resolveMarkdownTableMode({
1696
- cfg: params.cfg,
1697
- channel: "matrix",
1698
- accountId: params.accountId
1699
- });
1700
- const logVerbose = (message) => {
1701
- if (core.logging.shouldLogVerbose()) params.runtime.log?.(message);
1702
- };
1703
- let hasReplied = false;
1704
- let deliveredAny = false;
1705
- for (const reply of params.replies) {
1706
- if (reply.isReasoning === true || shouldSuppressReasoningReplyText(reply.text)) {
1707
- logVerbose("matrix reply suppressed as reasoning-only");
1708
- continue;
1709
- }
1710
- const hasMedia = Boolean(reply?.mediaUrl) || (reply?.mediaUrls?.length ?? 0) > 0;
1711
- if (!reply?.text && !hasMedia) {
1712
- if (reply?.audioAsVoice) {
1713
- logVerbose("matrix reply has audioAsVoice without media/text; skipping");
1714
- continue;
1715
- }
1716
- params.runtime.error?.("matrix reply missing text/media");
1717
- continue;
1718
- }
1719
- const replyToIdRaw = reply.replyToId?.trim();
1720
- const replyToId = params.threadId || params.replyToMode === "off" ? void 0 : replyToIdRaw;
1721
- const rawText = reply.text ?? "";
1722
- const mediaList = reply.mediaUrls?.length ? reply.mediaUrls : reply.mediaUrl ? [reply.mediaUrl] : [];
1723
- const shouldIncludeReply = (id) => Boolean(id) && (params.replyToMode === "all" || !hasReplied);
1724
- const replyToIdForReply = shouldIncludeReply(replyToId) ? replyToId : void 0;
1725
- if (mediaList.length === 0) {
1726
- let sentTextChunk = false;
1727
- const { chunks } = chunkMatrixText(rawText, {
1728
- cfg: params.cfg,
1729
- accountId: params.accountId,
1730
- tableMode
1731
- });
1732
- for (const chunk of chunks) {
1733
- const trimmed = chunk.trim();
1734
- if (!trimmed) continue;
1735
- await sendMessageMatrix(params.roomId, trimmed, {
1736
- client: params.client,
1737
- cfg: params.cfg,
1738
- replyToId: replyToIdForReply,
1739
- threadId: params.threadId,
1740
- accountId: params.accountId
1741
- });
1742
- deliveredAny = true;
1743
- sentTextChunk = true;
1744
- }
1745
- if (replyToIdForReply && !hasReplied && sentTextChunk) hasReplied = true;
1746
- continue;
1747
- }
1748
- let first = true;
1749
- for (const mediaUrl of mediaList) {
1750
- const caption = first ? rawText : "";
1751
- await sendMessageMatrix(params.roomId, caption, {
1752
- client: params.client,
1753
- cfg: params.cfg,
1754
- mediaUrl,
1755
- mediaLocalRoots: params.mediaLocalRoots,
1756
- replyToId: replyToIdForReply,
1757
- threadId: params.threadId,
1758
- audioAsVoice: reply.audioAsVoice,
1759
- accountId: params.accountId
1760
- });
1761
- deliveredAny = true;
1762
- first = false;
1763
- }
1764
- if (replyToIdForReply && !hasReplied) hasReplied = true;
1765
- }
1766
- return deliveredAny;
1767
- }
1768
- //#endregion
1769
- //#region extensions/matrix/src/matrix/monitor/context-summary.ts
1770
- function trimMatrixMaybeString(value) {
1771
- if (typeof value !== "string") return;
1772
- return value.trim() || void 0;
1773
- }
1774
- function summarizeMatrixMessageContextEvent(event) {
1775
- if (isPollStartType(event.type)) {
1776
- const pollSummary = parsePollStartContent(event.content);
1777
- if (pollSummary) return formatPollAsText(pollSummary);
1778
- }
1779
- const content = event.content;
1780
- return formatMatrixMessageText({
1781
- body: resolveMatrixMessageBody({
1782
- body: trimMatrixMaybeString(content.body),
1783
- filename: trimMatrixMaybeString(content.filename),
1784
- msgtype: trimMatrixMaybeString(content.msgtype)
1785
- }),
1786
- attachment: resolveMatrixMessageAttachment({
1787
- body: trimMatrixMaybeString(content.body),
1788
- filename: trimMatrixMaybeString(content.filename),
1789
- msgtype: trimMatrixMaybeString(content.msgtype)
1790
- })
1791
- });
1792
- }
1793
- //#endregion
1794
- //#region extensions/matrix/src/matrix/monitor/reply-context.ts
1795
- const MAX_CACHED_REPLY_CONTEXTS = 256;
1796
- const MAX_REPLY_BODY_LENGTH = 500;
1797
- function truncateReplyBody(value) {
1798
- if (value.length <= MAX_REPLY_BODY_LENGTH) return value;
1799
- return `${value.slice(0, MAX_REPLY_BODY_LENGTH - 3)}...`;
1800
- }
1801
- function summarizeMatrixReplyEvent(event) {
1802
- const body = summarizeMatrixMessageContextEvent(event);
1803
- return body ? truncateReplyBody(body) : void 0;
1804
- }
1805
- /**
1806
- * Creates a cached resolver that fetches the body and sender of a replied-to
1807
- * Matrix event. This allows the agent to see the content of the message being
1808
- * replied to, not just its event ID.
1809
- */
1810
- function createMatrixReplyContextResolver(params) {
1811
- const cache = /* @__PURE__ */ new Map();
1812
- const remember = (key, value) => {
1813
- cache.set(key, value);
1814
- if (cache.size > MAX_CACHED_REPLY_CONTEXTS) {
1815
- const oldest = cache.keys().next().value;
1816
- if (typeof oldest === "string") cache.delete(oldest);
1817
- }
1818
- return value;
1819
- };
1820
- return async (input) => {
1821
- const cacheKey = `${input.roomId}:${input.eventId}`;
1822
- const cached = cache.get(cacheKey);
1823
- if (cached) {
1824
- cache.delete(cacheKey);
1825
- cache.set(cacheKey, cached);
1826
- return cached;
1827
- }
1828
- const event = await params.client.getEvent(input.roomId, input.eventId).catch((err) => {
1829
- params.logVerboseMessage(`matrix: failed resolving reply context room=${input.roomId} id=${input.eventId}: ${String(err)}`);
1830
- return null;
1831
- });
1832
- if (!event) return {};
1833
- const rawEvent = event;
1834
- if (rawEvent.unsigned?.redacted_because) return remember(cacheKey, {});
1835
- const replyToBody = summarizeMatrixReplyEvent(rawEvent);
1836
- if (!replyToBody) return remember(cacheKey, {});
1837
- const senderId = trimMatrixMaybeString(rawEvent.sender);
1838
- return remember(cacheKey, {
1839
- replyToBody,
1840
- replyToSender: (senderId && await params.getMemberDisplayName(input.roomId, senderId).catch(() => void 0)) ?? senderId,
1841
- replyToSenderId: senderId
1842
- });
1843
- };
1844
- }
1845
- //#endregion
1846
- //#region extensions/matrix/src/matrix/monitor/room-history.ts
1847
- /** Maximum entries retained per room (hard cap to bound memory). */
1848
- const DEFAULT_MAX_QUEUE_SIZE = 200;
1849
- /** Maximum number of rooms to retain queues for (FIFO eviction beyond this). */
1850
- const DEFAULT_MAX_ROOM_QUEUES = 1e3;
1851
- /** Maximum number of (agentId, roomId) watermark entries to retain. */
1852
- const MAX_WATERMARK_ENTRIES = 5e3;
1853
- /** Maximum prepared trigger snapshots retained per room for retry reuse. */
1854
- const MAX_PREPARED_TRIGGER_ENTRIES = 500;
1855
- function createRoomHistoryTrackerInternal(maxQueueSize = DEFAULT_MAX_QUEUE_SIZE, maxRoomQueues = DEFAULT_MAX_ROOM_QUEUES, maxWatermarkEntries = MAX_WATERMARK_ENTRIES, maxPreparedTriggerEntries = MAX_PREPARED_TRIGGER_ENTRIES) {
1856
- const roomQueues = /* @__PURE__ */ new Map();
1857
- /** Maps `${agentId}:${roomId}` → absolute consumed-up-to index */
1858
- const agentWatermarks = /* @__PURE__ */ new Map();
1859
- let nextQueueGeneration = 1;
1860
- function clearRoomWatermarks(roomId) {
1861
- const roomSuffix = `:${roomId}`;
1862
- for (const key of agentWatermarks.keys()) if (key.endsWith(roomSuffix)) agentWatermarks.delete(key);
1863
- }
1864
- function getOrCreateQueue(roomId) {
1865
- let queue = roomQueues.get(roomId);
1866
- if (!queue) {
1867
- queue = {
1868
- entries: [],
1869
- baseIndex: 0,
1870
- generation: nextQueueGeneration++,
1871
- preparedTriggers: /* @__PURE__ */ new Map()
1872
- };
1873
- roomQueues.set(roomId, queue);
1874
- if (roomQueues.size > maxRoomQueues) {
1875
- const oldest = roomQueues.keys().next().value;
1876
- if (oldest !== void 0) {
1877
- roomQueues.delete(oldest);
1878
- clearRoomWatermarks(oldest);
1879
- }
1880
- }
1881
- }
1882
- return queue;
1883
- }
1884
- function appendToQueue(queue, entry) {
1885
- queue.entries.push(entry);
1886
- if (queue.entries.length > maxQueueSize) {
1887
- const overflow = queue.entries.length - maxQueueSize;
1888
- queue.entries.splice(0, overflow);
1889
- queue.baseIndex += overflow;
1890
- }
1891
- return {
1892
- snapshotIdx: queue.baseIndex + queue.entries.length,
1893
- queueGeneration: queue.generation
1894
- };
1895
- }
1896
- function wmKey(agentId, roomId) {
1897
- return `${agentId}:${roomId}`;
1898
- }
1899
- function preparedTriggerKey(agentId, messageId) {
1900
- if (!messageId?.trim()) return null;
1901
- return `${agentId}:${messageId.trim()}`;
1902
- }
1903
- function rememberWatermark(key, snapshotIdx) {
1904
- const nextSnapshotIdx = Math.max(agentWatermarks.get(key) ?? 0, snapshotIdx);
1905
- if (agentWatermarks.has(key)) agentWatermarks.delete(key);
1906
- agentWatermarks.set(key, nextSnapshotIdx);
1907
- if (agentWatermarks.size > maxWatermarkEntries) {
1908
- const oldest = agentWatermarks.keys().next().value;
1909
- if (oldest !== void 0) agentWatermarks.delete(oldest);
1910
- }
1911
- }
1912
- function rememberPreparedTrigger(queue, retryKey, prepared) {
1913
- if (queue.preparedTriggers.has(retryKey)) queue.preparedTriggers.delete(retryKey);
1914
- queue.preparedTriggers.set(retryKey, prepared);
1915
- if (queue.preparedTriggers.size > maxPreparedTriggerEntries) {
1916
- const oldest = queue.preparedTriggers.keys().next().value;
1917
- if (oldest !== void 0) queue.preparedTriggers.delete(oldest);
1918
- }
1919
- return prepared;
1920
- }
1921
- function computePendingHistory(queue, agentId, roomId, limit) {
1922
- if (limit <= 0 || queue.entries.length === 0) return [];
1923
- const wm = agentWatermarks.get(wmKey(agentId, roomId)) ?? 0;
1924
- const startRel = Math.max(wm, queue.baseIndex) - queue.baseIndex;
1925
- const available = queue.entries.slice(startRel);
1926
- return available.length > limit ? available.slice(-limit) : available;
1927
- }
1928
- return {
1929
- recordPending(roomId, entry) {
1930
- appendToQueue(getOrCreateQueue(roomId), entry);
1931
- },
1932
- getPendingHistory(agentId, roomId, limit) {
1933
- const queue = roomQueues.get(roomId);
1934
- if (!queue) return [];
1935
- return computePendingHistory(queue, agentId, roomId, limit);
1936
- },
1937
- recordTrigger(roomId, entry) {
1938
- return appendToQueue(getOrCreateQueue(roomId), entry);
1939
- },
1940
- prepareTrigger(agentId, roomId, limit, entry) {
1941
- const queue = getOrCreateQueue(roomId);
1942
- const retryKey = preparedTriggerKey(agentId, entry.messageId);
1943
- if (retryKey) {
1944
- const prepared = queue.preparedTriggers.get(retryKey);
1945
- if (prepared) return rememberPreparedTrigger(queue, retryKey, prepared);
1946
- }
1947
- const prepared = {
1948
- history: computePendingHistory(queue, agentId, roomId, limit),
1949
- ...appendToQueue(queue, entry)
1950
- };
1951
- if (retryKey) return rememberPreparedTrigger(queue, retryKey, prepared);
1952
- return prepared;
1953
- },
1954
- consumeHistory(agentId, roomId, snapshot, messageId) {
1955
- const key = wmKey(agentId, roomId);
1956
- const queue = roomQueues.get(roomId);
1957
- if (!queue) {
1958
- agentWatermarks.delete(key);
1959
- return;
1960
- }
1961
- if (queue.generation !== snapshot.queueGeneration) return;
1962
- rememberWatermark(key, snapshot.snapshotIdx);
1963
- const retryKey = preparedTriggerKey(agentId, messageId);
1964
- if (queue && retryKey) queue.preparedTriggers.delete(retryKey);
1965
- }
1966
- };
1967
- }
1968
- function createRoomHistoryTracker(maxQueueSize = DEFAULT_MAX_QUEUE_SIZE, maxRoomQueues = DEFAULT_MAX_ROOM_QUEUES, maxWatermarkEntries = MAX_WATERMARK_ENTRIES, maxPreparedTriggerEntries = MAX_PREPARED_TRIGGER_ENTRIES) {
1969
- const tracker = createRoomHistoryTrackerInternal(maxQueueSize, maxRoomQueues, maxWatermarkEntries, maxPreparedTriggerEntries);
1970
- return {
1971
- recordPending: tracker.recordPending,
1972
- prepareTrigger: tracker.prepareTrigger,
1973
- consumeHistory: tracker.consumeHistory
1974
- };
1975
- }
1976
- //#endregion
1977
- //#region extensions/matrix/src/matrix/monitor/thread-context.ts
1978
- const MAX_TRACKED_THREAD_STARTERS = 256;
1979
- const MAX_THREAD_STARTER_BODY_LENGTH = 500;
1980
- function truncateThreadStarterBody(value) {
1981
- if (value.length <= MAX_THREAD_STARTER_BODY_LENGTH) return value;
1982
- return `${value.slice(0, MAX_THREAD_STARTER_BODY_LENGTH - 3)}...`;
1983
- }
1984
- function summarizeMatrixThreadStarterEvent(event) {
1985
- const body = summarizeMatrixMessageContextEvent(event);
1986
- if (body) return truncateThreadStarterBody(body);
1987
- const content = event.content;
1988
- const msgtype = trimMatrixMaybeString(content.msgtype);
1989
- if (msgtype) return `Matrix ${msgtype} message`;
1990
- const eventType = trimMatrixMaybeString(event.type);
1991
- return eventType ? `Matrix ${eventType} event` : void 0;
1992
- }
1993
- function formatMatrixThreadStarterBody(params) {
1994
- const senderLabel = params.senderName ?? params.senderId ?? "unknown sender";
1995
- const lines = [`Matrix thread root ${params.threadRootId} from ${senderLabel}:`];
1996
- if (params.summary) lines.push(params.summary);
1997
- return lines.join("\n");
1998
- }
1999
- function createMatrixThreadContextResolver(params) {
2000
- const cache = /* @__PURE__ */ new Map();
2001
- const remember = (key, value) => {
2002
- cache.set(key, value);
2003
- if (cache.size > MAX_TRACKED_THREAD_STARTERS) {
2004
- const oldest = cache.keys().next().value;
2005
- if (typeof oldest === "string") cache.delete(oldest);
2006
- }
2007
- return value;
2008
- };
2009
- return async (input) => {
2010
- const cacheKey = `${input.roomId}:${input.threadRootId}`;
2011
- const cached = cache.get(cacheKey);
2012
- if (cached) return cached;
2013
- const rootEvent = await params.client.getEvent(input.roomId, input.threadRootId).catch((err) => {
2014
- params.logVerboseMessage(`matrix: failed resolving thread root room=${input.roomId} id=${input.threadRootId}: ${String(err)}`);
2015
- return null;
2016
- });
2017
- if (!rootEvent) return { threadStarterBody: `Matrix thread root ${input.threadRootId}` };
2018
- const rawEvent = rootEvent;
2019
- const senderId = trimMatrixMaybeString(rawEvent.sender);
2020
- const senderName = senderId && await params.getMemberDisplayName(input.roomId, senderId).catch(() => void 0);
2021
- const senderLabel = senderName ?? senderId;
2022
- const summary = summarizeMatrixThreadStarterEvent(rawEvent);
2023
- return remember(cacheKey, {
2024
- threadStarterBody: formatMatrixThreadStarterBody({
2025
- threadRootId: input.threadRootId,
2026
- senderId,
2027
- senderName,
2028
- summary
2029
- }),
2030
- senderId,
2031
- senderLabel,
2032
- summary
2033
- });
2034
- };
2035
- }
2036
- //#endregion
2037
- //#region extensions/matrix/src/matrix/monitor/handler.ts
2038
- const ALLOW_FROM_STORE_CACHE_TTL_MS = 3e4;
2039
- const PAIRING_REPLY_COOLDOWN_MS = 5 * 6e4;
2040
- const MATRIX_TOOL_PROGRESS_MAX_CHARS = 300;
2041
- let matrixSendModulePromise;
2042
- let acpBindingRuntimePromise;
2043
- let sessionBindingRuntimePromise;
2044
- let matrixReactionEventsPromise;
2045
- let matrixDraftStreamPromise;
2046
- function loadMatrixSendModule() {
2047
- matrixSendModulePromise ??= import("./send-sZ40sJXS.js");
2048
- return matrixSendModulePromise;
2049
- }
2050
- function loadAcpBindingRuntime() {
2051
- acpBindingRuntimePromise ??= import("./plugin-sdk/acp-binding-runtime.js");
2052
- return acpBindingRuntimePromise;
2053
- }
2054
- function loadSessionBindingRuntime() {
2055
- sessionBindingRuntimePromise ??= import("./plugin-sdk/session-binding-runtime.js");
2056
- return sessionBindingRuntimePromise;
2057
- }
2058
- function loadMatrixReactionEvents() {
2059
- matrixReactionEventsPromise ??= import("./reaction-events-tMCLsscl.js");
2060
- return matrixReactionEventsPromise;
2061
- }
2062
- function loadMatrixDraftStream() {
2063
- matrixDraftStreamPromise ??= import("./draft-stream-oH6q8cSR.js");
2064
- return matrixDraftStreamPromise;
2065
- }
2066
- const MAX_TRACKED_PAIRING_REPLY_SENDERS = 512;
2067
- const MAX_TRACKED_SHARED_DM_CONTEXT_NOTICES = 512;
2068
- var MatrixRetryableInboundError = class extends Error {
2069
- constructor(message, options) {
2070
- super(message, options);
2071
- this.name = "MatrixRetryableInboundError";
2072
- }
2073
- };
2074
- async function redactMatrixDraftEvent(client, roomId, draftEventId) {
2075
- await client.redactEvent(roomId, draftEventId).catch(() => {});
2076
- }
2077
- function buildMatrixFinalizedPreviewContent() {
2078
- return { [MATRIX_DAOCORE_FINALIZED_PREVIEW_KEY]: true };
2079
- }
2080
- function resolveMatrixMentionPrecheckText(params) {
2081
- if (params.locationText?.trim()) return params.locationText.trim();
2082
- if (typeof params.content.body === "string" && params.content.body.trim()) return params.content.body.trim();
2083
- if (isPollStartType(params.eventType)) {
2084
- const parsed = parsePollStartContent(params.content);
2085
- if (parsed) return formatPollAsText(parsed);
2086
- }
2087
- return "";
2088
- }
2089
- function hasBundledMatrixReplacementRelation(event) {
2090
- const relations = event.unsigned?.["m.relations"];
2091
- if (!relations || typeof relations !== "object") return false;
2092
- return relations[RelationType.Replace] !== void 0;
2093
- }
2094
- function resolveMatrixInboundBodyText(params) {
2095
- if (params.mediaPlaceholder) return params.rawBody || params.mediaPlaceholder;
2096
- if (!params.mediaDownloadFailed || !params.hadMediaUrl) return params.rawBody;
2097
- if (params.mediaSizeLimitExceeded) return formatMatrixMediaTooLargeText({
2098
- body: params.rawBody,
2099
- filename: params.filename,
2100
- msgtype: params.msgtype
2101
- });
2102
- return formatMatrixMediaUnavailableText({
2103
- body: params.rawBody,
2104
- filename: params.filename,
2105
- msgtype: params.msgtype
2106
- });
2107
- }
2108
- function markTrackedRoomIfFirst(set, roomId) {
2109
- if (set.has(roomId)) return false;
2110
- set.add(roomId);
2111
- if (set.size > MAX_TRACKED_SHARED_DM_CONTEXT_NOTICES) {
2112
- const oldest = set.keys().next().value;
2113
- if (typeof oldest === "string") set.delete(oldest);
2114
- }
2115
- return true;
2116
- }
2117
- function resolveMatrixSharedDmContextNotice(params) {
2118
- if ((params.dmSessionScope ?? "per-user") === "per-room") return null;
2119
- if (params.sentRooms.has(params.roomId)) return null;
2120
- try {
2121
- const currentSession = resolveMatrixStoredSessionMeta(resolveSessionStoreEntry({
2122
- store: loadSessionStore(params.storePath),
2123
- sessionKey: params.sessionKey
2124
- }).existing);
2125
- if (!currentSession) return null;
2126
- if (currentSession.channel && currentSession.channel !== "matrix") return null;
2127
- if (currentSession.accountId && currentSession.accountId !== params.accountId) return null;
2128
- if (!currentSession.directUserId) return null;
2129
- if (!currentSession.roomId || currentSession.roomId === params.roomId) return null;
2130
- return [
2131
- "This Matrix DM is sharing a session with another Matrix DM room.",
2132
- "Use /focus here for a one-off isolated thread session when thread bindings are enabled, or set",
2133
- "channels.matrix.dm.sessionScope to per-room to isolate each Matrix DM room."
2134
- ].join(" ");
2135
- } catch (err) {
2136
- params.logVerboseMessage(`matrix: failed checking shared DM session notice room=${params.roomId} (${String(err)})`);
2137
- return null;
2138
- }
2139
- }
2140
- function resolveMatrixPendingHistoryText(params) {
2141
- if (params.mentionPrecheckText) return params.mentionPrecheckText;
2142
- if (!params.mediaUrl) return "";
2143
- const body = typeof params.content.body === "string" ? params.content.body.trim() : void 0;
2144
- const filename = typeof params.content.filename === "string" ? params.content.filename.trim() : void 0;
2145
- const msgtype = typeof params.content.msgtype === "string" ? params.content.msgtype : void 0;
2146
- return formatMatrixMessageText({
2147
- body: resolveMatrixMessageBody({
2148
- body,
2149
- filename,
2150
- msgtype
2151
- }),
2152
- attachment: resolveMatrixMessageAttachment({
2153
- body,
2154
- filename,
2155
- msgtype
2156
- })
2157
- }) ?? "";
2158
- }
2159
- function resolveMatrixAllowBotsMode(value) {
2160
- if (value === true) return "all";
2161
- if (value === "mentions") return "mentions";
2162
- return "off";
2163
- }
2164
- function formatMatrixToolProgressMarkdownCode(text) {
2165
- return `\`${(text.length <= MATRIX_TOOL_PROGRESS_MAX_CHARS ? text : `${text.slice(0, MATRIX_TOOL_PROGRESS_MAX_CHARS - 1).trimEnd()}...`).replaceAll("`", "'")}\``;
2166
- }
2167
- function createMatrixRoomMessageHandler(params) {
2168
- const { client, core, cfg, accountId, accountConfig, runtime, logger, logVerboseMessage, allowFromResolvedEntries = [], groupAllowFromResolvedEntries = [], roomsConfig, accountAllowBots, configuredBotUserIds = /* @__PURE__ */ new Set(), groupPolicy, replyToMode, threadReplies, dmThreadReplies, dmSessionScope, streaming, previewToolProgressEnabled, blockStreamingEnabled, dmEnabled, dmPolicy, textLimit, mediaMaxBytes, historyLimit, startupMs, startupGraceMs, dropPreStartupMessages, inboundDeduper, directTracker, getRoomInfo, getMemberDisplayName, needsRoomAliasesForConfig, resolveLiveUserAllowlist = resolveMatrixMonitorLiveUserAllowlist } = params;
2169
- const contextVisibilityMode = resolveChannelContextVisibilityMode({
2170
- cfg,
2171
- channel: "matrix",
2172
- accountId
2173
- });
2174
- let cachedStoreAllowFrom = null;
2175
- let liveDmAllowlistCache = null;
2176
- let liveGroupAllowlistCache = null;
2177
- const resolveCachedLiveAllowlist = async (params) => {
2178
- const accountConfig = resolveMatrixAccountConfig({
2179
- cfg: params.cfg,
2180
- accountId
2181
- });
2182
- const signature = JSON.stringify({
2183
- entries: (params.entries ?? []).map((entry) => String(entry).trim()),
2184
- failClosedOnUnresolved: params.failClosedOnUnresolved === true,
2185
- dangerouslyAllowNameMatching: isDangerousNameMatchingEnabled(accountConfig)
2186
- });
2187
- if (params.cache?.signature === signature) return params.cache.entries;
2188
- const entries = await resolveLiveUserAllowlist({
2189
- cfg: params.cfg,
2190
- accountId,
2191
- entries: params.entries,
2192
- failClosedOnUnresolved: params.failClosedOnUnresolved,
2193
- startupResolvedEntries: params.startupResolvedEntries,
2194
- runtime
2195
- });
2196
- const next = {
2197
- signature,
2198
- entries
2199
- };
2200
- params.updateCache(next);
2201
- return entries;
2202
- };
2203
- const pairingReplySentAtMsBySender = /* @__PURE__ */ new Map();
2204
- const resolveThreadContext = createMatrixThreadContextResolver({
2205
- client,
2206
- getMemberDisplayName,
2207
- logVerboseMessage
2208
- });
2209
- const resolveReplyContext = createMatrixReplyContextResolver({
2210
- client,
2211
- getMemberDisplayName,
2212
- logVerboseMessage
2213
- });
2214
- const roomHistoryTracker = createRoomHistoryTracker();
2215
- const roomIngressTails = /* @__PURE__ */ new Map();
2216
- const sharedDmContextNoticeRooms = /* @__PURE__ */ new Set();
2217
- const readStoreAllowFrom = async () => {
2218
- const now = Date.now();
2219
- if (cachedStoreAllowFrom && now < cachedStoreAllowFrom.expiresAtMs) return cachedStoreAllowFrom.value;
2220
- const value = await core.channel.pairing.readAllowFromStore({
2221
- channel: "matrix",
2222
- env: process.env,
2223
- accountId
2224
- }).catch(() => []);
2225
- cachedStoreAllowFrom = {
2226
- value,
2227
- expiresAtMs: now + ALLOW_FROM_STORE_CACHE_TTL_MS
2228
- };
2229
- return value;
2230
- };
2231
- const shouldSendPairingReply = (senderId, created) => {
2232
- const now = Date.now();
2233
- if (created) {
2234
- pairingReplySentAtMsBySender.set(senderId, now);
2235
- return true;
2236
- }
2237
- const lastSentAtMs = pairingReplySentAtMsBySender.get(senderId);
2238
- if (typeof lastSentAtMs === "number" && now - lastSentAtMs < PAIRING_REPLY_COOLDOWN_MS) return false;
2239
- pairingReplySentAtMsBySender.set(senderId, now);
2240
- if (pairingReplySentAtMsBySender.size > MAX_TRACKED_PAIRING_REPLY_SENDERS) {
2241
- const oldestSender = pairingReplySentAtMsBySender.keys().next().value;
2242
- if (typeof oldestSender === "string") pairingReplySentAtMsBySender.delete(oldestSender);
2243
- }
2244
- return true;
2245
- };
2246
- const runRoomIngress = async (roomId, task) => {
2247
- const previous = roomIngressTails.get(roomId) ?? Promise.resolve();
2248
- let releaseCurrent;
2249
- const current = new Promise((resolve) => {
2250
- releaseCurrent = resolve;
2251
- });
2252
- const chain = previous.catch(() => {}).then(() => current);
2253
- roomIngressTails.set(roomId, chain);
2254
- await previous.catch(() => {});
2255
- try {
2256
- return await task();
2257
- } finally {
2258
- releaseCurrent();
2259
- if (roomIngressTails.get(roomId) === chain) roomIngressTails.delete(roomId);
2260
- }
2261
- };
2262
- return async (roomId, event) => {
2263
- const eventId = typeof event.event_id === "string" ? event.event_id.trim() : "";
2264
- let claimedInboundEvent = false;
2265
- let draftStreamRef;
2266
- let draftConsumed = false;
2267
- try {
2268
- const eventType = event.type;
2269
- if (eventType === EventType.RoomMessageEncrypted) return;
2270
- const isPollEvent = isPollEventType(eventType);
2271
- const isReactionEvent = eventType === EventType.Reaction;
2272
- const locationContent = event.content;
2273
- const isLocationEvent = eventType === EventType.Location || eventType === EventType.RoomMessage && locationContent.msgtype === EventType.Location;
2274
- if (eventType !== EventType.RoomMessage && !isPollEvent && !isLocationEvent && !isReactionEvent) return;
2275
- logVerboseMessage(`matrix: inbound event room=${roomId} type=${eventType} id=${event.event_id ?? "unknown"}`);
2276
- if (event.unsigned?.redacted_because) return;
2277
- const senderId = event.sender;
2278
- if (!senderId) return;
2279
- const eventTs = event.origin_server_ts;
2280
- const eventAge = event.unsigned?.age;
2281
- const commitInboundEventIfClaimed = async () => {
2282
- if (!claimedInboundEvent || !inboundDeduper || !eventId) return;
2283
- await inboundDeduper.commitEvent({
2284
- roomId,
2285
- eventId
2286
- });
2287
- claimedInboundEvent = false;
2288
- };
2289
- const readIngressPrefix = async () => {
2290
- const selfUserId = await client.getUserId();
2291
- if (senderId === selfUserId) return;
2292
- if (dropPreStartupMessages) {
2293
- if (typeof eventTs === "number" && eventTs < startupMs - startupGraceMs) return;
2294
- if (typeof eventTs !== "number" && typeof eventAge === "number" && eventAge > startupGraceMs) return;
2295
- }
2296
- let content = event.content;
2297
- if (eventType === EventType.RoomMessage && isMatrixVerificationRoomMessage({
2298
- msgtype: content.msgtype,
2299
- body: content.body
2300
- })) {
2301
- logVerboseMessage(`matrix: skip verification/system room message room=${roomId}`);
2302
- return;
2303
- }
2304
- const locationPayload = resolveMatrixLocation({
2305
- eventType,
2306
- content
2307
- });
2308
- const relates = content["m.relates_to"];
2309
- if (relates && "rel_type" in relates && relates.rel_type === RelationType.Replace) return;
2310
- if (hasBundledMatrixReplacementRelation(event)) return;
2311
- if (eventId && inboundDeduper) {
2312
- claimedInboundEvent = inboundDeduper.claimEvent({
2313
- roomId,
2314
- eventId
2315
- });
2316
- if (!claimedInboundEvent) {
2317
- logVerboseMessage(`matrix: skip duplicate inbound event room=${roomId} id=${eventId}`);
2318
- return;
2319
- }
2320
- }
2321
- return {
2322
- content,
2323
- isDirectMessage: await directTracker.isDirectMessage({
2324
- roomId,
2325
- senderId,
2326
- selfUserId
2327
- }),
2328
- locationPayload,
2329
- selfUserId
2330
- };
2331
- };
2332
- const continueIngress = async (params) => {
2333
- let content = params.content;
2334
- const isDirectMessage = params.isDirectMessage;
2335
- const isRoom = !isDirectMessage;
2336
- const { locationPayload, selfUserId } = params;
2337
- if (isRoom && groupPolicy === "disabled") {
2338
- await commitInboundEventIfClaimed();
2339
- return;
2340
- }
2341
- const roomInfoForConfig = isRoom && needsRoomAliasesForConfig ? await getRoomInfo(roomId, { includeAliases: true }) : void 0;
2342
- const roomAliasesForConfig = roomInfoForConfig ? [roomInfoForConfig.canonicalAlias ?? "", ...roomInfoForConfig.altAliases].filter(Boolean) : [];
2343
- const roomConfigInfo = isRoom ? resolveMatrixRoomConfig({
2344
- rooms: roomsConfig,
2345
- roomId,
2346
- aliases: roomAliasesForConfig
2347
- }) : void 0;
2348
- const roomConfig = roomConfigInfo?.config;
2349
- const allowBotsMode = resolveMatrixAllowBotsMode(roomConfig?.allowBots ?? accountAllowBots);
2350
- const isConfiguredBotSender = configuredBotUserIds.has(senderId);
2351
- const roomMatchMeta = roomConfigInfo ? `matchKey=${roomConfigInfo.matchKey ?? "none"} matchSource=${roomConfigInfo.matchSource ?? "none"}` : "matchKey=none matchSource=none";
2352
- if (isConfiguredBotSender && allowBotsMode === "off") {
2353
- logVerboseMessage(`matrix: drop configured bot sender=${senderId} (allowBots=false${isDirectMessage ? "" : `, ${roomMatchMeta}`})`);
2354
- await commitInboundEventIfClaimed();
2355
- return;
2356
- }
2357
- const botLoopProtection = isConfiguredBotSender && senderId !== selfUserId ? {
2358
- scopeId: accountId,
2359
- conversationId: roomId,
2360
- senderId,
2361
- receiverId: selfUserId,
2362
- config: mergePairLoopGuardConfig(accountConfig?.botLoopProtection, roomConfig?.botLoopProtection),
2363
- defaultsConfig: cfg.channels?.defaults?.botLoopProtection,
2364
- defaultEnabled: true,
2365
- nowMs: eventTs ?? void 0
2366
- } : void 0;
2367
- if (isRoom && roomConfig && !roomConfigInfo?.allowed) {
2368
- logVerboseMessage(`matrix: room disabled room=${roomId} (${roomMatchMeta})`);
2369
- await commitInboundEventIfClaimed();
2370
- return;
2371
- }
2372
- if (isRoom && groupPolicy === "allowlist") {
2373
- if (!roomConfigInfo?.allowlistConfigured) {
2374
- logVerboseMessage(`matrix: drop room message (no allowlist, ${roomMatchMeta})`);
2375
- await commitInboundEventIfClaimed();
2376
- return;
2377
- }
2378
- if (!roomConfig) {
2379
- logVerboseMessage(`matrix: drop room message (not in allowlist, ${roomMatchMeta})`);
2380
- await commitInboundEventIfClaimed();
2381
- return;
2382
- }
2383
- }
2384
- let senderNamePromise = null;
2385
- const getSenderName = async () => {
2386
- senderNamePromise ??= getMemberDisplayName(roomId, senderId).catch(() => senderId);
2387
- return await senderNamePromise;
2388
- };
2389
- const storeAllowFrom = isDirectMessage && dmPolicy !== "allowlist" && dmPolicy !== "open" ? await readStoreAllowFrom() : [];
2390
- const roomUsers = roomConfig?.users ?? [];
2391
- const liveCfg = core.config.current();
2392
- const liveAccountAllowlists = resolveMatrixAccountAllowlistConfig({
2393
- cfg: liveCfg,
2394
- accountId
2395
- });
2396
- const accessState = await resolveMatrixMonitorAccessState({
2397
- allowFrom: await resolveCachedLiveAllowlist({
2398
- cfg: liveCfg,
2399
- entries: liveAccountAllowlists.dmAllowFrom,
2400
- startupResolvedEntries: allowFromResolvedEntries,
2401
- cache: liveDmAllowlistCache,
2402
- updateCache: (next) => {
2403
- liveDmAllowlistCache = next;
2404
- }
2405
- }),
2406
- storeAllowFrom,
2407
- dmPolicy,
2408
- groupPolicy,
2409
- groupAllowFrom: await resolveCachedLiveAllowlist({
2410
- cfg: liveCfg,
2411
- entries: liveAccountAllowlists.groupAllowFrom,
2412
- failClosedOnUnresolved: true,
2413
- startupResolvedEntries: groupAllowFromResolvedEntries,
2414
- cache: liveGroupAllowlistCache,
2415
- updateCache: (next) => {
2416
- liveGroupAllowlistCache = next;
2417
- }
2418
- }),
2419
- roomUsers,
2420
- senderId,
2421
- isRoom,
2422
- accountId,
2423
- eventKind: isReactionEvent ? "reaction" : "message"
2424
- });
2425
- const { effectiveGroupAllowFrom, effectiveRoomUsers, messageIngress } = accessState;
2426
- const ingressDecision = messageIngress.ingress;
2427
- if (isDirectMessage) {
2428
- if (!dmEnabled || dmPolicy === "disabled") {
2429
- await commitInboundEventIfClaimed();
2430
- return;
2431
- }
2432
- const senderReason = messageIngress.senderAccess.reasonCode;
2433
- if (ingressDecision.decision !== "allow") {
2434
- if (ingressDecision.admission === "pairing-required") {
2435
- const senderName = await getSenderName();
2436
- const { code, created } = await core.channel.pairing.upsertPairingRequest({
2437
- channel: "matrix",
2438
- id: senderId,
2439
- accountId,
2440
- meta: { name: senderName }
2441
- });
2442
- if (shouldSendPairingReply(senderId, created)) {
2443
- const pairingReply = core.channel.pairing.buildPairingReply({
2444
- channel: "matrix",
2445
- idLine: `Your Matrix user id: ${senderId}`,
2446
- code
2447
- });
2448
- logVerboseMessage(created ? `matrix pairing request sender=${senderId} name=${senderName ?? "unknown"} (reason=${senderReason})` : `matrix pairing reminder sender=${senderId} name=${senderName ?? "unknown"} (reason=${senderReason})`);
2449
- try {
2450
- const { sendMessageMatrix } = await loadMatrixSendModule();
2451
- await sendMessageMatrix(`room:${roomId}`, created ? pairingReply : `${pairingReply}\n\nPairing request is still pending approval. Reusing existing code.`, {
2452
- client,
2453
- cfg,
2454
- accountId
2455
- });
2456
- await commitInboundEventIfClaimed();
2457
- } catch (err) {
2458
- logVerboseMessage(`matrix pairing reply failed for ${senderId}: ${String(err)}`);
2459
- return;
2460
- }
2461
- } else {
2462
- logVerboseMessage(`matrix pairing reminder suppressed sender=${senderId} (cooldown)`);
2463
- await commitInboundEventIfClaimed();
2464
- }
2465
- }
2466
- if (isReactionEvent || dmPolicy !== "pairing") {
2467
- logVerboseMessage(`matrix: blocked ${isReactionEvent ? "reaction" : "dm"} sender ${senderId} (dmPolicy=${dmPolicy}, reason=${senderReason})`);
2468
- await commitInboundEventIfClaimed();
2469
- }
2470
- return;
2471
- }
2472
- }
2473
- if (isRoom && ingressDecision.decision !== "allow") {
2474
- logVerboseMessage(`matrix: blocked sender ${senderId} (ingress=${ingressDecision.reasonCode}, ${roomMatchMeta})`);
2475
- await commitInboundEventIfClaimed();
2476
- return;
2477
- }
2478
- if (isRoom) logVerboseMessage(`matrix: allow room ${roomId} (${roomMatchMeta})`);
2479
- if (isReactionEvent) {
2480
- const senderName = await getSenderName();
2481
- const { handleInboundMatrixReaction } = await loadMatrixReactionEvents();
2482
- await handleInboundMatrixReaction({
2483
- client,
2484
- core,
2485
- cfg,
2486
- accountId,
2487
- roomId,
2488
- event,
2489
- senderId,
2490
- senderLabel: senderName,
2491
- selfUserId,
2492
- isDirectMessage,
2493
- logVerboseMessage
2494
- });
2495
- await commitInboundEventIfClaimed();
2496
- return;
2497
- }
2498
- let pollSnapshotPromise = null;
2499
- const getPollSnapshot = async () => {
2500
- if (!isPollEvent) return null;
2501
- pollSnapshotPromise ??= fetchMatrixPollSnapshot(client, roomId, event).catch((err) => {
2502
- logVerboseMessage(`matrix: failed resolving poll snapshot room=${roomId} id=${event.event_id ?? "unknown"}: ${String(err)}`);
2503
- return null;
2504
- });
2505
- return await pollSnapshotPromise;
2506
- };
2507
- const mentionPrecheckText = resolveMatrixMentionPrecheckText({
2508
- eventType,
2509
- content,
2510
- locationText: locationPayload?.text
2511
- });
2512
- const contentUrl = "url" in content && typeof content.url === "string" ? content.url : void 0;
2513
- const contentFile = "file" in content && content.file && typeof content.file === "object" ? content.file : void 0;
2514
- const mediaUrl = contentUrl ?? contentFile?.url;
2515
- const pendingHistoryText = resolveMatrixPendingHistoryText({
2516
- mentionPrecheckText,
2517
- content,
2518
- mediaUrl
2519
- });
2520
- const pendingHistoryPollText = !pendingHistoryText && isPollEvent && historyLimit > 0 ? (await getPollSnapshot())?.text : "";
2521
- if (!mentionPrecheckText && !mediaUrl && !isPollEvent) {
2522
- await commitInboundEventIfClaimed();
2523
- return;
2524
- }
2525
- const messageId = event.event_id ?? "";
2526
- const threadRootId = resolveMatrixThreadRootId({
2527
- event,
2528
- content
2529
- });
2530
- const thread = resolveMatrixThreadRouting({
2531
- isDirectMessage,
2532
- threadReplies,
2533
- dmThreadReplies,
2534
- messageId,
2535
- threadRootId
2536
- });
2537
- const { route: _route, configuredBinding: _configuredBinding, runtimeBindingId: _runtimeBindingId } = resolveMatrixInboundRoute({
2538
- cfg,
2539
- accountId,
2540
- roomId,
2541
- senderId,
2542
- isDirectMessage,
2543
- dmSessionScope,
2544
- threadId: thread.threadId,
2545
- eventTs: eventTs ?? void 0,
2546
- resolveAgentRoute: core.channel.routing.resolveAgentRoute
2547
- });
2548
- const hasExplicitSessionBinding = _configuredBinding !== null || _runtimeBindingId !== null;
2549
- const agentMentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, _route.agentId);
2550
- const selfDisplayName = content.formatted_body ? await getMemberDisplayName(roomId, selfUserId).catch(() => void 0) : void 0;
2551
- const { wasMentioned, hasExplicitMention } = resolveMentions({
2552
- content,
2553
- userId: selfUserId,
2554
- displayName: selfDisplayName,
2555
- text: mentionPrecheckText,
2556
- mentionRegexes: agentMentionRegexes
2557
- });
2558
- if (isConfiguredBotSender && allowBotsMode === "mentions" && !isDirectMessage && !wasMentioned) {
2559
- logVerboseMessage(`matrix: drop configured bot sender=${senderId} (allowBots=mentions, missing mention, ${roomMatchMeta})`);
2560
- await commitInboundEventIfClaimed();
2561
- return;
2562
- }
2563
- const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
2564
- cfg,
2565
- surface: "matrix"
2566
- });
2567
- const useAccessGroups = cfg.commands?.useAccessGroups !== false;
2568
- const commandCheckText = stripMatrixMentionPrefix({
2569
- text: mentionPrecheckText,
2570
- userId: selfUserId,
2571
- displayName: selfDisplayName,
2572
- mentionRegexes: agentMentionRegexes
2573
- });
2574
- const hasControlCommandInMessage = core.channel.text.hasControlCommand(commandCheckText, cfg);
2575
- const commandAccess = await resolveMatrixMonitorCommandAccess(accessState, {
2576
- useAccessGroups,
2577
- allowTextCommands,
2578
- hasControlCommand: hasControlCommandInMessage
2579
- });
2580
- const commandAuthorized = commandAccess.authorized;
2581
- if (isRoom && commandAccess.shouldBlockControlCommand) {
2582
- logInboundDrop({
2583
- log: logVerboseMessage,
2584
- channel: "matrix",
2585
- reason: "control command (unauthorized)",
2586
- target: senderId
2587
- });
2588
- await commitInboundEventIfClaimed();
2589
- return;
2590
- }
2591
- const shouldRequireMention = isRoom ? roomConfig?.autoReply === true ? false : roomConfig?.autoReply === false ? true : typeof roomConfig?.requireMention === "boolean" ? roomConfig?.requireMention : true : false;
2592
- const shouldBypassMention = allowTextCommands && isRoom && shouldRequireMention && !wasMentioned && !hasExplicitMention && commandAuthorized && hasControlCommandInMessage;
2593
- const canDetectMention = agentMentionRegexes.length > 0 || hasExplicitMention;
2594
- if (isRoom && shouldRequireMention && !wasMentioned && !shouldBypassMention) {
2595
- const pendingHistoryBody = pendingHistoryText || pendingHistoryPollText;
2596
- if (historyLimit > 0 && pendingHistoryBody) {
2597
- const pendingEntry = {
2598
- sender: senderId,
2599
- body: pendingHistoryBody,
2600
- timestamp: eventTs ?? void 0,
2601
- messageId
2602
- };
2603
- roomHistoryTracker.recordPending(roomId, pendingEntry);
2604
- }
2605
- logger.info("skipping room message", {
2606
- roomId,
2607
- reason: "no-mention"
2608
- });
2609
- await commitInboundEventIfClaimed();
2610
- return;
2611
- }
2612
- if (isPollEvent) {
2613
- const pollSnapshot = await getPollSnapshot();
2614
- if (!pollSnapshot) return;
2615
- content = {
2616
- msgtype: "m.text",
2617
- body: pollSnapshot.text
2618
- };
2619
- }
2620
- let media = null;
2621
- let mediaDownloadFailed = false;
2622
- let mediaSizeLimitExceeded = false;
2623
- const finalContentUrl = "url" in content && typeof content.url === "string" ? content.url : void 0;
2624
- const finalContentFile = "file" in content && content.file && typeof content.file === "object" ? content.file : void 0;
2625
- const finalMediaUrl = finalContentUrl ?? finalContentFile?.url;
2626
- const contentBody = typeof content.body === "string" ? content.body.trim() : "";
2627
- const originalFilename = (typeof content.filename === "string" ? content.filename.trim() : "") || contentBody || void 0;
2628
- const contentInfo = "info" in content && content.info && typeof content.info === "object" ? content.info : void 0;
2629
- const contentType = contentInfo?.mimetype;
2630
- const contentSize = typeof contentInfo?.size === "number" ? contentInfo.size : void 0;
2631
- if (finalMediaUrl?.startsWith("mxc://")) try {
2632
- media = await downloadMatrixMedia({
2633
- client,
2634
- mxcUrl: finalMediaUrl,
2635
- contentType,
2636
- sizeBytes: contentSize,
2637
- maxBytes: mediaMaxBytes,
2638
- file: finalContentFile,
2639
- originalFilename
2640
- });
2641
- } catch (err) {
2642
- mediaDownloadFailed = true;
2643
- if (isMatrixMediaSizeLimitError(err)) mediaSizeLimitExceeded = true;
2644
- const errorText = formatMatrixErrorMessage(err);
2645
- logVerboseMessage(`matrix: media download failed room=${roomId} id=${event.event_id ?? "unknown"} type=${content.msgtype} error=${errorText}`);
2646
- logger.warn("matrix media download failed", {
2647
- roomId,
2648
- eventId: event.event_id,
2649
- msgtype: content.msgtype,
2650
- encrypted: Boolean(finalContentFile),
2651
- error: errorText
2652
- });
2653
- }
2654
- const bodyText = resolveMatrixInboundBodyText({
2655
- rawBody: locationPayload?.text ?? contentBody,
2656
- filename: typeof content.filename === "string" ? content.filename : void 0,
2657
- mediaPlaceholder: media?.placeholder,
2658
- msgtype: content.msgtype,
2659
- hadMediaUrl: Boolean(finalMediaUrl),
2660
- mediaDownloadFailed,
2661
- mediaSizeLimitExceeded
2662
- });
2663
- if (!bodyText) {
2664
- await commitInboundEventIfClaimed();
2665
- return;
2666
- }
2667
- const commandBodyText = hasControlCommandInMessage ? commandCheckText : bodyText;
2668
- const senderName = await getSenderName();
2669
- if (_configuredBinding) {
2670
- const { ensureConfiguredAcpBindingReady } = await loadAcpBindingRuntime();
2671
- if (!(await ensureConfiguredAcpBindingReady({
2672
- cfg,
2673
- configuredBinding: _configuredBinding
2674
- })).ok) {
2675
- logInboundDrop({
2676
- log: logVerboseMessage,
2677
- channel: "matrix",
2678
- reason: "configured ACP binding unavailable",
2679
- target: _configuredBinding.spec.conversationId
2680
- });
2681
- return;
2682
- }
2683
- }
2684
- if (_runtimeBindingId) {
2685
- const { getSessionBindingService } = await loadSessionBindingRuntime();
2686
- getSessionBindingService().touch(_runtimeBindingId, eventTs ?? void 0);
2687
- }
2688
- const preparedTrigger = isRoom && historyLimit > 0 ? roomHistoryTracker.prepareTrigger(_route.agentId, roomId, historyLimit, {
2689
- sender: senderName,
2690
- body: bodyText,
2691
- timestamp: eventTs ?? void 0,
2692
- messageId
2693
- }) : void 0;
2694
- return {
2695
- route: _route,
2696
- hasExplicitSessionBinding,
2697
- roomConfig,
2698
- isDirectMessage,
2699
- isRoom,
2700
- shouldRequireMention,
2701
- wasMentioned,
2702
- shouldBypassMention,
2703
- canDetectMention,
2704
- commandAuthorized,
2705
- inboundHistory: preparedTrigger ? buildInboundHistoryFromEntries({
2706
- entries: preparedTrigger.history,
2707
- limit: historyLimit
2708
- }) : void 0,
2709
- senderName,
2710
- bodyText,
2711
- commandBodyText,
2712
- media,
2713
- locationPayload,
2714
- messageId,
2715
- triggerSnapshot: preparedTrigger,
2716
- threadRootId,
2717
- thread,
2718
- botLoopProtection,
2719
- effectiveGroupAllowFrom,
2720
- effectiveRoomUsers
2721
- };
2722
- };
2723
- const ingressResult = historyLimit > 0 ? await runRoomIngress(roomId, async () => {
2724
- const prefix = await readIngressPrefix();
2725
- if (!prefix) return;
2726
- if (prefix.isDirectMessage) return { deferredPrefix: prefix };
2727
- return { ingressResult: await continueIngress(prefix) };
2728
- }) : void 0;
2729
- const resolvedIngressResult = historyLimit > 0 ? ingressResult?.deferredPrefix ? await continueIngress(ingressResult.deferredPrefix) : ingressResult?.ingressResult : await (async () => {
2730
- const prefix = await readIngressPrefix();
2731
- if (!prefix) return;
2732
- return await continueIngress(prefix);
2733
- })();
2734
- if (!resolvedIngressResult) return;
2735
- const { route: _route, hasExplicitSessionBinding, roomConfig, isDirectMessage, isRoom, shouldRequireMention, wasMentioned, shouldBypassMention, canDetectMention, commandAuthorized, inboundHistory, senderName, bodyText, commandBodyText, media, locationPayload, messageId, triggerSnapshot, threadRootId, thread, botLoopProtection, effectiveGroupAllowFrom, effectiveRoomUsers } = resolvedIngressResult;
2736
- const replyToEventId = resolveMatrixReplyToEventId(event.content);
2737
- const threadTarget = thread.threadId;
2738
- const isRoomContextSenderAllowed = (contextSenderId) => {
2739
- if (!isRoom || !contextSenderId) return true;
2740
- if (effectiveRoomUsers.length > 0) return resolveMatrixAllowListMatch({
2741
- allowList: effectiveRoomUsers,
2742
- userId: contextSenderId
2743
- }).allowed;
2744
- if (groupPolicy === "allowlist" && effectiveGroupAllowFrom.length > 0) return resolveMatrixAllowListMatch({
2745
- allowList: effectiveGroupAllowFrom,
2746
- userId: contextSenderId
2747
- }).allowed;
2748
- return true;
2749
- };
2750
- const shouldIncludeRoomContextSender = (kind, contextSenderId) => evaluateSupplementalContextVisibility({
2751
- mode: contextVisibilityMode,
2752
- kind,
2753
- senderAllowed: isRoomContextSenderAllowed(contextSenderId)
2754
- }).include;
2755
- let threadContext = threadRootId ? await resolveThreadContext({
2756
- roomId,
2757
- threadRootId
2758
- }) : void 0;
2759
- let threadContextBlockedByPolicy = false;
2760
- if (threadContext?.senderId && !shouldIncludeRoomContextSender("thread", threadContext.senderId)) {
2761
- logVerboseMessage(`matrix: drop thread root context (mode=${contextVisibilityMode})`);
2762
- threadContextBlockedByPolicy = true;
2763
- threadContext = void 0;
2764
- }
2765
- let replyContext;
2766
- if (replyToEventId && replyToEventId === threadRootId && threadContext?.summary) replyContext = {
2767
- replyToBody: threadContext.summary,
2768
- replyToSender: threadContext.senderLabel,
2769
- replyToSenderId: threadContext.senderId
2770
- };
2771
- else if (replyToEventId && replyToEventId === threadRootId && threadContextBlockedByPolicy) replyContext = await resolveReplyContext({
2772
- roomId,
2773
- eventId: replyToEventId
2774
- });
2775
- else replyContext = replyToEventId ? await resolveReplyContext({
2776
- roomId,
2777
- eventId: replyToEventId
2778
- }) : void 0;
2779
- if (replyContext?.replyToSenderId && !shouldIncludeRoomContextSender("quote", replyContext.replyToSenderId)) {
2780
- logVerboseMessage(`matrix: drop reply context (mode=${contextVisibilityMode})`);
2781
- replyContext = void 0;
2782
- }
2783
- const roomName = (isRoom ? await getRoomInfo(roomId) : void 0)?.name;
2784
- const envelopeFrom = isDirectMessage ? senderName : roomName ?? roomId;
2785
- const textWithId = `${bodyText}\n[matrix event id: ${messageId} room: ${roomId}]`;
2786
- const storePath = core.channel.session.resolveStorePath(cfg.session?.store, { agentId: _route.agentId });
2787
- const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
2788
- const previousTimestamp = core.channel.session.readSessionUpdatedAt({
2789
- storePath,
2790
- sessionKey: _route.sessionKey
2791
- });
2792
- const sharedDmNoticeSessionKey = threadTarget ? _route.mainSessionKey || _route.sessionKey : _route.sessionKey;
2793
- const sharedDmContextNotice = isDirectMessage ? hasExplicitSessionBinding ? null : resolveMatrixSharedDmContextNotice({
2794
- storePath,
2795
- sessionKey: sharedDmNoticeSessionKey,
2796
- roomId,
2797
- accountId: _route.accountId,
2798
- dmSessionScope,
2799
- sentRooms: sharedDmContextNoticeRooms,
2800
- logVerboseMessage
2801
- }) : null;
2802
- const body = core.channel.reply.formatAgentEnvelope({
2803
- channel: "Matrix",
2804
- from: envelopeFrom,
2805
- timestamp: eventTs ?? void 0,
2806
- previousTimestamp,
2807
- envelope: envelopeOptions,
2808
- body: textWithId
2809
- });
2810
- const groupSystemPrompt = normalizeOptionalString(roomConfig?.systemPrompt);
2811
- const ctxPayload = core.channel.reply.finalizeInboundContext({
2812
- Body: body,
2813
- RawBody: bodyText,
2814
- CommandBody: commandBodyText,
2815
- BodyForAgent: bodyText,
2816
- BodyForCommands: commandBodyText,
2817
- InboundHistory: inboundHistory && inboundHistory.length > 0 ? inboundHistory : void 0,
2818
- From: isDirectMessage ? `matrix:${senderId}` : `matrix:channel:${roomId}`,
2819
- To: `room:${roomId}`,
2820
- SessionKey: _route.sessionKey,
2821
- AccountId: _route.accountId,
2822
- ChatType: isDirectMessage ? "direct" : "channel",
2823
- ConversationLabel: envelopeFrom,
2824
- SenderName: senderName,
2825
- SenderId: senderId,
2826
- SenderUsername: senderId.split(":")[0]?.replace(/^@/, ""),
2827
- GroupSubject: isRoom ? roomName ?? roomId : void 0,
2828
- GroupId: isRoom ? roomId : void 0,
2829
- GroupChannel: isRoom ? roomId : void 0,
2830
- GroupSystemPrompt: isRoom ? groupSystemPrompt : void 0,
2831
- Provider: "matrix",
2832
- Surface: "matrix",
2833
- WasMentioned: isRoom ? wasMentioned : void 0,
2834
- MessageSid: messageId,
2835
- ReplyToId: threadTarget ? void 0 : replyToEventId ?? void 0,
2836
- ReplyToBody: replyContext?.replyToBody,
2837
- ReplyToSender: replyContext?.replyToSender,
2838
- MessageThreadId: threadTarget,
2839
- ThreadStarterBody: threadContext?.threadStarterBody,
2840
- Timestamp: eventTs ?? void 0,
2841
- MediaPath: media?.path,
2842
- MediaType: media?.contentType,
2843
- MediaUrl: media?.path,
2844
- ...locationPayload?.context,
2845
- CommandAuthorized: commandAuthorized,
2846
- CommandSource: "text",
2847
- NativeChannelId: roomId,
2848
- NativeDirectUserId: isDirectMessage ? senderId : void 0,
2849
- OriginatingChannel: "matrix",
2850
- OriginatingTo: `room:${roomId}`
2851
- });
2852
- logVerboseMessage(`matrix inbound: room=${roomId} from=${senderId} preview="${bodyText.slice(0, 200).replace(/\n/g, "\\n")}"`);
2853
- const replyTarget = ctxPayload.To;
2854
- if (!replyTarget) {
2855
- runtime.error?.("matrix: missing reply target");
2856
- return;
2857
- }
2858
- const { ackReaction, ackReactionScope: ackScope } = resolveMatrixAckReactionConfig({
2859
- cfg,
2860
- agentId: _route.agentId,
2861
- accountId
2862
- });
2863
- const shouldAckReaction = () => Boolean(ackReaction && core.channel.reactions.shouldAckReaction({
2864
- scope: ackScope,
2865
- isDirect: isDirectMessage,
2866
- isGroup: isRoom,
2867
- isMentionableGroup: isRoom,
2868
- requireMention: shouldRequireMention,
2869
- canDetectMention,
2870
- effectiveWasMentioned: wasMentioned || shouldBypassMention,
2871
- shouldBypassMention
2872
- }));
2873
- if (shouldAckReaction() && messageId) loadMatrixSendModule().then(({ reactMatrixMessage }) => reactMatrixMessage(roomId, messageId, ackReaction, client)).catch((err) => {
2874
- logVerboseMessage(`matrix react failed for room ${roomId}: ${String(err)}`);
2875
- });
2876
- if (messageId) loadMatrixSendModule().then(({ sendReadReceiptMatrix }) => sendReadReceiptMatrix(roomId, messageId, client)).catch((err) => {
2877
- logVerboseMessage(`matrix: read receipt failed room=${roomId} id=${messageId}: ${String(err)}`);
2878
- });
2879
- const tableMode = core.channel.text.resolveMarkdownTableMode({
2880
- cfg,
2881
- channel: "matrix",
2882
- accountId: _route.accountId
2883
- });
2884
- const mediaLocalRoots = getAgentScopedMediaLocalRoots(cfg, _route.agentId);
2885
- let finalReplyDeliveryFailed = false;
2886
- let nonFinalReplyDeliveryFailed = false;
2887
- let retryableReplyDeliveryFailed = false;
2888
- const { onModelSelected, ...prefixOptions } = createReplyPrefixOptions({
2889
- cfg,
2890
- agentId: _route.agentId,
2891
- channel: "matrix",
2892
- accountId: _route.accountId
2893
- });
2894
- const typingCallbacks = createTypingCallbacks({
2895
- start: async () => {
2896
- const { sendTypingMatrix } = await loadMatrixSendModule();
2897
- await sendTypingMatrix(roomId, true, void 0, client);
2898
- },
2899
- stop: async () => {
2900
- const { sendTypingMatrix } = await loadMatrixSendModule();
2901
- await sendTypingMatrix(roomId, false, void 0, client);
2902
- },
2903
- onStartError: (err) => {
2904
- logTypingFailure({
2905
- log: logVerboseMessage,
2906
- channel: "matrix",
2907
- action: "start",
2908
- target: roomId,
2909
- error: err
2910
- });
2911
- },
2912
- onStopError: (err) => {
2913
- logTypingFailure({
2914
- log: logVerboseMessage,
2915
- channel: "matrix",
2916
- action: "stop",
2917
- target: roomId,
2918
- error: err
2919
- });
2920
- }
2921
- });
2922
- const draftStreamingEnabled = streaming !== "off";
2923
- const quietDraftStreaming = streaming === "quiet" || streaming === "progress";
2924
- const progressDraftStreaming = streaming === "progress";
2925
- const draftReplyToId = replyToMode !== "off" && !threadTarget ? messageId : void 0;
2926
- const draftStream = draftStreamingEnabled ? await loadMatrixDraftStream().then(({ createMatrixDraftStream }) => createMatrixDraftStream({
2927
- roomId,
2928
- client,
2929
- cfg,
2930
- mode: quietDraftStreaming ? "quiet" : "partial",
2931
- threadId: threadTarget,
2932
- replyToId: draftReplyToId,
2933
- preserveReplyId: replyToMode === "all",
2934
- accountId: _route.accountId,
2935
- log: logVerboseMessage
2936
- })) : void 0;
2937
- draftStreamRef = draftStream;
2938
- const shouldStreamPreviewToolProgress = Boolean(draftStream) && previewToolProgressEnabled;
2939
- const shouldSuppressDefaultToolProgressMessages = Boolean(draftStream) && (shouldStreamPreviewToolProgress || params.streaming === "progress");
2940
- let currentDraftMessageGeneration = 0;
2941
- let currentDraftBlockOffset = 0;
2942
- let latestDraftFullText = "";
2943
- const pendingDraftBoundaries = [];
2944
- const latestQueuedDraftBoundaryOffsets = /* @__PURE__ */ new Map();
2945
- let currentDraftReplyToId = draftReplyToId;
2946
- let previewToolProgressSuppressed = false;
2947
- let previewToolProgressLines = [];
2948
- const progressConfigEntry = params.accountConfig ?? cfg.channels?.matrix;
2949
- const progressSeed = `${_route.accountId}:${roomId}`;
2950
- const renderProgressDraft = () => {
2951
- if (!draftStream || !progressDraftStreaming) return;
2952
- const previewText = formatChannelProgressDraftText({
2953
- entry: progressConfigEntry,
2954
- lines: previewToolProgressLines,
2955
- seed: progressSeed,
2956
- formatLine: formatMatrixToolProgressMarkdownCode,
2957
- bullet: "-"
2958
- });
2959
- if (!previewText) return;
2960
- draftStream.update(previewText);
2961
- };
2962
- const progressDraftGate = createChannelProgressDraftGate({ onStart: renderProgressDraft });
2963
- const pushPreviewToolProgress = async (line, options) => {
2964
- if (!draftStream) return;
2965
- if (options?.toolName !== void 0 && !isChannelProgressDraftWorkToolName(options.toolName)) return;
2966
- const normalized = normalizeChannelProgressDraftLineIdentity(line);
2967
- const progressLine = typeof line === "object" && line !== void 0 ? line : normalized;
2968
- if (!progressDraftStreaming) {
2969
- if (!shouldStreamPreviewToolProgress || previewToolProgressSuppressed || !normalized) return;
2970
- const nextLines = mergeChannelProgressDraftLine(previewToolProgressLines, progressLine, { maxLines: resolveChannelProgressDraftMaxLines(progressConfigEntry) });
2971
- if (nextLines === previewToolProgressLines) return;
2972
- previewToolProgressLines = nextLines;
2973
- draftStream.update(formatChannelProgressDraftText({
2974
- entry: progressConfigEntry,
2975
- lines: previewToolProgressLines,
2976
- seed: progressSeed,
2977
- formatLine: formatMatrixToolProgressMarkdownCode,
2978
- bullet: "-"
2979
- }));
2980
- return;
2981
- }
2982
- if (shouldStreamPreviewToolProgress && !previewToolProgressSuppressed && normalized) previewToolProgressLines = mergeChannelProgressDraftLine(previewToolProgressLines, progressLine, { maxLines: resolveChannelProgressDraftMaxLines(progressConfigEntry) });
2983
- const alreadyStarted = progressDraftGate.hasStarted;
2984
- await progressDraftGate.noteWork();
2985
- if (alreadyStarted && progressDraftGate.hasStarted) renderProgressDraft();
2986
- };
2987
- const suppressPreviewToolProgressForAnswerText = (text) => {
2988
- if (!text?.trim()) return;
2989
- previewToolProgressSuppressed = true;
2990
- previewToolProgressLines = [];
2991
- };
2992
- const resetPreviewToolProgress = () => {
2993
- previewToolProgressSuppressed = false;
2994
- previewToolProgressLines = [];
2995
- };
2996
- const buildPreviewToolProgressReplyOptions = () => {
2997
- if (!shouldSuppressDefaultToolProgressMessages) return {};
2998
- const options = { suppressDefaultToolProgressMessages: true };
2999
- if (!shouldStreamPreviewToolProgress) return options;
3000
- return {
3001
- ...options,
3002
- onToolStart: async (payload) => {
3003
- const toolName = payload.name?.trim();
3004
- await pushPreviewToolProgress(formatChannelProgressDraftLineForEntry(progressConfigEntry, {
3005
- event: "tool",
3006
- name: toolName,
3007
- phase: payload.phase,
3008
- args: payload.args
3009
- }, payload.detailMode ? { detailMode: payload.detailMode } : void 0), { toolName });
3010
- },
3011
- onItemEvent: async (payload) => {
3012
- await pushPreviewToolProgress(buildChannelProgressDraftLineForEntry(progressConfigEntry, {
3013
- event: "item",
3014
- itemId: payload.itemId,
3015
- itemKind: payload.kind,
3016
- title: payload.title,
3017
- name: payload.name,
3018
- phase: payload.phase,
3019
- status: payload.status,
3020
- summary: payload.summary,
3021
- progressText: payload.progressText,
3022
- meta: payload.meta
3023
- }));
3024
- },
3025
- onPlanUpdate: async (payload) => {
3026
- if (payload.phase !== "update") return;
3027
- await pushPreviewToolProgress(formatChannelProgressDraftLine({
3028
- event: "plan",
3029
- phase: payload.phase,
3030
- title: payload.title,
3031
- explanation: payload.explanation,
3032
- steps: payload.steps
3033
- }));
3034
- },
3035
- onApprovalEvent: async (payload) => {
3036
- if (payload.phase !== "requested") return;
3037
- await pushPreviewToolProgress(formatChannelProgressDraftLine({
3038
- event: "approval",
3039
- phase: payload.phase,
3040
- title: payload.title,
3041
- command: payload.command,
3042
- reason: payload.reason,
3043
- message: payload.message
3044
- }));
3045
- },
3046
- onCommandOutput: async (payload) => {
3047
- if (payload.phase !== "end") return;
3048
- await pushPreviewToolProgress(formatChannelProgressDraftLine({
3049
- event: "command-output",
3050
- phase: payload.phase,
3051
- title: payload.title,
3052
- name: payload.name,
3053
- status: payload.status,
3054
- exitCode: payload.exitCode
3055
- }));
3056
- },
3057
- onPatchSummary: async (payload) => {
3058
- if (payload.phase !== "end") return;
3059
- await pushPreviewToolProgress(formatChannelProgressDraftLine({
3060
- event: "patch",
3061
- phase: payload.phase,
3062
- title: payload.title,
3063
- name: payload.name,
3064
- added: payload.added,
3065
- modified: payload.modified,
3066
- deleted: payload.deleted,
3067
- summary: payload.summary
3068
- }));
3069
- }
3070
- };
3071
- };
3072
- const getDisplayableDraftText = () => {
3073
- const nextDraftBoundaryOffset = pendingDraftBoundaries.find((boundary) => boundary.messageGeneration === currentDraftMessageGeneration)?.endOffset;
3074
- if (nextDraftBoundaryOffset === void 0) return latestDraftFullText.slice(currentDraftBlockOffset);
3075
- return latestDraftFullText.slice(currentDraftBlockOffset, nextDraftBoundaryOffset);
3076
- };
3077
- const updateDraftFromLatestFullText = () => {
3078
- const blockText = getDisplayableDraftText();
3079
- if (blockText) draftStream?.update(blockText);
3080
- };
3081
- const queueDraftBlockBoundary = (payload, context) => {
3082
- const payloadTextLength = payload.text?.length ?? 0;
3083
- const messageGeneration = context?.assistantMessageIndex ?? currentDraftMessageGeneration;
3084
- const nextDraftBoundaryOffset = (latestQueuedDraftBoundaryOffsets.get(messageGeneration) ?? 0) + payloadTextLength;
3085
- latestQueuedDraftBoundaryOffsets.set(messageGeneration, nextDraftBoundaryOffset);
3086
- pendingDraftBoundaries.push({
3087
- messageGeneration,
3088
- endOffset: nextDraftBoundaryOffset
3089
- });
3090
- };
3091
- const advanceDraftBlockBoundary = (options) => {
3092
- const completedBoundary = pendingDraftBoundaries.shift();
3093
- if (completedBoundary) {
3094
- if (!pendingDraftBoundaries.some((entry) => entry.messageGeneration === completedBoundary.messageGeneration)) latestQueuedDraftBoundaryOffsets.delete(completedBoundary.messageGeneration);
3095
- if (completedBoundary.messageGeneration === currentDraftMessageGeneration) currentDraftBlockOffset = completedBoundary.endOffset;
3096
- return;
3097
- }
3098
- if (options?.fallbackToLatestEnd) currentDraftBlockOffset = latestDraftFullText.length;
3099
- };
3100
- const resetDraftBlockOffsets = () => {
3101
- currentDraftMessageGeneration += 1;
3102
- currentDraftBlockOffset = 0;
3103
- latestDraftFullText = "";
3104
- };
3105
- const { dispatcher, replyOptions, markDispatchIdle, markRunComplete } = core.channel.reply.createReplyDispatcherWithTyping({
3106
- ...prefixOptions,
3107
- humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, _route.agentId),
3108
- deliver: async (payload, info) => {
3109
- if (draftStream && info.kind !== "tool" && !payload.isCompactionNotice) {
3110
- const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
3111
- const ttsSupplement = getReplyPayloadTtsSupplement(payload);
3112
- const fallbackPayload = ttsSupplement && ttsSupplement.visibleTextAlreadyDelivered !== true && !payload.text?.trim() ? {
3113
- ...payload,
3114
- text: ttsSupplement.spokenText
3115
- } : payload;
3116
- if (draftConsumed) {
3117
- await draftStream.discardPending();
3118
- await deliverMatrixReplies({
3119
- cfg,
3120
- replies: [fallbackPayload],
3121
- roomId,
3122
- client,
3123
- runtime,
3124
- textLimit,
3125
- replyToMode,
3126
- threadId: threadTarget,
3127
- accountId: _route.accountId,
3128
- mediaLocalRoots,
3129
- tableMode
3130
- });
3131
- return;
3132
- }
3133
- const payloadReplyToId = normalizeOptionalString(payload.replyToId);
3134
- const payloadReplyMismatch = replyToMode !== "off" && !threadTarget && payloadReplyToId !== currentDraftReplyToId;
3135
- let mustDeliverFinalNormally = draftStream.mustDeliverFinalNormally();
3136
- if (Boolean(payload.text?.trim()) && !payload.isError && !payloadReplyMismatch && !mustDeliverFinalNormally) {
3137
- await draftStream.stop();
3138
- mustDeliverFinalNormally = draftStream.mustDeliverFinalNormally();
3139
- } else await draftStream.discardPending();
3140
- const draftEventId = draftStream.eventId();
3141
- if (draftEventId && payload.text && !payload.isError && !hasMedia && !payloadReplyMismatch && !mustDeliverFinalNormally) {
3142
- const finalPreviewText = payload.text;
3143
- await deliverWithFinalizableLivePreviewAdapter({
3144
- kind: "final",
3145
- payload,
3146
- adapter: defineFinalizableLivePreviewAdapter({
3147
- draft: {
3148
- flush: async () => {},
3149
- clear: async () => {},
3150
- discardPending: async () => {},
3151
- id: () => draftEventId
3152
- },
3153
- buildFinalEdit: () => ({
3154
- text: finalPreviewText,
3155
- finalizeLive: !(quietDraftStreaming || !draftStream.matchesPreparedText(finalPreviewText)),
3156
- ...quietDraftStreaming ? { extraContent: buildMatrixFinalizedPreviewContent() } : {}
3157
- }),
3158
- editFinal: async (_draftEventId, edit) => {
3159
- if (edit.finalizeLive) {
3160
- if (!await draftStream.finalizeLive()) throw new Error("Matrix draft live finalize failed");
3161
- return;
3162
- }
3163
- const { editMessageMatrix } = await loadMatrixSendModule();
3164
- await editMessageMatrix(roomId, _draftEventId, edit.text, {
3165
- client,
3166
- cfg,
3167
- threadId: threadTarget,
3168
- accountId: _route.accountId,
3169
- extraContent: edit.extraContent
3170
- });
3171
- },
3172
- createPreviewReceipt: (id) => createPreviewMessageReceipt({
3173
- id,
3174
- ...threadTarget ? { threadId: threadTarget } : {},
3175
- ...currentDraftReplyToId ? { replyToId: currentDraftReplyToId } : {}
3176
- }),
3177
- logPreviewEditFailure: (err) => {
3178
- logVerboseMessage(`matrix: preview final edit failed: ${String(err)}`);
3179
- }
3180
- }),
3181
- deliverNormally: async () => {
3182
- await redactMatrixDraftEvent(client, roomId, draftEventId);
3183
- await deliverMatrixReplies({
3184
- cfg,
3185
- replies: [fallbackPayload],
3186
- roomId,
3187
- client,
3188
- runtime,
3189
- textLimit,
3190
- replyToMode,
3191
- threadId: threadTarget,
3192
- accountId: _route.accountId,
3193
- mediaLocalRoots,
3194
- tableMode
3195
- });
3196
- }
3197
- });
3198
- draftConsumed = true;
3199
- } else if (draftEventId && hasMedia && !payloadReplyMismatch) {
3200
- let textEditOk = !mustDeliverFinalNormally;
3201
- const payloadText = payload.text ?? ttsSupplement?.spokenText;
3202
- const payloadTextMatchesDraft = typeof payloadText === "string" && draftStream.matchesPreparedText(payloadText);
3203
- const reusesDraftTextUnchanged = typeof payloadText === "string" && Boolean(payloadText.trim()) && payloadTextMatchesDraft;
3204
- if (textEditOk && payloadText && (quietDraftStreaming || typeof payloadText === "string" && !payloadTextMatchesDraft)) {
3205
- const { editMessageMatrix } = await loadMatrixSendModule();
3206
- textEditOk = await editMessageMatrix(roomId, draftEventId, payloadText, {
3207
- client,
3208
- cfg,
3209
- threadId: threadTarget,
3210
- accountId: _route.accountId,
3211
- extraContent: quietDraftStreaming ? buildMatrixFinalizedPreviewContent() : void 0
3212
- }).then(() => true, () => false);
3213
- } else if (textEditOk && reusesDraftTextUnchanged) textEditOk = await draftStream.finalizeLive();
3214
- const reusesDraftAsFinalText = Boolean(payloadText?.trim()) && textEditOk;
3215
- if (!reusesDraftAsFinalText) await redactMatrixDraftEvent(client, roomId, draftEventId);
3216
- await deliverMatrixReplies({
3217
- cfg,
3218
- replies: [ttsSupplement && reusesDraftAsFinalText ? buildTtsSupplementMediaPayload(payload) : {
3219
- ...payload,
3220
- text: reusesDraftAsFinalText ? void 0 : payload.text ?? (ttsSupplement?.visibleTextAlreadyDelivered === true ? void 0 : ttsSupplement?.spokenText)
3221
- }],
3222
- roomId,
3223
- client,
3224
- runtime,
3225
- textLimit,
3226
- replyToMode,
3227
- threadId: threadTarget,
3228
- accountId: _route.accountId,
3229
- mediaLocalRoots,
3230
- tableMode
3231
- });
3232
- draftConsumed = true;
3233
- } else {
3234
- const draftRedacted = Boolean(draftEventId) && (payload.isError || payloadReplyMismatch || mustDeliverFinalNormally);
3235
- if (draftRedacted && draftEventId) await redactMatrixDraftEvent(client, roomId, draftEventId);
3236
- const deliveredFallback = await deliverMatrixReplies({
3237
- cfg,
3238
- replies: [fallbackPayload],
3239
- roomId,
3240
- client,
3241
- runtime,
3242
- textLimit,
3243
- replyToMode,
3244
- threadId: threadTarget,
3245
- accountId: _route.accountId,
3246
- mediaLocalRoots,
3247
- tableMode
3248
- });
3249
- if (draftRedacted || deliveredFallback) draftConsumed = true;
3250
- }
3251
- if (info.kind === "block") {
3252
- draftConsumed = false;
3253
- advanceDraftBlockBoundary({ fallbackToLatestEnd: true });
3254
- draftStream.reset();
3255
- currentDraftReplyToId = replyToMode === "all" ? draftReplyToId : void 0;
3256
- updateDraftFromLatestFullText();
3257
- const { sendTypingMatrix } = await loadMatrixSendModule();
3258
- await sendTypingMatrix(roomId, true, void 0, client).catch(() => {});
3259
- }
3260
- } else await deliverMatrixReplies({
3261
- cfg,
3262
- replies: [payload],
3263
- roomId,
3264
- client,
3265
- runtime,
3266
- textLimit,
3267
- replyToMode,
3268
- threadId: threadTarget,
3269
- accountId: _route.accountId,
3270
- mediaLocalRoots,
3271
- tableMode
3272
- });
3273
- },
3274
- onError: (err, info) => {
3275
- if (err instanceof MatrixRetryableInboundError) retryableReplyDeliveryFailed = true;
3276
- if (info.kind === "final") finalReplyDeliveryFailed = true;
3277
- else nonFinalReplyDeliveryFailed = true;
3278
- if (info.kind === "block") advanceDraftBlockBoundary({ fallbackToLatestEnd: true });
3279
- runtime.error?.(`matrix ${info.kind} reply failed: ${String(err)}`);
3280
- },
3281
- onReplyStart: typingCallbacks.onReplyStart,
3282
- onIdle: typingCallbacks.onIdle
3283
- });
3284
- const pinnedMainDmOwner = isDirectMessage ? await (async () => {
3285
- const livePinnedCfg = core.config.current();
3286
- const livePinnedDmAllowFrom = await resolveCachedLiveAllowlist({
3287
- cfg: livePinnedCfg,
3288
- entries: resolveMatrixAccountAllowlistConfig({
3289
- cfg: livePinnedCfg,
3290
- accountId
3291
- }).dmAllowFrom,
3292
- startupResolvedEntries: allowFromResolvedEntries,
3293
- cache: liveDmAllowlistCache,
3294
- updateCache: (next) => {
3295
- liveDmAllowlistCache = next;
3296
- }
3297
- });
3298
- return resolvePinnedMainDmOwnerFromAllowlist({
3299
- dmScope: livePinnedCfg.session?.dmScope,
3300
- allowFrom: livePinnedDmAllowFrom,
3301
- normalizeEntry: normalizeMatrixUserId
3302
- });
3303
- })() : null;
3304
- const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
3305
- route: _route,
3306
- sessionKey: _route.sessionKey
3307
- });
3308
- const turnResult = await core.channel.turn.run({
3309
- channel: "matrix",
3310
- accountId: _route.accountId,
3311
- raw: event,
3312
- adapter: {
3313
- ingest: () => ({
3314
- id: messageId,
3315
- rawText: bodyText,
3316
- textForAgent: ctxPayload.BodyForAgent,
3317
- textForCommands: ctxPayload.CommandBody,
3318
- raw: event
3319
- }),
3320
- resolveTurn: () => ({
3321
- channel: "matrix",
3322
- accountId: _route.accountId,
3323
- routeSessionKey: _route.sessionKey,
3324
- storePath,
3325
- ctxPayload,
3326
- recordInboundSession: core.channel.session.recordInboundSession,
3327
- botLoopProtection,
3328
- record: {
3329
- updateLastRoute: isDirectMessage ? {
3330
- sessionKey: inboundLastRouteSessionKey,
3331
- channel: "matrix",
3332
- to: `room:${roomId}`,
3333
- accountId: _route.accountId,
3334
- mainDmOwnerPin: inboundLastRouteSessionKey === _route.mainSessionKey && pinnedMainDmOwner ? {
3335
- ownerRecipient: pinnedMainDmOwner,
3336
- senderRecipient: normalizeMatrixUserId(senderId),
3337
- onSkip: ({ ownerRecipient, senderRecipient }) => {
3338
- logVerboseMessage(`matrix: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
3339
- }
3340
- } : void 0
3341
- } : void 0,
3342
- onRecordError: (err) => {
3343
- logger.warn("failed updating session meta", {
3344
- error: String(err),
3345
- storePath,
3346
- sessionKey: ctxPayload.SessionKey ?? _route.sessionKey
3347
- });
3348
- }
3349
- },
3350
- onPreDispatchFailure: () => core.channel.reply.settleReplyDispatcher({
3351
- dispatcher,
3352
- onSettled: () => {
3353
- markRunComplete();
3354
- markDispatchIdle();
3355
- }
3356
- }),
3357
- runDispatch: async () => {
3358
- if (sharedDmContextNotice && markTrackedRoomIfFirst(sharedDmContextNoticeRooms, roomId)) client.sendMessage(roomId, {
3359
- msgtype: "m.notice",
3360
- body: sharedDmContextNotice
3361
- }).catch((err) => {
3362
- logVerboseMessage(`matrix: failed sending shared DM session notice room=${roomId}: ${String(err)}`);
3363
- });
3364
- return await core.channel.reply.withReplyDispatcher({
3365
- dispatcher,
3366
- onSettled: () => {
3367
- markDispatchIdle();
3368
- },
3369
- run: async () => {
3370
- try {
3371
- return await core.channel.reply.dispatchReplyFromConfig({
3372
- ctx: ctxPayload,
3373
- cfg,
3374
- dispatcher,
3375
- replyOptions: {
3376
- ...replyOptions,
3377
- skillFilter: roomConfig?.skills,
3378
- disableBlockStreaming: !blockStreamingEnabled,
3379
- onPartialReply: draftStream ? (payload) => {
3380
- if (progressDraftStreaming) return;
3381
- latestDraftFullText = payload.text ?? "";
3382
- suppressPreviewToolProgressForAnswerText(latestDraftFullText);
3383
- updateDraftFromLatestFullText();
3384
- } : void 0,
3385
- onBlockReplyQueued: draftStream ? (payload, context) => {
3386
- if (payload.isCompactionNotice === true) return;
3387
- queueDraftBlockBoundary(payload, context);
3388
- } : void 0,
3389
- onAssistantMessageStart: draftStream ? () => {
3390
- resetDraftBlockOffsets();
3391
- resetPreviewToolProgress();
3392
- } : void 0,
3393
- ...buildPreviewToolProgressReplyOptions(),
3394
- onModelSelected
3395
- }
3396
- });
3397
- } finally {
3398
- progressDraftGate.cancel();
3399
- markRunComplete();
3400
- }
3401
- }
3402
- });
3403
- }
3404
- })
3405
- }
3406
- });
3407
- if (!turnResult.dispatched) {
3408
- if (turnResult.admission.kind === "drop" && turnResult.admission.reason === "bot-loop-protection") await commitInboundEventIfClaimed();
3409
- return;
3410
- }
3411
- const { dispatchResult } = turnResult;
3412
- const { queuedFinal, counts } = dispatchResult;
3413
- if (finalReplyDeliveryFailed) {
3414
- if (retryableReplyDeliveryFailed) {
3415
- logVerboseMessage(`matrix: final reply delivery failed room=${roomId} id=${messageId}; leaving event uncommitted`);
3416
- return;
3417
- }
3418
- logVerboseMessage(`matrix: final reply delivery failed room=${roomId} id=${messageId}; keeping replay committed`);
3419
- await commitInboundEventIfClaimed();
3420
- return;
3421
- }
3422
- if (!queuedFinal && nonFinalReplyDeliveryFailed) {
3423
- if (retryableReplyDeliveryFailed) {
3424
- logVerboseMessage(`matrix: non-final reply delivery failed room=${roomId} id=${messageId}; leaving event uncommitted`);
3425
- return;
3426
- }
3427
- logVerboseMessage(`matrix: non-final reply delivery failed room=${roomId} id=${messageId}; keeping replay committed`);
3428
- await commitInboundEventIfClaimed();
3429
- return;
3430
- }
3431
- if (isRoom && triggerSnapshot) roomHistoryTracker.consumeHistory(_route.agentId, roomId, triggerSnapshot, messageId);
3432
- if (!hasFinalChannelTurnDispatch({
3433
- queuedFinal,
3434
- counts
3435
- })) {
3436
- await commitInboundEventIfClaimed();
3437
- return;
3438
- }
3439
- const finalCount = counts.final;
3440
- logVerboseMessage(`matrix: delivered ${finalCount} reply${finalCount === 1 ? "" : "ies"} to ${replyTarget}`);
3441
- await commitInboundEventIfClaimed();
3442
- } catch (err) {
3443
- runtime.error?.(`matrix handler failed: ${String(err)}`);
3444
- } finally {
3445
- if (draftStreamRef) {
3446
- const draftEventId = await draftStreamRef.stop().catch(() => void 0);
3447
- if (draftEventId && !draftConsumed) await redactMatrixDraftEvent(client, roomId, draftEventId);
3448
- }
3449
- if (claimedInboundEvent && inboundDeduper && eventId) inboundDeduper.releaseEvent({
3450
- roomId,
3451
- eventId
3452
- });
3453
- }
3454
- };
3455
- }
3456
- //#endregion
3457
- //#region extensions/matrix/src/matrix/monitor/inbound-dedupe.ts
3458
- const INBOUND_DEDUPE_FILENAME = "inbound-dedupe.json";
3459
- const STORE_VERSION = 1;
3460
- const DEFAULT_MAX_ENTRIES = 2e4;
3461
- const DEFAULT_TTL_MS = 720 * 60 * 60 * 1e3;
3462
- const PERSIST_DEBOUNCE_MS = 250;
3463
- function normalizeEventPart(value) {
3464
- return value.trim();
3465
- }
3466
- function buildEventKey(params) {
3467
- const roomId = normalizeEventPart(params.roomId);
3468
- const eventId = normalizeEventPart(params.eventId);
3469
- return roomId && eventId ? `${roomId}|${eventId}` : "";
3470
- }
3471
- function resolveInboundDedupeStatePath(params) {
3472
- return resolveMatrixStateFilePath({
3473
- auth: params.auth,
3474
- env: params.env,
3475
- stateDir: params.stateDir,
3476
- filename: INBOUND_DEDUPE_FILENAME
3477
- });
3478
- }
3479
- function normalizeTimestamp(raw) {
3480
- if (typeof raw !== "number" || !Number.isFinite(raw)) return null;
3481
- return Math.max(0, Math.floor(raw));
3482
- }
3483
- function pruneSeenEvents(params) {
3484
- const { seen, ttlMs, maxEntries, nowMs } = params;
3485
- if (ttlMs > 0) {
3486
- const cutoff = nowMs - ttlMs;
3487
- for (const [key, ts] of seen) if (ts < cutoff) seen.delete(key);
3488
- }
3489
- const max = Math.max(0, Math.floor(maxEntries));
3490
- if (max <= 0) {
3491
- seen.clear();
3492
- return;
3493
- }
3494
- while (seen.size > max) {
3495
- const oldestKey = seen.keys().next().value;
3496
- if (typeof oldestKey !== "string") break;
3497
- seen.delete(oldestKey);
3498
- }
3499
- }
3500
- function toStoredState(params) {
3501
- pruneSeenEvents(params);
3502
- return {
3503
- version: STORE_VERSION,
3504
- entries: Array.from(params.seen.entries()).map(([key, ts]) => ({
3505
- key,
3506
- ts
3507
- }))
3508
- };
3509
- }
3510
- async function readStoredState(storagePath) {
3511
- const { value } = await readJsonFileWithFallback(storagePath, null);
3512
- if (value?.version !== STORE_VERSION || !Array.isArray(value.entries)) return null;
3513
- return value;
3514
- }
3515
- async function createMatrixInboundEventDeduper(params) {
3516
- const nowMs = params.nowMs ?? (() => Date.now());
3517
- const ttlMs = typeof params.ttlMs === "number" && Number.isFinite(params.ttlMs) ? Math.max(0, Math.floor(params.ttlMs)) : DEFAULT_TTL_MS;
3518
- const maxEntries = typeof params.maxEntries === "number" && Number.isFinite(params.maxEntries) ? Math.max(0, Math.floor(params.maxEntries)) : DEFAULT_MAX_ENTRIES;
3519
- const storagePath = params.storagePath ?? resolveInboundDedupeStatePath({
3520
- auth: params.auth,
3521
- env: params.env,
3522
- stateDir: params.stateDir
3523
- });
3524
- const seen = /* @__PURE__ */ new Map();
3525
- const pending = /* @__PURE__ */ new Set();
3526
- const persistLock = createAsyncLock();
3527
- try {
3528
- const stored = await readStoredState(storagePath);
3529
- for (const entry of stored?.entries ?? []) {
3530
- if (!entry || typeof entry.key !== "string") continue;
3531
- const key = entry.key.trim();
3532
- const ts = normalizeTimestamp(entry.ts);
3533
- if (!key || ts === null) continue;
3534
- seen.set(key, ts);
3535
- }
3536
- pruneSeenEvents({
3537
- seen,
3538
- ttlMs,
3539
- maxEntries,
3540
- nowMs: nowMs()
3541
- });
3542
- } catch (err) {
3543
- LogService.warn("MatrixInboundDedupe", "Failed loading Matrix inbound dedupe store:", err);
3544
- }
3545
- let dirty = false;
3546
- let persistTimer = null;
3547
- let persistPromise = null;
3548
- const persist = async () => {
3549
- dirty = false;
3550
- const payload = toStoredState({
3551
- seen,
3552
- ttlMs,
3553
- maxEntries,
3554
- nowMs: nowMs()
3555
- });
3556
- try {
3557
- await persistLock(async () => {
3558
- await writeJsonFileAtomically(storagePath, payload);
3559
- });
3560
- } catch (err) {
3561
- dirty = true;
3562
- throw err;
3563
- }
3564
- };
3565
- const flush = async () => {
3566
- if (persistTimer) {
3567
- clearTimeout(persistTimer);
3568
- persistTimer = null;
3569
- }
3570
- for (;;) {
3571
- if (!dirty && !persistPromise) break;
3572
- if (dirty && !persistPromise) persistPromise = persist().finally(() => {
3573
- persistPromise = null;
3574
- });
3575
- await persistPromise;
3576
- }
3577
- };
3578
- const schedulePersist = () => {
3579
- dirty = true;
3580
- if (persistTimer) return;
3581
- persistTimer = setTimeout(() => {
3582
- persistTimer = null;
3583
- flush().catch((err) => {
3584
- LogService.warn("MatrixInboundDedupe", "Failed persisting Matrix inbound dedupe store:", err);
3585
- });
3586
- }, PERSIST_DEBOUNCE_MS);
3587
- persistTimer.unref?.();
3588
- };
3589
- return {
3590
- claimEvent: ({ roomId, eventId }) => {
3591
- const key = buildEventKey({
3592
- roomId,
3593
- eventId
3594
- });
3595
- if (!key) return true;
3596
- pruneSeenEvents({
3597
- seen,
3598
- ttlMs,
3599
- maxEntries,
3600
- nowMs: nowMs()
3601
- });
3602
- if (seen.has(key) || pending.has(key)) return false;
3603
- pending.add(key);
3604
- return true;
3605
- },
3606
- commitEvent: async ({ roomId, eventId }) => {
3607
- const key = buildEventKey({
3608
- roomId,
3609
- eventId
3610
- });
3611
- if (!key) return;
3612
- pending.delete(key);
3613
- const ts = nowMs();
3614
- seen.delete(key);
3615
- seen.set(key, ts);
3616
- pruneSeenEvents({
3617
- seen,
3618
- ttlMs,
3619
- maxEntries,
3620
- nowMs: nowMs()
3621
- });
3622
- schedulePersist();
3623
- },
3624
- releaseEvent: ({ roomId, eventId }) => {
3625
- const key = buildEventKey({
3626
- roomId,
3627
- eventId
3628
- });
3629
- if (!key) return;
3630
- pending.delete(key);
3631
- },
3632
- flush,
3633
- stop: async () => {
3634
- try {
3635
- await flush();
3636
- } catch (err) {
3637
- LogService.warn("MatrixInboundDedupe", "Failed to flush Matrix inbound dedupe store during stop():", err);
3638
- }
3639
- }
3640
- };
3641
- }
3642
- //#endregion
3643
- //#region extensions/matrix/src/matrix/monitor/recent-invite.ts
3644
- function shouldPromoteRecentInviteRoom(params) {
3645
- if (!params.roomInfo.nameResolved || !params.roomInfo.aliasesResolved) return false;
3646
- const roomAliases = [params.roomInfo.canonicalAlias ?? "", ...params.roomInfo.altAliases].filter(Boolean);
3647
- if ((params.roomInfo.name?.trim() ?? "") || roomAliases.length > 0) return false;
3648
- return resolveMatrixRoomConfig({
3649
- rooms: params.rooms,
3650
- roomId: params.roomId,
3651
- aliases: roomAliases
3652
- }).matchSource === void 0;
3653
- }
3654
- //#endregion
3655
- //#region extensions/matrix/src/matrix/monitor/room-info.ts
3656
- const MAX_TRACKED_ROOM_INFO = 1024;
3657
- const MAX_TRACKED_MEMBER_DISPLAY_NAMES = 4096;
3658
- function rememberBounded(map, key, value, maxEntries) {
3659
- map.set(key, value);
3660
- if (map.size > maxEntries) {
3661
- const oldest = map.keys().next().value;
3662
- if (typeof oldest === "string") map.delete(oldest);
3663
- }
3664
- }
3665
- function createMatrixRoomInfoResolver(client) {
3666
- const roomNameCache = /* @__PURE__ */ new Map();
3667
- const roomAliasCache = /* @__PURE__ */ new Map();
3668
- const memberDisplayNameCache = /* @__PURE__ */ new Map();
3669
- const getRoomName = async (roomId) => {
3670
- if (roomNameCache.has(roomId)) return roomNameCache.get(roomId) ?? { nameResolved: false };
3671
- let name;
3672
- let nameResolved = false;
3673
- try {
3674
- const nameState = await client.getRoomStateEvent(roomId, "m.room.name", "");
3675
- nameResolved = true;
3676
- if (nameState && typeof nameState.name === "string") name = nameState.name;
3677
- } catch (err) {
3678
- if (isMatrixNotFoundError(err)) nameResolved = true;
3679
- }
3680
- const info = {
3681
- name,
3682
- nameResolved
3683
- };
3684
- if (nameResolved) rememberBounded(roomNameCache, roomId, info, MAX_TRACKED_ROOM_INFO);
3685
- return info;
3686
- };
3687
- const getRoomAliases = async (roomId) => {
3688
- const cached = roomAliasCache.get(roomId);
3689
- if (cached) return cached;
3690
- let canonicalAlias;
3691
- let altAliases = [];
3692
- let aliasesResolved = false;
3693
- try {
3694
- const aliasState = await client.getRoomStateEvent(roomId, "m.room.canonical_alias", "");
3695
- aliasesResolved = true;
3696
- if (aliasState && typeof aliasState.alias === "string") canonicalAlias = aliasState.alias;
3697
- const rawAliases = aliasState?.alt_aliases;
3698
- if (Array.isArray(rawAliases)) altAliases = rawAliases.filter((entry) => typeof entry === "string");
3699
- } catch (err) {
3700
- if (isMatrixNotFoundError(err)) aliasesResolved = true;
3701
- }
3702
- const info = {
3703
- canonicalAlias,
3704
- altAliases,
3705
- aliasesResolved
3706
- };
3707
- if (aliasesResolved) rememberBounded(roomAliasCache, roomId, info, MAX_TRACKED_ROOM_INFO);
3708
- return info;
3709
- };
3710
- const getRoomInfo = async (roomId, opts = {}) => {
3711
- const { name, nameResolved } = await getRoomName(roomId);
3712
- if (!opts.includeAliases) return {
3713
- name,
3714
- altAliases: [],
3715
- nameResolved,
3716
- aliasesResolved: false
3717
- };
3718
- return {
3719
- name,
3720
- nameResolved,
3721
- ...await getRoomAliases(roomId)
3722
- };
3723
- };
3724
- const getMemberDisplayName = async (roomId, userId) => {
3725
- const cacheKey = `${roomId}:${userId}`;
3726
- if (memberDisplayNameCache.has(cacheKey)) return memberDisplayNameCache.get(cacheKey) ?? userId;
3727
- const memberState = await client.getRoomStateEvent(roomId, "m.room.member", userId).catch(() => null);
3728
- const displayName = memberState && typeof memberState.displayname === "string" ? memberState.displayname : userId;
3729
- rememberBounded(memberDisplayNameCache, cacheKey, displayName, MAX_TRACKED_MEMBER_DISPLAY_NAMES);
3730
- return displayName;
3731
- };
3732
- return {
3733
- getRoomInfo,
3734
- getMemberDisplayName
3735
- };
3736
- }
3737
- //#endregion
3738
- //#region extensions/matrix/src/matrix/monitor/startup.ts
3739
- let matrixStartupMaintenanceDepsPromise;
3740
- async function loadMatrixStartupMaintenanceDeps() {
3741
- matrixStartupMaintenanceDepsPromise ??= Promise.all([
3742
- import("./config-update-U5fJI7oN.js"),
3743
- import("./device-health-CJqwWGmU.js"),
3744
- import("./profile-Bca_U_rV.js"),
3745
- import("./legacy-crypto-restore-D2CzFkbv.js"),
3746
- import("./startup-verification-D7jkPyKf.js")
3747
- ]).then(([configUpdateModule, deviceHealthModule, profileModule, legacyCryptoRestoreModule, startupVerificationModule]) => ({
3748
- updateMatrixAccountConfig: configUpdateModule.updateMatrixAccountConfig,
3749
- summarizeMatrixDeviceHealth: deviceHealthModule.summarizeMatrixDeviceHealth,
3750
- syncMatrixOwnProfile: profileModule.syncMatrixOwnProfile,
3751
- maybeRestoreLegacyMatrixBackup: legacyCryptoRestoreModule.maybeRestoreLegacyMatrixBackup,
3752
- ensureMatrixStartupVerification: startupVerificationModule.ensureMatrixStartupVerification
3753
- }));
3754
- return await matrixStartupMaintenanceDepsPromise;
3755
- }
3756
- async function runMatrixStartupMaintenance(params, deps) {
3757
- const runtimeDeps = deps ?? await loadMatrixStartupMaintenanceDeps();
3758
- throwIfMatrixStartupAborted(params.abortSignal);
3759
- try {
3760
- const profileSync = await runtimeDeps.syncMatrixOwnProfile({
3761
- client: params.client,
3762
- userId: params.auth.userId,
3763
- displayName: params.accountConfig.name,
3764
- avatarUrl: params.accountConfig.avatarUrl,
3765
- loadAvatarFromUrl: async (url, maxBytes) => await params.loadWebMedia(url, maxBytes)
3766
- });
3767
- throwIfMatrixStartupAborted(params.abortSignal);
3768
- if (profileSync.displayNameUpdated) params.logger.info(`matrix: profile display name updated for ${params.auth.userId}`);
3769
- if (profileSync.avatarUpdated) params.logger.info(`matrix: profile avatar updated for ${params.auth.userId}`);
3770
- if (profileSync.convertedAvatarFromHttp && profileSync.resolvedAvatarUrl && params.accountConfig.avatarUrl !== profileSync.resolvedAvatarUrl) {
3771
- const latestCfg = params.getRuntimeConfig();
3772
- const updatedCfg = runtimeDeps.updateMatrixAccountConfig(latestCfg, params.accountId, { avatarUrl: profileSync.resolvedAvatarUrl });
3773
- await params.replaceConfigFile(updatedCfg);
3774
- throwIfMatrixStartupAborted(params.abortSignal);
3775
- params.logVerboseMessage(`matrix: persisted converted avatar URL for account ${params.accountId} (${profileSync.resolvedAvatarUrl})`);
3776
- }
3777
- } catch (err) {
3778
- if (isMatrixStartupAbortError(err)) throw err;
3779
- params.logger.warn("matrix: failed to sync profile from config", { error: String(err) });
3780
- }
3781
- if (!(params.auth.encryption && params.client.crypto)) return;
3782
- try {
3783
- throwIfMatrixStartupAborted(params.abortSignal);
3784
- const deviceHealth = runtimeDeps.summarizeMatrixDeviceHealth(await params.client.listOwnDevices());
3785
- if (deviceHealth.staleDaoCoreDevices.length > 0) params.logger.warn(`matrix: stale DaoCore devices detected for ${params.auth.userId}: ${deviceHealth.staleDaoCoreDevices.map((device) => device.deviceId).join(", ")}. Run 'daocore matrix devices prune-stale --account ${params.effectiveAccountId}' to keep encrypted-room trust healthy.`);
3786
- } catch (err) {
3787
- if (isMatrixStartupAbortError(err)) throw err;
3788
- params.logger.debug?.("Failed to inspect matrix device hygiene (non-fatal)", { error: String(err) });
3789
- }
3790
- try {
3791
- throwIfMatrixStartupAborted(params.abortSignal);
3792
- const startupVerification = await runtimeDeps.ensureMatrixStartupVerification({
3793
- client: params.client,
3794
- auth: params.auth,
3795
- accountConfig: params.accountConfig,
3796
- env: params.env
3797
- });
3798
- throwIfMatrixStartupAborted(params.abortSignal);
3799
- if (startupVerification.kind === "verified") params.logger.info("matrix: device is verified by its owner and ready for encrypted rooms");
3800
- else if (startupVerification.kind === "disabled" || startupVerification.kind === "cooldown" || startupVerification.kind === "pending" || startupVerification.kind === "request-failed") {
3801
- params.logger.info("matrix: device not verified — run 'daocore matrix verify device <key>' to enable E2EE");
3802
- if (startupVerification.kind === "pending") params.logger.info("matrix: startup verification request is already pending; finish it in another Matrix client");
3803
- else if (startupVerification.kind === "cooldown") params.logVerboseMessage(`matrix: skipped startup verification request due to cooldown (retryAfterMs=${startupVerification.retryAfterMs ?? 0})`);
3804
- else if (startupVerification.kind === "request-failed") params.logger.debug?.("Matrix startup verification request failed (non-fatal)", { error: startupVerification.error ?? "unknown" });
3805
- } else if (startupVerification.kind === "requested") params.logger.info("matrix: device not verified — requested verification in another Matrix client");
3806
- } catch (err) {
3807
- if (isMatrixStartupAbortError(err)) throw err;
3808
- params.logger.debug?.("Failed to resolve matrix verification status (non-fatal)", { error: String(err) });
3809
- }
3810
- try {
3811
- throwIfMatrixStartupAborted(params.abortSignal);
3812
- const legacyCryptoRestore = await runtimeDeps.maybeRestoreLegacyMatrixBackup({
3813
- client: params.client,
3814
- auth: params.auth,
3815
- env: params.env
3816
- });
3817
- throwIfMatrixStartupAborted(params.abortSignal);
3818
- if (legacyCryptoRestore.kind === "restored") {
3819
- params.logger.info(`matrix: restored ${legacyCryptoRestore.imported}/${legacyCryptoRestore.total} room key(s) from legacy encrypted-state backup`);
3820
- if (legacyCryptoRestore.localOnlyKeys > 0) params.logger.warn(`matrix: ${legacyCryptoRestore.localOnlyKeys} legacy local-only room key(s) were never backed up and could not be restored automatically`);
3821
- } else if (legacyCryptoRestore.kind === "failed") {
3822
- params.logger.warn(`matrix: failed restoring room keys from legacy encrypted-state backup: ${legacyCryptoRestore.error}`);
3823
- if (legacyCryptoRestore.localOnlyKeys > 0) params.logger.warn(`matrix: ${legacyCryptoRestore.localOnlyKeys} legacy local-only room key(s) were never backed up and may remain unavailable until manually recovered`);
3824
- }
3825
- } catch (err) {
3826
- if (isMatrixStartupAbortError(err)) throw err;
3827
- params.logger.warn("matrix: failed restoring legacy encrypted-state backup", { error: String(err) });
3828
- }
3829
- }
3830
- //#endregion
3831
- //#region extensions/matrix/src/matrix/monitor/status.ts
3832
- function cloneLastDisconnect(value) {
3833
- if (!value || typeof value === "string") return value ?? null;
3834
- return { ...value };
3835
- }
3836
- function formatSyncError(error) {
3837
- if (!error) return null;
3838
- if (error instanceof Error) return error.message || error.name || "unknown";
3839
- return formatMatrixErrorMessage(error);
3840
- }
3841
- function createMatrixMonitorStatusController(params) {
3842
- const status = {
3843
- accountId: params.accountId,
3844
- ...params.baseUrl ? { baseUrl: params.baseUrl } : {},
3845
- connected: false,
3846
- lastConnectedAt: null,
3847
- lastDisconnect: null,
3848
- lastError: null,
3849
- healthState: "starting"
3850
- };
3851
- const emit = () => {
3852
- params.statusSink?.({
3853
- ...status,
3854
- lastDisconnect: cloneLastDisconnect(status.lastDisconnect)
3855
- });
3856
- };
3857
- const noteConnected = (at = Date.now(), options) => {
3858
- if (status.connected === true) status.lastEventAt = at;
3859
- else Object.assign(status, createConnectedChannelStatusPatch(at));
3860
- if (options?.transportActivity) Object.assign(status, createTransportActivityStatusPatch(at));
3861
- status.lastError = null;
3862
- status.lastDisconnect = null;
3863
- status.healthState = "healthy";
3864
- emit();
3865
- };
3866
- const noteDisconnected = (params) => {
3867
- const at = params.at ?? Date.now();
3868
- const error = formatSyncError(params.error);
3869
- status.connected = false;
3870
- status.lastEventAt = at;
3871
- status.lastDisconnect = {
3872
- at,
3873
- ...error ? { error } : {}
3874
- };
3875
- status.lastError = error;
3876
- status.healthState = params.state.toLowerCase();
3877
- emit();
3878
- };
3879
- emit();
3880
- return {
3881
- noteSyncState(state, error, at = Date.now()) {
3882
- if (isMatrixReadySyncState(state)) {
3883
- noteConnected(at, { transportActivity: state === "SYNCING" });
3884
- return;
3885
- }
3886
- if (isMatrixDisconnectedSyncState(state)) {
3887
- noteDisconnected({
3888
- state,
3889
- at,
3890
- error
3891
- });
3892
- return;
3893
- }
3894
- status.lastEventAt = at;
3895
- status.healthState = state.toLowerCase();
3896
- emit();
3897
- },
3898
- noteUnexpectedError(error, at = Date.now()) {
3899
- noteDisconnected({
3900
- state: "ERROR",
3901
- at,
3902
- error
3903
- });
3904
- },
3905
- markStopped(at = Date.now()) {
3906
- status.connected = false;
3907
- status.lastEventAt = at;
3908
- if (status.healthState !== "error") status.healthState = "stopped";
3909
- emit();
3910
- }
3911
- };
3912
- }
3913
- //#endregion
3914
- //#region extensions/matrix/src/matrix/monitor/sync-lifecycle.ts
3915
- function formatSyncLifecycleError(state, error) {
3916
- if (error instanceof Error) return error;
3917
- const message = typeof error === "string" && error.trim() ? error.trim() : void 0;
3918
- if (state === "STOPPED") return new Error(message ?? "Matrix sync stopped unexpectedly");
3919
- if (state === "ERROR") return new Error(message ?? "Matrix sync entered ERROR unexpectedly");
3920
- return new Error(message ?? `Matrix sync entered ${state} unexpectedly`);
3921
- }
3922
- function createMatrixMonitorSyncLifecycle(params) {
3923
- let fatalError = null;
3924
- let resolveFatalWait = null;
3925
- let rejectFatalWait = null;
3926
- const settleFatal = (error) => {
3927
- if (fatalError) return;
3928
- fatalError = error;
3929
- rejectFatalWait?.(error);
3930
- resolveFatalWait = null;
3931
- rejectFatalWait = null;
3932
- };
3933
- const onSyncState = (state, _prevState, error) => {
3934
- if (isMatrixTerminalSyncState(state) && !params.isStopping?.()) {
3935
- const fatalError = formatSyncLifecycleError(state, error);
3936
- params.statusController.noteUnexpectedError(fatalError);
3937
- settleFatal(fatalError);
3938
- return;
3939
- }
3940
- if (fatalError) return;
3941
- if (params.isStopping?.() && !isMatrixTerminalSyncState(state)) return;
3942
- params.statusController.noteSyncState(state, error);
3943
- };
3944
- const onUnexpectedError = (error) => {
3945
- if (params.isStopping?.()) return;
3946
- params.statusController.noteUnexpectedError(error);
3947
- settleFatal(error);
3948
- };
3949
- params.client.on("sync.state", onSyncState);
3950
- params.client.on("sync.unexpected_error", onUnexpectedError);
3951
- return {
3952
- async waitForFatalStop() {
3953
- if (fatalError) throw fatalError;
3954
- if (resolveFatalWait || rejectFatalWait) throw new Error("Matrix fatal-stop wait already in progress");
3955
- await new Promise((resolve, reject) => {
3956
- resolveFatalWait = resolve;
3957
- rejectFatalWait = (error) => reject(error);
3958
- });
3959
- },
3960
- dispose() {
3961
- resolveFatalWait?.();
3962
- resolveFatalWait = null;
3963
- rejectFatalWait = null;
3964
- params.client.off("sync.state", onSyncState);
3965
- params.client.off("sync.unexpected_error", onUnexpectedError);
3966
- }
3967
- };
3968
- }
3969
- //#endregion
3970
- //#region extensions/matrix/src/matrix/monitor/task-runner.ts
3971
- function createMatrixMonitorTaskRunner(params) {
3972
- const inFlight = /* @__PURE__ */ new Set();
3973
- const runDetachedTask = (label, task) => {
3974
- let trackedTask;
3975
- trackedTask = Promise.resolve().then(task).catch((error) => {
3976
- const message = String(error);
3977
- params.logVerboseMessage(`matrix: ${label} failed (${message})`);
3978
- params.logger.warn("matrix background task failed", {
3979
- task: label,
3980
- error: message
3981
- });
3982
- }).finally(() => {
3983
- inFlight.delete(trackedTask);
3984
- });
3985
- inFlight.add(trackedTask);
3986
- return trackedTask;
3987
- };
3988
- const waitForIdle = async () => {
3989
- while (inFlight.size > 0) await Promise.allSettled(Array.from(inFlight));
3990
- };
3991
- return {
3992
- runDetachedTask,
3993
- waitForIdle
3994
- };
3995
- }
3996
- //#endregion
3997
- //#region extensions/matrix/src/matrix/monitor/index.ts
3998
- function isMatrixStreamingConfig(streaming) {
3999
- return Boolean(streaming && typeof streaming === "object" && !Array.isArray(streaming));
4000
- }
4001
- function resolveMatrixStreamingMode(streaming) {
4002
- if (streaming === true || streaming === "partial") return "partial";
4003
- if (streaming === "quiet") return "quiet";
4004
- if (streaming === "progress") return "progress";
4005
- if (isMatrixStreamingConfig(streaming)) {
4006
- if (streaming.mode === "partial" || streaming.mode === "quiet" || streaming.mode === "progress") return streaming.mode;
4007
- }
4008
- return "off";
4009
- }
4010
- function resolveMatrixPreviewToolProgress(streaming) {
4011
- if (!isMatrixStreamingConfig(streaming)) return true;
4012
- if (resolveMatrixStreamingMode(streaming) === "progress") return streaming.progress?.toolProgress ?? streaming.preview?.toolProgress ?? true;
4013
- return streaming.preview?.toolProgress ?? true;
4014
- }
4015
- function resolveMatrixPreviewToolProgressEnabled(streaming) {
4016
- return resolveMatrixStreamingMode(streaming) !== "off" && resolveMatrixPreviewToolProgress(streaming);
4017
- }
4018
- const DEFAULT_MEDIA_MAX_MB = 20;
4019
- async function monitorMatrixProvider(opts = {}) {
4020
- if (opts.abortSignal?.aborted) return;
4021
- if (isBunRuntime()) throw new Error("Matrix provider requires Node (bun runtime not supported)");
4022
- const core = getMatrixRuntime();
4023
- let cfg = core.config.current();
4024
- if (cfg.channels?.["matrix"]?.enabled === false) return;
4025
- const logger = core.logging.getChildLogger({ module: "matrix-auto-reply" });
4026
- const formatRuntimeMessage = (...args) => format(...args);
4027
- const runtime = opts.runtime ?? {
4028
- log: (...args) => {
4029
- logger.info(formatRuntimeMessage(...args));
4030
- },
4031
- error: (...args) => {
4032
- logger.error(formatRuntimeMessage(...args));
4033
- },
4034
- exit: (code) => {
4035
- throw new Error(`exit ${code}`);
4036
- }
4037
- };
4038
- const logVerboseMessage = (message) => {
4039
- if (!core.logging.shouldLogVerbose()) return;
4040
- logger.debug?.(message);
4041
- };
4042
- const effectiveAccountId = resolveMatrixAuthContext({
4043
- cfg,
4044
- accountId: opts.accountId
4045
- }).accountId;
4046
- const accountConfig = resolveMatrixAccountConfig({
4047
- cfg,
4048
- accountId: effectiveAccountId
4049
- });
4050
- const allowlistOnly = accountConfig.allowlistOnly === true;
4051
- const accountAllowBots = accountConfig.allowBots;
4052
- let allowFrom = (accountConfig.dm?.allowFrom ?? []).map(String);
4053
- let groupAllowFrom = (accountConfig.groupAllowFrom ?? []).map(String);
4054
- let allowFromResolvedEntries = [];
4055
- let groupAllowFromResolvedEntries = [];
4056
- let roomsConfig = accountConfig.groups ?? accountConfig.rooms;
4057
- let needsRoomAliasesForConfig = false;
4058
- const configuredBotUserIds = resolveConfiguredMatrixBotUserIds({
4059
- cfg,
4060
- accountId: effectiveAccountId
4061
- });
4062
- ({allowFrom, allowFromResolvedEntries, groupAllowFrom, groupAllowFromResolvedEntries, roomsConfig} = await resolveMatrixMonitorConfig({
4063
- cfg,
4064
- accountId: effectiveAccountId,
4065
- allowFrom,
4066
- groupAllowFrom,
4067
- roomsConfig,
4068
- runtime
4069
- }));
4070
- needsRoomAliasesForConfig = Boolean(roomsConfig && Object.keys(roomsConfig).some((key) => key.trim().startsWith("#")));
4071
- cfg = {
4072
- ...cfg,
4073
- channels: {
4074
- ...cfg.channels,
4075
- matrix: {
4076
- ...cfg.channels?.["matrix"],
4077
- dm: {
4078
- ...cfg.channels?.["matrix"]?.dm,
4079
- allowFrom
4080
- },
4081
- groupAllowFrom,
4082
- ...roomsConfig ? { groups: roomsConfig } : {}
4083
- }
4084
- }
4085
- };
4086
- const auth = await resolveMatrixAuth({
4087
- cfg,
4088
- accountId: effectiveAccountId
4089
- });
4090
- const resolvedInitialSyncLimit = typeof opts.initialSyncLimit === "number" ? Math.max(0, Math.floor(opts.initialSyncLimit)) : auth.initialSyncLimit;
4091
- const authWithLimit = resolvedInitialSyncLimit === auth.initialSyncLimit ? auth : {
4092
- ...auth,
4093
- initialSyncLimit: resolvedInitialSyncLimit
4094
- };
4095
- const statusController = createMatrixMonitorStatusController({
4096
- accountId: auth.accountId,
4097
- baseUrl: auth.homeserver,
4098
- statusSink: opts.setStatus
4099
- });
4100
- let cleanedUp = false;
4101
- let client = null;
4102
- let threadBindingManager = null;
4103
- let inboundDeduper = null;
4104
- const monitorTaskRunner = createMatrixMonitorTaskRunner({
4105
- logger,
4106
- logVerboseMessage
4107
- });
4108
- let syncLifecycle = null;
4109
- const cleanup = async (mode = "persist") => {
4110
- if (cleanedUp) return;
4111
- cleanedUp = true;
4112
- try {
4113
- client?.stopSyncWithoutPersist();
4114
- if (client && mode === "persist") await client.drainPendingDecryptions("matrix monitor shutdown");
4115
- if (mode === "persist") await monitorTaskRunner.waitForIdle();
4116
- threadBindingManager?.stop();
4117
- await inboundDeduper?.stop();
4118
- if (client) await releaseSharedClientInstance(client, mode);
4119
- } finally {
4120
- client?.off("sync.state", onSyncState);
4121
- syncLifecycle?.dispose();
4122
- statusController.markStopped();
4123
- setActiveMatrixClient(null, auth.accountId);
4124
- }
4125
- };
4126
- const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
4127
- const { groupPolicy: groupPolicyRaw, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
4128
- providerConfigPresent: cfg.channels?.["matrix"] !== void 0,
4129
- groupPolicy: accountConfig.groupPolicy,
4130
- defaultGroupPolicy
4131
- });
4132
- warnMissingProviderGroupPolicyFallbackOnce({
4133
- providerMissingFallbackApplied,
4134
- providerKey: "matrix",
4135
- accountId: effectiveAccountId,
4136
- blockedLabel: GROUP_POLICY_BLOCKED_LABEL.room,
4137
- log: (message) => logVerboseMessage(message)
4138
- });
4139
- const groupPolicy = allowlistOnly && groupPolicyRaw === "open" ? "allowlist" : groupPolicyRaw;
4140
- const replyToMode = opts.replyToMode ?? accountConfig.replyToMode ?? "off";
4141
- const threadReplies = accountConfig.threadReplies ?? "inbound";
4142
- const dmThreadReplies = accountConfig.dm?.threadReplies;
4143
- const threadBindingIdleTimeoutMs = resolveThreadBindingIdleTimeoutMsForChannel({
4144
- cfg,
4145
- channel: "matrix",
4146
- accountId: effectiveAccountId
4147
- });
4148
- const threadBindingMaxAgeMs = resolveThreadBindingMaxAgeMsForChannel({
4149
- cfg,
4150
- channel: "matrix",
4151
- accountId: effectiveAccountId
4152
- });
4153
- const dmConfig = accountConfig.dm;
4154
- const dmEnabled = dmConfig?.enabled ?? true;
4155
- const dmPolicyRaw = dmConfig?.policy ?? "pairing";
4156
- const dmPolicy = allowlistOnly && dmPolicyRaw !== "disabled" ? "allowlist" : dmPolicyRaw;
4157
- const dmSessionScope = dmConfig?.sessionScope ?? "per-user";
4158
- const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "matrix", effectiveAccountId);
4159
- const globalGroupChatHistoryLimit = cfg.messages?.groupChat?.historyLimit;
4160
- const historyLimit = Math.max(0, accountConfig.historyLimit ?? globalGroupChatHistoryLimit ?? 0);
4161
- const mediaMaxMb = opts.mediaMaxMb ?? accountConfig.mediaMaxMb ?? DEFAULT_MEDIA_MAX_MB;
4162
- const mediaMaxBytes = Math.max(1, mediaMaxMb) * 1024 * 1024;
4163
- const streaming = resolveMatrixStreamingMode(accountConfig.streaming);
4164
- const previewToolProgressEnabled = resolveMatrixPreviewToolProgressEnabled(accountConfig.streaming);
4165
- const blockStreamingEnabled = accountConfig.blockStreaming === true;
4166
- const startupMs = Date.now();
4167
- const startupGraceMs = 0;
4168
- const warnedEncryptedRooms = /* @__PURE__ */ new Set();
4169
- const warnedCryptoMissingRooms = /* @__PURE__ */ new Set();
4170
- let healthySyncSinceMs;
4171
- const noteSyncHealthState = (state, at = Date.now()) => {
4172
- if (isMatrixReadySyncState(state)) {
4173
- healthySyncSinceMs ??= at;
4174
- return;
4175
- }
4176
- if (isMatrixDisconnectedSyncState(state)) healthySyncSinceMs = void 0;
4177
- };
4178
- const onSyncState = (state) => {
4179
- noteSyncHealthState(state);
4180
- };
4181
- try {
4182
- client = await resolveSharedMatrixClient({
4183
- cfg,
4184
- auth: authWithLimit,
4185
- startClient: false,
4186
- accountId: auth.accountId
4187
- });
4188
- setActiveMatrixClient(client, auth.accountId);
4189
- inboundDeduper = await createMatrixInboundEventDeduper({
4190
- auth,
4191
- env: process.env
4192
- });
4193
- syncLifecycle = createMatrixMonitorSyncLifecycle({
4194
- client,
4195
- statusController,
4196
- isStopping: () => cleanedUp || opts.abortSignal?.aborted === true
4197
- });
4198
- client.on("sync.state", onSyncState);
4199
- const dropPreStartupMessages = !client.hasPersistedSyncState();
4200
- const { getRoomInfo, getMemberDisplayName } = createMatrixRoomInfoResolver(client);
4201
- const isExplicitlyConfiguredRoom = async (roomId) => {
4202
- const roomInfoForConfig = needsRoomAliasesForConfig ? await getRoomInfo(roomId, { includeAliases: true }) : void 0;
4203
- const aliases = roomInfoForConfig ? [roomInfoForConfig.canonicalAlias ?? "", ...roomInfoForConfig.altAliases].filter(Boolean) : [];
4204
- return resolveMatrixRoomConfig({
4205
- rooms: roomsConfig,
4206
- roomId,
4207
- aliases
4208
- }).matchSource === "direct";
4209
- };
4210
- const directTracker = createDirectRoomTracker(client, {
4211
- log: logVerboseMessage,
4212
- isExplicitlyConfiguredRoom,
4213
- canPromoteRecentInvite: async (roomId) => shouldPromoteRecentInviteRoom({
4214
- roomId,
4215
- roomInfo: await getRoomInfo(roomId, { includeAliases: true }),
4216
- rooms: roomsConfig
4217
- }),
4218
- ...dmSessionScope === "per-room" ? { canPromoteUnmappedStrictRoom: async (roomId) => shouldPromoteRecentInviteRoom({
4219
- roomId,
4220
- roomInfo: await getRoomInfo(roomId, { includeAliases: true }),
4221
- rooms: roomsConfig
4222
- }) } : {},
4223
- shouldKeepLocallyPromotedDirectRoom: async (roomId) => {
4224
- try {
4225
- const roomInfo = await getRoomInfo(roomId, { includeAliases: true });
4226
- if (!roomInfo.nameResolved || !roomInfo.aliasesResolved) return;
4227
- return shouldPromoteRecentInviteRoom({
4228
- roomId,
4229
- roomInfo,
4230
- rooms: roomsConfig
4231
- });
4232
- } catch (err) {
4233
- logVerboseMessage(`matrix: local promotion revalidation failed room=${roomId} (${String(err)})`);
4234
- return;
4235
- }
4236
- }
4237
- });
4238
- registerMatrixAutoJoin({
4239
- client,
4240
- accountConfig,
4241
- runtime
4242
- });
4243
- const handleRoomMessage = createMatrixRoomMessageHandler({
4244
- client,
4245
- core,
4246
- cfg,
4247
- accountId: effectiveAccountId,
4248
- accountConfig,
4249
- runtime,
4250
- logger,
4251
- logVerboseMessage,
4252
- allowFrom,
4253
- allowFromResolvedEntries,
4254
- groupAllowFrom,
4255
- groupAllowFromResolvedEntries,
4256
- roomsConfig,
4257
- accountAllowBots,
4258
- configuredBotUserIds,
4259
- groupPolicy,
4260
- replyToMode,
4261
- threadReplies,
4262
- dmThreadReplies,
4263
- dmSessionScope,
4264
- streaming,
4265
- previewToolProgressEnabled,
4266
- blockStreamingEnabled,
4267
- dmEnabled,
4268
- dmPolicy,
4269
- textLimit,
4270
- mediaMaxBytes,
4271
- historyLimit,
4272
- startupMs,
4273
- startupGraceMs,
4274
- dropPreStartupMessages,
4275
- inboundDeduper,
4276
- directTracker,
4277
- getRoomInfo,
4278
- getMemberDisplayName,
4279
- needsRoomAliasesForConfig
4280
- });
4281
- threadBindingManager = await createMatrixThreadBindingManager({
4282
- cfg,
4283
- accountId: effectiveAccountId,
4284
- auth,
4285
- client,
4286
- env: process.env,
4287
- idleTimeoutMs: threadBindingIdleTimeoutMs,
4288
- maxAgeMs: threadBindingMaxAgeMs,
4289
- logVerboseMessage
4290
- });
4291
- logVerboseMessage(`matrix: thread bindings ready account=${threadBindingManager.accountId} idleMs=${threadBindingIdleTimeoutMs} maxAgeMs=${threadBindingMaxAgeMs}`);
4292
- registerMatrixMonitorEvents({
4293
- cfg,
4294
- client,
4295
- auth,
4296
- allowFrom,
4297
- dmEnabled,
4298
- dmPolicy,
4299
- readStoreAllowFrom: async () => await core.channel.pairing.readAllowFromStore({
4300
- channel: "matrix",
4301
- env: process.env,
4302
- accountId: effectiveAccountId
4303
- }).catch(() => []),
4304
- directTracker,
4305
- logVerboseMessage,
4306
- warnedEncryptedRooms,
4307
- warnedCryptoMissingRooms,
4308
- logger,
4309
- startupGraceMs,
4310
- getHealthySyncSinceMs: () => healthySyncSinceMs,
4311
- formatNativeDependencyHint: core.system.formatNativeDependencyHint,
4312
- onRoomMessage: handleRoomMessage,
4313
- runDetachedTask: monitorTaskRunner.runDetachedTask
4314
- });
4315
- logVerboseMessage("matrix: starting client");
4316
- await resolveSharedMatrixClient({
4317
- cfg,
4318
- auth: authWithLimit,
4319
- accountId: auth.accountId,
4320
- abortSignal: opts.abortSignal
4321
- });
4322
- logVerboseMessage("matrix: client started");
4323
- logger.info(`matrix: logged in as ${auth.userId}`);
4324
- backfillMatrixAuthDeviceIdAfterStartup({
4325
- auth,
4326
- env: process.env,
4327
- abortSignal: opts.abortSignal
4328
- }).catch((err) => {
4329
- logVerboseMessage(`matrix: failed to backfill deviceId after startup (${String(err)})`);
4330
- });
4331
- registerChannelRuntimeContext({
4332
- channelRuntime: opts.channelRuntime,
4333
- channelId: "matrix",
4334
- accountId: effectiveAccountId,
4335
- capability: CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY,
4336
- context: { client },
4337
- abortSignal: opts.abortSignal
4338
- });
4339
- await runMatrixStartupMaintenance({
4340
- client,
4341
- auth,
4342
- accountId: effectiveAccountId,
4343
- effectiveAccountId,
4344
- accountConfig,
4345
- logger,
4346
- logVerboseMessage,
4347
- getRuntimeConfig: () => core.config.current(),
4348
- replaceConfigFile: async (nextCfg) => {
4349
- await core.config.replaceConfigFile({
4350
- nextConfig: nextCfg,
4351
- afterWrite: { mode: "auto" }
4352
- });
4353
- },
4354
- loadWebMedia: async (url, maxBytes) => await core.media.loadWebMedia(url, maxBytes),
4355
- env: process.env,
4356
- abortSignal: opts.abortSignal
4357
- });
4358
- await Promise.race([waitUntilAbort(opts.abortSignal, async () => {
4359
- try {
4360
- logVerboseMessage("matrix: stopping client");
4361
- await cleanup();
4362
- } catch (err) {
4363
- logger.warn("matrix: failed during monitor shutdown cleanup", { error: String(err) });
4364
- }
4365
- }), syncLifecycle.waitForFatalStop()]);
4366
- } catch (err) {
4367
- if (opts.abortSignal?.aborted === true && isMatrixStartupAbortError(err)) {
4368
- await cleanup("stop");
4369
- return;
4370
- }
4371
- statusController.noteUnexpectedError(err);
4372
- await cleanup();
4373
- throw err;
4374
- }
4375
- }
4376
- //#endregion
4377
- export { monitorMatrixProvider };