@gakr-gakr/matrix 0.1.0 → 0.1.1

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 (301) hide show
  1. package/autobot.plugin.json +891 -3
  2. package/dist/account-selection-D4xDzY_1.js +158 -0
  3. package/dist/active-client-BXz0W1fG.js +20 -0
  4. package/dist/api.js +12 -0
  5. package/dist/approval-handler.runtime-XgtgHryy.js +377 -0
  6. package/dist/approval-ids-Bj1MSuK0.js +7 -0
  7. package/dist/approval-reaction-auth-CP8yUUiI.js +27 -0
  8. package/dist/approval-reactions-C7FrzFhD.js +162 -0
  9. package/dist/async-lock-SsmtFXtt.js +19 -0
  10. package/dist/auth-presence.js +26 -0
  11. package/dist/backup-health-3BHbHxyd.js +60 -0
  12. package/dist/channel-CVtvS1kS.js +1380 -0
  13. package/dist/channel-plugin-api.js +2 -0
  14. package/dist/channel.runtime-BCl9atvS.js +250 -0
  15. package/dist/cli-D1Fxo6zb.js +1338 -0
  16. package/dist/cli-metadata-lo35g_nH.js +22 -0
  17. package/dist/cli-metadata.js +2 -0
  18. package/dist/client-4JU3adE6.js +30 -0
  19. package/dist/client-DVbkO1fr.js +25 -0
  20. package/dist/client-bootstrap-mLJmDCv8.js +114 -0
  21. package/dist/config-paths-BRIwec9o.js +114 -0
  22. package/dist/config-schema-ON2KZjSH.js +308 -0
  23. package/dist/config-secret-input.runtime-BcE98Tab.js +2 -0
  24. package/dist/contract-api.js +8 -0
  25. package/dist/create-client-nSnXsRe0.js +64 -0
  26. package/dist/credentials-CLaeORZB.js +56 -0
  27. package/dist/credentials-read-lnekFDSy.js +112 -0
  28. package/dist/credentials-write.runtime-AcuXkIly.js +17 -0
  29. package/dist/crypto-node.runtime-D9qxgRPa.js +12 -0
  30. package/dist/crypto-runtime-D577JLjP.js +1214 -0
  31. package/dist/deps-CcgU6fF9.js +208 -0
  32. package/dist/device-health-BDJoK0GP.js +16 -0
  33. package/dist/directory-live-D5osmyPM.js +150 -0
  34. package/dist/doctor-contract-CRTZe22J.js +246 -0
  35. package/dist/doctor-contract-api.js +2 -0
  36. package/dist/doctor-k53ce7TR.js +153 -0
  37. package/dist/draft-stream-B81ki3aq.js +143 -0
  38. package/dist/encryption-guidance-C4UZO9P_.js +15 -0
  39. package/dist/env-auth-ZPNhil6w.js +63 -0
  40. package/dist/env-vars-Ch51id3Y.js +63 -0
  41. package/dist/errors-D8exgH7Z.js +17 -0
  42. package/dist/exec-approval-resolver-NR6hHp1P.js +15 -0
  43. package/dist/helper-api.js +4 -0
  44. package/dist/http-client-CLvnNzJZ.js +331 -0
  45. package/dist/index.js +46 -0
  46. package/dist/legacy-crypto-inspector-BXa-K6Qb.js +41 -0
  47. package/dist/legacy-crypto-restore-DmSdbVyW.js +85 -0
  48. package/dist/logging-BWx5aV5G.js +99 -0
  49. package/dist/matrix-migration.runtime-C5EAzuSF.js +525 -0
  50. package/dist/media-text-H2gCWr7p.js +146 -0
  51. package/dist/messages-BM8v2OhM.js +140 -0
  52. package/dist/migration-snapshot-backup-B4qRjmn2.js +69 -0
  53. package/dist/migration-snapshot.runtime-CEaEL8JK.js +2 -0
  54. package/dist/monitor-9_MYVUk0.js +4331 -0
  55. package/dist/plugin-entry.handlers.runtime.js +51 -0
  56. package/dist/probe.runtime-ARO_q_Zl.js +3 -0
  57. package/dist/profile-update-DgBXphvR.js +68 -0
  58. package/dist/reaction-common-Bx8mZPc9.js +71 -0
  59. package/dist/reaction-events-B2GhGktu.js +121 -0
  60. package/{src/record-shared.ts → dist/record-shared-D-PbvaZ7.js} +1 -2
  61. package/dist/resolve-targets-CFr6_x9K.js +140 -0
  62. package/dist/resolver.runtime-fPzzTZVJ.js +5 -0
  63. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  64. package/dist/route-m49kMiHx.js +161 -0
  65. package/dist/runtime-BfjP-NST.js +8 -0
  66. package/dist/runtime-api-D7plmCoC.js +24 -0
  67. package/dist/runtime-api.js +25 -0
  68. package/dist/runtime-heavy-api.js +3 -0
  69. package/dist/runtime-lwTSy9Yt.js +6 -0
  70. package/dist/runtime-setter-api.js +2 -0
  71. package/dist/sdk-CK0ON6Js.js +1704 -0
  72. package/dist/secret-contract-BKkC-9fa.js +120 -0
  73. package/dist/secret-contract-api.js +2 -0
  74. package/dist/send-CWOxcUMq.js +1517 -0
  75. package/dist/setup-bootstrap-VShXhiBJ.js +62 -0
  76. package/dist/setup-core-CmXNGvQt.js +677 -0
  77. package/dist/setup-entry.js +19 -0
  78. package/dist/setup-plugin-api.js +43 -0
  79. package/dist/setup-surface-zTLHNBns.js +537 -0
  80. package/dist/shared-BrKJkpx_.js +642 -0
  81. package/dist/startup-abort-D79WSeUh.js +109 -0
  82. package/dist/startup-verification-Dj34oWgb.js +132 -0
  83. package/dist/storage-DxbroIe0.js +281 -0
  84. package/dist/storage-paths-BcLg30GH.js +52 -0
  85. package/dist/subagent-hooks-api-CjHBfEoY.js +170 -0
  86. package/dist/subagent-hooks-api.js +2 -0
  87. package/dist/sync-state-Bx0gPaGA.js +12 -0
  88. package/dist/target-ids-iZwjCUZa.js +77 -0
  89. package/dist/test-api.js +4 -0
  90. package/dist/thread-binding-api-BWT96Ttd.js +17 -0
  91. package/dist/thread-binding-api.js +2 -0
  92. package/dist/thread-bindings-owbheXoV.js +352 -0
  93. package/dist/thread-bindings-runtime.js +2 -0
  94. package/dist/thread-bindings-shared-4nkBBftw.js +97 -0
  95. package/dist/timeout-abort-signal-CPD0PPNy.js +2 -0
  96. package/dist/tool-actions.runtime-DDh2EP6z.js +532 -0
  97. package/dist/url-validation-fQvf_pW_.js +36 -0
  98. package/dist/verification-BhMWyuAf.js +345 -0
  99. package/package.json +16 -4
  100. package/CHANGELOG.md +0 -285
  101. package/SPEC-SUPPORT.md +0 -116
  102. package/api.ts +0 -38
  103. package/auth-presence.ts +0 -56
  104. package/channel-plugin-api.ts +0 -3
  105. package/cli-metadata.ts +0 -11
  106. package/contract-api.ts +0 -17
  107. package/doctor-contract-api.ts +0 -1
  108. package/helper-api.ts +0 -3
  109. package/index.ts +0 -55
  110. package/plugin-entry.handlers.runtime.ts +0 -1
  111. package/runtime-api.ts +0 -72
  112. package/runtime-heavy-api.ts +0 -1
  113. package/runtime-setter-api.ts +0 -3
  114. package/secret-contract-api.ts +0 -5
  115. package/setup-entry.ts +0 -17
  116. package/setup-plugin-api.ts +0 -3
  117. package/src/account-selection.ts +0 -223
  118. package/src/actions.ts +0 -346
  119. package/src/approval-auth.ts +0 -25
  120. package/src/approval-handler.runtime.ts +0 -595
  121. package/src/approval-ids.ts +0 -6
  122. package/src/approval-native.ts +0 -348
  123. package/src/approval-reaction-auth.ts +0 -45
  124. package/src/approval-reactions.ts +0 -313
  125. package/src/auth-precedence.ts +0 -61
  126. package/src/channel-account-paths.ts +0 -97
  127. package/src/channel.runtime.ts +0 -17
  128. package/src/channel.setup.ts +0 -48
  129. package/src/channel.ts +0 -667
  130. package/src/cli-metadata.ts +0 -19
  131. package/src/cli.ts +0 -2298
  132. package/src/config-adapter.ts +0 -41
  133. package/src/config-schema.ts +0 -159
  134. package/src/config-ui-hints.ts +0 -56
  135. package/src/directory-live.ts +0 -238
  136. package/src/doctor-contract.ts +0 -287
  137. package/src/doctor.ts +0 -262
  138. package/src/env-vars.ts +0 -92
  139. package/src/exec-approval-resolver.ts +0 -23
  140. package/src/exec-approvals.ts +0 -293
  141. package/src/group-mentions.ts +0 -41
  142. package/src/legacy-crypto-inspector-availability.ts +0 -60
  143. package/src/legacy-crypto.ts +0 -531
  144. package/src/legacy-state.ts +0 -156
  145. package/src/matrix/account-config.ts +0 -175
  146. package/src/matrix/accounts.ts +0 -194
  147. package/src/matrix/actions/client.ts +0 -31
  148. package/src/matrix/actions/devices.ts +0 -34
  149. package/src/matrix/actions/limits.ts +0 -6
  150. package/src/matrix/actions/messages.ts +0 -129
  151. package/src/matrix/actions/pins.ts +0 -63
  152. package/src/matrix/actions/polls.ts +0 -109
  153. package/src/matrix/actions/profile.ts +0 -37
  154. package/src/matrix/actions/reactions.ts +0 -59
  155. package/src/matrix/actions/room.ts +0 -71
  156. package/src/matrix/actions/summary.ts +0 -88
  157. package/src/matrix/actions/types.ts +0 -63
  158. package/src/matrix/actions/verification.ts +0 -589
  159. package/src/matrix/actions.ts +0 -37
  160. package/src/matrix/active-client.ts +0 -26
  161. package/src/matrix/async-lock.ts +0 -18
  162. package/src/matrix/backup-health.ts +0 -124
  163. package/src/matrix/client/config-runtime-api.ts +0 -9
  164. package/src/matrix/client/config-secret-input.runtime.ts +0 -1
  165. package/src/matrix/client/config.ts +0 -853
  166. package/src/matrix/client/create-client.ts +0 -105
  167. package/src/matrix/client/env-auth.ts +0 -95
  168. package/src/matrix/client/file-sync-store.ts +0 -289
  169. package/src/matrix/client/logging.ts +0 -140
  170. package/src/matrix/client/migration-snapshot.runtime.ts +0 -1
  171. package/src/matrix/client/private-network-host.ts +0 -1
  172. package/src/matrix/client/runtime.ts +0 -4
  173. package/src/matrix/client/shared.ts +0 -316
  174. package/src/matrix/client/storage.ts +0 -543
  175. package/src/matrix/client/types.ts +0 -50
  176. package/src/matrix/client/url-validation.ts +0 -76
  177. package/src/matrix/client-bootstrap.ts +0 -173
  178. package/src/matrix/client.ts +0 -23
  179. package/src/matrix/config-paths.ts +0 -31
  180. package/src/matrix/config-update.ts +0 -292
  181. package/src/matrix/credentials-read.ts +0 -207
  182. package/src/matrix/credentials-write.runtime.ts +0 -35
  183. package/src/matrix/credentials.ts +0 -95
  184. package/src/matrix/deps.ts +0 -309
  185. package/src/matrix/device-health.ts +0 -31
  186. package/src/matrix/direct-management.ts +0 -349
  187. package/src/matrix/direct-room.ts +0 -128
  188. package/src/matrix/draft-stream.ts +0 -225
  189. package/src/matrix/encryption-guidance.ts +0 -24
  190. package/src/matrix/errors.ts +0 -21
  191. package/src/matrix/format.ts +0 -426
  192. package/src/matrix/legacy-crypto-inspector.ts +0 -95
  193. package/src/matrix/media-errors.ts +0 -20
  194. package/src/matrix/media-text.ts +0 -162
  195. package/src/matrix/monitor/access-state.ts +0 -145
  196. package/src/matrix/monitor/ack-config.ts +0 -27
  197. package/src/matrix/monitor/allowlist.ts +0 -92
  198. package/src/matrix/monitor/auto-join.ts +0 -86
  199. package/src/matrix/monitor/config.ts +0 -569
  200. package/src/matrix/monitor/context-summary.ts +0 -43
  201. package/src/matrix/monitor/direct.ts +0 -296
  202. package/src/matrix/monitor/events.ts +0 -397
  203. package/src/matrix/monitor/handler.ts +0 -2271
  204. package/src/matrix/monitor/inbound-dedupe.ts +0 -267
  205. package/src/matrix/monitor/index.ts +0 -540
  206. package/src/matrix/monitor/legacy-crypto-restore.ts +0 -139
  207. package/src/matrix/monitor/location.ts +0 -108
  208. package/src/matrix/monitor/media.ts +0 -119
  209. package/src/matrix/monitor/mentions.ts +0 -256
  210. package/src/matrix/monitor/reaction-events.ts +0 -197
  211. package/src/matrix/monitor/recent-invite.ts +0 -30
  212. package/src/matrix/monitor/replies.ts +0 -136
  213. package/src/matrix/monitor/reply-context.ts +0 -92
  214. package/src/matrix/monitor/room-history.ts +0 -301
  215. package/src/matrix/monitor/room-info.ts +0 -126
  216. package/src/matrix/monitor/rooms.ts +0 -52
  217. package/src/matrix/monitor/route.ts +0 -179
  218. package/src/matrix/monitor/runtime-api.ts +0 -28
  219. package/src/matrix/monitor/startup-verification.ts +0 -237
  220. package/src/matrix/monitor/startup.ts +0 -218
  221. package/src/matrix/monitor/status.ts +0 -120
  222. package/src/matrix/monitor/sync-lifecycle.ts +0 -91
  223. package/src/matrix/monitor/task-runner.ts +0 -38
  224. package/src/matrix/monitor/test-events.ts +0 -21
  225. package/src/matrix/monitor/thread-context.ts +0 -108
  226. package/src/matrix/monitor/threads.ts +0 -85
  227. package/src/matrix/monitor/types.ts +0 -30
  228. package/src/matrix/monitor/verification-events.ts +0 -643
  229. package/src/matrix/monitor/verification-utils.ts +0 -46
  230. package/src/matrix/outbound-media-runtime.ts +0 -1
  231. package/src/matrix/poll-summary.ts +0 -110
  232. package/src/matrix/poll-types.ts +0 -429
  233. package/src/matrix/probe.runtime.ts +0 -4
  234. package/src/matrix/probe.ts +0 -97
  235. package/src/matrix/profile.ts +0 -184
  236. package/src/matrix/reaction-common.ts +0 -147
  237. package/src/matrix/sdk/crypto-bootstrap.ts +0 -438
  238. package/src/matrix/sdk/crypto-facade.ts +0 -242
  239. package/src/matrix/sdk/crypto-node.runtime.ts +0 -17
  240. package/src/matrix/sdk/crypto-runtime.ts +0 -14
  241. package/src/matrix/sdk/decrypt-bridge.ts +0 -410
  242. package/src/matrix/sdk/event-helpers.ts +0 -83
  243. package/src/matrix/sdk/http-client.ts +0 -87
  244. package/src/matrix/sdk/idb-persistence-lock.ts +0 -51
  245. package/src/matrix/sdk/idb-persistence.ts +0 -286
  246. package/src/matrix/sdk/logger.ts +0 -108
  247. package/src/matrix/sdk/read-response-with-limit.ts +0 -19
  248. package/src/matrix/sdk/recovery-key-store.ts +0 -453
  249. package/src/matrix/sdk/timeout-abort-signal.ts +0 -1
  250. package/src/matrix/sdk/transport-runtime-api.ts +0 -18
  251. package/src/matrix/sdk/transport.ts +0 -352
  252. package/src/matrix/sdk/types.ts +0 -245
  253. package/src/matrix/sdk/verification-manager.ts +0 -795
  254. package/src/matrix/sdk/verification-status.ts +0 -23
  255. package/src/matrix/sdk.ts +0 -2152
  256. package/src/matrix/send/client.ts +0 -93
  257. package/src/matrix/send/formatting.ts +0 -189
  258. package/src/matrix/send/media.ts +0 -244
  259. package/src/matrix/send/targets.ts +0 -104
  260. package/src/matrix/send/types.ts +0 -131
  261. package/src/matrix/send.ts +0 -660
  262. package/src/matrix/session-store-metadata.ts +0 -108
  263. package/src/matrix/startup-abort.ts +0 -44
  264. package/src/matrix/subagent-hooks.ts +0 -308
  265. package/src/matrix/sync-state.ts +0 -27
  266. package/src/matrix/target-ids.ts +0 -79
  267. package/src/matrix/thread-bindings-shared.ts +0 -206
  268. package/src/matrix/thread-bindings.ts +0 -580
  269. package/src/matrix-migration.runtime.ts +0 -9
  270. package/src/migration-config.ts +0 -243
  271. package/src/migration-snapshot-backup.ts +0 -116
  272. package/src/migration-snapshot.ts +0 -53
  273. package/src/onboarding.ts +0 -775
  274. package/src/outbound.ts +0 -248
  275. package/src/plugin-entry.runtime.js +0 -115
  276. package/src/plugin-entry.runtime.ts +0 -70
  277. package/src/profile-update.ts +0 -71
  278. package/src/resolve-targets.ts +0 -175
  279. package/src/resolver.runtime.ts +0 -5
  280. package/src/resolver.ts +0 -21
  281. package/src/runtime-api.ts +0 -106
  282. package/src/runtime.ts +0 -13
  283. package/src/secret-contract.ts +0 -174
  284. package/src/session-route.ts +0 -126
  285. package/src/setup-bootstrap.ts +0 -102
  286. package/src/setup-config.ts +0 -222
  287. package/src/setup-contract.ts +0 -90
  288. package/src/setup-core.ts +0 -146
  289. package/src/setup-dm-policy.ts +0 -15
  290. package/src/setup-surface.ts +0 -4
  291. package/src/startup-maintenance.ts +0 -114
  292. package/src/storage-paths.ts +0 -92
  293. package/src/thread-binding-api.ts +0 -23
  294. package/src/tool-actions.runtime.ts +0 -1
  295. package/src/tool-actions.ts +0 -498
  296. package/src/types.ts +0 -257
  297. package/subagent-hooks-api.ts +0 -31
  298. package/test-api.ts +0 -21
  299. package/thread-binding-api.ts +0 -4
  300. package/thread-bindings-runtime.ts +0 -4
  301. package/tsconfig.json +0 -16
@@ -0,0 +1,1380 @@
1
+ import { a as resolveMatrixTargetIdentity, i as resolveMatrixDirectUserId, n as normalizeMatrixMessagingTarget, r as normalizeMatrixResolvableTarget } from "./target-ids-iZwjCUZa.js";
2
+ import { d as setMatrixThreadBindingIdleTimeoutBySessionKey, p as setMatrixThreadBindingMaxAgeBySessionKey } from "./thread-bindings-shared-4nkBBftw.js";
3
+ import { n as requiresExplicitMatrixDefaultAccount } from "./account-selection-D4xDzY_1.js";
4
+ import { c as resolveMatrixAccountConfig } from "./config-paths-BRIwec9o.js";
5
+ import { d as resolveSingleAccountPromotionTarget, f as singleAccountKeysToMove, g as resolveMatrixAccount, h as resolveDefaultMatrixAccountId, n as matrixSetupAdapter, p as listMatrixAccountIds, t as createMatrixSetupWizardProxy, u as namedAccountPromotionKeys } from "./setup-core-CmXNGvQt.js";
6
+ import { a as normalizeMatrixUserId, n as DEFAULT_ACCOUNT_ID$2, r as matrixConfigAdapter, t as MatrixChannelConfigSchema } from "./config-schema-ON2KZjSH.js";
7
+ import { t as normalizeMatrixApproverId } from "./approval-ids-Bj1MSuK0.js";
8
+ import { t as formatMatrixErrorMessage } from "./errors-D8exgH7Z.js";
9
+ import { n as normalizeCompatibilityConfig, t as legacyConfigRules } from "./doctor-contract-CRTZe22J.js";
10
+ import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-BKkC-9fa.js";
11
+ import { i as autoPrepareLegacyMatrixCrypto, o as autoMigrateLegacyMatrixState, r as resolveMatrixMigrationStatus } from "./matrix-migration.runtime-C5EAzuSF.js";
12
+ import { t as maybeCreateMatrixMigrationSnapshot } from "./migration-snapshot-backup-B4qRjmn2.js";
13
+ import { n as resolveMatrixInboundConversation } from "./thread-binding-api-BWT96Ttd.js";
14
+ import { normalizeAccountId } from "autobot/plugin-sdk/account-id";
15
+ import { createScopedAccountReplyToModeResolver } from "autobot/plugin-sdk/conversation-runtime";
16
+ import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeOptionalStringifiedId } from "autobot/plugin-sdk/string-coerce-runtime";
17
+ import { describeAccountSnapshot } from "autobot/plugin-sdk/account-helpers";
18
+ import { adaptScopedAccountAccessor, createScopedDmSecurityResolver } from "autobot/plugin-sdk/channel-config-helpers";
19
+ import { buildChannelOutboundSessionRoute, buildThreadAwareOutboundSessionRoute, createChatChannelPlugin } from "autobot/plugin-sdk/channel-core";
20
+ import { createChannelMessageAdapterFromOutbound } from "autobot/plugin-sdk/channel-message";
21
+ import { createAllowlistProviderOpenWarningCollector, projectAccountConfigWarningCollector } from "autobot/plugin-sdk/channel-policy";
22
+ import { createChannelDirectoryAdapter, createResolvedDirectoryEntriesLister, createRuntimeDirectoryLiveAdapter } from "autobot/plugin-sdk/directory-runtime";
23
+ import { createLazyRuntimeNamedExport } from "autobot/plugin-sdk/lazy-runtime";
24
+ import { createRuntimeOutboundDelegates } from "autobot/plugin-sdk/outbound-runtime";
25
+ import { buildProbeChannelStatusSummary, collectStatusIssuesFromLastError, createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "autobot/plugin-sdk/status-helpers";
26
+ import { chunkTextForOutbound } from "autobot/plugin-sdk/text-chunking";
27
+ import { ToolAuthorizationError, createActionGate, readNumberParam, readStringParam } from "autobot/plugin-sdk/channel-actions";
28
+ import { extractToolSend } from "autobot/plugin-sdk/tool-send";
29
+ import { Type } from "typebox";
30
+ import { createApproverRestrictedNativeApprovalCapability, createChannelApprovalCapability, splitChannelApprovalCapability } from "autobot/plugin-sdk/approval-delivery-runtime";
31
+ import { createLazyChannelApprovalNativeRuntimeAdapter } from "autobot/plugin-sdk/approval-handler-adapter-runtime";
32
+ import { createChannelNativeOriginTargetResolver, resolveApprovalRequestChannelAccountId, resolveApprovalRequestSessionConversation } from "autobot/plugin-sdk/approval-native-runtime";
33
+ import { createResolvedApproverActionAuthAdapter, resolveApprovalApprovers } from "autobot/plugin-sdk/approval-auth-runtime";
34
+ import { addAllowlistUserEntriesFromConfigEntry, buildAllowlistResolutionSummary, canonicalizeAllowlistWithResolvedIds, patchAllowlistUsersInConfigEntries, summarizeMapping } from "autobot/plugin-sdk/allow-from";
35
+ import { createChannelExecApprovalProfile, getExecApprovalReplyMetadata, isChannelExecApprovalClientEnabledFromConfig, isChannelExecApprovalTargetRecipient, matchesApprovalRequestFilters } from "autobot/plugin-sdk/approval-client-runtime";
36
+ import { normalizeAccountId as normalizeAccountId$1, parseThreadSessionSuffix } from "autobot/plugin-sdk/routing";
37
+ import { createPairingPrefixStripper } from "autobot/plugin-sdk/channel-pairing";
38
+ import { PAIRING_APPROVED_MESSAGE } from "autobot/plugin-sdk/channel-status";
39
+ import { createReplyPrefixOptions, createTypingCallbacks } from "autobot/plugin-sdk/channel-reply-options-runtime";
40
+ import { formatLocationText, toLocationContext } from "autobot/plugin-sdk/channel-location";
41
+ import { getAgentScopedMediaLocalRoots } from "autobot/plugin-sdk/agent-media-payload";
42
+ import { logInboundDrop, logTypingFailure } from "autobot/plugin-sdk/channel-logging";
43
+ import { buildChannelKeyCandidates, resolveChannelEntryMatch } from "autobot/plugin-sdk/channel-targets";
44
+ import { loadSessionStore, resolveSessionStoreEntry, resolveStorePath } from "autobot/plugin-sdk/session-store-runtime";
45
+ //#region extensions/matrix/src/actions.ts
46
+ const MATRIX_PLUGIN_HANDLED_ACTIONS = new Set([
47
+ "send",
48
+ "poll-vote",
49
+ "react",
50
+ "reactions",
51
+ "read",
52
+ "edit",
53
+ "delete",
54
+ "pin",
55
+ "unpin",
56
+ "list-pins",
57
+ "set-profile",
58
+ "member-info",
59
+ "channel-info",
60
+ "permissions"
61
+ ]);
62
+ const MATRIX_PROFILE_MEDIA_PROPERTIES = {
63
+ avatarUrl: Type.Optional(Type.String({ description: "Profile avatar URL for Matrix self-profile update actions. Matrix accepts mxc:// and http(s) URLs." })),
64
+ avatar_url: Type.Optional(Type.String({ description: "snake_case alias of avatarUrl for Matrix self-profile update actions. Matrix accepts mxc:// and http(s) URLs." })),
65
+ avatarPath: Type.Optional(Type.String({ description: "Local avatar file path for Matrix self-profile update actions. Matrix uploads this file and sets the resulting MXC URI." })),
66
+ avatar_path: Type.Optional(Type.String({ description: "snake_case alias of avatarPath for Matrix self-profile update actions. Matrix uploads this file and sets the resulting MXC URI." }))
67
+ };
68
+ const MATRIX_PROFILE_MEDIA_SOURCE_PARAMS = Object.freeze(["avatarUrl", "avatarPath"]);
69
+ function createMatrixExposedActions(params) {
70
+ const actions = new Set(["poll", "poll-vote"]);
71
+ if (params.gate("messages")) {
72
+ actions.add("send");
73
+ actions.add("read");
74
+ actions.add("edit");
75
+ actions.add("delete");
76
+ }
77
+ if (params.gate("reactions")) {
78
+ actions.add("react");
79
+ actions.add("reactions");
80
+ }
81
+ if (params.gate("pins")) {
82
+ actions.add("pin");
83
+ actions.add("unpin");
84
+ actions.add("list-pins");
85
+ }
86
+ if (params.gate("profile") && params.senderIsOwner === true) actions.add("set-profile");
87
+ if (params.gate("memberInfo")) actions.add("member-info");
88
+ if (params.gate("channelInfo")) actions.add("channel-info");
89
+ if (params.encryptionEnabled && params.gate("verification")) actions.add("permissions");
90
+ return actions;
91
+ }
92
+ function buildMatrixProfileToolSchema() {
93
+ return {
94
+ actions: ["set-profile"],
95
+ properties: {
96
+ displayName: Type.Optional(Type.String({ description: "Profile display name for Matrix self-profile update actions." })),
97
+ display_name: Type.Optional(Type.String({ description: "snake_case alias of displayName for Matrix self-profile update actions." })),
98
+ ...MATRIX_PROFILE_MEDIA_PROPERTIES
99
+ }
100
+ };
101
+ }
102
+ const matrixMessageActions = {
103
+ describeMessageTool: ({ cfg, accountId, senderIsOwner }) => {
104
+ const resolvedCfg = cfg;
105
+ if (!accountId && requiresExplicitMatrixDefaultAccount(resolvedCfg)) return {
106
+ actions: [],
107
+ capabilities: []
108
+ };
109
+ const account = resolveMatrixAccount({
110
+ cfg: resolvedCfg,
111
+ accountId: accountId ?? resolveDefaultMatrixAccountId(resolvedCfg)
112
+ });
113
+ if (!account.enabled || !account.configured) return {
114
+ actions: [],
115
+ capabilities: []
116
+ };
117
+ const actions = createMatrixExposedActions({
118
+ gate: createActionGate(account.config.actions),
119
+ encryptionEnabled: account.config.encryption === true,
120
+ senderIsOwner
121
+ });
122
+ const listedActions = Array.from(actions);
123
+ return {
124
+ actions: listedActions,
125
+ capabilities: [],
126
+ schema: listedActions.includes("set-profile") ? buildMatrixProfileToolSchema() : null,
127
+ mediaSourceParams: listedActions.includes("set-profile") ? { "set-profile": MATRIX_PROFILE_MEDIA_SOURCE_PARAMS } : null
128
+ };
129
+ },
130
+ supportsAction: ({ action }) => MATRIX_PLUGIN_HANDLED_ACTIONS.has(action),
131
+ extractToolSend: ({ args }) => {
132
+ return extractToolSend(args, "sendMessage");
133
+ },
134
+ handleAction: async (ctx) => {
135
+ const { handleMatrixAction } = await import("./tool-actions.runtime-DDh2EP6z.js");
136
+ const { action, params, cfg, accountId, mediaLocalRoots } = ctx;
137
+ const dispatch = async (actionParams) => await handleMatrixAction({
138
+ ...actionParams,
139
+ ...accountId ? { accountId } : {}
140
+ }, cfg, { mediaLocalRoots });
141
+ const resolveRoomId = () => readStringParam(params, "roomId") ?? readStringParam(params, "channelId") ?? readStringParam(params, "to", { required: true });
142
+ if (action === "send") {
143
+ const to = readStringParam(params, "to", { required: true });
144
+ const mediaUrl = readStringParam(params, "media", { trim: false }) ?? readStringParam(params, "mediaUrl", { trim: false }) ?? readStringParam(params, "filePath", { trim: false }) ?? readStringParam(params, "path", { trim: false });
145
+ const content = readStringParam(params, "message", {
146
+ required: !mediaUrl,
147
+ allowEmpty: true
148
+ });
149
+ const replyTo = readStringParam(params, "replyTo");
150
+ const threadId = readStringParam(params, "threadId");
151
+ const audioAsVoice = typeof params.asVoice === "boolean" ? params.asVoice : typeof params.audioAsVoice === "boolean" ? params.audioAsVoice : void 0;
152
+ return await dispatch({
153
+ action: "sendMessage",
154
+ to,
155
+ content,
156
+ mediaUrl: mediaUrl ?? void 0,
157
+ replyToId: replyTo ?? void 0,
158
+ threadId: threadId ?? void 0,
159
+ audioAsVoice
160
+ });
161
+ }
162
+ if (action === "poll-vote") return await dispatch({
163
+ ...params,
164
+ action: "pollVote"
165
+ });
166
+ if (action === "react") {
167
+ const messageId = readStringParam(params, "messageId", { required: true });
168
+ const emoji = readStringParam(params, "emoji", { allowEmpty: true });
169
+ const remove = typeof params.remove === "boolean" ? params.remove : void 0;
170
+ return await dispatch({
171
+ action: "react",
172
+ roomId: resolveRoomId(),
173
+ messageId,
174
+ emoji,
175
+ remove
176
+ });
177
+ }
178
+ if (action === "reactions") {
179
+ const messageId = readStringParam(params, "messageId", { required: true });
180
+ const limit = readNumberParam(params, "limit", { integer: true });
181
+ return await dispatch({
182
+ action: "reactions",
183
+ roomId: resolveRoomId(),
184
+ messageId,
185
+ limit
186
+ });
187
+ }
188
+ if (action === "read") {
189
+ const limit = readNumberParam(params, "limit", { integer: true });
190
+ return await dispatch({
191
+ action: "readMessages",
192
+ roomId: resolveRoomId(),
193
+ limit,
194
+ before: readStringParam(params, "before"),
195
+ after: readStringParam(params, "after")
196
+ });
197
+ }
198
+ if (action === "edit") {
199
+ const messageId = readStringParam(params, "messageId", { required: true });
200
+ const content = readStringParam(params, "message", { required: true });
201
+ return await dispatch({
202
+ action: "editMessage",
203
+ roomId: resolveRoomId(),
204
+ messageId,
205
+ content
206
+ });
207
+ }
208
+ if (action === "delete") {
209
+ const messageId = readStringParam(params, "messageId", { required: true });
210
+ return await dispatch({
211
+ action: "deleteMessage",
212
+ roomId: resolveRoomId(),
213
+ messageId
214
+ });
215
+ }
216
+ if (action === "pin" || action === "unpin" || action === "list-pins") {
217
+ const messageId = action === "list-pins" ? void 0 : readStringParam(params, "messageId", { required: true });
218
+ return await dispatch({
219
+ action: action === "pin" ? "pinMessage" : action === "unpin" ? "unpinMessage" : "listPins",
220
+ roomId: resolveRoomId(),
221
+ messageId
222
+ });
223
+ }
224
+ if (action === "set-profile") {
225
+ if (ctx.senderIsOwner !== true) throw new ToolAuthorizationError("Matrix profile updates require owner access.");
226
+ const avatarPath = readStringParam(params, "avatarPath") ?? readStringParam(params, "path") ?? readStringParam(params, "filePath");
227
+ return await dispatch({
228
+ action: "setProfile",
229
+ displayName: readStringParam(params, "displayName") ?? readStringParam(params, "name"),
230
+ avatarUrl: readStringParam(params, "avatarUrl"),
231
+ avatarPath
232
+ });
233
+ }
234
+ if (action === "member-info") return await dispatch({
235
+ action: "memberInfo",
236
+ userId: readStringParam(params, "userId", { required: true }),
237
+ roomId: readStringParam(params, "roomId") ?? readStringParam(params, "channelId")
238
+ });
239
+ if (action === "channel-info") return await dispatch({
240
+ action: "channelInfo",
241
+ roomId: resolveRoomId()
242
+ });
243
+ if (action === "permissions") {
244
+ const operation = normalizeLowercaseStringOrEmpty(readStringParam(params, "operation") ?? readStringParam(params, "mode") ?? "verification-list");
245
+ const operationToAction = {
246
+ "encryption-status": "encryptionStatus",
247
+ "verification-status": "verificationStatus",
248
+ "verification-bootstrap": "verificationBootstrap",
249
+ "verification-recovery-key": "verificationRecoveryKey",
250
+ "verification-backup-status": "verificationBackupStatus",
251
+ "verification-backup-restore": "verificationBackupRestore",
252
+ "verification-list": "verificationList",
253
+ "verification-request": "verificationRequest",
254
+ "verification-accept": "verificationAccept",
255
+ "verification-cancel": "verificationCancel",
256
+ "verification-start": "verificationStart",
257
+ "verification-generate-qr": "verificationGenerateQr",
258
+ "verification-scan-qr": "verificationScanQr",
259
+ "verification-sas": "verificationSas",
260
+ "verification-confirm": "verificationConfirm",
261
+ "verification-mismatch": "verificationMismatch",
262
+ "verification-confirm-qr": "verificationConfirmQr"
263
+ };
264
+ const resolvedAction = operationToAction[operation];
265
+ if (!resolvedAction) throw new Error(`Unsupported Matrix permissions operation: ${operation}. Supported values: ${Object.keys(operationToAction).join(", ")}`);
266
+ return await dispatch({
267
+ ...params,
268
+ action: resolvedAction
269
+ });
270
+ }
271
+ throw new Error(`Action ${action} is not supported for provider matrix.`);
272
+ }
273
+ };
274
+ //#endregion
275
+ //#region extensions/matrix/src/approval-auth.ts
276
+ function getMatrixApprovalAuthApprovers(params) {
277
+ return resolveApprovalApprovers({
278
+ allowFrom: resolveMatrixAccount(params).config.dm?.allowFrom,
279
+ normalizeApprover: normalizeMatrixApproverId
280
+ });
281
+ }
282
+ const matrixApprovalAuth = createResolvedApproverActionAuthAdapter({
283
+ channelLabel: "Matrix",
284
+ resolveApprovers: ({ cfg, accountId }) => getMatrixApprovalAuthApprovers({
285
+ cfg,
286
+ accountId
287
+ }),
288
+ normalizeSenderId: (value) => normalizeMatrixApproverId(value)
289
+ });
290
+ //#endregion
291
+ //#region extensions/matrix/src/exec-approvals.ts
292
+ function normalizeMatrixExecApproverId(value) {
293
+ const normalized = normalizeMatrixApproverId(value);
294
+ return normalized === "*" ? void 0 : normalized;
295
+ }
296
+ function resolveMatrixExecApprovalConfig(params) {
297
+ const account = resolveMatrixAccount(params);
298
+ const config = account.config.execApprovals;
299
+ if (!config) return;
300
+ return {
301
+ ...config,
302
+ enabled: account.enabled && account.configured ? config.enabled : false
303
+ };
304
+ }
305
+ function countMatrixExecApprovalEligibleAccounts(params) {
306
+ return listMatrixAccountIds(params.cfg).filter((accountId) => {
307
+ const account = resolveMatrixAccount({
308
+ cfg: params.cfg,
309
+ accountId
310
+ });
311
+ if (!account.enabled || !account.configured) return false;
312
+ const config = resolveMatrixExecApprovalConfig({
313
+ cfg: params.cfg,
314
+ accountId
315
+ });
316
+ const filters = config?.enabled ? {
317
+ agentFilter: config.agentFilter,
318
+ sessionFilter: config.sessionFilter
319
+ } : {
320
+ agentFilter: void 0,
321
+ sessionFilter: void 0
322
+ };
323
+ return isChannelExecApprovalClientEnabledFromConfig({
324
+ enabled: config?.enabled,
325
+ approverCount: getMatrixApprovalApprovers({
326
+ cfg: params.cfg,
327
+ accountId,
328
+ approvalKind: params.approvalKind
329
+ }).length
330
+ }) && matchesApprovalRequestFilters({
331
+ request: params.request.request,
332
+ agentFilter: filters.agentFilter,
333
+ sessionFilter: filters.sessionFilter
334
+ });
335
+ }).length;
336
+ }
337
+ function matchesMatrixRequestAccount(params) {
338
+ const turnSourceChannel = normalizeLowercaseStringOrEmpty(params.request.request.turnSourceChannel);
339
+ const boundAccountId = resolveApprovalRequestChannelAccountId({
340
+ cfg: params.cfg,
341
+ request: params.request,
342
+ channel: "matrix"
343
+ });
344
+ if (turnSourceChannel && turnSourceChannel !== "matrix" && !boundAccountId) return countMatrixExecApprovalEligibleAccounts({
345
+ cfg: params.cfg,
346
+ request: params.request,
347
+ approvalKind: params.approvalKind
348
+ }) <= 1;
349
+ return !boundAccountId || !params.accountId || normalizeAccountId$1(boundAccountId) === normalizeAccountId$1(params.accountId);
350
+ }
351
+ function getMatrixExecApprovalApprovers(params) {
352
+ const account = resolveMatrixAccount(params).config;
353
+ return resolveApprovalApprovers({
354
+ explicit: account.execApprovals?.approvers,
355
+ allowFrom: account.dm?.allowFrom,
356
+ normalizeApprover: normalizeMatrixExecApproverId
357
+ });
358
+ }
359
+ function resolveMatrixApprovalKind(request) {
360
+ return request.id.startsWith("plugin:") ? "plugin" : "exec";
361
+ }
362
+ function getMatrixApprovalApprovers(params) {
363
+ if (params.approvalKind === "plugin") return getMatrixApprovalAuthApprovers({
364
+ cfg: params.cfg,
365
+ accountId: params.accountId
366
+ });
367
+ return getMatrixExecApprovalApprovers(params);
368
+ }
369
+ function isMatrixExecApprovalTargetRecipient(params) {
370
+ return isChannelExecApprovalTargetRecipient({
371
+ ...params,
372
+ channel: "matrix",
373
+ normalizeSenderId: normalizeMatrixApproverId,
374
+ matchTarget: ({ target, normalizedSenderId }) => normalizeMatrixApproverId(target.to) === normalizedSenderId
375
+ });
376
+ }
377
+ const matrixExecApprovalProfile = createChannelExecApprovalProfile({
378
+ resolveConfig: resolveMatrixExecApprovalConfig,
379
+ resolveApprovers: getMatrixExecApprovalApprovers,
380
+ normalizeSenderId: normalizeMatrixApproverId,
381
+ isTargetRecipient: isMatrixExecApprovalTargetRecipient,
382
+ matchesRequestAccount: (params) => matchesMatrixRequestAccount({
383
+ ...params,
384
+ approvalKind: "exec"
385
+ })
386
+ });
387
+ const isMatrixExecApprovalClientEnabled = matrixExecApprovalProfile.isClientEnabled;
388
+ matrixExecApprovalProfile.isApprover;
389
+ const isMatrixExecApprovalAuthorizedSender = matrixExecApprovalProfile.isAuthorizedSender;
390
+ const resolveMatrixExecApprovalTarget = matrixExecApprovalProfile.resolveTarget;
391
+ matrixExecApprovalProfile.shouldHandleRequest;
392
+ function isMatrixApprovalClientEnabled(params) {
393
+ if (params.approvalKind === "exec") return isMatrixExecApprovalClientEnabled(params);
394
+ return isChannelExecApprovalClientEnabledFromConfig({
395
+ enabled: resolveMatrixExecApprovalConfig(params)?.enabled,
396
+ approverCount: getMatrixApprovalApprovers(params).length
397
+ });
398
+ }
399
+ function isMatrixAnyApprovalClientEnabled(params) {
400
+ return isMatrixApprovalClientEnabled({
401
+ ...params,
402
+ approvalKind: "exec"
403
+ }) || isMatrixApprovalClientEnabled({
404
+ ...params,
405
+ approvalKind: "plugin"
406
+ });
407
+ }
408
+ function shouldHandleMatrixApprovalRequest(params) {
409
+ const approvalKind = resolveMatrixApprovalKind(params.request);
410
+ if (!matchesMatrixRequestAccount({
411
+ ...params,
412
+ approvalKind
413
+ })) return false;
414
+ const config = resolveMatrixExecApprovalConfig(params);
415
+ if (!isChannelExecApprovalClientEnabledFromConfig({
416
+ enabled: config?.enabled,
417
+ approverCount: getMatrixApprovalApprovers({
418
+ ...params,
419
+ approvalKind
420
+ }).length
421
+ })) return false;
422
+ return matchesApprovalRequestFilters({
423
+ request: params.request.request,
424
+ agentFilter: config?.agentFilter,
425
+ sessionFilter: config?.sessionFilter
426
+ });
427
+ }
428
+ function buildFilterCheckRequest(params) {
429
+ if (params.metadata.approvalKind === "plugin") return {
430
+ id: params.metadata.approvalId,
431
+ request: {
432
+ title: "Plugin Approval Required",
433
+ description: "",
434
+ agentId: params.metadata.agentId ?? null,
435
+ sessionKey: params.metadata.sessionKey ?? null
436
+ },
437
+ createdAtMs: 0,
438
+ expiresAtMs: 0
439
+ };
440
+ return {
441
+ id: params.metadata.approvalId,
442
+ request: {
443
+ command: "",
444
+ agentId: params.metadata.agentId ?? null,
445
+ sessionKey: params.metadata.sessionKey ?? null
446
+ },
447
+ createdAtMs: 0,
448
+ expiresAtMs: 0
449
+ };
450
+ }
451
+ function shouldSuppressLocalMatrixExecApprovalPrompt(params) {
452
+ if (!matrixExecApprovalProfile.shouldSuppressLocalPrompt(params)) return false;
453
+ const metadata = getExecApprovalReplyMetadata(params.payload);
454
+ if (!metadata) return false;
455
+ const request = buildFilterCheckRequest({ metadata });
456
+ return shouldHandleMatrixApprovalRequest({
457
+ cfg: params.cfg,
458
+ accountId: params.accountId,
459
+ request
460
+ });
461
+ }
462
+ //#endregion
463
+ //#region extensions/matrix/src/approval-native.ts
464
+ function normalizeComparableTarget(value) {
465
+ const target = resolveMatrixTargetIdentity(value);
466
+ if (!target) return normalizeLowercaseStringOrEmpty(value);
467
+ if (target.kind === "user") return `user:${normalizeMatrixUserId(target.id)}`;
468
+ return `${normalizeLowercaseStringOrEmpty(target.kind)}:${target.id}`;
469
+ }
470
+ function resolveMatrixNativeTarget(raw) {
471
+ const target = resolveMatrixTargetIdentity(raw);
472
+ if (!target) return null;
473
+ return target.kind === "user" ? `user:${target.id}` : `room:${target.id}`;
474
+ }
475
+ function resolveTurnSourceMatrixOriginTarget(request) {
476
+ const turnSourceChannel = normalizeLowercaseStringOrEmpty(request.request.turnSourceChannel);
477
+ const target = resolveMatrixNativeTarget(request.request.turnSourceTo?.trim() || "");
478
+ if (turnSourceChannel !== "matrix" || !target) return null;
479
+ return {
480
+ to: target,
481
+ threadId: normalizeOptionalStringifiedId(request.request.turnSourceThreadId)
482
+ };
483
+ }
484
+ function resolveSessionMatrixOriginTarget(sessionTarget) {
485
+ const target = resolveMatrixNativeTarget(sessionTarget.to);
486
+ if (!target) return null;
487
+ return {
488
+ to: target,
489
+ threadId: normalizeOptionalStringifiedId(sessionTarget.threadId)
490
+ };
491
+ }
492
+ function normalizeMatrixOriginTarget(target) {
493
+ return {
494
+ ...target,
495
+ to: normalizeComparableTarget(target.to)
496
+ };
497
+ }
498
+ function hasMatrixPluginApprovers(params) {
499
+ return getMatrixApprovalAuthApprovers(params).length > 0;
500
+ }
501
+ function availabilityState(enabled) {
502
+ return enabled ? { kind: "enabled" } : { kind: "disabled" };
503
+ }
504
+ function hasMatrixApprovalApprovers(params) {
505
+ return getMatrixApprovalApprovers({
506
+ cfg: params.cfg,
507
+ accountId: params.accountId,
508
+ approvalKind: params.approvalKind
509
+ }).length > 0;
510
+ }
511
+ function hasAnyMatrixApprovalApprovers(params) {
512
+ return getMatrixExecApprovalApprovers(params).length > 0 || getMatrixApprovalAuthApprovers(params).length > 0;
513
+ }
514
+ function isMatrixPluginAuthorizedSender(params) {
515
+ const normalizedSenderId = params.senderId ? normalizeMatrixApproverId(params.senderId) : void 0;
516
+ if (!normalizedSenderId) return false;
517
+ return getMatrixApprovalAuthApprovers(params).includes(normalizedSenderId);
518
+ }
519
+ function resolveSuppressionAccountId(params) {
520
+ return params.target.accountId?.trim() || params.request.request.turnSourceAccountId?.trim() || void 0;
521
+ }
522
+ const resolveMatrixOriginTarget = createChannelNativeOriginTargetResolver({
523
+ channel: "matrix",
524
+ shouldHandleRequest: ({ cfg, accountId, request }) => shouldHandleMatrixApprovalRequest({
525
+ cfg,
526
+ accountId,
527
+ request
528
+ }),
529
+ resolveTurnSourceTarget: resolveTurnSourceMatrixOriginTarget,
530
+ resolveSessionTarget: resolveSessionMatrixOriginTarget,
531
+ normalizeTargetForMatch: normalizeMatrixOriginTarget,
532
+ resolveFallbackTarget: (request) => {
533
+ const sessionConversation = resolveApprovalRequestSessionConversation({
534
+ request,
535
+ channel: "matrix"
536
+ });
537
+ if (!sessionConversation) return null;
538
+ const target = resolveMatrixNativeTarget(sessionConversation.id);
539
+ if (!target) return null;
540
+ return {
541
+ to: target,
542
+ threadId: normalizeOptionalStringifiedId(sessionConversation.threadId)
543
+ };
544
+ }
545
+ });
546
+ function resolveMatrixApproverDmTargets(params) {
547
+ if (!shouldHandleMatrixApprovalRequest(params)) return [];
548
+ return getMatrixApprovalApprovers(params).map((approver) => {
549
+ const normalized = normalizeMatrixUserId(approver);
550
+ return normalized ? { to: `user:${normalized}` } : null;
551
+ }).filter((target) => target !== null);
552
+ }
553
+ const matrixNativeApprovalCapability = createApproverRestrictedNativeApprovalCapability({
554
+ channel: "matrix",
555
+ channelLabel: "Matrix",
556
+ describeExecApprovalSetup: ({ accountId }) => {
557
+ const prefix = accountId && accountId !== "default" ? `channels.matrix.accounts.${accountId}` : "channels.matrix";
558
+ return `Approve it from the Web UI or terminal UI for now. Matrix supports native exec approvals for this account. Configure \`${prefix}.execApprovals.approvers\` or \`${prefix}.dm.allowFrom\`; leave \`${prefix}.execApprovals.enabled\` unset/\`auto\` or set it to \`true\`.`;
559
+ },
560
+ listAccountIds: listMatrixAccountIds,
561
+ hasApprovers: ({ cfg, accountId }) => hasAnyMatrixApprovalApprovers({
562
+ cfg,
563
+ accountId
564
+ }),
565
+ isExecAuthorizedSender: ({ cfg, accountId, senderId }) => isMatrixExecApprovalAuthorizedSender({
566
+ cfg,
567
+ accountId,
568
+ senderId
569
+ }),
570
+ isPluginAuthorizedSender: ({ cfg, accountId, senderId }) => isMatrixPluginAuthorizedSender({
571
+ cfg,
572
+ accountId,
573
+ senderId
574
+ }),
575
+ isNativeDeliveryEnabled: ({ cfg, accountId }) => isMatrixExecApprovalClientEnabled({
576
+ cfg,
577
+ accountId
578
+ }),
579
+ resolveNativeDeliveryMode: ({ cfg, accountId }) => resolveMatrixExecApprovalTarget({
580
+ cfg,
581
+ accountId
582
+ }),
583
+ requireMatchingTurnSourceChannel: true,
584
+ resolveSuppressionAccountId,
585
+ resolveOriginTarget: resolveMatrixOriginTarget,
586
+ resolveApproverDmTargets: resolveMatrixApproverDmTargets,
587
+ notifyOriginWhenDmOnly: true,
588
+ nativeRuntime: createLazyChannelApprovalNativeRuntimeAdapter({
589
+ eventKinds: ["exec", "plugin"],
590
+ isConfigured: ({ cfg, accountId }) => isMatrixAnyApprovalClientEnabled({
591
+ cfg,
592
+ accountId
593
+ }),
594
+ shouldHandle: ({ cfg, accountId, request }) => shouldHandleMatrixApprovalRequest({
595
+ cfg,
596
+ accountId,
597
+ request
598
+ }),
599
+ load: async () => (await import("./approval-handler.runtime-XgtgHryy.js")).matrixApprovalNativeRuntime
600
+ })
601
+ });
602
+ const splitMatrixApprovalCapability = splitChannelApprovalCapability(matrixNativeApprovalCapability);
603
+ const matrixBaseNativeApprovalAdapter = splitMatrixApprovalCapability.native;
604
+ const matrixBaseDeliveryAdapter = splitMatrixApprovalCapability.delivery;
605
+ const matrixDeliveryAdapter = matrixBaseDeliveryAdapter && {
606
+ ...matrixBaseDeliveryAdapter,
607
+ shouldSuppressForwardingFallback: (params) => {
608
+ const accountId = resolveSuppressionAccountId(params);
609
+ if (!hasMatrixApprovalApprovers({
610
+ cfg: params.cfg,
611
+ accountId,
612
+ approvalKind: params.approvalKind
613
+ })) return false;
614
+ return matrixBaseDeliveryAdapter.shouldSuppressForwardingFallback?.(params) ?? false;
615
+ }
616
+ };
617
+ const matrixNativeAdapter = matrixBaseNativeApprovalAdapter && {
618
+ describeDeliveryCapabilities: (params) => {
619
+ const capabilities = matrixBaseNativeApprovalAdapter.describeDeliveryCapabilities(params);
620
+ const hasApprovers = hasMatrixApprovalApprovers({
621
+ cfg: params.cfg,
622
+ accountId: params.accountId,
623
+ approvalKind: params.approvalKind
624
+ });
625
+ const clientEnabled = isMatrixApprovalClientEnabled({
626
+ cfg: params.cfg,
627
+ accountId: params.accountId,
628
+ approvalKind: params.approvalKind
629
+ });
630
+ return {
631
+ ...capabilities,
632
+ enabled: capabilities.enabled && hasApprovers && clientEnabled
633
+ };
634
+ },
635
+ resolveOriginTarget: matrixBaseNativeApprovalAdapter.resolveOriginTarget,
636
+ resolveApproverDmTargets: matrixBaseNativeApprovalAdapter.resolveApproverDmTargets
637
+ };
638
+ const matrixApprovalCapability = createChannelApprovalCapability({
639
+ authorizeActorAction: (params) => {
640
+ if (params.approvalKind !== "plugin") return matrixNativeApprovalCapability.authorizeActorAction?.(params) ?? { authorized: true };
641
+ if (!hasMatrixPluginApprovers({
642
+ cfg: params.cfg,
643
+ accountId: params.accountId
644
+ })) return {
645
+ authorized: false,
646
+ reason: "❌ Matrix plugin approvals are not enabled for this bot account."
647
+ };
648
+ return matrixApprovalAuth.authorizeActorAction(params);
649
+ },
650
+ getActionAvailabilityState: (params) => {
651
+ if (params.approvalKind === "plugin") return availabilityState(hasMatrixPluginApprovers({
652
+ cfg: params.cfg,
653
+ accountId: params.accountId
654
+ }));
655
+ return matrixNativeApprovalCapability.getActionAvailabilityState?.(params) ?? { kind: "disabled" };
656
+ },
657
+ getExecInitiatingSurfaceState: (params) => matrixNativeApprovalCapability.getExecInitiatingSurfaceState?.(params) ?? { kind: "disabled" },
658
+ describeExecApprovalSetup: matrixNativeApprovalCapability.describeExecApprovalSetup,
659
+ delivery: matrixDeliveryAdapter,
660
+ nativeRuntime: matrixNativeApprovalCapability.nativeRuntime,
661
+ native: matrixNativeAdapter,
662
+ render: matrixNativeApprovalCapability.render
663
+ });
664
+ //#endregion
665
+ //#region extensions/matrix/src/channel-account-paths.ts
666
+ function createMatrixProbeAccount(params) {
667
+ return async ({ account, timeoutMs, cfg }) => {
668
+ try {
669
+ const auth = await params.resolveMatrixAuth({
670
+ cfg,
671
+ accountId: account.accountId
672
+ });
673
+ return await params.probeMatrix({
674
+ homeserver: auth.homeserver,
675
+ accessToken: auth.accessToken,
676
+ userId: auth.userId,
677
+ deviceId: auth.deviceId,
678
+ timeoutMs: timeoutMs ?? 5e3,
679
+ accountId: account.accountId,
680
+ allowPrivateNetwork: auth.allowPrivateNetwork,
681
+ ssrfPolicy: auth.ssrfPolicy,
682
+ dispatcherPolicy: auth.dispatcherPolicy
683
+ });
684
+ } catch (err) {
685
+ return {
686
+ ok: false,
687
+ error: formatMatrixErrorMessage(err),
688
+ elapsedMs: 0
689
+ };
690
+ }
691
+ };
692
+ }
693
+ function createMatrixPairingText(sendMessageMatrix) {
694
+ return {
695
+ idLabel: "matrixUserId",
696
+ message: PAIRING_APPROVED_MESSAGE,
697
+ normalizeAllowEntry: createPairingPrefixStripper(/^matrix:/i),
698
+ notify: async ({ id, message, cfg, accountId }) => {
699
+ await sendMessageMatrix(`user:${id}`, message, {
700
+ cfg,
701
+ ...accountId ? { accountId } : {}
702
+ });
703
+ }
704
+ };
705
+ }
706
+ //#endregion
707
+ //#region extensions/matrix/src/matrix/monitor/rooms.ts
708
+ function readLegacyRoomAllowAlias(room) {
709
+ const rawRoom = room;
710
+ return typeof rawRoom?.allow === "boolean" ? rawRoom.allow : void 0;
711
+ }
712
+ function resolveMatrixRoomConfig(params) {
713
+ const rooms = params.rooms ?? {};
714
+ const allowlistConfigured = Object.keys(rooms).length > 0;
715
+ const { entry: matched, key: matchedKey, wildcardEntry, wildcardKey } = resolveChannelEntryMatch({
716
+ entries: rooms,
717
+ keys: buildChannelKeyCandidates(params.roomId, `room:${params.roomId}`, ...params.aliases),
718
+ wildcardKey: "*"
719
+ });
720
+ const resolved = matched ?? wildcardEntry;
721
+ const legacyAllow = readLegacyRoomAllowAlias(resolved);
722
+ return {
723
+ allowed: resolved ? resolved.enabled !== false && legacyAllow !== false : false,
724
+ allowlistConfigured,
725
+ config: resolved,
726
+ matchKey: matchedKey ?? wildcardKey,
727
+ matchSource: matched ? "direct" : wildcardEntry ? "wildcard" : void 0
728
+ };
729
+ }
730
+ //#endregion
731
+ //#region extensions/matrix/src/group-mentions.ts
732
+ function resolveMatrixRoomConfigForGroup(params) {
733
+ const roomId = normalizeMatrixResolvableTarget(params.groupId?.trim() ?? "");
734
+ const groupChannel = params.groupChannel?.trim() ?? "";
735
+ const aliases = groupChannel ? [normalizeMatrixResolvableTarget(groupChannel)] : [];
736
+ const cfg = params.cfg;
737
+ const matrixConfig = resolveMatrixAccountConfig({
738
+ cfg,
739
+ accountId: params.accountId
740
+ });
741
+ return resolveMatrixRoomConfig({
742
+ rooms: matrixConfig.groups ?? matrixConfig.rooms,
743
+ roomId,
744
+ aliases
745
+ }).config;
746
+ }
747
+ function resolveMatrixGroupRequireMention(params) {
748
+ const resolved = resolveMatrixRoomConfigForGroup(params);
749
+ if (resolved) {
750
+ if (resolved.autoReply === true) return false;
751
+ if (resolved.autoReply === false) return true;
752
+ if (typeof resolved.requireMention === "boolean") return resolved.requireMention;
753
+ }
754
+ return true;
755
+ }
756
+ function resolveMatrixGroupToolPolicy(params) {
757
+ return resolveMatrixRoomConfigForGroup(params)?.tools;
758
+ }
759
+ //#endregion
760
+ //#region extensions/matrix/src/resolver.ts
761
+ const loadMatrixChannelRuntime$1 = createLazyRuntimeNamedExport(() => import("./resolver.runtime-fPzzTZVJ.js"), "matrixResolverRuntime");
762
+ const matrixResolverAdapter = { resolveTargets: async ({ cfg, accountId, inputs, kind, runtime }) => (await loadMatrixChannelRuntime$1()).resolveMatrixTargets({
763
+ cfg,
764
+ accountId,
765
+ inputs,
766
+ kind,
767
+ runtime
768
+ }) };
769
+ //#endregion
770
+ //#region extensions/matrix/src/matrix/session-store-metadata.ts
771
+ function trimMaybeString(value) {
772
+ if (typeof value !== "string") return;
773
+ const trimmed = value.trim();
774
+ return trimmed.length > 0 ? trimmed : void 0;
775
+ }
776
+ function resolveMatrixRoomTargetId(value) {
777
+ const trimmed = trimMaybeString(value);
778
+ if (!trimmed) return;
779
+ const target = resolveMatrixTargetIdentity(trimmed);
780
+ return target?.kind === "room" && target.id.startsWith("!") ? target.id : void 0;
781
+ }
782
+ function resolveMatrixSessionAccountId(value) {
783
+ const trimmed = trimMaybeString(value);
784
+ return trimmed ? normalizeAccountId(trimmed) : void 0;
785
+ }
786
+ function resolveMatrixStoredRoomId(params) {
787
+ return resolveMatrixRoomTargetId(params.deliveryTo) ?? resolveMatrixRoomTargetId(params.lastTo) ?? resolveMatrixRoomTargetId(params.originNativeChannelId) ?? resolveMatrixRoomTargetId(params.originTo);
788
+ }
789
+ function resolveMatrixStoredSessionMeta(entry) {
790
+ if (!entry) return null;
791
+ const channel = trimMaybeString(entry.deliveryContext?.channel) ?? trimMaybeString(entry.lastChannel) ?? trimMaybeString(entry.origin?.provider);
792
+ const accountId = resolveMatrixSessionAccountId(entry.deliveryContext?.accountId ?? entry.lastAccountId ?? entry.origin?.accountId) ?? void 0;
793
+ const roomId = resolveMatrixStoredRoomId({
794
+ deliveryTo: entry.deliveryContext?.to,
795
+ lastTo: entry.lastTo,
796
+ originNativeChannelId: entry.origin?.nativeChannelId,
797
+ originTo: entry.origin?.to
798
+ });
799
+ const chatType = trimMaybeString(entry.origin?.chatType) ?? trimMaybeString(entry.chatType) ?? void 0;
800
+ const directUserId = chatType === "direct" ? trimMaybeString(entry.origin?.nativeDirectUserId) ?? resolveMatrixDirectUserId({
801
+ from: trimMaybeString(entry.origin?.from),
802
+ to: (roomId ? `room:${roomId}` : void 0) ?? trimMaybeString(entry.deliveryContext?.to) ?? trimMaybeString(entry.lastTo) ?? trimMaybeString(entry.origin?.to),
803
+ chatType
804
+ }) : void 0;
805
+ if (!channel && !accountId && !roomId && !directUserId) return null;
806
+ return {
807
+ ...channel ? { channel } : {},
808
+ ...accountId ? { accountId } : {},
809
+ ...roomId ? { roomId } : {},
810
+ ...directUserId ? { directUserId } : {}
811
+ };
812
+ }
813
+ //#endregion
814
+ //#region extensions/matrix/src/session-route.ts
815
+ function resolveEffectiveMatrixAccountId(params) {
816
+ return normalizeAccountId(params.accountId ?? resolveDefaultMatrixAccountId(params.cfg));
817
+ }
818
+ function resolveMatrixDmSessionScope(params) {
819
+ return resolveMatrixAccountConfig({
820
+ cfg: params.cfg,
821
+ accountId: params.accountId
822
+ }).dm?.sessionScope ?? "per-user";
823
+ }
824
+ function resolveMatrixCurrentDmRoomId(params) {
825
+ const sessionKey = parseThreadSessionSuffix(params.currentSessionKey).baseSessionKey ?? params.currentSessionKey?.trim();
826
+ if (!sessionKey) return;
827
+ try {
828
+ const existing = resolveSessionStoreEntry({
829
+ store: loadSessionStore(resolveStorePath(params.cfg.session?.store, { agentId: params.agentId })),
830
+ sessionKey
831
+ }).existing;
832
+ const currentSession = resolveMatrixStoredSessionMeta(existing);
833
+ if (!currentSession) return;
834
+ if (currentSession.accountId && currentSession.accountId !== params.accountId) return;
835
+ if (!currentSession.directUserId || currentSession.directUserId !== params.targetUserId) return;
836
+ return currentSession.roomId;
837
+ } catch {
838
+ return;
839
+ }
840
+ }
841
+ function resolveMatrixOutboundSessionRoute(params) {
842
+ const target = resolveMatrixTargetIdentity(params.resolvedTarget?.to ?? params.target) ?? resolveMatrixTargetIdentity(params.target);
843
+ if (!target) return null;
844
+ const effectiveAccountId = resolveEffectiveMatrixAccountId(params);
845
+ const roomScopedDmId = target.kind === "user" && resolveMatrixDmSessionScope({
846
+ cfg: params.cfg,
847
+ accountId: effectiveAccountId
848
+ }) === "per-room" ? resolveMatrixCurrentDmRoomId({
849
+ cfg: params.cfg,
850
+ agentId: params.agentId,
851
+ accountId: effectiveAccountId,
852
+ currentSessionKey: params.currentSessionKey,
853
+ targetUserId: target.id
854
+ }) : void 0;
855
+ const peer = roomScopedDmId !== void 0 ? {
856
+ kind: "channel",
857
+ id: roomScopedDmId
858
+ } : {
859
+ kind: target.kind === "user" ? "direct" : "channel",
860
+ id: target.id
861
+ };
862
+ const chatType = target.kind === "user" ? "direct" : "channel";
863
+ const from = target.kind === "user" ? `matrix:${target.id}` : `matrix:channel:${target.id}`;
864
+ const to = `room:${roomScopedDmId ?? target.id}`;
865
+ return buildThreadAwareOutboundSessionRoute({
866
+ route: buildChannelOutboundSessionRoute({
867
+ cfg: params.cfg,
868
+ agentId: params.agentId,
869
+ channel: "matrix",
870
+ accountId: effectiveAccountId,
871
+ peer,
872
+ chatType,
873
+ from,
874
+ to
875
+ }),
876
+ replyToId: params.replyToId,
877
+ threadId: params.threadId,
878
+ currentSessionKey: params.currentSessionKey,
879
+ normalizeThreadId: (threadId) => threadId,
880
+ canRecoverCurrentThread: ({ route }) => route.peer.kind !== "direct" || (params.cfg.session?.dmScope ?? "main") !== "main"
881
+ });
882
+ }
883
+ //#endregion
884
+ //#region extensions/matrix/src/startup-maintenance.ts
885
+ function logWarningOnlyMatrixMigrationReasons(params) {
886
+ if (params.status.legacyState && "warning" in params.status.legacyState) params.log.warn?.(`matrix: ${params.status.legacyState.warning}`);
887
+ if (params.status.legacyCrypto.warnings.length > 0) params.log.warn?.(`matrix: legacy encrypted-state warnings:\n${params.status.legacyCrypto.warnings.map((entry) => `- ${entry}`).join("\n")}`);
888
+ }
889
+ async function runBestEffortMatrixMigrationStep(params) {
890
+ try {
891
+ await params.run();
892
+ } catch (err) {
893
+ params.log.warn?.(`${params.logPrefix?.trim() || "gateway"}: ${params.label} failed during Matrix migration; continuing startup: ${String(err)}`);
894
+ }
895
+ }
896
+ async function runMatrixStartupMaintenance(params) {
897
+ const env = params.env ?? process.env;
898
+ const createSnapshot = params.deps?.maybeCreateMatrixMigrationSnapshot ?? maybeCreateMatrixMigrationSnapshot;
899
+ const migrateLegacyState = params.deps?.autoMigrateLegacyMatrixState ?? autoMigrateLegacyMatrixState;
900
+ const prepareLegacyCrypto = params.deps?.autoPrepareLegacyMatrixCrypto ?? autoPrepareLegacyMatrixCrypto;
901
+ const trigger = params.trigger?.trim() || "gateway-startup";
902
+ const logPrefix = params.logPrefix?.trim() || "gateway";
903
+ const migrationStatus = resolveMatrixMigrationStatus({
904
+ cfg: params.cfg,
905
+ env
906
+ });
907
+ if (!migrationStatus.pending) return;
908
+ if (!migrationStatus.actionable) {
909
+ params.log.info?.("matrix: migration remains in a warning-only state; no pre-migration snapshot was needed yet");
910
+ logWarningOnlyMatrixMigrationReasons({
911
+ status: migrationStatus,
912
+ log: params.log
913
+ });
914
+ return;
915
+ }
916
+ try {
917
+ await createSnapshot({
918
+ trigger,
919
+ env,
920
+ log: params.log
921
+ });
922
+ } catch (err) {
923
+ params.log.warn?.(`${logPrefix}: failed creating a Matrix migration snapshot; skipping Matrix migration for now: ${String(err)}`);
924
+ return;
925
+ }
926
+ await runBestEffortMatrixMigrationStep({
927
+ label: "legacy Matrix state migration",
928
+ log: params.log,
929
+ logPrefix,
930
+ run: () => migrateLegacyState({
931
+ cfg: params.cfg,
932
+ env,
933
+ log: params.log
934
+ })
935
+ });
936
+ await runBestEffortMatrixMigrationStep({
937
+ label: "legacy Matrix encrypted-state preparation",
938
+ log: params.log,
939
+ logPrefix,
940
+ run: () => prepareLegacyCrypto({
941
+ cfg: params.cfg,
942
+ env,
943
+ log: params.log
944
+ })
945
+ });
946
+ }
947
+ //#endregion
948
+ //#region extensions/matrix/src/channel.ts
949
+ let matrixStartupLock = Promise.resolve();
950
+ const loadMatrixSetupWizard = createLazyRuntimeNamedExport(() => import("./setup-surface-zTLHNBns.js").then((n) => n.t), "matrixSetupWizard");
951
+ const loadMatrixChannelRuntime = createLazyRuntimeNamedExport(() => import("./channel.runtime-BCl9atvS.js"), "matrixChannelRuntime");
952
+ const meta = {
953
+ id: "matrix",
954
+ label: "Matrix",
955
+ selectionLabel: "Matrix (plugin)",
956
+ docsPath: "/channels/matrix",
957
+ docsLabel: "matrix",
958
+ blurb: "open protocol; configure a homeserver + access token.",
959
+ order: 70,
960
+ quickstartAllowFrom: true
961
+ };
962
+ function buildMatrixTrafficStatusSummary(snapshot) {
963
+ return {
964
+ lastInboundAt: snapshot?.lastInboundAt ?? null,
965
+ lastOutboundAt: snapshot?.lastOutboundAt ?? null
966
+ };
967
+ }
968
+ const matrixDoctor = {
969
+ dmAllowFromMode: "nestedOnly",
970
+ groupModel: "sender",
971
+ groupAllowFromFallbackToAllowFrom: false,
972
+ warnOnEmptyGroupSenderAllowlist: true,
973
+ legacyConfigRules,
974
+ normalizeCompatibilityConfig,
975
+ runConfigSequence: async ({ cfg, env, shouldRepair }) => await (await import("./doctor-k53ce7TR.js")).runMatrixDoctorSequence({
976
+ cfg,
977
+ env,
978
+ shouldRepair
979
+ }),
980
+ cleanStaleConfig: async ({ cfg }) => await (await import("./doctor-k53ce7TR.js")).cleanStaleMatrixPluginConfig(cfg)
981
+ };
982
+ const listMatrixDirectoryPeersFromConfig = createResolvedDirectoryEntriesLister({
983
+ kind: "user",
984
+ resolveAccount: adaptScopedAccountAccessor(resolveMatrixAccount),
985
+ resolveSources: (account) => [
986
+ account.config.dm?.allowFrom ?? [],
987
+ account.config.groupAllowFrom ?? [],
988
+ ...Object.values(account.config.groups ?? account.config.rooms ?? {}).map((room) => room.users ?? [])
989
+ ],
990
+ normalizeId: (entry) => {
991
+ const raw = entry.replace(/^matrix:/i, "").trim();
992
+ if (!raw || raw === "*") return null;
993
+ const cleaned = normalizeLowercaseStringOrEmpty(raw).startsWith("user:") ? raw.slice(5).trim() : raw;
994
+ return cleaned.startsWith("@") ? `user:${cleaned}` : cleaned;
995
+ }
996
+ });
997
+ const listMatrixDirectoryGroupsFromConfig = createResolvedDirectoryEntriesLister({
998
+ kind: "group",
999
+ resolveAccount: adaptScopedAccountAccessor(resolveMatrixAccount),
1000
+ resolveSources: (account) => [Object.keys(account.config.groups ?? account.config.rooms ?? {})],
1001
+ normalizeId: (entry) => {
1002
+ const raw = entry.replace(/^matrix:/i, "").trim();
1003
+ if (!raw || raw === "*") return null;
1004
+ const lowered = normalizeLowercaseStringOrEmpty(raw);
1005
+ if (lowered.startsWith("room:") || lowered.startsWith("channel:")) return raw;
1006
+ return raw.startsWith("!") ? `room:${raw}` : raw;
1007
+ }
1008
+ });
1009
+ function projectMatrixConversationBinding(binding) {
1010
+ return {
1011
+ boundAt: binding.boundAt,
1012
+ lastActivityAt: typeof binding.metadata?.lastActivityAt === "number" ? binding.metadata.lastActivityAt : binding.boundAt,
1013
+ idleTimeoutMs: typeof binding.metadata?.idleTimeoutMs === "number" ? binding.metadata.idleTimeoutMs : void 0,
1014
+ maxAgeMs: typeof binding.metadata?.maxAgeMs === "number" ? binding.metadata.maxAgeMs : void 0
1015
+ };
1016
+ }
1017
+ const resolveMatrixDmPolicy = createScopedDmSecurityResolver({
1018
+ channelKey: "matrix",
1019
+ resolvePolicy: (account) => account.config.dm?.policy,
1020
+ resolveAllowFrom: (account) => account.config.dm?.allowFrom,
1021
+ allowFromPathSuffix: "dm.",
1022
+ normalizeEntry: (raw) => normalizeMatrixUserId(raw)
1023
+ });
1024
+ const collectMatrixSecurityWarnings = createAllowlistProviderOpenWarningCollector({
1025
+ providerConfigPresent: (cfg) => cfg.channels?.matrix !== void 0,
1026
+ resolveGroupPolicy: (account) => account.config.groupPolicy,
1027
+ buildOpenWarning: {
1028
+ surface: "Matrix rooms",
1029
+ openBehavior: "allows any room to trigger (mention-gated)",
1030
+ remediation: "Set channels.matrix.groupPolicy=\"allowlist\" + channels.matrix.groups (and optionally channels.matrix.groupAllowFrom) to restrict rooms"
1031
+ }
1032
+ });
1033
+ function resolveMatrixAccountConfigPath(accountId, field) {
1034
+ return accountId === DEFAULT_ACCOUNT_ID$2 ? `channels.matrix.${field}` : `channels.matrix.accounts.${accountId}.${field}`;
1035
+ }
1036
+ function collectMatrixSecurityWarningsForAccount(params) {
1037
+ const warnings = collectMatrixSecurityWarnings(params);
1038
+ if (params.account.accountId !== DEFAULT_ACCOUNT_ID$2) {
1039
+ const groupPolicyPath = resolveMatrixAccountConfigPath(params.account.accountId, "groupPolicy");
1040
+ const groupsPath = resolveMatrixAccountConfigPath(params.account.accountId, "groups");
1041
+ const groupAllowFromPath = resolveMatrixAccountConfigPath(params.account.accountId, "groupAllowFrom");
1042
+ return warnings.map((warning) => warning.replace("channels.matrix.groupPolicy", groupPolicyPath).replace("channels.matrix.groups", groupsPath).replace("channels.matrix.groupAllowFrom", groupAllowFromPath));
1043
+ }
1044
+ if (params.account.config.autoJoin !== "always") return warnings;
1045
+ const autoJoinPath = resolveMatrixAccountConfigPath(params.account.accountId, "autoJoin");
1046
+ const autoJoinAllowlistPath = resolveMatrixAccountConfigPath(params.account.accountId, "autoJoinAllowlist");
1047
+ return [...warnings, `- Matrix invites: autoJoin="always" joins any invited room before message policy applies. Set ${autoJoinPath}="allowlist" + ${autoJoinAllowlistPath} (or ${autoJoinPath}="off") to restrict joins.`];
1048
+ }
1049
+ function normalizeMatrixAcpConversationId(conversationId) {
1050
+ const target = resolveMatrixTargetIdentity(conversationId);
1051
+ if (!target || target.kind !== "room") return null;
1052
+ return { conversationId: target.id };
1053
+ }
1054
+ function matchMatrixAcpConversation(params) {
1055
+ const binding = normalizeMatrixAcpConversationId(params.bindingConversationId);
1056
+ if (!binding) return null;
1057
+ if (binding.conversationId === params.conversationId) return {
1058
+ conversationId: params.conversationId,
1059
+ matchPriority: 2
1060
+ };
1061
+ if (params.parentConversationId && params.parentConversationId !== params.conversationId && binding.conversationId === params.parentConversationId) return {
1062
+ conversationId: params.parentConversationId,
1063
+ matchPriority: 1
1064
+ };
1065
+ return null;
1066
+ }
1067
+ function resolveMatrixCommandConversation(params) {
1068
+ const parentConversationId = [
1069
+ params.originatingTo,
1070
+ params.commandTo,
1071
+ params.fallbackTo
1072
+ ].map((candidate) => {
1073
+ const trimmed = candidate?.trim();
1074
+ if (!trimmed) return;
1075
+ const target = resolveMatrixTargetIdentity(trimmed);
1076
+ return target?.kind === "room" ? target.id : void 0;
1077
+ }).find((candidate) => Boolean(candidate));
1078
+ if (params.threadId) return {
1079
+ conversationId: params.threadId,
1080
+ ...parentConversationId ? { parentConversationId } : {}
1081
+ };
1082
+ return parentConversationId ? { conversationId: parentConversationId } : null;
1083
+ }
1084
+ function resolveMatrixDeliveryTarget(params) {
1085
+ const parentConversationId = params.parentConversationId?.trim();
1086
+ if (parentConversationId && parentConversationId !== params.conversationId.trim()) {
1087
+ const parentTarget = resolveMatrixTargetIdentity(parentConversationId);
1088
+ if (parentTarget?.kind === "room") return {
1089
+ to: `room:${parentTarget.id}`,
1090
+ threadId: params.conversationId.trim()
1091
+ };
1092
+ }
1093
+ const conversationTarget = resolveMatrixTargetIdentity(params.conversationId);
1094
+ if (conversationTarget?.kind === "room") return { to: `room:${conversationTarget.id}` };
1095
+ return null;
1096
+ }
1097
+ const matrixChannelOutbound = {
1098
+ deliveryMode: "direct",
1099
+ chunker: chunkTextForOutbound,
1100
+ chunkerMode: "markdown",
1101
+ textChunkLimit: 4e3,
1102
+ deliveryCapabilities: { durableFinal: {
1103
+ text: true,
1104
+ media: true,
1105
+ replyTo: true,
1106
+ thread: true,
1107
+ messageSendingHooks: true
1108
+ } },
1109
+ presentationCapabilities: {
1110
+ supported: true,
1111
+ buttons: true,
1112
+ selects: true,
1113
+ context: true,
1114
+ divider: true,
1115
+ limits: { text: {
1116
+ markdownDialect: "markdown",
1117
+ supportsEdit: true
1118
+ } }
1119
+ },
1120
+ shouldSuppressLocalPayloadPrompt: ({ cfg, accountId, payload }) => shouldSuppressLocalMatrixExecApprovalPrompt({
1121
+ cfg,
1122
+ accountId,
1123
+ payload
1124
+ }),
1125
+ ...createRuntimeOutboundDelegates({
1126
+ getRuntime: loadMatrixChannelRuntime,
1127
+ renderPresentation: {
1128
+ resolve: (runtime) => runtime.matrixOutbound.renderPresentation,
1129
+ unavailableMessage: "Matrix outbound presentation rendering is unavailable"
1130
+ },
1131
+ sendPayload: {
1132
+ resolve: (runtime) => runtime.matrixOutbound.sendPayload,
1133
+ unavailableMessage: "Matrix outbound payload delivery is unavailable"
1134
+ },
1135
+ sendText: {
1136
+ resolve: (runtime) => runtime.matrixOutbound.sendText,
1137
+ unavailableMessage: "Matrix outbound text delivery is unavailable"
1138
+ },
1139
+ sendMedia: {
1140
+ resolve: (runtime) => runtime.matrixOutbound.sendMedia,
1141
+ unavailableMessage: "Matrix outbound media delivery is unavailable"
1142
+ },
1143
+ sendPoll: {
1144
+ resolve: (runtime) => runtime.matrixOutbound.sendPoll,
1145
+ unavailableMessage: "Matrix outbound poll delivery is unavailable"
1146
+ }
1147
+ })
1148
+ };
1149
+ const matrixMessageAdapter = createChannelMessageAdapterFromOutbound({
1150
+ id: "matrix",
1151
+ outbound: matrixChannelOutbound,
1152
+ live: {
1153
+ capabilities: {
1154
+ draftPreview: true,
1155
+ previewFinalization: true,
1156
+ progressUpdates: true,
1157
+ quietFinalization: true
1158
+ },
1159
+ finalizer: { capabilities: {
1160
+ finalEdit: true,
1161
+ normalFallback: true,
1162
+ discardPending: true,
1163
+ previewReceipt: true
1164
+ } }
1165
+ }
1166
+ });
1167
+ const matrixPlugin = createChatChannelPlugin({
1168
+ base: {
1169
+ id: "matrix",
1170
+ meta,
1171
+ setupWizard: createMatrixSetupWizardProxy(async () => ({ matrixSetupWizard: await loadMatrixSetupWizard() })),
1172
+ capabilities: {
1173
+ chatTypes: [
1174
+ "direct",
1175
+ "group",
1176
+ "thread"
1177
+ ],
1178
+ polls: true,
1179
+ reactions: true,
1180
+ threads: true,
1181
+ media: true,
1182
+ tts: { voice: { synthesisTarget: "voice-note" } }
1183
+ },
1184
+ reload: { configPrefixes: ["channels.matrix"] },
1185
+ configSchema: MatrixChannelConfigSchema,
1186
+ config: {
1187
+ ...matrixConfigAdapter,
1188
+ isConfigured: (account) => account.configured,
1189
+ describeAccount: (account) => describeAccountSnapshot({
1190
+ account,
1191
+ configured: account.configured,
1192
+ extra: { baseUrl: account.homeserver }
1193
+ })
1194
+ },
1195
+ approvalCapability: matrixApprovalCapability,
1196
+ groups: {
1197
+ resolveRequireMention: resolveMatrixGroupRequireMention,
1198
+ resolveToolPolicy: resolveMatrixGroupToolPolicy
1199
+ },
1200
+ conversationBindings: {
1201
+ supportsCurrentConversationBinding: true,
1202
+ defaultTopLevelPlacement: "child",
1203
+ setIdleTimeoutBySessionKey: ({ targetSessionKey, accountId, idleTimeoutMs }) => setMatrixThreadBindingIdleTimeoutBySessionKey({
1204
+ targetSessionKey,
1205
+ accountId: accountId ?? "",
1206
+ idleTimeoutMs
1207
+ }).map(projectMatrixConversationBinding),
1208
+ setMaxAgeBySessionKey: ({ targetSessionKey, accountId, maxAgeMs }) => setMatrixThreadBindingMaxAgeBySessionKey({
1209
+ targetSessionKey,
1210
+ accountId: accountId ?? "",
1211
+ maxAgeMs
1212
+ }).map(projectMatrixConversationBinding)
1213
+ },
1214
+ messaging: {
1215
+ defaultMarkdownTableMode: "bullets",
1216
+ targetPrefixes: ["matrix"],
1217
+ normalizeTarget: normalizeMatrixMessagingTarget,
1218
+ resolveInboundConversation: ({ to, conversationId, threadId }) => resolveMatrixInboundConversation({
1219
+ to,
1220
+ conversationId,
1221
+ threadId
1222
+ }),
1223
+ resolveDeliveryTarget: ({ conversationId, parentConversationId }) => resolveMatrixDeliveryTarget({
1224
+ conversationId,
1225
+ parentConversationId
1226
+ }),
1227
+ resolveOutboundSessionRoute: (params) => resolveMatrixOutboundSessionRoute(params),
1228
+ targetResolver: {
1229
+ looksLikeId: (raw) => {
1230
+ const trimmed = raw.trim();
1231
+ if (!trimmed) return false;
1232
+ if (/^(matrix:)?[!#@]/i.test(trimmed)) return true;
1233
+ return trimmed.includes(":");
1234
+ },
1235
+ hint: "<room|alias|user>"
1236
+ }
1237
+ },
1238
+ directory: createChannelDirectoryAdapter({
1239
+ listPeers: async (params) => {
1240
+ return (await listMatrixDirectoryPeersFromConfig(params)).map((entry) => {
1241
+ const raw = entry.id.startsWith("user:") ? entry.id.slice(5) : entry.id;
1242
+ return !raw.startsWith("@") || !raw.includes(":") ? Object.assign({}, entry, { name: `incomplete id; expected @user:server` }) : entry;
1243
+ });
1244
+ },
1245
+ listGroups: async (params) => await listMatrixDirectoryGroupsFromConfig(params),
1246
+ ...createRuntimeDirectoryLiveAdapter({
1247
+ getRuntime: loadMatrixChannelRuntime,
1248
+ listPeersLive: (runtime) => runtime.listMatrixDirectoryPeersLive,
1249
+ listGroupsLive: (runtime) => runtime.listMatrixDirectoryGroupsLive
1250
+ })
1251
+ }),
1252
+ resolver: matrixResolverAdapter,
1253
+ actions: matrixMessageActions,
1254
+ message: matrixMessageAdapter,
1255
+ secrets: {
1256
+ secretTargetRegistryEntries,
1257
+ collectRuntimeConfigAssignments
1258
+ },
1259
+ setup: {
1260
+ ...matrixSetupAdapter,
1261
+ singleAccountKeysToMove,
1262
+ namedAccountPromotionKeys,
1263
+ resolveSingleAccountPromotionTarget
1264
+ },
1265
+ bindings: {
1266
+ compileConfiguredBinding: ({ conversationId }) => normalizeMatrixAcpConversationId(conversationId),
1267
+ matchInboundConversation: ({ compiledBinding, conversationId, parentConversationId }) => matchMatrixAcpConversation({
1268
+ bindingConversationId: compiledBinding.conversationId,
1269
+ conversationId,
1270
+ parentConversationId
1271
+ }),
1272
+ resolveCommandConversation: ({ threadId, originatingTo, commandTo, fallbackTo }) => resolveMatrixCommandConversation({
1273
+ threadId,
1274
+ originatingTo,
1275
+ commandTo,
1276
+ fallbackTo
1277
+ })
1278
+ },
1279
+ status: createComputedAccountStatusAdapter({
1280
+ defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID$2),
1281
+ collectStatusIssues: (accounts) => collectStatusIssuesFromLastError("matrix", accounts),
1282
+ buildChannelSummary: ({ snapshot }) => buildProbeChannelStatusSummary(snapshot, { baseUrl: snapshot.baseUrl ?? null }),
1283
+ probeAccount: async ({ account, timeoutMs, cfg }) => await createMatrixProbeAccount({
1284
+ resolveMatrixAuth: async ({ cfg, accountId }) => (await loadMatrixChannelRuntime()).resolveMatrixAuth({
1285
+ cfg,
1286
+ accountId
1287
+ }),
1288
+ probeMatrix: async (params) => await (await loadMatrixChannelRuntime()).probeMatrix(params)
1289
+ })({
1290
+ account,
1291
+ timeoutMs,
1292
+ cfg
1293
+ }),
1294
+ resolveAccountSnapshot: ({ account, runtime }) => ({
1295
+ accountId: account.accountId,
1296
+ name: account.name,
1297
+ enabled: account.enabled,
1298
+ configured: account.configured,
1299
+ extra: {
1300
+ baseUrl: account.homeserver,
1301
+ lastProbeAt: runtime?.lastProbeAt ?? null,
1302
+ ...buildMatrixTrafficStatusSummary(runtime)
1303
+ }
1304
+ })
1305
+ }),
1306
+ gateway: { startAccount: async (ctx) => {
1307
+ const account = ctx.account;
1308
+ ctx.setStatus({
1309
+ accountId: account.accountId,
1310
+ baseUrl: account.homeserver
1311
+ });
1312
+ ctx.log?.info(`[${account.accountId}] starting provider (${account.homeserver ?? "matrix"})`);
1313
+ const previousLock = matrixStartupLock;
1314
+ let releaseLock = () => {};
1315
+ matrixStartupLock = new Promise((resolve) => {
1316
+ releaseLock = resolve;
1317
+ });
1318
+ await previousLock;
1319
+ let monitorMatrixProvider;
1320
+ try {
1321
+ monitorMatrixProvider = (await import("./monitor-9_MYVUk0.js")).monitorMatrixProvider;
1322
+ } finally {
1323
+ releaseLock();
1324
+ }
1325
+ return monitorMatrixProvider({
1326
+ runtime: ctx.runtime,
1327
+ channelRuntime: ctx.channelRuntime,
1328
+ abortSignal: ctx.abortSignal,
1329
+ mediaMaxMb: account.config.mediaMaxMb,
1330
+ initialSyncLimit: account.config.initialSyncLimit,
1331
+ replyToMode: account.config.replyToMode,
1332
+ accountId: account.accountId,
1333
+ setStatus: ctx.setStatus
1334
+ });
1335
+ } },
1336
+ doctor: matrixDoctor,
1337
+ lifecycle: { runStartupMaintenance: runMatrixStartupMaintenance },
1338
+ heartbeat: {
1339
+ sendTyping: async ({ cfg, to, accountId }) => {
1340
+ await (await loadMatrixChannelRuntime()).sendTypingMatrix(to, true, {
1341
+ cfg,
1342
+ ...accountId ? { accountId } : {}
1343
+ });
1344
+ },
1345
+ clearTyping: async ({ cfg, to, accountId }) => {
1346
+ await (await loadMatrixChannelRuntime()).sendTypingMatrix(to, false, {
1347
+ cfg,
1348
+ ...accountId ? { accountId } : {}
1349
+ });
1350
+ }
1351
+ }
1352
+ },
1353
+ security: {
1354
+ resolveDmPolicy: resolveMatrixDmPolicy,
1355
+ collectWarnings: projectAccountConfigWarningCollector((cfg) => cfg, collectMatrixSecurityWarningsForAccount)
1356
+ },
1357
+ pairing: { text: createMatrixPairingText(async (to, message, options) => await (await loadMatrixChannelRuntime()).sendMessageMatrix(to, message, options)) },
1358
+ threading: {
1359
+ resolveReplyToMode: createScopedAccountReplyToModeResolver({
1360
+ resolveAccount: adaptScopedAccountAccessor(resolveMatrixAccountConfig),
1361
+ resolveReplyToMode: (account) => account.replyToMode
1362
+ }),
1363
+ buildToolContext: ({ context, hasRepliedRef }) => {
1364
+ const currentTarget = context.To;
1365
+ return {
1366
+ currentChannelId: normalizeOptionalString(currentTarget),
1367
+ currentThreadTs: context.MessageThreadId != null ? String(context.MessageThreadId) : void 0,
1368
+ currentDirectUserId: resolveMatrixDirectUserId({
1369
+ from: context.From,
1370
+ to: context.To,
1371
+ chatType: context.ChatType
1372
+ }),
1373
+ hasRepliedRef
1374
+ };
1375
+ }
1376
+ },
1377
+ outbound: matrixChannelOutbound
1378
+ });
1379
+ //#endregion
1380
+ export { shouldHandleMatrixApprovalRequest as _, buildAllowlistResolutionSummary as a, createTypingCallbacks as c, logInboundDrop as d, logTypingFailure as f, isMatrixAnyApprovalClientEnabled as g, toLocationContext as h, addAllowlistUserEntriesFromConfigEntry as i, formatLocationText as l, summarizeMapping as m, resolveMatrixStoredSessionMeta as n, canonicalizeAllowlistWithResolvedIds as o, patchAllowlistUsersInConfigEntries as p, resolveMatrixRoomConfig as r, createReplyPrefixOptions as s, matrixPlugin as t, getAgentScopedMediaLocalRoots as u };