@openclaw/matrix 2026.7.2-beta.3 → 2026.7.2-beta.5

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 (77) hide show
  1. package/README.md +1 -1
  2. package/dist/api.js +4 -4
  3. package/dist/{approval-handler.runtime-BEa98wwG.js → approval-handler.runtime-D1ibJgSk.js} +4 -4
  4. package/dist/{approval-ids-Dfn7oQAm.js → approval-ids-2OQj32-K.js} +1 -1
  5. package/dist/{approval-reaction-auth-kXkCJBGi.js → approval-reaction-auth-CCAWWkbu.js} +2 -2
  6. package/dist/{channel-j331Xd7b.js → channel-Cmi248PA.js} +34 -32
  7. package/dist/channel-plugin-api.js +1 -1
  8. package/dist/{channel.runtime-BIwlVfQw.js → channel.runtime-BaPXFRgT.js} +34 -40
  9. package/dist/{cli-0EcKfqFw.js → cli-0CNHkps5.js} +868 -852
  10. package/dist/{cli-metadata-Xq1Xb15R.js → cli-metadata-DnXxNCoj.js} +1 -1
  11. package/dist/cli-metadata.js +1 -1
  12. package/dist/{client-CA0PULls.js → client-BFRg0kd4.js} +2 -2
  13. package/dist/{client-BtG4quUl.js → client-CitERujx.js} +2 -2
  14. package/dist/{client-bootstrap-Dk5EAn3n.js → client-bootstrap-CkAnkzB6.js} +1 -1
  15. package/dist/{config-schema-B5GRV8wL.js → config-schema-BShrVROw.js} +19 -6
  16. package/dist/contract-api.js +2 -2
  17. package/dist/{create-client-WQExaby_.js → create-client-f-CkRllE.js} +3 -3
  18. package/dist/{crypto-runtime-CAff-n15.js → crypto-runtime-D9_6J5tZ.js} +2 -2
  19. package/dist/{device-health-D4LBxuPq.js → device-health-B4-YXtJR.js} +6 -1
  20. package/dist/{directory-live-DiC-0XBC.js → directory-live-YRgYDx2w.js} +3 -3
  21. package/dist/{doctor-DwUVm5Lw.js → doctor-CM8ijNpW.js} +1 -1
  22. package/dist/doctor-contract-BMSJkkAE.js +167 -0
  23. package/dist/doctor-contract-api.js +112 -71
  24. package/dist/{draft-stream-CTLKtJJ0.js → draft-stream-CIjafRr0.js} +1 -1
  25. package/dist/{file-sync-store-CPkgnSXp.js → file-sync-store-DiiFsayX.js} +1 -1
  26. package/dist/{http-client-BmrgOZTL.js → http-client-CycYxU9-.js} +2 -2
  27. package/dist/{idb-persistence-Dyy6ipgU.js → idb-persistence-B6x7dMsF.js} +75 -72
  28. package/dist/index.js +1 -1
  29. package/dist/{logging-QH-48Gr6.js → logging-DV-p52N0.js} +8 -1
  30. package/dist/{media-text-BMXEXb1j.js → media-text-DlQC_k_K.js} +1 -1
  31. package/dist/{messages-3UBHfZrN.js → messages-Bf_s--M9.js} +3 -3
  32. package/dist/{monitor-BtUIds8T.js → monitor-s--XqoxF.js} +2041 -1804
  33. package/dist/plugin-entry.handlers.runtime.js +1 -1
  34. package/dist/probe.runtime-BJOvCHnZ.js +3 -0
  35. package/dist/{profile-update-Bh2XtJwN.js → profile-update-z3aM46KS.js} +2 -2
  36. package/dist/{reaction-events-BwAKtUyQ.js → reaction-events-DrK9Zua7.js} +2 -2
  37. package/dist/{recovery-key-store-CW6eePfp.js → recovery-key-store-BNnHvXdk.js} +1 -1
  38. package/dist/{resolve-targets-DVoj-YxB.js → resolve-targets-nNMcrV3W.js} +1 -1
  39. package/dist/{resolver.runtime-CC0VVsAt.js → resolver.runtime-BvaFlVLg.js} +1 -1
  40. package/dist/{room-info-B6vKD5DF.js → room-info-CAFZ3Z9J.js} +13 -12
  41. package/dist/{sdk-CIDZXWpZ.js → sdk-UzPd8tst.js} +227 -181
  42. package/dist/{send-BJbrdmNm.js → send-C9Ssx-iV.js} +624 -109
  43. package/dist/session-binding-contract-api.js +1 -1
  44. package/dist/{setup-bootstrap-DGPOOdz-.js → setup-bootstrap-BBGpPKgy.js} +2 -2
  45. package/dist/{setup-core-XCdAx1nY.js → setup-core-a542Ernq.js} +135 -45
  46. package/dist/setup-plugin-api.js +4 -3
  47. package/dist/{setup-surface-CzUiTe_k.js → setup-surface-BJrCI6KT.js} +34 -30
  48. package/dist/{shared-DquM1oz6.js → shared-CUH5otj8.js} +5 -12
  49. package/dist/{startup-verification-CA00kebL.js → startup-verification-wm3_i88s.js} +1 -1
  50. package/dist/{storage-CzHxeF5E.js → storage-BvAkgzvT.js} +24 -57
  51. package/dist/{thread-bindings-Cw194yEn.js → thread-bindings-D3RfVgAF.js} +4 -3
  52. package/dist/{tool-actions.runtime-C0jgWYhX.js → tool-actions.runtime-Dh5ow2EK.js} +8 -8
  53. package/dist/{verification-DjxyWTNP.js → verification-ZdAXdmuh.js} +1 -1
  54. package/node_modules/music-metadata/lib/common/Util.d.ts +1 -1
  55. package/node_modules/music-metadata/lib/common/Util.js +7 -1
  56. package/node_modules/music-metadata/lib/id3v2/FrameHeader.js +23 -3
  57. package/node_modules/music-metadata/lib/id3v2/FrameParser.js +2 -2
  58. package/node_modules/music-metadata/lib/id3v2/ID3v2Token.js +1 -1
  59. package/node_modules/music-metadata/lib/mp4/AtomToken.js +38 -13
  60. package/node_modules/music-metadata/lib/mpeg/MpegParser.js +1 -1
  61. package/node_modules/music-metadata/package.json +6 -6
  62. package/node_modules/typebox/build/compile/validator.d.mts +1 -4
  63. package/node_modules/typebox/build/guard/guard.d.mts +1 -1
  64. package/node_modules/typebox/build/guard/guard.mjs +5 -2
  65. package/node_modules/typebox/build/guard/string.mjs +16 -4
  66. package/node_modules/typebox/build/schema/engine/_functions.mjs +34 -15
  67. package/node_modules/typebox/build/type/action/readonly_object.d.mts +5 -0
  68. package/node_modules/typebox/build/type/action/readonly_object.mjs +8 -0
  69. package/node_modules/typebox/build/typebox.d.mts +1 -1
  70. package/node_modules/typebox/build/typebox.mjs +1 -1
  71. package/node_modules/typebox/package.json +1 -1
  72. package/node_modules/typebox/readme.md +29 -32
  73. package/openclaw.plugin.json +7 -20
  74. package/package.json +111 -29
  75. package/dist/doctor-contract-BA2Y6Crx.js +0 -312
  76. package/dist/probe.runtime-sBV-Govx.js +0 -3
  77. package/npm-shrinkwrap.json +0 -557
@@ -1,44 +1,23 @@
1
1
  import { a as resolveMatrixAccountConfig } from "./account-config-BZWN9tGS.js";
2
2
  import { t as getMatrixRuntime } from "./runtime-6S3DNFNv.js";
3
- import { c as resolveMatrixConfigPath, g as resolveMatrixAccount, l as updateMatrixAccountConfig, n as matrixSetupAdapter } from "./setup-core-XCdAx1nY.js";
3
+ import { _ as resolveMatrixAccount, l as resolveMatrixConfigPath, n as matrixSetupAdapter, u as updateMatrixAccountConfig } from "./setup-core-a542Ernq.js";
4
4
  import { t as formatMatrixErrorMessage } from "./errors-C47hvAF8.js";
5
- import { n as withResolvedActionClient } from "./client-BtG4quUl.js";
6
- import { p as resolveMatrixAuthContext } from "./shared-DquM1oz6.js";
7
- import "./client-CA0PULls.js";
5
+ import { n as withResolvedActionClient } from "./client-CitERujx.js";
6
+ import { p as resolveMatrixAuthContext } from "./shared-CUH5otj8.js";
7
+ import "./client-BFRg0kd4.js";
8
8
  import { a as formatZonedTimestamp } from "./runtime-api-D1xI_cvh.js";
9
- import { isOpenClawManagedMatrixDevice, summarizeMatrixDeviceHealth } from "./device-health-D4LBxuPq.js";
10
- import { n as updateMatrixOwnProfile, t as applyMatrixProfileUpdate } from "./profile-update-Bh2XtJwN.js";
11
- import { a as confirmMatrixVerificationSas, b as verifyMatrixRecoveryKey, c as getMatrixRoomKeyBackupStatus, d as listMatrixVerifications, f as mismatchMatrixVerificationSas, g as runMatrixSelfVerification, h as restoreMatrixRoomKeyBackup, l as getMatrixVerificationSas, m as resetMatrixRoomKeyBackup, n as bootstrapMatrixVerification, p as requestMatrixVerification, r as cancelMatrixVerification, t as acceptMatrixVerification, u as getMatrixVerificationStatus, v as startMatrixVerification } from "./verification-DjxyWTNP.js";
12
9
  import { t as resolveMatrixRoomKeyBackupIssue } from "./backup-health-Dm_YMVFT.js";
13
- import { setMatrixSdkConsoleLogging, setMatrixSdkLogMode } from "./logging-QH-48Gr6.js";
10
+ import { i as setMatrixSdkLogMode, r as setMatrixSdkConsoleLogging } from "./logging-DV-p52N0.js";
11
+ import { n as isOpenClawManagedMatrixDevice, r as summarizeMatrixDeviceHealth } from "./device-health-B4-YXtJR.js";
12
+ import { n as updateMatrixOwnProfile, t as applyMatrixProfileUpdate } from "./profile-update-z3aM46KS.js";
13
+ import { a as confirmMatrixVerificationSas, b as verifyMatrixRecoveryKey, c as getMatrixRoomKeyBackupStatus, d as listMatrixVerifications, f as mismatchMatrixVerificationSas, g as runMatrixSelfVerification, h as restoreMatrixRoomKeyBackup, l as getMatrixVerificationSas, m as resetMatrixRoomKeyBackup, n as bootstrapMatrixVerification, p as requestMatrixVerification, r as cancelMatrixVerification, t as acceptMatrixVerification, u as getMatrixVerificationStatus, v as startMatrixVerification } from "./verification-ZdAXdmuh.js";
14
14
  import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
15
15
  import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
16
16
  import { parseStrictInteger, timestampMsToIsoString } from "openclaw/plugin-sdk/number-runtime";
17
- //#region extensions/matrix/src/matrix/actions/devices.ts
18
- async function listMatrixOwnDevices(opts = {}) {
19
- return await withResolvedActionClient(opts, async (client) => await client.listOwnDevices());
20
- }
21
- async function pruneMatrixStaleGatewayDevices(opts = {}) {
22
- return await withResolvedActionClient(opts, async (client) => {
23
- const devices = await client.listOwnDevices();
24
- const staleGatewayDeviceIds = summarizeMatrixDeviceHealth(devices).staleOpenClawDevices.map((device) => device.deviceId);
25
- return {
26
- before: devices,
27
- staleGatewayDeviceIds,
28
- ...staleGatewayDeviceIds.length > 0 ? await client.deleteOwnDevices(staleGatewayDeviceIds) : {
29
- currentDeviceId: devices.find((device) => device.current)?.deviceId ?? null,
30
- deletedDeviceIds: [],
31
- remainingDevices: devices
32
- }
33
- };
34
- });
35
- }
36
- //#endregion
37
- //#region extensions/matrix/src/cli.ts
17
+ import { readByteStreamWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
18
+ //#region extensions/matrix/src/cli-shared.ts
38
19
  let matrixCliExitScheduled = false;
39
20
  const MATRIX_CLI_RECOVERY_KEY_STDIN_MAX_BYTES = 1024 * 1024;
40
- const loadMatrixActionClientModule = createLazyRuntimeModule(() => import("./client-BtG4quUl.js").then((n) => n.t));
41
- const loadMatrixDirectManagementModule = createLazyRuntimeModule(() => import("./send-BJbrdmNm.js").then((n) => n.d));
42
21
  function scheduleMatrixCliExit() {
43
22
  if (matrixCliExitScheduled || process.env.VITEST) return;
44
23
  matrixCliExitScheduled = true;
@@ -54,15 +33,10 @@ function markCliFailure() {
54
33
  process.exitCode = 1;
55
34
  }
56
35
  async function readMatrixCliRecoveryKeyFromStdin() {
57
- const chunks = [];
58
- let totalBytes = 0;
59
- for await (const chunk of process.stdin) {
60
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
61
- totalBytes += buffer.byteLength;
62
- if (totalBytes > MATRIX_CLI_RECOVERY_KEY_STDIN_MAX_BYTES) throw new Error(`Matrix recovery key stdin exceeds ${MATRIX_CLI_RECOVERY_KEY_STDIN_MAX_BYTES} bytes.`);
63
- chunks.push(buffer);
64
- }
65
- const recoveryKey = Buffer.concat(chunks, totalBytes).toString("utf8").trim();
36
+ const recoveryKey = (await readByteStreamWithLimit(process.stdin, {
37
+ maxBytes: MATRIX_CLI_RECOVERY_KEY_STDIN_MAX_BYTES,
38
+ onOverflow: ({ maxBytes }) => /* @__PURE__ */ new Error(`Matrix recovery key stdin exceeds ${maxBytes} bytes.`)
39
+ })).toString("utf8").trim();
66
40
  if (!recoveryKey) throw new Error("Matrix recovery key was requested from stdin, but stdin was empty.");
67
41
  return recoveryKey;
68
42
  }
@@ -76,28 +50,18 @@ async function requireMatrixCliRecoveryKeyInput(options) {
76
50
  if (!recoveryKey) throw new Error("Matrix recovery key is required. Pass --recovery-key-stdin to read it from stdin.");
77
51
  return recoveryKey;
78
52
  }
79
- function toErrorMessage(err) {
80
- return formatMatrixErrorMessage(err);
81
- }
82
53
  function printJson(payload) {
83
54
  process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
84
55
  }
85
- function formatLocalTimestamp(value) {
86
- if (!value) return null;
87
- const parsed = new Date(value);
88
- if (!Number.isFinite(parsed.getTime())) return value;
89
- return formatZonedTimestamp(parsed, { displaySeconds: true }) ?? value;
90
- }
91
56
  function printTimestamp(label, value) {
92
- const formatted = formatLocalTimestamp(value);
93
- if (formatted) console.log(`${label}: ${formatMatrixCliText(formatted)}`);
57
+ if (!value) return;
58
+ const parsed = new Date(value);
59
+ const formatted = Number.isFinite(parsed.getTime()) ? formatZonedTimestamp(parsed, { displaySeconds: true }) ?? value : value;
60
+ console.log(`${label}: ${formatMatrixCliText(formatted)}`);
94
61
  }
95
62
  function printAccountLabel(accountId) {
96
63
  console.log(`Account: ${formatMatrixCliText(normalizeAccountId(accountId))}`);
97
64
  }
98
- function resolveMatrixCliAccountId(accountId) {
99
- return resolveMatrixCliAccountContext(accountId).accountId;
100
- }
101
65
  function resolveMatrixCliAccountContext(accountId) {
102
66
  const cfg = getMatrixRuntime().config.current();
103
67
  return {
@@ -136,19 +100,6 @@ function formatMatrixCliShellArg(value) {
136
100
  function formatMatrixCliText(value, fallback = "unknown") {
137
101
  return sanitizeMatrixCliText(value ?? fallback);
138
102
  }
139
- function printMatrixOwnDevices(devices) {
140
- if (devices.length === 0) {
141
- console.log("Devices: none");
142
- return;
143
- }
144
- for (const device of devices) {
145
- const labels = [device.current ? "current" : null, device.displayName].filter((label) => Boolean(label)).map((label) => formatMatrixCliText(label));
146
- console.log(`- ${formatMatrixCliText(device.deviceId)}${labels.length ? ` (${labels.join(", ")})` : ""}`);
147
- const lastSeenAt = timestampMsToIsoString(device.lastSeenTs);
148
- if (lastSeenAt) printTimestamp(" Last seen", lastSeenAt);
149
- if (device.lastSeenIp) console.log(` Last IP: ${formatMatrixCliText(device.lastSeenIp)}`);
150
- }
151
- }
152
103
  function configureCliLogMode(verbose) {
153
104
  setMatrixSdkLogMode(verbose ? "default" : "quiet");
154
105
  setMatrixSdkConsoleLogging(verbose);
@@ -162,209 +113,6 @@ function parseOptionalInt(value, fieldName, opts = {}) {
162
113
  if (opts.min !== void 0 && parsed < opts.min) throw new Error(opts.min === 1 ? `${fieldName} must be a positive integer` : `${fieldName} must be a non-negative integer`);
163
114
  return parsed;
164
115
  }
165
- async function addMatrixAccount(params) {
166
- const initialSyncLimit = parseOptionalInt(params.initialSyncLimit, "--initial-sync-limit", { min: 0 });
167
- const runtime = getMatrixRuntime();
168
- const cfg = runtime.config.current();
169
- if (!matrixSetupAdapter.applyAccountConfig) throw new Error("Matrix account setup is unavailable.");
170
- const input = {
171
- name: params.name,
172
- avatarUrl: params.avatarUrl,
173
- homeserver: params.homeserver,
174
- dangerouslyAllowPrivateNetwork: params.allowPrivateNetwork,
175
- proxy: params.proxy,
176
- userId: params.userId,
177
- accessToken: params.accessToken,
178
- password: params.password,
179
- deviceName: params.deviceName,
180
- initialSyncLimit,
181
- useEnv: params.useEnv === true
182
- };
183
- const accountId = matrixSetupAdapter.resolveAccountId?.({
184
- cfg,
185
- accountId: params.account,
186
- input
187
- }) ?? normalizeAccountId(params.account?.trim() || params.name?.trim());
188
- const validationError = matrixSetupAdapter.validateInput?.({
189
- cfg,
190
- accountId,
191
- input
192
- });
193
- if (validationError) throw new Error(validationError);
194
- let updated = matrixSetupAdapter.applyAccountConfig({
195
- cfg,
196
- accountId,
197
- input
198
- });
199
- if (params.enableEncryption === true) updated = updateMatrixAccountConfig(updated, accountId, { encryption: true });
200
- await runtime.config.replaceConfigFile({
201
- nextConfig: updated,
202
- afterWrite: { mode: "auto" }
203
- });
204
- const accountConfig = resolveMatrixAccountConfig({
205
- cfg: updated,
206
- accountId
207
- });
208
- let verificationBootstrap = {
209
- attempted: false,
210
- success: false,
211
- recoveryKeyCreatedAt: null,
212
- backupVersion: null
213
- };
214
- if (accountConfig.encryption === true) {
215
- const { maybeBootstrapNewEncryptedMatrixAccount } = await import("./setup-bootstrap-DGPOOdz-.js");
216
- verificationBootstrap = await maybeBootstrapNewEncryptedMatrixAccount({
217
- previousCfg: cfg,
218
- cfg: updated,
219
- accountId
220
- });
221
- }
222
- const desiredDisplayName = input.name?.trim();
223
- const desiredAvatarUrl = input.avatarUrl?.trim();
224
- let profile = {
225
- attempted: false,
226
- displayNameUpdated: false,
227
- avatarUpdated: false,
228
- resolvedAvatarUrl: null,
229
- convertedAvatarFromHttp: false
230
- };
231
- if (desiredDisplayName || desiredAvatarUrl) try {
232
- const synced = await updateMatrixOwnProfile({
233
- cfg: updated,
234
- accountId,
235
- displayName: desiredDisplayName,
236
- avatarUrl: desiredAvatarUrl
237
- });
238
- let resolvedAvatarUrl = synced.resolvedAvatarUrl;
239
- if (synced.convertedAvatarFromHttp && synced.resolvedAvatarUrl) {
240
- const withAvatar = updateMatrixAccountConfig(runtime.config.current(), accountId, { avatarUrl: synced.resolvedAvatarUrl });
241
- await runtime.config.replaceConfigFile({
242
- nextConfig: withAvatar,
243
- afterWrite: { mode: "auto" }
244
- });
245
- resolvedAvatarUrl = synced.resolvedAvatarUrl;
246
- }
247
- profile = {
248
- attempted: true,
249
- displayNameUpdated: synced.displayNameUpdated,
250
- avatarUpdated: synced.avatarUpdated,
251
- resolvedAvatarUrl,
252
- convertedAvatarFromHttp: synced.convertedAvatarFromHttp
253
- };
254
- } catch (err) {
255
- profile = {
256
- attempted: true,
257
- displayNameUpdated: false,
258
- avatarUpdated: false,
259
- resolvedAvatarUrl: null,
260
- convertedAvatarFromHttp: false,
261
- error: toErrorMessage(err)
262
- };
263
- }
264
- let deviceHealth;
265
- try {
266
- const addedDevices = await listMatrixOwnDevices({
267
- accountId,
268
- cfg: updated
269
- });
270
- deviceHealth = {
271
- currentDeviceId: addedDevices.find((device) => device.current)?.deviceId ?? null,
272
- staleOpenClawDeviceIds: addedDevices.filter((device) => !device.current && isOpenClawManagedMatrixDevice(device.displayName)).map((device) => device.deviceId)
273
- };
274
- } catch (err) {
275
- deviceHealth = {
276
- currentDeviceId: null,
277
- staleOpenClawDeviceIds: [],
278
- error: toErrorMessage(err)
279
- };
280
- }
281
- return {
282
- accountId,
283
- configPath: resolveMatrixConfigPath(updated, accountId),
284
- useEnv: input.useEnv === true,
285
- encryptionEnabled: accountConfig.encryption === true,
286
- deviceHealth,
287
- verificationBootstrap,
288
- profile
289
- };
290
- }
291
- function printDirectRoomCandidate(room) {
292
- const members = room.joinedMembers === null ? "unavailable" : room.joinedMembers.map((member) => formatMatrixCliText(member)).join(", ") || "none";
293
- console.log(`- ${formatMatrixCliText(room.roomId)} [${room.source}] strict=${room.strict ? "yes" : "no"} joined=${members}`);
294
- }
295
- function printDirectRoomInspection(result) {
296
- printAccountLabel(result.accountId);
297
- console.log(`Peer: ${formatMatrixCliText(result.remoteUserId)}`);
298
- console.log(`Self: ${formatMatrixCliText(result.selfUserId)}`);
299
- console.log(`Active direct room: ${formatMatrixCliText(result.activeRoomId, "none")}`);
300
- console.log(`Mapped rooms: ${result.mappedRoomIds.length ? result.mappedRoomIds.map((roomId) => formatMatrixCliText(roomId)).join(", ") : "none"}`);
301
- console.log(`Discovered strict rooms: ${result.discoveredStrictRoomIds.length ? result.discoveredStrictRoomIds.map((roomId) => formatMatrixCliText(roomId)).join(", ") : "none"}`);
302
- if (result.mappedRooms.length > 0) {
303
- console.log("Mapped room details:");
304
- for (const room of result.mappedRooms) printDirectRoomCandidate(room);
305
- }
306
- }
307
- async function inspectMatrixDirectRoom(params) {
308
- const cfg = getMatrixRuntime().config.current();
309
- const [{ withResolvedActionClient }, { inspectMatrixDirectRooms }] = await Promise.all([loadMatrixActionClientModule(), loadMatrixDirectManagementModule()]);
310
- return await withResolvedActionClient({
311
- accountId: params.accountId,
312
- cfg
313
- }, async (client) => {
314
- const inspection = await inspectMatrixDirectRooms({
315
- client,
316
- remoteUserId: params.userId
317
- });
318
- return {
319
- accountId: params.accountId,
320
- remoteUserId: inspection.remoteUserId,
321
- selfUserId: inspection.selfUserId,
322
- mappedRoomIds: inspection.mappedRoomIds,
323
- mappedRooms: inspection.mappedRooms.map(toCliDirectRoomCandidate),
324
- discoveredStrictRoomIds: inspection.discoveredStrictRoomIds,
325
- activeRoomId: inspection.activeRoomId
326
- };
327
- }, "persist");
328
- }
329
- async function repairMatrixDirectRoom(params) {
330
- const cfg = getMatrixRuntime().config.current();
331
- const account = resolveMatrixAccount({
332
- cfg,
333
- accountId: params.accountId
334
- });
335
- const [{ withStartedActionClient }, { repairMatrixDirectRooms }] = await Promise.all([loadMatrixActionClientModule(), loadMatrixDirectManagementModule()]);
336
- return await withStartedActionClient({
337
- accountId: params.accountId,
338
- cfg
339
- }, async (client) => {
340
- const repaired = await repairMatrixDirectRooms({
341
- client,
342
- remoteUserId: params.userId,
343
- encrypted: account.config.encryption === true
344
- });
345
- return {
346
- accountId: params.accountId,
347
- remoteUserId: repaired.remoteUserId,
348
- selfUserId: repaired.selfUserId,
349
- mappedRoomIds: repaired.mappedRoomIds,
350
- mappedRooms: repaired.mappedRooms.map(toCliDirectRoomCandidate),
351
- discoveredStrictRoomIds: repaired.discoveredStrictRoomIds,
352
- activeRoomId: repaired.activeRoomId,
353
- encrypted: account.config.encryption === true,
354
- createdRoomId: repaired.createdRoomId,
355
- changed: repaired.changed,
356
- directContentBefore: repaired.directContentBefore,
357
- directContentAfter: repaired.directContentAfter
358
- };
359
- });
360
- }
361
- async function setMatrixProfile(params) {
362
- return await applyMatrixProfileUpdate({
363
- account: params.account,
364
- displayName: params.name,
365
- avatarUrl: params.avatarUrl
366
- });
367
- }
368
116
  async function runMatrixCliCommand(config) {
369
117
  configureCliLogMode(config.verbose);
370
118
  try {
@@ -373,7 +121,7 @@ async function runMatrixCliCommand(config) {
373
121
  else config.onText(result, config.verbose);
374
122
  if (config.shouldFail?.(result)) markCliFailure();
375
123
  } catch (err) {
376
- const message = toErrorMessage(err);
124
+ const message = formatMatrixErrorMessage(err);
377
125
  if (config.json) printJson(config.onJsonError ? config.onJsonError(message) : { error: message });
378
126
  else {
379
127
  console.error(`${config.errorPrefix}: ${formatMatrixCliText(message)}`);
@@ -384,122 +132,6 @@ async function runMatrixCliCommand(config) {
384
132
  scheduleMatrixCliExit();
385
133
  }
386
134
  }
387
- function isMatrixVerificationSetupComplete(status) {
388
- return status.encryptionEnabled && status.verified && status.crossSigningVerified && status.signedByOwner && status.serverDeviceKnown === true && resolveMatrixRoomKeyBackupIssue(resolveBackupStatus(status)).code === "ok";
389
- }
390
- function buildNoopMatrixVerificationBootstrap(status) {
391
- return {
392
- success: true,
393
- verification: {
394
- ...status,
395
- backup: resolveBackupStatus(status),
396
- serverDeviceKnown: status.serverDeviceKnown ?? null
397
- },
398
- crossSigning: {
399
- userId: status.userId,
400
- masterKeyPublished: status.crossSigningVerified,
401
- selfSigningKeyPublished: status.signedByOwner,
402
- userSigningKeyPublished: status.signedByOwner,
403
- published: status.crossSigningVerified && status.signedByOwner
404
- },
405
- pendingVerifications: status.pendingVerifications,
406
- cryptoBootstrap: null
407
- };
408
- }
409
- async function setupMatrixEncryption(params) {
410
- const runtime = getMatrixRuntime();
411
- const { accountId, cfg } = resolveMatrixCliAccountContext(params.account);
412
- if (!resolveMatrixAccount({
413
- cfg,
414
- accountId
415
- }).configured) throw new Error(`Matrix account "${accountId}" is not configured; run ${formatMatrixCliCommand("account add", accountId)} first.`);
416
- const encryptionChanged = resolveMatrixAccountConfig({
417
- cfg,
418
- accountId
419
- }).encryption !== true;
420
- const updated = encryptionChanged ? updateMatrixAccountConfig(cfg, accountId, { encryption: true }) : cfg;
421
- if (encryptionChanged) await runtime.config.replaceConfigFile({
422
- nextConfig: updated,
423
- afterWrite: { mode: "auto" }
424
- });
425
- const existingStatus = !encryptionChanged && !params.recoveryKey && params.forceResetCrossSigning !== true ? await getMatrixVerificationStatus({
426
- accountId,
427
- cfg: updated,
428
- readiness: "none"
429
- }) : null;
430
- if (existingStatus && isMatrixVerificationSetupComplete(existingStatus)) return {
431
- accountId,
432
- configPath: resolveMatrixConfigPath(updated, accountId),
433
- encryptionChanged,
434
- bootstrap: buildNoopMatrixVerificationBootstrap(existingStatus),
435
- status: existingStatus
436
- };
437
- const bootstrap = await bootstrapMatrixVerification({
438
- accountId,
439
- cfg: updated,
440
- recoveryKey: params.recoveryKey,
441
- forceResetCrossSigning: params.forceResetCrossSigning === true
442
- });
443
- const status = await getMatrixVerificationStatus({
444
- accountId,
445
- cfg: updated
446
- });
447
- return {
448
- accountId,
449
- configPath: resolveMatrixConfigPath(updated, accountId),
450
- encryptionChanged,
451
- bootstrap,
452
- status
453
- };
454
- }
455
- function toCliDirectRoomCandidate(room) {
456
- return {
457
- roomId: room.roomId,
458
- source: room.source,
459
- strict: room.strict,
460
- joinedMembers: room.joinedMembers
461
- };
462
- }
463
- function resolveBackupStatus(status) {
464
- return {
465
- serverVersion: status.backup?.serverVersion ?? status.backupVersion ?? null,
466
- activeVersion: status.backup?.activeVersion ?? null,
467
- trusted: status.backup?.trusted ?? null,
468
- matchesDecryptionKey: status.backup?.matchesDecryptionKey ?? null,
469
- decryptionKeyCached: status.backup?.decryptionKeyCached ?? null,
470
- keyLoadAttempted: status.backup?.keyLoadAttempted ?? false,
471
- keyLoadError: status.backup?.keyLoadError ?? null
472
- };
473
- }
474
- function yesNoUnknown(value) {
475
- if (value === true) return "yes";
476
- if (value === false) return "no";
477
- return "unknown";
478
- }
479
- function printBackupStatus(backup) {
480
- console.log(`Backup server version: ${formatMatrixCliText(backup.serverVersion, "none")}`);
481
- console.log(`Backup active on this device: ${formatMatrixCliText(backup.activeVersion, "no")}`);
482
- console.log(`Backup trusted by this device: ${yesNoUnknown(backup.trusted)}`);
483
- console.log(`Backup matches local decryption key: ${yesNoUnknown(backup.matchesDecryptionKey)}`);
484
- console.log(`Backup key cached locally: ${yesNoUnknown(backup.decryptionKeyCached)}`);
485
- console.log(`Backup key load attempted: ${yesNoUnknown(backup.keyLoadAttempted)}`);
486
- if (backup.keyLoadError) console.log(`Backup key load error: ${formatMatrixCliText(backup.keyLoadError)}`);
487
- }
488
- function printVerificationIdentity(status) {
489
- console.log(`User: ${formatMatrixCliText(status.userId)}`);
490
- console.log(`Device: ${formatMatrixCliText(status.deviceId)}`);
491
- }
492
- function printVerificationBackupSummary(status) {
493
- printBackupSummary(resolveBackupStatus(status));
494
- }
495
- function printVerificationBackupStatus(status) {
496
- printBackupStatus(resolveBackupStatus(status));
497
- }
498
- function printVerificationTrustDiagnostics(status) {
499
- console.log(`Locally trusted: ${status.localVerified ? "yes" : "no"}`);
500
- console.log(`Cross-signing verified: ${status.crossSigningVerified ? "yes" : "no"}`);
501
- console.log(`Signed by owner: ${status.signedByOwner ? "yes" : "no"}`);
502
- }
503
135
  function sanitizeMatrixCliText(value) {
504
136
  let withoutAnsi = "";
505
137
  for (let index = 0; index < value.length; index++) {
@@ -570,6 +202,46 @@ function isUnsafeMatrixCliTerminalCode(code) {
570
202
  function isAnsiFinalByte(code) {
571
203
  return code >= 64 && code <= 126;
572
204
  }
205
+ function resolveBackupStatus(status) {
206
+ return {
207
+ serverVersion: status.backup?.serverVersion ?? status.backupVersion ?? null,
208
+ activeVersion: status.backup?.activeVersion ?? null,
209
+ trusted: status.backup?.trusted ?? null,
210
+ matchesDecryptionKey: status.backup?.matchesDecryptionKey ?? null,
211
+ decryptionKeyCached: status.backup?.decryptionKeyCached ?? null,
212
+ keyLoadAttempted: status.backup?.keyLoadAttempted ?? false,
213
+ keyLoadError: status.backup?.keyLoadError ?? null
214
+ };
215
+ }
216
+ function yesNoUnknown(value) {
217
+ if (value === true) return "yes";
218
+ if (value === false) return "no";
219
+ return "unknown";
220
+ }
221
+ function printBackupStatus(backup) {
222
+ console.log(`Backup server version: ${formatMatrixCliText(backup.serverVersion, "none")}`);
223
+ console.log(`Backup active on this device: ${formatMatrixCliText(backup.activeVersion, "no")}`);
224
+ console.log(`Backup trusted by this device: ${yesNoUnknown(backup.trusted)}`);
225
+ console.log(`Backup matches local decryption key: ${yesNoUnknown(backup.matchesDecryptionKey)}`);
226
+ console.log(`Backup key cached locally: ${yesNoUnknown(backup.decryptionKeyCached)}`);
227
+ console.log(`Backup key load attempted: ${yesNoUnknown(backup.keyLoadAttempted)}`);
228
+ if (backup.keyLoadError) console.log(`Backup key load error: ${formatMatrixCliText(backup.keyLoadError)}`);
229
+ }
230
+ function printVerificationIdentity(status) {
231
+ console.log(`User: ${formatMatrixCliText(status.userId)}`);
232
+ console.log(`Device: ${formatMatrixCliText(status.deviceId)}`);
233
+ }
234
+ function printVerificationBackupSummary(status) {
235
+ printBackupSummary(resolveBackupStatus(status));
236
+ }
237
+ function printVerificationBackupStatus(status) {
238
+ printBackupStatus(resolveBackupStatus(status));
239
+ }
240
+ function printVerificationTrustDiagnostics(status) {
241
+ console.log(`Locally trusted: ${status.localVerified ? "yes" : "no"}`);
242
+ console.log(`Cross-signing verified: ${status.crossSigningVerified ? "yes" : "no"}`);
243
+ console.log(`Signed by owner: ${status.signedByOwner ? "yes" : "no"}`);
244
+ }
573
245
  function formatMatrixCliSasEmoji(emoji) {
574
246
  return emoji.map(([emojiValue, label]) => `${sanitizeMatrixCliText(emojiValue)} ${sanitizeMatrixCliText(label)}`).join(" | ");
575
247
  }
@@ -600,11 +272,775 @@ function printMatrixVerificationSummaries(summaries) {
600
272
  printMatrixVerificationSummary(summary);
601
273
  });
602
274
  }
603
- function printMatrixVerificationSas(sas) {
604
- if (sas.emoji?.length) console.log(`SAS emoji: ${formatMatrixCliSasEmoji(sas.emoji)}`);
605
- else if (sas.decimal) console.log(`SAS decimals: ${sas.decimal.join(" ")}`);
606
- else console.log("SAS: unavailable");
607
- }
275
+ function printMatrixVerificationSas(sas) {
276
+ if (sas.emoji?.length) console.log(`SAS emoji: ${formatMatrixCliSasEmoji(sas.emoji)}`);
277
+ else if (sas.decimal) console.log(`SAS decimals: ${sas.decimal.join(" ")}`);
278
+ else console.log("SAS: unavailable");
279
+ }
280
+ function printVerificationGuidance(status, accountId) {
281
+ printGuidance(buildVerificationGuidance(status, accountId));
282
+ }
283
+ function printBackupGuidance(backup, accountId, options = {}) {
284
+ printGuidance(buildBackupGuidance(backup, accountId, options));
285
+ }
286
+ function printBackupSummary(backup) {
287
+ const issue = resolveMatrixRoomKeyBackupIssue(backup);
288
+ console.log(`Backup: ${issue.summary}`);
289
+ if (backup.serverVersion) console.log(`Backup version: ${formatMatrixCliText(backup.serverVersion)}`);
290
+ }
291
+ function buildVerificationGuidance(status, accountId) {
292
+ const backup = resolveBackupStatus(status);
293
+ const nextSteps = /* @__PURE__ */ new Set();
294
+ if (!status.verified) if (status.recoveryKeyAccepted === true && status.backupUsable === true) {
295
+ nextSteps.add(`Recovery key can unlock the room-key backup, but full Matrix identity trust is still incomplete. Run ${formatMatrixCliCommand("verify self", accountId)}, accept the request in another verified Matrix client, and confirm the SAS only if it matches.`);
296
+ nextSteps.add(`If you intend to replace the current cross-signing identity, run the shown printf pipeline with the Matrix recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify bootstrap --recovery-key-stdin --force-reset-cross-signing", accountId)}.`);
297
+ } else nextSteps.add(`Run the shown printf pipeline with the Matrix recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify device --recovery-key-stdin", accountId)}. If you do not have the recovery key but still have another verified Matrix client, run ${formatMatrixCliCommand("verify self", accountId)} instead.`);
298
+ if (status.serverDeviceKnown === false) nextSteps.add(`This Matrix device is no longer listed on the homeserver. Create a new OpenClaw Matrix device with ${formatMatrixCliCommand("account add --homeserver <url> --user-id <@user:server> --password <password> --device-name OpenClaw-Gateway", accountId)}. If you use token auth, create a fresh Matrix access token in your Matrix client or admin UI, then run ${formatMatrixCliCommand("account add --homeserver <url> --access-token <token>", accountId)}.`);
299
+ for (const step of buildBackupGuidance(backup, accountId, { recoveryKeyStored: status.recoveryKeyStored })) nextSteps.add(step);
300
+ if (status.pendingVerifications > 0) nextSteps.add(`Review pending verification requests with ${formatMatrixCliCommand("verify list", accountId)}. Complete each active request with ${formatMatrixCliCommand("verify sas <id>", accountId)} and ${formatMatrixCliCommand("verify confirm-sas <id>", accountId)}, or cancel stale requests with ${formatMatrixCliCommand("verify cancel <id>", accountId)}.`);
301
+ return Array.from(nextSteps);
302
+ }
303
+ function buildBackupGuidance(backup, accountId, options = {}) {
304
+ const backupIssue = resolveMatrixRoomKeyBackupIssue(backup);
305
+ const nextSteps = /* @__PURE__ */ new Set();
306
+ if (backupIssue.code === "missing-server-backup") nextSteps.add(`Run ${formatMatrixCliCommand("verify bootstrap", accountId)} to create a room key backup.`);
307
+ else if (backupIssue.code === "key-load-failed" || backupIssue.code === "key-not-loaded" || backupIssue.code === "inactive") if (options.recoveryKeyStored) nextSteps.add(`Backup key is not loaded on this device. Run ${formatMatrixCliCommand("verify backup restore", accountId)} to load it and restore old room keys. If restore still cannot load the key, run the shown printf pipeline with the Matrix recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify backup restore --recovery-key-stdin", accountId)}.`);
308
+ else nextSteps.add(`Run the shown printf pipeline with the Matrix recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify backup restore --recovery-key-stdin", accountId)} to load the server backup and store the key for future restores.`);
309
+ else if (backupIssue.code === "key-mismatch") {
310
+ nextSteps.add(`Backup key mismatch on this device. Run the shown printf pipeline with the active server backup recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify backup restore --recovery-key-stdin", accountId)}.`);
311
+ nextSteps.add(`If you want a fresh backup baseline and accept losing unrecoverable history, run ${formatMatrixCliCommand("verify backup reset --yes", accountId)}. Add --rotate-recovery-key only when the old recovery key should stop unlocking the fresh backup.`);
312
+ } else if (backupIssue.code === "untrusted-signature") {
313
+ nextSteps.add(`Backup trust chain is not verified on this device. Run the shown printf pipeline with the correct recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify device --recovery-key-stdin", accountId)}.`);
314
+ nextSteps.add(`If device identity trust remains incomplete after that, run ${formatMatrixCliCommand("verify self", accountId)} from another verified Matrix client.`);
315
+ nextSteps.add(`If you want a fresh backup baseline and accept losing unrecoverable history, run ${formatMatrixCliCommand("verify backup reset --yes", accountId)}. Add --rotate-recovery-key only when the old recovery key should stop unlocking the fresh backup.`);
316
+ } else if (backupIssue.code === "indeterminate") nextSteps.add(`Run ${formatMatrixCliCommand("verify status --verbose", accountId)} to inspect backup trust diagnostics.`);
317
+ return Array.from(nextSteps);
318
+ }
319
+ function printGuidance(lines) {
320
+ if (lines.length === 0) return;
321
+ console.log("Next steps:");
322
+ for (const line of lines) console.log(`- ${line}`);
323
+ }
324
+ function printVerificationStatus(status, verbose = false, accountId) {
325
+ console.log(`Verified by owner: ${status.verified ? "yes" : "no"}`);
326
+ if (status.serverDeviceKnown === false) console.log("Device issue: current Matrix device is missing from the homeserver device list");
327
+ const backupIssue = resolveMatrixRoomKeyBackupIssue(resolveBackupStatus(status));
328
+ printVerificationBackupSummary(status);
329
+ if (backupIssue.message) console.log(`Backup issue: ${backupIssue.message}`);
330
+ if (verbose) {
331
+ console.log("Diagnostics:");
332
+ printVerificationIdentity(status);
333
+ if (status.serverDeviceKnown !== void 0) console.log(`Device present on server: ${yesNoUnknown(status.serverDeviceKnown ?? null)}`);
334
+ printVerificationTrustDiagnostics(status);
335
+ printVerificationBackupStatus(status);
336
+ console.log(`Recovery key stored: ${status.recoveryKeyStored ? "yes" : "no"}`);
337
+ printTimestamp("Recovery key created at", status.recoveryKeyCreatedAt);
338
+ console.log(`Pending verifications: ${status.pendingVerifications}`);
339
+ } else console.log(`Recovery key stored: ${status.recoveryKeyStored ? "yes" : "no"}`);
340
+ printVerificationGuidance(status, accountId);
341
+ }
342
+ //#endregion
343
+ //#region extensions/matrix/src/matrix/actions/devices.ts
344
+ async function listMatrixOwnDevices(opts = {}) {
345
+ return await withResolvedActionClient(opts, async (client) => await client.listOwnDevices());
346
+ }
347
+ async function pruneMatrixStaleGatewayDevices(opts = {}) {
348
+ return await withResolvedActionClient(opts, async (client) => {
349
+ const devices = await client.listOwnDevices();
350
+ const staleGatewayDeviceIds = summarizeMatrixDeviceHealth(devices).staleOpenClawDevices.map((device) => device.deviceId);
351
+ return {
352
+ before: devices,
353
+ staleGatewayDeviceIds,
354
+ ...staleGatewayDeviceIds.length > 0 ? await client.deleteOwnDevices(staleGatewayDeviceIds) : {
355
+ currentDeviceId: devices.find((device) => device.current)?.deviceId ?? null,
356
+ deletedDeviceIds: [],
357
+ remainingDevices: devices
358
+ }
359
+ };
360
+ });
361
+ }
362
+ //#endregion
363
+ //#region extensions/matrix/src/cli-account.ts
364
+ async function addMatrixAccount(params) {
365
+ const initialSyncLimit = parseOptionalInt(params.initialSyncLimit, "--initial-sync-limit", { min: 0 });
366
+ const runtime = getMatrixRuntime();
367
+ const cfg = runtime.config.current();
368
+ if (!matrixSetupAdapter.applyAccountConfig) throw new Error("Matrix account setup is unavailable.");
369
+ const input = {
370
+ name: params.name,
371
+ avatarUrl: params.avatarUrl,
372
+ homeserver: params.homeserver,
373
+ dangerouslyAllowPrivateNetwork: params.allowPrivateNetwork,
374
+ proxy: params.proxy,
375
+ userId: params.userId,
376
+ accessToken: params.accessToken,
377
+ password: params.password,
378
+ deviceName: params.deviceName,
379
+ initialSyncLimit,
380
+ useEnv: params.useEnv === true
381
+ };
382
+ const accountId = matrixSetupAdapter.resolveAccountId?.({
383
+ cfg,
384
+ accountId: params.account,
385
+ input
386
+ }) ?? normalizeAccountId(params.account?.trim() || params.name?.trim());
387
+ const validationError = matrixSetupAdapter.validateInput?.({
388
+ cfg,
389
+ accountId,
390
+ input
391
+ });
392
+ if (validationError) throw new Error(validationError);
393
+ let updated = matrixSetupAdapter.applyAccountConfig({
394
+ cfg,
395
+ accountId,
396
+ input
397
+ });
398
+ if (params.enableEncryption === true) updated = updateMatrixAccountConfig(updated, accountId, { encryption: true });
399
+ await runtime.config.replaceConfigFile({
400
+ nextConfig: updated,
401
+ afterWrite: { mode: "auto" }
402
+ });
403
+ const accountConfig = resolveMatrixAccountConfig({
404
+ cfg: updated,
405
+ accountId
406
+ });
407
+ let verificationBootstrap = {
408
+ attempted: false,
409
+ success: false,
410
+ recoveryKeyCreatedAt: null,
411
+ backupVersion: null
412
+ };
413
+ if (accountConfig.encryption === true) {
414
+ const { maybeBootstrapNewEncryptedMatrixAccount } = await import("./setup-bootstrap-BBGpPKgy.js");
415
+ verificationBootstrap = await maybeBootstrapNewEncryptedMatrixAccount({
416
+ previousCfg: cfg,
417
+ cfg: updated,
418
+ accountId
419
+ });
420
+ }
421
+ const desiredDisplayName = input.name?.trim();
422
+ const desiredAvatarUrl = input.avatarUrl?.trim();
423
+ let profile = {
424
+ attempted: false,
425
+ displayNameUpdated: false,
426
+ avatarUpdated: false,
427
+ resolvedAvatarUrl: null,
428
+ convertedAvatarFromHttp: false
429
+ };
430
+ if (desiredDisplayName || desiredAvatarUrl) try {
431
+ const synced = await updateMatrixOwnProfile({
432
+ cfg: updated,
433
+ accountId,
434
+ displayName: desiredDisplayName,
435
+ avatarUrl: desiredAvatarUrl
436
+ });
437
+ let resolvedAvatarUrl = synced.resolvedAvatarUrl;
438
+ if (synced.convertedAvatarFromHttp && synced.resolvedAvatarUrl) {
439
+ const withAvatar = updateMatrixAccountConfig(runtime.config.current(), accountId, { avatarUrl: synced.resolvedAvatarUrl });
440
+ await runtime.config.replaceConfigFile({
441
+ nextConfig: withAvatar,
442
+ afterWrite: { mode: "auto" }
443
+ });
444
+ resolvedAvatarUrl = synced.resolvedAvatarUrl;
445
+ }
446
+ profile = {
447
+ attempted: true,
448
+ displayNameUpdated: synced.displayNameUpdated,
449
+ avatarUpdated: synced.avatarUpdated,
450
+ resolvedAvatarUrl,
451
+ convertedAvatarFromHttp: synced.convertedAvatarFromHttp
452
+ };
453
+ } catch (err) {
454
+ profile = {
455
+ attempted: true,
456
+ displayNameUpdated: false,
457
+ avatarUpdated: false,
458
+ resolvedAvatarUrl: null,
459
+ convertedAvatarFromHttp: false,
460
+ error: formatMatrixErrorMessage(err)
461
+ };
462
+ }
463
+ let deviceHealth;
464
+ try {
465
+ const addedDevices = await listMatrixOwnDevices({
466
+ accountId,
467
+ cfg: updated
468
+ });
469
+ deviceHealth = {
470
+ currentDeviceId: addedDevices.find((device) => device.current)?.deviceId ?? null,
471
+ staleOpenClawDeviceIds: addedDevices.filter((device) => !device.current && isOpenClawManagedMatrixDevice(device.displayName)).map((device) => device.deviceId)
472
+ };
473
+ } catch (err) {
474
+ deviceHealth = {
475
+ currentDeviceId: null,
476
+ staleOpenClawDeviceIds: [],
477
+ error: formatMatrixErrorMessage(err)
478
+ };
479
+ }
480
+ return {
481
+ accountId,
482
+ configPath: resolveMatrixConfigPath(updated, accountId),
483
+ useEnv: input.useEnv === true,
484
+ encryptionEnabled: accountConfig.encryption === true,
485
+ deviceHealth,
486
+ verificationBootstrap,
487
+ profile
488
+ };
489
+ }
490
+ function registerMatrixAccountCommands(root) {
491
+ root.command("account").description("Manage matrix channel accounts").command("add").description("Add or update a matrix account (wrapper around channel setup)").option("--account <id>", "Account ID (default: normalized --name, else default)").option("--name <name>", "Optional display name for this account").option("--avatar-url <url>", "Optional Matrix avatar URL (mxc:// or http(s) URL)").option("--homeserver <url>", "Matrix homeserver URL").option("--proxy <url>", "Optional HTTP(S) proxy URL for Matrix requests").option("--allow-private-network", "Allow Matrix homeserver traffic to private/internal hosts for this account").option("--user-id <id>", "Matrix user ID").option("--access-token <token>", "Matrix access token").option("--password <password>", "Matrix password").option("--device-name <name>", "Matrix device display name").option("--initial-sync-limit <n>", "Matrix initial sync limit").option("--enable-e2ee", "Enable Matrix end-to-end encryption and bootstrap verification").option("--encryption", "Alias for --enable-e2ee").option("--use-env", "Use MATRIX_* env vars (or MATRIX_<ACCOUNT_ID>_* for non-default accounts)").option("--verbose", "Show setup details").option("--json", "Output as JSON").action(async (options) => {
492
+ await runMatrixCliCommand({
493
+ verbose: options.verbose === true,
494
+ json: options.json === true,
495
+ run: async () => await addMatrixAccount({
496
+ account: options.account,
497
+ name: options.name,
498
+ avatarUrl: options.avatarUrl,
499
+ homeserver: options.homeserver,
500
+ proxy: options.proxy,
501
+ allowPrivateNetwork: options.allowPrivateNetwork === true,
502
+ userId: options.userId,
503
+ accessToken: options.accessToken,
504
+ password: options.password,
505
+ deviceName: options.deviceName,
506
+ initialSyncLimit: options.initialSyncLimit,
507
+ enableEncryption: options.enableE2ee === true || options.encryption === true,
508
+ useEnv: options.useEnv === true
509
+ }),
510
+ onText: (result) => {
511
+ console.log(`Saved matrix account: ${formatMatrixCliText(result.accountId)}`);
512
+ console.log(`Config path: ${formatMatrixCliText(result.configPath)}`);
513
+ console.log(`Credentials source: ${result.useEnv ? "MATRIX_* / MATRIX_<ACCOUNT_ID>_* env vars" : "inline config"}`);
514
+ console.log(`Encryption: ${result.encryptionEnabled ? "enabled" : "disabled"}`);
515
+ if (result.verificationBootstrap.attempted) if (result.verificationBootstrap.success) {
516
+ console.log("Matrix verification bootstrap: complete");
517
+ printTimestamp("Recovery key created at", result.verificationBootstrap.recoveryKeyCreatedAt);
518
+ if (result.verificationBootstrap.backupVersion) console.log(`Backup version: ${formatMatrixCliText(result.verificationBootstrap.backupVersion)}`);
519
+ } else console.error(`Matrix verification bootstrap warning: ${formatMatrixCliText(result.verificationBootstrap.error)}`);
520
+ if (result.deviceHealth.error) console.error(`Matrix device health warning: ${formatMatrixCliText(result.deviceHealth.error)}`);
521
+ else if (result.deviceHealth.staleOpenClawDeviceIds.length > 0) {
522
+ const staleDeviceIds = result.deviceHealth.staleOpenClawDeviceIds.map((deviceId) => formatMatrixCliText(deviceId)).join(", ");
523
+ console.log(`Matrix device hygiene warning: stale OpenClaw devices detected (${staleDeviceIds}). Run ${formatMatrixCliCommand("devices prune-stale", result.accountId)}.`);
524
+ }
525
+ if (result.profile.attempted) if (result.profile.error) console.error(`Profile sync warning: ${formatMatrixCliText(result.profile.error)}`);
526
+ else {
527
+ console.log(`Profile sync: name ${result.profile.displayNameUpdated ? "updated" : "unchanged"}, avatar ${result.profile.avatarUpdated ? "updated" : "unchanged"}`);
528
+ if (result.profile.convertedAvatarFromHttp && result.profile.resolvedAvatarUrl) console.log(`Avatar converted and saved as: ${formatMatrixCliText(result.profile.resolvedAvatarUrl)}`);
529
+ }
530
+ const bindHint = `openclaw agents bind --agent <id> --bind matrix:${result.accountId}`;
531
+ console.log(`Bind this account to an agent: ${bindHint}`);
532
+ },
533
+ errorPrefix: "Account setup failed"
534
+ });
535
+ });
536
+ }
537
+ //#endregion
538
+ //#region extensions/matrix/src/cli-devices.ts
539
+ function printMatrixOwnDevices(devices) {
540
+ if (devices.length === 0) {
541
+ console.log("Devices: none");
542
+ return;
543
+ }
544
+ for (const device of devices) {
545
+ const labels = [device.current ? "current" : null, device.displayName].filter((label) => Boolean(label)).map((label) => formatMatrixCliText(label));
546
+ console.log(`- ${formatMatrixCliText(device.deviceId)}${labels.length ? ` (${labels.join(", ")})` : ""}`);
547
+ const lastSeenAt = timestampMsToIsoString(device.lastSeenTs);
548
+ if (lastSeenAt) printTimestamp(" Last seen", lastSeenAt);
549
+ if (device.lastSeenIp) console.log(` Last IP: ${formatMatrixCliText(device.lastSeenIp)}`);
550
+ }
551
+ }
552
+ function registerMatrixDeviceCommands(root) {
553
+ const devices = root.command("devices").description("Inspect and clean up Matrix devices");
554
+ devices.command("list").description("List server-side Matrix devices for this account").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
555
+ const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
556
+ await runMatrixCliCommand({
557
+ verbose: options.verbose === true,
558
+ json: options.json === true,
559
+ run: async () => await listMatrixOwnDevices({
560
+ accountId,
561
+ cfg
562
+ }),
563
+ onText: (result) => {
564
+ printAccountLabel(accountId);
565
+ printMatrixOwnDevices(result);
566
+ },
567
+ errorPrefix: "Device listing failed"
568
+ });
569
+ });
570
+ devices.command("prune-stale").description("Delete stale OpenClaw-managed devices for this account").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
571
+ const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
572
+ await runMatrixCliCommand({
573
+ verbose: options.verbose === true,
574
+ json: options.json === true,
575
+ run: async () => await pruneMatrixStaleGatewayDevices({
576
+ accountId,
577
+ cfg
578
+ }),
579
+ onText: (result, verbose) => {
580
+ printAccountLabel(accountId);
581
+ console.log(`Deleted stale OpenClaw devices: ${result.deletedDeviceIds.length ? result.deletedDeviceIds.map((deviceId) => formatMatrixCliText(deviceId)).join(", ") : "none"}`);
582
+ console.log(`Current device: ${formatMatrixCliText(result.currentDeviceId)}`);
583
+ console.log(`Remaining devices: ${result.remainingDevices.length}`);
584
+ if (verbose) {
585
+ console.log("Devices before cleanup:");
586
+ printMatrixOwnDevices(result.before);
587
+ console.log("Devices after cleanup:");
588
+ printMatrixOwnDevices(result.remainingDevices);
589
+ }
590
+ },
591
+ errorPrefix: "Device cleanup failed"
592
+ });
593
+ });
594
+ }
595
+ //#endregion
596
+ //#region extensions/matrix/src/cli-direct.ts
597
+ const loadMatrixActionClientModule = createLazyRuntimeModule(() => import("./client-CitERujx.js").then((n) => n.t));
598
+ const loadMatrixDirectManagementModule = createLazyRuntimeModule(() => import("./send-C9Ssx-iV.js").then((n) => n.l));
599
+ function printDirectRoomCandidate(room) {
600
+ const members = room.joinedMembers === null ? "unavailable" : room.joinedMembers.map((member) => formatMatrixCliText(member)).join(", ") || "none";
601
+ console.log(`- ${formatMatrixCliText(room.roomId)} [${room.source}] strict=${room.strict ? "yes" : "no"} joined=${members}`);
602
+ }
603
+ function printDirectRoomInspection(result) {
604
+ printAccountLabel(result.accountId);
605
+ console.log(`Peer: ${formatMatrixCliText(result.remoteUserId)}`);
606
+ console.log(`Self: ${formatMatrixCliText(result.selfUserId)}`);
607
+ console.log(`Active direct room: ${formatMatrixCliText(result.activeRoomId, "none")}`);
608
+ console.log(`Mapped rooms: ${result.mappedRoomIds.length ? result.mappedRoomIds.map((roomId) => formatMatrixCliText(roomId)).join(", ") : "none"}`);
609
+ console.log(`Discovered strict rooms: ${result.discoveredStrictRoomIds.length ? result.discoveredStrictRoomIds.map((roomId) => formatMatrixCliText(roomId)).join(", ") : "none"}`);
610
+ if (result.mappedRooms.length > 0) {
611
+ console.log("Mapped room details:");
612
+ for (const room of result.mappedRooms) printDirectRoomCandidate(room);
613
+ }
614
+ }
615
+ async function inspectMatrixDirectRoom(params) {
616
+ const cfg = getMatrixRuntime().config.current();
617
+ const [{ withResolvedActionClient }, { inspectMatrixDirectRooms }] = await Promise.all([loadMatrixActionClientModule(), loadMatrixDirectManagementModule()]);
618
+ return await withResolvedActionClient({
619
+ accountId: params.accountId,
620
+ cfg
621
+ }, async (client) => {
622
+ const inspection = await inspectMatrixDirectRooms({
623
+ client,
624
+ remoteUserId: params.userId
625
+ });
626
+ return {
627
+ accountId: params.accountId,
628
+ remoteUserId: inspection.remoteUserId,
629
+ selfUserId: inspection.selfUserId,
630
+ mappedRoomIds: inspection.mappedRoomIds,
631
+ mappedRooms: inspection.mappedRooms.map(toCliDirectRoomCandidate),
632
+ discoveredStrictRoomIds: inspection.discoveredStrictRoomIds,
633
+ activeRoomId: inspection.activeRoomId
634
+ };
635
+ }, "persist");
636
+ }
637
+ async function repairMatrixDirectRoom(params) {
638
+ const cfg = getMatrixRuntime().config.current();
639
+ const account = resolveMatrixAccount({
640
+ cfg,
641
+ accountId: params.accountId
642
+ });
643
+ const [{ withStartedActionClient }, { repairMatrixDirectRooms }] = await Promise.all([loadMatrixActionClientModule(), loadMatrixDirectManagementModule()]);
644
+ return await withStartedActionClient({
645
+ accountId: params.accountId,
646
+ cfg
647
+ }, async (client) => {
648
+ const repaired = await repairMatrixDirectRooms({
649
+ client,
650
+ remoteUserId: params.userId,
651
+ encrypted: account.config.encryption === true
652
+ });
653
+ return {
654
+ accountId: params.accountId,
655
+ remoteUserId: repaired.remoteUserId,
656
+ selfUserId: repaired.selfUserId,
657
+ mappedRoomIds: repaired.mappedRoomIds,
658
+ mappedRooms: repaired.mappedRooms.map(toCliDirectRoomCandidate),
659
+ discoveredStrictRoomIds: repaired.discoveredStrictRoomIds,
660
+ activeRoomId: repaired.activeRoomId,
661
+ encrypted: account.config.encryption === true,
662
+ createdRoomId: repaired.createdRoomId,
663
+ changed: repaired.changed,
664
+ directContentBefore: repaired.directContentBefore,
665
+ directContentAfter: repaired.directContentAfter
666
+ };
667
+ });
668
+ }
669
+ function toCliDirectRoomCandidate(room) {
670
+ return {
671
+ roomId: room.roomId,
672
+ source: room.source,
673
+ strict: room.strict,
674
+ joinedMembers: room.joinedMembers
675
+ };
676
+ }
677
+ function registerMatrixDirectCommands(root) {
678
+ const direct = root.command("direct").description("Inspect and repair Matrix direct-room state");
679
+ direct.command("inspect").description("Inspect direct-room mappings for a Matrix user").requiredOption("--user-id <id>", "Peer Matrix user ID").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
680
+ const accountId = resolveMatrixCliAccountContext(options.account).accountId;
681
+ await runMatrixCliCommand({
682
+ verbose: options.verbose === true,
683
+ json: options.json === true,
684
+ run: async () => await inspectMatrixDirectRoom({
685
+ accountId,
686
+ userId: options.userId
687
+ }),
688
+ onText: (result) => {
689
+ printDirectRoomInspection(result);
690
+ },
691
+ errorPrefix: "Direct room inspection failed"
692
+ });
693
+ });
694
+ direct.command("repair").description("Repair Matrix direct-room mappings for a Matrix user").requiredOption("--user-id <id>", "Peer Matrix user ID").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
695
+ const accountId = resolveMatrixCliAccountContext(options.account).accountId;
696
+ await runMatrixCliCommand({
697
+ verbose: options.verbose === true,
698
+ json: options.json === true,
699
+ run: async () => await repairMatrixDirectRoom({
700
+ accountId,
701
+ userId: options.userId
702
+ }),
703
+ onText: (result, verbose) => {
704
+ printDirectRoomInspection(result);
705
+ console.log(`Encrypted room creation: ${result.encrypted ? "enabled" : "disabled"}`);
706
+ console.log(`Created room: ${formatMatrixCliText(result.createdRoomId, "none")}`);
707
+ console.log(`m.direct updated: ${result.changed ? "yes" : "no"}`);
708
+ if (verbose) {
709
+ console.log(`m.direct before: ${formatMatrixCliText(JSON.stringify(result.directContentBefore[result.remoteUserId] ?? []))}`);
710
+ console.log(`m.direct after: ${formatMatrixCliText(JSON.stringify(result.directContentAfter[result.remoteUserId] ?? []))}`);
711
+ }
712
+ },
713
+ errorPrefix: "Direct room repair failed"
714
+ });
715
+ });
716
+ }
717
+ //#endregion
718
+ //#region extensions/matrix/src/cli-encryption.ts
719
+ function isMatrixVerificationSetupComplete(status) {
720
+ return status.encryptionEnabled && status.verified && status.crossSigningVerified && status.signedByOwner && status.serverDeviceKnown === true && resolveMatrixRoomKeyBackupIssue(resolveBackupStatus(status)).code === "ok";
721
+ }
722
+ function buildNoopMatrixVerificationBootstrap(status) {
723
+ return {
724
+ success: true,
725
+ verification: {
726
+ ...status,
727
+ backup: resolveBackupStatus(status),
728
+ serverDeviceKnown: status.serverDeviceKnown ?? null
729
+ },
730
+ crossSigning: {
731
+ userId: status.userId,
732
+ masterKeyPublished: status.crossSigningVerified,
733
+ selfSigningKeyPublished: status.signedByOwner,
734
+ userSigningKeyPublished: status.signedByOwner,
735
+ published: status.crossSigningVerified && status.signedByOwner
736
+ },
737
+ pendingVerifications: status.pendingVerifications,
738
+ cryptoBootstrap: null
739
+ };
740
+ }
741
+ async function setupMatrixEncryption(params) {
742
+ const runtime = getMatrixRuntime();
743
+ const { accountId, cfg } = resolveMatrixCliAccountContext(params.account);
744
+ if (!resolveMatrixAccount({
745
+ cfg,
746
+ accountId
747
+ }).configured) throw new Error(`Matrix account "${accountId}" is not configured; run ${formatMatrixCliCommand("account add", accountId)} first.`);
748
+ const encryptionChanged = resolveMatrixAccountConfig({
749
+ cfg,
750
+ accountId
751
+ }).encryption !== true;
752
+ const updated = encryptionChanged ? updateMatrixAccountConfig(cfg, accountId, { encryption: true }) : cfg;
753
+ if (encryptionChanged) await runtime.config.replaceConfigFile({
754
+ nextConfig: updated,
755
+ afterWrite: { mode: "auto" }
756
+ });
757
+ const existingStatus = !encryptionChanged && !params.recoveryKey && params.forceResetCrossSigning !== true ? await getMatrixVerificationStatus({
758
+ accountId,
759
+ cfg: updated,
760
+ readiness: "none"
761
+ }) : null;
762
+ if (existingStatus && isMatrixVerificationSetupComplete(existingStatus)) return {
763
+ accountId,
764
+ configPath: resolveMatrixConfigPath(updated, accountId),
765
+ encryptionChanged,
766
+ bootstrap: buildNoopMatrixVerificationBootstrap(existingStatus),
767
+ status: existingStatus
768
+ };
769
+ const bootstrap = await bootstrapMatrixVerification({
770
+ accountId,
771
+ cfg: updated,
772
+ recoveryKey: params.recoveryKey,
773
+ forceResetCrossSigning: params.forceResetCrossSigning === true
774
+ });
775
+ const status = await getMatrixVerificationStatus({
776
+ accountId,
777
+ cfg: updated
778
+ });
779
+ return {
780
+ accountId,
781
+ configPath: resolveMatrixConfigPath(updated, accountId),
782
+ encryptionChanged,
783
+ bootstrap,
784
+ status
785
+ };
786
+ }
787
+ function printMatrixEncryptionSetupResult(result, verbose = false) {
788
+ printAccountLabel(result.accountId);
789
+ console.log(`Encryption config: ${result.encryptionChanged ? "enabled" : "already enabled"} at ${formatMatrixCliText(result.configPath)}`);
790
+ console.log(`Bootstrap success: ${result.bootstrap.success ? "yes" : "no"}`);
791
+ if (result.bootstrap.error) console.log(`Bootstrap error: ${formatMatrixCliText(result.bootstrap.error)}`);
792
+ console.log(`Verified by owner: ${result.status.verified ? "yes" : "no"}`);
793
+ printVerificationBackupSummary(result.status);
794
+ if (verbose) {
795
+ printVerificationIdentity(result.status);
796
+ printVerificationTrustDiagnostics(result.status);
797
+ printVerificationBackupStatus(result.status);
798
+ console.log(`Recovery key stored: ${result.status.recoveryKeyStored ? "yes" : "no"}`);
799
+ printTimestamp("Recovery key created at", result.status.recoveryKeyCreatedAt);
800
+ console.log(`Pending verifications: ${result.status.pendingVerifications}`);
801
+ }
802
+ printVerificationGuidance(result.status, result.accountId);
803
+ }
804
+ function registerMatrixEncryptionCommands(root) {
805
+ root.command("encryption").description("Set up Matrix end-to-end encryption").command("setup").description("Enable Matrix E2EE, bootstrap verification, and print next steps").option("--account <id>", "Account ID (for multi-account setups)").option("--recovery-key <key>", "Recovery key to apply before bootstrap (prefer --recovery-key-stdin)").option("--recovery-key-stdin", "Read the Matrix recovery key from stdin").option("--force-reset-cross-signing", "Force reset cross-signing identity before bootstrap (requires active recovery key)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
806
+ await runMatrixCliCommand({
807
+ verbose: options.verbose === true,
808
+ json: options.json === true,
809
+ run: async () => await setupMatrixEncryption({
810
+ account: options.account,
811
+ recoveryKey: await resolveMatrixCliRecoveryKeyInput({
812
+ recoveryKey: options.recoveryKey,
813
+ recoveryKeyStdin: options.recoveryKeyStdin
814
+ }),
815
+ forceResetCrossSigning: options.forceResetCrossSigning === true
816
+ }),
817
+ onText: (result, verbose) => {
818
+ printMatrixEncryptionSetupResult(result, verbose);
819
+ },
820
+ onJson: (result) => ({
821
+ success: result.bootstrap.success,
822
+ ...result
823
+ }),
824
+ shouldFail: (result) => !result.bootstrap.success,
825
+ errorPrefix: "Encryption setup failed",
826
+ onJsonError: (message) => ({
827
+ success: false,
828
+ error: message
829
+ })
830
+ });
831
+ });
832
+ }
833
+ //#endregion
834
+ //#region extensions/matrix/src/cli-profile.ts
835
+ function registerMatrixProfileCommands(root) {
836
+ root.command("profile").description("Manage Matrix bot profile").command("set").description("Update Matrix profile display name and/or avatar").option("--account <id>", "Account ID (for multi-account setups)").option("--name <name>", "Profile display name").option("--avatar-url <url>", "Profile avatar URL (mxc:// or http(s) URL)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
837
+ await runMatrixCliCommand({
838
+ verbose: options.verbose === true,
839
+ json: options.json === true,
840
+ run: async () => await applyMatrixProfileUpdate({
841
+ account: options.account,
842
+ displayName: options.name,
843
+ avatarUrl: options.avatarUrl
844
+ }),
845
+ onText: (result) => {
846
+ printAccountLabel(result.accountId);
847
+ console.log(`Config path: ${result.configPath}`);
848
+ console.log(`Profile update: name ${result.profile.displayNameUpdated ? "updated" : "unchanged"}, avatar ${result.profile.avatarUpdated ? "updated" : "unchanged"}`);
849
+ if (result.profile.convertedAvatarFromHttp && result.avatarUrl) console.log(`Avatar converted and saved as: ${formatMatrixCliText(result.avatarUrl)}`);
850
+ },
851
+ errorPrefix: "Profile update failed"
852
+ });
853
+ });
854
+ }
855
+ //#endregion
856
+ //#region extensions/matrix/src/cli-verification-backup.ts
857
+ function registerMatrixVerificationBackupCommands(verify) {
858
+ const backup = verify.command("backup").description("Matrix room-key backup health and restore");
859
+ backup.command("status").description("Show Matrix room-key backup status for this device").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
860
+ const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
861
+ await runMatrixCliCommand({
862
+ verbose: options.verbose === true,
863
+ json: options.json === true,
864
+ run: async () => await getMatrixRoomKeyBackupStatus({
865
+ accountId,
866
+ cfg
867
+ }),
868
+ onText: (status, verbose) => {
869
+ printAccountLabel(accountId);
870
+ printBackupSummary(status);
871
+ if (verbose) printBackupStatus(status);
872
+ printBackupGuidance(status, accountId);
873
+ },
874
+ errorPrefix: "Backup status failed"
875
+ });
876
+ });
877
+ backup.command("reset").description("Delete the current server backup and create a fresh room-key backup baseline, repairing secret storage if needed for a durable reset").option("--account <id>", "Account ID (for multi-account setups)").option("--yes", "Confirm destructive backup reset", false).option("--rotate-recovery-key", "Create a new Matrix recovery key for the fresh backup").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
878
+ const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
879
+ await runMatrixCliCommand({
880
+ verbose: options.verbose === true,
881
+ json: options.json === true,
882
+ run: async () => {
883
+ if (options.yes !== true) throw new Error(`Refusing to reset Matrix room-key backup without --yes. If you accept losing unrecoverable history, re-run ${formatMatrixCliCommand("verify backup reset --yes", accountId)}.`);
884
+ return await resetMatrixRoomKeyBackup({
885
+ accountId,
886
+ cfg,
887
+ rotateRecoveryKey: options.rotateRecoveryKey === true
888
+ });
889
+ },
890
+ onText: (result, verbose) => {
891
+ printAccountLabel(accountId);
892
+ console.log(`Reset success: ${result.success ? "yes" : "no"}`);
893
+ if (result.error) console.log(`Error: ${formatMatrixCliText(result.error)}`);
894
+ console.log(`Previous backup version: ${formatMatrixCliText(result.previousVersion, "none")}`);
895
+ console.log(`Deleted backup version: ${formatMatrixCliText(result.deletedVersion, "none")}`);
896
+ console.log(`Current backup version: ${formatMatrixCliText(result.createdVersion, "none")}`);
897
+ printBackupSummary(result.backup);
898
+ if (verbose) {
899
+ printTimestamp("Reset at", result.resetAt);
900
+ printBackupStatus(result.backup);
901
+ }
902
+ printBackupGuidance(result.backup, accountId);
903
+ },
904
+ shouldFail: (result) => !result.success,
905
+ errorPrefix: "Backup reset failed",
906
+ onJsonError: (message) => ({
907
+ success: false,
908
+ error: message
909
+ })
910
+ });
911
+ });
912
+ backup.command("restore").description("Restore encrypted room keys from server backup").option("--account <id>", "Account ID (for multi-account setups)").option("--recovery-key <key>", "Optional recovery key to load before restoring (prefer --recovery-key-stdin)").option("--recovery-key-stdin", "Read the Matrix recovery key from stdin").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
913
+ const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
914
+ await runMatrixCliCommand({
915
+ verbose: options.verbose === true,
916
+ json: options.json === true,
917
+ run: async () => await restoreMatrixRoomKeyBackup({
918
+ accountId,
919
+ cfg,
920
+ recoveryKey: await resolveMatrixCliRecoveryKeyInput(options)
921
+ }),
922
+ onText: (result, verbose) => {
923
+ printAccountLabel(accountId);
924
+ console.log(`Restore success: ${result.success ? "yes" : "no"}`);
925
+ if (result.error) console.log(`Error: ${formatMatrixCliText(result.error)}`);
926
+ console.log(`Backup version: ${formatMatrixCliText(result.backupVersion, "none")}`);
927
+ console.log(`Imported keys: ${result.imported}/${result.total}`);
928
+ printBackupSummary(result.backup);
929
+ if (verbose) {
930
+ console.log(`Loaded key from secret storage: ${result.loadedFromSecretStorage ? "yes" : "no"}`);
931
+ printTimestamp("Restored at", result.restoredAt);
932
+ printBackupStatus(result.backup);
933
+ }
934
+ printBackupGuidance(result.backup, accountId, { recoveryKeyStored: result.loadedFromSecretStorage });
935
+ },
936
+ shouldFail: (result) => !result.success,
937
+ errorPrefix: "Backup restore failed",
938
+ onJsonError: (message) => ({
939
+ success: false,
940
+ error: message
941
+ })
942
+ });
943
+ });
944
+ verify.command("bootstrap").description("Bootstrap Matrix cross-signing and device verification state").option("--account <id>", "Account ID (for multi-account setups)").option("--recovery-key <key>", "Recovery key to apply before bootstrap (prefer --recovery-key-stdin)").option("--recovery-key-stdin", "Read the Matrix recovery key from stdin").option("--force-reset-cross-signing", "Force reset cross-signing identity before bootstrap (requires active recovery key)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
945
+ const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
946
+ await runMatrixCliCommand({
947
+ verbose: options.verbose === true,
948
+ json: options.json === true,
949
+ run: async () => await bootstrapMatrixVerification({
950
+ accountId,
951
+ cfg,
952
+ recoveryKey: await resolveMatrixCliRecoveryKeyInput(options),
953
+ forceResetCrossSigning: options.forceResetCrossSigning === true
954
+ }),
955
+ onText: (result, verbose) => {
956
+ printAccountLabel(accountId);
957
+ console.log(`Bootstrap success: ${result.success ? "yes" : "no"}`);
958
+ if (result.error) console.log(`Error: ${formatMatrixCliText(result.error)}`);
959
+ console.log(`Verified by owner: ${result.verification.verified ? "yes" : "no"}`);
960
+ printVerificationIdentity(result.verification);
961
+ if (verbose) {
962
+ printVerificationTrustDiagnostics(result.verification);
963
+ console.log(`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"})`);
964
+ printVerificationBackupStatus(result.verification);
965
+ printTimestamp("Recovery key created at", result.verification.recoveryKeyCreatedAt);
966
+ console.log(`Pending verifications: ${result.pendingVerifications}`);
967
+ } else {
968
+ console.log(`Cross-signing published: ${result.crossSigning.published ? "yes" : "no"}`);
969
+ printVerificationBackupSummary(result.verification);
970
+ }
971
+ printVerificationGuidance({
972
+ ...result.verification,
973
+ pendingVerifications: result.pendingVerifications
974
+ }, accountId);
975
+ },
976
+ shouldFail: (result) => !result.success,
977
+ errorPrefix: "Verification bootstrap failed",
978
+ onJsonError: (message) => ({
979
+ success: false,
980
+ error: message
981
+ })
982
+ });
983
+ });
984
+ verify.command("device [key]").description("Verify device using a Matrix recovery key").option("--account <id>", "Account ID (for multi-account setups)").option("--recovery-key-stdin", "Read the Matrix recovery key from stdin").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (key, options) => {
985
+ const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
986
+ await runMatrixCliCommand({
987
+ verbose: options.verbose === true,
988
+ json: options.json === true,
989
+ run: async () => await verifyMatrixRecoveryKey(await requireMatrixCliRecoveryKeyInput({
990
+ recoveryKey: key,
991
+ recoveryKeyStdin: options.recoveryKeyStdin
992
+ }), {
993
+ accountId,
994
+ cfg
995
+ }),
996
+ onText: (result, verbose) => {
997
+ printAccountLabel(accountId);
998
+ if (!result.success) {
999
+ console.error(`Verification failed: ${formatMatrixCliText(result.error)}`);
1000
+ printVerificationIdentity(result);
1001
+ console.log(`Recovery key accepted: ${result.recoveryKeyAccepted ? "yes" : "no"}`);
1002
+ console.log(`Backup usable: ${result.backupUsable ? "yes" : "no"}`);
1003
+ console.log(`Device verified by owner: ${result.deviceOwnerVerified ? "yes" : "no"}`);
1004
+ printVerificationBackupSummary(result);
1005
+ if (verbose) {
1006
+ printVerificationTrustDiagnostics(result);
1007
+ printVerificationBackupStatus(result);
1008
+ printTimestamp("Recovery key created at", result.recoveryKeyCreatedAt);
1009
+ }
1010
+ printVerificationGuidance({
1011
+ ...result,
1012
+ pendingVerifications: 0
1013
+ }, accountId);
1014
+ return;
1015
+ }
1016
+ console.log("Device verification completed successfully.");
1017
+ printVerificationIdentity(result);
1018
+ console.log(`Recovery key accepted: ${result.recoveryKeyAccepted ? "yes" : "no"}`);
1019
+ console.log(`Backup usable: ${result.backupUsable ? "yes" : "no"}`);
1020
+ console.log(`Device verified by owner: ${result.deviceOwnerVerified ? "yes" : "no"}`);
1021
+ printVerificationBackupSummary(result);
1022
+ if (verbose) {
1023
+ printVerificationTrustDiagnostics(result);
1024
+ printVerificationBackupStatus(result);
1025
+ printTimestamp("Recovery key created at", result.recoveryKeyCreatedAt);
1026
+ printTimestamp("Verified at", result.verifiedAt);
1027
+ }
1028
+ printVerificationGuidance({
1029
+ ...result,
1030
+ pendingVerifications: 0
1031
+ }, accountId);
1032
+ },
1033
+ shouldFail: (result) => !result.success,
1034
+ errorPrefix: "Verification failed",
1035
+ onJsonError: (message) => ({
1036
+ success: false,
1037
+ error: message
1038
+ })
1039
+ });
1040
+ });
1041
+ }
1042
+ //#endregion
1043
+ //#region extensions/matrix/src/cli-verification.ts
608
1044
  function matrixCliVerificationDmLookupOptions(options) {
609
1045
  const lookup = {};
610
1046
  if (options.roomId !== void 0) lookup.verificationDmRoomId = options.roomId;
@@ -733,243 +1169,35 @@ async function runMatrixCliSelfVerificationCommand(options) {
733
1169
  onRequested: (summary) => {
734
1170
  printAccountLabel(accountId);
735
1171
  printMatrixVerificationSummary(summary);
736
- console.log("Accept this verification request in another Matrix client.");
737
- },
738
- onReady: (summary) => {
739
- console.log("Verification request accepted.");
740
- if (!summary.hasSas) console.log("Starting SAS verification...");
741
- },
742
- onSas: (summary) => {
743
- printMatrixVerificationSas(summary.sas ?? {});
744
- console.log("Compare this SAS with the other Matrix client.");
745
- },
746
- confirmSas: async () => await promptMatrixVerificationSasMatch()
747
- });
748
- },
749
- onText: (summary, verbose) => {
750
- printMatrixVerificationSummary(summary);
751
- console.log(`Device verified by owner: ${summary.deviceOwnerVerified ? "yes" : "no"}`);
752
- printVerificationTrustDiagnostics(summary.ownerVerification);
753
- printVerificationBackupSummary(summary.ownerVerification);
754
- if (verbose) printVerificationBackupStatus(summary.ownerVerification);
755
- console.log("Self-verification complete.");
756
- },
757
- onTextError: () => {
758
- const accountId = resolvedAccountId ?? options.account;
759
- printGuidance([`Run ${formatMatrixCliCommand("verify self", accountId)} again and accept the request in another verified Matrix client for this account.`, `Then run ${formatMatrixCliCommand("verify status --verbose", accountId)} to confirm Cross-signing verified: yes and Signed by owner: yes.`]);
760
- },
761
- errorPrefix: "Self-verification failed"
762
- });
763
- }
764
- function printVerificationGuidance(status, accountId) {
765
- printGuidance(buildVerificationGuidance(status, accountId));
766
- }
767
- function printBackupGuidance(backup, accountId, options = {}) {
768
- printGuidance(buildBackupGuidance(backup, accountId, options));
769
- }
770
- function printBackupSummary(backup) {
771
- const issue = resolveMatrixRoomKeyBackupIssue(backup);
772
- console.log(`Backup: ${issue.summary}`);
773
- if (backup.serverVersion) console.log(`Backup version: ${formatMatrixCliText(backup.serverVersion)}`);
774
- }
775
- function buildVerificationGuidance(status, accountId) {
776
- const backup = resolveBackupStatus(status);
777
- const nextSteps = /* @__PURE__ */ new Set();
778
- if (!status.verified) if (status.recoveryKeyAccepted === true && status.backupUsable === true) {
779
- nextSteps.add(`Recovery key can unlock the room-key backup, but full Matrix identity trust is still incomplete. Run ${formatMatrixCliCommand("verify self", accountId)}, accept the request in another verified Matrix client, and confirm the SAS only if it matches.`);
780
- nextSteps.add(`If you intend to replace the current cross-signing identity, run the shown printf pipeline with the Matrix recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify bootstrap --recovery-key-stdin --force-reset-cross-signing", accountId)}.`);
781
- } else nextSteps.add(`Run the shown printf pipeline with the Matrix recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify device --recovery-key-stdin", accountId)}. If you do not have the recovery key but still have another verified Matrix client, run ${formatMatrixCliCommand("verify self", accountId)} instead.`);
782
- if (status.serverDeviceKnown === false) nextSteps.add(`This Matrix device is no longer listed on the homeserver. Create a new OpenClaw Matrix device with ${formatMatrixCliCommand("account add --homeserver <url> --user-id <@user:server> --password <password> --device-name OpenClaw-Gateway", accountId)}. If you use token auth, create a fresh Matrix access token in your Matrix client or admin UI, then run ${formatMatrixCliCommand("account add --homeserver <url> --access-token <token>", accountId)}.`);
783
- for (const step of buildBackupGuidance(backup, accountId, { recoveryKeyStored: status.recoveryKeyStored })) nextSteps.add(step);
784
- if (status.pendingVerifications > 0) nextSteps.add(`Review pending verification requests with ${formatMatrixCliCommand("verify list", accountId)}. Complete each active request with ${formatMatrixCliCommand("verify sas <id>", accountId)} and ${formatMatrixCliCommand("verify confirm-sas <id>", accountId)}, or cancel stale requests with ${formatMatrixCliCommand("verify cancel <id>", accountId)}.`);
785
- return Array.from(nextSteps);
786
- }
787
- function buildBackupGuidance(backup, accountId, options = {}) {
788
- const backupIssue = resolveMatrixRoomKeyBackupIssue(backup);
789
- const nextSteps = /* @__PURE__ */ new Set();
790
- if (backupIssue.code === "missing-server-backup") nextSteps.add(`Run ${formatMatrixCliCommand("verify bootstrap", accountId)} to create a room key backup.`);
791
- else if (backupIssue.code === "key-load-failed" || backupIssue.code === "key-not-loaded" || backupIssue.code === "inactive") if (options.recoveryKeyStored) nextSteps.add(`Backup key is not loaded on this device. Run ${formatMatrixCliCommand("verify backup restore", accountId)} to load it and restore old room keys. If restore still cannot load the key, run the shown printf pipeline with the Matrix recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify backup restore --recovery-key-stdin", accountId)}.`);
792
- else nextSteps.add(`Run the shown printf pipeline with the Matrix recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify backup restore --recovery-key-stdin", accountId)} to load the server backup and store the key for future restores.`);
793
- else if (backupIssue.code === "key-mismatch") {
794
- nextSteps.add(`Backup key mismatch on this device. Run the shown printf pipeline with the active server backup recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify backup restore --recovery-key-stdin", accountId)}.`);
795
- nextSteps.add(`If you want a fresh backup baseline and accept losing unrecoverable history, run ${formatMatrixCliCommand("verify backup reset --yes", accountId)}. Add --rotate-recovery-key only when the old recovery key should stop unlocking the fresh backup.`);
796
- } else if (backupIssue.code === "untrusted-signature") {
797
- nextSteps.add(`Backup trust chain is not verified on this device. Run the shown printf pipeline with the correct recovery key env var for this account: ${formatMatrixCliRecoveryKeyStdinCommand("verify device --recovery-key-stdin", accountId)}.`);
798
- nextSteps.add(`If device identity trust remains incomplete after that, run ${formatMatrixCliCommand("verify self", accountId)} from another verified Matrix client.`);
799
- nextSteps.add(`If you want a fresh backup baseline and accept losing unrecoverable history, run ${formatMatrixCliCommand("verify backup reset --yes", accountId)}. Add --rotate-recovery-key only when the old recovery key should stop unlocking the fresh backup.`);
800
- } else if (backupIssue.code === "indeterminate") nextSteps.add(`Run ${formatMatrixCliCommand("verify status --verbose", accountId)} to inspect backup trust diagnostics.`);
801
- return Array.from(nextSteps);
802
- }
803
- function printGuidance(lines) {
804
- if (lines.length === 0) return;
805
- console.log("Next steps:");
806
- for (const line of lines) console.log(`- ${line}`);
807
- }
808
- function printVerificationStatus(status, verbose = false, accountId) {
809
- console.log(`Verified by owner: ${status.verified ? "yes" : "no"}`);
810
- if (status.serverDeviceKnown === false) console.log("Device issue: current Matrix device is missing from the homeserver device list");
811
- const backupIssue = resolveMatrixRoomKeyBackupIssue(resolveBackupStatus(status));
812
- printVerificationBackupSummary(status);
813
- if (backupIssue.message) console.log(`Backup issue: ${backupIssue.message}`);
814
- if (verbose) {
815
- console.log("Diagnostics:");
816
- printVerificationIdentity(status);
817
- if (status.serverDeviceKnown !== void 0) console.log(`Device present on server: ${yesNoUnknown(status.serverDeviceKnown ?? null)}`);
818
- printVerificationTrustDiagnostics(status);
819
- printVerificationBackupStatus(status);
820
- console.log(`Recovery key stored: ${status.recoveryKeyStored ? "yes" : "no"}`);
821
- printTimestamp("Recovery key created at", status.recoveryKeyCreatedAt);
822
- console.log(`Pending verifications: ${status.pendingVerifications}`);
823
- } else console.log(`Recovery key stored: ${status.recoveryKeyStored ? "yes" : "no"}`);
824
- printVerificationGuidance(status, accountId);
825
- }
826
- function printMatrixEncryptionSetupResult(result, verbose = false) {
827
- printAccountLabel(result.accountId);
828
- console.log(`Encryption config: ${result.encryptionChanged ? "enabled" : "already enabled"} at ${formatMatrixCliText(result.configPath)}`);
829
- console.log(`Bootstrap success: ${result.bootstrap.success ? "yes" : "no"}`);
830
- if (result.bootstrap.error) console.log(`Bootstrap error: ${formatMatrixCliText(result.bootstrap.error)}`);
831
- console.log(`Verified by owner: ${result.status.verified ? "yes" : "no"}`);
832
- printVerificationBackupSummary(result.status);
833
- if (verbose) {
834
- printVerificationIdentity(result.status);
835
- printVerificationTrustDiagnostics(result.status);
836
- printVerificationBackupStatus(result.status);
837
- console.log(`Recovery key stored: ${result.status.recoveryKeyStored ? "yes" : "no"}`);
838
- printTimestamp("Recovery key created at", result.status.recoveryKeyCreatedAt);
839
- console.log(`Pending verifications: ${result.status.pendingVerifications}`);
840
- }
841
- printVerificationGuidance(result.status, result.accountId);
842
- }
843
- function registerMatrixCli(params) {
844
- const root = params.program.command("matrix").description("Matrix channel utilities").addHelpText("after", () => "\nDocs: https://docs.openclaw.ai/channels/matrix\n");
845
- root.command("account").description("Manage matrix channel accounts").command("add").description("Add or update a matrix account (wrapper around channel setup)").option("--account <id>", "Account ID (default: normalized --name, else default)").option("--name <name>", "Optional display name for this account").option("--avatar-url <url>", "Optional Matrix avatar URL (mxc:// or http(s) URL)").option("--homeserver <url>", "Matrix homeserver URL").option("--proxy <url>", "Optional HTTP(S) proxy URL for Matrix requests").option("--allow-private-network", "Allow Matrix homeserver traffic to private/internal hosts for this account").option("--user-id <id>", "Matrix user ID").option("--access-token <token>", "Matrix access token").option("--password <password>", "Matrix password").option("--device-name <name>", "Matrix device display name").option("--initial-sync-limit <n>", "Matrix initial sync limit").option("--enable-e2ee", "Enable Matrix end-to-end encryption and bootstrap verification").option("--encryption", "Alias for --enable-e2ee").option("--use-env", "Use MATRIX_* env vars (or MATRIX_<ACCOUNT_ID>_* for non-default accounts)").option("--verbose", "Show setup details").option("--json", "Output as JSON").action(async (options) => {
846
- await runMatrixCliCommand({
847
- verbose: options.verbose === true,
848
- json: options.json === true,
849
- run: async () => await addMatrixAccount({
850
- account: options.account,
851
- name: options.name,
852
- avatarUrl: options.avatarUrl,
853
- homeserver: options.homeserver,
854
- proxy: options.proxy,
855
- allowPrivateNetwork: options.allowPrivateNetwork === true,
856
- userId: options.userId,
857
- accessToken: options.accessToken,
858
- password: options.password,
859
- deviceName: options.deviceName,
860
- initialSyncLimit: options.initialSyncLimit,
861
- enableEncryption: options.enableE2ee === true || options.encryption === true,
862
- useEnv: options.useEnv === true
863
- }),
864
- onText: (result) => {
865
- console.log(`Saved matrix account: ${formatMatrixCliText(result.accountId)}`);
866
- console.log(`Config path: ${formatMatrixCliText(result.configPath)}`);
867
- console.log(`Credentials source: ${result.useEnv ? "MATRIX_* / MATRIX_<ACCOUNT_ID>_* env vars" : "inline config"}`);
868
- console.log(`Encryption: ${result.encryptionEnabled ? "enabled" : "disabled"}`);
869
- if (result.verificationBootstrap.attempted) if (result.verificationBootstrap.success) {
870
- console.log("Matrix verification bootstrap: complete");
871
- printTimestamp("Recovery key created at", result.verificationBootstrap.recoveryKeyCreatedAt);
872
- if (result.verificationBootstrap.backupVersion) console.log(`Backup version: ${formatMatrixCliText(result.verificationBootstrap.backupVersion)}`);
873
- } else console.error(`Matrix verification bootstrap warning: ${formatMatrixCliText(result.verificationBootstrap.error)}`);
874
- if (result.deviceHealth.error) console.error(`Matrix device health warning: ${formatMatrixCliText(result.deviceHealth.error)}`);
875
- else if (result.deviceHealth.staleOpenClawDeviceIds.length > 0) {
876
- const staleDeviceIds = result.deviceHealth.staleOpenClawDeviceIds.map((deviceId) => formatMatrixCliText(deviceId)).join(", ");
877
- console.log(`Matrix device hygiene warning: stale OpenClaw devices detected (${staleDeviceIds}). Run ${formatMatrixCliCommand("devices prune-stale", result.accountId)}.`);
878
- }
879
- if (result.profile.attempted) if (result.profile.error) console.error(`Profile sync warning: ${formatMatrixCliText(result.profile.error)}`);
880
- else {
881
- console.log(`Profile sync: name ${result.profile.displayNameUpdated ? "updated" : "unchanged"}, avatar ${result.profile.avatarUpdated ? "updated" : "unchanged"}`);
882
- if (result.profile.convertedAvatarFromHttp && result.profile.resolvedAvatarUrl) console.log(`Avatar converted and saved as: ${formatMatrixCliText(result.profile.resolvedAvatarUrl)}`);
883
- }
884
- const bindHint = `openclaw agents bind --agent <id> --bind matrix:${result.accountId}`;
885
- console.log(`Bind this account to an agent: ${bindHint}`);
886
- },
887
- errorPrefix: "Account setup failed"
888
- });
889
- });
890
- root.command("profile").description("Manage Matrix bot profile").command("set").description("Update Matrix profile display name and/or avatar").option("--account <id>", "Account ID (for multi-account setups)").option("--name <name>", "Profile display name").option("--avatar-url <url>", "Profile avatar URL (mxc:// or http(s) URL)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
891
- await runMatrixCliCommand({
892
- verbose: options.verbose === true,
893
- json: options.json === true,
894
- run: async () => await setMatrixProfile({
895
- account: options.account,
896
- name: options.name,
897
- avatarUrl: options.avatarUrl
898
- }),
899
- onText: (result) => {
900
- printAccountLabel(result.accountId);
901
- console.log(`Config path: ${result.configPath}`);
902
- console.log(`Profile update: name ${result.profile.displayNameUpdated ? "updated" : "unchanged"}, avatar ${result.profile.avatarUpdated ? "updated" : "unchanged"}`);
903
- if (result.profile.convertedAvatarFromHttp && result.avatarUrl) console.log(`Avatar converted and saved as: ${formatMatrixCliText(result.avatarUrl)}`);
904
- },
905
- errorPrefix: "Profile update failed"
906
- });
907
- });
908
- const direct = root.command("direct").description("Inspect and repair Matrix direct-room state");
909
- direct.command("inspect").description("Inspect direct-room mappings for a Matrix user").requiredOption("--user-id <id>", "Peer Matrix user ID").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
910
- const accountId = resolveMatrixCliAccountId(options.account);
911
- await runMatrixCliCommand({
912
- verbose: options.verbose === true,
913
- json: options.json === true,
914
- run: async () => await inspectMatrixDirectRoom({
915
- accountId,
916
- userId: options.userId
917
- }),
918
- onText: (result) => {
919
- printDirectRoomInspection(result);
920
- },
921
- errorPrefix: "Direct room inspection failed"
922
- });
923
- });
924
- direct.command("repair").description("Repair Matrix direct-room mappings for a Matrix user").requiredOption("--user-id <id>", "Peer Matrix user ID").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
925
- const accountId = resolveMatrixCliAccountId(options.account);
926
- await runMatrixCliCommand({
927
- verbose: options.verbose === true,
928
- json: options.json === true,
929
- run: async () => await repairMatrixDirectRoom({
930
- accountId,
931
- userId: options.userId
932
- }),
933
- onText: (result, verbose) => {
934
- printDirectRoomInspection(result);
935
- console.log(`Encrypted room creation: ${result.encrypted ? "enabled" : "disabled"}`);
936
- console.log(`Created room: ${formatMatrixCliText(result.createdRoomId, "none")}`);
937
- console.log(`m.direct updated: ${result.changed ? "yes" : "no"}`);
938
- if (verbose) {
939
- console.log(`m.direct before: ${formatMatrixCliText(JSON.stringify(result.directContentBefore[result.remoteUserId] ?? []))}`);
940
- console.log(`m.direct after: ${formatMatrixCliText(JSON.stringify(result.directContentAfter[result.remoteUserId] ?? []))}`);
941
- }
942
- },
943
- errorPrefix: "Direct room repair failed"
944
- });
945
- });
946
- root.command("encryption").description("Set up Matrix end-to-end encryption").command("setup").description("Enable Matrix E2EE, bootstrap verification, and print next steps").option("--account <id>", "Account ID (for multi-account setups)").option("--recovery-key <key>", "Recovery key to apply before bootstrap (prefer --recovery-key-stdin)").option("--recovery-key-stdin", "Read the Matrix recovery key from stdin").option("--force-reset-cross-signing", "Force reset cross-signing identity before bootstrap (requires active recovery key)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
947
- await runMatrixCliCommand({
948
- verbose: options.verbose === true,
949
- json: options.json === true,
950
- run: async () => await setupMatrixEncryption({
951
- account: options.account,
952
- recoveryKey: await resolveMatrixCliRecoveryKeyInput({
953
- recoveryKey: options.recoveryKey,
954
- recoveryKeyStdin: options.recoveryKeyStdin
955
- }),
956
- forceResetCrossSigning: options.forceResetCrossSigning === true
957
- }),
958
- onText: (result, verbose) => {
959
- printMatrixEncryptionSetupResult(result, verbose);
960
- },
961
- onJson: (result) => ({
962
- success: result.bootstrap.success,
963
- ...result
964
- }),
965
- shouldFail: (result) => !result.bootstrap.success,
966
- errorPrefix: "Encryption setup failed",
967
- onJsonError: (message) => ({
968
- success: false,
969
- error: message
970
- })
971
- });
1172
+ console.log("Accept this verification request in another Matrix client.");
1173
+ },
1174
+ onReady: (summary) => {
1175
+ console.log("Verification request accepted.");
1176
+ if (!summary.hasSas) console.log("Starting SAS verification...");
1177
+ },
1178
+ onSas: (summary) => {
1179
+ printMatrixVerificationSas(summary.sas ?? {});
1180
+ console.log("Compare this SAS with the other Matrix client.");
1181
+ },
1182
+ confirmSas: async () => await promptMatrixVerificationSasMatch()
1183
+ });
1184
+ },
1185
+ onText: (summary, verbose) => {
1186
+ printMatrixVerificationSummary(summary);
1187
+ console.log(`Device verified by owner: ${summary.deviceOwnerVerified ? "yes" : "no"}`);
1188
+ printVerificationTrustDiagnostics(summary.ownerVerification);
1189
+ printVerificationBackupSummary(summary.ownerVerification);
1190
+ if (verbose) printVerificationBackupStatus(summary.ownerVerification);
1191
+ console.log("Self-verification complete.");
1192
+ },
1193
+ onTextError: () => {
1194
+ const accountId = resolvedAccountId ?? options.account;
1195
+ printGuidance([`Run ${formatMatrixCliCommand("verify self", accountId)} again and accept the request in another verified Matrix client for this account.`, `Then run ${formatMatrixCliCommand("verify status --verbose", accountId)} to confirm Cross-signing verified: yes and Signed by owner: yes.`]);
1196
+ },
1197
+ errorPrefix: "Self-verification failed"
972
1198
  });
1199
+ }
1200
+ function registerMatrixVerificationCommands(root) {
973
1201
  const verify = root.command("verify").description("Device verification for Matrix E2EE");
974
1202
  verify.command("list").description("List pending Matrix verification requests").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
975
1203
  const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
@@ -1120,230 +1348,18 @@ function registerMatrixCli(params) {
1120
1348
  errorPrefix: "Error"
1121
1349
  });
1122
1350
  });
1123
- const backup = verify.command("backup").description("Matrix room-key backup health and restore");
1124
- backup.command("status").description("Show Matrix room-key backup status for this device").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
1125
- const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
1126
- await runMatrixCliCommand({
1127
- verbose: options.verbose === true,
1128
- json: options.json === true,
1129
- run: async () => await getMatrixRoomKeyBackupStatus({
1130
- accountId,
1131
- cfg
1132
- }),
1133
- onText: (status, verbose) => {
1134
- printAccountLabel(accountId);
1135
- printBackupSummary(status);
1136
- if (verbose) printBackupStatus(status);
1137
- printBackupGuidance(status, accountId);
1138
- },
1139
- errorPrefix: "Backup status failed"
1140
- });
1141
- });
1142
- backup.command("reset").description("Delete the current server backup and create a fresh room-key backup baseline, repairing secret storage if needed for a durable reset").option("--account <id>", "Account ID (for multi-account setups)").option("--yes", "Confirm destructive backup reset", false).option("--rotate-recovery-key", "Create a new Matrix recovery key for the fresh backup").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
1143
- const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
1144
- await runMatrixCliCommand({
1145
- verbose: options.verbose === true,
1146
- json: options.json === true,
1147
- run: async () => {
1148
- if (options.yes !== true) throw new Error(`Refusing to reset Matrix room-key backup without --yes. If you accept losing unrecoverable history, re-run ${formatMatrixCliCommand("verify backup reset --yes", accountId)}.`);
1149
- return await resetMatrixRoomKeyBackup({
1150
- accountId,
1151
- cfg,
1152
- rotateRecoveryKey: options.rotateRecoveryKey === true
1153
- });
1154
- },
1155
- onText: (result, verbose) => {
1156
- printAccountLabel(accountId);
1157
- console.log(`Reset success: ${result.success ? "yes" : "no"}`);
1158
- if (result.error) console.log(`Error: ${formatMatrixCliText(result.error)}`);
1159
- console.log(`Previous backup version: ${formatMatrixCliText(result.previousVersion, "none")}`);
1160
- console.log(`Deleted backup version: ${formatMatrixCliText(result.deletedVersion, "none")}`);
1161
- console.log(`Current backup version: ${formatMatrixCliText(result.createdVersion, "none")}`);
1162
- printBackupSummary(result.backup);
1163
- if (verbose) {
1164
- printTimestamp("Reset at", result.resetAt);
1165
- printBackupStatus(result.backup);
1166
- }
1167
- printBackupGuidance(result.backup, accountId);
1168
- },
1169
- shouldFail: (result) => !result.success,
1170
- errorPrefix: "Backup reset failed",
1171
- onJsonError: (message) => ({
1172
- success: false,
1173
- error: message
1174
- })
1175
- });
1176
- });
1177
- backup.command("restore").description("Restore encrypted room keys from server backup").option("--account <id>", "Account ID (for multi-account setups)").option("--recovery-key <key>", "Optional recovery key to load before restoring (prefer --recovery-key-stdin)").option("--recovery-key-stdin", "Read the Matrix recovery key from stdin").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
1178
- const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
1179
- await runMatrixCliCommand({
1180
- verbose: options.verbose === true,
1181
- json: options.json === true,
1182
- run: async () => await restoreMatrixRoomKeyBackup({
1183
- accountId,
1184
- cfg,
1185
- recoveryKey: await resolveMatrixCliRecoveryKeyInput(options)
1186
- }),
1187
- onText: (result, verbose) => {
1188
- printAccountLabel(accountId);
1189
- console.log(`Restore success: ${result.success ? "yes" : "no"}`);
1190
- if (result.error) console.log(`Error: ${formatMatrixCliText(result.error)}`);
1191
- console.log(`Backup version: ${formatMatrixCliText(result.backupVersion, "none")}`);
1192
- console.log(`Imported keys: ${result.imported}/${result.total}`);
1193
- printBackupSummary(result.backup);
1194
- if (verbose) {
1195
- console.log(`Loaded key from secret storage: ${result.loadedFromSecretStorage ? "yes" : "no"}`);
1196
- printTimestamp("Restored at", result.restoredAt);
1197
- printBackupStatus(result.backup);
1198
- }
1199
- printBackupGuidance(result.backup, accountId, { recoveryKeyStored: result.loadedFromSecretStorage });
1200
- },
1201
- shouldFail: (result) => !result.success,
1202
- errorPrefix: "Backup restore failed",
1203
- onJsonError: (message) => ({
1204
- success: false,
1205
- error: message
1206
- })
1207
- });
1208
- });
1209
- verify.command("bootstrap").description("Bootstrap Matrix cross-signing and device verification state").option("--account <id>", "Account ID (for multi-account setups)").option("--recovery-key <key>", "Recovery key to apply before bootstrap (prefer --recovery-key-stdin)").option("--recovery-key-stdin", "Read the Matrix recovery key from stdin").option("--force-reset-cross-signing", "Force reset cross-signing identity before bootstrap (requires active recovery key)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
1210
- const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
1211
- await runMatrixCliCommand({
1212
- verbose: options.verbose === true,
1213
- json: options.json === true,
1214
- run: async () => await bootstrapMatrixVerification({
1215
- accountId,
1216
- cfg,
1217
- recoveryKey: await resolveMatrixCliRecoveryKeyInput(options),
1218
- forceResetCrossSigning: options.forceResetCrossSigning === true
1219
- }),
1220
- onText: (result, verbose) => {
1221
- printAccountLabel(accountId);
1222
- console.log(`Bootstrap success: ${result.success ? "yes" : "no"}`);
1223
- if (result.error) console.log(`Error: ${formatMatrixCliText(result.error)}`);
1224
- console.log(`Verified by owner: ${result.verification.verified ? "yes" : "no"}`);
1225
- printVerificationIdentity(result.verification);
1226
- if (verbose) {
1227
- printVerificationTrustDiagnostics(result.verification);
1228
- console.log(`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"})`);
1229
- printVerificationBackupStatus(result.verification);
1230
- printTimestamp("Recovery key created at", result.verification.recoveryKeyCreatedAt);
1231
- console.log(`Pending verifications: ${result.pendingVerifications}`);
1232
- } else {
1233
- console.log(`Cross-signing published: ${result.crossSigning.published ? "yes" : "no"}`);
1234
- printVerificationBackupSummary(result.verification);
1235
- }
1236
- printVerificationGuidance({
1237
- ...result.verification,
1238
- pendingVerifications: result.pendingVerifications
1239
- }, accountId);
1240
- },
1241
- shouldFail: (result) => !result.success,
1242
- errorPrefix: "Verification bootstrap failed",
1243
- onJsonError: (message) => ({
1244
- success: false,
1245
- error: message
1246
- })
1247
- });
1248
- });
1249
- verify.command("device [key]").description("Verify device using a Matrix recovery key").option("--account <id>", "Account ID (for multi-account setups)").option("--recovery-key-stdin", "Read the Matrix recovery key from stdin").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (key, options) => {
1250
- const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
1251
- await runMatrixCliCommand({
1252
- verbose: options.verbose === true,
1253
- json: options.json === true,
1254
- run: async () => await verifyMatrixRecoveryKey(await requireMatrixCliRecoveryKeyInput({
1255
- recoveryKey: key,
1256
- recoveryKeyStdin: options.recoveryKeyStdin
1257
- }), {
1258
- accountId,
1259
- cfg
1260
- }),
1261
- onText: (result, verbose) => {
1262
- printAccountLabel(accountId);
1263
- if (!result.success) {
1264
- console.error(`Verification failed: ${formatMatrixCliText(result.error)}`);
1265
- printVerificationIdentity(result);
1266
- console.log(`Recovery key accepted: ${result.recoveryKeyAccepted ? "yes" : "no"}`);
1267
- console.log(`Backup usable: ${result.backupUsable ? "yes" : "no"}`);
1268
- console.log(`Device verified by owner: ${result.deviceOwnerVerified ? "yes" : "no"}`);
1269
- printVerificationBackupSummary(result);
1270
- if (verbose) {
1271
- printVerificationTrustDiagnostics(result);
1272
- printVerificationBackupStatus(result);
1273
- printTimestamp("Recovery key created at", result.recoveryKeyCreatedAt);
1274
- }
1275
- printVerificationGuidance({
1276
- ...result,
1277
- pendingVerifications: 0
1278
- }, accountId);
1279
- return;
1280
- }
1281
- console.log("Device verification completed successfully.");
1282
- printVerificationIdentity(result);
1283
- console.log(`Recovery key accepted: ${result.recoveryKeyAccepted ? "yes" : "no"}`);
1284
- console.log(`Backup usable: ${result.backupUsable ? "yes" : "no"}`);
1285
- console.log(`Device verified by owner: ${result.deviceOwnerVerified ? "yes" : "no"}`);
1286
- printVerificationBackupSummary(result);
1287
- if (verbose) {
1288
- printVerificationTrustDiagnostics(result);
1289
- printVerificationBackupStatus(result);
1290
- printTimestamp("Recovery key created at", result.recoveryKeyCreatedAt);
1291
- printTimestamp("Verified at", result.verifiedAt);
1292
- }
1293
- printVerificationGuidance({
1294
- ...result,
1295
- pendingVerifications: 0
1296
- }, accountId);
1297
- },
1298
- shouldFail: (result) => !result.success,
1299
- errorPrefix: "Verification failed",
1300
- onJsonError: (message) => ({
1301
- success: false,
1302
- error: message
1303
- })
1304
- });
1305
- });
1306
- const devices = root.command("devices").description("Inspect and clean up Matrix devices");
1307
- devices.command("list").description("List server-side Matrix devices for this account").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
1308
- const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
1309
- await runMatrixCliCommand({
1310
- verbose: options.verbose === true,
1311
- json: options.json === true,
1312
- run: async () => await listMatrixOwnDevices({
1313
- accountId,
1314
- cfg
1315
- }),
1316
- onText: (result) => {
1317
- printAccountLabel(accountId);
1318
- printMatrixOwnDevices(result);
1319
- },
1320
- errorPrefix: "Device listing failed"
1321
- });
1322
- });
1323
- devices.command("prune-stale").description("Delete stale OpenClaw-managed devices for this account").option("--account <id>", "Account ID (for multi-account setups)").option("--verbose", "Show detailed diagnostics").option("--json", "Output as JSON").action(async (options) => {
1324
- const { accountId, cfg } = resolveMatrixCliAccountContext(options.account);
1325
- await runMatrixCliCommand({
1326
- verbose: options.verbose === true,
1327
- json: options.json === true,
1328
- run: async () => await pruneMatrixStaleGatewayDevices({
1329
- accountId,
1330
- cfg
1331
- }),
1332
- onText: (result, verbose) => {
1333
- printAccountLabel(accountId);
1334
- console.log(`Deleted stale OpenClaw devices: ${result.deletedDeviceIds.length ? result.deletedDeviceIds.map((deviceId) => formatMatrixCliText(deviceId)).join(", ") : "none"}`);
1335
- console.log(`Current device: ${formatMatrixCliText(result.currentDeviceId)}`);
1336
- console.log(`Remaining devices: ${result.remainingDevices.length}`);
1337
- if (verbose) {
1338
- console.log("Devices before cleanup:");
1339
- printMatrixOwnDevices(result.before);
1340
- console.log("Devices after cleanup:");
1341
- printMatrixOwnDevices(result.remainingDevices);
1342
- }
1343
- },
1344
- errorPrefix: "Device cleanup failed"
1345
- });
1346
- });
1351
+ registerMatrixVerificationBackupCommands(verify);
1352
+ }
1353
+ //#endregion
1354
+ //#region extensions/matrix/src/cli.ts
1355
+ function registerMatrixCli(params) {
1356
+ const root = params.program.command("matrix").description("Matrix channel utilities").addHelpText("after", () => "\nDocs: https://docs.openclaw.ai/channels/matrix\n");
1357
+ registerMatrixAccountCommands(root);
1358
+ registerMatrixProfileCommands(root);
1359
+ registerMatrixDirectCommands(root);
1360
+ registerMatrixEncryptionCommands(root);
1361
+ registerMatrixVerificationCommands(root);
1362
+ registerMatrixDeviceCommands(root);
1347
1363
  }
1348
1364
  //#endregion
1349
1365
  export { registerMatrixCli };