@kodelyth/matrix 2026.5.42 → 2026.6.2

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/klaw.plugin.json +891 -3
  2. package/package.json +18 -6
  3. package/CHANGELOG.md +0 -321
  4. package/SPEC-SUPPORT.md +0 -116
  5. package/api.ts +0 -38
  6. package/auth-presence.ts +0 -56
  7. package/channel-plugin-api.ts +0 -3
  8. package/cli-metadata.ts +0 -11
  9. package/contract-api.ts +0 -17
  10. package/doctor-contract-api.ts +0 -1
  11. package/helper-api.ts +0 -3
  12. package/index.ts +0 -55
  13. package/plugin-entry.handlers.runtime.ts +0 -1
  14. package/runtime-api.ts +0 -72
  15. package/runtime-heavy-api.ts +0 -1
  16. package/runtime-setter-api.ts +0 -3
  17. package/secret-contract-api.ts +0 -5
  18. package/setup-entry.ts +0 -17
  19. package/setup-plugin-api.ts +0 -3
  20. package/src/account-selection.ts +0 -223
  21. package/src/actions.ts +0 -346
  22. package/src/approval-auth.ts +0 -25
  23. package/src/approval-handler.runtime.ts +0 -592
  24. package/src/approval-ids.ts +0 -6
  25. package/src/approval-native.ts +0 -345
  26. package/src/approval-reaction-auth.ts +0 -45
  27. package/src/approval-reactions.ts +0 -313
  28. package/src/auth-precedence.ts +0 -61
  29. package/src/channel-account-paths.ts +0 -97
  30. package/src/channel.runtime.ts +0 -17
  31. package/src/channel.setup.ts +0 -48
  32. package/src/channel.ts +0 -667
  33. package/src/cli-metadata.ts +0 -19
  34. package/src/cli.ts +0 -2298
  35. package/src/config-adapter.ts +0 -41
  36. package/src/config-schema.ts +0 -159
  37. package/src/config-ui-hints.ts +0 -56
  38. package/src/directory-live.ts +0 -238
  39. package/src/doctor-contract.ts +0 -287
  40. package/src/doctor.ts +0 -262
  41. package/src/env-vars.ts +0 -92
  42. package/src/exec-approval-resolver.ts +0 -23
  43. package/src/exec-approvals.ts +0 -287
  44. package/src/group-mentions.ts +0 -41
  45. package/src/legacy-crypto-inspector-availability.ts +0 -60
  46. package/src/legacy-crypto.ts +0 -531
  47. package/src/legacy-state.ts +0 -156
  48. package/src/matrix/account-config.ts +0 -175
  49. package/src/matrix/accounts.ts +0 -194
  50. package/src/matrix/actions/client.ts +0 -31
  51. package/src/matrix/actions/devices.ts +0 -34
  52. package/src/matrix/actions/limits.ts +0 -6
  53. package/src/matrix/actions/messages.ts +0 -129
  54. package/src/matrix/actions/pins.ts +0 -63
  55. package/src/matrix/actions/polls.ts +0 -109
  56. package/src/matrix/actions/profile.ts +0 -37
  57. package/src/matrix/actions/reactions.ts +0 -59
  58. package/src/matrix/actions/room.ts +0 -71
  59. package/src/matrix/actions/summary.ts +0 -88
  60. package/src/matrix/actions/types.ts +0 -63
  61. package/src/matrix/actions/verification.ts +0 -589
  62. package/src/matrix/actions.ts +0 -37
  63. package/src/matrix/active-client.ts +0 -26
  64. package/src/matrix/async-lock.ts +0 -18
  65. package/src/matrix/backup-health.ts +0 -124
  66. package/src/matrix/client/config-runtime-api.ts +0 -9
  67. package/src/matrix/client/config-secret-input.runtime.ts +0 -1
  68. package/src/matrix/client/config.ts +0 -853
  69. package/src/matrix/client/create-client.ts +0 -105
  70. package/src/matrix/client/env-auth.ts +0 -95
  71. package/src/matrix/client/file-sync-store.ts +0 -289
  72. package/src/matrix/client/logging.ts +0 -140
  73. package/src/matrix/client/migration-snapshot.runtime.ts +0 -1
  74. package/src/matrix/client/private-network-host.ts +0 -1
  75. package/src/matrix/client/runtime.ts +0 -4
  76. package/src/matrix/client/shared.ts +0 -316
  77. package/src/matrix/client/storage.ts +0 -543
  78. package/src/matrix/client/types.ts +0 -50
  79. package/src/matrix/client/url-validation.ts +0 -73
  80. package/src/matrix/client-bootstrap.ts +0 -173
  81. package/src/matrix/client.ts +0 -23
  82. package/src/matrix/config-paths.ts +0 -31
  83. package/src/matrix/config-update.ts +0 -292
  84. package/src/matrix/credentials-read.ts +0 -208
  85. package/src/matrix/credentials-write.runtime.ts +0 -35
  86. package/src/matrix/credentials.ts +0 -95
  87. package/src/matrix/deps.ts +0 -309
  88. package/src/matrix/device-health.ts +0 -29
  89. package/src/matrix/direct-management.ts +0 -349
  90. package/src/matrix/direct-room.ts +0 -128
  91. package/src/matrix/draft-stream.ts +0 -225
  92. package/src/matrix/encryption-guidance.ts +0 -24
  93. package/src/matrix/errors.ts +0 -21
  94. package/src/matrix/format.ts +0 -426
  95. package/src/matrix/legacy-crypto-inspector.ts +0 -95
  96. package/src/matrix/media-errors.ts +0 -20
  97. package/src/matrix/media-text.ts +0 -162
  98. package/src/matrix/monitor/access-state.ts +0 -145
  99. package/src/matrix/monitor/ack-config.ts +0 -27
  100. package/src/matrix/monitor/allowlist.ts +0 -89
  101. package/src/matrix/monitor/auto-join.ts +0 -86
  102. package/src/matrix/monitor/config.ts +0 -569
  103. package/src/matrix/monitor/context-summary.ts +0 -43
  104. package/src/matrix/monitor/direct.ts +0 -296
  105. package/src/matrix/monitor/events.ts +0 -397
  106. package/src/matrix/monitor/handler.ts +0 -2266
  107. package/src/matrix/monitor/inbound-dedupe.ts +0 -267
  108. package/src/matrix/monitor/index.ts +0 -540
  109. package/src/matrix/monitor/legacy-crypto-restore.ts +0 -139
  110. package/src/matrix/monitor/location.ts +0 -108
  111. package/src/matrix/monitor/media.ts +0 -119
  112. package/src/matrix/monitor/mentions.ts +0 -256
  113. package/src/matrix/monitor/reaction-events.ts +0 -197
  114. package/src/matrix/monitor/recent-invite.ts +0 -30
  115. package/src/matrix/monitor/replies.ts +0 -136
  116. package/src/matrix/monitor/reply-context.ts +0 -92
  117. package/src/matrix/monitor/room-history.ts +0 -301
  118. package/src/matrix/monitor/room-info.ts +0 -126
  119. package/src/matrix/monitor/rooms.ts +0 -52
  120. package/src/matrix/monitor/route.ts +0 -179
  121. package/src/matrix/monitor/runtime-api.ts +0 -28
  122. package/src/matrix/monitor/startup-verification.ts +0 -237
  123. package/src/matrix/monitor/startup.ts +0 -218
  124. package/src/matrix/monitor/status.ts +0 -120
  125. package/src/matrix/monitor/sync-lifecycle.ts +0 -91
  126. package/src/matrix/monitor/task-runner.ts +0 -38
  127. package/src/matrix/monitor/test-events.ts +0 -21
  128. package/src/matrix/monitor/thread-context.ts +0 -108
  129. package/src/matrix/monitor/threads.ts +0 -85
  130. package/src/matrix/monitor/types.ts +0 -30
  131. package/src/matrix/monitor/verification-events.ts +0 -643
  132. package/src/matrix/monitor/verification-utils.ts +0 -46
  133. package/src/matrix/outbound-media-runtime.ts +0 -1
  134. package/src/matrix/poll-summary.ts +0 -110
  135. package/src/matrix/poll-types.ts +0 -429
  136. package/src/matrix/probe.runtime.ts +0 -4
  137. package/src/matrix/probe.ts +0 -97
  138. package/src/matrix/profile.ts +0 -184
  139. package/src/matrix/reaction-common.ts +0 -147
  140. package/src/matrix/sdk/crypto-bootstrap.ts +0 -438
  141. package/src/matrix/sdk/crypto-facade.ts +0 -242
  142. package/src/matrix/sdk/crypto-node.runtime.ts +0 -17
  143. package/src/matrix/sdk/crypto-runtime.ts +0 -14
  144. package/src/matrix/sdk/decrypt-bridge.ts +0 -410
  145. package/src/matrix/sdk/event-helpers.ts +0 -83
  146. package/src/matrix/sdk/http-client.ts +0 -87
  147. package/src/matrix/sdk/idb-persistence-lock.ts +0 -51
  148. package/src/matrix/sdk/idb-persistence.ts +0 -288
  149. package/src/matrix/sdk/logger.ts +0 -108
  150. package/src/matrix/sdk/read-response-with-limit.ts +0 -19
  151. package/src/matrix/sdk/recovery-key-store.ts +0 -453
  152. package/src/matrix/sdk/timeout-abort-signal.ts +0 -1
  153. package/src/matrix/sdk/transport-runtime-api.ts +0 -18
  154. package/src/matrix/sdk/transport.ts +0 -352
  155. package/src/matrix/sdk/types.ts +0 -245
  156. package/src/matrix/sdk/verification-manager.ts +0 -795
  157. package/src/matrix/sdk/verification-status.ts +0 -23
  158. package/src/matrix/sdk.ts +0 -2152
  159. package/src/matrix/send/client.ts +0 -93
  160. package/src/matrix/send/formatting.ts +0 -189
  161. package/src/matrix/send/media.ts +0 -244
  162. package/src/matrix/send/targets.ts +0 -104
  163. package/src/matrix/send/types.ts +0 -131
  164. package/src/matrix/send.ts +0 -660
  165. package/src/matrix/session-store-metadata.ts +0 -108
  166. package/src/matrix/startup-abort.ts +0 -44
  167. package/src/matrix/subagent-hooks.ts +0 -308
  168. package/src/matrix/sync-state.ts +0 -27
  169. package/src/matrix/target-ids.ts +0 -79
  170. package/src/matrix/thread-bindings-shared.ts +0 -206
  171. package/src/matrix/thread-bindings.ts +0 -580
  172. package/src/matrix-migration.runtime.ts +0 -9
  173. package/src/migration-config.ts +0 -243
  174. package/src/migration-snapshot-backup.ts +0 -116
  175. package/src/migration-snapshot.ts +0 -53
  176. package/src/onboarding.ts +0 -775
  177. package/src/outbound.ts +0 -248
  178. package/src/plugin-entry.runtime.js +0 -115
  179. package/src/plugin-entry.runtime.ts +0 -70
  180. package/src/profile-update.ts +0 -71
  181. package/src/record-shared.ts +0 -3
  182. package/src/resolve-targets.ts +0 -175
  183. package/src/resolver.runtime.ts +0 -5
  184. package/src/resolver.ts +0 -21
  185. package/src/runtime-api.ts +0 -106
  186. package/src/runtime.ts +0 -13
  187. package/src/secret-contract.ts +0 -174
  188. package/src/session-route.ts +0 -126
  189. package/src/setup-bootstrap.ts +0 -102
  190. package/src/setup-config.ts +0 -222
  191. package/src/setup-contract.ts +0 -90
  192. package/src/setup-core.ts +0 -146
  193. package/src/setup-dm-policy.ts +0 -15
  194. package/src/setup-surface.ts +0 -4
  195. package/src/startup-maintenance.ts +0 -114
  196. package/src/storage-paths.ts +0 -92
  197. package/src/thread-binding-api.ts +0 -23
  198. package/src/tool-actions.runtime.ts +0 -1
  199. package/src/tool-actions.ts +0 -498
  200. package/src/types.ts +0 -257
  201. package/subagent-hooks-api.ts +0 -31
  202. package/test-api.ts +0 -21
  203. package/thread-binding-api.ts +0 -4
  204. package/thread-bindings-runtime.ts +0 -4
  205. package/tsconfig.json +0 -16
@@ -1,108 +0,0 @@
1
- import { normalizeAccountId } from "klaw/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
- }
@@ -1,44 +0,0 @@
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
- }
@@ -1,308 +0,0 @@
1
- import { DEFAULT_ACCOUNT_ID } from "klaw/plugin-sdk/account-id";
2
- import {
3
- getSessionBindingService,
4
- type SessionBindingRecord,
5
- } from "klaw/plugin-sdk/conversation-binding-runtime";
6
- import {
7
- formatThreadBindingDisabledError,
8
- formatThreadBindingSpawnDisabledError,
9
- resolveThreadBindingSpawnPolicy,
10
- } from "klaw/plugin-sdk/conversation-runtime";
11
- import type { KlawPluginApi } from "klaw/plugin-sdk/core";
12
- import { normalizeOptionalString } from "klaw/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: KlawPluginApi,
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
- }
@@ -1,27 +0,0 @@
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
- }
@@ -1,79 +0,0 @@
1
- import { normalizeLowercaseStringOrEmpty } from "klaw/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
- }