@archipelagolab/lobi 1.0.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 (315) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/ENDOFFILE +0 -0
  3. package/EOF +0 -0
  4. package/LICENSE +21 -0
  5. package/SPEC-SUPPORT.md +116 -0
  6. package/YAMLEND +0 -0
  7. package/api.ts +18 -0
  8. package/archipelagolab-lobi-1.0.0.tgz +0 -0
  9. package/auth-presence.ts +56 -0
  10. package/channel-plugin-api.ts +3 -0
  11. package/cli-metadata.ts +11 -0
  12. package/contract-api.ts +17 -0
  13. package/docs/CHECKLIST.md +83 -0
  14. package/docs/FORK_SDK_GUIDE.md +279 -0
  15. package/helper-api.ts +3 -0
  16. package/index.test.ts +61 -0
  17. package/index.ts +65 -0
  18. package/openclaw.plugin.json +23 -0
  19. package/package.json +52 -0
  20. package/plugin-entry.handlers.runtime.ts +1 -0
  21. package/runtime-api.ts +54 -0
  22. package/runtime-heavy-api.ts +1 -0
  23. package/scripts/migrate-to-lobi.sh +72 -0
  24. package/secret-contract-api.ts +5 -0
  25. package/setup-entry.ts +13 -0
  26. package/src/account-selection.test.ts +124 -0
  27. package/src/account-selection.ts +226 -0
  28. package/src/actions.account-propagation.test.ts +251 -0
  29. package/src/actions.test.ts +251 -0
  30. package/src/actions.ts +336 -0
  31. package/src/approval-auth.test.ts +23 -0
  32. package/src/approval-auth.ts +25 -0
  33. package/src/approval-handler.runtime.test.ts +46 -0
  34. package/src/approval-handler.runtime.ts +400 -0
  35. package/src/approval-ids.ts +6 -0
  36. package/src/approval-native.test.ts +329 -0
  37. package/src/approval-native.ts +336 -0
  38. package/src/approval-reactions.test.ts +107 -0
  39. package/src/approval-reactions.ts +158 -0
  40. package/src/auth-precedence.ts +61 -0
  41. package/src/channel-account-paths.ts +92 -0
  42. package/src/channel.account-paths.test.ts +102 -0
  43. package/src/channel.directory.test.ts +601 -0
  44. package/src/channel.resolve.test.ts +38 -0
  45. package/src/channel.runtime.ts +16 -0
  46. package/src/channel.setup.test.ts +269 -0
  47. package/src/channel.ts +570 -0
  48. package/src/cli-metadata.ts +19 -0
  49. package/src/cli.test.ts +1015 -0
  50. package/src/cli.ts +1198 -0
  51. package/src/config-adapter.ts +41 -0
  52. package/src/config-schema.test.ts +90 -0
  53. package/src/config-schema.ts +114 -0
  54. package/src/directory-live.test.ts +200 -0
  55. package/src/directory-live.ts +238 -0
  56. package/src/doctor-contract.ts +287 -0
  57. package/src/doctor.test.ts +440 -0
  58. package/src/doctor.ts +262 -0
  59. package/src/env-vars.ts +92 -0
  60. package/src/exec-approval-resolver.test.ts +68 -0
  61. package/src/exec-approval-resolver.ts +23 -0
  62. package/src/exec-approvals.test.ts +483 -0
  63. package/src/exec-approvals.ts +290 -0
  64. package/src/group-mentions.ts +41 -0
  65. package/src/legacy-crypto-inspector-availability.test.ts +81 -0
  66. package/src/legacy-crypto-inspector-availability.ts +60 -0
  67. package/src/legacy-crypto.test.ts +234 -0
  68. package/src/legacy-crypto.ts +549 -0
  69. package/src/legacy-state.test.ts +86 -0
  70. package/src/legacy-state.ts +156 -0
  71. package/src/matrix/account-config.ts +150 -0
  72. package/src/matrix/accounts.readiness.test.ts +27 -0
  73. package/src/matrix/accounts.test.ts +757 -0
  74. package/src/matrix/accounts.ts +194 -0
  75. package/src/matrix/actions/client.test.ts +215 -0
  76. package/src/matrix/actions/client.ts +31 -0
  77. package/src/matrix/actions/devices.test.ts +114 -0
  78. package/src/matrix/actions/devices.ts +34 -0
  79. package/src/matrix/actions/limits.test.ts +15 -0
  80. package/src/matrix/actions/limits.ts +6 -0
  81. package/src/matrix/actions/messages.test.ts +289 -0
  82. package/src/matrix/actions/messages.ts +123 -0
  83. package/src/matrix/actions/pins.test.ts +74 -0
  84. package/src/matrix/actions/pins.ts +64 -0
  85. package/src/matrix/actions/polls.test.ts +71 -0
  86. package/src/matrix/actions/polls.ts +109 -0
  87. package/src/matrix/actions/profile.test.ts +109 -0
  88. package/src/matrix/actions/profile.ts +37 -0
  89. package/src/matrix/actions/reactions.test.ts +135 -0
  90. package/src/matrix/actions/reactions.ts +59 -0
  91. package/src/matrix/actions/room.test.ts +79 -0
  92. package/src/matrix/actions/room.ts +71 -0
  93. package/src/matrix/actions/summary.test.ts +87 -0
  94. package/src/matrix/actions/summary.ts +88 -0
  95. package/src/matrix/actions/types.ts +82 -0
  96. package/src/matrix/actions/verification.test.ts +105 -0
  97. package/src/matrix/actions/verification.ts +237 -0
  98. package/src/matrix/actions.ts +37 -0
  99. package/src/matrix/active-client.ts +26 -0
  100. package/src/matrix/async-lock.ts +18 -0
  101. package/src/matrix/backup-health.ts +115 -0
  102. package/src/matrix/client/config-runtime-api.ts +14 -0
  103. package/src/matrix/client/config-secret-input.runtime.ts +1 -0
  104. package/src/matrix/client/config.ts +982 -0
  105. package/src/matrix/client/create-client.test.ts +115 -0
  106. package/src/matrix/client/create-client.ts +101 -0
  107. package/src/matrix/client/env-auth.ts +6 -0
  108. package/src/matrix/client/file-sync-store.test.ts +265 -0
  109. package/src/matrix/client/file-sync-store.ts +289 -0
  110. package/src/matrix/client/logging.ts +123 -0
  111. package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
  112. package/src/matrix/client/private-network-host.ts +56 -0
  113. package/src/matrix/client/runtime.ts +4 -0
  114. package/src/matrix/client/shared.test.ts +344 -0
  115. package/src/matrix/client/shared.ts +306 -0
  116. package/src/matrix/client/storage.test.ts +634 -0
  117. package/src/matrix/client/storage.ts +544 -0
  118. package/src/matrix/client/types.ts +50 -0
  119. package/src/matrix/client-bootstrap.test.ts +84 -0
  120. package/src/matrix/client-bootstrap.ts +164 -0
  121. package/src/matrix/client-resolver.test-helpers.ts +147 -0
  122. package/src/matrix/client.test.ts +1521 -0
  123. package/src/matrix/client.ts +23 -0
  124. package/src/matrix/config-paths.ts +31 -0
  125. package/src/matrix/config-update.test.ts +237 -0
  126. package/src/matrix/config-update.ts +291 -0
  127. package/src/matrix/credentials-read.ts +206 -0
  128. package/src/matrix/credentials-write.runtime.ts +26 -0
  129. package/src/matrix/credentials.test.ts +501 -0
  130. package/src/matrix/credentials.ts +95 -0
  131. package/src/matrix/deps.test.ts +74 -0
  132. package/src/matrix/deps.ts +225 -0
  133. package/src/matrix/device-health.test.ts +45 -0
  134. package/src/matrix/device-health.ts +31 -0
  135. package/src/matrix/direct-management.test.ts +350 -0
  136. package/src/matrix/direct-management.ts +347 -0
  137. package/src/matrix/direct-room.test.ts +61 -0
  138. package/src/matrix/direct-room.ts +128 -0
  139. package/src/matrix/draft-stream.test.ts +406 -0
  140. package/src/matrix/draft-stream.ts +216 -0
  141. package/src/matrix/encryption-guidance.ts +27 -0
  142. package/src/matrix/errors.ts +21 -0
  143. package/src/matrix/format.test.ts +340 -0
  144. package/src/matrix/format.ts +428 -0
  145. package/src/matrix/legacy-crypto-inspector.ts +95 -0
  146. package/src/matrix/media-errors.ts +20 -0
  147. package/src/matrix/media-text.ts +169 -0
  148. package/src/matrix/monitor/access-state.test.ts +45 -0
  149. package/src/matrix/monitor/access-state.ts +77 -0
  150. package/src/matrix/monitor/ack-config.test.ts +57 -0
  151. package/src/matrix/monitor/ack-config.ts +26 -0
  152. package/src/matrix/monitor/allowlist.test.ts +45 -0
  153. package/src/matrix/monitor/allowlist.ts +94 -0
  154. package/src/matrix/monitor/auto-join.test.ts +203 -0
  155. package/src/matrix/monitor/auto-join.ts +86 -0
  156. package/src/matrix/monitor/config.test.ts +197 -0
  157. package/src/matrix/monitor/config.ts +303 -0
  158. package/src/matrix/monitor/context-summary.ts +43 -0
  159. package/src/matrix/monitor/direct.test.ts +529 -0
  160. package/src/matrix/monitor/direct.ts +270 -0
  161. package/src/matrix/monitor/events.test.ts +1524 -0
  162. package/src/matrix/monitor/events.ts +213 -0
  163. package/src/matrix/monitor/handler.body-for-agent.test.ts +396 -0
  164. package/src/matrix/monitor/handler.group-history.test.ts +648 -0
  165. package/src/matrix/monitor/handler.media-failure.test.ts +267 -0
  166. package/src/matrix/monitor/handler.test-helpers.ts +308 -0
  167. package/src/matrix/monitor/handler.test.ts +2952 -0
  168. package/src/matrix/monitor/handler.thread-root-media.test.ts +82 -0
  169. package/src/matrix/monitor/handler.ts +1679 -0
  170. package/src/matrix/monitor/inbound-dedupe.test.ts +146 -0
  171. package/src/matrix/monitor/inbound-dedupe.ts +267 -0
  172. package/src/matrix/monitor/index.test.ts +920 -0
  173. package/src/matrix/monitor/index.ts +434 -0
  174. package/src/matrix/monitor/legacy-crypto-restore.test.ts +206 -0
  175. package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
  176. package/src/matrix/monitor/location.ts +100 -0
  177. package/src/matrix/monitor/media.test.ts +159 -0
  178. package/src/matrix/monitor/media.ts +119 -0
  179. package/src/matrix/monitor/mentions.test.ts +289 -0
  180. package/src/matrix/monitor/mentions.ts +177 -0
  181. package/src/matrix/monitor/reaction-events.test.ts +326 -0
  182. package/src/matrix/monitor/reaction-events.ts +187 -0
  183. package/src/matrix/monitor/recent-invite.test.ts +92 -0
  184. package/src/matrix/monitor/recent-invite.ts +30 -0
  185. package/src/matrix/monitor/replies.test.ts +265 -0
  186. package/src/matrix/monitor/replies.ts +136 -0
  187. package/src/matrix/monitor/reply-context.test.ts +276 -0
  188. package/src/matrix/monitor/reply-context.ts +92 -0
  189. package/src/matrix/monitor/room-history.test.ts +258 -0
  190. package/src/matrix/monitor/room-history.ts +301 -0
  191. package/src/matrix/monitor/room-info.test.ts +201 -0
  192. package/src/matrix/monitor/room-info.ts +126 -0
  193. package/src/matrix/monitor/rooms.test.ts +121 -0
  194. package/src/matrix/monitor/rooms.ts +52 -0
  195. package/src/matrix/monitor/route.test.ts +255 -0
  196. package/src/matrix/monitor/route.ts +178 -0
  197. package/src/matrix/monitor/runtime-api.ts +31 -0
  198. package/src/matrix/monitor/startup-verification.test.ts +294 -0
  199. package/src/matrix/monitor/startup-verification.ts +237 -0
  200. package/src/matrix/monitor/startup.test.ts +257 -0
  201. package/src/matrix/monitor/startup.ts +218 -0
  202. package/src/matrix/monitor/status.ts +111 -0
  203. package/src/matrix/monitor/sync-lifecycle.test.ts +224 -0
  204. package/src/matrix/monitor/sync-lifecycle.ts +91 -0
  205. package/src/matrix/monitor/task-runner.ts +38 -0
  206. package/src/matrix/monitor/thread-context.test.ts +149 -0
  207. package/src/matrix/monitor/thread-context.ts +108 -0
  208. package/src/matrix/monitor/threads.test.ts +68 -0
  209. package/src/matrix/monitor/threads.ts +85 -0
  210. package/src/matrix/monitor/types.ts +30 -0
  211. package/src/matrix/monitor/verification-events.ts +627 -0
  212. package/src/matrix/monitor/verification-utils.test.ts +47 -0
  213. package/src/matrix/monitor/verification-utils.ts +46 -0
  214. package/src/matrix/outbound-media-runtime.ts +1 -0
  215. package/src/matrix/poll-summary.ts +110 -0
  216. package/src/matrix/poll-types.test.ts +205 -0
  217. package/src/matrix/poll-types.ts +433 -0
  218. package/src/matrix/probe.runtime.ts +4 -0
  219. package/src/matrix/probe.test.ts +154 -0
  220. package/src/matrix/probe.ts +96 -0
  221. package/src/matrix/profile.test.ts +154 -0
  222. package/src/matrix/profile.ts +184 -0
  223. package/src/matrix/reaction-common.test.ts +96 -0
  224. package/src/matrix/reaction-common.ts +147 -0
  225. package/src/matrix/sdk/crypto-bootstrap.test.ts +505 -0
  226. package/src/matrix/sdk/crypto-bootstrap.ts +341 -0
  227. package/src/matrix/sdk/crypto-facade.test.ts +197 -0
  228. package/src/matrix/sdk/crypto-facade.ts +207 -0
  229. package/src/matrix/sdk/crypto-node.runtime.test.ts +27 -0
  230. package/src/matrix/sdk/crypto-node.runtime.ts +9 -0
  231. package/src/matrix/sdk/crypto-runtime.ts +11 -0
  232. package/src/matrix/sdk/decrypt-bridge.ts +356 -0
  233. package/src/matrix/sdk/event-helpers.test.ts +60 -0
  234. package/src/matrix/sdk/event-helpers.ts +71 -0
  235. package/src/matrix/sdk/http-client.test.ts +134 -0
  236. package/src/matrix/sdk/http-client.ts +87 -0
  237. package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
  238. package/src/matrix/sdk/idb-persistence.lock-order.test.ts +108 -0
  239. package/src/matrix/sdk/idb-persistence.test-helpers.ts +88 -0
  240. package/src/matrix/sdk/idb-persistence.test.ts +149 -0
  241. package/src/matrix/sdk/idb-persistence.ts +283 -0
  242. package/src/matrix/sdk/logger.test.ts +25 -0
  243. package/src/matrix/sdk/logger.ts +108 -0
  244. package/src/matrix/sdk/read-response-with-limit.ts +19 -0
  245. package/src/matrix/sdk/recovery-key-store.test.ts +385 -0
  246. package/src/matrix/sdk/recovery-key-store.ts +430 -0
  247. package/src/matrix/sdk/transport.test.ts +161 -0
  248. package/src/matrix/sdk/transport.ts +344 -0
  249. package/src/matrix/sdk/types.ts +236 -0
  250. package/src/matrix/sdk/verification-manager.test.ts +509 -0
  251. package/src/matrix/sdk/verification-manager.ts +694 -0
  252. package/src/matrix/sdk/verification-status.ts +23 -0
  253. package/src/matrix/sdk.test.ts +2568 -0
  254. package/src/matrix/sdk.ts +1789 -0
  255. package/src/matrix/send/client.test.ts +174 -0
  256. package/src/matrix/send/client.ts +90 -0
  257. package/src/matrix/send/formatting.ts +189 -0
  258. package/src/matrix/send/media.ts +244 -0
  259. package/src/matrix/send/targets.test.ts +254 -0
  260. package/src/matrix/send/targets.ts +104 -0
  261. package/src/matrix/send/types.ts +134 -0
  262. package/src/matrix/send.test.ts +958 -0
  263. package/src/matrix/send.ts +609 -0
  264. package/src/matrix/session-store-metadata.ts +108 -0
  265. package/src/matrix/startup-abort.ts +44 -0
  266. package/src/matrix/sync-state.ts +27 -0
  267. package/src/matrix/target-ids.ts +102 -0
  268. package/src/matrix/thread-bindings-shared.ts +201 -0
  269. package/src/matrix/thread-bindings.test.ts +673 -0
  270. package/src/matrix/thread-bindings.ts +577 -0
  271. package/src/matrix-migration.runtime.ts +9 -0
  272. package/src/migration-config.test.ts +228 -0
  273. package/src/migration-config.ts +243 -0
  274. package/src/migration-snapshot-backup.ts +117 -0
  275. package/src/migration-snapshot.test.ts +184 -0
  276. package/src/migration-snapshot.ts +55 -0
  277. package/src/onboarding.resolve.test.ts +55 -0
  278. package/src/onboarding.test-harness.ts +158 -0
  279. package/src/onboarding.test.ts +665 -0
  280. package/src/onboarding.ts +773 -0
  281. package/src/outbound.test.ts +173 -0
  282. package/src/outbound.ts +78 -0
  283. package/src/plugin-entry.runtime.js +159 -0
  284. package/src/plugin-entry.runtime.test.ts +108 -0
  285. package/src/plugin-entry.runtime.ts +68 -0
  286. package/src/profile-update.ts +68 -0
  287. package/src/record-shared.ts +3 -0
  288. package/src/resolve-targets.test.ts +178 -0
  289. package/src/resolve-targets.ts +175 -0
  290. package/src/resolver.ts +21 -0
  291. package/src/runtime-api.ts +144 -0
  292. package/src/runtime.ts +7 -0
  293. package/src/secret-contract.ts +174 -0
  294. package/src/session-route.test.ts +315 -0
  295. package/src/session-route.ts +113 -0
  296. package/src/setup-bootstrap.ts +94 -0
  297. package/src/setup-config.ts +222 -0
  298. package/src/setup-contract.ts +89 -0
  299. package/src/setup-core.test.ts +326 -0
  300. package/src/setup-core.ts +50 -0
  301. package/src/setup-surface.ts +4 -0
  302. package/src/startup-maintenance.test.ts +227 -0
  303. package/src/startup-maintenance.ts +114 -0
  304. package/src/storage-paths.ts +92 -0
  305. package/src/test-helpers.ts +42 -0
  306. package/src/test-mocks.ts +55 -0
  307. package/src/test-runtime.ts +72 -0
  308. package/src/test-support/monitor-route-test-support.ts +8 -0
  309. package/src/tool-actions.runtime.ts +1 -0
  310. package/src/tool-actions.test.ts +422 -0
  311. package/src/tool-actions.ts +498 -0
  312. package/src/types.ts +230 -0
  313. package/test-api.ts +2 -0
  314. package/thread-bindings-runtime.ts +4 -0
  315. package/tsconfig.json +16 -0
package/src/cli.ts ADDED
@@ -0,0 +1,1198 @@
1
+ import type { Command } from "commander";
2
+ import { resolveMatrixAccount, resolveMatrixAccountConfig } from "./matrix/accounts.js";
3
+ import { withResolvedActionClient, withStartedActionClient } from "./matrix/actions/client.js";
4
+ import { listMatrixOwnDevices, pruneMatrixStaleGatewayDevices } from "./matrix/actions/devices.js";
5
+ import { updateMatrixOwnProfile } from "./matrix/actions/profile.js";
6
+ import {
7
+ bootstrapMatrixVerification,
8
+ getMatrixRoomKeyBackupStatus,
9
+ getMatrixVerificationStatus,
10
+ resetMatrixRoomKeyBackup,
11
+ restoreMatrixRoomKeyBackup,
12
+ verifyMatrixRecoveryKey,
13
+ } from "./matrix/actions/verification.js";
14
+ import { resolveMatrixRoomKeyBackupIssue } from "./matrix/backup-health.js";
15
+ import { resolveMatrixAuthContext } from "./matrix/client.js";
16
+ import { setMatrixSdkConsoleLogging, setMatrixSdkLogMode } from "./matrix/client/logging.js";
17
+ import { resolveMatrixConfigPath, updateMatrixAccountConfig } from "./matrix/config-update.js";
18
+ import { isOpenClawManagedMatrixDevice } from "./matrix/device-health.js";
19
+ import {
20
+ inspectMatrixDirectRooms,
21
+ repairMatrixDirectRooms,
22
+ type MatrixDirectRoomCandidate,
23
+ } from "./matrix/direct-management.js";
24
+ import { formatMatrixErrorMessage } from "./matrix/errors.js";
25
+ import { applyMatrixProfileUpdate, type MatrixProfileUpdateResult } from "./profile-update.js";
26
+ import { formatZonedTimestamp, normalizeAccountId, type ChannelSetupInput } from "./runtime-api.js";
27
+ import { getMatrixRuntime } from "./runtime.js";
28
+ import { matrixSetupAdapter } from "./setup-core.js";
29
+ import type { CoreConfig } from "./types.js";
30
+
31
+ let matrixCliExitScheduled = false;
32
+
33
+ export function resetMatrixCliStateForTests(): void {
34
+ matrixCliExitScheduled = false;
35
+ }
36
+
37
+ function scheduleMatrixCliExit(): void {
38
+ if (matrixCliExitScheduled || process.env.VITEST) {
39
+ return;
40
+ }
41
+ matrixCliExitScheduled = true;
42
+ // matrix-js-sdk rust crypto can leave background async work alive after command completion.
43
+ setTimeout(() => {
44
+ process.exit(process.exitCode ?? 0);
45
+ }, 0);
46
+ }
47
+
48
+ function markCliFailure(): void {
49
+ process.exitCode = 1;
50
+ }
51
+
52
+ function toErrorMessage(err: unknown): string {
53
+ return formatMatrixErrorMessage(err);
54
+ }
55
+
56
+ function printJson(payload: unknown): void {
57
+ console.log(JSON.stringify(payload, null, 2));
58
+ }
59
+
60
+ function formatLocalTimestamp(value: string | null | undefined): string | null {
61
+ if (!value) {
62
+ return null;
63
+ }
64
+ const parsed = new Date(value);
65
+ if (!Number.isFinite(parsed.getTime())) {
66
+ return value;
67
+ }
68
+ return formatZonedTimestamp(parsed, { displaySeconds: true }) ?? value;
69
+ }
70
+
71
+ function printTimestamp(label: string, value: string | null | undefined): void {
72
+ const formatted = formatLocalTimestamp(value);
73
+ if (formatted) {
74
+ console.log(`${label}: ${formatted}`);
75
+ }
76
+ }
77
+
78
+ function printAccountLabel(accountId?: string): void {
79
+ console.log(`Account: ${normalizeAccountId(accountId)}`);
80
+ }
81
+
82
+ function resolveMatrixCliAccountId(accountId?: string): string {
83
+ const cfg = getMatrixRuntime().config.loadConfig() as CoreConfig;
84
+ return resolveMatrixAuthContext({ cfg, accountId }).accountId;
85
+ }
86
+
87
+ function formatMatrixCliCommand(command: string, accountId?: string): string {
88
+ const normalizedAccountId = normalizeAccountId(accountId);
89
+ const suffix = normalizedAccountId === "default" ? "" : ` --account ${normalizedAccountId}`;
90
+ return `openclaw matrix ${command}${suffix}`;
91
+ }
92
+
93
+ function printMatrixOwnDevices(
94
+ devices: Array<{
95
+ deviceId: string;
96
+ displayName: string | null;
97
+ lastSeenIp: string | null;
98
+ lastSeenTs: number | null;
99
+ current: boolean;
100
+ }>,
101
+ ): void {
102
+ if (devices.length === 0) {
103
+ console.log("Devices: none");
104
+ return;
105
+ }
106
+ for (const device of devices) {
107
+ const labels = [device.current ? "current" : null, device.displayName].filter(Boolean);
108
+ console.log(`- ${device.deviceId}${labels.length ? ` (${labels.join(", ")})` : ""}`);
109
+ if (device.lastSeenTs) {
110
+ printTimestamp(" Last seen", new Date(device.lastSeenTs).toISOString());
111
+ }
112
+ if (device.lastSeenIp) {
113
+ console.log(` Last IP: ${device.lastSeenIp}`);
114
+ }
115
+ }
116
+ }
117
+
118
+ function configureCliLogMode(verbose: boolean): void {
119
+ setMatrixSdkLogMode(verbose ? "default" : "quiet");
120
+ setMatrixSdkConsoleLogging(verbose);
121
+ }
122
+
123
+ function parseOptionalInt(value: string | undefined, fieldName: string): number | undefined {
124
+ const trimmed = value?.trim();
125
+ if (!trimmed) {
126
+ return undefined;
127
+ }
128
+ const parsed = Number.parseInt(trimmed, 10);
129
+ if (!Number.isFinite(parsed)) {
130
+ throw new Error(`${fieldName} must be an integer`);
131
+ }
132
+ return parsed;
133
+ }
134
+
135
+ type MatrixCliAccountAddResult = {
136
+ accountId: string;
137
+ configPath: string;
138
+ useEnv: boolean;
139
+ deviceHealth: {
140
+ currentDeviceId: string | null;
141
+ staleOpenClawDeviceIds: string[];
142
+ error?: string;
143
+ };
144
+ verificationBootstrap: {
145
+ attempted: boolean;
146
+ success: boolean;
147
+ recoveryKeyCreatedAt: string | null;
148
+ backupVersion: string | null;
149
+ error?: string;
150
+ };
151
+ profile: {
152
+ attempted: boolean;
153
+ displayNameUpdated: boolean;
154
+ avatarUpdated: boolean;
155
+ resolvedAvatarUrl: string | null;
156
+ convertedAvatarFromHttp: boolean;
157
+ error?: string;
158
+ };
159
+ };
160
+
161
+ async function addMatrixAccount(params: {
162
+ account?: string;
163
+ name?: string;
164
+ avatarUrl?: string;
165
+ homeserver?: string;
166
+ proxy?: string;
167
+ userId?: string;
168
+ accessToken?: string;
169
+ password?: string;
170
+ deviceName?: string;
171
+ initialSyncLimit?: string;
172
+ allowPrivateNetwork?: boolean;
173
+ useEnv?: boolean;
174
+ }): Promise<MatrixCliAccountAddResult> {
175
+ const runtime = getMatrixRuntime();
176
+ const cfg = runtime.config.loadConfig() as CoreConfig;
177
+ if (!matrixSetupAdapter.applyAccountConfig) {
178
+ throw new Error("Matrix account setup is unavailable.");
179
+ }
180
+
181
+ const input: ChannelSetupInput = {
182
+ name: params.name,
183
+ avatarUrl: params.avatarUrl,
184
+ homeserver: params.homeserver,
185
+ dangerouslyAllowPrivateNetwork: params.allowPrivateNetwork,
186
+ proxy: params.proxy,
187
+ userId: params.userId,
188
+ accessToken: params.accessToken,
189
+ password: params.password,
190
+ deviceName: params.deviceName,
191
+ initialSyncLimit: parseOptionalInt(params.initialSyncLimit, "--initial-sync-limit"),
192
+ useEnv: params.useEnv === true,
193
+ };
194
+ const accountId =
195
+ matrixSetupAdapter.resolveAccountId?.({
196
+ cfg,
197
+ accountId: params.account,
198
+ input,
199
+ }) ?? normalizeAccountId(params.account?.trim() || params.name?.trim());
200
+ const validationError = matrixSetupAdapter.validateInput?.({
201
+ cfg,
202
+ accountId,
203
+ input,
204
+ });
205
+ if (validationError) {
206
+ throw new Error(validationError);
207
+ }
208
+
209
+ const updated = matrixSetupAdapter.applyAccountConfig({
210
+ cfg,
211
+ accountId,
212
+ input,
213
+ }) as CoreConfig;
214
+ await runtime.config.writeConfigFile(updated as never);
215
+ const accountConfig = resolveMatrixAccountConfig({ cfg: updated, accountId });
216
+
217
+ let verificationBootstrap: MatrixCliAccountAddResult["verificationBootstrap"] = {
218
+ attempted: false,
219
+ success: false,
220
+ recoveryKeyCreatedAt: null,
221
+ backupVersion: null,
222
+ };
223
+ if (accountConfig.encryption === true) {
224
+ const { maybeBootstrapNewEncryptedMatrixAccount } = await import("./setup-bootstrap.js");
225
+ verificationBootstrap = await maybeBootstrapNewEncryptedMatrixAccount({
226
+ previousCfg: cfg,
227
+ cfg: updated,
228
+ accountId,
229
+ });
230
+ }
231
+
232
+ const desiredDisplayName = input.name?.trim();
233
+ const desiredAvatarUrl = input.avatarUrl?.trim();
234
+ let profile: MatrixCliAccountAddResult["profile"] = {
235
+ attempted: false,
236
+ displayNameUpdated: false,
237
+ avatarUpdated: false,
238
+ resolvedAvatarUrl: null,
239
+ convertedAvatarFromHttp: false,
240
+ };
241
+ if (desiredDisplayName || desiredAvatarUrl) {
242
+ try {
243
+ const synced = await updateMatrixOwnProfile({
244
+ accountId,
245
+ displayName: desiredDisplayName,
246
+ avatarUrl: desiredAvatarUrl,
247
+ });
248
+ let resolvedAvatarUrl = synced.resolvedAvatarUrl;
249
+ if (synced.convertedAvatarFromHttp && synced.resolvedAvatarUrl) {
250
+ const latestCfg = runtime.config.loadConfig() as CoreConfig;
251
+ const withAvatar = updateMatrixAccountConfig(latestCfg, accountId, {
252
+ avatarUrl: synced.resolvedAvatarUrl,
253
+ });
254
+ await runtime.config.writeConfigFile(withAvatar as never);
255
+ resolvedAvatarUrl = synced.resolvedAvatarUrl;
256
+ }
257
+ profile = {
258
+ attempted: true,
259
+ displayNameUpdated: synced.displayNameUpdated,
260
+ avatarUpdated: synced.avatarUpdated,
261
+ resolvedAvatarUrl,
262
+ convertedAvatarFromHttp: synced.convertedAvatarFromHttp,
263
+ };
264
+ } catch (err) {
265
+ profile = {
266
+ attempted: true,
267
+ displayNameUpdated: false,
268
+ avatarUpdated: false,
269
+ resolvedAvatarUrl: null,
270
+ convertedAvatarFromHttp: false,
271
+ error: toErrorMessage(err),
272
+ };
273
+ }
274
+ }
275
+
276
+ let deviceHealth: MatrixCliAccountAddResult["deviceHealth"] = {
277
+ currentDeviceId: null,
278
+ staleOpenClawDeviceIds: [],
279
+ };
280
+ try {
281
+ const addedDevices = await listMatrixOwnDevices({ accountId });
282
+ deviceHealth = {
283
+ currentDeviceId: addedDevices.find((device) => device.current)?.deviceId ?? null,
284
+ staleOpenClawDeviceIds: addedDevices
285
+ .filter((device) => !device.current && isOpenClawManagedMatrixDevice(device.displayName))
286
+ .map((device) => device.deviceId),
287
+ };
288
+ } catch (err) {
289
+ deviceHealth = {
290
+ currentDeviceId: null,
291
+ staleOpenClawDeviceIds: [],
292
+ error: toErrorMessage(err),
293
+ };
294
+ }
295
+
296
+ return {
297
+ accountId,
298
+ configPath: resolveMatrixConfigPath(updated, accountId),
299
+ useEnv: input.useEnv === true,
300
+ deviceHealth,
301
+ verificationBootstrap,
302
+ profile,
303
+ };
304
+ }
305
+
306
+ function printDirectRoomCandidate(room: MatrixCliDirectRoomCandidate): void {
307
+ const members =
308
+ room.joinedMembers === null ? "unavailable" : room.joinedMembers.join(", ") || "none";
309
+ console.log(
310
+ `- ${room.roomId} [${room.source}] strict=${room.strict ? "yes" : "no"} joined=${members}`,
311
+ );
312
+ }
313
+
314
+ function printDirectRoomInspection(result: MatrixCliDirectRoomInspection): void {
315
+ printAccountLabel(result.accountId);
316
+ console.log(`Peer: ${result.remoteUserId}`);
317
+ console.log(`Self: ${result.selfUserId ?? "unknown"}`);
318
+ console.log(`Active direct room: ${result.activeRoomId ?? "none"}`);
319
+ console.log(
320
+ `Mapped rooms: ${result.mappedRoomIds.length ? result.mappedRoomIds.join(", ") : "none"}`,
321
+ );
322
+ console.log(
323
+ `Discovered strict rooms: ${result.discoveredStrictRoomIds.length ? result.discoveredStrictRoomIds.join(", ") : "none"}`,
324
+ );
325
+ if (result.mappedRooms.length > 0) {
326
+ console.log("Mapped room details:");
327
+ for (const room of result.mappedRooms) {
328
+ printDirectRoomCandidate(room);
329
+ }
330
+ }
331
+ }
332
+
333
+ async function inspectMatrixDirectRoom(params: {
334
+ accountId: string;
335
+ userId: string;
336
+ }): Promise<MatrixCliDirectRoomInspection> {
337
+ return await withResolvedActionClient(
338
+ { accountId: params.accountId },
339
+ async (client) => {
340
+ const inspection = await inspectMatrixDirectRooms({
341
+ client,
342
+ remoteUserId: params.userId,
343
+ });
344
+ return {
345
+ accountId: params.accountId,
346
+ remoteUserId: inspection.remoteUserId,
347
+ selfUserId: inspection.selfUserId,
348
+ mappedRoomIds: inspection.mappedRoomIds,
349
+ mappedRooms: inspection.mappedRooms.map(toCliDirectRoomCandidate),
350
+ discoveredStrictRoomIds: inspection.discoveredStrictRoomIds,
351
+ activeRoomId: inspection.activeRoomId,
352
+ };
353
+ },
354
+ "persist",
355
+ );
356
+ }
357
+
358
+ async function repairMatrixDirectRoom(params: {
359
+ accountId: string;
360
+ userId: string;
361
+ }): Promise<MatrixCliDirectRoomRepair> {
362
+ const cfg = getMatrixRuntime().config.loadConfig() as CoreConfig;
363
+ const account = resolveMatrixAccount({ cfg, accountId: params.accountId });
364
+ return await withStartedActionClient({ accountId: params.accountId }, async (client) => {
365
+ const repaired = await repairMatrixDirectRooms({
366
+ client,
367
+ remoteUserId: params.userId,
368
+ encrypted: account.config.encryption === true,
369
+ });
370
+ return {
371
+ accountId: params.accountId,
372
+ remoteUserId: repaired.remoteUserId,
373
+ selfUserId: repaired.selfUserId,
374
+ mappedRoomIds: repaired.mappedRoomIds,
375
+ mappedRooms: repaired.mappedRooms.map(toCliDirectRoomCandidate),
376
+ discoveredStrictRoomIds: repaired.discoveredStrictRoomIds,
377
+ activeRoomId: repaired.activeRoomId,
378
+ encrypted: account.config.encryption === true,
379
+ createdRoomId: repaired.createdRoomId,
380
+ changed: repaired.changed,
381
+ directContentBefore: repaired.directContentBefore,
382
+ directContentAfter: repaired.directContentAfter,
383
+ };
384
+ });
385
+ }
386
+
387
+ type MatrixCliProfileSetResult = MatrixProfileUpdateResult;
388
+
389
+ async function setMatrixProfile(params: {
390
+ account?: string;
391
+ name?: string;
392
+ avatarUrl?: string;
393
+ }): Promise<MatrixCliProfileSetResult> {
394
+ return await applyMatrixProfileUpdate({
395
+ account: params.account,
396
+ displayName: params.name,
397
+ avatarUrl: params.avatarUrl,
398
+ });
399
+ }
400
+
401
+ type MatrixCliCommandConfig<TResult> = {
402
+ verbose: boolean;
403
+ json: boolean;
404
+ run: () => Promise<TResult>;
405
+ onText: (result: TResult, verbose: boolean) => void;
406
+ onJson?: (result: TResult) => unknown;
407
+ shouldFail?: (result: TResult) => boolean;
408
+ errorPrefix: string;
409
+ onJsonError?: (message: string) => unknown;
410
+ };
411
+
412
+ async function runMatrixCliCommand<TResult>(
413
+ config: MatrixCliCommandConfig<TResult>,
414
+ ): Promise<void> {
415
+ configureCliLogMode(config.verbose);
416
+ try {
417
+ const result = await config.run();
418
+ if (config.json) {
419
+ printJson(config.onJson ? config.onJson(result) : result);
420
+ } else {
421
+ config.onText(result, config.verbose);
422
+ }
423
+ if (config.shouldFail?.(result)) {
424
+ markCliFailure();
425
+ }
426
+ } catch (err) {
427
+ const message = toErrorMessage(err);
428
+ if (config.json) {
429
+ printJson(config.onJsonError ? config.onJsonError(message) : { error: message });
430
+ } else {
431
+ console.error(`${config.errorPrefix}: ${message}`);
432
+ }
433
+ markCliFailure();
434
+ } finally {
435
+ scheduleMatrixCliExit();
436
+ }
437
+ }
438
+
439
+ type MatrixCliBackupStatus = {
440
+ serverVersion: string | null;
441
+ activeVersion: string | null;
442
+ trusted: boolean | null;
443
+ matchesDecryptionKey: boolean | null;
444
+ decryptionKeyCached: boolean | null;
445
+ keyLoadAttempted: boolean;
446
+ keyLoadError: string | null;
447
+ };
448
+
449
+ type MatrixCliVerificationStatus = {
450
+ encryptionEnabled: boolean;
451
+ verified: boolean;
452
+ userId: string | null;
453
+ deviceId: string | null;
454
+ localVerified: boolean;
455
+ crossSigningVerified: boolean;
456
+ signedByOwner: boolean;
457
+ backupVersion: string | null;
458
+ backup?: MatrixCliBackupStatus;
459
+ recoveryKeyStored: boolean;
460
+ recoveryKeyCreatedAt: string | null;
461
+ pendingVerifications: number;
462
+ };
463
+
464
+ type MatrixCliDirectRoomCandidate = {
465
+ roomId: string;
466
+ source: "account-data" | "joined";
467
+ strict: boolean;
468
+ joinedMembers: string[] | null;
469
+ };
470
+
471
+ type MatrixCliDirectRoomInspection = {
472
+ accountId: string;
473
+ remoteUserId: string;
474
+ selfUserId: string | null;
475
+ mappedRoomIds: string[];
476
+ mappedRooms: MatrixCliDirectRoomCandidate[];
477
+ discoveredStrictRoomIds: string[];
478
+ activeRoomId: string | null;
479
+ };
480
+
481
+ type MatrixCliDirectRoomRepair = MatrixCliDirectRoomInspection & {
482
+ encrypted: boolean;
483
+ createdRoomId: string | null;
484
+ changed: boolean;
485
+ directContentBefore: Record<string, string[]>;
486
+ directContentAfter: Record<string, string[]>;
487
+ };
488
+
489
+ function toCliDirectRoomCandidate(room: MatrixDirectRoomCandidate): MatrixCliDirectRoomCandidate {
490
+ return {
491
+ roomId: room.roomId,
492
+ source: room.source,
493
+ strict: room.strict,
494
+ joinedMembers: room.joinedMembers,
495
+ };
496
+ }
497
+
498
+ function resolveBackupStatus(status: {
499
+ backupVersion: string | null;
500
+ backup?: MatrixCliBackupStatus;
501
+ }): MatrixCliBackupStatus {
502
+ return {
503
+ serverVersion: status.backup?.serverVersion ?? status.backupVersion ?? null,
504
+ activeVersion: status.backup?.activeVersion ?? null,
505
+ trusted: status.backup?.trusted ?? null,
506
+ matchesDecryptionKey: status.backup?.matchesDecryptionKey ?? null,
507
+ decryptionKeyCached: status.backup?.decryptionKeyCached ?? null,
508
+ keyLoadAttempted: status.backup?.keyLoadAttempted ?? false,
509
+ keyLoadError: status.backup?.keyLoadError ?? null,
510
+ };
511
+ }
512
+
513
+ function yesNoUnknown(value: boolean | null): string {
514
+ if (value === true) {
515
+ return "yes";
516
+ }
517
+ if (value === false) {
518
+ return "no";
519
+ }
520
+ return "unknown";
521
+ }
522
+
523
+ function printBackupStatus(backup: MatrixCliBackupStatus): void {
524
+ console.log(`Backup server version: ${backup.serverVersion ?? "none"}`);
525
+ console.log(`Backup active on this device: ${backup.activeVersion ?? "no"}`);
526
+ console.log(`Backup trusted by this device: ${yesNoUnknown(backup.trusted)}`);
527
+ console.log(`Backup matches local decryption key: ${yesNoUnknown(backup.matchesDecryptionKey)}`);
528
+ console.log(`Backup key cached locally: ${yesNoUnknown(backup.decryptionKeyCached)}`);
529
+ console.log(`Backup key load attempted: ${yesNoUnknown(backup.keyLoadAttempted)}`);
530
+ if (backup.keyLoadError) {
531
+ console.log(`Backup key load error: ${backup.keyLoadError}`);
532
+ }
533
+ }
534
+
535
+ function printVerificationIdentity(status: {
536
+ userId: string | null;
537
+ deviceId: string | null;
538
+ }): void {
539
+ console.log(`User: ${status.userId ?? "unknown"}`);
540
+ console.log(`Device: ${status.deviceId ?? "unknown"}`);
541
+ }
542
+
543
+ function printVerificationBackupSummary(status: {
544
+ backupVersion: string | null;
545
+ backup?: MatrixCliBackupStatus;
546
+ }): void {
547
+ printBackupSummary(resolveBackupStatus(status));
548
+ }
549
+
550
+ function printVerificationBackupStatus(status: {
551
+ backupVersion: string | null;
552
+ backup?: MatrixCliBackupStatus;
553
+ }): void {
554
+ printBackupStatus(resolveBackupStatus(status));
555
+ }
556
+
557
+ function printVerificationTrustDiagnostics(status: {
558
+ localVerified: boolean;
559
+ crossSigningVerified: boolean;
560
+ signedByOwner: boolean;
561
+ }): void {
562
+ console.log(`Locally trusted: ${status.localVerified ? "yes" : "no"}`);
563
+ console.log(`Cross-signing verified: ${status.crossSigningVerified ? "yes" : "no"}`);
564
+ console.log(`Signed by owner: ${status.signedByOwner ? "yes" : "no"}`);
565
+ }
566
+
567
+ function printVerificationGuidance(status: MatrixCliVerificationStatus, accountId?: string): void {
568
+ printGuidance(buildVerificationGuidance(status, accountId));
569
+ }
570
+
571
+ function printBackupSummary(backup: MatrixCliBackupStatus): void {
572
+ const issue = resolveMatrixRoomKeyBackupIssue(backup);
573
+ console.log(`Backup: ${issue.summary}`);
574
+ if (backup.serverVersion) {
575
+ console.log(`Backup version: ${backup.serverVersion}`);
576
+ }
577
+ }
578
+
579
+ function buildVerificationGuidance(
580
+ status: MatrixCliVerificationStatus,
581
+ accountId?: string,
582
+ ): string[] {
583
+ const backup = resolveBackupStatus(status);
584
+ const backupIssue = resolveMatrixRoomKeyBackupIssue(backup);
585
+ const nextSteps = new Set<string>();
586
+ if (!status.verified) {
587
+ nextSteps.add(
588
+ `Run '${formatMatrixCliCommand("verify device <key>", accountId)}' to verify this device.`,
589
+ );
590
+ }
591
+ if (backupIssue.code === "missing-server-backup") {
592
+ nextSteps.add(
593
+ `Run '${formatMatrixCliCommand("verify bootstrap", accountId)}' to create a room key backup.`,
594
+ );
595
+ } else if (
596
+ backupIssue.code === "key-load-failed" ||
597
+ backupIssue.code === "key-not-loaded" ||
598
+ backupIssue.code === "inactive"
599
+ ) {
600
+ if (status.recoveryKeyStored) {
601
+ nextSteps.add(
602
+ `Backup key is not loaded on this device. Run '${formatMatrixCliCommand("verify backup restore", accountId)}' to load it and restore old room keys.`,
603
+ );
604
+ } else {
605
+ nextSteps.add(
606
+ `Store a recovery key with '${formatMatrixCliCommand("verify device <key>", accountId)}', then run '${formatMatrixCliCommand("verify backup restore", accountId)}'.`,
607
+ );
608
+ }
609
+ } else if (backupIssue.code === "key-mismatch") {
610
+ nextSteps.add(
611
+ `Backup key mismatch on this device. Re-run '${formatMatrixCliCommand("verify device <key>", accountId)}' with the matching recovery key.`,
612
+ );
613
+ nextSteps.add(
614
+ `If you want a fresh backup baseline and accept losing unrecoverable history, run '${formatMatrixCliCommand("verify backup reset --yes", accountId)}'. This may also repair secret storage so the new backup key can be loaded after restart.`,
615
+ );
616
+ } else if (backupIssue.code === "untrusted-signature") {
617
+ nextSteps.add(
618
+ `Backup trust chain is not verified on this device. Re-run '${formatMatrixCliCommand("verify device <key>", accountId)}' if you have the correct recovery key.`,
619
+ );
620
+ nextSteps.add(
621
+ `If you want a fresh backup baseline and accept losing unrecoverable history, run '${formatMatrixCliCommand("verify backup reset --yes", accountId)}'. This may also repair secret storage so the new backup key can be loaded after restart.`,
622
+ );
623
+ } else if (backupIssue.code === "indeterminate") {
624
+ nextSteps.add(
625
+ `Run '${formatMatrixCliCommand("verify status --verbose", accountId)}' to inspect backup trust diagnostics.`,
626
+ );
627
+ }
628
+ if (status.pendingVerifications > 0) {
629
+ nextSteps.add(`Complete ${status.pendingVerifications} pending verification request(s).`);
630
+ }
631
+ return Array.from(nextSteps);
632
+ }
633
+
634
+ function printGuidance(lines: string[]): void {
635
+ if (lines.length === 0) {
636
+ return;
637
+ }
638
+ console.log("Next steps:");
639
+ for (const line of lines) {
640
+ console.log(`- ${line}`);
641
+ }
642
+ }
643
+
644
+ function printVerificationStatus(
645
+ status: MatrixCliVerificationStatus,
646
+ verbose = false,
647
+ accountId?: string,
648
+ ): void {
649
+ console.log(`Verified by owner: ${status.verified ? "yes" : "no"}`);
650
+ const backup = resolveBackupStatus(status);
651
+ const backupIssue = resolveMatrixRoomKeyBackupIssue(backup);
652
+ printVerificationBackupSummary(status);
653
+ if (backupIssue.message) {
654
+ console.log(`Backup issue: ${backupIssue.message}`);
655
+ }
656
+ if (verbose) {
657
+ console.log("Diagnostics:");
658
+ printVerificationIdentity(status);
659
+ printVerificationTrustDiagnostics(status);
660
+ printVerificationBackupStatus(status);
661
+ console.log(`Recovery key stored: ${status.recoveryKeyStored ? "yes" : "no"}`);
662
+ printTimestamp("Recovery key created at", status.recoveryKeyCreatedAt);
663
+ console.log(`Pending verifications: ${status.pendingVerifications}`);
664
+ } else {
665
+ console.log(`Recovery key stored: ${status.recoveryKeyStored ? "yes" : "no"}`);
666
+ }
667
+ printVerificationGuidance(status, accountId);
668
+ }
669
+
670
+ export function registerMatrixCli(params: { program: Command }): void {
671
+ const root = params.program
672
+ .command("matrix")
673
+ .description("Matrix channel utilities")
674
+ .addHelpText("after", () => "\nDocs: https://docs.openclaw.ai/channels/matrix\n");
675
+
676
+ const account = root.command("account").description("Manage matrix channel accounts");
677
+
678
+ account
679
+ .command("add")
680
+ .description("Add or update a matrix account (wrapper around channel setup)")
681
+ .option("--account <id>", "Account ID (default: normalized --name, else default)")
682
+ .option("--name <name>", "Optional display name for this account")
683
+ .option("--avatar-url <url>", "Optional Matrix avatar URL (mxc:// or http(s) URL)")
684
+ .option("--homeserver <url>", "Matrix homeserver URL")
685
+ .option("--proxy <url>", "Optional HTTP(S) proxy URL for Matrix requests")
686
+ .option(
687
+ "--allow-private-network",
688
+ "Allow Matrix homeserver traffic to private/internal hosts for this account",
689
+ )
690
+ .option("--user-id <id>", "Matrix user ID")
691
+ .option("--access-token <token>", "Matrix access token")
692
+ .option("--password <password>", "Matrix password")
693
+ .option("--device-name <name>", "Matrix device display name")
694
+ .option("--initial-sync-limit <n>", "Matrix initial sync limit")
695
+ .option(
696
+ "--use-env",
697
+ "Use MATRIX_* env vars (or MATRIX_<ACCOUNT_ID>_* for non-default accounts)",
698
+ )
699
+ .option("--verbose", "Show setup details")
700
+ .option("--json", "Output as JSON")
701
+ .action(
702
+ async (options: {
703
+ account?: string;
704
+ name?: string;
705
+ avatarUrl?: string;
706
+ homeserver?: string;
707
+ proxy?: string;
708
+ allowPrivateNetwork?: boolean;
709
+ userId?: string;
710
+ accessToken?: string;
711
+ password?: string;
712
+ deviceName?: string;
713
+ initialSyncLimit?: string;
714
+ useEnv?: boolean;
715
+ verbose?: boolean;
716
+ json?: boolean;
717
+ }) => {
718
+ await runMatrixCliCommand({
719
+ verbose: options.verbose === true,
720
+ json: options.json === true,
721
+ run: async () =>
722
+ await addMatrixAccount({
723
+ account: options.account,
724
+ name: options.name,
725
+ avatarUrl: options.avatarUrl,
726
+ homeserver: options.homeserver,
727
+ proxy: options.proxy,
728
+ allowPrivateNetwork: options.allowPrivateNetwork === true,
729
+ userId: options.userId,
730
+ accessToken: options.accessToken,
731
+ password: options.password,
732
+ deviceName: options.deviceName,
733
+ initialSyncLimit: options.initialSyncLimit,
734
+ useEnv: options.useEnv === true,
735
+ }),
736
+ onText: (result) => {
737
+ console.log(`Saved matrix account: ${result.accountId}`);
738
+ console.log(`Config path: ${result.configPath}`);
739
+ console.log(
740
+ `Credentials source: ${result.useEnv ? "MATRIX_* / MATRIX_<ACCOUNT_ID>_* env vars" : "inline config"}`,
741
+ );
742
+ if (result.verificationBootstrap.attempted) {
743
+ if (result.verificationBootstrap.success) {
744
+ console.log("Matrix verification bootstrap: complete");
745
+ printTimestamp(
746
+ "Recovery key created at",
747
+ result.verificationBootstrap.recoveryKeyCreatedAt,
748
+ );
749
+ if (result.verificationBootstrap.backupVersion) {
750
+ console.log(`Backup version: ${result.verificationBootstrap.backupVersion}`);
751
+ }
752
+ } else {
753
+ console.error(
754
+ `Matrix verification bootstrap warning: ${result.verificationBootstrap.error}`,
755
+ );
756
+ }
757
+ }
758
+ if (result.deviceHealth.error) {
759
+ console.error(`Matrix device health warning: ${result.deviceHealth.error}`);
760
+ } else if (result.deviceHealth.staleOpenClawDeviceIds.length > 0) {
761
+ console.log(
762
+ `Matrix device hygiene warning: stale OpenClaw devices detected (${result.deviceHealth.staleOpenClawDeviceIds.join(", ")}). Run 'openclaw matrix devices prune-stale --account ${result.accountId}'.`,
763
+ );
764
+ }
765
+ if (result.profile.attempted) {
766
+ if (result.profile.error) {
767
+ console.error(`Profile sync warning: ${result.profile.error}`);
768
+ } else {
769
+ console.log(
770
+ `Profile sync: name ${result.profile.displayNameUpdated ? "updated" : "unchanged"}, avatar ${result.profile.avatarUpdated ? "updated" : "unchanged"}`,
771
+ );
772
+ if (result.profile.convertedAvatarFromHttp && result.profile.resolvedAvatarUrl) {
773
+ console.log(`Avatar converted and saved as: ${result.profile.resolvedAvatarUrl}`);
774
+ }
775
+ }
776
+ }
777
+ const bindHint = `openclaw agents bind --agent <id> --bind matrix:${result.accountId}`;
778
+ console.log(`Bind this account to an agent: ${bindHint}`);
779
+ },
780
+ errorPrefix: "Account setup failed",
781
+ });
782
+ },
783
+ );
784
+
785
+ const profile = root.command("profile").description("Manage Matrix bot profile");
786
+
787
+ profile
788
+ .command("set")
789
+ .description("Update Matrix profile display name and/or avatar")
790
+ .option("--account <id>", "Account ID (for multi-account setups)")
791
+ .option("--name <name>", "Profile display name")
792
+ .option("--avatar-url <url>", "Profile avatar URL (mxc:// or http(s) URL)")
793
+ .option("--verbose", "Show detailed diagnostics")
794
+ .option("--json", "Output as JSON")
795
+ .action(
796
+ async (options: {
797
+ account?: string;
798
+ name?: string;
799
+ avatarUrl?: string;
800
+ verbose?: boolean;
801
+ json?: boolean;
802
+ }) => {
803
+ await runMatrixCliCommand({
804
+ verbose: options.verbose === true,
805
+ json: options.json === true,
806
+ run: async () =>
807
+ await setMatrixProfile({
808
+ account: options.account,
809
+ name: options.name,
810
+ avatarUrl: options.avatarUrl,
811
+ }),
812
+ onText: (result) => {
813
+ printAccountLabel(result.accountId);
814
+ console.log(`Config path: ${result.configPath}`);
815
+ console.log(
816
+ `Profile update: name ${result.profile.displayNameUpdated ? "updated" : "unchanged"}, avatar ${result.profile.avatarUpdated ? "updated" : "unchanged"}`,
817
+ );
818
+ if (result.profile.convertedAvatarFromHttp && result.avatarUrl) {
819
+ console.log(`Avatar converted and saved as: ${result.avatarUrl}`);
820
+ }
821
+ },
822
+ errorPrefix: "Profile update failed",
823
+ });
824
+ },
825
+ );
826
+
827
+ const direct = root.command("direct").description("Inspect and repair Matrix direct-room state");
828
+
829
+ direct
830
+ .command("inspect")
831
+ .description("Inspect direct-room mappings for a Matrix user")
832
+ .requiredOption("--user-id <id>", "Peer Matrix user ID")
833
+ .option("--account <id>", "Account ID (for multi-account setups)")
834
+ .option("--verbose", "Show detailed diagnostics")
835
+ .option("--json", "Output as JSON")
836
+ .action(
837
+ async (options: { userId: string; account?: string; verbose?: boolean; json?: boolean }) => {
838
+ const accountId = resolveMatrixCliAccountId(options.account);
839
+ await runMatrixCliCommand({
840
+ verbose: options.verbose === true,
841
+ json: options.json === true,
842
+ run: async () =>
843
+ await inspectMatrixDirectRoom({
844
+ accountId,
845
+ userId: options.userId,
846
+ }),
847
+ onText: (result) => {
848
+ printDirectRoomInspection(result);
849
+ },
850
+ errorPrefix: "Direct room inspection failed",
851
+ });
852
+ },
853
+ );
854
+
855
+ direct
856
+ .command("repair")
857
+ .description("Repair Matrix direct-room mappings for a Matrix user")
858
+ .requiredOption("--user-id <id>", "Peer Matrix user ID")
859
+ .option("--account <id>", "Account ID (for multi-account setups)")
860
+ .option("--verbose", "Show detailed diagnostics")
861
+ .option("--json", "Output as JSON")
862
+ .action(
863
+ async (options: { userId: string; account?: string; verbose?: boolean; json?: boolean }) => {
864
+ const accountId = resolveMatrixCliAccountId(options.account);
865
+ await runMatrixCliCommand({
866
+ verbose: options.verbose === true,
867
+ json: options.json === true,
868
+ run: async () =>
869
+ await repairMatrixDirectRoom({
870
+ accountId,
871
+ userId: options.userId,
872
+ }),
873
+ onText: (result, verbose) => {
874
+ printDirectRoomInspection(result);
875
+ console.log(`Encrypted room creation: ${result.encrypted ? "enabled" : "disabled"}`);
876
+ console.log(`Created room: ${result.createdRoomId ?? "none"}`);
877
+ console.log(`m.direct updated: ${result.changed ? "yes" : "no"}`);
878
+ if (verbose) {
879
+ console.log(
880
+ `m.direct before: ${JSON.stringify(result.directContentBefore[result.remoteUserId] ?? [])}`,
881
+ );
882
+ console.log(
883
+ `m.direct after: ${JSON.stringify(result.directContentAfter[result.remoteUserId] ?? [])}`,
884
+ );
885
+ }
886
+ },
887
+ errorPrefix: "Direct room repair failed",
888
+ });
889
+ },
890
+ );
891
+
892
+ const verify = root.command("verify").description("Device verification for Matrix E2EE");
893
+
894
+ verify
895
+ .command("status")
896
+ .description("Check Matrix device verification status")
897
+ .option("--account <id>", "Account ID (for multi-account setups)")
898
+ .option("--verbose", "Show detailed diagnostics")
899
+ .option("--include-recovery-key", "Include stored recovery key in output")
900
+ .option("--json", "Output as JSON")
901
+ .action(
902
+ async (options: {
903
+ account?: string;
904
+ verbose?: boolean;
905
+ includeRecoveryKey?: boolean;
906
+ json?: boolean;
907
+ }) => {
908
+ const accountId = resolveMatrixCliAccountId(options.account);
909
+ await runMatrixCliCommand({
910
+ verbose: options.verbose === true,
911
+ json: options.json === true,
912
+ run: async () =>
913
+ await getMatrixVerificationStatus({
914
+ accountId,
915
+ includeRecoveryKey: options.includeRecoveryKey === true,
916
+ }),
917
+ onText: (status, verbose) => {
918
+ printAccountLabel(accountId);
919
+ printVerificationStatus(status, verbose, accountId);
920
+ },
921
+ errorPrefix: "Error",
922
+ });
923
+ },
924
+ );
925
+
926
+ const backup = verify.command("backup").description("Matrix room-key backup health and restore");
927
+
928
+ backup
929
+ .command("status")
930
+ .description("Show Matrix room-key backup status for this device")
931
+ .option("--account <id>", "Account ID (for multi-account setups)")
932
+ .option("--verbose", "Show detailed diagnostics")
933
+ .option("--json", "Output as JSON")
934
+ .action(async (options: { account?: string; verbose?: boolean; json?: boolean }) => {
935
+ const accountId = resolveMatrixCliAccountId(options.account);
936
+ await runMatrixCliCommand({
937
+ verbose: options.verbose === true,
938
+ json: options.json === true,
939
+ run: async () => await getMatrixRoomKeyBackupStatus({ accountId }),
940
+ onText: (status, verbose) => {
941
+ printAccountLabel(accountId);
942
+ printBackupSummary(status);
943
+ if (verbose) {
944
+ printBackupStatus(status);
945
+ }
946
+ },
947
+ errorPrefix: "Backup status failed",
948
+ });
949
+ });
950
+
951
+ backup
952
+ .command("reset")
953
+ .description(
954
+ "Delete the current server backup and create a fresh room-key backup baseline, repairing secret storage if needed for a durable reset",
955
+ )
956
+ .option("--account <id>", "Account ID (for multi-account setups)")
957
+ .option("--yes", "Confirm destructive backup reset", false)
958
+ .option("--verbose", "Show detailed diagnostics")
959
+ .option("--json", "Output as JSON")
960
+ .action(
961
+ async (options: { account?: string; yes?: boolean; verbose?: boolean; json?: boolean }) => {
962
+ const accountId = resolveMatrixCliAccountId(options.account);
963
+ await runMatrixCliCommand({
964
+ verbose: options.verbose === true,
965
+ json: options.json === true,
966
+ run: async () => {
967
+ if (options.yes !== true) {
968
+ throw new Error("Refusing to reset Matrix room-key backup without --yes");
969
+ }
970
+ return await resetMatrixRoomKeyBackup({ accountId });
971
+ },
972
+ onText: (result, verbose) => {
973
+ printAccountLabel(accountId);
974
+ console.log(`Reset success: ${result.success ? "yes" : "no"}`);
975
+ if (result.error) {
976
+ console.log(`Error: ${result.error}`);
977
+ }
978
+ console.log(`Previous backup version: ${result.previousVersion ?? "none"}`);
979
+ console.log(`Deleted backup version: ${result.deletedVersion ?? "none"}`);
980
+ console.log(`Current backup version: ${result.createdVersion ?? "none"}`);
981
+ printBackupSummary(result.backup);
982
+ if (verbose) {
983
+ printTimestamp("Reset at", result.resetAt);
984
+ printBackupStatus(result.backup);
985
+ }
986
+ },
987
+ shouldFail: (result) => !result.success,
988
+ errorPrefix: "Backup reset failed",
989
+ onJsonError: (message) => ({ success: false, error: message }),
990
+ });
991
+ },
992
+ );
993
+
994
+ backup
995
+ .command("restore")
996
+ .description("Restore encrypted room keys from server backup")
997
+ .option("--account <id>", "Account ID (for multi-account setups)")
998
+ .option("--recovery-key <key>", "Optional recovery key to load before restoring")
999
+ .option("--verbose", "Show detailed diagnostics")
1000
+ .option("--json", "Output as JSON")
1001
+ .action(
1002
+ async (options: {
1003
+ account?: string;
1004
+ recoveryKey?: string;
1005
+ verbose?: boolean;
1006
+ json?: boolean;
1007
+ }) => {
1008
+ const accountId = resolveMatrixCliAccountId(options.account);
1009
+ await runMatrixCliCommand({
1010
+ verbose: options.verbose === true,
1011
+ json: options.json === true,
1012
+ run: async () =>
1013
+ await restoreMatrixRoomKeyBackup({
1014
+ accountId,
1015
+ recoveryKey: options.recoveryKey,
1016
+ }),
1017
+ onText: (result, verbose) => {
1018
+ printAccountLabel(accountId);
1019
+ console.log(`Restore success: ${result.success ? "yes" : "no"}`);
1020
+ if (result.error) {
1021
+ console.log(`Error: ${result.error}`);
1022
+ }
1023
+ console.log(`Backup version: ${result.backupVersion ?? "none"}`);
1024
+ console.log(`Imported keys: ${result.imported}/${result.total}`);
1025
+ printBackupSummary(result.backup);
1026
+ if (verbose) {
1027
+ console.log(
1028
+ `Loaded key from secret storage: ${result.loadedFromSecretStorage ? "yes" : "no"}`,
1029
+ );
1030
+ printTimestamp("Restored at", result.restoredAt);
1031
+ printBackupStatus(result.backup);
1032
+ }
1033
+ },
1034
+ shouldFail: (result) => !result.success,
1035
+ errorPrefix: "Backup restore failed",
1036
+ onJsonError: (message) => ({ success: false, error: message }),
1037
+ });
1038
+ },
1039
+ );
1040
+
1041
+ verify
1042
+ .command("bootstrap")
1043
+ .description("Bootstrap Matrix cross-signing and device verification state")
1044
+ .option("--account <id>", "Account ID (for multi-account setups)")
1045
+ .option("--recovery-key <key>", "Recovery key to apply before bootstrap")
1046
+ .option("--force-reset-cross-signing", "Force reset cross-signing identity before bootstrap")
1047
+ .option("--verbose", "Show detailed diagnostics")
1048
+ .option("--json", "Output as JSON")
1049
+ .action(
1050
+ async (options: {
1051
+ account?: string;
1052
+ recoveryKey?: string;
1053
+ forceResetCrossSigning?: boolean;
1054
+ verbose?: boolean;
1055
+ json?: boolean;
1056
+ }) => {
1057
+ const accountId = resolveMatrixCliAccountId(options.account);
1058
+ await runMatrixCliCommand({
1059
+ verbose: options.verbose === true,
1060
+ json: options.json === true,
1061
+ run: async () =>
1062
+ await bootstrapMatrixVerification({
1063
+ accountId,
1064
+ recoveryKey: options.recoveryKey,
1065
+ forceResetCrossSigning: options.forceResetCrossSigning === true,
1066
+ }),
1067
+ onText: (result, verbose) => {
1068
+ printAccountLabel(accountId);
1069
+ console.log(`Bootstrap success: ${result.success ? "yes" : "no"}`);
1070
+ if (result.error) {
1071
+ console.log(`Error: ${result.error}`);
1072
+ }
1073
+ console.log(`Verified by owner: ${result.verification.verified ? "yes" : "no"}`);
1074
+ printVerificationIdentity(result.verification);
1075
+ if (verbose) {
1076
+ printVerificationTrustDiagnostics(result.verification);
1077
+ console.log(
1078
+ `Cross-signing published: ${result.crossSigning.published ? "yes" : "no"} (master=${result.crossSigning.masterKeyPublished ? "yes" : "no"}, self=${result.crossSigning.selfSigningKeyPublished ? "yes" : "no"}, user=${result.crossSigning.userSigningKeyPublished ? "yes" : "no"})`,
1079
+ );
1080
+ printVerificationBackupStatus(result.verification);
1081
+ printTimestamp("Recovery key created at", result.verification.recoveryKeyCreatedAt);
1082
+ console.log(`Pending verifications: ${result.pendingVerifications}`);
1083
+ } else {
1084
+ console.log(
1085
+ `Cross-signing published: ${result.crossSigning.published ? "yes" : "no"}`,
1086
+ );
1087
+ printVerificationBackupSummary(result.verification);
1088
+ }
1089
+ printVerificationGuidance(
1090
+ {
1091
+ ...result.verification,
1092
+ pendingVerifications: result.pendingVerifications,
1093
+ },
1094
+ accountId,
1095
+ );
1096
+ },
1097
+ shouldFail: (result) => !result.success,
1098
+ errorPrefix: "Verification bootstrap failed",
1099
+ onJsonError: (message) => ({ success: false, error: message }),
1100
+ });
1101
+ },
1102
+ );
1103
+
1104
+ verify
1105
+ .command("device <key>")
1106
+ .description("Verify device using a Matrix recovery key")
1107
+ .option("--account <id>", "Account ID (for multi-account setups)")
1108
+ .option("--verbose", "Show detailed diagnostics")
1109
+ .option("--json", "Output as JSON")
1110
+ .action(
1111
+ async (key: string, options: { account?: string; verbose?: boolean; json?: boolean }) => {
1112
+ const accountId = resolveMatrixCliAccountId(options.account);
1113
+ await runMatrixCliCommand({
1114
+ verbose: options.verbose === true,
1115
+ json: options.json === true,
1116
+ run: async () => await verifyMatrixRecoveryKey(key, { accountId }),
1117
+ onText: (result, verbose) => {
1118
+ printAccountLabel(accountId);
1119
+ if (!result.success) {
1120
+ console.error(`Verification failed: ${result.error ?? "unknown error"}`);
1121
+ return;
1122
+ }
1123
+ console.log("Device verification completed successfully.");
1124
+ printVerificationIdentity(result);
1125
+ printVerificationBackupSummary(result);
1126
+ if (verbose) {
1127
+ printVerificationTrustDiagnostics(result);
1128
+ printVerificationBackupStatus(result);
1129
+ printTimestamp("Recovery key created at", result.recoveryKeyCreatedAt);
1130
+ printTimestamp("Verified at", result.verifiedAt);
1131
+ }
1132
+ printVerificationGuidance(
1133
+ {
1134
+ ...result,
1135
+ pendingVerifications: 0,
1136
+ },
1137
+ accountId,
1138
+ );
1139
+ },
1140
+ shouldFail: (result) => !result.success,
1141
+ errorPrefix: "Verification failed",
1142
+ onJsonError: (message) => ({ success: false, error: message }),
1143
+ });
1144
+ },
1145
+ );
1146
+
1147
+ const devices = root.command("devices").description("Inspect and clean up Matrix devices");
1148
+
1149
+ devices
1150
+ .command("list")
1151
+ .description("List server-side Matrix devices for this account")
1152
+ .option("--account <id>", "Account ID (for multi-account setups)")
1153
+ .option("--verbose", "Show detailed diagnostics")
1154
+ .option("--json", "Output as JSON")
1155
+ .action(async (options: { account?: string; verbose?: boolean; json?: boolean }) => {
1156
+ const accountId = resolveMatrixCliAccountId(options.account);
1157
+ await runMatrixCliCommand({
1158
+ verbose: options.verbose === true,
1159
+ json: options.json === true,
1160
+ run: async () => await listMatrixOwnDevices({ accountId }),
1161
+ onText: (result) => {
1162
+ printAccountLabel(accountId);
1163
+ printMatrixOwnDevices(result);
1164
+ },
1165
+ errorPrefix: "Device listing failed",
1166
+ });
1167
+ });
1168
+
1169
+ devices
1170
+ .command("prune-stale")
1171
+ .description("Delete stale OpenClaw-managed devices for this account")
1172
+ .option("--account <id>", "Account ID (for multi-account setups)")
1173
+ .option("--verbose", "Show detailed diagnostics")
1174
+ .option("--json", "Output as JSON")
1175
+ .action(async (options: { account?: string; verbose?: boolean; json?: boolean }) => {
1176
+ const accountId = resolveMatrixCliAccountId(options.account);
1177
+ await runMatrixCliCommand({
1178
+ verbose: options.verbose === true,
1179
+ json: options.json === true,
1180
+ run: async () => await pruneMatrixStaleGatewayDevices({ accountId }),
1181
+ onText: (result, verbose) => {
1182
+ printAccountLabel(accountId);
1183
+ console.log(
1184
+ `Deleted stale OpenClaw devices: ${result.deletedDeviceIds.length ? result.deletedDeviceIds.join(", ") : "none"}`,
1185
+ );
1186
+ console.log(`Current device: ${result.currentDeviceId ?? "unknown"}`);
1187
+ console.log(`Remaining devices: ${result.remainingDevices.length}`);
1188
+ if (verbose) {
1189
+ console.log("Devices before cleanup:");
1190
+ printMatrixOwnDevices(result.before);
1191
+ console.log("Devices after cleanup:");
1192
+ printMatrixOwnDevices(result.remainingDevices);
1193
+ }
1194
+ },
1195
+ errorPrefix: "Device cleanup failed",
1196
+ });
1197
+ });
1198
+ }