@gakr-gakr/matrix 0.1.0

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 (205) hide show
  1. package/CHANGELOG.md +285 -0
  2. package/SPEC-SUPPORT.md +116 -0
  3. package/api.ts +38 -0
  4. package/auth-presence.ts +56 -0
  5. package/autobot.plugin.json +28 -0
  6. package/channel-plugin-api.ts +3 -0
  7. package/cli-metadata.ts +11 -0
  8. package/contract-api.ts +17 -0
  9. package/doctor-contract-api.ts +1 -0
  10. package/helper-api.ts +3 -0
  11. package/index.ts +55 -0
  12. package/package.json +101 -0
  13. package/plugin-entry.handlers.runtime.ts +1 -0
  14. package/runtime-api.ts +72 -0
  15. package/runtime-heavy-api.ts +1 -0
  16. package/runtime-setter-api.ts +3 -0
  17. package/secret-contract-api.ts +5 -0
  18. package/setup-entry.ts +17 -0
  19. package/setup-plugin-api.ts +3 -0
  20. package/src/account-selection.ts +223 -0
  21. package/src/actions.ts +346 -0
  22. package/src/approval-auth.ts +25 -0
  23. package/src/approval-handler.runtime.ts +595 -0
  24. package/src/approval-ids.ts +6 -0
  25. package/src/approval-native.ts +348 -0
  26. package/src/approval-reaction-auth.ts +45 -0
  27. package/src/approval-reactions.ts +313 -0
  28. package/src/auth-precedence.ts +61 -0
  29. package/src/channel-account-paths.ts +97 -0
  30. package/src/channel.runtime.ts +17 -0
  31. package/src/channel.setup.ts +48 -0
  32. package/src/channel.ts +667 -0
  33. package/src/cli-metadata.ts +19 -0
  34. package/src/cli.ts +2298 -0
  35. package/src/config-adapter.ts +41 -0
  36. package/src/config-schema.ts +159 -0
  37. package/src/config-ui-hints.ts +56 -0
  38. package/src/directory-live.ts +238 -0
  39. package/src/doctor-contract.ts +287 -0
  40. package/src/doctor.ts +262 -0
  41. package/src/env-vars.ts +92 -0
  42. package/src/exec-approval-resolver.ts +23 -0
  43. package/src/exec-approvals.ts +293 -0
  44. package/src/group-mentions.ts +41 -0
  45. package/src/legacy-crypto-inspector-availability.ts +60 -0
  46. package/src/legacy-crypto.ts +531 -0
  47. package/src/legacy-state.ts +156 -0
  48. package/src/matrix/account-config.ts +175 -0
  49. package/src/matrix/accounts.ts +194 -0
  50. package/src/matrix/actions/client.ts +31 -0
  51. package/src/matrix/actions/devices.ts +34 -0
  52. package/src/matrix/actions/limits.ts +6 -0
  53. package/src/matrix/actions/messages.ts +129 -0
  54. package/src/matrix/actions/pins.ts +63 -0
  55. package/src/matrix/actions/polls.ts +109 -0
  56. package/src/matrix/actions/profile.ts +37 -0
  57. package/src/matrix/actions/reactions.ts +59 -0
  58. package/src/matrix/actions/room.ts +71 -0
  59. package/src/matrix/actions/summary.ts +88 -0
  60. package/src/matrix/actions/types.ts +63 -0
  61. package/src/matrix/actions/verification.ts +589 -0
  62. package/src/matrix/actions.ts +37 -0
  63. package/src/matrix/active-client.ts +26 -0
  64. package/src/matrix/async-lock.ts +18 -0
  65. package/src/matrix/backup-health.ts +124 -0
  66. package/src/matrix/client/config-runtime-api.ts +9 -0
  67. package/src/matrix/client/config-secret-input.runtime.ts +1 -0
  68. package/src/matrix/client/config.ts +853 -0
  69. package/src/matrix/client/create-client.ts +105 -0
  70. package/src/matrix/client/env-auth.ts +95 -0
  71. package/src/matrix/client/file-sync-store.ts +289 -0
  72. package/src/matrix/client/logging.ts +140 -0
  73. package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
  74. package/src/matrix/client/private-network-host.ts +1 -0
  75. package/src/matrix/client/runtime.ts +4 -0
  76. package/src/matrix/client/shared.ts +316 -0
  77. package/src/matrix/client/storage.ts +543 -0
  78. package/src/matrix/client/types.ts +50 -0
  79. package/src/matrix/client/url-validation.ts +76 -0
  80. package/src/matrix/client-bootstrap.ts +173 -0
  81. package/src/matrix/client.ts +23 -0
  82. package/src/matrix/config-paths.ts +31 -0
  83. package/src/matrix/config-update.ts +292 -0
  84. package/src/matrix/credentials-read.ts +207 -0
  85. package/src/matrix/credentials-write.runtime.ts +35 -0
  86. package/src/matrix/credentials.ts +95 -0
  87. package/src/matrix/deps.ts +309 -0
  88. package/src/matrix/device-health.ts +31 -0
  89. package/src/matrix/direct-management.ts +349 -0
  90. package/src/matrix/direct-room.ts +128 -0
  91. package/src/matrix/draft-stream.ts +225 -0
  92. package/src/matrix/encryption-guidance.ts +24 -0
  93. package/src/matrix/errors.ts +21 -0
  94. package/src/matrix/format.ts +426 -0
  95. package/src/matrix/legacy-crypto-inspector.ts +95 -0
  96. package/src/matrix/media-errors.ts +20 -0
  97. package/src/matrix/media-text.ts +162 -0
  98. package/src/matrix/monitor/access-state.ts +145 -0
  99. package/src/matrix/monitor/ack-config.ts +27 -0
  100. package/src/matrix/monitor/allowlist.ts +92 -0
  101. package/src/matrix/monitor/auto-join.ts +86 -0
  102. package/src/matrix/monitor/config.ts +569 -0
  103. package/src/matrix/monitor/context-summary.ts +43 -0
  104. package/src/matrix/monitor/direct.ts +296 -0
  105. package/src/matrix/monitor/events.ts +397 -0
  106. package/src/matrix/monitor/handler.ts +2271 -0
  107. package/src/matrix/monitor/inbound-dedupe.ts +267 -0
  108. package/src/matrix/monitor/index.ts +540 -0
  109. package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
  110. package/src/matrix/monitor/location.ts +108 -0
  111. package/src/matrix/monitor/media.ts +119 -0
  112. package/src/matrix/monitor/mentions.ts +256 -0
  113. package/src/matrix/monitor/reaction-events.ts +197 -0
  114. package/src/matrix/monitor/recent-invite.ts +30 -0
  115. package/src/matrix/monitor/replies.ts +136 -0
  116. package/src/matrix/monitor/reply-context.ts +92 -0
  117. package/src/matrix/monitor/room-history.ts +301 -0
  118. package/src/matrix/monitor/room-info.ts +126 -0
  119. package/src/matrix/monitor/rooms.ts +52 -0
  120. package/src/matrix/monitor/route.ts +179 -0
  121. package/src/matrix/monitor/runtime-api.ts +28 -0
  122. package/src/matrix/monitor/startup-verification.ts +237 -0
  123. package/src/matrix/monitor/startup.ts +218 -0
  124. package/src/matrix/monitor/status.ts +120 -0
  125. package/src/matrix/monitor/sync-lifecycle.ts +91 -0
  126. package/src/matrix/monitor/task-runner.ts +38 -0
  127. package/src/matrix/monitor/test-events.ts +21 -0
  128. package/src/matrix/monitor/thread-context.ts +108 -0
  129. package/src/matrix/monitor/threads.ts +85 -0
  130. package/src/matrix/monitor/types.ts +30 -0
  131. package/src/matrix/monitor/verification-events.ts +643 -0
  132. package/src/matrix/monitor/verification-utils.ts +46 -0
  133. package/src/matrix/outbound-media-runtime.ts +1 -0
  134. package/src/matrix/poll-summary.ts +110 -0
  135. package/src/matrix/poll-types.ts +429 -0
  136. package/src/matrix/probe.runtime.ts +4 -0
  137. package/src/matrix/probe.ts +97 -0
  138. package/src/matrix/profile.ts +184 -0
  139. package/src/matrix/reaction-common.ts +147 -0
  140. package/src/matrix/sdk/crypto-bootstrap.ts +438 -0
  141. package/src/matrix/sdk/crypto-facade.ts +242 -0
  142. package/src/matrix/sdk/crypto-node.runtime.ts +17 -0
  143. package/src/matrix/sdk/crypto-runtime.ts +14 -0
  144. package/src/matrix/sdk/decrypt-bridge.ts +410 -0
  145. package/src/matrix/sdk/event-helpers.ts +83 -0
  146. package/src/matrix/sdk/http-client.ts +87 -0
  147. package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
  148. package/src/matrix/sdk/idb-persistence.ts +286 -0
  149. package/src/matrix/sdk/logger.ts +108 -0
  150. package/src/matrix/sdk/read-response-with-limit.ts +19 -0
  151. package/src/matrix/sdk/recovery-key-store.ts +453 -0
  152. package/src/matrix/sdk/timeout-abort-signal.ts +1 -0
  153. package/src/matrix/sdk/transport-runtime-api.ts +18 -0
  154. package/src/matrix/sdk/transport.ts +352 -0
  155. package/src/matrix/sdk/types.ts +245 -0
  156. package/src/matrix/sdk/verification-manager.ts +795 -0
  157. package/src/matrix/sdk/verification-status.ts +23 -0
  158. package/src/matrix/sdk.ts +2152 -0
  159. package/src/matrix/send/client.ts +93 -0
  160. package/src/matrix/send/formatting.ts +189 -0
  161. package/src/matrix/send/media.ts +244 -0
  162. package/src/matrix/send/targets.ts +104 -0
  163. package/src/matrix/send/types.ts +131 -0
  164. package/src/matrix/send.ts +660 -0
  165. package/src/matrix/session-store-metadata.ts +108 -0
  166. package/src/matrix/startup-abort.ts +44 -0
  167. package/src/matrix/subagent-hooks.ts +308 -0
  168. package/src/matrix/sync-state.ts +27 -0
  169. package/src/matrix/target-ids.ts +79 -0
  170. package/src/matrix/thread-bindings-shared.ts +206 -0
  171. package/src/matrix/thread-bindings.ts +580 -0
  172. package/src/matrix-migration.runtime.ts +9 -0
  173. package/src/migration-config.ts +243 -0
  174. package/src/migration-snapshot-backup.ts +116 -0
  175. package/src/migration-snapshot.ts +53 -0
  176. package/src/onboarding.ts +775 -0
  177. package/src/outbound.ts +248 -0
  178. package/src/plugin-entry.runtime.js +115 -0
  179. package/src/plugin-entry.runtime.ts +70 -0
  180. package/src/profile-update.ts +71 -0
  181. package/src/record-shared.ts +3 -0
  182. package/src/resolve-targets.ts +175 -0
  183. package/src/resolver.runtime.ts +5 -0
  184. package/src/resolver.ts +21 -0
  185. package/src/runtime-api.ts +106 -0
  186. package/src/runtime.ts +13 -0
  187. package/src/secret-contract.ts +174 -0
  188. package/src/session-route.ts +126 -0
  189. package/src/setup-bootstrap.ts +102 -0
  190. package/src/setup-config.ts +222 -0
  191. package/src/setup-contract.ts +90 -0
  192. package/src/setup-core.ts +146 -0
  193. package/src/setup-dm-policy.ts +15 -0
  194. package/src/setup-surface.ts +4 -0
  195. package/src/startup-maintenance.ts +114 -0
  196. package/src/storage-paths.ts +92 -0
  197. package/src/thread-binding-api.ts +23 -0
  198. package/src/tool-actions.runtime.ts +1 -0
  199. package/src/tool-actions.ts +498 -0
  200. package/src/types.ts +257 -0
  201. package/subagent-hooks-api.ts +31 -0
  202. package/test-api.ts +21 -0
  203. package/thread-binding-api.ts +4 -0
  204. package/thread-bindings-runtime.ts +4 -0
  205. package/tsconfig.json +16 -0
@@ -0,0 +1,108 @@
1
+ import { normalizeAccountId } from "autobot/plugin-sdk/account-id";
2
+ import { resolveMatrixDirectUserId, resolveMatrixTargetIdentity } from "./target-ids.js";
3
+
4
+ function trimMaybeString(value: unknown): string | undefined {
5
+ if (typeof value !== "string") {
6
+ return undefined;
7
+ }
8
+ const trimmed = value.trim();
9
+ return trimmed.length > 0 ? trimmed : undefined;
10
+ }
11
+
12
+ function resolveMatrixRoomTargetId(value: unknown): string | undefined {
13
+ const trimmed = trimMaybeString(value);
14
+ if (!trimmed) {
15
+ return undefined;
16
+ }
17
+ const target = resolveMatrixTargetIdentity(trimmed);
18
+ return target?.kind === "room" && target.id.startsWith("!") ? target.id : undefined;
19
+ }
20
+
21
+ function resolveMatrixSessionAccountId(value: unknown): string | undefined {
22
+ const trimmed = trimMaybeString(value);
23
+ return trimmed ? normalizeAccountId(trimmed) : undefined;
24
+ }
25
+
26
+ function resolveMatrixStoredRoomId(params: {
27
+ deliveryTo?: unknown;
28
+ lastTo?: unknown;
29
+ originNativeChannelId?: unknown;
30
+ originTo?: unknown;
31
+ }): string | undefined {
32
+ return (
33
+ resolveMatrixRoomTargetId(params.deliveryTo) ??
34
+ resolveMatrixRoomTargetId(params.lastTo) ??
35
+ resolveMatrixRoomTargetId(params.originNativeChannelId) ??
36
+ resolveMatrixRoomTargetId(params.originTo)
37
+ );
38
+ }
39
+
40
+ type MatrixStoredSessionEntryLike = {
41
+ deliveryContext?: {
42
+ channel?: unknown;
43
+ to?: unknown;
44
+ accountId?: unknown;
45
+ };
46
+ origin?: {
47
+ provider?: unknown;
48
+ from?: unknown;
49
+ to?: unknown;
50
+ nativeChannelId?: unknown;
51
+ nativeDirectUserId?: unknown;
52
+ accountId?: unknown;
53
+ chatType?: unknown;
54
+ };
55
+ lastChannel?: unknown;
56
+ lastTo?: unknown;
57
+ lastAccountId?: unknown;
58
+ chatType?: unknown;
59
+ };
60
+
61
+ export function resolveMatrixStoredSessionMeta(entry?: MatrixStoredSessionEntryLike): {
62
+ channel?: string;
63
+ accountId?: string;
64
+ roomId?: string;
65
+ directUserId?: string;
66
+ } | null {
67
+ if (!entry) {
68
+ return null;
69
+ }
70
+ const channel =
71
+ trimMaybeString(entry.deliveryContext?.channel) ??
72
+ trimMaybeString(entry.lastChannel) ??
73
+ trimMaybeString(entry.origin?.provider);
74
+ const accountId =
75
+ resolveMatrixSessionAccountId(
76
+ entry.deliveryContext?.accountId ?? entry.lastAccountId ?? entry.origin?.accountId,
77
+ ) ?? undefined;
78
+ const roomId = resolveMatrixStoredRoomId({
79
+ deliveryTo: entry.deliveryContext?.to,
80
+ lastTo: entry.lastTo,
81
+ originNativeChannelId: entry.origin?.nativeChannelId,
82
+ originTo: entry.origin?.to,
83
+ });
84
+ const chatType =
85
+ trimMaybeString(entry.origin?.chatType) ?? trimMaybeString(entry.chatType) ?? undefined;
86
+ const directUserId =
87
+ chatType === "direct"
88
+ ? (trimMaybeString(entry.origin?.nativeDirectUserId) ??
89
+ resolveMatrixDirectUserId({
90
+ from: trimMaybeString(entry.origin?.from),
91
+ to:
92
+ (roomId ? `room:${roomId}` : undefined) ??
93
+ trimMaybeString(entry.deliveryContext?.to) ??
94
+ trimMaybeString(entry.lastTo) ??
95
+ trimMaybeString(entry.origin?.to),
96
+ chatType,
97
+ }))
98
+ : undefined;
99
+ if (!channel && !accountId && !roomId && !directUserId) {
100
+ return null;
101
+ }
102
+ return {
103
+ ...(channel ? { channel } : {}),
104
+ ...(accountId ? { accountId } : {}),
105
+ ...(roomId ? { roomId } : {}),
106
+ ...(directUserId ? { directUserId } : {}),
107
+ };
108
+ }
@@ -0,0 +1,44 @@
1
+ export function createMatrixStartupAbortError(): Error {
2
+ const error = new Error("Matrix startup aborted");
3
+ error.name = "AbortError";
4
+ return error;
5
+ }
6
+
7
+ export function throwIfMatrixStartupAborted(abortSignal?: AbortSignal): void {
8
+ if (abortSignal?.aborted === true) {
9
+ throw createMatrixStartupAbortError();
10
+ }
11
+ }
12
+
13
+ export function isMatrixStartupAbortError(error: unknown): boolean {
14
+ return error instanceof Error && error.name === "AbortError";
15
+ }
16
+
17
+ export async function awaitMatrixStartupWithAbort<T>(
18
+ promise: Promise<T>,
19
+ abortSignal?: AbortSignal,
20
+ ): Promise<T> {
21
+ if (!abortSignal) {
22
+ return await promise;
23
+ }
24
+ if (abortSignal.aborted) {
25
+ throw createMatrixStartupAbortError();
26
+ }
27
+ return await new Promise<T>((resolve, reject) => {
28
+ const onAbort = () => {
29
+ abortSignal.removeEventListener("abort", onAbort);
30
+ reject(createMatrixStartupAbortError());
31
+ };
32
+ abortSignal.addEventListener("abort", onAbort, { once: true });
33
+ promise.then(
34
+ (value) => {
35
+ abortSignal.removeEventListener("abort", onAbort);
36
+ resolve(value);
37
+ },
38
+ (error) => {
39
+ abortSignal.removeEventListener("abort", onAbort);
40
+ reject(error);
41
+ },
42
+ );
43
+ });
44
+ }
@@ -0,0 +1,308 @@
1
+ import { DEFAULT_ACCOUNT_ID } from "autobot/plugin-sdk/account-id";
2
+ import {
3
+ getSessionBindingService,
4
+ type SessionBindingRecord,
5
+ } from "autobot/plugin-sdk/conversation-binding-runtime";
6
+ import {
7
+ formatThreadBindingDisabledError,
8
+ formatThreadBindingSpawnDisabledError,
9
+ resolveThreadBindingSpawnPolicy,
10
+ } from "autobot/plugin-sdk/conversation-runtime";
11
+ import type { AutoBotPluginApi } from "autobot/plugin-sdk/core";
12
+ import { normalizeOptionalString } from "autobot/plugin-sdk/string-coerce-runtime";
13
+ import { resolveMatrixTargetIdentity } from "./target-ids.js";
14
+ import {
15
+ getMatrixThreadBindingManager,
16
+ listAllBindings,
17
+ listBindingsForAccount,
18
+ removeBindingRecord,
19
+ resolveBindingKey,
20
+ } from "./thread-bindings-shared.js";
21
+
22
+ type MatrixSubagentSpawningEvent = {
23
+ threadRequested: boolean;
24
+ requester?: {
25
+ channel?: string;
26
+ accountId?: string;
27
+ to?: string;
28
+ threadId?: string | number;
29
+ };
30
+ childSessionKey: string;
31
+ agentId: string;
32
+ label?: string;
33
+ };
34
+
35
+ type MatrixSubagentEndedEvent = {
36
+ targetSessionKey: string;
37
+ targetKind: string;
38
+ accountId?: string;
39
+ reason?: string;
40
+ sendFarewell?: boolean;
41
+ };
42
+
43
+ type MatrixSubagentDeliveryTargetEvent = {
44
+ childSessionKey: string;
45
+ requesterOrigin?: {
46
+ channel?: string;
47
+ accountId?: string;
48
+ to?: string;
49
+ threadId?: string | number;
50
+ };
51
+ expectsCompletionMessage: boolean;
52
+ };
53
+
54
+ type MatrixDeliveryOrigin = {
55
+ channel: "matrix";
56
+ accountId: string;
57
+ to: string;
58
+ threadId?: string;
59
+ };
60
+
61
+ type SpawningResult =
62
+ | {
63
+ status: "ok";
64
+ threadBindingReady?: boolean;
65
+ deliveryOrigin?: MatrixDeliveryOrigin;
66
+ }
67
+ | { status: "error"; error: string };
68
+
69
+ type DeliveryTargetResult = {
70
+ origin: MatrixDeliveryOrigin;
71
+ };
72
+
73
+ function summarizeError(err: unknown): string {
74
+ if (err instanceof Error) {
75
+ return err.message;
76
+ }
77
+ if (typeof err === "string") {
78
+ return err;
79
+ }
80
+ return "error";
81
+ }
82
+
83
+ function resolveMatrixBindingThreadId(binding: SessionBindingRecord): string | undefined {
84
+ const { conversationId, parentConversationId } = binding.conversation;
85
+ return parentConversationId && parentConversationId !== conversationId
86
+ ? conversationId
87
+ : undefined;
88
+ }
89
+
90
+ function resolveMatrixBindingDeliveryOrigin(
91
+ binding: SessionBindingRecord,
92
+ fallbackAccountId: string,
93
+ ): MatrixDeliveryOrigin {
94
+ const boundRoomId =
95
+ binding.conversation.parentConversationId ?? binding.conversation.conversationId;
96
+ const threadId = resolveMatrixBindingThreadId(binding);
97
+ return {
98
+ channel: "matrix",
99
+ accountId: binding.conversation.accountId ?? fallbackAccountId,
100
+ to: `room:${boundRoomId}`,
101
+ ...(threadId ? { threadId } : {}),
102
+ };
103
+ }
104
+
105
+ export async function handleMatrixSubagentSpawning(
106
+ api: AutoBotPluginApi,
107
+ event: MatrixSubagentSpawningEvent,
108
+ ): Promise<SpawningResult | undefined> {
109
+ if (!event.threadRequested) {
110
+ return undefined;
111
+ }
112
+ const channel = event.requester?.channel?.trim().toLowerCase();
113
+ if (channel !== "matrix") {
114
+ return undefined;
115
+ }
116
+
117
+ // Normalize early so per-account config and manager lookup use the same id.
118
+ // Falls back to DEFAULT_ACCOUNT_ID so accounts.default.threadBindings.* is
119
+ // respected even when the requester omits accountId.
120
+ const accountId = normalizeOptionalString(event.requester?.accountId) || DEFAULT_ACCOUNT_ID;
121
+ const policy = resolveThreadBindingSpawnPolicy({
122
+ cfg: api.config,
123
+ channel: "matrix",
124
+ accountId,
125
+ kind: "subagent",
126
+ });
127
+
128
+ if (!policy.enabled) {
129
+ return {
130
+ status: "error",
131
+ error: formatThreadBindingDisabledError({
132
+ channel: policy.channel,
133
+ accountId: policy.accountId,
134
+ kind: "subagent",
135
+ }),
136
+ } satisfies SpawningResult;
137
+ }
138
+ if (!policy.spawnEnabled) {
139
+ return {
140
+ status: "error",
141
+ error: formatThreadBindingSpawnDisabledError({
142
+ channel: policy.channel,
143
+ accountId: policy.accountId,
144
+ kind: "subagent",
145
+ }),
146
+ };
147
+ }
148
+
149
+ // Resolve the raw Matrix room ID from the requester's `to` field
150
+ // (e.g. "room:!abc123:example.org" → "!abc123:example.org").
151
+ const rawTo = normalizeOptionalString(event.requester?.to) ?? "";
152
+ const matrixTarget = rawTo ? resolveMatrixTargetIdentity(rawTo) : null;
153
+ const roomId = matrixTarget?.kind === "room" ? matrixTarget.id : "";
154
+
155
+ if (!roomId) {
156
+ return {
157
+ status: "error",
158
+ error:
159
+ "Cannot create Matrix thread binding: no room target in spawn request (requester.to must be a Matrix room ID).",
160
+ };
161
+ }
162
+
163
+ const bindingService = getSessionBindingService();
164
+ const capabilities = bindingService.getCapabilities({ channel: "matrix", accountId });
165
+ if (!capabilities.adapterAvailable || !capabilities.bindSupported) {
166
+ return {
167
+ status: "error",
168
+ error: `No Matrix session binding adapter available for account "${accountId}". Is the Matrix channel running?`,
169
+ };
170
+ }
171
+ if (!capabilities.placements.includes("child")) {
172
+ return {
173
+ status: "error",
174
+ error: `Matrix session binding adapter for account "${accountId}" does not support child thread bindings.`,
175
+ };
176
+ }
177
+
178
+ try {
179
+ // placement="child" tells the Matrix SessionBindingAdapter to:
180
+ // 1. Send an intro message to the room, creating a new thread root event
181
+ // 2. Use the returned event ID as boundConversationId (the thread ID)
182
+ // 3. Register the binding record in the in-memory store and persist it
183
+ //
184
+ // We do NOT call setBindingRecord here — the adapter's bind() handles
185
+ // record creation, thread creation, and persistence atomically.
186
+ const binding = await bindingService.bind({
187
+ targetSessionKey: event.childSessionKey,
188
+ targetKind: "subagent",
189
+ conversation: {
190
+ channel: "matrix",
191
+ accountId,
192
+ conversationId: roomId,
193
+ },
194
+ placement: "child",
195
+ metadata: {
196
+ agentId: event.agentId?.trim() || undefined,
197
+ label: normalizeOptionalString(event.label) || undefined,
198
+ boundBy: "system",
199
+ },
200
+ });
201
+ return {
202
+ status: "ok",
203
+ threadBindingReady: true,
204
+ deliveryOrigin: resolveMatrixBindingDeliveryOrigin(binding, accountId),
205
+ } satisfies SpawningResult;
206
+ } catch (err) {
207
+ return {
208
+ status: "error",
209
+ error: `Matrix thread bind failed: ${summarizeError(err)}`,
210
+ };
211
+ }
212
+ }
213
+
214
+ export async function handleMatrixSubagentEnded(event: MatrixSubagentEndedEvent): Promise<void> {
215
+ const accountId = normalizeOptionalString(event.accountId) || undefined;
216
+ // Use the targeted account list when available; fall back to a full scan
217
+ // so bindings are cleaned up even when accountId is absent.
218
+ const candidates = accountId ? listBindingsForAccount(accountId) : listAllBindings();
219
+ const matching = candidates.filter(
220
+ (entry) => entry.targetSessionKey === event.targetSessionKey && entry.targetKind === "subagent",
221
+ );
222
+ const removedBindingKeys = new Set<string>();
223
+ if (event.sendFarewell) {
224
+ const bindingService = getSessionBindingService();
225
+ const reason = normalizeOptionalString(event.reason) || "subagent-ended";
226
+ for (const binding of matching) {
227
+ const bindingId = resolveBindingKey(binding);
228
+ const removed = await bindingService.unbind({ bindingId, reason });
229
+ if (removed.some((entry) => entry.bindingId === bindingId)) {
230
+ removedBindingKeys.add(bindingId);
231
+ }
232
+ }
233
+ }
234
+
235
+ const affectedAccountIds = new Set<string>();
236
+ for (const binding of matching) {
237
+ if (removedBindingKeys.has(resolveBindingKey(binding))) {
238
+ continue;
239
+ }
240
+ if (removeBindingRecord(binding)) {
241
+ affectedAccountIds.add(binding.accountId);
242
+ }
243
+ }
244
+ // Flush each affected account's manager so removals are persisted to disk.
245
+ for (const acctId of affectedAccountIds) {
246
+ const manager = getMatrixThreadBindingManager(acctId);
247
+ await manager?.persist();
248
+ }
249
+ }
250
+
251
+ export function handleMatrixSubagentDeliveryTarget(
252
+ event: MatrixSubagentDeliveryTargetEvent,
253
+ ): DeliveryTargetResult | undefined {
254
+ if (!event.expectsCompletionMessage) {
255
+ return undefined;
256
+ }
257
+ const requesterChannel = event.requesterOrigin?.channel?.trim().toLowerCase();
258
+ if (requesterChannel !== "matrix") {
259
+ return undefined;
260
+ }
261
+
262
+ const requesterAccountId = normalizeOptionalString(event.requesterOrigin?.accountId);
263
+ const requesterThreadId =
264
+ event.requesterOrigin?.threadId != null && event.requesterOrigin.threadId !== ""
265
+ ? String(event.requesterOrigin.threadId).trim()
266
+ : "";
267
+
268
+ // Search the targeted account when available; otherwise scan all accounts.
269
+ const candidates = requesterAccountId
270
+ ? listBindingsForAccount(requesterAccountId)
271
+ : listAllBindings();
272
+ const bindings = candidates.filter(
273
+ (entry) => entry.targetSessionKey === event.childSessionKey && entry.targetKind === "subagent",
274
+ );
275
+ if (bindings.length === 0) {
276
+ return undefined;
277
+ }
278
+
279
+ let binding: (typeof bindings)[number] | undefined;
280
+ if (requesterThreadId) {
281
+ binding = bindings.find(
282
+ (entry) =>
283
+ entry.conversationId === requesterThreadId &&
284
+ (!requesterAccountId || entry.accountId === requesterAccountId),
285
+ );
286
+ }
287
+ if (!binding && bindings.length === 1) {
288
+ binding = bindings[0];
289
+ }
290
+ if (!binding) {
291
+ return undefined;
292
+ }
293
+
294
+ const roomId = binding.parentConversationId ?? binding.conversationId;
295
+ const threadId =
296
+ binding.parentConversationId && binding.parentConversationId !== binding.conversationId
297
+ ? binding.conversationId
298
+ : undefined;
299
+
300
+ return {
301
+ origin: {
302
+ channel: "matrix",
303
+ accountId: binding.accountId,
304
+ to: `room:${roomId}`,
305
+ ...(threadId ? { threadId } : {}),
306
+ },
307
+ };
308
+ }
@@ -0,0 +1,27 @@
1
+ export type MatrixSyncState =
2
+ | "PREPARED"
3
+ | "SYNCING"
4
+ | "CATCHUP"
5
+ | "RECONNECTING"
6
+ | "ERROR"
7
+ | "STOPPED"
8
+ | (string & {});
9
+
10
+ export function isMatrixReadySyncState(
11
+ state: MatrixSyncState | null | undefined,
12
+ ): state is "PREPARED" | "SYNCING" | "CATCHUP" {
13
+ return state === "PREPARED" || state === "SYNCING" || state === "CATCHUP";
14
+ }
15
+
16
+ export function isMatrixDisconnectedSyncState(
17
+ state: MatrixSyncState | null | undefined,
18
+ ): state is "RECONNECTING" | "ERROR" | "STOPPED" {
19
+ return state === "RECONNECTING" || state === "ERROR" || state === "STOPPED";
20
+ }
21
+
22
+ export function isMatrixTerminalSyncState(
23
+ state: MatrixSyncState | null | undefined,
24
+ ): state is "STOPPED" {
25
+ // matrix-js-sdk can recover from ERROR to PREPARED during initial sync.
26
+ return state === "STOPPED";
27
+ }
@@ -0,0 +1,79 @@
1
+ import { normalizeLowercaseStringOrEmpty } from "autobot/plugin-sdk/string-coerce-runtime";
2
+
3
+ type MatrixTarget = { kind: "room"; id: string } | { kind: "user"; id: string };
4
+ const MATRIX_PREFIX = "matrix:";
5
+ const ROOM_PREFIX = "room:";
6
+ const CHANNEL_PREFIX = "channel:";
7
+ const USER_PREFIX = "user:";
8
+
9
+ function stripKnownPrefixes(raw: string, prefixes: readonly string[]): string {
10
+ let normalized = raw.trim();
11
+ while (normalized) {
12
+ const lowered = normalizeLowercaseStringOrEmpty(normalized);
13
+ const matched = prefixes.find((prefix) => lowered.startsWith(prefix));
14
+ if (!matched) {
15
+ return normalized;
16
+ }
17
+ normalized = normalized.slice(matched.length).trim();
18
+ }
19
+ return normalized;
20
+ }
21
+
22
+ export function resolveMatrixTargetIdentity(raw: string): MatrixTarget | null {
23
+ const normalized = stripKnownPrefixes(raw, [MATRIX_PREFIX]);
24
+ if (!normalized) {
25
+ return null;
26
+ }
27
+ const lowered = normalizeLowercaseStringOrEmpty(normalized);
28
+ if (lowered.startsWith(USER_PREFIX)) {
29
+ const id = normalized.slice(USER_PREFIX.length).trim();
30
+ return id ? { kind: "user", id } : null;
31
+ }
32
+ if (lowered.startsWith(ROOM_PREFIX)) {
33
+ const id = normalized.slice(ROOM_PREFIX.length).trim();
34
+ return id ? { kind: "room", id } : null;
35
+ }
36
+ if (lowered.startsWith(CHANNEL_PREFIX)) {
37
+ const id = normalized.slice(CHANNEL_PREFIX.length).trim();
38
+ return id ? { kind: "room", id } : null;
39
+ }
40
+ if (isMatrixQualifiedUserId(normalized)) {
41
+ return { kind: "user", id: normalized };
42
+ }
43
+ return { kind: "room", id: normalized };
44
+ }
45
+
46
+ export function isMatrixQualifiedUserId(raw: string): boolean {
47
+ const trimmed = raw.trim();
48
+ return trimmed.startsWith("@") && trimmed.includes(":");
49
+ }
50
+
51
+ export function normalizeMatrixResolvableTarget(raw: string): string {
52
+ return stripKnownPrefixes(raw, [MATRIX_PREFIX, ROOM_PREFIX, CHANNEL_PREFIX]);
53
+ }
54
+
55
+ export function normalizeMatrixMessagingTarget(raw: string): string | undefined {
56
+ const normalized = stripKnownPrefixes(raw, [
57
+ MATRIX_PREFIX,
58
+ ROOM_PREFIX,
59
+ CHANNEL_PREFIX,
60
+ USER_PREFIX,
61
+ ]);
62
+ return normalized || undefined;
63
+ }
64
+
65
+ export function resolveMatrixDirectUserId(params: {
66
+ from?: string;
67
+ to?: string;
68
+ chatType?: string;
69
+ }): string | undefined {
70
+ if (params.chatType !== "direct") {
71
+ return undefined;
72
+ }
73
+ const roomId = normalizeMatrixResolvableTarget(params.to ?? "");
74
+ if (!roomId.startsWith("!")) {
75
+ return undefined;
76
+ }
77
+ const userId = stripKnownPrefixes(params.from ?? "", [MATRIX_PREFIX, USER_PREFIX]);
78
+ return isMatrixQualifiedUserId(userId) ? userId : undefined;
79
+ }