@openclaw/mattermost 2026.2.21 → 2026.6.11

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 (787) hide show
  1. package/README.md +13 -0
  2. package/dist/accounts-DnAHfb5f.js +438 -0
  3. package/dist/api.js +2 -0
  4. package/dist/channel-plugin-api.js +31 -0
  5. package/dist/channel-plugin-runtime-MXClEU4F.js +1160 -0
  6. package/dist/channel-plugin-runtime.js +2 -0
  7. package/dist/channel.runtime-W-pjr9zL.js +2671 -0
  8. package/dist/doctor-contract-api.js +2 -0
  9. package/dist/doctor-contract-ttH0DCuq.js +7 -0
  10. package/dist/gateway-auth-api.js +2 -0
  11. package/dist/gateway-auth-bypass-BHgOAkk8.js +37 -0
  12. package/dist/index.js +31 -0
  13. package/dist/monitor-auth-BiDuyvOc.js +183 -0
  14. package/dist/policy-api.js +2 -0
  15. package/dist/runtime-CNB4YGqJ.js +8 -0
  16. package/dist/runtime-api.js +24 -0
  17. package/dist/secret-contract-Cx0LUNXy.js +44 -0
  18. package/dist/secret-contract-api.js +2 -0
  19. package/dist/setup-entry.js +15 -0
  20. package/dist/slash-route-api.js +2 -0
  21. package/dist/slash-state-I1qleAHM.js +2251 -0
  22. package/node_modules/ws/LICENSE +20 -0
  23. package/node_modules/ws/README.md +548 -0
  24. package/node_modules/ws/browser.js +8 -0
  25. package/node_modules/ws/index.js +22 -0
  26. package/node_modules/ws/lib/buffer-util.js +131 -0
  27. package/node_modules/ws/lib/constants.js +19 -0
  28. package/node_modules/ws/lib/event-target.js +292 -0
  29. package/node_modules/ws/lib/extension.js +203 -0
  30. package/node_modules/ws/lib/limiter.js +55 -0
  31. package/node_modules/ws/lib/permessage-deflate.js +528 -0
  32. package/node_modules/ws/lib/receiver.js +760 -0
  33. package/node_modules/ws/lib/sender.js +607 -0
  34. package/node_modules/ws/lib/stream.js +161 -0
  35. package/node_modules/ws/lib/subprotocol.js +62 -0
  36. package/node_modules/ws/lib/validation.js +152 -0
  37. package/node_modules/ws/lib/websocket-server.js +562 -0
  38. package/node_modules/ws/lib/websocket.js +1407 -0
  39. package/node_modules/ws/package.json +70 -0
  40. package/node_modules/ws/wrapper.mjs +21 -0
  41. package/node_modules/zod/LICENSE +21 -0
  42. package/node_modules/zod/README.md +191 -0
  43. package/node_modules/zod/index.cjs +33 -0
  44. package/node_modules/zod/index.d.cts +4 -0
  45. package/node_modules/zod/index.d.ts +4 -0
  46. package/node_modules/zod/index.js +4 -0
  47. package/node_modules/zod/locales/index.cjs +17 -0
  48. package/node_modules/zod/locales/index.d.cts +1 -0
  49. package/node_modules/zod/locales/index.d.ts +1 -0
  50. package/node_modules/zod/locales/index.js +1 -0
  51. package/node_modules/zod/locales/package.json +7 -0
  52. package/node_modules/zod/mini/index.cjs +32 -0
  53. package/node_modules/zod/mini/index.d.cts +3 -0
  54. package/node_modules/zod/mini/index.d.ts +3 -0
  55. package/node_modules/zod/mini/index.js +3 -0
  56. package/node_modules/zod/mini/package.json +7 -0
  57. package/node_modules/zod/package.json +135 -0
  58. package/node_modules/zod/src/index.ts +4 -0
  59. package/node_modules/zod/src/locales/index.ts +1 -0
  60. package/node_modules/zod/src/mini/index.ts +3 -0
  61. package/node_modules/zod/src/v3/ZodError.ts +330 -0
  62. package/node_modules/zod/src/v3/benchmarks/datetime.ts +58 -0
  63. package/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts +80 -0
  64. package/node_modules/zod/src/v3/benchmarks/index.ts +59 -0
  65. package/node_modules/zod/src/v3/benchmarks/ipv4.ts +57 -0
  66. package/node_modules/zod/src/v3/benchmarks/object.ts +69 -0
  67. package/node_modules/zod/src/v3/benchmarks/primitives.ts +162 -0
  68. package/node_modules/zod/src/v3/benchmarks/realworld.ts +63 -0
  69. package/node_modules/zod/src/v3/benchmarks/string.ts +55 -0
  70. package/node_modules/zod/src/v3/benchmarks/union.ts +80 -0
  71. package/node_modules/zod/src/v3/errors.ts +13 -0
  72. package/node_modules/zod/src/v3/external.ts +6 -0
  73. package/node_modules/zod/src/v3/helpers/enumUtil.ts +17 -0
  74. package/node_modules/zod/src/v3/helpers/errorUtil.ts +8 -0
  75. package/node_modules/zod/src/v3/helpers/parseUtil.ts +176 -0
  76. package/node_modules/zod/src/v3/helpers/partialUtil.ts +34 -0
  77. package/node_modules/zod/src/v3/helpers/typeAliases.ts +2 -0
  78. package/node_modules/zod/src/v3/helpers/util.ts +224 -0
  79. package/node_modules/zod/src/v3/index.ts +4 -0
  80. package/node_modules/zod/src/v3/locales/en.ts +124 -0
  81. package/node_modules/zod/src/v3/standard-schema.ts +113 -0
  82. package/node_modules/zod/src/v3/tests/Mocker.ts +54 -0
  83. package/node_modules/zod/src/v3/tests/all-errors.test.ts +157 -0
  84. package/node_modules/zod/src/v3/tests/anyunknown.test.ts +28 -0
  85. package/node_modules/zod/src/v3/tests/array.test.ts +71 -0
  86. package/node_modules/zod/src/v3/tests/async-parsing.test.ts +388 -0
  87. package/node_modules/zod/src/v3/tests/async-refinements.test.ts +46 -0
  88. package/node_modules/zod/src/v3/tests/base.test.ts +29 -0
  89. package/node_modules/zod/src/v3/tests/bigint.test.ts +55 -0
  90. package/node_modules/zod/src/v3/tests/branded.test.ts +53 -0
  91. package/node_modules/zod/src/v3/tests/catch.test.ts +220 -0
  92. package/node_modules/zod/src/v3/tests/coerce.test.ts +133 -0
  93. package/node_modules/zod/src/v3/tests/complex.test.ts +70 -0
  94. package/node_modules/zod/src/v3/tests/custom.test.ts +31 -0
  95. package/node_modules/zod/src/v3/tests/date.test.ts +32 -0
  96. package/node_modules/zod/src/v3/tests/deepmasking.test.ts +186 -0
  97. package/node_modules/zod/src/v3/tests/default.test.ts +112 -0
  98. package/node_modules/zod/src/v3/tests/description.test.ts +33 -0
  99. package/node_modules/zod/src/v3/tests/discriminated-unions.test.ts +315 -0
  100. package/node_modules/zod/src/v3/tests/enum.test.ts +80 -0
  101. package/node_modules/zod/src/v3/tests/error.test.ts +551 -0
  102. package/node_modules/zod/src/v3/tests/firstparty.test.ts +87 -0
  103. package/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts +21 -0
  104. package/node_modules/zod/src/v3/tests/function.test.ts +261 -0
  105. package/node_modules/zod/src/v3/tests/generics.test.ts +48 -0
  106. package/node_modules/zod/src/v3/tests/instanceof.test.ts +37 -0
  107. package/node_modules/zod/src/v3/tests/intersection.test.ts +110 -0
  108. package/node_modules/zod/src/v3/tests/language-server.source.ts +76 -0
  109. package/node_modules/zod/src/v3/tests/language-server.test.ts +207 -0
  110. package/node_modules/zod/src/v3/tests/literal.test.ts +36 -0
  111. package/node_modules/zod/src/v3/tests/map.test.ts +110 -0
  112. package/node_modules/zod/src/v3/tests/masking.test.ts +4 -0
  113. package/node_modules/zod/src/v3/tests/mocker.test.ts +19 -0
  114. package/node_modules/zod/src/v3/tests/nan.test.ts +24 -0
  115. package/node_modules/zod/src/v3/tests/nativeEnum.test.ts +87 -0
  116. package/node_modules/zod/src/v3/tests/nullable.test.ts +42 -0
  117. package/node_modules/zod/src/v3/tests/number.test.ts +176 -0
  118. package/node_modules/zod/src/v3/tests/object-augmentation.test.ts +29 -0
  119. package/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts +29 -0
  120. package/node_modules/zod/src/v3/tests/object.test.ts +434 -0
  121. package/node_modules/zod/src/v3/tests/optional.test.ts +42 -0
  122. package/node_modules/zod/src/v3/tests/parseUtil.test.ts +23 -0
  123. package/node_modules/zod/src/v3/tests/parser.test.ts +41 -0
  124. package/node_modules/zod/src/v3/tests/partials.test.ts +243 -0
  125. package/node_modules/zod/src/v3/tests/pickomit.test.ts +111 -0
  126. package/node_modules/zod/src/v3/tests/pipeline.test.ts +29 -0
  127. package/node_modules/zod/src/v3/tests/preprocess.test.ts +186 -0
  128. package/node_modules/zod/src/v3/tests/primitive.test.ts +440 -0
  129. package/node_modules/zod/src/v3/tests/promise.test.ts +90 -0
  130. package/node_modules/zod/src/v3/tests/readonly.test.ts +194 -0
  131. package/node_modules/zod/src/v3/tests/record.test.ts +171 -0
  132. package/node_modules/zod/src/v3/tests/recursive.test.ts +197 -0
  133. package/node_modules/zod/src/v3/tests/refine.test.ts +313 -0
  134. package/node_modules/zod/src/v3/tests/safeparse.test.ts +27 -0
  135. package/node_modules/zod/src/v3/tests/set.test.ts +142 -0
  136. package/node_modules/zod/src/v3/tests/standard-schema.test.ts +83 -0
  137. package/node_modules/zod/src/v3/tests/string.test.ts +916 -0
  138. package/node_modules/zod/src/v3/tests/transformer.test.ts +233 -0
  139. package/node_modules/zod/src/v3/tests/tuple.test.ts +90 -0
  140. package/node_modules/zod/src/v3/tests/unions.test.ts +57 -0
  141. package/node_modules/zod/src/v3/tests/validations.test.ts +133 -0
  142. package/node_modules/zod/src/v3/tests/void.test.ts +15 -0
  143. package/node_modules/zod/src/v3/types.ts +5138 -0
  144. package/node_modules/zod/src/v4/classic/checks.ts +32 -0
  145. package/node_modules/zod/src/v4/classic/coerce.ts +27 -0
  146. package/node_modules/zod/src/v4/classic/compat.ts +70 -0
  147. package/node_modules/zod/src/v4/classic/errors.ts +82 -0
  148. package/node_modules/zod/src/v4/classic/external.ts +52 -0
  149. package/node_modules/zod/src/v4/classic/from-json-schema.ts +659 -0
  150. package/node_modules/zod/src/v4/classic/index.ts +5 -0
  151. package/node_modules/zod/src/v4/classic/iso.ts +90 -0
  152. package/node_modules/zod/src/v4/classic/parse.ts +82 -0
  153. package/node_modules/zod/src/v4/classic/schemas.ts +2672 -0
  154. package/node_modules/zod/src/v4/classic/tests/anyunknown.test.ts +26 -0
  155. package/node_modules/zod/src/v4/classic/tests/apply.test.ts +59 -0
  156. package/node_modules/zod/src/v4/classic/tests/array.test.ts +264 -0
  157. package/node_modules/zod/src/v4/classic/tests/assignability.test.ts +216 -0
  158. package/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts +381 -0
  159. package/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts +68 -0
  160. package/node_modules/zod/src/v4/classic/tests/base.test.ts +7 -0
  161. package/node_modules/zod/src/v4/classic/tests/bigint.test.ts +54 -0
  162. package/node_modules/zod/src/v4/classic/tests/brand.test.ts +106 -0
  163. package/node_modules/zod/src/v4/classic/tests/catch.test.ts +326 -0
  164. package/node_modules/zod/src/v4/classic/tests/coalesce.test.ts +20 -0
  165. package/node_modules/zod/src/v4/classic/tests/codec-examples.test.ts +573 -0
  166. package/node_modules/zod/src/v4/classic/tests/codec.test.ts +703 -0
  167. package/node_modules/zod/src/v4/classic/tests/coerce.test.ts +160 -0
  168. package/node_modules/zod/src/v4/classic/tests/continuability.test.ts +374 -0
  169. package/node_modules/zod/src/v4/classic/tests/custom.test.ts +40 -0
  170. package/node_modules/zod/src/v4/classic/tests/date.test.ts +62 -0
  171. package/node_modules/zod/src/v4/classic/tests/datetime.test.ts +302 -0
  172. package/node_modules/zod/src/v4/classic/tests/default.test.ts +409 -0
  173. package/node_modules/zod/src/v4/classic/tests/describe-meta-checks.test.ts +27 -0
  174. package/node_modules/zod/src/v4/classic/tests/description.test.ts +32 -0
  175. package/node_modules/zod/src/v4/classic/tests/detached-methods.test.ts +197 -0
  176. package/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +694 -0
  177. package/node_modules/zod/src/v4/classic/tests/enum.test.ts +285 -0
  178. package/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +807 -0
  179. package/node_modules/zod/src/v4/classic/tests/error.test.ts +711 -0
  180. package/node_modules/zod/src/v4/classic/tests/file.test.ts +96 -0
  181. package/node_modules/zod/src/v4/classic/tests/firstparty.test.ts +179 -0
  182. package/node_modules/zod/src/v4/classic/tests/fix-json-issue.test.ts +26 -0
  183. package/node_modules/zod/src/v4/classic/tests/from-json-schema.test.ts +895 -0
  184. package/node_modules/zod/src/v4/classic/tests/function.test.ts +360 -0
  185. package/node_modules/zod/src/v4/classic/tests/generics.test.ts +72 -0
  186. package/node_modules/zod/src/v4/classic/tests/global-config.test.ts +39 -0
  187. package/node_modules/zod/src/v4/classic/tests/hash.test.ts +68 -0
  188. package/node_modules/zod/src/v4/classic/tests/index.test.ts +939 -0
  189. package/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +60 -0
  190. package/node_modules/zod/src/v4/classic/tests/intersection.test.ts +198 -0
  191. package/node_modules/zod/src/v4/classic/tests/jitless-allows-eval.test.ts +46 -0
  192. package/node_modules/zod/src/v4/classic/tests/json.test.ts +109 -0
  193. package/node_modules/zod/src/v4/classic/tests/lazy.test.ts +227 -0
  194. package/node_modules/zod/src/v4/classic/tests/literal.test.ts +117 -0
  195. package/node_modules/zod/src/v4/classic/tests/locales_ka.test.ts +29 -0
  196. package/node_modules/zod/src/v4/classic/tests/locales_ro.test.ts +24 -0
  197. package/node_modules/zod/src/v4/classic/tests/map.test.ts +330 -0
  198. package/node_modules/zod/src/v4/classic/tests/nan.test.ts +21 -0
  199. package/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts +168 -0
  200. package/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts +101 -0
  201. package/node_modules/zod/src/v4/classic/tests/nullable.test.ts +22 -0
  202. package/node_modules/zod/src/v4/classic/tests/number.test.ts +325 -0
  203. package/node_modules/zod/src/v4/classic/tests/object.test.ts +717 -0
  204. package/node_modules/zod/src/v4/classic/tests/optional.test.ts +333 -0
  205. package/node_modules/zod/src/v4/classic/tests/partial.test.ts +450 -0
  206. package/node_modules/zod/src/v4/classic/tests/pickomit.test.ts +211 -0
  207. package/node_modules/zod/src/v4/classic/tests/pipe.test.ts +101 -0
  208. package/node_modules/zod/src/v4/classic/tests/prefault.test.ts +74 -0
  209. package/node_modules/zod/src/v4/classic/tests/preprocess-types.test.ts +26 -0
  210. package/node_modules/zod/src/v4/classic/tests/preprocess.test.ts +351 -0
  211. package/node_modules/zod/src/v4/classic/tests/primitive.test.ts +175 -0
  212. package/node_modules/zod/src/v4/classic/tests/promise.test.ts +81 -0
  213. package/node_modules/zod/src/v4/classic/tests/prototypes.test.ts +23 -0
  214. package/node_modules/zod/src/v4/classic/tests/readonly.test.ts +252 -0
  215. package/node_modules/zod/src/v4/classic/tests/record.test.ts +717 -0
  216. package/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +631 -0
  217. package/node_modules/zod/src/v4/classic/tests/refine.test.ts +633 -0
  218. package/node_modules/zod/src/v4/classic/tests/registries.test.ts +243 -0
  219. package/node_modules/zod/src/v4/classic/tests/set.test.ts +181 -0
  220. package/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts +134 -0
  221. package/node_modules/zod/src/v4/classic/tests/string-formats.test.ts +125 -0
  222. package/node_modules/zod/src/v4/classic/tests/string.test.ts +1224 -0
  223. package/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +106 -0
  224. package/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +771 -0
  225. package/node_modules/zod/src/v4/classic/tests/to-json-schema-methods.test.ts +438 -0
  226. package/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +3125 -0
  227. package/node_modules/zod/src/v4/classic/tests/transform.test.ts +378 -0
  228. package/node_modules/zod/src/v4/classic/tests/tuple.test.ts +496 -0
  229. package/node_modules/zod/src/v4/classic/tests/union.test.ts +273 -0
  230. package/node_modules/zod/src/v4/classic/tests/url.test.ts +13 -0
  231. package/node_modules/zod/src/v4/classic/tests/validations.test.ts +283 -0
  232. package/node_modules/zod/src/v4/classic/tests/void.test.ts +12 -0
  233. package/node_modules/zod/src/v4/core/api.ts +1823 -0
  234. package/node_modules/zod/src/v4/core/checks.ts +1293 -0
  235. package/node_modules/zod/src/v4/core/config.ts +15 -0
  236. package/node_modules/zod/src/v4/core/core.ts +153 -0
  237. package/node_modules/zod/src/v4/core/doc.ts +44 -0
  238. package/node_modules/zod/src/v4/core/errors.ts +455 -0
  239. package/node_modules/zod/src/v4/core/index.ts +16 -0
  240. package/node_modules/zod/src/v4/core/json-schema-generator.ts +126 -0
  241. package/node_modules/zod/src/v4/core/json-schema-processors.ts +666 -0
  242. package/node_modules/zod/src/v4/core/json-schema.ts +147 -0
  243. package/node_modules/zod/src/v4/core/parse.ts +195 -0
  244. package/node_modules/zod/src/v4/core/regexes.ts +190 -0
  245. package/node_modules/zod/src/v4/core/registries.ts +105 -0
  246. package/node_modules/zod/src/v4/core/schemas.ts +4730 -0
  247. package/node_modules/zod/src/v4/core/standard-schema.ts +159 -0
  248. package/node_modules/zod/src/v4/core/tests/extend.test.ts +59 -0
  249. package/node_modules/zod/src/v4/core/tests/index.test.ts +46 -0
  250. package/node_modules/zod/src/v4/core/tests/locales/be.test.ts +124 -0
  251. package/node_modules/zod/src/v4/core/tests/locales/el.test.ts +215 -0
  252. package/node_modules/zod/src/v4/core/tests/locales/en.test.ts +22 -0
  253. package/node_modules/zod/src/v4/core/tests/locales/es.test.ts +181 -0
  254. package/node_modules/zod/src/v4/core/tests/locales/fr.test.ts +72 -0
  255. package/node_modules/zod/src/v4/core/tests/locales/he.test.ts +379 -0
  256. package/node_modules/zod/src/v4/core/tests/locales/hr.test.ts +163 -0
  257. package/node_modules/zod/src/v4/core/tests/locales/nl.test.ts +46 -0
  258. package/node_modules/zod/src/v4/core/tests/locales/ru.test.ts +128 -0
  259. package/node_modules/zod/src/v4/core/tests/locales/tr.test.ts +69 -0
  260. package/node_modules/zod/src/v4/core/tests/locales/uz.test.ts +105 -0
  261. package/node_modules/zod/src/v4/core/tests/record-constructor.test.ts +125 -0
  262. package/node_modules/zod/src/v4/core/tests/recursive-tuples.test.ts +45 -0
  263. package/node_modules/zod/src/v4/core/to-json-schema.ts +622 -0
  264. package/node_modules/zod/src/v4/core/util.ts +983 -0
  265. package/node_modules/zod/src/v4/core/versions.ts +5 -0
  266. package/node_modules/zod/src/v4/core/zsf.ts +323 -0
  267. package/node_modules/zod/src/v4/index.ts +4 -0
  268. package/node_modules/zod/src/v4/locales/ar.ts +115 -0
  269. package/node_modules/zod/src/v4/locales/az.ts +111 -0
  270. package/node_modules/zod/src/v4/locales/be.ts +176 -0
  271. package/node_modules/zod/src/v4/locales/bg.ts +128 -0
  272. package/node_modules/zod/src/v4/locales/ca.ts +116 -0
  273. package/node_modules/zod/src/v4/locales/cs.ts +118 -0
  274. package/node_modules/zod/src/v4/locales/da.ts +123 -0
  275. package/node_modules/zod/src/v4/locales/de.ts +116 -0
  276. package/node_modules/zod/src/v4/locales/el.ts +121 -0
  277. package/node_modules/zod/src/v4/locales/en.ts +123 -0
  278. package/node_modules/zod/src/v4/locales/eo.ts +118 -0
  279. package/node_modules/zod/src/v4/locales/es.ts +141 -0
  280. package/node_modules/zod/src/v4/locales/fa.ts +126 -0
  281. package/node_modules/zod/src/v4/locales/fi.ts +121 -0
  282. package/node_modules/zod/src/v4/locales/fr-CA.ts +116 -0
  283. package/node_modules/zod/src/v4/locales/fr.ts +132 -0
  284. package/node_modules/zod/src/v4/locales/he.ts +246 -0
  285. package/node_modules/zod/src/v4/locales/hr.ts +131 -0
  286. package/node_modules/zod/src/v4/locales/hu.ts +117 -0
  287. package/node_modules/zod/src/v4/locales/hy.ts +164 -0
  288. package/node_modules/zod/src/v4/locales/id.ts +115 -0
  289. package/node_modules/zod/src/v4/locales/index.ts +52 -0
  290. package/node_modules/zod/src/v4/locales/is.ts +119 -0
  291. package/node_modules/zod/src/v4/locales/it.ts +116 -0
  292. package/node_modules/zod/src/v4/locales/ja.ts +114 -0
  293. package/node_modules/zod/src/v4/locales/ka.ts +123 -0
  294. package/node_modules/zod/src/v4/locales/kh.ts +7 -0
  295. package/node_modules/zod/src/v4/locales/km.ts +119 -0
  296. package/node_modules/zod/src/v4/locales/ko.ts +121 -0
  297. package/node_modules/zod/src/v4/locales/lt.ts +239 -0
  298. package/node_modules/zod/src/v4/locales/mk.ts +118 -0
  299. package/node_modules/zod/src/v4/locales/ms.ts +115 -0
  300. package/node_modules/zod/src/v4/locales/nl.ts +121 -0
  301. package/node_modules/zod/src/v4/locales/no.ts +116 -0
  302. package/node_modules/zod/src/v4/locales/ota.ts +117 -0
  303. package/node_modules/zod/src/v4/locales/pl.ts +118 -0
  304. package/node_modules/zod/src/v4/locales/ps.ts +126 -0
  305. package/node_modules/zod/src/v4/locales/pt.ts +116 -0
  306. package/node_modules/zod/src/v4/locales/ro.ts +129 -0
  307. package/node_modules/zod/src/v4/locales/ru.ts +176 -0
  308. package/node_modules/zod/src/v4/locales/sl.ts +118 -0
  309. package/node_modules/zod/src/v4/locales/sv.ts +119 -0
  310. package/node_modules/zod/src/v4/locales/ta.ts +118 -0
  311. package/node_modules/zod/src/v4/locales/th.ts +119 -0
  312. package/node_modules/zod/src/v4/locales/tr.ts +111 -0
  313. package/node_modules/zod/src/v4/locales/ua.ts +7 -0
  314. package/node_modules/zod/src/v4/locales/uk.ts +117 -0
  315. package/node_modules/zod/src/v4/locales/ur.ts +119 -0
  316. package/node_modules/zod/src/v4/locales/uz.ts +117 -0
  317. package/node_modules/zod/src/v4/locales/vi.ts +117 -0
  318. package/node_modules/zod/src/v4/locales/yo.ts +124 -0
  319. package/node_modules/zod/src/v4/locales/zh-CN.ts +116 -0
  320. package/node_modules/zod/src/v4/locales/zh-TW.ts +115 -0
  321. package/node_modules/zod/src/v4/mini/checks.ts +32 -0
  322. package/node_modules/zod/src/v4/mini/coerce.ts +27 -0
  323. package/node_modules/zod/src/v4/mini/external.ts +41 -0
  324. package/node_modules/zod/src/v4/mini/index.ts +3 -0
  325. package/node_modules/zod/src/v4/mini/iso.ts +66 -0
  326. package/node_modules/zod/src/v4/mini/parse.ts +14 -0
  327. package/node_modules/zod/src/v4/mini/schemas.ts +1947 -0
  328. package/node_modules/zod/src/v4/mini/tests/apply.test.ts +24 -0
  329. package/node_modules/zod/src/v4/mini/tests/assignability.test.ts +129 -0
  330. package/node_modules/zod/src/v4/mini/tests/brand.test.ts +94 -0
  331. package/node_modules/zod/src/v4/mini/tests/checks.test.ts +144 -0
  332. package/node_modules/zod/src/v4/mini/tests/codec.test.ts +548 -0
  333. package/node_modules/zod/src/v4/mini/tests/computed.test.ts +36 -0
  334. package/node_modules/zod/src/v4/mini/tests/error.test.ts +22 -0
  335. package/node_modules/zod/src/v4/mini/tests/functions.test.ts +5 -0
  336. package/node_modules/zod/src/v4/mini/tests/index.test.ts +993 -0
  337. package/node_modules/zod/src/v4/mini/tests/number.test.ts +95 -0
  338. package/node_modules/zod/src/v4/mini/tests/object.test.ts +227 -0
  339. package/node_modules/zod/src/v4/mini/tests/prototypes.test.ts +43 -0
  340. package/node_modules/zod/src/v4/mini/tests/recursive-types.test.ts +325 -0
  341. package/node_modules/zod/src/v4/mini/tests/standard-schema.test.ts +50 -0
  342. package/node_modules/zod/src/v4/mini/tests/string.test.ts +352 -0
  343. package/node_modules/zod/src/v4-mini/index.ts +3 -0
  344. package/node_modules/zod/v3/ZodError.cjs +138 -0
  345. package/node_modules/zod/v3/ZodError.d.cts +164 -0
  346. package/node_modules/zod/v3/ZodError.d.ts +164 -0
  347. package/node_modules/zod/v3/ZodError.js +133 -0
  348. package/node_modules/zod/v3/errors.cjs +17 -0
  349. package/node_modules/zod/v3/errors.d.cts +5 -0
  350. package/node_modules/zod/v3/errors.d.ts +5 -0
  351. package/node_modules/zod/v3/errors.js +9 -0
  352. package/node_modules/zod/v3/external.cjs +22 -0
  353. package/node_modules/zod/v3/external.d.cts +6 -0
  354. package/node_modules/zod/v3/external.d.ts +6 -0
  355. package/node_modules/zod/v3/external.js +6 -0
  356. package/node_modules/zod/v3/helpers/enumUtil.cjs +2 -0
  357. package/node_modules/zod/v3/helpers/enumUtil.d.cts +8 -0
  358. package/node_modules/zod/v3/helpers/enumUtil.d.ts +8 -0
  359. package/node_modules/zod/v3/helpers/enumUtil.js +1 -0
  360. package/node_modules/zod/v3/helpers/errorUtil.cjs +9 -0
  361. package/node_modules/zod/v3/helpers/errorUtil.d.cts +9 -0
  362. package/node_modules/zod/v3/helpers/errorUtil.d.ts +9 -0
  363. package/node_modules/zod/v3/helpers/errorUtil.js +6 -0
  364. package/node_modules/zod/v3/helpers/parseUtil.cjs +124 -0
  365. package/node_modules/zod/v3/helpers/parseUtil.d.cts +78 -0
  366. package/node_modules/zod/v3/helpers/parseUtil.d.ts +78 -0
  367. package/node_modules/zod/v3/helpers/parseUtil.js +109 -0
  368. package/node_modules/zod/v3/helpers/partialUtil.cjs +2 -0
  369. package/node_modules/zod/v3/helpers/partialUtil.d.cts +8 -0
  370. package/node_modules/zod/v3/helpers/partialUtil.d.ts +8 -0
  371. package/node_modules/zod/v3/helpers/partialUtil.js +1 -0
  372. package/node_modules/zod/v3/helpers/typeAliases.cjs +2 -0
  373. package/node_modules/zod/v3/helpers/typeAliases.d.cts +2 -0
  374. package/node_modules/zod/v3/helpers/typeAliases.d.ts +2 -0
  375. package/node_modules/zod/v3/helpers/typeAliases.js +1 -0
  376. package/node_modules/zod/v3/helpers/util.cjs +137 -0
  377. package/node_modules/zod/v3/helpers/util.d.cts +85 -0
  378. package/node_modules/zod/v3/helpers/util.d.ts +85 -0
  379. package/node_modules/zod/v3/helpers/util.js +133 -0
  380. package/node_modules/zod/v3/index.cjs +33 -0
  381. package/node_modules/zod/v3/index.d.cts +4 -0
  382. package/node_modules/zod/v3/index.d.ts +4 -0
  383. package/node_modules/zod/v3/index.js +4 -0
  384. package/node_modules/zod/v3/locales/en.cjs +112 -0
  385. package/node_modules/zod/v3/locales/en.d.cts +3 -0
  386. package/node_modules/zod/v3/locales/en.d.ts +3 -0
  387. package/node_modules/zod/v3/locales/en.js +109 -0
  388. package/node_modules/zod/v3/package.json +7 -0
  389. package/node_modules/zod/v3/standard-schema.cjs +2 -0
  390. package/node_modules/zod/v3/standard-schema.d.cts +102 -0
  391. package/node_modules/zod/v3/standard-schema.d.ts +102 -0
  392. package/node_modules/zod/v3/standard-schema.js +1 -0
  393. package/node_modules/zod/v3/types.cjs +3777 -0
  394. package/node_modules/zod/v3/types.d.cts +1034 -0
  395. package/node_modules/zod/v3/types.d.ts +1034 -0
  396. package/node_modules/zod/v3/types.js +3695 -0
  397. package/node_modules/zod/v4/classic/checks.cjs +33 -0
  398. package/node_modules/zod/v4/classic/checks.d.cts +1 -0
  399. package/node_modules/zod/v4/classic/checks.d.ts +1 -0
  400. package/node_modules/zod/v4/classic/checks.js +1 -0
  401. package/node_modules/zod/v4/classic/coerce.cjs +47 -0
  402. package/node_modules/zod/v4/classic/coerce.d.cts +17 -0
  403. package/node_modules/zod/v4/classic/coerce.d.ts +17 -0
  404. package/node_modules/zod/v4/classic/coerce.js +17 -0
  405. package/node_modules/zod/v4/classic/compat.cjs +61 -0
  406. package/node_modules/zod/v4/classic/compat.d.cts +50 -0
  407. package/node_modules/zod/v4/classic/compat.d.ts +50 -0
  408. package/node_modules/zod/v4/classic/compat.js +31 -0
  409. package/node_modules/zod/v4/classic/errors.cjs +74 -0
  410. package/node_modules/zod/v4/classic/errors.d.cts +30 -0
  411. package/node_modules/zod/v4/classic/errors.d.ts +30 -0
  412. package/node_modules/zod/v4/classic/errors.js +48 -0
  413. package/node_modules/zod/v4/classic/external.cjs +73 -0
  414. package/node_modules/zod/v4/classic/external.d.cts +16 -0
  415. package/node_modules/zod/v4/classic/external.d.ts +16 -0
  416. package/node_modules/zod/v4/classic/external.js +20 -0
  417. package/node_modules/zod/v4/classic/from-json-schema.cjs +625 -0
  418. package/node_modules/zod/v4/classic/from-json-schema.d.cts +12 -0
  419. package/node_modules/zod/v4/classic/from-json-schema.d.ts +12 -0
  420. package/node_modules/zod/v4/classic/from-json-schema.js +599 -0
  421. package/node_modules/zod/v4/classic/index.cjs +33 -0
  422. package/node_modules/zod/v4/classic/index.d.cts +4 -0
  423. package/node_modules/zod/v4/classic/index.d.ts +4 -0
  424. package/node_modules/zod/v4/classic/index.js +4 -0
  425. package/node_modules/zod/v4/classic/iso.cjs +60 -0
  426. package/node_modules/zod/v4/classic/iso.d.cts +22 -0
  427. package/node_modules/zod/v4/classic/iso.d.ts +22 -0
  428. package/node_modules/zod/v4/classic/iso.js +30 -0
  429. package/node_modules/zod/v4/classic/package.json +7 -0
  430. package/node_modules/zod/v4/classic/parse.cjs +41 -0
  431. package/node_modules/zod/v4/classic/parse.d.cts +31 -0
  432. package/node_modules/zod/v4/classic/parse.d.ts +31 -0
  433. package/node_modules/zod/v4/classic/parse.js +15 -0
  434. package/node_modules/zod/v4/classic/schemas.cjs +1511 -0
  435. package/node_modules/zod/v4/classic/schemas.d.cts +767 -0
  436. package/node_modules/zod/v4/classic/schemas.d.ts +767 -0
  437. package/node_modules/zod/v4/classic/schemas.js +1395 -0
  438. package/node_modules/zod/v4/core/api.cjs +1227 -0
  439. package/node_modules/zod/v4/core/api.d.cts +325 -0
  440. package/node_modules/zod/v4/core/api.d.ts +325 -0
  441. package/node_modules/zod/v4/core/api.js +1087 -0
  442. package/node_modules/zod/v4/core/checks.cjs +601 -0
  443. package/node_modules/zod/v4/core/checks.d.cts +278 -0
  444. package/node_modules/zod/v4/core/checks.d.ts +278 -0
  445. package/node_modules/zod/v4/core/checks.js +575 -0
  446. package/node_modules/zod/v4/core/core.cjs +85 -0
  447. package/node_modules/zod/v4/core/core.d.cts +70 -0
  448. package/node_modules/zod/v4/core/core.d.ts +70 -0
  449. package/node_modules/zod/v4/core/core.js +78 -0
  450. package/node_modules/zod/v4/core/doc.cjs +39 -0
  451. package/node_modules/zod/v4/core/doc.d.cts +14 -0
  452. package/node_modules/zod/v4/core/doc.d.ts +14 -0
  453. package/node_modules/zod/v4/core/doc.js +35 -0
  454. package/node_modules/zod/v4/core/errors.cjs +216 -0
  455. package/node_modules/zod/v4/core/errors.d.cts +221 -0
  456. package/node_modules/zod/v4/core/errors.d.ts +221 -0
  457. package/node_modules/zod/v4/core/errors.js +185 -0
  458. package/node_modules/zod/v4/core/index.cjs +47 -0
  459. package/node_modules/zod/v4/core/index.d.cts +16 -0
  460. package/node_modules/zod/v4/core/index.d.ts +16 -0
  461. package/node_modules/zod/v4/core/index.js +16 -0
  462. package/node_modules/zod/v4/core/json-schema-generator.cjs +99 -0
  463. package/node_modules/zod/v4/core/json-schema-generator.d.cts +65 -0
  464. package/node_modules/zod/v4/core/json-schema-generator.d.ts +65 -0
  465. package/node_modules/zod/v4/core/json-schema-generator.js +95 -0
  466. package/node_modules/zod/v4/core/json-schema-processors.cjs +644 -0
  467. package/node_modules/zod/v4/core/json-schema-processors.d.cts +49 -0
  468. package/node_modules/zod/v4/core/json-schema-processors.d.ts +49 -0
  469. package/node_modules/zod/v4/core/json-schema-processors.js +601 -0
  470. package/node_modules/zod/v4/core/json-schema.cjs +2 -0
  471. package/node_modules/zod/v4/core/json-schema.d.cts +88 -0
  472. package/node_modules/zod/v4/core/json-schema.d.ts +88 -0
  473. package/node_modules/zod/v4/core/json-schema.js +1 -0
  474. package/node_modules/zod/v4/core/package.json +7 -0
  475. package/node_modules/zod/v4/core/parse.cjs +131 -0
  476. package/node_modules/zod/v4/core/parse.d.cts +49 -0
  477. package/node_modules/zod/v4/core/parse.d.ts +49 -0
  478. package/node_modules/zod/v4/core/parse.js +93 -0
  479. package/node_modules/zod/v4/core/regexes.cjs +172 -0
  480. package/node_modules/zod/v4/core/regexes.d.cts +85 -0
  481. package/node_modules/zod/v4/core/regexes.d.ts +85 -0
  482. package/node_modules/zod/v4/core/regexes.js +139 -0
  483. package/node_modules/zod/v4/core/registries.cjs +56 -0
  484. package/node_modules/zod/v4/core/registries.d.cts +35 -0
  485. package/node_modules/zod/v4/core/registries.d.ts +35 -0
  486. package/node_modules/zod/v4/core/registries.js +51 -0
  487. package/node_modules/zod/v4/core/schemas.cjs +2270 -0
  488. package/node_modules/zod/v4/core/schemas.d.cts +1184 -0
  489. package/node_modules/zod/v4/core/schemas.d.ts +1184 -0
  490. package/node_modules/zod/v4/core/schemas.js +2239 -0
  491. package/node_modules/zod/v4/core/standard-schema.cjs +2 -0
  492. package/node_modules/zod/v4/core/standard-schema.d.cts +126 -0
  493. package/node_modules/zod/v4/core/standard-schema.d.ts +126 -0
  494. package/node_modules/zod/v4/core/standard-schema.js +1 -0
  495. package/node_modules/zod/v4/core/to-json-schema.cjs +457 -0
  496. package/node_modules/zod/v4/core/to-json-schema.d.cts +114 -0
  497. package/node_modules/zod/v4/core/to-json-schema.d.ts +114 -0
  498. package/node_modules/zod/v4/core/to-json-schema.js +448 -0
  499. package/node_modules/zod/v4/core/util.cjs +734 -0
  500. package/node_modules/zod/v4/core/util.d.cts +200 -0
  501. package/node_modules/zod/v4/core/util.d.ts +200 -0
  502. package/node_modules/zod/v4/core/util.js +674 -0
  503. package/node_modules/zod/v4/core/versions.cjs +8 -0
  504. package/node_modules/zod/v4/core/versions.d.cts +5 -0
  505. package/node_modules/zod/v4/core/versions.d.ts +5 -0
  506. package/node_modules/zod/v4/core/versions.js +5 -0
  507. package/node_modules/zod/v4/index.cjs +22 -0
  508. package/node_modules/zod/v4/index.d.cts +3 -0
  509. package/node_modules/zod/v4/index.d.ts +3 -0
  510. package/node_modules/zod/v4/index.js +3 -0
  511. package/node_modules/zod/v4/locales/ar.cjs +133 -0
  512. package/node_modules/zod/v4/locales/ar.d.cts +5 -0
  513. package/node_modules/zod/v4/locales/ar.d.ts +4 -0
  514. package/node_modules/zod/v4/locales/ar.js +106 -0
  515. package/node_modules/zod/v4/locales/az.cjs +132 -0
  516. package/node_modules/zod/v4/locales/az.d.cts +5 -0
  517. package/node_modules/zod/v4/locales/az.d.ts +4 -0
  518. package/node_modules/zod/v4/locales/az.js +105 -0
  519. package/node_modules/zod/v4/locales/be.cjs +183 -0
  520. package/node_modules/zod/v4/locales/be.d.cts +5 -0
  521. package/node_modules/zod/v4/locales/be.d.ts +4 -0
  522. package/node_modules/zod/v4/locales/be.js +156 -0
  523. package/node_modules/zod/v4/locales/bg.cjs +147 -0
  524. package/node_modules/zod/v4/locales/bg.d.cts +5 -0
  525. package/node_modules/zod/v4/locales/bg.d.ts +4 -0
  526. package/node_modules/zod/v4/locales/bg.js +120 -0
  527. package/node_modules/zod/v4/locales/ca.cjs +134 -0
  528. package/node_modules/zod/v4/locales/ca.d.cts +5 -0
  529. package/node_modules/zod/v4/locales/ca.d.ts +4 -0
  530. package/node_modules/zod/v4/locales/ca.js +107 -0
  531. package/node_modules/zod/v4/locales/cs.cjs +138 -0
  532. package/node_modules/zod/v4/locales/cs.d.cts +5 -0
  533. package/node_modules/zod/v4/locales/cs.d.ts +4 -0
  534. package/node_modules/zod/v4/locales/cs.js +111 -0
  535. package/node_modules/zod/v4/locales/da.cjs +142 -0
  536. package/node_modules/zod/v4/locales/da.d.cts +5 -0
  537. package/node_modules/zod/v4/locales/da.d.ts +4 -0
  538. package/node_modules/zod/v4/locales/da.js +115 -0
  539. package/node_modules/zod/v4/locales/de.cjs +135 -0
  540. package/node_modules/zod/v4/locales/de.d.cts +5 -0
  541. package/node_modules/zod/v4/locales/de.d.ts +4 -0
  542. package/node_modules/zod/v4/locales/de.js +108 -0
  543. package/node_modules/zod/v4/locales/el.cjs +136 -0
  544. package/node_modules/zod/v4/locales/el.d.cts +5 -0
  545. package/node_modules/zod/v4/locales/el.d.ts +4 -0
  546. package/node_modules/zod/v4/locales/el.js +109 -0
  547. package/node_modules/zod/v4/locales/en.cjs +140 -0
  548. package/node_modules/zod/v4/locales/en.d.cts +5 -0
  549. package/node_modules/zod/v4/locales/en.d.ts +4 -0
  550. package/node_modules/zod/v4/locales/en.js +113 -0
  551. package/node_modules/zod/v4/locales/eo.cjs +136 -0
  552. package/node_modules/zod/v4/locales/eo.d.cts +5 -0
  553. package/node_modules/zod/v4/locales/eo.d.ts +4 -0
  554. package/node_modules/zod/v4/locales/eo.js +109 -0
  555. package/node_modules/zod/v4/locales/es.cjs +159 -0
  556. package/node_modules/zod/v4/locales/es.d.cts +5 -0
  557. package/node_modules/zod/v4/locales/es.d.ts +4 -0
  558. package/node_modules/zod/v4/locales/es.js +132 -0
  559. package/node_modules/zod/v4/locales/fa.cjs +141 -0
  560. package/node_modules/zod/v4/locales/fa.d.cts +5 -0
  561. package/node_modules/zod/v4/locales/fa.d.ts +4 -0
  562. package/node_modules/zod/v4/locales/fa.js +114 -0
  563. package/node_modules/zod/v4/locales/fi.cjs +139 -0
  564. package/node_modules/zod/v4/locales/fi.d.cts +5 -0
  565. package/node_modules/zod/v4/locales/fi.d.ts +4 -0
  566. package/node_modules/zod/v4/locales/fi.js +112 -0
  567. package/node_modules/zod/v4/locales/fr-CA.cjs +134 -0
  568. package/node_modules/zod/v4/locales/fr-CA.d.cts +5 -0
  569. package/node_modules/zod/v4/locales/fr-CA.d.ts +4 -0
  570. package/node_modules/zod/v4/locales/fr-CA.js +107 -0
  571. package/node_modules/zod/v4/locales/fr.cjs +152 -0
  572. package/node_modules/zod/v4/locales/fr.d.cts +5 -0
  573. package/node_modules/zod/v4/locales/fr.d.ts +4 -0
  574. package/node_modules/zod/v4/locales/fr.js +125 -0
  575. package/node_modules/zod/v4/locales/he.cjs +241 -0
  576. package/node_modules/zod/v4/locales/he.d.cts +5 -0
  577. package/node_modules/zod/v4/locales/he.d.ts +4 -0
  578. package/node_modules/zod/v4/locales/he.js +214 -0
  579. package/node_modules/zod/v4/locales/hr.cjs +149 -0
  580. package/node_modules/zod/v4/locales/hr.d.cts +5 -0
  581. package/node_modules/zod/v4/locales/hr.d.ts +4 -0
  582. package/node_modules/zod/v4/locales/hr.js +122 -0
  583. package/node_modules/zod/v4/locales/hu.cjs +135 -0
  584. package/node_modules/zod/v4/locales/hu.d.cts +5 -0
  585. package/node_modules/zod/v4/locales/hu.d.ts +4 -0
  586. package/node_modules/zod/v4/locales/hu.js +108 -0
  587. package/node_modules/zod/v4/locales/hy.cjs +174 -0
  588. package/node_modules/zod/v4/locales/hy.d.cts +5 -0
  589. package/node_modules/zod/v4/locales/hy.d.ts +4 -0
  590. package/node_modules/zod/v4/locales/hy.js +147 -0
  591. package/node_modules/zod/v4/locales/id.cjs +133 -0
  592. package/node_modules/zod/v4/locales/id.d.cts +5 -0
  593. package/node_modules/zod/v4/locales/id.d.ts +4 -0
  594. package/node_modules/zod/v4/locales/id.js +106 -0
  595. package/node_modules/zod/v4/locales/index.cjs +111 -0
  596. package/node_modules/zod/v4/locales/index.d.cts +52 -0
  597. package/node_modules/zod/v4/locales/index.d.ts +52 -0
  598. package/node_modules/zod/v4/locales/index.js +52 -0
  599. package/node_modules/zod/v4/locales/is.cjs +136 -0
  600. package/node_modules/zod/v4/locales/is.d.cts +5 -0
  601. package/node_modules/zod/v4/locales/is.d.ts +4 -0
  602. package/node_modules/zod/v4/locales/is.js +109 -0
  603. package/node_modules/zod/v4/locales/it.cjs +135 -0
  604. package/node_modules/zod/v4/locales/it.d.cts +5 -0
  605. package/node_modules/zod/v4/locales/it.d.ts +4 -0
  606. package/node_modules/zod/v4/locales/it.js +108 -0
  607. package/node_modules/zod/v4/locales/ja.cjs +134 -0
  608. package/node_modules/zod/v4/locales/ja.d.cts +5 -0
  609. package/node_modules/zod/v4/locales/ja.d.ts +4 -0
  610. package/node_modules/zod/v4/locales/ja.js +107 -0
  611. package/node_modules/zod/v4/locales/ka.cjs +139 -0
  612. package/node_modules/zod/v4/locales/ka.d.cts +5 -0
  613. package/node_modules/zod/v4/locales/ka.d.ts +4 -0
  614. package/node_modules/zod/v4/locales/ka.js +112 -0
  615. package/node_modules/zod/v4/locales/kh.cjs +12 -0
  616. package/node_modules/zod/v4/locales/kh.d.cts +5 -0
  617. package/node_modules/zod/v4/locales/kh.d.ts +5 -0
  618. package/node_modules/zod/v4/locales/kh.js +5 -0
  619. package/node_modules/zod/v4/locales/km.cjs +137 -0
  620. package/node_modules/zod/v4/locales/km.d.cts +5 -0
  621. package/node_modules/zod/v4/locales/km.d.ts +4 -0
  622. package/node_modules/zod/v4/locales/km.js +110 -0
  623. package/node_modules/zod/v4/locales/ko.cjs +138 -0
  624. package/node_modules/zod/v4/locales/ko.d.cts +5 -0
  625. package/node_modules/zod/v4/locales/ko.d.ts +4 -0
  626. package/node_modules/zod/v4/locales/ko.js +111 -0
  627. package/node_modules/zod/v4/locales/lt.cjs +230 -0
  628. package/node_modules/zod/v4/locales/lt.d.cts +5 -0
  629. package/node_modules/zod/v4/locales/lt.d.ts +4 -0
  630. package/node_modules/zod/v4/locales/lt.js +203 -0
  631. package/node_modules/zod/v4/locales/mk.cjs +136 -0
  632. package/node_modules/zod/v4/locales/mk.d.cts +5 -0
  633. package/node_modules/zod/v4/locales/mk.d.ts +4 -0
  634. package/node_modules/zod/v4/locales/mk.js +109 -0
  635. package/node_modules/zod/v4/locales/ms.cjs +134 -0
  636. package/node_modules/zod/v4/locales/ms.d.cts +5 -0
  637. package/node_modules/zod/v4/locales/ms.d.ts +4 -0
  638. package/node_modules/zod/v4/locales/ms.js +107 -0
  639. package/node_modules/zod/v4/locales/nl.cjs +137 -0
  640. package/node_modules/zod/v4/locales/nl.d.cts +5 -0
  641. package/node_modules/zod/v4/locales/nl.d.ts +4 -0
  642. package/node_modules/zod/v4/locales/nl.js +110 -0
  643. package/node_modules/zod/v4/locales/no.cjs +135 -0
  644. package/node_modules/zod/v4/locales/no.d.cts +5 -0
  645. package/node_modules/zod/v4/locales/no.d.ts +4 -0
  646. package/node_modules/zod/v4/locales/no.js +108 -0
  647. package/node_modules/zod/v4/locales/ota.cjs +136 -0
  648. package/node_modules/zod/v4/locales/ota.d.cts +5 -0
  649. package/node_modules/zod/v4/locales/ota.d.ts +4 -0
  650. package/node_modules/zod/v4/locales/ota.js +109 -0
  651. package/node_modules/zod/v4/locales/package.json +7 -0
  652. package/node_modules/zod/v4/locales/pl.cjs +136 -0
  653. package/node_modules/zod/v4/locales/pl.d.cts +5 -0
  654. package/node_modules/zod/v4/locales/pl.d.ts +4 -0
  655. package/node_modules/zod/v4/locales/pl.js +109 -0
  656. package/node_modules/zod/v4/locales/ps.cjs +141 -0
  657. package/node_modules/zod/v4/locales/ps.d.cts +5 -0
  658. package/node_modules/zod/v4/locales/ps.d.ts +4 -0
  659. package/node_modules/zod/v4/locales/ps.js +114 -0
  660. package/node_modules/zod/v4/locales/pt.cjs +135 -0
  661. package/node_modules/zod/v4/locales/pt.d.cts +5 -0
  662. package/node_modules/zod/v4/locales/pt.d.ts +4 -0
  663. package/node_modules/zod/v4/locales/pt.js +108 -0
  664. package/node_modules/zod/v4/locales/ro.cjs +146 -0
  665. package/node_modules/zod/v4/locales/ro.d.cts +5 -0
  666. package/node_modules/zod/v4/locales/ro.d.ts +4 -0
  667. package/node_modules/zod/v4/locales/ro.js +119 -0
  668. package/node_modules/zod/v4/locales/ru.cjs +183 -0
  669. package/node_modules/zod/v4/locales/ru.d.cts +5 -0
  670. package/node_modules/zod/v4/locales/ru.d.ts +4 -0
  671. package/node_modules/zod/v4/locales/ru.js +156 -0
  672. package/node_modules/zod/v4/locales/sl.cjs +136 -0
  673. package/node_modules/zod/v4/locales/sl.d.cts +5 -0
  674. package/node_modules/zod/v4/locales/sl.d.ts +4 -0
  675. package/node_modules/zod/v4/locales/sl.js +109 -0
  676. package/node_modules/zod/v4/locales/sv.cjs +137 -0
  677. package/node_modules/zod/v4/locales/sv.d.cts +5 -0
  678. package/node_modules/zod/v4/locales/sv.d.ts +4 -0
  679. package/node_modules/zod/v4/locales/sv.js +110 -0
  680. package/node_modules/zod/v4/locales/ta.cjs +137 -0
  681. package/node_modules/zod/v4/locales/ta.d.cts +5 -0
  682. package/node_modules/zod/v4/locales/ta.d.ts +4 -0
  683. package/node_modules/zod/v4/locales/ta.js +110 -0
  684. package/node_modules/zod/v4/locales/th.cjs +137 -0
  685. package/node_modules/zod/v4/locales/th.d.cts +5 -0
  686. package/node_modules/zod/v4/locales/th.d.ts +4 -0
  687. package/node_modules/zod/v4/locales/th.js +110 -0
  688. package/node_modules/zod/v4/locales/tr.cjs +132 -0
  689. package/node_modules/zod/v4/locales/tr.d.cts +5 -0
  690. package/node_modules/zod/v4/locales/tr.d.ts +4 -0
  691. package/node_modules/zod/v4/locales/tr.js +105 -0
  692. package/node_modules/zod/v4/locales/ua.cjs +12 -0
  693. package/node_modules/zod/v4/locales/ua.d.cts +5 -0
  694. package/node_modules/zod/v4/locales/ua.d.ts +5 -0
  695. package/node_modules/zod/v4/locales/ua.js +5 -0
  696. package/node_modules/zod/v4/locales/uk.cjs +135 -0
  697. package/node_modules/zod/v4/locales/uk.d.cts +5 -0
  698. package/node_modules/zod/v4/locales/uk.d.ts +4 -0
  699. package/node_modules/zod/v4/locales/uk.js +108 -0
  700. package/node_modules/zod/v4/locales/ur.cjs +137 -0
  701. package/node_modules/zod/v4/locales/ur.d.cts +5 -0
  702. package/node_modules/zod/v4/locales/ur.d.ts +4 -0
  703. package/node_modules/zod/v4/locales/ur.js +110 -0
  704. package/node_modules/zod/v4/locales/uz.cjs +137 -0
  705. package/node_modules/zod/v4/locales/uz.d.cts +5 -0
  706. package/node_modules/zod/v4/locales/uz.d.ts +4 -0
  707. package/node_modules/zod/v4/locales/uz.js +110 -0
  708. package/node_modules/zod/v4/locales/vi.cjs +135 -0
  709. package/node_modules/zod/v4/locales/vi.d.cts +5 -0
  710. package/node_modules/zod/v4/locales/vi.d.ts +4 -0
  711. package/node_modules/zod/v4/locales/vi.js +108 -0
  712. package/node_modules/zod/v4/locales/yo.cjs +134 -0
  713. package/node_modules/zod/v4/locales/yo.d.cts +5 -0
  714. package/node_modules/zod/v4/locales/yo.d.ts +4 -0
  715. package/node_modules/zod/v4/locales/yo.js +107 -0
  716. package/node_modules/zod/v4/locales/zh-CN.cjs +136 -0
  717. package/node_modules/zod/v4/locales/zh-CN.d.cts +5 -0
  718. package/node_modules/zod/v4/locales/zh-CN.d.ts +4 -0
  719. package/node_modules/zod/v4/locales/zh-CN.js +109 -0
  720. package/node_modules/zod/v4/locales/zh-TW.cjs +134 -0
  721. package/node_modules/zod/v4/locales/zh-TW.d.cts +5 -0
  722. package/node_modules/zod/v4/locales/zh-TW.d.ts +4 -0
  723. package/node_modules/zod/v4/locales/zh-TW.js +107 -0
  724. package/node_modules/zod/v4/mini/checks.cjs +34 -0
  725. package/node_modules/zod/v4/mini/checks.d.cts +1 -0
  726. package/node_modules/zod/v4/mini/checks.d.ts +1 -0
  727. package/node_modules/zod/v4/mini/checks.js +1 -0
  728. package/node_modules/zod/v4/mini/coerce.cjs +52 -0
  729. package/node_modules/zod/v4/mini/coerce.d.cts +7 -0
  730. package/node_modules/zod/v4/mini/coerce.d.ts +7 -0
  731. package/node_modules/zod/v4/mini/coerce.js +22 -0
  732. package/node_modules/zod/v4/mini/external.cjs +63 -0
  733. package/node_modules/zod/v4/mini/external.d.cts +13 -0
  734. package/node_modules/zod/v4/mini/external.d.ts +13 -0
  735. package/node_modules/zod/v4/mini/external.js +14 -0
  736. package/node_modules/zod/v4/mini/index.cjs +32 -0
  737. package/node_modules/zod/v4/mini/index.d.cts +3 -0
  738. package/node_modules/zod/v4/mini/index.d.ts +3 -0
  739. package/node_modules/zod/v4/mini/index.js +3 -0
  740. package/node_modules/zod/v4/mini/iso.cjs +64 -0
  741. package/node_modules/zod/v4/mini/iso.d.cts +22 -0
  742. package/node_modules/zod/v4/mini/iso.d.ts +22 -0
  743. package/node_modules/zod/v4/mini/iso.js +34 -0
  744. package/node_modules/zod/v4/mini/package.json +7 -0
  745. package/node_modules/zod/v4/mini/parse.cjs +16 -0
  746. package/node_modules/zod/v4/mini/parse.d.cts +1 -0
  747. package/node_modules/zod/v4/mini/parse.d.ts +1 -0
  748. package/node_modules/zod/v4/mini/parse.js +1 -0
  749. package/node_modules/zod/v4/mini/schemas.cjs +1083 -0
  750. package/node_modules/zod/v4/mini/schemas.d.cts +445 -0
  751. package/node_modules/zod/v4/mini/schemas.d.ts +445 -0
  752. package/node_modules/zod/v4/mini/schemas.js +961 -0
  753. package/node_modules/zod/v4/package.json +7 -0
  754. package/node_modules/zod/v4-mini/index.cjs +32 -0
  755. package/node_modules/zod/v4-mini/index.d.cts +3 -0
  756. package/node_modules/zod/v4-mini/index.d.ts +3 -0
  757. package/node_modules/zod/v4-mini/index.js +3 -0
  758. package/node_modules/zod/v4-mini/package.json +7 -0
  759. package/npm-shrinkwrap.json +54 -0
  760. package/openclaw.plugin.json +997 -1
  761. package/package.json +48 -7
  762. package/index.ts +0 -17
  763. package/src/channel.test.ts +0 -235
  764. package/src/channel.ts +0 -433
  765. package/src/config-schema.ts +0 -61
  766. package/src/group-mentions.ts +0 -15
  767. package/src/mattermost/accounts.ts +0 -128
  768. package/src/mattermost/client.test.ts +0 -19
  769. package/src/mattermost/client.ts +0 -230
  770. package/src/mattermost/index.ts +0 -9
  771. package/src/mattermost/monitor-helpers.ts +0 -93
  772. package/src/mattermost/monitor-onchar.ts +0 -25
  773. package/src/mattermost/monitor-websocket.test.ts +0 -232
  774. package/src/mattermost/monitor-websocket.ts +0 -221
  775. package/src/mattermost/monitor.ts +0 -1030
  776. package/src/mattermost/probe.ts +0 -73
  777. package/src/mattermost/reactions.test-helpers.ts +0 -83
  778. package/src/mattermost/reactions.test.ts +0 -103
  779. package/src/mattermost/reactions.ts +0 -124
  780. package/src/mattermost/reconnect.test.ts +0 -192
  781. package/src/mattermost/reconnect.ts +0 -103
  782. package/src/mattermost/send.ts +0 -231
  783. package/src/normalize.ts +0 -46
  784. package/src/onboarding-helpers.ts +0 -1
  785. package/src/onboarding.ts +0 -186
  786. package/src/runtime.ts +0 -14
  787. package/src/types.ts +0 -57
@@ -0,0 +1,2671 @@
1
+ import { C as resolveChannelMediaMaxBytes, E as warnMissingProviderGroupPolicyFallbackOnce, S as resolveAllowlistProviderRuntimeGroupPolicy, T as resolveDefaultGroupPolicy, _ as logInboundDrop, c as buildAgentMediaPayload, d as createChannelMessageReplyPipeline, f as createChannelPairingController, h as listSkillCommandsForAgents, i as normalizeMattermostAllowEntry, l as buildModelsProviderData, n as formatMattermostDirectMessageDropLog, o as resolveMattermostMonitorInboundAccess, s as DEFAULT_GROUP_HISTORY_LIMIT, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, v as logTypingFailure, x as registerPluginHttpRoute, y as parseTcpPort } from "./monitor-auth-BiDuyvOc.js";
2
+ import { _ as readMattermostError, a as MattermostPostSchema, b as updateMattermostPost, c as createMattermostPost, f as fetchMattermostMe, g as normalizeMattermostBaseUrl, h as fetchMattermostUserTeams, i as resolveMattermostReplyToMode, l as deleteMattermostPost, o as createMattermostClient, p as fetchMattermostUser, r as resolveMattermostAccount, t as listMattermostAccountIds, u as fetchMattermostChannel, y as sendMattermostTyping } from "./accounts-DnAHfb5f.js";
3
+ import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.js";
4
+ import { C as registerSlashCommands, S as isSlashCommandsEnabled, T as resolveSlashCommandConfig, _ as renderMattermostModelsPickerView, a as sendMessageMattermost, b as DEFAULT_COMMAND_SPECS, c as computeInteractionCallbackUrl, d as setInteractionCallbackUrl, f as setInteractionSecret, g as parseMattermostModelPickerContext, h as buildMattermostAllowedModelRefs, l as createMattermostInteractionHandler, m as deliverMattermostReplyPayload, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as createMattermostReplyDeliveryBarrier, r as getSlashCommandState, s as buildButtonProps, t as activateSlashCommands, u as resolveInteractionCallbackPath, v as renderMattermostProviderPickerView, w as resolveCallbackUrl, x as cleanupSlashCommands, y as resolveMattermostModelPickerCurrentModel } from "./slash-state-I1qleAHM.js";
5
+ import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringEntries, normalizeTrimmedStringList, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
6
+ import { formatInboundFromLabel } from "openclaw/plugin-sdk/channel-inbound";
7
+ import { buildChannelProgressDraftLineForEntry, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
8
+ import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
9
+ import { asDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
10
+ import { safeParseJsonWithSchema, safeParseWithSchema } from "openclaw/plugin-sdk/extension-shared";
11
+ import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload } from "openclaw/plugin-sdk/reply-payload";
12
+ import { fetchWithSsrFGuard, isPrivateNetworkOptInEnabled, ssrfPolicyFromPrivateNetworkOptIn } from "openclaw/plugin-sdk/ssrf-runtime";
13
+ import { z } from "zod";
14
+ import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
15
+ import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
16
+ import { randomUUID } from "node:crypto";
17
+ import { isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
18
+ import { createClaimableDedupe } from "openclaw/plugin-sdk/persistent-dedupe";
19
+ import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
20
+ import WebSocket from "ws";
21
+ import { resolveGlobalDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
22
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
23
+ //#region extensions/mattermost/src/mattermost/directory.ts
24
+ function buildClient(params) {
25
+ const account = resolveMattermostAccount({
26
+ cfg: params.cfg,
27
+ accountId: params.accountId
28
+ });
29
+ if (!account.enabled || !account.botToken || !account.baseUrl) return null;
30
+ return createMattermostClient({
31
+ baseUrl: account.baseUrl,
32
+ botToken: account.botToken,
33
+ allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
34
+ });
35
+ }
36
+ /**
37
+ * Build clients from ALL enabled accounts (deduplicated by token).
38
+ *
39
+ * We always scan every account because:
40
+ * - Private channels are only visible to bots that are members
41
+ * - The requesting agent's account may have an expired/invalid token
42
+ *
43
+ * This means a single healthy bot token is enough for directory discovery.
44
+ */
45
+ function buildClients(params) {
46
+ const accountIds = listMattermostAccountIds(params.cfg);
47
+ const seen = /* @__PURE__ */ new Set();
48
+ const clients = [];
49
+ for (const id of accountIds) {
50
+ const client = buildClient({
51
+ cfg: params.cfg,
52
+ accountId: id
53
+ });
54
+ if (client && !seen.has(client.token)) {
55
+ seen.add(client.token);
56
+ clients.push(client);
57
+ }
58
+ }
59
+ return clients;
60
+ }
61
+ /**
62
+ * List channels (public + private) visible to any configured bot account.
63
+ *
64
+ * NOTE: Uses per_page=200 which covers most instances. Mattermost does not
65
+ * return a "has more" indicator, so very large instances (200+ channels per bot)
66
+ * may see incomplete results. Pagination can be added if needed.
67
+ */
68
+ async function listMattermostDirectoryGroups(params) {
69
+ const clients = buildClients(params);
70
+ if (!clients.length) return [];
71
+ const q = normalizeLowercaseStringOrEmpty(params.query);
72
+ const seenIds = /* @__PURE__ */ new Set();
73
+ const entries = [];
74
+ for (const client of clients) try {
75
+ const me = await fetchMattermostMe(client);
76
+ const channels = await client.request(`/users/${me.id}/channels?per_page=200`);
77
+ for (const ch of channels) {
78
+ if (ch.type !== "O" && ch.type !== "P") continue;
79
+ if (seenIds.has(ch.id)) continue;
80
+ if (q) {
81
+ const name = normalizeLowercaseStringOrEmpty(ch.name);
82
+ const display = normalizeLowercaseStringOrEmpty(ch.display_name);
83
+ if (!name.includes(q) && !display.includes(q)) continue;
84
+ }
85
+ seenIds.add(ch.id);
86
+ entries.push({
87
+ kind: "group",
88
+ id: `channel:${ch.id}`,
89
+ name: ch.name ?? void 0,
90
+ handle: ch.display_name ?? void 0
91
+ });
92
+ }
93
+ } catch (err) {
94
+ console.debug?.("[mattermost-directory] listGroups: skipping account:", err?.message);
95
+ continue;
96
+ }
97
+ return params.limit && params.limit > 0 ? entries.slice(0, params.limit) : entries;
98
+ }
99
+ /**
100
+ * List team members as peer directory entries.
101
+ *
102
+ * Uses only the first available client since all bots in a team see the same
103
+ * user list (unlike channels where membership varies). Uses the first team
104
+ * returned — multi-team setups will only see members from that team.
105
+ *
106
+ * NOTE: per_page=200 for member listing; same pagination caveat as groups.
107
+ */
108
+ async function listMattermostDirectoryPeers(params) {
109
+ const clients = buildClients(params);
110
+ if (!clients.length) return [];
111
+ const client = clients[0];
112
+ try {
113
+ const me = await fetchMattermostMe(client);
114
+ const teams = await client.request("/users/me/teams");
115
+ if (!teams.length) return [];
116
+ const teamId = teams[0].id;
117
+ const q = normalizeLowercaseStringOrEmpty(params.query);
118
+ let users;
119
+ if (q) users = await client.request("/users/search", {
120
+ method: "POST",
121
+ body: JSON.stringify({
122
+ term: q,
123
+ team_id: teamId
124
+ })
125
+ });
126
+ else {
127
+ const userIds = (await client.request(`/teams/${teamId}/members?per_page=200`)).map((m) => m.user_id).filter((id) => id !== me.id);
128
+ if (!userIds.length) return [];
129
+ users = await client.request("/users/ids", {
130
+ method: "POST",
131
+ body: JSON.stringify(userIds)
132
+ });
133
+ }
134
+ const entries = users.filter((u) => u.id !== me.id).map((u) => ({
135
+ kind: "user",
136
+ id: `user:${u.id}`,
137
+ name: u.username ?? void 0,
138
+ handle: [u.first_name, u.last_name].filter(Boolean).join(" ").trim() || u.nickname || void 0
139
+ }));
140
+ return params.limit && params.limit > 0 ? entries.slice(0, params.limit) : entries;
141
+ } catch (err) {
142
+ console.debug?.("[mattermost-directory] listPeers failed:", err?.message);
143
+ return [];
144
+ }
145
+ }
146
+ //#endregion
147
+ //#region extensions/mattermost/src/mattermost/draft-stream.ts
148
+ const MATTERMOST_STREAM_MAX_CHARS = 4e3;
149
+ const DEFAULT_THROTTLE_MS = 1e3;
150
+ function normalizeMattermostDraftText(text, maxChars) {
151
+ const trimmed = text.trim();
152
+ if (!trimmed) return "";
153
+ if (trimmed.length <= maxChars) return trimmed;
154
+ return `${trimmed.slice(0, Math.max(0, maxChars - 3)).trimEnd()}...`;
155
+ }
156
+ function createMattermostDraftStream(params) {
157
+ const maxChars = Math.min(params.maxChars ?? MATTERMOST_STREAM_MAX_CHARS, MATTERMOST_STREAM_MAX_CHARS);
158
+ const throttleMs = Math.max(250, params.throttleMs ?? DEFAULT_THROTTLE_MS);
159
+ const streamState = {
160
+ stopped: false,
161
+ final: false
162
+ };
163
+ let streamPostId;
164
+ let lastSentText = "";
165
+ const sendOrEditStreamMessage = async (text) => {
166
+ if (streamState.stopped && !streamState.final) return false;
167
+ const normalized = normalizeMattermostDraftText(params.renderText?.(text) ?? text, maxChars);
168
+ if (!normalized) return false;
169
+ if (normalized === lastSentText) return true;
170
+ try {
171
+ if (streamPostId) await updateMattermostPost(params.client, streamPostId, { message: normalized });
172
+ else {
173
+ const postId = (await createMattermostPost(params.client, {
174
+ channelId: params.channelId,
175
+ message: normalized,
176
+ rootId: params.rootId
177
+ })).id?.trim();
178
+ if (!postId) {
179
+ streamState.stopped = true;
180
+ params.warn?.("mattermost stream preview stopped (missing post id from create)");
181
+ return false;
182
+ }
183
+ streamPostId = postId;
184
+ }
185
+ lastSentText = normalized;
186
+ return true;
187
+ } catch (err) {
188
+ streamState.stopped = true;
189
+ params.warn?.(`mattermost stream preview failed: ${err instanceof Error ? err.message : String(err)}`);
190
+ return false;
191
+ }
192
+ };
193
+ const { loop, update, stop, clear, discardPending, seal } = createFinalizableDraftLifecycle({
194
+ throttleMs,
195
+ state: streamState,
196
+ sendOrEditStreamMessage,
197
+ readMessageId: () => streamPostId,
198
+ clearMessageId: () => {
199
+ streamPostId = void 0;
200
+ },
201
+ isValidMessageId: (value) => typeof value === "string" && value.length > 0,
202
+ deleteMessage: async (postId) => {
203
+ await deleteMattermostPost(params.client, postId);
204
+ },
205
+ warn: params.warn,
206
+ warnPrefix: "mattermost stream preview cleanup failed"
207
+ });
208
+ const forceNewMessage = () => {
209
+ streamPostId = void 0;
210
+ lastSentText = "";
211
+ loop.resetPending();
212
+ loop.resetThrottleWindow();
213
+ };
214
+ params.log?.(`mattermost stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
215
+ return {
216
+ update,
217
+ flush: loop.flush,
218
+ postId: () => streamPostId,
219
+ clear,
220
+ discardPending,
221
+ seal,
222
+ stop,
223
+ forceNewMessage
224
+ };
225
+ }
226
+ //#endregion
227
+ //#region extensions/mattermost/src/mattermost/monitor-gating.ts
228
+ function mapMattermostChannelTypeToChatType(channelType) {
229
+ const normalized = channelType?.trim().toUpperCase();
230
+ if (!normalized) return "direct";
231
+ if (normalized === "D") return "direct";
232
+ if (normalized === "G" || normalized === "P") return "group";
233
+ return "channel";
234
+ }
235
+ function resolveMattermostTrustedChatKind(params) {
236
+ const channelType = params.channelType?.trim();
237
+ if (channelType) return mapMattermostChannelTypeToChatType(channelType);
238
+ return params.fallback ?? "direct";
239
+ }
240
+ function evaluateMattermostMentionGate(params) {
241
+ const shouldRequireMention = params.kind !== "direct" && params.resolveRequireMention({
242
+ cfg: params.cfg,
243
+ channel: "mattermost",
244
+ accountId: params.accountId,
245
+ groupId: params.channelId,
246
+ requireMentionOverride: params.requireMentionOverride
247
+ });
248
+ const shouldBypassMention = params.isControlCommand && shouldRequireMention && !params.wasMentioned && params.commandAuthorized;
249
+ const effectiveWasMentioned = params.wasMentioned || shouldBypassMention || params.oncharTriggered || params.threadAlreadyEngaged === true;
250
+ if (params.oncharEnabled && !params.oncharTriggered && !params.wasMentioned && !params.isControlCommand && params.threadAlreadyEngaged !== true) return {
251
+ shouldRequireMention,
252
+ shouldBypassMention,
253
+ effectiveWasMentioned,
254
+ dropReason: "onchar-not-triggered"
255
+ };
256
+ if (params.kind !== "direct" && shouldRequireMention && params.canDetectMention && !effectiveWasMentioned) return {
257
+ shouldRequireMention,
258
+ shouldBypassMention,
259
+ effectiveWasMentioned,
260
+ dropReason: "missing-mention"
261
+ };
262
+ return {
263
+ shouldRequireMention,
264
+ shouldBypassMention,
265
+ effectiveWasMentioned,
266
+ dropReason: null
267
+ };
268
+ }
269
+ //#endregion
270
+ //#region extensions/mattermost/src/mattermost/monitor-helpers.ts
271
+ const formatInboundFromLabel$1 = formatInboundFromLabel;
272
+ function resolveThreadSessionKeys$1(params) {
273
+ return resolveThreadSessionKeys({
274
+ ...params,
275
+ normalizeThreadId: (threadId) => threadId
276
+ });
277
+ }
278
+ /**
279
+ * Strip bot mention from message text while preserving newlines and
280
+ * block-level Markdown formatting (headings, lists, blockquotes).
281
+ */
282
+ function normalizeMention(text, mention) {
283
+ if (!mention) return text.trim();
284
+ const escaped = mention.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
285
+ const hasMentionRe = new RegExp(`@${escaped}\\b`, "i");
286
+ const leadingMentionRe = new RegExp(`^([\\t ]*)@${escaped}\\b[\\t ]*`, "i");
287
+ const trailingMentionRe = new RegExp(`[\\t ]*@${escaped}\\b[\\t ]*$`, "i");
288
+ const normalizedLines = text.split("\n").map((line) => {
289
+ const hadMention = hasMentionRe.test(line);
290
+ const normalizedLine = line.replace(leadingMentionRe, "$1").replace(trailingMentionRe, "").replace(new RegExp(`@${escaped}\\b`, "gi"), "").replace(/(\S)[ \t]{2,}/g, "$1 ");
291
+ return {
292
+ text: normalizedLine,
293
+ mentionOnlyBlank: hadMention && normalizedLine.trim() === ""
294
+ };
295
+ });
296
+ while (normalizedLines[0]?.mentionOnlyBlank) normalizedLines.shift();
297
+ while (normalizedLines.at(-1)?.text.trim() === "") normalizedLines.pop();
298
+ return normalizedLines.map((line) => line.text).join("\n");
299
+ }
300
+ function shouldDropEmptyMattermostBody(params) {
301
+ if (/[^\p{White_Space}\p{Cc}\p{Cf}\p{M}]/u.test(params.bodyText)) return false;
302
+ const botUsername = normalizeLowercaseStringOrEmpty(params.botUsername ?? "");
303
+ const bareMention = params.rawText.match(/^[ \t]*(@\S+)[ \t]*$/u)?.[1];
304
+ return !botUsername || normalizeLowercaseStringOrEmpty(bareMention ?? "") !== `@${botUsername}`;
305
+ }
306
+ //#endregion
307
+ //#region extensions/mattermost/src/mattermost/monitor-onchar.ts
308
+ const DEFAULT_ONCHAR_PREFIXES = [">", "!"];
309
+ function resolveOncharPrefixes(prefixes) {
310
+ const cleaned = prefixes ? normalizeStringEntries(prefixes) : DEFAULT_ONCHAR_PREFIXES;
311
+ return cleaned.length > 0 ? cleaned : DEFAULT_ONCHAR_PREFIXES;
312
+ }
313
+ function stripOncharPrefix(text, prefixes) {
314
+ const trimmed = text.trimStart();
315
+ for (const prefix of prefixes) {
316
+ if (!prefix) continue;
317
+ if (trimmed.startsWith(prefix)) return {
318
+ triggered: true,
319
+ stripped: trimmed.slice(prefix.length).trimStart()
320
+ };
321
+ }
322
+ return {
323
+ triggered: false,
324
+ stripped: text
325
+ };
326
+ }
327
+ //#endregion
328
+ //#region extensions/mattermost/src/mattermost/monitor-resources.ts
329
+ const CHANNEL_CACHE_TTL_MS = 5 * 6e4;
330
+ const USER_CACHE_TTL_MS = 10 * 6e4;
331
+ function createMattermostMonitorResources(params) {
332
+ const { accountId, callbackUrl, client, logger, mediaMaxBytes, saveRemoteMedia, mediaKindFromMime } = params;
333
+ const channelCache = /* @__PURE__ */ new Map();
334
+ const userCache = /* @__PURE__ */ new Map();
335
+ const getCachedValue = (cache, key, nowMs) => {
336
+ const cached = cache.get(key);
337
+ if (!cached) return;
338
+ if (nowMs !== void 0 && cached.expiresAt > nowMs) return cached.value;
339
+ cache.delete(key);
340
+ };
341
+ const setCachedValue = (cache, key, value, ttlMs, rawNowMs) => {
342
+ const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNowMs });
343
+ if (expiresAt !== void 0) cache.set(key, {
344
+ value,
345
+ expiresAt
346
+ });
347
+ };
348
+ const resolveMattermostMedia = async (fileIds) => {
349
+ const ids = normalizeStringEntries(fileIds ?? []);
350
+ if (ids.length === 0) return [];
351
+ const out = [];
352
+ for (const fileId of ids) try {
353
+ const saved = await saveRemoteMedia({
354
+ url: `${client.apiBaseUrl}/files/${fileId}`,
355
+ requestInit: { headers: { Authorization: `Bearer ${client.token}` } },
356
+ filePathHint: fileId,
357
+ maxBytes: mediaMaxBytes,
358
+ ssrfPolicy: { allowedHostnames: [new URL(client.baseUrl).hostname] }
359
+ });
360
+ const contentType = saved.contentType ?? void 0;
361
+ out.push({
362
+ path: saved.path,
363
+ contentType,
364
+ kind: mediaKindFromMime(contentType) ?? "unknown"
365
+ });
366
+ } catch (err) {
367
+ logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
368
+ }
369
+ return out;
370
+ };
371
+ const sendTypingIndicator = async (channelId, parentId) => {
372
+ await sendMattermostTyping(client, {
373
+ channelId,
374
+ parentId
375
+ });
376
+ };
377
+ const resolveChannelInfo = async (channelId) => {
378
+ const rawNow = Date.now();
379
+ const cached = getCachedValue(channelCache, channelId, asDateTimestampMs(rawNow));
380
+ if (cached !== void 0) return cached;
381
+ try {
382
+ const info = await fetchMattermostChannel(client, channelId);
383
+ setCachedValue(channelCache, channelId, info, CHANNEL_CACHE_TTL_MS, rawNow);
384
+ return info;
385
+ } catch (err) {
386
+ logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
387
+ setCachedValue(channelCache, channelId, null, CHANNEL_CACHE_TTL_MS, rawNow);
388
+ return null;
389
+ }
390
+ };
391
+ const resolveUserInfo = async (userId) => {
392
+ const rawNow = Date.now();
393
+ const cached = getCachedValue(userCache, userId, asDateTimestampMs(rawNow));
394
+ if (cached !== void 0) return cached;
395
+ try {
396
+ const info = await fetchMattermostUser(client, userId);
397
+ setCachedValue(userCache, userId, info, USER_CACHE_TTL_MS, rawNow);
398
+ return info;
399
+ } catch (err) {
400
+ logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
401
+ setCachedValue(userCache, userId, null, USER_CACHE_TTL_MS, rawNow);
402
+ return null;
403
+ }
404
+ };
405
+ const buildModelPickerProps = (channelId, buttons) => buildButtonProps({
406
+ callbackUrl,
407
+ accountId,
408
+ channelId,
409
+ buttons
410
+ });
411
+ const updateModelPickerPost = async (paramsLocal) => {
412
+ const props = buildModelPickerProps(paramsLocal.channelId, paramsLocal.buttons ?? []) ?? { attachments: [] };
413
+ await updateMattermostPost(client, paramsLocal.postId, {
414
+ message: paramsLocal.message,
415
+ props
416
+ });
417
+ return {};
418
+ };
419
+ return {
420
+ resolveMattermostMedia,
421
+ sendTypingIndicator,
422
+ resolveChannelInfo,
423
+ resolveUserInfo,
424
+ updateModelPickerPost
425
+ };
426
+ }
427
+ //#endregion
428
+ //#region extensions/mattermost/src/mattermost/monitor-slash.ts
429
+ function buildSlashCommands(params) {
430
+ const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
431
+ if (!params.nativeSkills) return commandsToRegister;
432
+ try {
433
+ const skillCommands = listSkillCommandsForAgents({ cfg: params.cfg });
434
+ for (const spec of skillCommands) {
435
+ const name = typeof spec.name === "string" ? spec.name.trim() : "";
436
+ if (!name) continue;
437
+ const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
438
+ commandsToRegister.push({
439
+ trigger,
440
+ description: spec.description || `Run skill ${name}`,
441
+ autoComplete: true,
442
+ autoCompleteHint: "[args]",
443
+ originalName: name
444
+ });
445
+ }
446
+ } catch (err) {
447
+ params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
448
+ }
449
+ return commandsToRegister;
450
+ }
451
+ function dedupeSlashCommands(commands) {
452
+ const seen = /* @__PURE__ */ new Set();
453
+ return commands.filter((cmd) => {
454
+ const key = cmd.trigger.trim();
455
+ if (!key || seen.has(key)) return false;
456
+ seen.add(key);
457
+ return true;
458
+ });
459
+ }
460
+ function buildTriggerMap(commands) {
461
+ const triggerMap = /* @__PURE__ */ new Map();
462
+ for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
463
+ return triggerMap;
464
+ }
465
+ function warnOnSuspiciousCallbackUrl(params) {
466
+ try {
467
+ const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
468
+ const callbackHost = new URL(params.callbackUrl).hostname;
469
+ if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) params.runtime.error?.(`mattermost: slash commands callbackUrl resolved to ${params.callbackUrl} (loopback) while baseUrl is ${params.baseUrl}. This MAY be unreachable depending on your deployment. If native slash commands don't work, set channels.mattermost.commands.callbackUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
470
+ } catch {}
471
+ }
472
+ async function registerSlashCommandsAcrossTeams(params) {
473
+ const registered = [];
474
+ let teamRegistrationFailures = 0;
475
+ for (const team of params.teams) try {
476
+ const created = await registerSlashCommands({
477
+ client: params.client,
478
+ teamId: team.id,
479
+ creatorUserId: params.botUserId,
480
+ callbackUrl: params.callbackUrl,
481
+ commands: params.commands,
482
+ log: (msg) => params.runtime.log?.(msg)
483
+ });
484
+ registered.push(...created);
485
+ } catch (err) {
486
+ teamRegistrationFailures += 1;
487
+ params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
488
+ }
489
+ return {
490
+ registered,
491
+ teamRegistrationFailures
492
+ };
493
+ }
494
+ async function registerMattermostMonitorSlashCommands(params) {
495
+ const commandsRaw = params.account.config.commands;
496
+ const slashConfig = resolveSlashCommandConfig(commandsRaw);
497
+ if (!isSlashCommandsEnabled(slashConfig)) return;
498
+ try {
499
+ const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
500
+ const slashCallbackUrl = resolveCallbackUrl({
501
+ config: slashConfig,
502
+ gatewayPort: parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789,
503
+ gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
504
+ });
505
+ warnOnSuspiciousCallbackUrl({
506
+ runtime: params.runtime,
507
+ baseUrl: params.baseUrl,
508
+ callbackUrl: slashCallbackUrl
509
+ });
510
+ const dedupedCommands = dedupeSlashCommands(buildSlashCommands({
511
+ cfg: params.cfg,
512
+ runtime: params.runtime,
513
+ nativeSkills: slashConfig.nativeSkills === true
514
+ }));
515
+ const { registered, teamRegistrationFailures } = await registerSlashCommandsAcrossTeams({
516
+ client: params.client,
517
+ teams,
518
+ botUserId: params.botUserId,
519
+ callbackUrl: slashCallbackUrl,
520
+ commands: dedupedCommands,
521
+ runtime: params.runtime
522
+ });
523
+ if (registered.length === 0) {
524
+ params.runtime.error?.("mattermost: native slash commands enabled but no commands could be registered; keeping slash callbacks inactive");
525
+ return;
526
+ }
527
+ if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
528
+ activateSlashCommands({
529
+ account: params.account,
530
+ commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
531
+ registeredCommands: registered,
532
+ triggerMap: buildTriggerMap(dedupedCommands),
533
+ api: {
534
+ cfg: params.cfg,
535
+ runtime: params.runtime
536
+ },
537
+ log: (msg) => params.runtime.log?.(msg)
538
+ });
539
+ params.runtime.log?.(`mattermost: slash commands registered (${registered.length} commands across ${teams.length} teams, callback=${slashCallbackUrl})`);
540
+ } catch (err) {
541
+ params.runtime.error?.(`mattermost: failed to register slash commands: ${String(err)}`);
542
+ }
543
+ }
544
+ //#endregion
545
+ //#region extensions/mattermost/src/mattermost/monitor-websocket.ts
546
+ const MattermostEventPayloadSchema = z.object({
547
+ event: z.string().optional(),
548
+ data: z.object({
549
+ post: z.union([z.string(), MattermostPostSchema]).optional(),
550
+ reaction: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
551
+ channel_id: z.string().optional(),
552
+ channel_name: z.string().optional(),
553
+ channel_display_name: z.string().optional(),
554
+ channel_type: z.string().optional(),
555
+ sender_name: z.string().optional(),
556
+ team_id: z.string().optional()
557
+ }).optional(),
558
+ broadcast: z.object({
559
+ channel_id: z.string().optional(),
560
+ team_id: z.string().optional(),
561
+ user_id: z.string().optional()
562
+ }).optional()
563
+ });
564
+ function parseMattermostEventPayload(raw) {
565
+ return safeParseJsonWithSchema(MattermostEventPayloadSchema, raw);
566
+ }
567
+ function parseMattermostPost(value) {
568
+ if (typeof value === "string") return safeParseJsonWithSchema(MattermostPostSchema, value);
569
+ return safeParseWithSchema(MattermostPostSchema, value);
570
+ }
571
+ var WebSocketClosedBeforeOpenError = class extends Error {
572
+ constructor(code, reason) {
573
+ super(`websocket closed before open (code ${code})`);
574
+ this.code = code;
575
+ this.reason = reason;
576
+ this.name = "WebSocketClosedBeforeOpenError";
577
+ }
578
+ };
579
+ const defaultMattermostWebSocketFactory = (url) => {
580
+ const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
581
+ return new WebSocket(url, agent ? { agent } : void 0);
582
+ };
583
+ function parsePostedPayload(payload) {
584
+ if (payload.event !== "posted") return null;
585
+ const postData = payload.data?.post;
586
+ if (!postData) return null;
587
+ const post = parseMattermostPost(postData);
588
+ if (!post) return null;
589
+ return {
590
+ payload,
591
+ post
592
+ };
593
+ }
594
+ function createMattermostConnectOnce(opts) {
595
+ const webSocketFactory = opts.webSocketFactory ?? defaultMattermostWebSocketFactory;
596
+ const healthCheckIntervalMs = opts.healthCheckIntervalMs ?? 3e4;
597
+ const pingIntervalMs = opts.pingIntervalMs ?? 3e4;
598
+ const pongTimeoutMs = opts.pongTimeoutMs ?? 1e4;
599
+ return async () => {
600
+ const flowId = randomUUID();
601
+ const ws = webSocketFactory(opts.wsUrl);
602
+ const onAbort = () => ws.terminate();
603
+ opts.abortSignal?.addEventListener("abort", onAbort, { once: true });
604
+ const getBotUpdateAt = opts.getBotUpdateAt;
605
+ try {
606
+ return await new Promise((resolve, reject) => {
607
+ let opened = false;
608
+ let settled = false;
609
+ let healthCheckEnabled = getBotUpdateAt != null;
610
+ let healthCheckInFlight = false;
611
+ let healthCheckTimer;
612
+ let protocolKeepaliveEnabled = true;
613
+ let protocolPingTimer;
614
+ let protocolPongTimer;
615
+ let initialUpdateAt;
616
+ const clearTimers = () => {
617
+ if (healthCheckTimer !== void 0) {
618
+ clearTimeout(healthCheckTimer);
619
+ healthCheckTimer = void 0;
620
+ }
621
+ if (protocolPingTimer !== void 0) {
622
+ clearTimeout(protocolPingTimer);
623
+ protocolPingTimer = void 0;
624
+ }
625
+ if (protocolPongTimer !== void 0) {
626
+ clearTimeout(protocolPongTimer);
627
+ protocolPongTimer = void 0;
628
+ }
629
+ };
630
+ const stopHealthChecks = () => {
631
+ healthCheckEnabled = false;
632
+ protocolKeepaliveEnabled = false;
633
+ clearTimers();
634
+ };
635
+ const sendProtocolPing = () => {
636
+ if (!protocolKeepaliveEnabled || settled) return;
637
+ if (protocolPongTimer !== void 0) clearTimeout(protocolPongTimer);
638
+ protocolPongTimer = setTimeout(() => {
639
+ protocolPongTimer = void 0;
640
+ if (!protocolKeepaliveEnabled || settled) return;
641
+ opts.runtime.error?.("mattermost websocket pong timeout — reconnecting");
642
+ stopHealthChecks();
643
+ ws.terminate();
644
+ }, pongTimeoutMs);
645
+ try {
646
+ ws.ping();
647
+ } catch (err) {
648
+ if (!protocolKeepaliveEnabled || settled) return;
649
+ opts.runtime.error?.(`mattermost websocket ping failed: ${String(err)}`);
650
+ stopHealthChecks();
651
+ ws.terminate();
652
+ }
653
+ };
654
+ const scheduleProtocolPing = () => {
655
+ if (!protocolKeepaliveEnabled || settled || protocolPingTimer !== void 0) return;
656
+ protocolPingTimer = setTimeout(() => {
657
+ protocolPingTimer = void 0;
658
+ sendProtocolPing();
659
+ }, pingIntervalMs);
660
+ };
661
+ const scheduleHealthCheck = () => {
662
+ if (!getBotUpdateAt || !healthCheckEnabled || settled || healthCheckInFlight) return;
663
+ healthCheckTimer = setTimeout(() => {
664
+ healthCheckTimer = void 0;
665
+ runHealthCheck();
666
+ }, healthCheckIntervalMs);
667
+ };
668
+ const runHealthCheck = async () => {
669
+ if (!getBotUpdateAt || !healthCheckEnabled || settled || healthCheckInFlight) return;
670
+ healthCheckInFlight = true;
671
+ try {
672
+ const current = await getBotUpdateAt();
673
+ if (!healthCheckEnabled || settled) return;
674
+ if (initialUpdateAt === void 0) {
675
+ initialUpdateAt = current;
676
+ return;
677
+ }
678
+ if (current !== initialUpdateAt) {
679
+ opts.runtime.log?.(`mattermost: bot account updated (update_at changed: ${initialUpdateAt} → ${current}) — reconnecting`);
680
+ stopHealthChecks();
681
+ ws.terminate();
682
+ }
683
+ } catch (err) {
684
+ if (!healthCheckEnabled || settled) return;
685
+ const label = initialUpdateAt === void 0 ? "mattermost: failed to get initial update_at" : "mattermost: health check error";
686
+ opts.runtime.error?.(`${label}: ${String(err)}`);
687
+ } finally {
688
+ healthCheckInFlight = false;
689
+ scheduleHealthCheck();
690
+ }
691
+ };
692
+ const resolveOnce = () => {
693
+ if (settled) return;
694
+ settled = true;
695
+ stopHealthChecks();
696
+ resolve();
697
+ };
698
+ const rejectOnce = (error) => {
699
+ if (settled) return;
700
+ settled = true;
701
+ stopHealthChecks();
702
+ reject(error);
703
+ };
704
+ ws.on("open", () => {
705
+ opened = true;
706
+ captureWsEvent({
707
+ url: opts.wsUrl,
708
+ direction: "local",
709
+ kind: "ws-open",
710
+ flowId,
711
+ meta: { subsystem: "mattermost-websocket" }
712
+ });
713
+ opts.statusSink?.({
714
+ connected: true,
715
+ lastConnectedAt: Date.now(),
716
+ lastError: null
717
+ });
718
+ const authPayload = JSON.stringify({
719
+ seq: opts.nextSeq(),
720
+ action: "authentication_challenge",
721
+ data: { token: opts.botToken }
722
+ });
723
+ captureWsEvent({
724
+ url: opts.wsUrl,
725
+ direction: "outbound",
726
+ kind: "ws-frame",
727
+ flowId,
728
+ payload: authPayload,
729
+ meta: {
730
+ subsystem: "mattermost-websocket",
731
+ eventType: "authentication_challenge"
732
+ }
733
+ });
734
+ ws.send(authPayload);
735
+ scheduleProtocolPing();
736
+ if (getBotUpdateAt) runHealthCheck();
737
+ });
738
+ ws.on("pong", () => {
739
+ if (protocolPongTimer !== void 0) {
740
+ clearTimeout(protocolPongTimer);
741
+ protocolPongTimer = void 0;
742
+ }
743
+ scheduleProtocolPing();
744
+ });
745
+ ws.on("message", async (data) => {
746
+ captureWsEvent({
747
+ url: opts.wsUrl,
748
+ direction: "inbound",
749
+ kind: "ws-frame",
750
+ flowId,
751
+ payload: Buffer.from(rawDataToString(data)),
752
+ meta: { subsystem: "mattermost-websocket" }
753
+ });
754
+ const payload = parseMattermostEventPayload(rawDataToString(data));
755
+ if (!payload) return;
756
+ if (payload.event === "reaction_added" || payload.event === "reaction_removed") {
757
+ if (!opts.onReaction) return;
758
+ try {
759
+ await opts.onReaction(payload);
760
+ } catch (err) {
761
+ opts.runtime.error?.(`mattermost reaction handler failed: ${String(err)}`);
762
+ }
763
+ return;
764
+ }
765
+ if (payload.event !== "posted") return;
766
+ const parsed = parsePostedPayload(payload);
767
+ if (!parsed) return;
768
+ try {
769
+ await opts.onPosted(parsed.post, parsed.payload);
770
+ } catch (err) {
771
+ opts.runtime.error?.(`mattermost handler failed: ${String(err)}`);
772
+ }
773
+ });
774
+ ws.on("close", (code, reason) => {
775
+ captureWsEvent({
776
+ url: opts.wsUrl,
777
+ direction: "local",
778
+ kind: "ws-close",
779
+ flowId,
780
+ closeCode: code,
781
+ payload: reason,
782
+ meta: { subsystem: "mattermost-websocket" }
783
+ });
784
+ stopHealthChecks();
785
+ const message = reasonToString(reason);
786
+ opts.statusSink?.({
787
+ connected: false,
788
+ lastDisconnect: {
789
+ at: Date.now(),
790
+ status: code,
791
+ error: message || void 0
792
+ }
793
+ });
794
+ if (opened) {
795
+ resolveOnce();
796
+ return;
797
+ }
798
+ rejectOnce(new WebSocketClosedBeforeOpenError(code, message || void 0));
799
+ });
800
+ ws.on("error", (err) => {
801
+ captureWsEvent({
802
+ url: opts.wsUrl,
803
+ direction: "local",
804
+ kind: "error",
805
+ flowId,
806
+ errorText: String(err),
807
+ meta: { subsystem: "mattermost-websocket" }
808
+ });
809
+ opts.runtime.error?.(`mattermost websocket error: ${String(err)}`);
810
+ opts.statusSink?.({ lastError: String(err) });
811
+ try {
812
+ ws.close();
813
+ } catch {}
814
+ });
815
+ });
816
+ } finally {
817
+ opts.abortSignal?.removeEventListener("abort", onAbort);
818
+ }
819
+ };
820
+ }
821
+ function reasonToString(reason) {
822
+ if (!reason) return "";
823
+ if (typeof reason === "string") return reason;
824
+ return reason.length > 0 ? reason.toString("utf8") : "";
825
+ }
826
+ //#endregion
827
+ //#region extensions/mattermost/src/mattermost/no-visible-reply-diagnostic.ts
828
+ /**
829
+ * Detects the #80501 symptom: `deliverMattermostReplyPayload` accepted a
830
+ * substantive (non-reasoning) payload, called the underlying
831
+ * `deliverTextOrMediaReply`, and the outcome was `"empty"` — meaning the
832
+ * payload had no text and no media to send, so no Mattermost API call
833
+ * happened. The agent's run completes successfully, but no visible
834
+ * channel/thread reply ever surfaces to the user.
835
+ *
836
+ * Returns a structured violation when the outcome is `"empty"` for a payload
837
+ * that nominally carried user-facing content (text or media bytes that ended
838
+ * up dropped by `resolveSendableOutboundReplyParts`/`sendMediaWithLeadingCaption`).
839
+ * Returns `null` for `"reasoning_skipped"` (intentional suppression),
840
+ * `"text"`, or `"media"` (successful visible sends).
841
+ */
842
+ function evaluateMattermostNoVisibleReply(params) {
843
+ if (params.outcome !== "empty") return null;
844
+ const finalText = typeof params.payload.text === "string" ? params.payload.text.trim() : "";
845
+ const mediaUrlCount = countOutboundMedia(params.payload);
846
+ if (finalText.length === 0 && mediaUrlCount === 0) return null;
847
+ return {
848
+ reason: "no-visible-reply-after-final-delivery",
849
+ outcome: params.outcome,
850
+ finalTextLength: finalText.length,
851
+ mediaUrlCount
852
+ };
853
+ }
854
+ function formatMattermostNoVisibleReplyLog(params) {
855
+ return `mattermost no-visible-reply: ${params.violation.reason} to=${params.to} accountId=${params.accountId} agentId=${params.agentId ?? "unknown"} outcome=${params.violation.outcome} finalTextLength=${params.violation.finalTextLength} mediaUrlCount=${params.violation.mediaUrlCount}`;
856
+ }
857
+ //#endregion
858
+ //#region extensions/mattermost/src/mattermost/reconnect.ts
859
+ /**
860
+ * Reconnection loop with exponential backoff.
861
+ *
862
+ * Calls `connectFn` in a while loop. On normal resolve (connection closed),
863
+ * the backoff resets. On thrown error (connection failed), the current delay is
864
+ * used, then doubled for the next retry.
865
+ * The loop exits when `abortSignal` fires.
866
+ */
867
+ async function runWithReconnect(connectFn, opts = {}) {
868
+ const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
869
+ const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
870
+ const random = opts.random ?? Math.random;
871
+ const backoff = createReconnectBackoff(initialDelayMs, maxDelayMs);
872
+ let attempt = 0;
873
+ while (!opts.abortSignal?.aborted) {
874
+ let outcome = "resolved";
875
+ let error;
876
+ try {
877
+ await connectFn();
878
+ backoff.reset();
879
+ } catch (err) {
880
+ if (opts.abortSignal?.aborted) return;
881
+ outcome = "rejected";
882
+ error = err;
883
+ opts.onError?.(err);
884
+ }
885
+ if (opts.abortSignal?.aborted) return;
886
+ const delayMs = withJitter(backoff.current(), jitterRatio, random);
887
+ if (!(opts.shouldReconnect?.({
888
+ attempt,
889
+ delayMs,
890
+ outcome,
891
+ error
892
+ }) ?? true)) return;
893
+ opts.onReconnect?.(delayMs);
894
+ await sleepAbortable(delayMs, opts.abortSignal);
895
+ if (outcome === "rejected") backoff.increase();
896
+ attempt++;
897
+ }
898
+ }
899
+ function createReconnectBackoff(initialDelayMs, maxDelayMs) {
900
+ let retryDelay = initialDelayMs;
901
+ return {
902
+ current: () => retryDelay,
903
+ reset: () => {
904
+ retryDelay = initialDelayMs;
905
+ },
906
+ increase: () => {
907
+ retryDelay = Math.min(retryDelay * 2, maxDelayMs);
908
+ }
909
+ };
910
+ }
911
+ function withJitter(baseMs, jitterRatio, random) {
912
+ if (jitterRatio <= 0) return baseMs;
913
+ const normalized = Math.max(0, Math.min(1, random()));
914
+ const spread = baseMs * jitterRatio;
915
+ return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
916
+ }
917
+ function sleepAbortable(ms, signal) {
918
+ return new Promise((resolve) => {
919
+ if (signal?.aborted) {
920
+ resolve();
921
+ return;
922
+ }
923
+ const onAbort = () => {
924
+ clearTimeout(timer);
925
+ resolve();
926
+ };
927
+ const timer = setTimeout(() => {
928
+ signal?.removeEventListener("abort", onAbort);
929
+ resolve();
930
+ }, ms);
931
+ signal?.addEventListener("abort", onAbort, { once: true });
932
+ });
933
+ }
934
+ //#endregion
935
+ //#region extensions/mattermost/src/mattermost/thread-participation.ts
936
+ /**
937
+ * In-memory + persisted cache of Mattermost threads the bot has replied in.
938
+ * Lets the bot auto-respond to thread follow-ups without a re-mention after its
939
+ * first visible reply. Mirrors the Slack `sent-thread-cache` dual-layer pattern.
940
+ */
941
+ const TTL_MS = 10080 * 60 * 1e3;
942
+ const MAX_ENTRIES = 5e3;
943
+ const PERSISTENT_MAX_ENTRIES = 1e3;
944
+ const PERSISTENT_NAMESPACE = "mattermost.thread-participation";
945
+ const threadParticipation = resolveGlobalDedupeCache(Symbol.for("openclaw.mattermostThreadParticipation"), {
946
+ ttlMs: TTL_MS,
947
+ maxSize: MAX_ENTRIES
948
+ });
949
+ let persistentStore;
950
+ let persistentStoreDisabled = false;
951
+ function makeKey(accountId, channelId, threadRootId) {
952
+ return `${accountId}:${channelId}:${threadRootId}`;
953
+ }
954
+ function reportPersistentThreadParticipationError(error) {
955
+ try {
956
+ getOptionalMattermostRuntime()?.logging.getChildLogger({
957
+ plugin: "mattermost",
958
+ feature: "thread-participation-state"
959
+ }).warn("Mattermost persistent thread participation state failed", { error: String(error) });
960
+ } catch {}
961
+ }
962
+ function disablePersistentThreadParticipation(error) {
963
+ persistentStoreDisabled = true;
964
+ persistentStore = void 0;
965
+ reportPersistentThreadParticipationError(error);
966
+ }
967
+ function getPersistentThreadParticipationStore() {
968
+ if (persistentStoreDisabled) return;
969
+ if (persistentStore) return persistentStore;
970
+ const runtime = getOptionalMattermostRuntime();
971
+ if (!runtime) return;
972
+ try {
973
+ persistentStore = runtime.state.openKeyedStore({
974
+ namespace: PERSISTENT_NAMESPACE,
975
+ maxEntries: PERSISTENT_MAX_ENTRIES,
976
+ defaultTtlMs: TTL_MS
977
+ });
978
+ return persistentStore;
979
+ } catch (error) {
980
+ disablePersistentThreadParticipation(error);
981
+ return;
982
+ }
983
+ }
984
+ function rememberPersistentThreadParticipation(params) {
985
+ const store = getPersistentThreadParticipationStore();
986
+ if (!store) return;
987
+ store.register(params.key, {
988
+ ...params.agentId ? { agentId: params.agentId } : {},
989
+ repliedAt: Date.now()
990
+ }).catch(disablePersistentThreadParticipation);
991
+ }
992
+ async function lookupPersistentThreadParticipation(key) {
993
+ const store = getPersistentThreadParticipationStore();
994
+ if (!store) return false;
995
+ try {
996
+ return Boolean(await store.lookup(key));
997
+ } catch (error) {
998
+ disablePersistentThreadParticipation(error);
999
+ return false;
1000
+ }
1001
+ }
1002
+ function recordMattermostThreadParticipation(accountId, channelId, threadRootId, opts) {
1003
+ if (!accountId || !channelId || !threadRootId) return;
1004
+ const key = makeKey(accountId, channelId, threadRootId);
1005
+ threadParticipation.check(key);
1006
+ rememberPersistentThreadParticipation({
1007
+ key,
1008
+ agentId: opts?.agentId
1009
+ });
1010
+ }
1011
+ async function hasMattermostThreadParticipationWithPersistence(params) {
1012
+ if (!params.accountId || !params.channelId || !params.threadRootId) return false;
1013
+ const key = makeKey(params.accountId, params.channelId, params.threadRootId);
1014
+ if (threadParticipation.peek(key)) return true;
1015
+ const found = await lookupPersistentThreadParticipation(key);
1016
+ if (found) threadParticipation.check(key);
1017
+ return found;
1018
+ }
1019
+ //#endregion
1020
+ //#region extensions/mattermost/src/mattermost/monitor.ts
1021
+ function shouldUpdateMattermostDraftToolProgress(account) {
1022
+ return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config);
1023
+ }
1024
+ function shouldSuppressMattermostDefaultToolProgressMessages(account) {
1025
+ return account.streamingMode !== "off";
1026
+ }
1027
+ const RECENT_MATTERMOST_MESSAGE_TTL_MS = 5 * 6e4;
1028
+ const RECENT_MATTERMOST_MESSAGE_MAX = 2e3;
1029
+ function normalizeInteractionSourceIps(values) {
1030
+ return normalizeTrimmedStringList(values);
1031
+ }
1032
+ const recentInboundMessages = createClaimableDedupe({
1033
+ ttlMs: RECENT_MATTERMOST_MESSAGE_TTL_MS,
1034
+ memoryMaxSize: RECENT_MATTERMOST_MESSAGE_MAX
1035
+ });
1036
+ var MattermostRetryableInboundError = class extends Error {
1037
+ constructor(message, options) {
1038
+ super(message, options);
1039
+ this.name = "MattermostRetryableInboundError";
1040
+ }
1041
+ };
1042
+ function buildMattermostModelPickerSelectMessageSid(params) {
1043
+ const provider = normalizeLowercaseStringOrEmpty(params.provider);
1044
+ const model = normalizeLowercaseStringOrEmpty(params.model);
1045
+ return `interaction:${params.postId}:select:${provider}/${model}`;
1046
+ }
1047
+ function buildMattermostInboundReplayKeys(params) {
1048
+ return uniqueStrings(params.messageIds.map((id) => `${params.accountId}:${id.trim()}`)).filter((key) => !key.endsWith(":"));
1049
+ }
1050
+ async function processMattermostReplayGuardedPost(params) {
1051
+ const replayGuard = params.replayGuard ?? recentInboundMessages;
1052
+ const replayKeys = buildMattermostInboundReplayKeys({
1053
+ accountId: params.accountId,
1054
+ messageIds: params.messageIds
1055
+ });
1056
+ if (replayKeys.length === 0) {
1057
+ await params.handlePost();
1058
+ return "processed";
1059
+ }
1060
+ const claimedKeys = [];
1061
+ for (const replayKey of replayKeys) if ((await replayGuard.claim(replayKey)).kind === "claimed") claimedKeys.push(replayKey);
1062
+ if (claimedKeys.length === 0) return "duplicate";
1063
+ try {
1064
+ await params.handlePost();
1065
+ await Promise.all(claimedKeys.map((replayKey) => replayGuard.commit(replayKey)));
1066
+ return "processed";
1067
+ } catch (error) {
1068
+ if (error instanceof MattermostRetryableInboundError) claimedKeys.forEach((replayKey) => replayGuard.release(replayKey, { error }));
1069
+ else await Promise.all(claimedKeys.map((replayKey) => replayGuard.commit(replayKey)));
1070
+ throw error;
1071
+ }
1072
+ }
1073
+ function resolveRuntime(opts) {
1074
+ return opts.runtime ?? {
1075
+ log: console.log,
1076
+ error: console.error,
1077
+ exit: (code) => {
1078
+ throw new Error(`exit ${code}`);
1079
+ }
1080
+ };
1081
+ }
1082
+ function isSystemPost(post) {
1083
+ return normalizeOptionalString(post.type) !== void 0;
1084
+ }
1085
+ function channelChatType(kind) {
1086
+ if (kind === "direct") return "direct";
1087
+ if (kind === "group") return "group";
1088
+ return "channel";
1089
+ }
1090
+ function resolveMattermostReplyRootId(params) {
1091
+ if (params.kind === "direct") return;
1092
+ const threadRootId = normalizeOptionalString(params.threadRootId);
1093
+ if (threadRootId) return threadRootId;
1094
+ return normalizeOptionalString(params.replyToId);
1095
+ }
1096
+ function canFinalizeMattermostPreviewInPlace(params) {
1097
+ return resolveMattermostReplyRootId({
1098
+ kind: params.kind,
1099
+ threadRootId: params.threadRootId,
1100
+ replyToId: params.replyToId
1101
+ }) === params.previewRootId?.trim();
1102
+ }
1103
+ function createDisabledMattermostDraftStream() {
1104
+ const noopAsync = async () => {};
1105
+ return {
1106
+ update: () => {},
1107
+ flush: noopAsync,
1108
+ postId: () => void 0,
1109
+ clear: noopAsync,
1110
+ discardPending: noopAsync,
1111
+ seal: noopAsync,
1112
+ stop: noopAsync,
1113
+ forceNewMessage: () => {}
1114
+ };
1115
+ }
1116
+ async function deliverMattermostReplyWithDraftPreview(params) {
1117
+ if (isReasoningReplyPayload(params.payload)) return;
1118
+ await deliverWithFinalizableLivePreviewAdapter({
1119
+ kind: params.info.kind,
1120
+ payload: params.payload,
1121
+ adapter: defineFinalizableLivePreviewAdapter({
1122
+ draft: {
1123
+ flush: params.draftStream.flush,
1124
+ clear: params.draftStream.clear,
1125
+ discardPending: params.draftStream.discardPending,
1126
+ seal: params.draftStream.seal,
1127
+ id: params.draftStream.postId
1128
+ },
1129
+ buildFinalEdit: (payload) => {
1130
+ const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
1131
+ const ttsSupplement = getReplyPayloadTtsSupplement(payload);
1132
+ const previewFinalText = params.resolvePreviewFinalText(payload.text ?? ttsSupplement?.spokenText);
1133
+ if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || !canFinalizeMattermostPreviewInPlace({
1134
+ kind: params.kind,
1135
+ previewRootId: params.effectiveReplyToId,
1136
+ threadRootId: params.effectiveReplyToId,
1137
+ replyToId: payload.replyToId
1138
+ })) return;
1139
+ return { message: previewFinalText };
1140
+ },
1141
+ editFinal: async (previewPostId, edit) => {
1142
+ await updateMattermostPost(params.client, previewPostId, edit);
1143
+ },
1144
+ onPreviewFinalized: () => {
1145
+ params.previewState.finalizedViaPreviewPost = true;
1146
+ params.recordThreadParticipation?.();
1147
+ },
1148
+ buildSupplementalPayload: (payload) => getReplyPayloadTtsSupplement(payload) ? buildTtsSupplementMediaPayload(payload) : void 0,
1149
+ deliverSupplemental: async (payload) => {
1150
+ await params.deliverPayload(payload);
1151
+ },
1152
+ logPreviewEditFailure: (err) => {
1153
+ params.logVerboseMessage(`mattermost preview final edit failed; falling back to normal send (${String(err)})`);
1154
+ }
1155
+ }),
1156
+ deliverNormally: async (payload) => {
1157
+ const supplement = getReplyPayloadTtsSupplement(payload);
1158
+ await params.deliverPayload(supplement && !payload.text?.trim() && supplement.visibleTextAlreadyDelivered !== true ? {
1159
+ ...payload,
1160
+ text: supplement.spokenText
1161
+ } : payload);
1162
+ }
1163
+ });
1164
+ }
1165
+ function formatMattermostFinalDeliveryOutcomeLog(params) {
1166
+ const violation = evaluateMattermostNoVisibleReply({
1167
+ outcome: params.outcome,
1168
+ payload: params.payload
1169
+ });
1170
+ if (violation) return formatMattermostNoVisibleReplyLog({
1171
+ violation,
1172
+ to: params.to,
1173
+ accountId: params.accountId,
1174
+ agentId: params.agentId
1175
+ });
1176
+ if (params.outcome === "text" || params.outcome === "media") return `delivered reply to ${params.to}`;
1177
+ }
1178
+ function resolveMattermostEffectiveReplyToId(params) {
1179
+ if (params.kind === "direct") return;
1180
+ const threadRootId = normalizeOptionalString(params.threadRootId);
1181
+ if (threadRootId) return threadRootId;
1182
+ const postId = normalizeOptionalString(params.postId);
1183
+ if (!postId) return;
1184
+ return params.replyToMode === "all" || params.replyToMode === "first" || params.replyToMode === "batched" ? postId : void 0;
1185
+ }
1186
+ function resolveMattermostThreadSessionContext(params) {
1187
+ const effectiveReplyToId = resolveMattermostEffectiveReplyToId({
1188
+ kind: params.kind,
1189
+ postId: params.postId,
1190
+ replyToMode: params.replyToMode,
1191
+ threadRootId: params.threadRootId
1192
+ });
1193
+ const threadKeys = resolveThreadSessionKeys$1({
1194
+ baseSessionKey: params.baseSessionKey,
1195
+ threadId: effectiveReplyToId,
1196
+ parentSessionKey: effectiveReplyToId ? params.baseSessionKey : void 0
1197
+ });
1198
+ return {
1199
+ effectiveReplyToId,
1200
+ sessionKey: threadKeys.sessionKey,
1201
+ parentSessionKey: threadKeys.parentSessionKey
1202
+ };
1203
+ }
1204
+ function resolveMattermostReactionChannelId(payload) {
1205
+ return normalizeOptionalString(payload.broadcast?.channel_id) ?? normalizeOptionalString(payload.data?.channel_id);
1206
+ }
1207
+ function buildMattermostAttachmentPlaceholder(mediaList) {
1208
+ if (mediaList.length === 0) return "";
1209
+ if (mediaList.length === 1) return `<media:${mediaList[0].kind === "unknown" ? "document" : mediaList[0].kind}>`;
1210
+ const allImages = mediaList.every((media) => media.kind === "image");
1211
+ const label = allImages ? "image" : "file";
1212
+ const suffix = mediaList.length === 1 ? label : `${label}s`;
1213
+ return `${allImages ? "<media:image>" : "<media:document>"} (${mediaList.length} ${suffix})`;
1214
+ }
1215
+ function buildMattermostWsUrl(baseUrl) {
1216
+ const normalized = normalizeMattermostBaseUrl(baseUrl);
1217
+ if (!normalized) throw new Error("Mattermost baseUrl is required");
1218
+ return `${normalized.replace(/^http/i, "ws")}/api/v4/websocket`;
1219
+ }
1220
+ async function monitorMattermostProvider(opts = {}) {
1221
+ const core = getMattermostRuntime();
1222
+ const runtime = resolveRuntime(opts);
1223
+ const cfg = opts.config ?? core.config.current();
1224
+ const account = resolveMattermostAccount({
1225
+ cfg,
1226
+ accountId: opts.accountId
1227
+ });
1228
+ const pairing = createChannelPairingController({
1229
+ core,
1230
+ channel: "mattermost",
1231
+ accountId: account.accountId
1232
+ });
1233
+ const botToken = normalizeOptionalString(opts.botToken) ?? normalizeOptionalString(account.botToken);
1234
+ if (!botToken) throw new Error(`Mattermost bot token missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.botToken or MATTERMOST_BOT_TOKEN for default).`);
1235
+ const baseUrl = normalizeMattermostBaseUrl(opts.baseUrl ?? account.baseUrl);
1236
+ if (!baseUrl) throw new Error(`Mattermost baseUrl missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.baseUrl or MATTERMOST_URL for default).`);
1237
+ const client = createMattermostClient({
1238
+ baseUrl,
1239
+ botToken,
1240
+ allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
1241
+ });
1242
+ let botUser;
1243
+ await runWithReconnect(async () => {
1244
+ botUser = await fetchMattermostMe(client);
1245
+ }, {
1246
+ abortSignal: opts.abortSignal,
1247
+ jitterRatio: .2,
1248
+ shouldReconnect: ({ outcome }) => outcome === "rejected",
1249
+ onError: (err) => {
1250
+ runtime.error?.(`mattermost: API auth failed: ${String(err)}`);
1251
+ opts.statusSink?.({
1252
+ lastError: String(err),
1253
+ connected: false
1254
+ });
1255
+ },
1256
+ onReconnect: (delayMs) => {
1257
+ runtime.log?.(`mattermost: API not accessible, retrying in ${Math.round(delayMs / 1e3)}s`);
1258
+ }
1259
+ });
1260
+ if (opts.abortSignal?.aborted) return;
1261
+ const botUserId = botUser.id;
1262
+ const botUsername = normalizeOptionalString(botUser.username);
1263
+ runtime.log?.(`mattermost connected as ${botUsername ? `@${botUsername}` : botUserId}`);
1264
+ await registerMattermostMonitorSlashCommands({
1265
+ client,
1266
+ cfg,
1267
+ runtime,
1268
+ account,
1269
+ baseUrl,
1270
+ botUserId
1271
+ });
1272
+ const slashEnabled = getSlashCommandState(account.accountId) != null;
1273
+ setInteractionSecret(account.accountId, botToken);
1274
+ const interactionPath = resolveInteractionCallbackPath(account.accountId);
1275
+ const callbackUrl = computeInteractionCallbackUrl(account.accountId, {
1276
+ gateway: cfg.gateway,
1277
+ interactions: account.config.interactions
1278
+ });
1279
+ setInteractionCallbackUrl(account.accountId, callbackUrl);
1280
+ const allowedInteractionSourceIps = normalizeInteractionSourceIps(account.config.interactions?.allowedSourceIps);
1281
+ try {
1282
+ const mmHost = new URL(baseUrl).hostname;
1283
+ const callbackHost = new URL(callbackUrl).hostname;
1284
+ if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) runtime.error?.(`mattermost: interactions callbackUrl resolved to ${callbackUrl} (loopback) while baseUrl is ${baseUrl}. This MAY be unreachable depending on your deployment. If button clicks don't work, set channels.mattermost.interactions.callbackBaseUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
1285
+ if (!isLoopbackHost(callbackHost) && allowedInteractionSourceIps.length === 0) runtime.error?.(`mattermost: interactions callbackUrl resolved to ${callbackUrl} without channels.mattermost.interactions.allowedSourceIps. For safety, non-loopback callback sources will be rejected until you allowlist the Mattermost server or trusted ingress IPs.`);
1286
+ } catch {}
1287
+ const effectiveInteractionSourceIps = allowedInteractionSourceIps.length > 0 ? allowedInteractionSourceIps : ["127.0.0.1", "::1"];
1288
+ const unregisterInteractions = registerPluginHttpRoute({
1289
+ path: interactionPath,
1290
+ fallbackPath: "/mattermost/interactions/default",
1291
+ auth: "plugin",
1292
+ handler: createMattermostInteractionHandler({
1293
+ client,
1294
+ botUserId,
1295
+ accountId: account.accountId,
1296
+ allowedSourceIps: effectiveInteractionSourceIps,
1297
+ trustedProxies: cfg.gateway?.trustedProxies,
1298
+ allowRealIpFallback: cfg.gateway?.allowRealIpFallback === true,
1299
+ handleInteraction: handleModelPickerInteraction,
1300
+ authorizeButtonClick: async ({ payload, post }) => {
1301
+ const channelInfo = await resolveChannelInfo(payload.channel_id);
1302
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1303
+ cfg,
1304
+ surface: "mattermost"
1305
+ });
1306
+ const decision = await authorizeMattermostCommandInvocation({
1307
+ account,
1308
+ cfg,
1309
+ senderId: payload.user_id,
1310
+ senderName: payload.user_name ?? "",
1311
+ channelId: payload.channel_id,
1312
+ channelInfo,
1313
+ readStoreAllowFrom: pairing.readAllowFromStore,
1314
+ allowTextCommands,
1315
+ hasControlCommand: false
1316
+ });
1317
+ if (decision.ok) return { ok: true };
1318
+ return {
1319
+ ok: false,
1320
+ response: {
1321
+ update: {
1322
+ message: post.message ?? "",
1323
+ props: post.props ?? void 0
1324
+ },
1325
+ ephemeral_text: `OpenClaw ignored this action for ${decision.roomLabel}.`
1326
+ }
1327
+ };
1328
+ },
1329
+ resolveSessionKey: async ({ channelId, userId, post }) => {
1330
+ const channelInfo = await resolveChannelInfo(channelId);
1331
+ if (!channelInfo?.type) {
1332
+ logVerboseMessage(`mattermost: drop interaction session event (cannot resolve channel type for ${channelId})`);
1333
+ throw new Error("Mattermost channel type could not be resolved");
1334
+ }
1335
+ const kind = mapMattermostChannelTypeToChatType(channelInfo.type);
1336
+ const teamId = channelInfo?.team_id ?? void 0;
1337
+ const route = core.channel.routing.resolveAgentRoute({
1338
+ cfg,
1339
+ channel: "mattermost",
1340
+ accountId: account.accountId,
1341
+ teamId,
1342
+ peer: {
1343
+ kind,
1344
+ id: kind === "direct" ? userId : channelId
1345
+ }
1346
+ });
1347
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
1348
+ return resolveMattermostThreadSessionContext({
1349
+ baseSessionKey: route.sessionKey,
1350
+ kind,
1351
+ postId: post.id || void 0,
1352
+ replyToMode,
1353
+ threadRootId: post.root_id
1354
+ }).sessionKey;
1355
+ },
1356
+ dispatchButtonClick: async (optsLocal) => {
1357
+ const channelInfo = await resolveChannelInfo(optsLocal.channelId);
1358
+ if (!channelInfo?.type) {
1359
+ logVerboseMessage(`mattermost: drop interaction dispatch (cannot resolve channel type for ${optsLocal.channelId})`);
1360
+ return;
1361
+ }
1362
+ const kind = mapMattermostChannelTypeToChatType(channelInfo.type);
1363
+ const chatType = channelChatType(kind);
1364
+ const teamId = channelInfo?.team_id ?? void 0;
1365
+ const channelName = channelInfo?.name ?? void 0;
1366
+ const channelDisplay = channelInfo?.display_name ?? channelName ?? optsLocal.channelId;
1367
+ const route = core.channel.routing.resolveAgentRoute({
1368
+ cfg,
1369
+ channel: "mattermost",
1370
+ accountId: account.accountId,
1371
+ teamId,
1372
+ peer: {
1373
+ kind,
1374
+ id: kind === "direct" ? optsLocal.userId : optsLocal.channelId
1375
+ }
1376
+ });
1377
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
1378
+ const threadContext = resolveMattermostThreadSessionContext({
1379
+ baseSessionKey: route.sessionKey,
1380
+ kind,
1381
+ postId: optsLocal.post.id || optsLocal.postId,
1382
+ replyToMode,
1383
+ threadRootId: optsLocal.post.root_id
1384
+ });
1385
+ const to = kind === "direct" ? `user:${optsLocal.userId}` : `channel:${optsLocal.channelId}`;
1386
+ const bodyText = `[Button click: user @${optsLocal.userName} selected "${optsLocal.actionName}"]`;
1387
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
1388
+ Body: bodyText,
1389
+ BodyForAgent: bodyText,
1390
+ RawBody: bodyText,
1391
+ CommandBody: bodyText,
1392
+ From: kind === "direct" ? `mattermost:${optsLocal.userId}` : kind === "group" ? `mattermost:group:${optsLocal.channelId}` : `mattermost:channel:${optsLocal.channelId}`,
1393
+ To: to,
1394
+ SessionKey: threadContext.sessionKey,
1395
+ ParentSessionKey: threadContext.parentSessionKey,
1396
+ AccountId: route.accountId,
1397
+ ChatType: chatType,
1398
+ ConversationLabel: `mattermost:${optsLocal.userName}`,
1399
+ GroupSubject: kind !== "direct" ? channelDisplay : void 0,
1400
+ GroupChannel: channelName ? `#${channelName}` : void 0,
1401
+ GroupSpace: teamId,
1402
+ SenderName: optsLocal.userName,
1403
+ SenderId: optsLocal.userId,
1404
+ Provider: "mattermost",
1405
+ Surface: "mattermost",
1406
+ MessageSid: `interaction:${optsLocal.postId}:${optsLocal.actionId}`,
1407
+ ReplyToId: threadContext.effectiveReplyToId,
1408
+ MessageThreadId: threadContext.effectiveReplyToId,
1409
+ WasMentioned: true,
1410
+ CommandAuthorized: false,
1411
+ OriginatingChannel: "mattermost",
1412
+ OriginatingTo: to
1413
+ });
1414
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
1415
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
1416
+ cfg,
1417
+ channel: "mattermost",
1418
+ accountId: account.accountId
1419
+ });
1420
+ const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
1421
+ cfg,
1422
+ agentId: route.agentId,
1423
+ channel: "mattermost",
1424
+ accountId: account.accountId,
1425
+ typing: {
1426
+ start: () => sendTypingIndicator(optsLocal.channelId, threadContext.effectiveReplyToId),
1427
+ onStartError: (err) => {
1428
+ logTypingFailure({
1429
+ log: (message) => logger.debug?.(message),
1430
+ channel: "mattermost",
1431
+ target: optsLocal.channelId,
1432
+ error: err
1433
+ });
1434
+ }
1435
+ }
1436
+ });
1437
+ const deliveryBarrier = createMattermostReplyDeliveryBarrier({
1438
+ isDirect: kind === "direct",
1439
+ dmRetryOptions: account.config.dmChannelRetry
1440
+ });
1441
+ const { dispatcher, replyOptions, markDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
1442
+ ...replyPipeline,
1443
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1444
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
1445
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId),
1446
+ deliver: async (payload) => {
1447
+ await deliverMattermostReplyPayload({
1448
+ core,
1449
+ cfg,
1450
+ payload,
1451
+ to,
1452
+ accountId: account.accountId,
1453
+ agentId: route.agentId,
1454
+ replyToId: resolveMattermostReplyRootId({
1455
+ kind,
1456
+ threadRootId: threadContext.effectiveReplyToId,
1457
+ replyToId: payload.replyToId
1458
+ }),
1459
+ textLimit,
1460
+ tableMode,
1461
+ sendMessage: sendMessageMattermost,
1462
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1463
+ });
1464
+ runtime.log?.(`delivered button-click reply to ${to}`);
1465
+ },
1466
+ onError: (err, info) => {
1467
+ runtime.error?.(`mattermost button-click ${info.kind} reply failed: ${String(err)}`);
1468
+ },
1469
+ onReplyStart: typingCallbacks?.onReplyStart
1470
+ });
1471
+ await core.channel.reply.dispatchReplyFromConfig({
1472
+ ctx: ctxPayload,
1473
+ cfg,
1474
+ dispatcher,
1475
+ replyOptions: {
1476
+ ...replyOptions,
1477
+ disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1478
+ onModelSelected
1479
+ }
1480
+ });
1481
+ markDispatchIdle();
1482
+ },
1483
+ log: (msg) => runtime.log?.(msg)
1484
+ }),
1485
+ pluginId: "mattermost",
1486
+ source: "mattermost-interactions",
1487
+ accountId: account.accountId,
1488
+ log: (msg) => runtime.log?.(msg)
1489
+ });
1490
+ const logger = core.logging.getChildLogger({ module: "mattermost" });
1491
+ const logVerboseMessage = (message) => {
1492
+ if (!core.logging.shouldLogVerbose()) return;
1493
+ logger.debug?.(message);
1494
+ };
1495
+ const mediaMaxBytes = resolveChannelMediaMaxBytes({
1496
+ cfg,
1497
+ resolveChannelLimitMb: () => void 0,
1498
+ accountId: account.accountId
1499
+ }) ?? 8 * 1024 * 1024;
1500
+ const historyLimit = Math.max(0, cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT);
1501
+ const channelHistories = /* @__PURE__ */ new Map();
1502
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
1503
+ const dmPolicy = account.config.dmPolicy ?? "pairing";
1504
+ const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
1505
+ providerConfigPresent: cfg.channels?.mattermost !== void 0,
1506
+ groupPolicy: account.config.groupPolicy,
1507
+ defaultGroupPolicy
1508
+ });
1509
+ warnMissingProviderGroupPolicyFallbackOnce({
1510
+ providerMissingFallbackApplied,
1511
+ providerKey: "mattermost",
1512
+ accountId: account.accountId,
1513
+ log: (message) => logVerboseMessage(message)
1514
+ });
1515
+ const { resolveMattermostMedia, sendTypingIndicator, resolveChannelInfo, resolveUserInfo, updateModelPickerPost } = createMattermostMonitorResources({
1516
+ accountId: account.accountId,
1517
+ callbackUrl,
1518
+ client,
1519
+ logger: { debug: (message) => logger.debug?.(String(message)) },
1520
+ mediaMaxBytes,
1521
+ saveRemoteMedia: (params) => core.channel.media.saveRemoteMedia(params),
1522
+ mediaKindFromMime: (contentType) => core.media.mediaKindFromMime(contentType)
1523
+ });
1524
+ const runModelPickerCommand = async (params) => {
1525
+ const to = params.kind === "direct" ? `user:${params.senderId}` : `channel:${params.channelId}`;
1526
+ const fromLabel = params.kind === "direct" ? `Mattermost DM from ${params.senderName}` : `Mattermost message in ${params.roomLabel} from ${params.senderName}`;
1527
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
1528
+ Body: params.commandText,
1529
+ BodyForAgent: params.commandText,
1530
+ RawBody: params.commandText,
1531
+ CommandBody: params.commandText,
1532
+ From: params.kind === "direct" ? `mattermost:${params.senderId}` : params.kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`,
1533
+ To: to,
1534
+ SessionKey: params.sessionKey,
1535
+ ParentSessionKey: params.parentSessionKey,
1536
+ AccountId: params.route.accountId,
1537
+ ChatType: params.chatType,
1538
+ ConversationLabel: fromLabel,
1539
+ GroupSubject: params.kind !== "direct" ? params.channelDisplay || params.roomLabel : void 0,
1540
+ GroupChannel: params.channelName ? `#${params.channelName}` : void 0,
1541
+ GroupSpace: params.teamId,
1542
+ SenderName: params.senderName,
1543
+ SenderId: params.senderId,
1544
+ Provider: "mattermost",
1545
+ Surface: "mattermost",
1546
+ MessageSid: params.messageSid ?? `interaction:${params.postId}:${Date.now()}`,
1547
+ ReplyToId: params.effectiveReplyToId,
1548
+ MessageThreadId: params.effectiveReplyToId,
1549
+ Timestamp: Date.now(),
1550
+ WasMentioned: true,
1551
+ CommandAuthorized: params.commandAuthorized,
1552
+ CommandSource: "native",
1553
+ OriginatingChannel: "mattermost",
1554
+ OriginatingTo: to
1555
+ });
1556
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
1557
+ cfg,
1558
+ channel: "mattermost",
1559
+ accountId: account.accountId
1560
+ });
1561
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
1562
+ const shouldDeliverReplies = params.deliverReplies === true;
1563
+ const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
1564
+ cfg,
1565
+ agentId: params.route.agentId,
1566
+ channel: "mattermost",
1567
+ accountId: account.accountId,
1568
+ typing: shouldDeliverReplies ? {
1569
+ start: () => sendTypingIndicator(params.channelId, params.effectiveReplyToId),
1570
+ onStartError: (err) => {
1571
+ logTypingFailure({
1572
+ log: (message) => logger.debug?.(message),
1573
+ channel: "mattermost",
1574
+ target: params.channelId,
1575
+ error: err
1576
+ });
1577
+ }
1578
+ } : void 0
1579
+ });
1580
+ const capturedTexts = [];
1581
+ const deliveryBarrier = createMattermostReplyDeliveryBarrier({
1582
+ isDirect: params.kind === "direct",
1583
+ dmRetryOptions: account.config.dmChannelRetry
1584
+ });
1585
+ const { dispatcher, replyOptions, markDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
1586
+ ...replyPipeline,
1587
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1588
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
1589
+ deliver: async (payload) => {
1590
+ const trimmedPayload = {
1591
+ ...payload,
1592
+ text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
1593
+ };
1594
+ if (!shouldDeliverReplies) {
1595
+ if (trimmedPayload.text) capturedTexts.push(trimmedPayload.text);
1596
+ return;
1597
+ }
1598
+ await deliverMattermostReplyPayload({
1599
+ core,
1600
+ cfg,
1601
+ payload: trimmedPayload,
1602
+ to,
1603
+ accountId: account.accountId,
1604
+ agentId: params.route.agentId,
1605
+ replyToId: resolveMattermostReplyRootId({
1606
+ kind: params.kind,
1607
+ threadRootId: params.effectiveReplyToId,
1608
+ replyToId: trimmedPayload.replyToId
1609
+ }),
1610
+ textLimit,
1611
+ tableMode: "off",
1612
+ sendMessage: sendMessageMattermost,
1613
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1614
+ });
1615
+ },
1616
+ onError: (err, info) => {
1617
+ runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
1618
+ },
1619
+ onReplyStart: typingCallbacks?.onReplyStart
1620
+ });
1621
+ await core.channel.reply.withReplyDispatcher({
1622
+ dispatcher,
1623
+ onSettled: () => {
1624
+ markDispatchIdle();
1625
+ },
1626
+ run: () => core.channel.reply.dispatchReplyFromConfig({
1627
+ ctx: ctxPayload,
1628
+ cfg,
1629
+ dispatcher,
1630
+ replyOptions: {
1631
+ ...replyOptions,
1632
+ disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1633
+ onModelSelected
1634
+ }
1635
+ })
1636
+ });
1637
+ return capturedTexts.join("\n\n").trim();
1638
+ };
1639
+ async function handleModelPickerInteraction(params) {
1640
+ const pickerState = parseMattermostModelPickerContext(params.context);
1641
+ if (!pickerState) return null;
1642
+ if (pickerState.ownerUserId !== params.payload.user_id) return { ephemeral_text: "Only the person who opened this picker can use it." };
1643
+ const channelInfo = await resolveChannelInfo(params.payload.channel_id);
1644
+ const pickerCommandText = pickerState.action === "select" ? `/model ${pickerState.provider}/${pickerState.model}` : pickerState.action === "list" ? `/models ${pickerState.provider}` : "/models";
1645
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1646
+ cfg,
1647
+ surface: "mattermost"
1648
+ });
1649
+ const hasControlCommand = core.channel.text.hasControlCommand(pickerCommandText, cfg);
1650
+ const auth = await authorizeMattermostCommandInvocation({
1651
+ account,
1652
+ cfg,
1653
+ senderId: params.payload.user_id,
1654
+ senderName: params.userName,
1655
+ channelId: params.payload.channel_id,
1656
+ channelInfo,
1657
+ readStoreAllowFrom: pairing.readAllowFromStore,
1658
+ allowTextCommands,
1659
+ hasControlCommand
1660
+ });
1661
+ if (!auth.ok) {
1662
+ if (auth.denyReason === "dm-pairing") {
1663
+ const { code } = await pairing.upsertPairingRequest({
1664
+ id: params.payload.user_id,
1665
+ meta: { name: params.userName }
1666
+ });
1667
+ return { ephemeral_text: core.channel.pairing.buildPairingReply({
1668
+ channel: "mattermost",
1669
+ idLine: `Your Mattermost user id: ${params.payload.user_id}`,
1670
+ code
1671
+ }) };
1672
+ }
1673
+ return { ephemeral_text: auth.denyReason === "unknown-channel" ? "Temporary error: unable to determine channel type. Please try again." : auth.denyReason === "dm-disabled" ? "This bot is not accepting direct messages." : auth.denyReason === "channels-disabled" ? "Model picker actions are disabled in channels." : auth.denyReason === "channel-no-allowlist" ? "Model picker actions are not configured for this channel." : "Unauthorized." };
1674
+ }
1675
+ const kind = auth.kind;
1676
+ const chatType = auth.chatType;
1677
+ const teamId = auth.channelInfo.team_id ?? params.payload.team_id ?? void 0;
1678
+ const channelName = auth.channelName || void 0;
1679
+ const channelDisplay = auth.channelDisplay || auth.channelName || params.payload.channel_id;
1680
+ const roomLabel = auth.roomLabel;
1681
+ const route = core.channel.routing.resolveAgentRoute({
1682
+ cfg,
1683
+ channel: "mattermost",
1684
+ accountId: account.accountId,
1685
+ teamId,
1686
+ peer: {
1687
+ kind,
1688
+ id: kind === "direct" ? params.payload.user_id : params.payload.channel_id
1689
+ }
1690
+ });
1691
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
1692
+ const threadContext = resolveMattermostThreadSessionContext({
1693
+ baseSessionKey: route.sessionKey,
1694
+ kind,
1695
+ postId: params.post.id || params.payload.post_id,
1696
+ replyToMode,
1697
+ threadRootId: params.post.root_id
1698
+ });
1699
+ const modelSessionRoute = {
1700
+ agentId: route.agentId,
1701
+ sessionKey: threadContext.sessionKey
1702
+ };
1703
+ const data = await buildModelsProviderData(cfg, route.agentId);
1704
+ if (data.providers.length === 0) return await updateModelPickerPost({
1705
+ channelId: params.payload.channel_id,
1706
+ postId: params.payload.post_id,
1707
+ message: "No models available."
1708
+ });
1709
+ if (pickerState.action === "providers" || pickerState.action === "back") {
1710
+ const currentModel = resolveMattermostModelPickerCurrentModel({
1711
+ cfg,
1712
+ route: modelSessionRoute,
1713
+ data
1714
+ });
1715
+ const view = renderMattermostProviderPickerView({
1716
+ ownerUserId: pickerState.ownerUserId,
1717
+ data,
1718
+ currentModel
1719
+ });
1720
+ return await updateModelPickerPost({
1721
+ channelId: params.payload.channel_id,
1722
+ postId: params.payload.post_id,
1723
+ message: view.text,
1724
+ buttons: view.buttons
1725
+ });
1726
+ }
1727
+ if (pickerState.action === "list") {
1728
+ const currentModel = resolveMattermostModelPickerCurrentModel({
1729
+ cfg,
1730
+ route: modelSessionRoute,
1731
+ data
1732
+ });
1733
+ const view = renderMattermostModelsPickerView({
1734
+ ownerUserId: pickerState.ownerUserId,
1735
+ data,
1736
+ provider: pickerState.provider,
1737
+ page: pickerState.page,
1738
+ currentModel
1739
+ });
1740
+ return await updateModelPickerPost({
1741
+ channelId: params.payload.channel_id,
1742
+ postId: params.payload.post_id,
1743
+ message: view.text,
1744
+ buttons: view.buttons
1745
+ });
1746
+ }
1747
+ const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
1748
+ if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
1749
+ (async () => {
1750
+ try {
1751
+ await runModelPickerCommand({
1752
+ commandText: `/model ${targetModelRef}`,
1753
+ commandAuthorized: auth.commandAuthorized,
1754
+ route,
1755
+ sessionKey: threadContext.sessionKey,
1756
+ parentSessionKey: threadContext.parentSessionKey,
1757
+ channelId: params.payload.channel_id,
1758
+ senderId: params.payload.user_id,
1759
+ senderName: params.userName,
1760
+ kind,
1761
+ chatType,
1762
+ channelName,
1763
+ channelDisplay,
1764
+ roomLabel,
1765
+ teamId,
1766
+ postId: params.payload.post_id,
1767
+ messageSid: buildMattermostModelPickerSelectMessageSid({
1768
+ postId: params.payload.post_id,
1769
+ provider: pickerState.provider,
1770
+ model: pickerState.model
1771
+ }),
1772
+ effectiveReplyToId: threadContext.effectiveReplyToId,
1773
+ deliverReplies: true
1774
+ });
1775
+ const updatedModel = resolveMattermostModelPickerCurrentModel({
1776
+ cfg,
1777
+ route: modelSessionRoute,
1778
+ data,
1779
+ skipCache: true
1780
+ });
1781
+ const view = renderMattermostModelsPickerView({
1782
+ ownerUserId: pickerState.ownerUserId,
1783
+ data,
1784
+ provider: pickerState.provider,
1785
+ page: pickerState.page,
1786
+ currentModel: updatedModel
1787
+ });
1788
+ await updateModelPickerPost({
1789
+ channelId: params.payload.channel_id,
1790
+ postId: params.payload.post_id,
1791
+ message: view.text,
1792
+ buttons: view.buttons
1793
+ });
1794
+ } catch (err) {
1795
+ runtime.error?.(`mattermost model picker select failed: ${String(err)}`);
1796
+ }
1797
+ })();
1798
+ return {};
1799
+ }
1800
+ const handlePost = async (post, payload, messageIds) => {
1801
+ const channelId = post.channel_id ?? payload.data?.channel_id ?? payload.broadcast?.channel_id;
1802
+ if (!channelId) {
1803
+ logVerboseMessage("mattermost: drop post (missing channel id)");
1804
+ return;
1805
+ }
1806
+ const allMessageIds = messageIds?.length ? messageIds : post.id ? [post.id] : [];
1807
+ if (allMessageIds.length === 0) {
1808
+ logVerboseMessage("mattermost: drop post (missing message id)");
1809
+ return;
1810
+ }
1811
+ if (await processMattermostReplayGuardedPost({
1812
+ accountId: account.accountId,
1813
+ messageIds: allMessageIds,
1814
+ handlePost: async () => {
1815
+ const senderId = post.user_id ?? payload.broadcast?.user_id;
1816
+ if (!senderId) {
1817
+ logVerboseMessage("mattermost: drop post (missing sender id)");
1818
+ return;
1819
+ }
1820
+ if (senderId === botUserId) {
1821
+ logVerboseMessage(`mattermost: drop post (self sender=${senderId})`);
1822
+ return;
1823
+ }
1824
+ if (isSystemPost(post)) {
1825
+ logVerboseMessage(`mattermost: drop post (system post type=${post.type ?? "unknown"})`);
1826
+ return;
1827
+ }
1828
+ const channelInfo = await resolveChannelInfo(channelId);
1829
+ const channelType = normalizeOptionalString(channelInfo?.type) ?? normalizeOptionalString(payload.data?.channel_type);
1830
+ if (!channelType) {
1831
+ logVerboseMessage(`mattermost: drop post (cannot resolve channel type for ${channelId})`);
1832
+ return;
1833
+ }
1834
+ const kind = resolveMattermostTrustedChatKind({ channelType });
1835
+ const chatType = channelChatType(kind);
1836
+ const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
1837
+ const rawPostText = typeof post.message === "string" ? post.message : "";
1838
+ const rawText = normalizeOptionalString(rawPostText) ?? "";
1839
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1840
+ cfg,
1841
+ surface: "mattermost"
1842
+ });
1843
+ const isControlCommand = allowTextCommands && core.channel.commands.isControlCommandMessage(rawText, cfg);
1844
+ const accessDecision = await resolveMattermostMonitorInboundAccess({
1845
+ account,
1846
+ cfg,
1847
+ senderId,
1848
+ senderName,
1849
+ channelId,
1850
+ kind,
1851
+ groupPolicy,
1852
+ readStoreAllowFrom: pairing.readAllowFromStore,
1853
+ allowTextCommands,
1854
+ hasControlCommand: isControlCommand,
1855
+ eventKind: "message",
1856
+ mayPair: true
1857
+ });
1858
+ const commandAuthorized = accessDecision.commandAccess.authorized;
1859
+ if (accessDecision.ingress.decision !== "allow") {
1860
+ if (kind === "direct") {
1861
+ if (accessDecision.ingress.reasonCode === "dm_policy_disabled") {
1862
+ logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
1863
+ return;
1864
+ }
1865
+ if (accessDecision.ingress.decision === "pairing") {
1866
+ const { code, created } = await pairing.upsertPairingRequest({
1867
+ id: senderId,
1868
+ meta: { name: senderName }
1869
+ });
1870
+ logVerboseMessage(`mattermost: pairing request sender=${senderId} created=${created}`);
1871
+ if (created) try {
1872
+ await sendMessageMattermost(`user:${senderId}`, core.channel.pairing.buildPairingReply({
1873
+ channel: "mattermost",
1874
+ idLine: `Your Mattermost user id: ${senderId}`,
1875
+ code
1876
+ }), {
1877
+ cfg,
1878
+ accountId: account.accountId
1879
+ });
1880
+ opts.statusSink?.({ lastOutboundAt: Date.now() });
1881
+ } catch (err) {
1882
+ logVerboseMessage(`mattermost: pairing reply failed for ${senderId}: ${String(err)}`);
1883
+ }
1884
+ return;
1885
+ }
1886
+ logVerboseMessage(formatMattermostDirectMessageDropLog({
1887
+ senderId,
1888
+ dmPolicy,
1889
+ reasonCode: accessDecision.senderAccess.reasonCode
1890
+ }));
1891
+ return;
1892
+ }
1893
+ if (accessDecision.ingress.reasonCode === "group_policy_disabled") {
1894
+ logVerboseMessage("mattermost: drop group message (groupPolicy=disabled)");
1895
+ return;
1896
+ }
1897
+ if (accessDecision.ingress.reasonCode === "group_policy_empty_allowlist") {
1898
+ logVerboseMessage("mattermost: drop group message (no group allowlist)");
1899
+ return;
1900
+ }
1901
+ if (accessDecision.ingress.reasonCode === "group_policy_not_allowlisted") {
1902
+ logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
1903
+ return;
1904
+ }
1905
+ logVerboseMessage(`mattermost: drop group message (groupPolicy=${groupPolicy} reason=${accessDecision.senderAccess.reasonCode})`);
1906
+ return;
1907
+ }
1908
+ if (kind !== "direct" && accessDecision.commandAccess.shouldBlockControlCommand) {
1909
+ logInboundDrop({
1910
+ log: logVerboseMessage,
1911
+ channel: "mattermost",
1912
+ reason: "control command (unauthorized)",
1913
+ target: senderId
1914
+ });
1915
+ return;
1916
+ }
1917
+ const teamId = payload.data?.team_id ?? channelInfo?.team_id ?? void 0;
1918
+ const channelName = payload.data?.channel_name ?? channelInfo?.name ?? "";
1919
+ const channelDisplay = payload.data?.channel_display_name ?? channelInfo?.display_name ?? channelName;
1920
+ const roomLabel = channelName ? `#${channelName}` : channelDisplay || `#${channelId}`;
1921
+ const route = core.channel.routing.resolveAgentRoute({
1922
+ cfg,
1923
+ channel: "mattermost",
1924
+ accountId: account.accountId,
1925
+ teamId,
1926
+ peer: {
1927
+ kind,
1928
+ id: kind === "direct" ? senderId : channelId
1929
+ }
1930
+ });
1931
+ const baseSessionKey = route.sessionKey;
1932
+ const threadRootId = normalizeOptionalString(post.root_id);
1933
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
1934
+ const { effectiveReplyToId, sessionKey, parentSessionKey } = resolveMattermostThreadSessionContext({
1935
+ baseSessionKey,
1936
+ kind,
1937
+ postId: post.id,
1938
+ replyToMode,
1939
+ threadRootId
1940
+ });
1941
+ const historyKey = kind === "direct" ? null : sessionKey;
1942
+ const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
1943
+ const wasMentioned = kind !== "direct" && ((botUsername ? normalizeLowercaseStringOrEmpty(rawText).includes(`@${normalizeLowercaseStringOrEmpty(botUsername)}`) : false) || core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
1944
+ const pendingBody = rawText || (post.file_ids?.length ? `[Mattermost ${post.file_ids.length === 1 ? "file" : "files"}]` : "");
1945
+ const pendingSender = senderName;
1946
+ const recordPendingHistory = () => {
1947
+ const trimmed = pendingBody.trim();
1948
+ createChannelHistoryWindow({ historyMap: channelHistories }).record({
1949
+ limit: historyLimit,
1950
+ historyKey: historyKey ?? "",
1951
+ entry: historyKey && trimmed ? {
1952
+ sender: pendingSender,
1953
+ body: trimmed,
1954
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
1955
+ messageId: post.id ?? void 0
1956
+ } : null
1957
+ });
1958
+ };
1959
+ const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
1960
+ const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
1961
+ const oncharResult = oncharEnabled ? stripOncharPrefix(rawText, oncharPrefixes) : {
1962
+ triggered: false,
1963
+ stripped: rawText
1964
+ };
1965
+ const oncharTriggered = oncharResult.triggered;
1966
+ const canDetectMention = Boolean(botUsername) || mentionRegexes.length > 0;
1967
+ const threadAlreadyEngaged = kind !== "direct" && effectiveReplyToId ? await hasMattermostThreadParticipationWithPersistence({
1968
+ accountId: account.accountId,
1969
+ channelId,
1970
+ threadRootId: effectiveReplyToId
1971
+ }) : false;
1972
+ const mentionDecision = evaluateMattermostMentionGate({
1973
+ kind,
1974
+ cfg,
1975
+ accountId: account.accountId,
1976
+ channelId,
1977
+ threadRootId,
1978
+ requireMentionOverride: account.requireMention,
1979
+ resolveRequireMention: core.channel.groups.resolveRequireMention,
1980
+ wasMentioned,
1981
+ threadAlreadyEngaged,
1982
+ isControlCommand,
1983
+ commandAuthorized,
1984
+ oncharEnabled,
1985
+ oncharTriggered,
1986
+ canDetectMention
1987
+ });
1988
+ const { shouldRequireMention, shouldBypassMention } = mentionDecision;
1989
+ if (mentionDecision.dropReason === "onchar-not-triggered") {
1990
+ logVerboseMessage(`mattermost: drop group message (onchar not triggered channel=${channelId} sender=${senderId})`);
1991
+ recordPendingHistory();
1992
+ return;
1993
+ }
1994
+ if (mentionDecision.dropReason === "missing-mention") {
1995
+ logVerboseMessage(`mattermost: drop group message (missing mention channel=${channelId} sender=${senderId} requireMention=${shouldRequireMention} bypass=${shouldBypassMention} canDetectMention=${canDetectMention})`);
1996
+ recordPendingHistory();
1997
+ return;
1998
+ }
1999
+ const mediaList = await resolveMattermostMedia(post.file_ids);
2000
+ const mediaPlaceholder = buildMattermostAttachmentPlaceholder(mediaList);
2001
+ const bodyText = normalizeMention([oncharTriggered ? oncharResult.stripped : rawText, mediaPlaceholder].filter(Boolean).join("\n").trim(), botUsername);
2002
+ if (shouldDropEmptyMattermostBody({
2003
+ bodyText,
2004
+ rawText: rawPostText,
2005
+ botUsername
2006
+ })) {
2007
+ logVerboseMessage(`mattermost: drop message (empty body after normalization channel=${channelId} sender=${senderId} wasMentioned=${wasMentioned})`);
2008
+ return;
2009
+ }
2010
+ const bodyForAgent = bodyText || rawText.trim();
2011
+ core.channel.activity.record({
2012
+ channel: "mattermost",
2013
+ accountId: account.accountId,
2014
+ direction: "inbound"
2015
+ });
2016
+ const fromLabel = formatInboundFromLabel$1({
2017
+ isGroup: kind !== "direct",
2018
+ groupLabel: channelDisplay || roomLabel,
2019
+ groupId: channelId,
2020
+ groupFallback: roomLabel || "Channel",
2021
+ directLabel: senderName,
2022
+ directId: senderId
2023
+ });
2024
+ const textWithId = `${bodyText}\n[mattermost message id: ${post.id ?? "unknown"} channel: ${channelId}]`;
2025
+ let combinedBody = core.channel.reply.formatInboundEnvelope({
2026
+ channel: "Mattermost",
2027
+ from: fromLabel,
2028
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2029
+ body: textWithId,
2030
+ chatType,
2031
+ sender: {
2032
+ name: senderName,
2033
+ id: senderId
2034
+ }
2035
+ });
2036
+ if (historyKey) combinedBody = createChannelHistoryWindow({ historyMap: channelHistories }).buildPendingContext({
2037
+ historyKey,
2038
+ limit: historyLimit,
2039
+ currentMessage: combinedBody,
2040
+ formatEntry: (entry) => core.channel.reply.formatInboundEnvelope({
2041
+ channel: "Mattermost",
2042
+ from: fromLabel,
2043
+ timestamp: entry.timestamp,
2044
+ body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} channel:${channelId}]` : ""}`,
2045
+ chatType,
2046
+ senderLabel: entry.sender
2047
+ })
2048
+ });
2049
+ const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
2050
+ const mediaPayload = buildAgentMediaPayload(mediaList);
2051
+ const commandBody = rawText.trim();
2052
+ const inboundHistory = historyKey && historyLimit > 0 ? createChannelHistoryWindow({ historyMap: channelHistories }).buildInboundHistory({
2053
+ historyKey,
2054
+ limit: historyLimit
2055
+ }) : void 0;
2056
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
2057
+ Body: combinedBody,
2058
+ BodyForAgent: bodyForAgent,
2059
+ InboundHistory: inboundHistory,
2060
+ RawBody: bodyText,
2061
+ CommandBody: commandBody,
2062
+ BodyForCommands: commandBody,
2063
+ From: kind === "direct" ? `mattermost:${senderId}` : kind === "group" ? `mattermost:group:${channelId}` : `mattermost:channel:${channelId}`,
2064
+ To: to,
2065
+ SessionKey: sessionKey,
2066
+ ParentSessionKey: parentSessionKey,
2067
+ AccountId: route.accountId,
2068
+ ChatType: chatType,
2069
+ ConversationLabel: fromLabel,
2070
+ GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
2071
+ GroupChannel: channelName ? `#${channelName}` : void 0,
2072
+ GroupSpace: teamId,
2073
+ SenderName: senderName,
2074
+ SenderId: senderId,
2075
+ Provider: "mattermost",
2076
+ Surface: "mattermost",
2077
+ MessageSid: post.id ?? void 0,
2078
+ MessageSids: allMessageIds.length > 1 ? allMessageIds : void 0,
2079
+ MessageSidFirst: allMessageIds.length > 1 ? allMessageIds[0] : void 0,
2080
+ MessageSidLast: allMessageIds.length > 1 ? allMessageIds[allMessageIds.length - 1] : void 0,
2081
+ ReplyToId: effectiveReplyToId,
2082
+ MessageThreadId: effectiveReplyToId,
2083
+ Timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2084
+ WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2085
+ CommandAuthorized: commandAuthorized,
2086
+ CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
2087
+ OriginatingChannel: "mattermost",
2088
+ OriginatingTo: to,
2089
+ ...mediaPayload
2090
+ });
2091
+ const pinnedMainDmOwner = kind === "direct" ? resolvePinnedMainDmOwnerFromAllowlist({
2092
+ dmScope: cfg.session?.dmScope,
2093
+ allowFrom: account.config.allowFrom,
2094
+ normalizeEntry: normalizeMattermostAllowEntry
2095
+ }) : null;
2096
+ const storePath = core.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
2097
+ const previewLine = bodyText.slice(0, 200).replace(/\n/g, "\\n");
2098
+ logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} len=${bodyText.length} preview="${previewLine}"`);
2099
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
2100
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
2101
+ cfg,
2102
+ channel: "mattermost",
2103
+ accountId: account.accountId
2104
+ });
2105
+ const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
2106
+ cfg,
2107
+ agentId: route.agentId,
2108
+ channel: "mattermost",
2109
+ accountId: account.accountId,
2110
+ typing: {
2111
+ start: () => sendTypingIndicator(channelId, effectiveReplyToId),
2112
+ onStartError: (err) => {
2113
+ logTypingFailure({
2114
+ log: (message) => logger.debug?.(message),
2115
+ channel: "mattermost",
2116
+ target: channelId,
2117
+ error: err
2118
+ });
2119
+ }
2120
+ }
2121
+ });
2122
+ const draftPreviewEnabled = account.streamingMode !== "off";
2123
+ const draftToolProgressEnabled = shouldUpdateMattermostDraftToolProgress(account);
2124
+ const suppressDefaultToolProgressMessages = shouldSuppressMattermostDefaultToolProgressMessages(account);
2125
+ const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
2126
+ client,
2127
+ channelId,
2128
+ rootId: effectiveReplyToId,
2129
+ throttleMs: 1200,
2130
+ log: logVerboseMessage,
2131
+ warn: logVerboseMessage
2132
+ }) : createDisabledMattermostDraftStream();
2133
+ let lastPartialText = "";
2134
+ const progressDraft = createChannelProgressDraftCompositor({
2135
+ entry: account.config,
2136
+ mode: account.streamingMode,
2137
+ active: draftPreviewEnabled,
2138
+ seed: `${account.accountId}:${channelId}`,
2139
+ update: async (previewText, options) => {
2140
+ draftStream.update(previewText);
2141
+ if (options?.flush) await draftStream.flush();
2142
+ }
2143
+ });
2144
+ const previewState = { finalizedViaPreviewPost: false };
2145
+ const resolvePreviewFinalText = (text) => {
2146
+ if (typeof text !== "string") return;
2147
+ const formatted = core.channel.text.convertMarkdownTables(text, tableMode);
2148
+ const chunkMode = core.channel.text.resolveChunkMode(cfg, "mattermost", account.accountId);
2149
+ const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
2150
+ if (!chunks.length && formatted) chunks.push(formatted);
2151
+ if (chunks.length != 1) return;
2152
+ const trimmed = chunks[0]?.trim();
2153
+ if (!trimmed) return;
2154
+ if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return;
2155
+ return trimmed;
2156
+ };
2157
+ const updateDraftFromPartial = (text) => {
2158
+ const cleaned = text?.trim();
2159
+ if (!cleaned) return;
2160
+ if (cleaned === lastPartialText) return;
2161
+ if (lastPartialText && lastPartialText.startsWith(cleaned) && cleaned.length < lastPartialText.length) return;
2162
+ lastPartialText = cleaned;
2163
+ draftStream.update(cleaned);
2164
+ };
2165
+ const deliveryBarrier = createMattermostReplyDeliveryBarrier({
2166
+ isDirect: kind === "direct",
2167
+ dmRetryOptions: account.config.dmChannelRetry
2168
+ });
2169
+ const { dispatcher, replyOptions, markDispatchIdle, markRunComplete } = core.channel.reply.createReplyDispatcherWithTyping({
2170
+ ...replyPipeline,
2171
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
2172
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
2173
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId),
2174
+ typingCallbacks,
2175
+ deliver: async (payloadEntry, info) => {
2176
+ if (info.kind === "final") progressDraft.markFinalReplyStarted();
2177
+ const markThreadParticipation = () => {
2178
+ if (kind !== "direct" && effectiveReplyToId) recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
2179
+ };
2180
+ await deliverMattermostReplyWithDraftPreview({
2181
+ payload: payloadEntry,
2182
+ info,
2183
+ kind,
2184
+ client,
2185
+ draftStream,
2186
+ effectiveReplyToId,
2187
+ resolvePreviewFinalText,
2188
+ previewState,
2189
+ logVerboseMessage,
2190
+ recordThreadParticipation: markThreadParticipation,
2191
+ deliverPayload: async (payloadToDeliver) => {
2192
+ const outcome = await deliverMattermostReplyPayload({
2193
+ core,
2194
+ cfg,
2195
+ payload: payloadToDeliver,
2196
+ to,
2197
+ accountId: account.accountId,
2198
+ agentId: route.agentId,
2199
+ replyToId: resolveMattermostReplyRootId({
2200
+ kind,
2201
+ threadRootId: effectiveReplyToId,
2202
+ replyToId: payloadToDeliver.replyToId
2203
+ }),
2204
+ textLimit,
2205
+ tableMode,
2206
+ sendMessage: sendMessageMattermost,
2207
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
2208
+ });
2209
+ if (outcome === "text" || outcome === "media") markThreadParticipation();
2210
+ const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
2211
+ outcome,
2212
+ payload: payloadToDeliver,
2213
+ to,
2214
+ accountId: account.accountId,
2215
+ agentId: route.agentId
2216
+ });
2217
+ if (deliveryLog) runtime.log?.(deliveryLog);
2218
+ }
2219
+ });
2220
+ if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2221
+ },
2222
+ onError: (err, info) => {
2223
+ runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
2224
+ }
2225
+ });
2226
+ const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
2227
+ route,
2228
+ sessionKey: route.sessionKey
2229
+ });
2230
+ let dispatchSettledBeforeStart = false;
2231
+ try {
2232
+ await core.channel.inbound.run({
2233
+ channel: "mattermost",
2234
+ accountId: route.accountId,
2235
+ raw: post,
2236
+ adapter: {
2237
+ ingest: () => ({
2238
+ id: post.id ?? `${to}:${Date.now()}`,
2239
+ timestamp: post.create_at ?? void 0,
2240
+ rawText,
2241
+ textForAgent: ctxPayload.BodyForAgent,
2242
+ textForCommands: ctxPayload.CommandBody,
2243
+ raw: post
2244
+ }),
2245
+ resolveTurn: () => ({
2246
+ channel: "mattermost",
2247
+ accountId: route.accountId,
2248
+ routeSessionKey: route.sessionKey,
2249
+ storePath,
2250
+ ctxPayload,
2251
+ recordInboundSession: core.channel.session.recordInboundSession,
2252
+ record: {
2253
+ updateLastRoute: kind === "direct" ? {
2254
+ sessionKey: inboundLastRouteSessionKey,
2255
+ channel: "mattermost",
2256
+ to,
2257
+ accountId: route.accountId,
2258
+ mainDmOwnerPin: inboundLastRouteSessionKey === route.mainSessionKey && pinnedMainDmOwner ? {
2259
+ ownerRecipient: pinnedMainDmOwner,
2260
+ senderRecipient: normalizeMattermostAllowEntry(senderId),
2261
+ onSkip: ({ ownerRecipient, senderRecipient }) => {
2262
+ logVerboseMessage(`mattermost: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
2263
+ }
2264
+ } : void 0
2265
+ } : void 0,
2266
+ onRecordError: (err) => {
2267
+ logVerboseMessage(`mattermost: failed updating session meta id=${post.id ?? "unknown"}: ${String(err)}`);
2268
+ }
2269
+ },
2270
+ history: {
2271
+ isGroup: Boolean(historyKey),
2272
+ historyKey: historyKey ?? void 0,
2273
+ historyMap: channelHistories,
2274
+ limit: historyLimit
2275
+ },
2276
+ onPreDispatchFailure: async () => {
2277
+ dispatchSettledBeforeStart = true;
2278
+ await core.channel.reply.settleReplyDispatcher({
2279
+ dispatcher,
2280
+ onSettled: () => {
2281
+ markRunComplete();
2282
+ markDispatchIdle();
2283
+ }
2284
+ });
2285
+ },
2286
+ runDispatch: () => core.channel.reply.withReplyDispatcher({
2287
+ dispatcher,
2288
+ onSettled: () => {
2289
+ markDispatchIdle();
2290
+ },
2291
+ run: () => core.channel.reply.dispatchReplyFromConfig({
2292
+ ctx: ctxPayload,
2293
+ cfg,
2294
+ dispatcher,
2295
+ replyOptions: {
2296
+ ...replyOptions,
2297
+ allowProgressCallbacksWhenSourceDeliverySuppressed: draftToolProgressEnabled ? true : void 0,
2298
+ onObservedReplyDelivery: draftToolProgressEnabled ? () => draftStream.clear() : void 0,
2299
+ disableBlockStreaming: true,
2300
+ ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
2301
+ onModelSelected,
2302
+ onPartialReply: (payloadResult) => {
2303
+ if (account.streamingMode !== "progress") updateDraftFromPartial(payloadResult.text);
2304
+ },
2305
+ onAssistantMessageStart: () => {
2306
+ lastPartialText = "";
2307
+ progressDraft.resetReasoningProgress();
2308
+ if (account.streamingMode !== "progress") progressDraft.reset();
2309
+ },
2310
+ onReasoningEnd: () => {
2311
+ lastPartialText = "";
2312
+ progressDraft.resetReasoningProgress();
2313
+ if (account.streamingMode !== "progress") progressDraft.reset();
2314
+ },
2315
+ onReasoningStream: async (payloadResult) => {
2316
+ if (account.streamingMode === "progress") {
2317
+ await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
2318
+ return;
2319
+ }
2320
+ if (!lastPartialText) draftStream.update("Thinking…");
2321
+ },
2322
+ onToolStart: async (payloadValue) => {
2323
+ if (!draftToolProgressEnabled) return;
2324
+ await progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2325
+ event: "tool",
2326
+ itemId: payloadValue.itemId,
2327
+ toolCallId: payloadValue.toolCallId,
2328
+ name: payloadValue.name,
2329
+ phase: payloadValue.phase,
2330
+ args: payloadValue.args
2331
+ }, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
2332
+ },
2333
+ onItemEvent: async (payloadLocal) => {
2334
+ if (!draftToolProgressEnabled) return;
2335
+ await progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2336
+ event: "item",
2337
+ itemId: payloadLocal.itemId,
2338
+ itemKind: payloadLocal.kind,
2339
+ title: payloadLocal.title,
2340
+ name: payloadLocal.name,
2341
+ phase: payloadLocal.phase,
2342
+ status: payloadLocal.status,
2343
+ summary: payloadLocal.summary,
2344
+ progressText: payloadLocal.progressText,
2345
+ meta: payloadLocal.meta
2346
+ }), { startImmediately: true });
2347
+ }
2348
+ }
2349
+ })
2350
+ })
2351
+ })
2352
+ }
2353
+ });
2354
+ } finally {
2355
+ try {
2356
+ await draftStream.stop();
2357
+ } catch (err) {
2358
+ logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`);
2359
+ }
2360
+ if (!dispatchSettledBeforeStart) markRunComplete();
2361
+ }
2362
+ }
2363
+ }) === "duplicate") logVerboseMessage(`mattermost: drop post (dedupe account=${account.accountId} ids=${allMessageIds.length})`);
2364
+ };
2365
+ const handleReactionEvent = async (payload) => {
2366
+ const reactionData = payload.data?.reaction;
2367
+ if (!reactionData) return;
2368
+ let reaction = null;
2369
+ if (typeof reactionData === "string") try {
2370
+ reaction = JSON.parse(reactionData);
2371
+ } catch {
2372
+ return;
2373
+ }
2374
+ else if (typeof reactionData === "object") reaction = reactionData;
2375
+ if (!reaction) return;
2376
+ const userId = reaction.user_id?.trim();
2377
+ const postId = reaction.post_id?.trim();
2378
+ const emojiName = reaction.emoji_name?.trim();
2379
+ if (!userId || !postId || !emojiName) return;
2380
+ if (userId === botUserId) return;
2381
+ const action = payload.event === "reaction_removed" ? "removed" : "added";
2382
+ const senderName = normalizeOptionalString((await resolveUserInfo(userId))?.username) ?? userId;
2383
+ const channelId = resolveMattermostReactionChannelId(payload);
2384
+ if (!channelId) {
2385
+ logVerboseMessage(`mattermost: drop reaction (no channel_id in broadcast, cannot enforce policy)`);
2386
+ return;
2387
+ }
2388
+ const channelInfo = await resolveChannelInfo(channelId);
2389
+ if (!channelInfo?.type) {
2390
+ logVerboseMessage(`mattermost: drop reaction (cannot resolve channel type for ${channelId})`);
2391
+ return;
2392
+ }
2393
+ const kind = mapMattermostChannelTypeToChatType(channelInfo.type);
2394
+ const reactionAccess = await resolveMattermostMonitorInboundAccess({
2395
+ account,
2396
+ cfg,
2397
+ senderId: userId,
2398
+ senderName,
2399
+ channelId,
2400
+ kind,
2401
+ groupPolicy,
2402
+ readStoreAllowFrom: pairing.readAllowFromStore,
2403
+ allowTextCommands: false,
2404
+ hasControlCommand: false,
2405
+ eventKind: "reaction",
2406
+ mayPair: false
2407
+ });
2408
+ if (reactionAccess.ingress.decision !== "allow") {
2409
+ if (kind === "direct") logVerboseMessage(`mattermost: drop reaction (dmPolicy=${dmPolicy} sender=${userId} reason=${reactionAccess.senderAccess.reasonCode})`);
2410
+ else logVerboseMessage(`mattermost: drop reaction (groupPolicy=${groupPolicy} sender=${userId} reason=${reactionAccess.senderAccess.reasonCode} channel=${channelId})`);
2411
+ return;
2412
+ }
2413
+ const teamId = channelInfo?.team_id ?? void 0;
2414
+ const sessionKey = core.channel.routing.resolveAgentRoute({
2415
+ cfg,
2416
+ channel: "mattermost",
2417
+ accountId: account.accountId,
2418
+ teamId,
2419
+ peer: {
2420
+ kind,
2421
+ id: kind === "direct" ? userId : channelId
2422
+ }
2423
+ }).sessionKey;
2424
+ const eventText = `Mattermost reaction ${action}: :${emojiName}: by @${senderName} on post ${postId} in channel ${channelId}`;
2425
+ core.system.enqueueSystemEvent(eventText, {
2426
+ sessionKey,
2427
+ contextKey: `mattermost:reaction:${postId}:${emojiName}:${userId}:${action}`
2428
+ });
2429
+ logVerboseMessage(`mattermost reaction: ${action} :${emojiName}: by ${senderName} on ${postId}`);
2430
+ };
2431
+ const inboundDebounceMs = core.channel.debounce.resolveInboundDebounceMs({
2432
+ cfg,
2433
+ channel: "mattermost"
2434
+ });
2435
+ const debouncer = core.channel.debounce.createInboundDebouncer({
2436
+ debounceMs: inboundDebounceMs,
2437
+ buildKey: (entry) => {
2438
+ const channelId = entry.post.channel_id ?? entry.payload.data?.channel_id ?? entry.payload.broadcast?.channel_id;
2439
+ if (!channelId) return null;
2440
+ const threadId = normalizeOptionalString(entry.post.root_id);
2441
+ const threadKey = threadId ? `thread:${threadId}` : "channel";
2442
+ return `mattermost:${account.accountId}:${channelId}:${threadKey}`;
2443
+ },
2444
+ shouldDebounce: (entry) => {
2445
+ if (entry.post.file_ids && entry.post.file_ids.length > 0) return false;
2446
+ const text = normalizeOptionalString(entry.post.message) ?? "";
2447
+ if (!text) return false;
2448
+ return !core.channel.commands.isControlCommandMessage(text, cfg);
2449
+ },
2450
+ onFlush: async (entries) => {
2451
+ const last = entries.at(-1);
2452
+ if (!last) return;
2453
+ if (entries.length === 1) {
2454
+ await handlePost(last.post, last.payload);
2455
+ return;
2456
+ }
2457
+ const combinedText = entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n");
2458
+ const mergedPost = {
2459
+ ...last.post,
2460
+ message: combinedText,
2461
+ file_ids: []
2462
+ };
2463
+ const ids = entries.map((entry) => entry.post.id).filter(Boolean);
2464
+ await handlePost(mergedPost, last.payload, ids.length > 0 ? ids : void 0);
2465
+ },
2466
+ onError: (err) => {
2467
+ runtime.error?.(`mattermost debounce flush failed: ${String(err)}`);
2468
+ }
2469
+ });
2470
+ const wsUrl = buildMattermostWsUrl(baseUrl);
2471
+ let seq = 1;
2472
+ const connectOnce = createMattermostConnectOnce({
2473
+ wsUrl,
2474
+ botToken,
2475
+ abortSignal: opts.abortSignal,
2476
+ statusSink: opts.statusSink,
2477
+ runtime,
2478
+ webSocketFactory: opts.webSocketFactory,
2479
+ nextSeq: () => seq++,
2480
+ getBotUpdateAt: async () => {
2481
+ return (await fetchMattermostMe(client)).update_at ?? 0;
2482
+ },
2483
+ onPosted: async (post, payload) => {
2484
+ await debouncer.enqueue({
2485
+ post,
2486
+ payload
2487
+ });
2488
+ },
2489
+ onReaction: async (payload) => {
2490
+ await handleReactionEvent(payload);
2491
+ }
2492
+ });
2493
+ let slashShutdownCleanup = null;
2494
+ if (slashEnabled) {
2495
+ const runAbortCleanup = () => {
2496
+ if (slashShutdownCleanup) return;
2497
+ const commands = getSlashCommandState(account.accountId)?.registeredCommands ?? [];
2498
+ deactivateSlashCommands(account.accountId);
2499
+ slashShutdownCleanup = cleanupSlashCommands({
2500
+ client,
2501
+ commands,
2502
+ log: (msg) => runtime.log?.(msg)
2503
+ }).catch((err) => {
2504
+ runtime.error?.(`mattermost: slash cleanup failed: ${String(err)}`);
2505
+ });
2506
+ };
2507
+ if (opts.abortSignal?.aborted) runAbortCleanup();
2508
+ else opts.abortSignal?.addEventListener("abort", runAbortCleanup, { once: true });
2509
+ }
2510
+ try {
2511
+ await runWithReconnect(connectOnce, {
2512
+ abortSignal: opts.abortSignal,
2513
+ jitterRatio: .2,
2514
+ onError: (err) => {
2515
+ runtime.error?.(`mattermost connection failed: ${String(err)}`);
2516
+ opts.statusSink?.({
2517
+ lastError: String(err),
2518
+ connected: false
2519
+ });
2520
+ },
2521
+ onReconnect: (delayMs) => {
2522
+ runtime.log?.(`mattermost reconnecting in ${Math.round(delayMs / 1e3)}s`);
2523
+ }
2524
+ });
2525
+ } finally {
2526
+ unregisterInteractions?.();
2527
+ }
2528
+ const slashShutdownCleanupPromise = slashShutdownCleanup;
2529
+ if (slashShutdownCleanupPromise) await Promise.resolve(slashShutdownCleanupPromise);
2530
+ }
2531
+ //#endregion
2532
+ //#region extensions/mattermost/src/mattermost/probe.ts
2533
+ async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivateNetwork = false) {
2534
+ const normalized = normalizeMattermostBaseUrl(baseUrl);
2535
+ if (!normalized) return {
2536
+ ok: false,
2537
+ error: "baseUrl missing"
2538
+ };
2539
+ const url = `${normalized}/api/v4/users/me`;
2540
+ const start = Date.now();
2541
+ const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : 0;
2542
+ const controller = resolvedTimeoutMs > 0 ? new AbortController() : void 0;
2543
+ let timer = null;
2544
+ if (controller) timer = setTimeout(() => controller.abort(), resolvedTimeoutMs);
2545
+ try {
2546
+ const { response: res, release } = await fetchWithSsrFGuard({
2547
+ url,
2548
+ init: {
2549
+ headers: { Authorization: `Bearer ${botToken}` },
2550
+ signal: controller?.signal
2551
+ },
2552
+ auditContext: "mattermost-probe",
2553
+ policy: ssrfPolicyFromPrivateNetworkOptIn(allowPrivateNetwork)
2554
+ });
2555
+ try {
2556
+ const elapsedMs = Date.now() - start;
2557
+ if (!res.ok) {
2558
+ const detail = await readMattermostError(res);
2559
+ return {
2560
+ ok: false,
2561
+ status: res.status,
2562
+ error: detail || res.statusText,
2563
+ elapsedMs
2564
+ };
2565
+ }
2566
+ const bot = await res.json();
2567
+ return {
2568
+ ok: true,
2569
+ status: res.status,
2570
+ elapsedMs,
2571
+ bot
2572
+ };
2573
+ } finally {
2574
+ await release();
2575
+ }
2576
+ } catch (err) {
2577
+ return {
2578
+ ok: false,
2579
+ status: null,
2580
+ error: formatErrorMessage(err),
2581
+ elapsedMs: Date.now() - start
2582
+ };
2583
+ } finally {
2584
+ if (timer) clearTimeout(timer);
2585
+ }
2586
+ }
2587
+ //#endregion
2588
+ //#region extensions/mattermost/src/mattermost/reactions.ts
2589
+ const BOT_USER_CACHE_TTL_MS = 10 * 6e4;
2590
+ const botUserIdCache = /* @__PURE__ */ new Map();
2591
+ async function resolveBotUserId(client, cacheKey) {
2592
+ const rawNow = Date.now();
2593
+ const now = asDateTimestampMs(rawNow);
2594
+ const cached = botUserIdCache.get(cacheKey);
2595
+ if (cached) {
2596
+ if (now !== void 0 && cached.expiresAt > now) return cached.userId;
2597
+ botUserIdCache.delete(cacheKey);
2598
+ }
2599
+ const userId = (await fetchMattermostMe(client))?.id?.trim();
2600
+ if (!userId) return null;
2601
+ const expiresAt = resolveExpiresAtMsFromDurationMs(BOT_USER_CACHE_TTL_MS, { nowMs: rawNow });
2602
+ if (expiresAt !== void 0) botUserIdCache.set(cacheKey, {
2603
+ userId,
2604
+ expiresAt
2605
+ });
2606
+ return userId;
2607
+ }
2608
+ async function addMattermostReaction(params) {
2609
+ return runMattermostReaction(params, {
2610
+ action: "add",
2611
+ mutation: createReaction
2612
+ });
2613
+ }
2614
+ async function removeMattermostReaction(params) {
2615
+ return runMattermostReaction(params, {
2616
+ action: "remove",
2617
+ mutation: deleteReaction
2618
+ });
2619
+ }
2620
+ async function runMattermostReaction(params, options) {
2621
+ const resolved = resolveMattermostAccount({
2622
+ cfg: params.cfg,
2623
+ accountId: params.accountId
2624
+ });
2625
+ const baseUrl = resolved.baseUrl?.trim();
2626
+ const botToken = resolved.botToken?.trim();
2627
+ if (!baseUrl || !botToken) return {
2628
+ ok: false,
2629
+ error: "Mattermost botToken/baseUrl missing."
2630
+ };
2631
+ const client = createMattermostClient({
2632
+ baseUrl,
2633
+ botToken,
2634
+ fetchImpl: params.fetchImpl,
2635
+ allowPrivateNetwork: isPrivateNetworkOptInEnabled(resolved.config)
2636
+ });
2637
+ const userId = await resolveBotUserId(client, `${baseUrl}:${botToken}`);
2638
+ if (!userId) return {
2639
+ ok: false,
2640
+ error: "Mattermost reactions failed: could not resolve bot user id."
2641
+ };
2642
+ try {
2643
+ await options.mutation(client, {
2644
+ userId,
2645
+ postId: params.postId,
2646
+ emojiName: params.emojiName
2647
+ });
2648
+ } catch (err) {
2649
+ return {
2650
+ ok: false,
2651
+ error: `Mattermost ${options.action} reaction failed: ${String(err)}`
2652
+ };
2653
+ }
2654
+ return { ok: true };
2655
+ }
2656
+ async function createReaction(client, params) {
2657
+ await client.request("/reactions", {
2658
+ method: "POST",
2659
+ body: JSON.stringify({
2660
+ user_id: params.userId,
2661
+ post_id: params.postId,
2662
+ emoji_name: params.emojiName
2663
+ })
2664
+ });
2665
+ }
2666
+ async function deleteReaction(client, params) {
2667
+ const emoji = encodeURIComponent(params.emojiName);
2668
+ await client.request(`/users/${params.userId}/posts/${params.postId}/reactions/${emoji}`, { method: "DELETE" });
2669
+ }
2670
+ //#endregion
2671
+ export { addMattermostReaction, listMattermostDirectoryGroups, listMattermostDirectoryPeers, monitorMattermostProvider, probeMattermost, removeMattermostReaction, resolveMattermostOpaqueTarget, sendMessageMattermost };