@openclaw/matrix 2026.9.2 → 2026.9.4

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 (68) hide show
  1. package/dist/{account-selection-DA-jfx22.js → account-selection-Bbtc483D.js} +9 -1
  2. package/dist/{accounts-DR1c4xF_.js → accounts-GwSAk9vY.js} +2 -2
  3. package/dist/api.js +6 -6
  4. package/dist/{approval-handler.runtime-BJCD4dLf.js → approval-handler.runtime-6I3IpyeX.js} +6 -6
  5. package/dist/{approval-ids-Bst7HM_o.js → approval-ids-C4NdeXNz.js} +1 -1
  6. package/dist/{approval-reaction-auth-DhH8QOSe.js → approval-reaction-auth-cbltZAUQ.js} +2 -2
  7. package/dist/{channel-Bs8VLb6q.js → channel-Cg97H4c1.js} +13 -202
  8. package/dist/channel-plugin-api.js +1 -1
  9. package/dist/{channel.runtime-CCJRhdH5.js → channel.runtime-Bhpfa1qc.js} +6 -11
  10. package/dist/{channel.setup-DhmDXwPp.js → channel.setup-DmS7m7aT.js} +3 -3
  11. package/dist/{cli-IvDUuiDH.js → cli-CLexRrQw.js} +9 -9
  12. package/dist/{cli-metadata-BGryAl2e.js → cli-metadata-zRyVmUOL.js} +1 -1
  13. package/dist/cli-metadata.js +1 -1
  14. package/dist/{client-oNOlldJI.js → client-C0nZFCTj.js} +2 -2
  15. package/dist/{client-Dj4mcf-s.js → client-CPcRv6ab.js} +6 -6
  16. package/dist/{client-bootstrap-n1Rqc8Go.js → client-bootstrap-DLN-K8Xb.js} +1 -6
  17. package/dist/contract-api.js +2 -2
  18. package/dist/{credentials-DJj2xs3q.js → credentials-DysXbkv2.js} +2 -2
  19. package/dist/{credentials-read-mexhw-Ur.js → credentials-read-WWpqi88V.js} +1 -1
  20. package/dist/{credentials-write.runtime-DQt-kgJq.js → credentials-write.runtime-D22lPwRO.js} +1 -1
  21. package/dist/{crypto-runtime-m1eplj3b.js → crypto-runtime-DiyH4R3D.js} +3 -25
  22. package/dist/{crypto-snapshot-doctor.runtime-D0v841D_.js → crypto-snapshot-doctor.runtime-DxgUMXUy.js} +2 -2
  23. package/dist/{directory-live-DLUgWBhA.js → directory-live-B8-GAVcc.js} +2 -2
  24. package/dist/doctor-contract-api.js +41 -21
  25. package/dist/{draft-stream-DglwxWzJ.js → draft-stream--NdEtnZ8.js} +16 -5
  26. package/dist/{encryption-guidance-BNcZNQZI.js → encryption-guidance-mDyxJV9U.js} +1 -1
  27. package/dist/{event-helpers-XRfAbOIh.js → event-helpers-CspuhE9k.js} +9 -1
  28. package/dist/helper-api.js +3 -3
  29. package/dist/{http-client-DOmFvKvB.js → http-client-BfPeF4CE.js} +1 -1
  30. package/dist/{idb-persistence-CU7CNLlX.js → idb-persistence-DBdwHSWg.js} +1 -1
  31. package/dist/index.js +1 -1
  32. package/dist/{messages-Czn8lNEh.js → messages-CpZfiQO0.js} +6 -99
  33. package/dist/{monitor-DouG43FJ.js → monitor-BUek91SW.js} +61 -92
  34. package/dist/{outbound-Co_tJyE6.js → outbound-D91JinYa.js} +1 -1
  35. package/dist/plugin-entry.handlers.runtime.js +1 -1
  36. package/dist/probe.runtime-DWdw74_H.js +2 -0
  37. package/dist/{profile-update-CAl8nZNG.js → profile-update-vnhxwjEt.js} +1 -1
  38. package/dist/{reaction-events-C_7G7bvI.js → reaction-events-2WM2nJe_.js} +5 -7
  39. package/dist/{resolve-targets-B64O69Nd.js → resolve-targets-K8D0HWPX.js} +1 -1
  40. package/dist/{resolver.runtime-TRmePJDV.js → resolver.runtime-C88GwQCx.js} +1 -1
  41. package/dist/{room-info-6viLR3NH.js → room-info-BPVJkXnp.js} +7 -4
  42. package/dist/runtime-api.js +2 -2
  43. package/dist/{sdk-C1yfda1L.js → sdk-B4By16Bt.js} +13 -6
  44. package/dist/{send-B5XChnvB.js → send-UWLIQ0bG.js} +211 -135
  45. package/dist/session-binding-contract-api.js +1 -1
  46. package/dist/{setup-bootstrap-S_loyUyM.js → setup-bootstrap-sVqkwtSY.js} +2 -2
  47. package/dist/{setup-core-XkIfQ65J.js → setup-core-8keb-Yre.js} +14 -29
  48. package/dist/setup-plugin-api.js +1 -1
  49. package/dist/{setup-surface-B2yZ8KGc.js → setup-surface-bcluelBI.js} +8 -17
  50. package/dist/{startup-verification-1Ney1mmI.js → startup-verification-BTSf31hS.js} +2 -1
  51. package/dist/storage-CV-pfV_2.js +320 -0
  52. package/dist/{storage-BVf4uucD.js → storage-metadata-DYArLcq1.js} +14 -319
  53. package/dist/{storage-paths-gUmSydsW.js → storage-paths-DVCANXTc.js} +13 -1
  54. package/dist/{sync-cache-state-d-A_OhbU.js → sync-cache-state-C-mhj3xb.js} +9 -3
  55. package/dist/{thread-bindings-BkBnn4te.js → thread-bindings-Bwv87Gve.js} +3 -2
  56. package/dist/{tool-actions.runtime-a5L5xGSP.js → tool-actions.runtime-Bf98Juk6.js} +295 -256
  57. package/dist/types-DzSc7Sqm.js +32 -0
  58. package/dist/{verification-XJtTc5DI.js → verification-BbG-VC9S.js} +2 -2
  59. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/package.json +1 -1
  60. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm.d.ts +69 -4
  61. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.cjs +526 -432
  62. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.js +358 -265
  63. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.wasm +0 -0
  64. package/node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.wasm.d.ts +8 -7
  65. package/openclaw.plugin.json +27 -1
  66. package/package.json +5 -5
  67. package/dist/probe.runtime-B1YPxG9x.js +0 -2
  68. package/dist/runtime-BefyhPWv.js +0 -6
@@ -1,11 +1,8 @@
1
1
  import { t as getMatrixRuntime } from "./runtime-6S3DNFNv.js";
2
- import { n as resolveMatrixAccountStorageRoot } from "./storage-paths-gUmSydsW.js";
3
2
  import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
4
- import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
5
3
  import { createHash, randomUUID } from "node:crypto";
6
4
  import path from "node:path";
7
5
  import fs from "node:fs";
8
- import { loadJsonFile } from "openclaw/plugin-sdk/json-store";
9
6
  import os from "node:os";
10
7
  //#region extensions/matrix/src/matrix/sqlite-state.ts
11
8
  function resolveStateDirOverride(options) {
@@ -241,19 +238,22 @@ function archiveLegacyStateFileIfPossible(filePath) {
241
238
  function readIdbSnapshotJsonFromStore(store) {
242
239
  const meta = store.lookup(idbMetaKey());
243
240
  if (!isIdbSnapshotMeta(meta)) return null;
244
- const chunks = readIdbSnapshotChunks(meta, (key) => store.lookup(key));
241
+ const chunks = readIdbSnapshotChunks(meta, store);
245
242
  return chunks ? chunks.join("") : null;
246
243
  }
247
244
  async function readIdbSnapshotJsonFromAsyncStore(store) {
248
245
  const meta = await store.lookup(idbMetaKey());
249
246
  if (!isIdbSnapshotMeta(meta)) return null;
250
- const chunks = await readIdbSnapshotChunksAsync(meta, (key) => store.lookup(key));
247
+ const chunks = await readIdbSnapshotChunksAsync(meta, store);
251
248
  return chunks ? chunks.join("") : null;
252
249
  }
253
- function readIdbSnapshotChunks(meta, lookup) {
250
+ function readIdbSnapshotChunks(meta, store) {
251
+ const records = store.lookupMany?.(Array.from({ length: meta.chunkCount }, (_, index) => idbChunkKey(meta.generation, index)));
254
252
  const chunks = [];
255
253
  for (let index = 0; index < meta.chunkCount; index += 1) {
256
- const chunk = lookup(idbChunkKey(meta.generation, index));
254
+ const result = records?.[index];
255
+ if (result && !result.ok) throw result.error;
256
+ const chunk = records ? result?.value : store.lookup(idbChunkKey(meta.generation, index));
257
257
  if (!isIdbSnapshotChunk(chunk) || chunk.index !== index) return null;
258
258
  chunks.push(chunk.data);
259
259
  }
@@ -261,10 +261,13 @@ function readIdbSnapshotChunks(meta, lookup) {
261
261
  if (meta.digest !== digestText(snapshotJson)) return null;
262
262
  return chunks;
263
263
  }
264
- async function readIdbSnapshotChunksAsync(meta, lookup) {
264
+ async function readIdbSnapshotChunksAsync(meta, store) {
265
+ const records = await store.lookupMany?.(Array.from({ length: meta.chunkCount }, (_, index) => idbChunkKey(meta.generation, index)));
265
266
  const chunks = [];
266
267
  for (let index = 0; index < meta.chunkCount; index += 1) {
267
- const chunk = await lookup(idbChunkKey(meta.generation, index));
268
+ const result = records?.[index];
269
+ if (result && !result.ok) throw result.error;
270
+ const chunk = records ? result?.value : await store.lookup(idbChunkKey(meta.generation, index));
268
271
  if (!isIdbSnapshotChunk(chunk) || chunk.index !== index) return null;
269
272
  chunks.push(chunk.data);
270
273
  }
@@ -345,10 +348,7 @@ function isIdbSnapshotChunk(value) {
345
348
  return isRecord(value) && value.kind === "snapshot-chunk" && typeof value.index === "number" && Number.isSafeInteger(value.index) && value.index >= 0 && typeof value.data === "string";
346
349
  }
347
350
  //#endregion
348
- //#region extensions/matrix/src/matrix/client/storage.ts
349
- const DEFAULT_ACCOUNT_KEY = "default";
350
- const STORAGE_META_FILENAME = "storage-meta.json";
351
- const THREAD_BINDINGS_FILENAME = "thread-bindings.json";
351
+ //#region extensions/matrix/src/matrix/client/storage-metadata.ts
352
352
  const STORAGE_META_NAMESPACE = "storage-meta";
353
353
  const STORAGE_META_STATE_KEY = "current";
354
354
  const STORAGE_META_MAX_ENTRIES = 10;
@@ -359,28 +359,6 @@ function openMatrixStorageMetaStoreOptions(storageRootDir) {
359
359
  env: resolveMatrixSqliteStateEnv({ stateDir: storageRootDir })
360
360
  };
361
361
  }
362
- function openStorageMetaStore(rootDir) {
363
- return getMatrixRuntime().state.openSyncKeyedStore(openMatrixStorageMetaStoreOptions(rootDir));
364
- }
365
- function scoreStorageRoot(rootDir, metadata = readStoredRootMetadata(rootDir)) {
366
- let score = 0;
367
- if (Object.keys(metadata).length > 0) score += 1;
368
- if (metadata.currentTokenStateClaimed === true) score += 8;
369
- if (fs.existsSync(path.join(rootDir, "crypto"))) score += 8;
370
- if (fs.existsSync(path.join(rootDir, THREAD_BINDINGS_FILENAME))) score += 4;
371
- if (fs.existsSync(path.join(rootDir, "legacy-crypto-migration.json"))) score += 3;
372
- if (fs.existsSync(path.join(rootDir, "recovery-key.json"))) score += 2;
373
- if (fs.existsSync(path.join(rootDir, "crypto-idb-snapshot.json"))) score += 2;
374
- score += scoreMatrixCryptoStateInStore(rootDir);
375
- return score;
376
- }
377
- function resolveStorageRootMtimeMs(rootDir) {
378
- try {
379
- return fs.statSync(rootDir).mtimeMs;
380
- } catch {
381
- return 0;
382
- }
383
- }
384
362
  function normalizeMatrixStorageMetadata(value) {
385
363
  if (!isRecord(value)) return null;
386
364
  const metadata = {};
@@ -399,288 +377,5 @@ async function hasMatrixStorageMetaStateInStore(params) {
399
377
  async function writeMatrixStorageMetaStateToStore(params) {
400
378
  await params.store.register(STORAGE_META_STATE_KEY, params.payload);
401
379
  }
402
- function readStoredRootMetadata(rootDir) {
403
- if (fs.existsSync(path.join(rootDir, "state", "openclaw.sqlite"))) try {
404
- const stored = normalizeMatrixStorageMetadata(openStorageMetaStore(rootDir).lookup(STORAGE_META_STATE_KEY));
405
- if (stored) return stored;
406
- } catch {}
407
- return normalizeMatrixStorageMetadata(loadJsonFile(path.join(rootDir, STORAGE_META_FILENAME))) ?? {};
408
- }
409
- function isCompatibleStorageRoot(params) {
410
- const metadata = readStoredRootMetadata(params.candidateRootDir);
411
- if (metadata.homeserver && metadata.homeserver !== params.homeserver) return false;
412
- if (metadata.userId && metadata.userId !== params.userId) return false;
413
- if (metadata.accountId && normalizeAccountId(metadata.accountId) !== normalizeAccountId(params.accountKey)) return false;
414
- if (params.deviceId && metadata.deviceId && metadata.deviceId.trim() && metadata.deviceId.trim() !== params.deviceId.trim()) return false;
415
- if (params.requireExplicitDeviceMatch && params.deviceId && (!metadata.deviceId || metadata.deviceId.trim() !== params.deviceId.trim())) return false;
416
- return true;
417
- }
418
- function resolvePreferredMatrixStorageRoot(params) {
419
- const canonical = {
420
- rootDir: params.canonicalRootDir,
421
- tokenHash: params.canonicalTokenHash
422
- };
423
- const deviceId = params.deviceId?.trim();
424
- if (!deviceId) return canonical;
425
- const canonicalMetadata = readStoredRootMetadata(params.canonicalRootDir);
426
- if (canonicalMetadata.accessTokenHash === params.canonicalTokenHash && canonicalMetadata.deviceId?.trim() === deviceId && canonicalMetadata.currentTokenStateClaimed === true) return canonical;
427
- const parentDir = path.dirname(params.canonicalRootDir);
428
- const bestCurrentScore = scoreStorageRoot(params.canonicalRootDir, canonicalMetadata);
429
- const bestCurrentMtimeMs = resolveStorageRootMtimeMs(params.canonicalRootDir);
430
- let best = {
431
- rootDir: params.canonicalRootDir,
432
- tokenHash: params.canonicalTokenHash,
433
- score: bestCurrentScore,
434
- mtimeMs: bestCurrentMtimeMs
435
- };
436
- let siblingEntries;
437
- try {
438
- siblingEntries = fs.readdirSync(parentDir, { withFileTypes: true });
439
- } catch {
440
- return {
441
- rootDir: best.rootDir,
442
- tokenHash: best.tokenHash
443
- };
444
- }
445
- const compatiblePopulatedSiblings = [];
446
- const populatedTokenHashes = bestCurrentScore > 0 ? [params.canonicalTokenHash] : [];
447
- for (const entry of siblingEntries.toSorted((a, b) => a.name.localeCompare(b.name))) {
448
- if (!entry.isDirectory()) continue;
449
- if (entry.name === params.canonicalTokenHash) continue;
450
- const candidateRootDir = path.join(parentDir, entry.name);
451
- if (!isCompatibleStorageRoot({
452
- candidateRootDir,
453
- homeserver: params.homeserver,
454
- userId: params.userId,
455
- accountKey: params.accountKey,
456
- deviceId,
457
- requireExplicitDeviceMatch: true
458
- })) continue;
459
- const candidateScore = scoreStorageRoot(candidateRootDir);
460
- if (candidateScore <= 0) continue;
461
- populatedTokenHashes.push(entry.name);
462
- compatiblePopulatedSiblings.push({
463
- rootDir: candidateRootDir,
464
- tokenHash: entry.name,
465
- score: candidateScore,
466
- mtimeMs: resolveStorageRootMtimeMs(candidateRootDir)
467
- });
468
- }
469
- for (const candidate of compatiblePopulatedSiblings) if (candidate.score > best.score || best.rootDir !== params.canonicalRootDir && candidate.score === best.score && candidate.mtimeMs > best.mtimeMs) best = {
470
- rootDir: candidate.rootDir,
471
- tokenHash: candidate.tokenHash,
472
- score: candidate.score,
473
- mtimeMs: candidate.mtimeMs
474
- };
475
- if (populatedTokenHashes.length > 1) getMatrixRuntime().logging.getChildLogger({ module: "matrix-storage" }).warn("matrix: multiple populated token-hash storage roots detected", {
476
- parentDir,
477
- canonicalTokenHash: params.canonicalTokenHash,
478
- selectedTokenHash: best.tokenHash,
479
- populatedTokenHashes,
480
- populatedSiblingTokenHashes: compatiblePopulatedSiblings.map((root) => root.tokenHash),
481
- populatedRootCount: populatedTokenHashes.length
482
- });
483
- return {
484
- rootDir: best.rootDir,
485
- tokenHash: best.tokenHash
486
- };
487
- }
488
- function resolveMatrixStoragePaths(params) {
489
- const env = params.env ?? process.env;
490
- const stateDir = params.stateDir ?? getMatrixRuntime().state.resolveStateDir(env, os.homedir);
491
- const canonical = resolveMatrixAccountStorageRoot({
492
- stateDir,
493
- homeserver: params.homeserver,
494
- userId: params.userId,
495
- accessToken: params.accessToken,
496
- accountId: params.accountId
497
- });
498
- const { rootDir, tokenHash } = resolvePreferredMatrixStorageRoot({
499
- canonicalRootDir: canonical.rootDir,
500
- canonicalTokenHash: canonical.tokenHash,
501
- homeserver: params.homeserver,
502
- userId: params.userId,
503
- accountKey: canonical.accountKey,
504
- deviceId: params.deviceId
505
- });
506
- return {
507
- rootDir,
508
- storagePath: path.join(rootDir, "bot-storage.json"),
509
- cryptoPath: path.join(rootDir, "crypto"),
510
- recoveryKeyPath: path.join(rootDir, MATRIX_RECOVERY_KEY_FILENAME),
511
- idbSnapshotPath: path.join(rootDir, MATRIX_IDB_SNAPSHOT_FILENAME),
512
- accountKey: canonical.accountKey,
513
- tokenHash
514
- };
515
- }
516
- function resolveMatrixStateFilePath(params) {
517
- const storagePaths = resolveMatrixStoragePaths({
518
- homeserver: params.auth.homeserver,
519
- userId: params.auth.userId,
520
- accessToken: params.auth.accessToken,
521
- accountId: params.accountId ?? params.auth.accountId,
522
- deviceId: params.auth.deviceId,
523
- env: params.env,
524
- stateDir: params.stateDir
525
- });
526
- return path.join(storagePaths.rootDir, params.filename);
527
- }
528
- async function maybeMigrateLegacyStorage(params) {
529
- const hasAccountScopedLegacyStorageFile = fs.existsSync(params.storagePaths.storagePath);
530
- const syncCache = hasAccountScopedLegacyStorageFile ? await import("./sync-cache-state-d-A_OhbU.js").then((n) => n.s) : null;
531
- const hasAccountScopedLegacyStorage = hasAccountScopedLegacyStorageFile && await syncCache?.readLegacyMatrixSyncCacheState(params.storagePaths.rootDir) !== null;
532
- const hasAccountScopedRecoveryKey = fs.existsSync(params.storagePaths.recoveryKeyPath);
533
- const hasAccountScopedLegacyCryptoMigration = fs.existsSync(path.join(params.storagePaths.rootDir, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME));
534
- if (!hasAccountScopedLegacyStorage && !hasAccountScopedRecoveryKey && !hasAccountScopedLegacyCryptoMigration) return;
535
- const logger = getMatrixRuntime().logging.getChildLogger({ module: "matrix-storage" });
536
- fs.mkdirSync(params.storagePaths.rootDir, { recursive: true });
537
- const moved = [];
538
- const pendingArchives = [];
539
- const skippedExistingTargets = [];
540
- try {
541
- if (hasAccountScopedLegacyStorage) await migrateLegacySyncCacheToSqlite({
542
- sourceRootDir: params.storagePaths.rootDir,
543
- sourcePath: params.storagePaths.storagePath,
544
- targetRootDir: params.storagePaths.rootDir,
545
- label: "account sync cache",
546
- moved,
547
- pendingArchives
548
- });
549
- if (hasAccountScopedRecoveryKey) {
550
- migrateLegacyMatrixRecoveryKeyFileToStore(params.storagePaths.rootDir);
551
- moved.push({
552
- sourcePath: params.storagePaths.recoveryKeyPath,
553
- targetPath: `${params.storagePaths.rootDir} SQLite recovery key state`,
554
- label: "recovery key"
555
- });
556
- }
557
- if (hasAccountScopedLegacyCryptoMigration) {
558
- migrateLegacyMatrixLegacyCryptoMigrationFileToStore(params.storagePaths.rootDir);
559
- moved.push({
560
- sourcePath: path.join(params.storagePaths.rootDir, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME),
561
- targetPath: `${params.storagePaths.rootDir} SQLite legacy crypto migration state`,
562
- label: "legacy crypto migration"
563
- });
564
- }
565
- } catch (err) {
566
- const rollbackError = rollbackLegacyMoves(moved);
567
- throw new Error(rollbackError ? `Failed migrating legacy Matrix client storage: ${String(err)}. Rollback also failed: ${rollbackError}` : `Failed migrating legacy Matrix client storage: ${String(err)}`, { cause: err });
568
- }
569
- for (const archive of pendingArchives) archiveLegacyStoragePath({
570
- ...archive,
571
- skippedExistingTargets
572
- });
573
- if (moved.length > 0) logger.info(`matrix: migrated legacy client storage into ${params.storagePaths.rootDir}\n${moved.map((entry) => `- ${entry.label}: ${entry.sourcePath} -> ${entry.targetPath}`).join("\n")}`);
574
- if (skippedExistingTargets.length > 0) logger.warn?.(`matrix: legacy client storage files were left in place because their migrated targets already existed.\n${skippedExistingTargets.join("\n")}`);
575
- }
576
- async function migrateLegacySyncCacheToSqlite(params) {
577
- const syncCache = await import("./sync-cache-state-d-A_OhbU.js").then((n) => n.s);
578
- const persisted = await syncCache.readLegacyMatrixSyncCacheState(params.sourceRootDir);
579
- if (!persisted) return;
580
- const store = getMatrixRuntime().state.openKeyedStore(syncCache.openMatrixSyncCacheStoreOptions(params.targetRootDir));
581
- if (!await syncCache.hasMatrixSyncCacheStateInStore({
582
- storageRootDir: params.targetRootDir,
583
- store
584
- })) {
585
- await syncCache.writeMatrixSyncCacheStateToStore({
586
- storageRootDir: params.targetRootDir,
587
- payload: persisted,
588
- store
589
- });
590
- claimCurrentTokenStorageState({ rootDir: params.targetRootDir });
591
- params.moved.push({
592
- sourcePath: params.sourcePath,
593
- targetPath: `${params.targetRootDir} SQLite sync cache`,
594
- label: params.label
595
- });
596
- }
597
- params.pendingArchives.push({
598
- sourcePath: params.sourcePath,
599
- label: params.label
600
- });
601
- }
602
- function archiveLegacyStoragePath(params) {
603
- const archivedLegacyStoragePath = `${params.sourcePath}.migrated`;
604
- if (fs.existsSync(archivedLegacyStoragePath)) {
605
- params.skippedExistingTargets.push(`- ${params.label} remains at ${params.sourcePath} because ${archivedLegacyStoragePath} already exists`);
606
- return;
607
- }
608
- fs.renameSync(params.sourcePath, archivedLegacyStoragePath);
609
- }
610
- function rollbackLegacyMoves(moved) {
611
- for (const entry of moved.toReversed()) try {
612
- if (!fs.existsSync(entry.targetPath) || fs.existsSync(entry.sourcePath)) continue;
613
- fs.renameSync(entry.targetPath, entry.sourcePath);
614
- } catch (err) {
615
- return `${entry.label} (${entry.targetPath} -> ${entry.sourcePath}): ${String(err)}`;
616
- }
617
- return null;
618
- }
619
- function writeStoredRootMetadata(rootDir, payload) {
620
- try {
621
- const normalized = normalizeMatrixStorageMetadata(payload);
622
- if (!normalized) return false;
623
- openStorageMetaStore(rootDir).register(STORAGE_META_STATE_KEY, normalized);
624
- return true;
625
- } catch {
626
- return false;
627
- }
628
- }
629
- function writeStorageMeta(params) {
630
- const existing = readStoredRootMetadata(params.storagePaths.rootDir);
631
- return writeStoredRootMetadata(params.storagePaths.rootDir, {
632
- homeserver: params.homeserver,
633
- userId: params.userId,
634
- accountId: params.accountId ?? DEFAULT_ACCOUNT_KEY,
635
- accessTokenHash: params.storagePaths.tokenHash,
636
- deviceId: params.deviceId ?? null,
637
- currentTokenStateClaimed: params.currentTokenStateClaimed ?? existing.currentTokenStateClaimed === true,
638
- createdAt: existing.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
639
- });
640
- }
641
- function claimCurrentTokenStorageState(params) {
642
- const metadata = readStoredRootMetadata(params.rootDir);
643
- if (!metadata.accessTokenHash?.trim()) return false;
644
- return writeStoredRootMetadata(params.rootDir, {
645
- homeserver: metadata.homeserver,
646
- userId: metadata.userId,
647
- accountId: metadata.accountId ?? DEFAULT_ACCOUNT_KEY,
648
- accessTokenHash: metadata.accessTokenHash,
649
- deviceId: metadata.deviceId ?? null,
650
- currentTokenStateClaimed: true,
651
- createdAt: metadata.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
652
- });
653
- }
654
- function recordCurrentStorageMetaDeviceId(params) {
655
- const deviceId = params.deviceId.trim();
656
- if (!deviceId) return false;
657
- const metadata = readStoredRootMetadata(params.rootDir);
658
- if (!metadata.accessTokenHash?.trim()) return false;
659
- return writeStoredRootMetadata(params.rootDir, {
660
- homeserver: metadata.homeserver,
661
- userId: metadata.userId,
662
- accountId: metadata.accountId ?? DEFAULT_ACCOUNT_KEY,
663
- accessTokenHash: metadata.accessTokenHash,
664
- deviceId,
665
- currentTokenStateClaimed: metadata.currentTokenStateClaimed === true,
666
- createdAt: metadata.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
667
- });
668
- }
669
- function repairCurrentTokenStorageMetaDeviceId(params) {
670
- return writeStorageMeta({
671
- storagePaths: resolveMatrixStoragePaths({
672
- homeserver: params.homeserver,
673
- userId: params.userId,
674
- accessToken: params.accessToken,
675
- accountId: params.accountId,
676
- env: params.env,
677
- stateDir: params.stateDir
678
- }),
679
- homeserver: params.homeserver,
680
- userId: params.userId,
681
- accountId: params.accountId,
682
- deviceId: params.deviceId
683
- });
684
- }
685
380
  //#endregion
686
- export { writeMatrixRecoveryKeyStateForPath as A, readLegacyMatrixRecoveryKeyState as C, writeMatrixIdbSnapshotJson as D, readMatrixRecoveryKeyStateForPath as E, resolveMatrixSqliteStateEnv as M, resolveMatrixSqliteStateKey as N, writeMatrixIdbSnapshotJsonToStore as O, readLegacyMatrixRecoveryKeyFile as S, readMatrixIdbSnapshotJsonFromStore as T, migrateLegacyMatrixRecoveryKeyFilePathToStore as _, openMatrixStorageMetaStoreOptions as a, openMatrixRecoveryKeyStoreOptions as b, resolveMatrixStateFilePath as c, writeStorageMeta as d, MATRIX_IDB_SNAPSHOT_FILENAME as f, hasMatrixRecoveryKeyStateInStore as g, hasMatrixLegacyCryptoMigrationStateInStore as h, normalizeMatrixStorageMetadata as i, writeMatrixRecoveryKeyStateToStore as j, writeMatrixLegacyCryptoMigrationStateToStore as k, resolveMatrixStoragePaths as l, MATRIX_RECOVERY_KEY_FILENAME as m, hasMatrixStorageMetaStateInStore as n, recordCurrentStorageMetaDeviceId as o, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME as p, maybeMigrateLegacyStorage as r, repairCurrentTokenStorageMetaDeviceId as s, claimCurrentTokenStorageState as t, writeMatrixStorageMetaStateToStore as u, openMatrixIdbSnapshotStoreOptions as v, readMatrixIdbSnapshotJson as w, readLegacyMatrixLegacyCryptoMigrationState as x, openMatrixLegacyCryptoMigrationStoreOptions as y };
381
+ export { resolveMatrixSqliteStateKey as A, scoreMatrixCryptoStateInStore as C, writeMatrixRecoveryKeyStateForPath as D, writeMatrixLegacyCryptoMigrationStateToStore as E, writeMatrixRecoveryKeyStateToStore as O, readMatrixRecoveryKeyStateForPath as S, writeMatrixIdbSnapshotJsonToStore as T, readLegacyMatrixLegacyCryptoMigrationState as _, writeMatrixStorageMetaStateToStore as a, readMatrixIdbSnapshotJson as b, MATRIX_RECOVERY_KEY_FILENAME as c, migrateLegacyMatrixLegacyCryptoMigrationFileToStore as d, migrateLegacyMatrixRecoveryKeyFilePathToStore as f, openMatrixRecoveryKeyStoreOptions as g, openMatrixLegacyCryptoMigrationStoreOptions as h, openMatrixStorageMetaStoreOptions as i, resolveMatrixSqliteStateEnv as k, hasMatrixLegacyCryptoMigrationStateInStore as l, openMatrixIdbSnapshotStoreOptions as m, hasMatrixStorageMetaStateInStore as n, MATRIX_IDB_SNAPSHOT_FILENAME as o, migrateLegacyMatrixRecoveryKeyFileToStore as p, normalizeMatrixStorageMetadata as r, MATRIX_LEGACY_CRYPTO_MIGRATION_FILENAME as s, STORAGE_META_STATE_KEY as t, hasMatrixRecoveryKeyStateInStore as u, readLegacyMatrixRecoveryKeyFile as v, writeMatrixIdbSnapshotJson as w, readMatrixIdbSnapshotJsonFromStore as x, readLegacyMatrixRecoveryKeyState as y };
@@ -3,6 +3,18 @@ import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "openclaw/plugin-sdk/acco
3
3
  import crypto from "node:crypto";
4
4
  import path from "node:path";
5
5
  //#region extensions/matrix/src/storage-paths.ts
6
+ const MATRIX_TOKEN_HASH_DIRECTORY_PATTERN = /^[a-f0-9]{16}$/u;
7
+ const MATRIX_SERVER_USER_DIRECTORY_PATTERN = /^.+__.+$/u;
8
+ function isMatrixActiveTokenRootDirectory(name) {
9
+ return MATRIX_TOKEN_HASH_DIRECTORY_PATTERN.test(name);
10
+ }
11
+ function resolveMatrixStateLayoutChildDepth(depth, name) {
12
+ if (depth === 0) return name === "accounts" ? 1 : null;
13
+ if (depth === 1) return 2;
14
+ if (depth === 2) return MATRIX_SERVER_USER_DIRECTORY_PATTERN.test(name) ? 3 : null;
15
+ if (depth === 3) return isMatrixActiveTokenRootDirectory(name) ? 4 : null;
16
+ return null;
17
+ }
6
18
  function sanitizeMatrixPathSegment(value) {
7
19
  return normalizeLowercaseStringOrEmpty(value).replace(/[^a-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "") || "unknown";
8
20
  }
@@ -38,4 +50,4 @@ function resolveMatrixAccountStorageRoot(params) {
38
50
  };
39
51
  }
40
52
  //#endregion
41
- export { resolveMatrixCredentialsPath as a, resolveMatrixCredentialsFilename as i, resolveMatrixAccountStorageRoot as n, resolveMatrixHomeserverKey as o, resolveMatrixCredentialsDir as r, sanitizeMatrixPathSegment as s, hashMatrixAccessToken as t };
53
+ export { resolveMatrixCredentialsFilename as a, resolveMatrixStateLayoutChildDepth as c, resolveMatrixCredentialsDir as i, sanitizeMatrixPathSegment as l, isMatrixActiveTokenRootDirectory as n, resolveMatrixCredentialsPath as o, resolveMatrixAccountStorageRoot as r, resolveMatrixHomeserverKey as s, hashMatrixAccessToken as t };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
- import { M as resolveMatrixSqliteStateEnv } from "./storage-BVf4uucD.js";
2
+ import { k as resolveMatrixSqliteStateEnv } from "./storage-metadata-DYArLcq1.js";
3
3
  import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import path from "node:path";
@@ -74,9 +74,12 @@ function readPersistedStoreFromSyncStore(store) {
74
74
  const stateKey = SYNC_CACHE_STATE_KEY;
75
75
  const meta = store.lookup(metaKey(stateKey));
76
76
  if (!isSyncCacheMeta(meta)) return null;
77
+ const records = store.lookupMany?.(Array.from({ length: meta.chunkCount }, (_, index) => chunkKey(stateKey, meta.generation, index)));
77
78
  const chunks = [];
78
79
  for (let index = 0; index < meta.chunkCount; index += 1) {
79
- const chunk = store.lookup(chunkKey(stateKey, meta.generation, index));
80
+ const result = records?.[index];
81
+ if (result && !result.ok) throw result.error;
82
+ const chunk = records ? result?.value : store.lookup(chunkKey(stateKey, meta.generation, index));
80
83
  if (!isSyncCacheChunk(chunk) || chunk.index !== index) return normalizePersistedStore({
81
84
  version: 1,
82
85
  savedSync: null,
@@ -191,9 +194,12 @@ async function hasMatrixSyncCacheStateInStore(params) {
191
194
  const stateKey = SYNC_CACHE_STATE_KEY;
192
195
  const meta = await params.store.lookup(metaKey(stateKey));
193
196
  if (!isSyncCacheMeta(meta) || meta.chunkCount <= 0) return false;
197
+ const records = await params.store.lookupMany?.(Array.from({ length: meta.chunkCount }, (_, index) => chunkKey(stateKey, meta.generation, index)));
194
198
  const chunks = [];
195
199
  for (let index = 0; index < meta.chunkCount; index += 1) {
196
- const chunk = await params.store.lookup(chunkKey(stateKey, meta.generation, index));
200
+ const result = records?.[index];
201
+ if (result && !result.ok) throw result.error;
202
+ const chunk = records ? result?.value : await params.store.lookup(chunkKey(stateKey, meta.generation, index));
197
203
  if (!isSyncCacheChunk(chunk) || chunk.index !== index) return false;
198
204
  chunks.push(chunk.data);
199
205
  }
@@ -1,7 +1,8 @@
1
1
  import { t as getMatrixRuntime } from "./runtime-6S3DNFNv.js";
2
2
  import { a as listBindingsForAccount, c as resolveEffectiveBindingExpiry, d as setMatrixThreadBindingManagerEntry, l as setBindingRecord, m as toSessionBindingRecord, o as removeBindingRecord, p as toMatrixBindingTargetKind, r as getMatrixThreadBindingManagerEntry, s as resolveBindingKey, t as deleteMatrixThreadBindingManagerEntry } from "./thread-bindings-shared-oNPiyMWY.js";
3
- import { M as resolveMatrixSqliteStateEnv, N as resolveMatrixSqliteStateKey, c as resolveMatrixStateFilePath, t as claimCurrentTokenStorageState } from "./storage-BVf4uucD.js";
4
- import { r as sendMessageMatrix } from "./send-B5XChnvB.js";
3
+ import { A as resolveMatrixSqliteStateKey, k as resolveMatrixSqliteStateEnv } from "./storage-metadata-DYArLcq1.js";
4
+ import { a as resolveMatrixStateFilePath, t as claimCurrentTokenStorageState } from "./storage-CV-pfV_2.js";
5
+ import { r as sendMessageMatrix } from "./send-UWLIQ0bG.js";
5
6
  import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
6
7
  import { createHash } from "node:crypto";
7
8
  import path from "node:path";