@vapi-network/core 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/account-add.d.ts +8 -1
  2. package/dist/account-add.d.ts.map +1 -1
  3. package/dist/account-movement-lock.d.ts +10 -0
  4. package/dist/account-movement-lock.d.ts.map +1 -0
  5. package/dist/agent-link.d.ts +1 -0
  6. package/dist/agent-link.d.ts.map +1 -1
  7. package/dist/agent-link.js +21 -10
  8. package/dist/agent-link.js.map +1 -1
  9. package/dist/agent-profile.d.ts +14 -2
  10. package/dist/agent-profile.d.ts.map +1 -1
  11. package/dist/agent-run.d.ts +12 -0
  12. package/dist/agent-run.d.ts.map +1 -0
  13. package/dist/allocation.d.ts +35 -4
  14. package/dist/allocation.d.ts.map +1 -1
  15. package/dist/api-key.js.map +1 -1
  16. package/dist/atomic-file.d.ts +23 -0
  17. package/dist/atomic-file.d.ts.map +1 -0
  18. package/dist/audit.d.ts +4 -1
  19. package/dist/audit.d.ts.map +1 -1
  20. package/dist/backup.d.ts +153 -32
  21. package/dist/backup.d.ts.map +1 -1
  22. package/dist/backup.js +2535 -139
  23. package/dist/backup.js.map +3 -3
  24. package/dist/call-contracts-wire.d.ts +12 -12
  25. package/dist/ceiling.d.ts +8 -0
  26. package/dist/ceiling.d.ts.map +1 -1
  27. package/dist/cloud-backup.d.ts +8 -10
  28. package/dist/cloud-backup.d.ts.map +1 -1
  29. package/dist/cloud-backup.js +2806 -381
  30. package/dist/cloud-backup.js.map +3 -3
  31. package/dist/config.d.ts.map +1 -1
  32. package/dist/distribute.d.ts +9 -1
  33. package/dist/distribute.d.ts.map +1 -1
  34. package/dist/index.d.ts +8 -2
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +5206 -1270
  37. package/dist/index.js.map +3 -3
  38. package/dist/marketplace-contracts.d.ts +14 -14
  39. package/dist/member-bundle.d.ts +110 -0
  40. package/dist/member-bundle.d.ts.map +1 -0
  41. package/dist/movement-open.d.ts +10 -0
  42. package/dist/movement-open.d.ts.map +1 -0
  43. package/dist/movement.d.ts +77 -7
  44. package/dist/movement.d.ts.map +1 -1
  45. package/dist/receipts.d.ts +9 -0
  46. package/dist/receipts.d.ts.map +1 -1
  47. package/dist/router-client.d.ts +9 -1
  48. package/dist/router-client.d.ts.map +1 -1
  49. package/dist/router-client.js +2073 -607
  50. package/dist/router-client.js.map +3 -3
  51. package/dist/run-budget.d.ts +17 -0
  52. package/dist/run-budget.d.ts.map +1 -0
  53. package/dist/secret-store.d.ts +6 -0
  54. package/dist/secret-store.d.ts.map +1 -1
  55. package/dist/secrets.d.ts +2 -1
  56. package/dist/secrets.d.ts.map +1 -1
  57. package/dist/secrets.js +884 -48
  58. package/dist/secrets.js.map +3 -3
  59. package/dist/support-report.d.ts +1 -1
  60. package/dist/swarm-capital.d.ts +147 -0
  61. package/dist/swarm-capital.d.ts.map +1 -0
  62. package/dist/swarm.d.ts +224 -0
  63. package/dist/swarm.d.ts.map +1 -0
  64. package/dist/transfer-journal.d.ts +11 -0
  65. package/dist/transfer-journal.d.ts.map +1 -0
  66. package/dist/transfer.d.ts +4 -1
  67. package/dist/transfer.d.ts.map +1 -1
  68. package/dist/vault.d.ts +11 -0
  69. package/dist/vault.d.ts.map +1 -1
  70. package/dist/wallet-store.d.ts +19 -8
  71. package/dist/wallet-store.d.ts.map +1 -1
  72. package/dist/x402-pay.d.ts +7 -0
  73. package/dist/x402-pay.d.ts.map +1 -1
  74. package/dist/x402.d.ts +3 -0
  75. package/dist/x402.d.ts.map +1 -1
  76. package/package.json +1 -1
package/dist/backup.js CHANGED
@@ -3947,7 +3947,7 @@ function weierstrass(curveDef) {
3947
3947
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
3948
3948
  if (["recovered", "canonical"].some((k) => k in opts))
3949
3949
  throw new Error("sign() legacy options not supported");
3950
- const { hash: hash2, randomBytes: randomBytes4 } = CURVE;
3950
+ const { hash: hash2, randomBytes: randomBytes7 } = CURVE;
3951
3951
  let { lowS, prehash, extraEntropy: ent } = opts;
3952
3952
  if (lowS == null)
3953
3953
  lowS = true;
@@ -3959,7 +3959,7 @@ function weierstrass(curveDef) {
3959
3959
  const d = normPrivateKeyToScalar(privateKey);
3960
3960
  const seedArgs = [int2octets(d), int2octets(h1int)];
3961
3961
  if (ent != null && ent !== false) {
3962
- const e = ent === true ? randomBytes4(Fp.BYTES) : ent;
3962
+ const e = ent === true ? randomBytes7(Fp.BYTES) : ent;
3963
3963
  seedArgs.push(ensureBytes("extraEntropy", e));
3964
3964
  }
3965
3965
  const seed = concatBytes3(...seedArgs);
@@ -4277,6 +4277,7 @@ import {
4277
4277
  createCipheriv as createCipheriv2,
4278
4278
  createDecipheriv as createDecipheriv2,
4279
4279
  createHash,
4280
+ createHmac,
4280
4281
  createPrivateKey,
4281
4282
  createPublicKey,
4282
4283
  diffieHellman,
@@ -4285,8 +4286,18 @@ import {
4285
4286
  scrypt as scrypt2,
4286
4287
  timingSafeEqual
4287
4288
  } from "node:crypto";
4288
- import { link, lstat, mkdir as mkdir2, mkdtemp, open as openFile, rm as rm2 } from "node:fs/promises";
4289
- import { join as join2 } from "node:path";
4289
+ import {
4290
+ chmod as chmod2,
4291
+ link as link2,
4292
+ lstat,
4293
+ mkdir as mkdir7,
4294
+ mkdtemp,
4295
+ open as openFile,
4296
+ readFile as readFile9,
4297
+ readdir as readdir5,
4298
+ rm as rm2
4299
+ } from "node:fs/promises";
4300
+ import { dirname as dirname4, join as join8 } from "node:path";
4290
4301
 
4291
4302
  // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
4292
4303
  init_getAddress();
@@ -5329,6 +5340,7 @@ function serializeSignature({ r, s, to = "hex", v, yParity }) {
5329
5340
 
5330
5341
  // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/index.js
5331
5342
  init_getAddress();
5343
+ init_isAddress();
5332
5344
 
5333
5345
  // ../../node_modules/.pnpm/@scure+bip32@1.7.0/node_modules/@scure/bip32/lib/esm/index.js
5334
5346
  init_modular();
@@ -45487,6 +45499,263 @@ function date4(params) {
45487
45499
  return _coercedDate(ZodDate, params);
45488
45500
  }
45489
45501
 
45502
+ // src/agent-profile.ts
45503
+ import { mkdir as mkdir3, readFile as readFile3, readdir as readdir2, rename as rename3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
45504
+ import { join as join4 } from "node:path";
45505
+
45506
+ // src/config.ts
45507
+ import { constants } from "node:fs";
45508
+ import { copyFile, mkdir as mkdir2, readFile as readFile2, rename as rename2, stat as stat2, writeFile } from "node:fs/promises";
45509
+ import { homedir } from "node:os";
45510
+ import { dirname as dirname2, join as join3 } from "node:path";
45511
+
45512
+ // src/atomic-file.ts
45513
+ import { randomBytes as randomBytes2 } from "node:crypto";
45514
+ import { link, mkdir, open as open2, readdir, readFile, rename, stat, unlink } from "node:fs/promises";
45515
+ import { basename, dirname, join as join2 } from "node:path";
45516
+ var DEFAULT_LOCK_TIMEOUT_MS = 2e3;
45517
+ var LOCK_RETRY_MS = 20;
45518
+ var LOCK_STALE_AFTER_MS = 12e4;
45519
+ var LOCK_HEARTBEAT_MS = 3e4;
45520
+ var atomicFileTestHooks;
45521
+ var FileLockedError = class extends Error {
45522
+ constructor(message = "Timed out waiting for the file lock.") {
45523
+ super(message);
45524
+ this.name = "FileLockedError";
45525
+ }
45526
+ };
45527
+ async function writeJsonAtomic(path, value, options = {}) {
45528
+ const directory = dirname(path);
45529
+ await mkdir(directory, { recursive: true, mode: 448 });
45530
+ const temporaryPath = join2(
45531
+ directory,
45532
+ `.${basename(path)}.${process.pid}.${randomBytes2(6).toString("hex")}.tmp`
45533
+ );
45534
+ let handle;
45535
+ try {
45536
+ handle = await open2(temporaryPath, "wx", options.mode ?? 384);
45537
+ await handle.writeFile(`${JSON.stringify(value, null, 2)}
45538
+ `, "utf8");
45539
+ await handle.sync();
45540
+ await handle.close();
45541
+ handle = void 0;
45542
+ await rename(temporaryPath, path);
45543
+ const directoryHandle = await open2(directory, "r");
45544
+ try {
45545
+ await directoryHandle.sync();
45546
+ } finally {
45547
+ await directoryHandle.close();
45548
+ }
45549
+ } catch (error61) {
45550
+ await handle?.close().catch(() => void 0);
45551
+ await unlink(temporaryPath).catch(() => void 0);
45552
+ throw error61;
45553
+ }
45554
+ }
45555
+ async function withFileLock(lockPath, fn, options = {}) {
45556
+ await mkdir(dirname(lockPath), { recursive: true, mode: 448 });
45557
+ const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS);
45558
+ const ownerRecord = {
45559
+ pid: process.pid,
45560
+ token: randomBytes2(16).toString("hex")
45561
+ };
45562
+ const owner = JSON.stringify(ownerRecord);
45563
+ const releasedOwner = JSON.stringify({ ...ownerRecord, released: true });
45564
+ let handle;
45565
+ while (handle === void 0) {
45566
+ await atomicFileTestHooks?.beforeLockAttempt?.(lockPath);
45567
+ try {
45568
+ const candidate = await open2(lockPath, "wx", 384);
45569
+ try {
45570
+ await candidate.writeFile(owner, "utf8");
45571
+ await candidate.sync();
45572
+ await atomicFileTestHooks?.afterLockCreate?.(lockPath);
45573
+ if (await lockTakeoverInProgress(lockPath)) {
45574
+ await candidate.close();
45575
+ await removeOwnedLock(lockPath, [owner]);
45576
+ await removeAbandonedLockTombs(lockPath);
45577
+ if (Date.now() >= deadline) {
45578
+ throw new FileLockedError(options.lockedMessage);
45579
+ }
45580
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
45581
+ continue;
45582
+ }
45583
+ handle = candidate;
45584
+ } catch (error61) {
45585
+ await candidate.close().catch(() => void 0);
45586
+ await removeOwnedLock(lockPath, [owner]).catch(() => void 0);
45587
+ throw error61;
45588
+ }
45589
+ } catch (error61) {
45590
+ if (!hasCode(error61, "EEXIST")) throw error61;
45591
+ await removeStaleLock(lockPath);
45592
+ if (Date.now() >= deadline) {
45593
+ throw new FileLockedError(options.lockedMessage);
45594
+ }
45595
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
45596
+ }
45597
+ }
45598
+ const ownedHandle = handle;
45599
+ const heartbeat = setInterval(() => {
45600
+ const time3 = /* @__PURE__ */ new Date();
45601
+ void ownedHandle.utimes(time3, time3).catch(() => void 0);
45602
+ }, LOCK_HEARTBEAT_MS);
45603
+ heartbeat.unref();
45604
+ try {
45605
+ return await fn();
45606
+ } finally {
45607
+ clearInterval(heartbeat);
45608
+ try {
45609
+ await markLockReleased(ownedHandle, releasedOwner);
45610
+ } finally {
45611
+ try {
45612
+ await ownedHandle.close();
45613
+ } finally {
45614
+ await removeOwnedLock(lockPath, [owner, releasedOwner]);
45615
+ }
45616
+ }
45617
+ }
45618
+ }
45619
+ async function removeStaleLock(path) {
45620
+ try {
45621
+ const owner = await readFile(path, "utf8");
45622
+ if (lockOwnerReleased(owner)) {
45623
+ await removeOwnedLock(path, [owner]);
45624
+ return;
45625
+ }
45626
+ const metadata = await stat(path);
45627
+ if (Date.now() - metadata.mtimeMs <= LOCK_STALE_AFTER_MS) return;
45628
+ const pid = lockOwnerPid(owner);
45629
+ if (pid !== void 0 && processIsAlive(pid)) return;
45630
+ await atomicFileTestHooks?.beforeStaleLockBreak?.(path);
45631
+ await removeOwnedLock(path, [owner]);
45632
+ } catch (error61) {
45633
+ if (!hasCode(error61, "ENOENT")) throw error61;
45634
+ }
45635
+ }
45636
+ async function removeOwnedLock(path, owners) {
45637
+ const tombPath = `${path}.stale.${randomBytes2(16).toString("hex")}`;
45638
+ try {
45639
+ await rename(path, tombPath);
45640
+ } catch (error61) {
45641
+ if (hasCode(error61, "ENOENT")) {
45642
+ await removeOwnedTombs(path, owners);
45643
+ const currentOwner = await readFile(path, "utf8").catch(() => void 0);
45644
+ if (currentOwner !== void 0 && owners.includes(currentOwner)) {
45645
+ await removeOwnedLock(path, owners);
45646
+ }
45647
+ return;
45648
+ }
45649
+ throw error61;
45650
+ }
45651
+ let pendingError;
45652
+ try {
45653
+ const renamedOwner = await readFile(tombPath, "utf8");
45654
+ if (!owners.includes(renamedOwner) && !lockOwnerReleased(renamedOwner)) {
45655
+ await atomicFileTestHooks?.afterMismatchedLockRename?.(path);
45656
+ const currentOwner = await readFile(tombPath, "utf8");
45657
+ if (!lockOwnerReleased(currentOwner)) await restoreRenamedLock(path, tombPath);
45658
+ await atomicFileTestHooks?.afterMismatchedLockRestore?.(path);
45659
+ }
45660
+ } catch (error61) {
45661
+ pendingError = error61;
45662
+ }
45663
+ try {
45664
+ await unlink(tombPath);
45665
+ } catch (error61) {
45666
+ if (!hasCode(error61, "ENOENT") && pendingError === void 0) {
45667
+ pendingError = error61;
45668
+ }
45669
+ }
45670
+ if (pendingError !== void 0) throw pendingError;
45671
+ }
45672
+ async function lockTakeoverInProgress(path) {
45673
+ const prefix = `${basename(path)}.stale.`;
45674
+ return (await readdir(dirname(path))).some((entry) => entry.startsWith(prefix));
45675
+ }
45676
+ async function removeAbandonedLockTombs(path) {
45677
+ const directory = dirname(path);
45678
+ const prefix = `${basename(path)}.stale.`;
45679
+ for (const entry of await readdir(directory)) {
45680
+ if (!entry.startsWith(prefix)) continue;
45681
+ const tombPath = join2(directory, entry);
45682
+ const [metadata, owner] = await Promise.all([
45683
+ stat(tombPath).catch(() => void 0),
45684
+ readFile(tombPath, "utf8").catch(() => void 0)
45685
+ ]);
45686
+ if (metadata === void 0 || owner === void 0) continue;
45687
+ const pid = lockOwnerPid(owner);
45688
+ const abandoned = lockOwnerReleased(owner) || Date.now() - metadata.mtimeMs > LOCK_STALE_AFTER_MS && (pid === void 0 || !processIsAlive(pid));
45689
+ if (!abandoned) continue;
45690
+ await unlink(tombPath).catch((error61) => {
45691
+ if (!hasCode(error61, "ENOENT")) throw error61;
45692
+ });
45693
+ }
45694
+ }
45695
+ async function removeOwnedTombs(path, owners) {
45696
+ const directory = dirname(path);
45697
+ const prefix = `${basename(path)}.stale.`;
45698
+ for (const entry of await readdir(directory)) {
45699
+ if (!entry.startsWith(prefix)) continue;
45700
+ const tombPath = join2(directory, entry);
45701
+ const owner = await readFile(tombPath, "utf8").catch(() => void 0);
45702
+ if (owner === void 0 || !owners.includes(owner)) continue;
45703
+ await unlink(tombPath).catch((error61) => {
45704
+ if (!hasCode(error61, "ENOENT")) throw error61;
45705
+ });
45706
+ }
45707
+ }
45708
+ async function restoreRenamedLock(path, tombPath) {
45709
+ while (true) {
45710
+ try {
45711
+ await link(tombPath, path);
45712
+ return;
45713
+ } catch (error61) {
45714
+ if (hasCode(error61, "ENOENT")) return;
45715
+ if (!hasCode(error61, "EEXIST")) throw error61;
45716
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
45717
+ }
45718
+ }
45719
+ }
45720
+ async function markLockReleased(handle, owner) {
45721
+ const contents = Buffer.from(owner, "utf8");
45722
+ await handle.write(contents, 0, contents.length, 0);
45723
+ await handle.truncate(contents.length);
45724
+ await handle.sync();
45725
+ }
45726
+ function lockOwnerPid(owner) {
45727
+ try {
45728
+ const value = JSON.parse(owner);
45729
+ if (typeof value !== "object" || value === null) return void 0;
45730
+ const pid = Reflect.get(value, "pid");
45731
+ return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
45732
+ } catch {
45733
+ return void 0;
45734
+ }
45735
+ }
45736
+ function lockOwnerReleased(owner) {
45737
+ try {
45738
+ const value = JSON.parse(owner);
45739
+ return typeof value === "object" && value !== null && Reflect.get(value, "released") === true;
45740
+ } catch {
45741
+ return false;
45742
+ }
45743
+ }
45744
+ function processIsAlive(pid) {
45745
+ if (atomicFileTestHooks?.isProcessAlive !== void 0) {
45746
+ return atomicFileTestHooks.isProcessAlive(pid);
45747
+ }
45748
+ try {
45749
+ process.kill(pid, 0);
45750
+ return true;
45751
+ } catch (error61) {
45752
+ return hasCode(error61, "EPERM");
45753
+ }
45754
+ }
45755
+ function hasCode(error61, code) {
45756
+ return error61 instanceof Error && "code" in error61 && error61.code === code;
45757
+ }
45758
+
45490
45759
  // src/x402-networks.ts
45491
45760
  var BASE_MAINNET_CAIP2 = "eip155:8453";
45492
45761
  var ARC_MAINNET_CAIP2 = "eip155:5042";
@@ -45591,6 +45860,14 @@ function parseEip155ChainId(network) {
45591
45860
  function isSolanaNetwork(network) {
45592
45861
  return network === SOLANA_MAINNET_CAIP2 || network === X402_SOLANA_MAINNET_CAIP2;
45593
45862
  }
45863
+ function explorerTransactionUrl(network, hash2) {
45864
+ try {
45865
+ const explorerUrl = getNetworkDefinition(network).explorerUrl;
45866
+ return explorerUrl ? `${explorerUrl}/tx/${hash2}` : void 0;
45867
+ } catch {
45868
+ return void 0;
45869
+ }
45870
+ }
45594
45871
  function isSupportedPaymentNetwork(network) {
45595
45872
  if (isSolanaNetwork(network)) return true;
45596
45873
  try {
@@ -45600,15 +45877,37 @@ function isSupportedPaymentNetwork(network) {
45600
45877
  return false;
45601
45878
  }
45602
45879
  }
45880
+ function getNetworkDefinition(network) {
45881
+ const known = NETWORKS[network];
45882
+ if (known) {
45883
+ return known;
45884
+ }
45885
+ const chainId = parseEip155ChainId(network);
45886
+ return {
45887
+ family: "evm",
45888
+ chainId,
45889
+ name: network,
45890
+ usdc: getAddress("0x0000000000000000000000000000000000000000"),
45891
+ gasToken: "ETH",
45892
+ rpcEnv: ""
45893
+ };
45894
+ }
45603
45895
 
45604
45896
  // src/config.ts
45605
45897
  var DEFAULT_REGISTRY_URL = "https://api.vapinetwork.ai";
45606
45898
  var DEFAULT_DISCOVERY_URL = `${DEFAULT_REGISTRY_URL}/api/call/services`;
45607
45899
  var DEFAULT_MARKETPLACE_DISCOVERY_URL = `${DEFAULT_REGISTRY_URL}/api/call/discovery`;
45900
+ var DEFAULT_REGISTRY_FALLBACKS = [
45901
+ {
45902
+ discoveryUrl: DEFAULT_DISCOVERY_URL,
45903
+ marketplaceDiscoveryUrl: DEFAULT_MARKETPLACE_DISCOVERY_URL
45904
+ }
45905
+ ];
45608
45906
  var DEFAULT_SPEND_CAPS = {
45609
45907
  perCallAtomic: "100000",
45610
45908
  perDayAtomic: "1000000"
45611
45909
  };
45910
+ var DEFAULT_CEILING_ATOMIC = 5000000n;
45612
45911
  var atomicString = external_exports.string().regex(/^\d+$/, "Expected non-negative atomic units.");
45613
45912
  var spendCapsSchema = external_exports.object({
45614
45913
  perCallAtomic: atomicString,
@@ -45671,9 +45970,339 @@ var configSchema = external_exports.object({
45671
45970
  }
45672
45971
  }
45673
45972
  });
45973
+ function getVapiPaths(directory = process.env.VAPI_HOME?.trim() || join3(homedir(), ".vapi")) {
45974
+ return {
45975
+ directory,
45976
+ agentsDir: join3(directory, "agents"),
45977
+ config: join3(directory, "config.json"),
45978
+ keystore: join3(directory, "keystore.json"),
45979
+ receipts: join3(directory, "receipts.jsonl"),
45980
+ searches: join3(directory, "searches.jsonl"),
45981
+ ledger: join3(directory, "spend-ledger.json")
45982
+ };
45983
+ }
45984
+ async function migrateLegacyVapiHome(options = {}) {
45985
+ const target = getVapiPaths(options.targetDirectory);
45986
+ const legacyDirectory = options.legacyDirectory ?? join3(homedir(), ".vapi", "agent-cash");
45987
+ if (legacyDirectory === target.directory || !await pathExists(legacyDirectory)) return [];
45988
+ await mkdir2(target.directory, { recursive: true, mode: 448 });
45989
+ const copied = [];
45990
+ for (const filename of [
45991
+ "config.json",
45992
+ "keystore.json",
45993
+ "receipts.jsonl",
45994
+ "searches.jsonl",
45995
+ "spend-ledger.json"
45996
+ ]) {
45997
+ const source = join3(legacyDirectory, filename);
45998
+ const destination = join3(target.directory, filename);
45999
+ try {
46000
+ const copy = async () => await copyFile(source, destination, constants.COPYFILE_EXCL);
46001
+ if (filename === "receipts.jsonl") {
46002
+ await withFileLock(`${destination}.lock`, copy, {
46003
+ lockedMessage: "The receipt journal is busy. Wait for the other vapi command to finish, then retry."
46004
+ });
46005
+ } else {
46006
+ await copy();
46007
+ }
46008
+ copied.push(destination);
46009
+ } catch (error61) {
46010
+ if (isMissingFile(error61) || isAlreadyExists(error61)) continue;
46011
+ throw error61;
46012
+ }
46013
+ }
46014
+ if (copied.length > 0) {
46015
+ const message = `Migrated legacy vAPI wallet files from ${legacyDirectory} to ${target.directory}; originals were kept.`;
46016
+ (options.notice ?? ((value) => process.stderr.write(`${value}
46017
+ `)))(message);
46018
+ }
46019
+ return copied;
46020
+ }
46021
+ var LEGACY_REGISTRY_HOSTS = /* @__PURE__ */ new Map([
46022
+ ["console.vapinetwork.ai", "api.vapinetwork.ai"],
46023
+ ["console-staging.vapinetwork.ai", "api-staging.vapinetwork.ai"]
46024
+ ]);
46025
+ var LEGACY_REGISTRY_PATHS = /* @__PURE__ */ new Map([
46026
+ ["/api/network/services", "/api/call/services"],
46027
+ ["/api/marketplace/discovery", "/api/call/discovery"]
46028
+ ]);
46029
+ var REGISTRY_DOMAIN = "vapinetwork.ai";
46030
+ function rewriteLegacyRegistryUrl(value) {
46031
+ let url2;
46032
+ try {
46033
+ url2 = new URL(value);
46034
+ } catch {
46035
+ return value;
46036
+ }
46037
+ let rewritten = false;
46038
+ const host = LEGACY_REGISTRY_HOSTS.get(url2.hostname.toLowerCase());
46039
+ if (host) {
46040
+ url2.hostname = host;
46041
+ rewritten = true;
46042
+ }
46043
+ const hostname3 = url2.hostname.toLowerCase();
46044
+ if (hostname3 === REGISTRY_DOMAIN || hostname3.endsWith(`.${REGISTRY_DOMAIN}`)) {
46045
+ const path = LEGACY_REGISTRY_PATHS.get(url2.pathname.replace(/\/+$/, ""));
46046
+ if (path) {
46047
+ url2.pathname = path;
46048
+ rewritten = true;
46049
+ }
46050
+ }
46051
+ return rewritten ? url2.href : value;
46052
+ }
46053
+ function rewriteLegacyRegistryUrls(config2) {
46054
+ const changes = [];
46055
+ const rewrite = (field, from) => {
46056
+ const to = rewriteLegacyRegistryUrl(from);
46057
+ if (to !== from) changes.push({ field, from, to });
46058
+ return to;
46059
+ };
46060
+ const next = {
46061
+ ...config2,
46062
+ discoveryUrl: rewrite("discoveryUrl", config2.discoveryUrl),
46063
+ marketplaceDiscoveryUrl: rewrite("marketplaceDiscoveryUrl", config2.marketplaceDiscoveryUrl),
46064
+ ...config2.registryFallbacks ? {
46065
+ registryFallbacks: config2.registryFallbacks.map((fallback, index) => ({
46066
+ discoveryUrl: rewrite(
46067
+ `registryFallbacks[${index}].discoveryUrl`,
46068
+ fallback.discoveryUrl
46069
+ ),
46070
+ marketplaceDiscoveryUrl: rewrite(
46071
+ `registryFallbacks[${index}].marketplaceDiscoveryUrl`,
46072
+ fallback.marketplaceDiscoveryUrl
46073
+ )
46074
+ }))
46075
+ } : {}
46076
+ };
46077
+ return changes.length === 0 ? { config: config2, changes } : { config: next, changes };
46078
+ }
46079
+ function formatLegacyRegistryRewrites(changes) {
46080
+ return [
46081
+ "Rewrote retired vAPI registry URLs in the local config:",
46082
+ ...changes.map((change) => ` ${change.field}: ${change.from} -> ${change.to}`)
46083
+ ].join("\n");
46084
+ }
46085
+ function getDefaultConfig(source = process.env, options = {}) {
46086
+ const registry2 = registryEndpoints(source.VAPI_REGISTRY_URL?.trim() || DEFAULT_REGISTRY_URL);
46087
+ const requested = new Set(options.networks ?? ["base"]);
46088
+ const networks = {};
46089
+ if (requested.has("base") || requested.has(BASE_MAINNET_CAIP2)) {
46090
+ networks[BASE_MAINNET_CAIP2] = {
46091
+ rpcUrl: source.BASE_RPC_URL?.trim() || NETWORKS[BASE_MAINNET_CAIP2].publicRpcUrl,
46092
+ usdc: NETWORKS[BASE_MAINNET_CAIP2].usdc
46093
+ };
46094
+ }
46095
+ const arcMainnetRpcUrl = source.ARC_RPC_URL?.trim();
46096
+ if (arcMainnetRpcUrl || requested.has("arc") || requested.has(ARC_MAINNET_CAIP2)) {
46097
+ networks[ARC_MAINNET_CAIP2] = {
46098
+ rpcUrl: arcMainnetRpcUrl || NETWORKS[ARC_MAINNET_CAIP2].publicRpcUrl,
46099
+ usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc
46100
+ };
46101
+ }
46102
+ const arcTestnetRpcUrl = source.ARC_TESTNET_RPC_URL?.trim();
46103
+ if (arcTestnetRpcUrl || requested.has("arc-testnet") || requested.has(ARC_TESTNET_CAIP2)) {
46104
+ if (!arcTestnetRpcUrl) {
46105
+ throw new Error(
46106
+ "Arc testnet RPC is required. Set ARC_TESTNET_RPC_URL before enabling Arc testnet."
46107
+ );
46108
+ }
46109
+ networks[ARC_TESTNET_CAIP2] = {
46110
+ rpcUrl: arcTestnetRpcUrl,
46111
+ usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc
46112
+ };
46113
+ }
46114
+ const solanaRpcUrl = source.SOLANA_RPC_URL?.trim();
46115
+ if (solanaRpcUrl || requested.has("solana") || requested.has(SOLANA_MAINNET_CAIP2)) {
46116
+ networks[SOLANA_MAINNET_CAIP2] = {
46117
+ rpcUrl: solanaRpcUrl || NETWORKS[SOLANA_MAINNET_CAIP2].publicRpcUrl,
46118
+ usdc: NETWORKS[SOLANA_MAINNET_CAIP2].usdc
46119
+ };
46120
+ }
46121
+ return {
46122
+ discoveryUrl: source.VAPI_DISCOVERY_URL?.trim() || registry2.discoveryUrl,
46123
+ marketplaceDiscoveryUrl: source.VAPI_MARKETPLACE_DISCOVERY_URL?.trim() || registry2.marketplaceDiscoveryUrl,
46124
+ registryFallbacks: DEFAULT_REGISTRY_FALLBACKS.map((fallback) => ({ ...fallback })),
46125
+ allowPrivateNetwork: false,
46126
+ networks,
46127
+ spendCaps: { ...DEFAULT_SPEND_CAPS }
46128
+ };
46129
+ }
46130
+ async function loadConfig(path = getVapiPaths().config, source = process.env, options = {}) {
46131
+ if (!process.env.VAPI_HOME?.trim() && path === getVapiPaths(join3(homedir(), ".vapi")).config) {
46132
+ await migrateLegacyVapiHome({ targetDirectory: join3(homedir(), ".vapi") });
46133
+ }
46134
+ let raw;
46135
+ try {
46136
+ raw = await readFile2(path, "utf8");
46137
+ } catch (error61) {
46138
+ if (isMissingFile(error61)) return getDefaultConfig(source);
46139
+ throw error61;
46140
+ }
46141
+ const parsed = configSchema.parse(JSON.parse(raw));
46142
+ parsed.registryFallbacks ??= DEFAULT_REGISTRY_FALLBACKS.map((fallback) => ({ ...fallback }));
46143
+ const migrated = rewriteLegacyRegistryUrls(parsed);
46144
+ const config2 = migrated.config;
46145
+ if (migrated.changes.length > 0 && options.notice) {
46146
+ options.notice(
46147
+ `${formatLegacyRegistryRewrites(migrated.changes)}
46148
+ Run vapi init to write the new URLs to ${path}.`
46149
+ );
46150
+ }
46151
+ const baseRpcUrl = source.BASE_RPC_URL?.trim();
46152
+ const arcMainnetRpcUrl = source.ARC_RPC_URL?.trim();
46153
+ const arcTestnetRpcUrl = source.ARC_TESTNET_RPC_URL?.trim();
46154
+ const solanaRpcUrl = source.SOLANA_RPC_URL?.trim();
46155
+ const discoveryUrl = source.VAPI_DISCOVERY_URL?.trim();
46156
+ const marketplaceDiscoveryUrl = source.VAPI_MARKETPLACE_DISCOVERY_URL?.trim();
46157
+ const registryUrl = source.VAPI_REGISTRY_URL?.trim();
46158
+ if (config2.networks[BASE_MAINNET_CAIP2] && baseRpcUrl) {
46159
+ config2.networks[BASE_MAINNET_CAIP2].rpcUrl = baseRpcUrl;
46160
+ }
46161
+ if (arcMainnetRpcUrl) {
46162
+ const existing = config2.networks[ARC_MAINNET_CAIP2];
46163
+ config2.networks[ARC_MAINNET_CAIP2] = {
46164
+ ...existing ?? { usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc },
46165
+ rpcUrl: arcMainnetRpcUrl
46166
+ };
46167
+ }
46168
+ if (arcTestnetRpcUrl) {
46169
+ const existing = config2.networks[ARC_TESTNET_CAIP2];
46170
+ config2.networks[ARC_TESTNET_CAIP2] = {
46171
+ ...existing ?? { usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc },
46172
+ rpcUrl: arcTestnetRpcUrl
46173
+ };
46174
+ }
46175
+ if (solanaRpcUrl) {
46176
+ config2.networks[SOLANA_MAINNET_CAIP2] = {
46177
+ rpcUrl: solanaRpcUrl,
46178
+ usdc: config2.networks[SOLANA_MAINNET_CAIP2]?.usdc ?? NETWORKS[SOLANA_MAINNET_CAIP2].usdc
46179
+ };
46180
+ }
46181
+ if (registryUrl) {
46182
+ const registry2 = registryEndpoints(registryUrl);
46183
+ config2.discoveryUrl = registry2.discoveryUrl;
46184
+ config2.marketplaceDiscoveryUrl = registry2.marketplaceDiscoveryUrl;
46185
+ }
46186
+ if (discoveryUrl) config2.discoveryUrl = discoveryUrl;
46187
+ if (marketplaceDiscoveryUrl) config2.marketplaceDiscoveryUrl = marketplaceDiscoveryUrl;
46188
+ for (const [network, configured] of Object.entries(config2.networks)) {
46189
+ configured.rpcUrl = configured.rpcUrl.trim();
46190
+ configured.usdc = configured.usdc.trim();
46191
+ if (isSolanaNetwork(network) && configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
46192
+ throw new Error(`Network ${network} must use canonical Solana mainnet USDC.`);
46193
+ }
46194
+ if (!configured.rpcUrl) delete config2.networks[network];
46195
+ }
46196
+ return config2;
46197
+ }
46198
+ function registryEndpoints(baseUrl) {
46199
+ const base = new URL(baseUrl);
46200
+ base.search = "";
46201
+ base.hash = "";
46202
+ const prefix = base.pathname === "/" ? "" : base.pathname.replace(/\/+$/, "");
46203
+ const discovery = new URL(base);
46204
+ discovery.pathname = `${prefix}/api/call/services`;
46205
+ const marketplace = new URL(base);
46206
+ marketplace.pathname = `${prefix}/api/call/discovery`;
46207
+ return { discoveryUrl: discovery.href, marketplaceDiscoveryUrl: marketplace.href };
46208
+ }
46209
+ async function pathExists(path) {
46210
+ try {
46211
+ await stat2(path);
46212
+ return true;
46213
+ } catch (error61) {
46214
+ if (isMissingFile(error61)) return false;
46215
+ throw error61;
46216
+ }
46217
+ }
46218
+ function isMissingFile(error61) {
46219
+ return error61 instanceof Error && "code" in error61 && error61.code === "ENOENT";
46220
+ }
46221
+ function isAlreadyExists(error61) {
46222
+ return error61 instanceof Error && "code" in error61 && error61.code === "EEXIST";
46223
+ }
46224
+
46225
+ // src/wallet-name.ts
46226
+ var DEFAULT_WALLET_NAME = "main";
46227
+ var WALLET_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
46228
+ var walletNameSchema = external_exports.string().regex(
46229
+ WALLET_NAME_PATTERN,
46230
+ "A wallet name is 1 to 32 characters of lowercase letters, digits and dashes, starting with a letter or digit."
46231
+ );
46232
+
46233
+ // src/agent-profile.ts
46234
+ var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
46235
+ var AGENT_GRANTS = ["read", "delegate", "allocate"];
46236
+ var agentProfileShape = {
46237
+ version: external_exports.literal(1),
46238
+ name: walletNameSchema,
46239
+ wallet: external_exports.string(),
46240
+ model: external_exports.string().min(1),
46241
+ instructions: external_exports.string().max(2e4),
46242
+ verifiedOnly: external_exports.boolean().default(true),
46243
+ approveAboveUsd: external_exports.number().min(0).default(0.5),
46244
+ maxSteps: external_exports.number().int().min(1).max(50).default(12),
46245
+ paused: external_exports.boolean().default(false),
46246
+ grants: external_exports.array(external_exports.enum(AGENT_GRANTS)).default([]),
46247
+ createdAt: external_exports.string()
46248
+ };
46249
+ function createAgentProfileSchema(toolNames) {
46250
+ if (toolNames.length === 0) {
46251
+ throw new Error("Agent profiles require at least one registered tool.");
46252
+ }
46253
+ const tools = [...toolNames];
46254
+ return external_exports.object({ ...agentProfileShape, tools: external_exports.array(external_exports.enum(tools)).default(tools) });
46255
+ }
46256
+ var agentProfileSchema = createAgentProfileSchema(DEFAULT_AGENT_TOOLS);
46257
+ async function listAgentProfiles(home, options = {}) {
46258
+ const directory = getVapiPaths(home).agentsDir;
46259
+ let files;
46260
+ try {
46261
+ files = await readdir2(directory);
46262
+ } catch (error61) {
46263
+ if (isMissingFile(error61)) return [];
46264
+ throw error61;
46265
+ }
46266
+ const warn = options.warn ?? ((message) => console.warn(message));
46267
+ const profiles = [];
46268
+ for (const file2 of files) {
46269
+ if (!file2.endsWith(".json")) continue;
46270
+ try {
46271
+ profiles.push(
46272
+ (options.schema ?? agentProfileSchema).parse(
46273
+ JSON.parse(await readFile3(join4(directory, file2), "utf8"))
46274
+ )
46275
+ );
46276
+ } catch {
46277
+ options.onInvalid?.(file2);
46278
+ warn(`Skipping invalid agent profile ${file2}.`);
46279
+ }
46280
+ }
46281
+ profiles.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
46282
+ return profiles;
46283
+ }
46284
+
46285
+ // src/device.ts
46286
+ import { hostname as operatingSystemHostname } from "node:os";
46287
+ var DEVICE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
46288
+ function normalizedDeviceName(value) {
46289
+ return value.toLowerCase().replace(/[^a-z0-9-]/gu, "-").replace(/-+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 32).replace(/-+$/gu, "");
46290
+ }
46291
+ function slugifyDeviceName(value) {
46292
+ return normalizedDeviceName(value) || "device";
46293
+ }
46294
+ function deviceName(args = {}) {
46295
+ const environmentValue = args.env === void 0 ? process.env.VAPI_DEVICE : args.env.VAPI_DEVICE;
46296
+ for (const value of [environmentValue?.trim(), args.config?.device]) {
46297
+ if (value === void 0 || value.length === 0) continue;
46298
+ const normalized = normalizedDeviceName(value);
46299
+ if (normalized.length > 0) return normalized;
46300
+ }
46301
+ return slugifyDeviceName(args.hostname ?? operatingSystemHostname());
46302
+ }
45674
46303
 
45675
46304
  // src/keystore.ts
45676
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes2, scrypt } from "node:crypto";
46305
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes3, scrypt } from "node:crypto";
45677
46306
  var SCRYPT_N = 2 ** 15;
45678
46307
  var SCRYPT_R = 8;
45679
46308
  var SCRYPT_P = 1;
@@ -45748,7 +46377,7 @@ function encryptWithKey(key, plaintext) {
45748
46377
  if (key.byteLength !== KEY_LENGTH) {
45749
46378
  throw new Error(`Expected a ${KEY_LENGTH}-byte AES-256-GCM key.`);
45750
46379
  }
45751
- const nonce = randomBytes2(12);
46380
+ const nonce = randomBytes3(12);
45752
46381
  const cipher = createCipheriv("aes-256-gcm", key, nonce, {
45753
46382
  authTagLength: AUTH_TAG_LENGTH
45754
46383
  });
@@ -45814,17 +46443,290 @@ function deriveEvmPrivateKey(seed, path = EVM_DERIVATION_PATH) {
45814
46443
  return `0x${Buffer.from(privateKey).toString("hex")}`;
45815
46444
  }
45816
46445
 
45817
- // src/wallet-name.ts
45818
- var WALLET_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
45819
- var walletNameSchema = external_exports.string().regex(
45820
- WALLET_NAME_PATTERN,
45821
- "A wallet name is 1 to 32 characters of lowercase letters, digits and dashes, starting with a letter or digit."
45822
- );
46446
+ // src/movement.ts
46447
+ import { randomBytes as randomBytes6 } from "node:crypto";
46448
+ import { chmod, mkdir as mkdir6, open as open5, readFile as readFile7, readdir as readdir3, rename as rename5, unlink as unlink5 } from "node:fs/promises";
46449
+ import { join as join6 } from "node:path";
46450
+
46451
+ // src/account-movement-lock.ts
46452
+ import { randomBytes as randomBytes4 } from "node:crypto";
46453
+ import { mkdir as mkdir4, open as open3, readFile as readFile4, stat as stat3, unlink as unlink3 } from "node:fs/promises";
46454
+ import { join as join5 } from "node:path";
46455
+ var AccountMovementLockedError = class extends Error {
46456
+ constructor(account) {
46457
+ super(`Another capital movement is already running for account ${account}.`);
46458
+ this.account = account;
46459
+ this.name = "AccountMovementLockedError";
46460
+ }
46461
+ account;
46462
+ code = "account_movement_locked";
46463
+ };
46464
+ async function withAccountMovementLock(home, account, timeoutMs, operation, signal) {
46465
+ const directory = join5(home, "movements");
46466
+ await mkdir4(directory, { recursive: true, mode: 448 });
46467
+ const path = join5(directory, `.${account}.lock`);
46468
+ const deadline = Date.now() + (timeoutMs ?? 2e3);
46469
+ const owner = JSON.stringify({ pid: process.pid, token: randomBytes4(16).toString("hex") });
46470
+ let handle;
46471
+ while (handle === void 0) {
46472
+ signal?.throwIfAborted();
46473
+ try {
46474
+ handle = await open3(path, "wx", 384);
46475
+ await handle.writeFile(owner, "utf8");
46476
+ await handle.sync();
46477
+ } catch (error61) {
46478
+ if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
46479
+ await removeStaleLock2(path);
46480
+ if (Date.now() >= deadline) throw new AccountMovementLockedError(account);
46481
+ await new Promise((resolve) => setTimeout(resolve, 20));
46482
+ }
46483
+ }
46484
+ const ownedHandle = handle;
46485
+ const heartbeat = setInterval(() => {
46486
+ const time3 = /* @__PURE__ */ new Date();
46487
+ void ownedHandle.utimes(time3, time3).catch(() => void 0);
46488
+ }, 3e4);
46489
+ heartbeat.unref();
46490
+ try {
46491
+ return await operation();
46492
+ } finally {
46493
+ clearInterval(heartbeat);
46494
+ await ownedHandle.close();
46495
+ await unlinkOwnedLock(path, owner);
46496
+ }
46497
+ }
46498
+ async function withAccountMovementLocks(home, accounts, timeoutMs, operation) {
46499
+ return await acquireAccountMovementLocks(
46500
+ home,
46501
+ [...new Set(accounts)].sort(),
46502
+ timeoutMs,
46503
+ operation
46504
+ );
46505
+ }
46506
+ async function acquireAccountMovementLocks(home, accounts, timeoutMs, operation) {
46507
+ const [account, ...remaining] = accounts;
46508
+ if (account === void 0) return await operation();
46509
+ return await withAccountMovementLock(
46510
+ home,
46511
+ account,
46512
+ timeoutMs,
46513
+ async () => acquireAccountMovementLocks(home, remaining, timeoutMs, operation)
46514
+ );
46515
+ }
46516
+ async function removeStaleLock2(path) {
46517
+ try {
46518
+ const metadata = await stat3(path);
46519
+ if (Date.now() - metadata.mtimeMs <= 12e4) return;
46520
+ const owner = await readFile4(path, "utf8").catch(() => "");
46521
+ const pid = lockOwnerPid2(owner);
46522
+ if (pid !== void 0 && processIsAlive2(pid)) return;
46523
+ await unlinkOwnedLock(path, owner);
46524
+ } catch (error61) {
46525
+ if (!isMissingFile(error61)) throw error61;
46526
+ }
46527
+ }
46528
+ async function unlinkOwnedLock(path, owner) {
46529
+ try {
46530
+ if (await readFile4(path, "utf8") === owner) await unlink3(path);
46531
+ } catch (error61) {
46532
+ if (!isMissingFile(error61)) throw error61;
46533
+ }
46534
+ }
46535
+ function lockOwnerPid2(owner) {
46536
+ try {
46537
+ const value = JSON.parse(owner);
46538
+ if (typeof value !== "object" || value === null) return void 0;
46539
+ const pid = Reflect.get(value, "pid");
46540
+ return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
46541
+ } catch {
46542
+ return void 0;
46543
+ }
46544
+ }
46545
+ function processIsAlive2(pid) {
46546
+ try {
46547
+ process.kill(pid, 0);
46548
+ return true;
46549
+ } catch (error61) {
46550
+ return error61 instanceof Error && "code" in error61 && error61.code === "EPERM";
46551
+ }
46552
+ }
46553
+
46554
+ // src/agent-run.ts
46555
+ var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
46556
+ var runRefSchema = external_exports.strictObject({
46557
+ id: external_exports.string().regex(RUN_ID_PATTERN),
46558
+ swarm: external_exports.string().optional(),
46559
+ member: external_exports.string().optional(),
46560
+ parentRunId: external_exports.string().optional()
46561
+ });
46562
+
46563
+ // src/receipts.ts
46564
+ var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
46565
+ async function withReceiptJournalLock(path, operation) {
46566
+ return await withFileLock(`${path}.lock`, operation, {
46567
+ lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
46568
+ });
46569
+ }
46570
+ var durationSchema = external_exports.number().nonnegative().finite();
46571
+ var receiptSchema = external_exports.strictObject({
46572
+ id: external_exports.string().min(1),
46573
+ timestamp: external_exports.iso.datetime(),
46574
+ run: runRefSchema.optional(),
46575
+ kind: external_exports.literal("transfer").optional(),
46576
+ wallet: walletNameSchema.optional(),
46577
+ resourceUrl: external_exports.url(),
46578
+ method: external_exports.string().min(1).optional(),
46579
+ source: external_exports.string().min(1).optional(),
46580
+ provenance: external_exports.array(
46581
+ external_exports.strictObject({
46582
+ source: external_exports.string().min(1),
46583
+ sourceUrl: external_exports.string().optional(),
46584
+ ref: external_exports.string().optional()
46585
+ })
46586
+ ).optional(),
46587
+ quote: external_exports.strictObject({
46588
+ network: external_exports.string(),
46589
+ asset: external_exports.string().optional(),
46590
+ amountAtomic: external_exports.string().regex(/^\d+$/),
46591
+ payTo: external_exports.string().optional()
46592
+ }).optional(),
46593
+ payer: external_exports.string().optional(),
46594
+ paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
46595
+ authorization: external_exports.strictObject({
46596
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
46597
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
46598
+ validBefore: external_exports.string().regex(/^\d+$/)
46599
+ }).optional(),
46600
+ transfer: external_exports.strictObject({
46601
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
46602
+ toName: external_exports.string().min(1),
46603
+ toKind: external_exports.enum(["owner", "account"]),
46604
+ amountAtomic: external_exports.string().regex(/^\d+$/),
46605
+ network: external_exports.string().min(1),
46606
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
46607
+ status: external_exports.enum(["sent", "unknown", "failed"]),
46608
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
46609
+ replayed: external_exports.boolean(),
46610
+ reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
46611
+ request: external_exports.strictObject({
46612
+ authorization: external_exports.strictObject({
46613
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
46614
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
46615
+ value: external_exports.string().regex(/^\d+$/),
46616
+ validAfter: external_exports.string().regex(/^\d+$/),
46617
+ validBefore: external_exports.string().regex(/^\d+$/),
46618
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
46619
+ }),
46620
+ signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
46621
+ }).optional()
46622
+ }).optional(),
46623
+ settlement: external_exports.strictObject({
46624
+ outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
46625
+ transaction: external_exports.string().optional(),
46626
+ explorerUrl: external_exports.url().optional(),
46627
+ evidence: external_exports.unknown().optional()
46628
+ }).optional(),
46629
+ latencyMs: external_exports.number().nonnegative().finite().optional(),
46630
+ status: external_exports.number().int().min(100).max(599).optional(),
46631
+ error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
46632
+ phases: external_exports.strictObject({
46633
+ discoverMs: durationSchema.optional(),
46634
+ quoteMs: durationSchema.optional(),
46635
+ signMs: durationSchema.optional(),
46636
+ requestMs: durationSchema.optional(),
46637
+ settleMs: durationSchema.optional()
46638
+ }).optional(),
46639
+ listing: external_exports.strictObject({
46640
+ name: external_exports.string().min(1).optional(),
46641
+ providerHost: external_exports.string().min(1).optional(),
46642
+ source: external_exports.string().min(1)
46643
+ }).optional(),
46644
+ retry: external_exports.number().int().nonnegative().optional(),
46645
+ policy: external_exports.strictObject({
46646
+ maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
46647
+ capsApplied: external_exports.boolean()
46648
+ }).optional(),
46649
+ client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
46650
+ outcome: external_exports.enum([
46651
+ "paid",
46652
+ "signed_in",
46653
+ "declined_policy",
46654
+ "failed_request",
46655
+ "settlement_rejected",
46656
+ "settlement_unknown"
46657
+ ]).optional()
46658
+ });
46659
+ function parseReceipt(value) {
46660
+ const receipt = receiptSchema.parse(value);
46661
+ const transaction = receipt.settlement?.transaction;
46662
+ const network = receipt.quote?.network;
46663
+ const explorerUrl = transaction === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction);
46664
+ if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
46665
+ return receipt;
46666
+ }
46667
+ return {
46668
+ ...receipt,
46669
+ settlement: {
46670
+ outcome: receipt.settlement.outcome,
46671
+ ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
46672
+ explorerUrl,
46673
+ ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
46674
+ }
46675
+ };
46676
+ }
46677
+ function receiptWallet(receipt) {
46678
+ return receipt.wallet ?? DEFAULT_WALLET_NAME;
46679
+ }
46680
+
46681
+ // src/movement-open.ts
46682
+ function isOpenMovementLeg(leg, journalEvidence) {
46683
+ if (leg.status === "sent" || leg.status === "cancelled") return false;
46684
+ if (leg.restored === true) return true;
46685
+ if (leg.status === "planned" || leg.status === "unknown") return true;
46686
+ if (leg.status !== "failed") return false;
46687
+ if (leg.retryable === true) return true;
46688
+ return journalEvidence === "signed";
46689
+ }
46690
+
46691
+ // src/transfer-journal.ts
46692
+ import { readFile as readFile5 } from "node:fs/promises";
46693
+ async function readTransferJournal(home, from, nonce) {
46694
+ let raw;
46695
+ try {
46696
+ raw = await readFile5(getVapiPaths(home).receipts, "utf8");
46697
+ } catch (error61) {
46698
+ if (isMissingFile(error61)) return { signed: false };
46699
+ throw error61;
46700
+ }
46701
+ let latest;
46702
+ let request;
46703
+ for (const [index, line] of raw.split("\n").entries()) {
46704
+ if (!line.trim()) continue;
46705
+ let receipt;
46706
+ try {
46707
+ receipt = parseReceipt(JSON.parse(line));
46708
+ } catch (error61) {
46709
+ throw new Error(`Invalid receipt on JSONL line ${index + 1}.`, { cause: error61 });
46710
+ }
46711
+ if (receiptWallet(receipt) !== from || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
46712
+ continue;
46713
+ }
46714
+ latest = receipt;
46715
+ if (receipt.transfer.request !== void 0) request = receipt;
46716
+ }
46717
+ return {
46718
+ signed: latest !== void 0,
46719
+ ...latest === void 0 ? {} : { latest },
46720
+ ...request === void 0 ? {} : { request },
46721
+ ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
46722
+ ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
46723
+ };
46724
+ }
45823
46725
 
45824
46726
  // src/vault.ts
45825
- import { randomBytes as randomBytes3 } from "node:crypto";
45826
- import { mkdir, open as open2, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
45827
- import { dirname } from "node:path";
46727
+ import { randomBytes as randomBytes5 } from "node:crypto";
46728
+ import { mkdir as mkdir5, open as open4, readFile as readFile6, rename as rename4, rm, stat as stat4, unlink as unlink4, writeFile as writeFile3 } from "node:fs/promises";
46729
+ import { dirname as dirname3 } from "node:path";
45828
46730
  var VaultError = class extends Error {
45829
46731
  code;
45830
46732
  constructor(code, message, options) {
@@ -46369,9 +47271,9 @@ async function readVaultFile(path, key) {
46369
47271
  async function readVaultFileUnlocked(path) {
46370
47272
  let raw;
46371
47273
  try {
46372
- raw = await readFile(path, "utf8");
47274
+ raw = await readFile6(path, "utf8");
46373
47275
  } catch (error61) {
46374
- if (isMissingFile(error61)) {
47276
+ if (isMissingFile2(error61)) {
46375
47277
  throw new VaultError("not_found", "No vault file was found at the requested path.", {
46376
47278
  cause: error61
46377
47279
  });
@@ -46382,9 +47284,9 @@ async function readVaultFileUnlocked(path) {
46382
47284
  }
46383
47285
  async function refuseExistingVault(path) {
46384
47286
  try {
46385
- await stat(path);
47287
+ await stat4(path);
46386
47288
  } catch (error61) {
46387
- if (isMissingFile(error61)) return;
47289
+ if (isMissingFile2(error61)) return;
46388
47290
  throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
46389
47291
  cause: error61
46390
47292
  });
@@ -46392,29 +47294,29 @@ async function refuseExistingVault(path) {
46392
47294
  throw new VaultError("corrupt", "A vault already exists at the requested path.");
46393
47295
  }
46394
47296
  async function writeVaultFile(path, file2) {
46395
- await mkdir(dirname(path), { recursive: true, mode: 448 });
46396
- const temporaryPath = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}.tmp`;
47297
+ await mkdir5(dirname3(path), { recursive: true, mode: 448 });
47298
+ const temporaryPath = `${path}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
46397
47299
  try {
46398
- await writeFile(temporaryPath, `${JSON.stringify(file2, null, 2)}
47300
+ await writeFile3(temporaryPath, `${JSON.stringify(file2, null, 2)}
46399
47301
  `, {
46400
47302
  encoding: "utf8",
46401
47303
  mode: 384,
46402
47304
  flag: "wx"
46403
47305
  });
46404
- await rename(temporaryPath, path);
47306
+ await rename4(temporaryPath, path);
46405
47307
  } catch (error61) {
46406
47308
  await rm(temporaryPath, { force: true }).catch(() => void 0);
46407
47309
  throw error61;
46408
47310
  }
46409
47311
  }
46410
47312
  async function withVaultLock(path, operation) {
46411
- await mkdir(dirname(path), { recursive: true, mode: 448 });
47313
+ await mkdir5(dirname3(path), { recursive: true, mode: 448 });
46412
47314
  const lockPath = `${path}.lock`;
46413
47315
  const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
46414
47316
  let handle;
46415
47317
  while (!handle) {
46416
47318
  try {
46417
- handle = await open2(lockPath, "wx", 384);
47319
+ handle = await open4(lockPath, "wx", 384);
46418
47320
  } catch (error61) {
46419
47321
  if (!isExistingFile(error61)) throw error61;
46420
47322
  await removeStaleVaultLock(lockPath);
@@ -46428,18 +47330,18 @@ async function withVaultLock(path, operation) {
46428
47330
  return await operation();
46429
47331
  } finally {
46430
47332
  await handle.close();
46431
- await unlink(lockPath).catch(() => void 0);
47333
+ await unlink4(lockPath).catch(() => void 0);
46432
47334
  }
46433
47335
  }
46434
47336
  async function removeStaleVaultLock(path) {
46435
47337
  try {
46436
- const metadata = await stat(path);
46437
- if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink(path);
47338
+ const metadata = await stat4(path);
47339
+ if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
46438
47340
  } catch (error61) {
46439
- if (!isMissingFile(error61)) throw error61;
47341
+ if (!isMissingFile2(error61)) throw error61;
46440
47342
  }
46441
47343
  }
46442
- function isMissingFile(error61) {
47344
+ function isMissingFile2(error61) {
46443
47345
  return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
46444
47346
  }
46445
47347
  function isExistingFile(error61) {
@@ -46465,6 +47367,7 @@ var routerRefillSchema = external_exports.object({
46465
47367
  });
46466
47368
  var ceilingSweepPendingSchema = external_exports.strictObject({
46467
47369
  owner: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
47370
+ target: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/).optional(),
46468
47371
  amountAtomic: external_exports.string().regex(/^\d+$/),
46469
47372
  nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
46470
47373
  createdAt: external_exports.iso.datetime(),
@@ -46488,6 +47391,426 @@ var walletRegistrySchema = external_exports.object({
46488
47391
  wallets: external_exports.record(walletNameSchema, walletEntrySchema)
46489
47392
  });
46490
47393
 
47394
+ // src/movement.ts
47395
+ var movementIdSchema = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/);
47396
+ var nonceSchema = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/);
47397
+ var amountSchema = external_exports.string().regex(/^\d+\.\d{2}$/);
47398
+ var movementReasonSchema = external_exports.enum([
47399
+ "distribute",
47400
+ "allocate",
47401
+ "rebalance",
47402
+ "delegate",
47403
+ "sweep",
47404
+ "send"
47405
+ ]);
47406
+ var movementPurposeSchema = external_exports.enum(["send", "sweep"]);
47407
+ var movementAddressSchema = external_exports.string().refine((value) => isAddress(value, { strict: false }));
47408
+ var movementLegSchema = external_exports.strictObject({
47409
+ from: walletNameSchema,
47410
+ to: external_exports.string().trim().min(1),
47411
+ fromAddress: movementAddressSchema.optional(),
47412
+ toAddress: movementAddressSchema.optional(),
47413
+ amountUsd: amountSchema,
47414
+ purpose: movementPurposeSchema,
47415
+ nonce: nonceSchema,
47416
+ status: external_exports.enum(["planned", "sent", "failed", "unknown", "cancelled"]),
47417
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).optional(),
47418
+ reason: external_exports.string().min(1).optional(),
47419
+ retryable: external_exports.boolean().optional(),
47420
+ restored: external_exports.literal(true).optional(),
47421
+ addressBindingSource: external_exports.enum(["journal", "terminal-review"]).optional()
47422
+ });
47423
+ var movementSchema = external_exports.strictObject({
47424
+ v: external_exports.literal(2),
47425
+ id: movementIdSchema,
47426
+ reason: movementReasonSchema,
47427
+ from: walletNameSchema,
47428
+ // The only account a `sweep` leg may name besides the owner. Sweeps skip the
47429
+ // spend caps, so the parent comes from the plan, never from a leg's `to`.
47430
+ treasury: walletNameSchema.optional(),
47431
+ network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
47432
+ createdAt: external_exports.iso.datetime(),
47433
+ legs: external_exports.array(movementLegSchema).min(1)
47434
+ });
47435
+ var legacyMovementSchema = external_exports.strictObject({
47436
+ v: external_exports.literal(1),
47437
+ id: movementIdSchema,
47438
+ reason: external_exports.literal("distribute"),
47439
+ from: walletNameSchema,
47440
+ network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
47441
+ createdAt: external_exports.iso.datetime(),
47442
+ legs: external_exports.array(
47443
+ external_exports.strictObject({
47444
+ to: external_exports.string().trim().min(1),
47445
+ amountUsd: amountSchema,
47446
+ nonce: nonceSchema,
47447
+ status: external_exports.enum(["planned", "sent", "failed", "unknown"]),
47448
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).optional(),
47449
+ reason: external_exports.string().min(1).optional(),
47450
+ retryable: external_exports.boolean().optional()
47451
+ })
47452
+ ).min(1)
47453
+ });
47454
+ var MovementError = class extends Error {
47455
+ constructor(code, message, movementId) {
47456
+ super(message);
47457
+ this.code = code;
47458
+ this.movementId = movementId;
47459
+ this.name = "MovementError";
47460
+ }
47461
+ code;
47462
+ movementId;
47463
+ };
47464
+ async function listUnfinishedMovementSnapshots(options) {
47465
+ const directory = movementsDirectory(options.home);
47466
+ let names;
47467
+ try {
47468
+ names = await readdir3(directory);
47469
+ } catch (error61) {
47470
+ if (isMissingFile(error61)) return [];
47471
+ throw error61;
47472
+ }
47473
+ const snapshots = [];
47474
+ for (const name of names.filter((candidate) => candidate.endsWith(".json")).sort()) {
47475
+ const movement = parseMovement(JSON.parse(await readFile7(join6(directory, name), "utf8")));
47476
+ if (options.from !== void 0 && !movement.legs.some((leg) => leg.from === options.from)) {
47477
+ continue;
47478
+ }
47479
+ const pendingLegs = movement.legs.filter((leg) => leg.status === "planned").length;
47480
+ const unknownLegs = movement.legs.filter((leg) => leg.status === "unknown").length;
47481
+ const evidence = await movementOpenEvidence(options.home, movement, options.from);
47482
+ if (!evidence.open) continue;
47483
+ snapshots.push({
47484
+ movement,
47485
+ summary: {
47486
+ id: movement.id,
47487
+ from: movement.from,
47488
+ network: movement.network,
47489
+ createdAt: movement.createdAt,
47490
+ pendingLegs,
47491
+ unknownLegs
47492
+ },
47493
+ signedFailedLegKeys: evidence.signedFailedLegKeys
47494
+ });
47495
+ }
47496
+ return snapshots.sort(
47497
+ (left, right) => left.summary.createdAt.localeCompare(right.summary.createdAt) || left.summary.id.localeCompare(right.summary.id)
47498
+ );
47499
+ }
47500
+ async function movementOpenEvidence(home, movement, from) {
47501
+ let open6 = false;
47502
+ const signedFailedLegKeys = [];
47503
+ for (const leg of movement.legs) {
47504
+ if (from !== void 0 && leg.from !== from) continue;
47505
+ if (isOpenMovementLeg(leg, "unsigned")) open6 = true;
47506
+ if (leg.status !== "failed") continue;
47507
+ const journal = await readTransferJournal(home, leg.from, leg.nonce);
47508
+ if (journal.signed) signedFailedLegKeys.push(movementTransferKey(leg.from, leg.nonce));
47509
+ if (isOpenMovementLeg(leg, journal.signed ? "signed" : "unsigned")) open6 = true;
47510
+ }
47511
+ return { open: open6, signedFailedLegKeys };
47512
+ }
47513
+ async function readMovement(home, id) {
47514
+ const safeId = parseMovementId(id);
47515
+ try {
47516
+ return parseMovement(
47517
+ JSON.parse(await readFile7(join6(movementsDirectory(home), `${safeId}.json`), "utf8"))
47518
+ );
47519
+ } catch (error61) {
47520
+ if (isMissingFile(error61)) {
47521
+ throw new MovementError(
47522
+ "movement_not_found",
47523
+ `No movement named ${safeId} was found.`,
47524
+ safeId
47525
+ );
47526
+ }
47527
+ throw error61;
47528
+ }
47529
+ }
47530
+ function movementTransferKey(from, nonce) {
47531
+ return `${from}\0${nonce.toLowerCase()}`;
47532
+ }
47533
+ async function reconcileSignedLegs(home, id, signedKeys) {
47534
+ const initial = await readMovement(home, id);
47535
+ return await withMovementLocks(home, movementSenders(initial), void 0, async () => {
47536
+ const movement = await readMovement(home, id);
47537
+ const reconciled = movementWithSignedLegsUnknown(movement, signedKeys);
47538
+ if (reconciled !== movement) await writeMovement(home, reconciled);
47539
+ return reconciled;
47540
+ });
47541
+ }
47542
+ async function markOpenLegsRestored(home, id) {
47543
+ let initial;
47544
+ try {
47545
+ initial = await readMovement(home, id);
47546
+ } catch (error61) {
47547
+ if (error61 instanceof MovementError && error61.code === "movement_not_found" || error61 instanceof SyntaxError || error61 instanceof external_exports.ZodError) {
47548
+ return void 0;
47549
+ }
47550
+ throw error61;
47551
+ }
47552
+ return await withMovementLocks(home, movementSenders(initial), void 0, async () => {
47553
+ const movement = await readMovement(home, id);
47554
+ let changed = false;
47555
+ const legs = movement.legs.map((leg) => {
47556
+ if (leg.status === "sent" || leg.status === "cancelled" || leg.restored === true) return leg;
47557
+ changed = true;
47558
+ return { ...leg, restored: true };
47559
+ });
47560
+ if (!changed) return movement;
47561
+ const restored = movementSchema.parse({ ...movement, legs });
47562
+ await writeMovement(home, restored);
47563
+ return restored;
47564
+ });
47565
+ }
47566
+ function unknownLeg(leg) {
47567
+ return {
47568
+ from: leg.from,
47569
+ to: leg.to,
47570
+ ...legAddressBinding(leg),
47571
+ amountUsd: leg.amountUsd,
47572
+ purpose: leg.purpose,
47573
+ nonce: leg.nonce,
47574
+ status: "unknown",
47575
+ ...restoredMarker(leg)
47576
+ };
47577
+ }
47578
+ function restoredMarker(leg) {
47579
+ return leg.restored === true ? { restored: true } : {};
47580
+ }
47581
+ function legAddressBinding(leg) {
47582
+ return {
47583
+ ...leg.fromAddress === void 0 ? {} : { fromAddress: leg.fromAddress },
47584
+ ...leg.toAddress === void 0 ? {} : { toAddress: leg.toAddress },
47585
+ ...leg.addressBindingSource === void 0 ? {} : { addressBindingSource: leg.addressBindingSource }
47586
+ };
47587
+ }
47588
+ function isExpiredRestoredReview(leg) {
47589
+ return leg.restored === true && leg.reason === "restored_nonce_expired";
47590
+ }
47591
+ function movementWithSignedLegsUnknown(movement, signedKeys) {
47592
+ let changed = false;
47593
+ const legs = movement.legs.map((leg) => {
47594
+ if (isExpiredRestoredReview(leg)) return leg;
47595
+ if (leg.status === "sent" || leg.status === "cancelled" || !signedKeys.has(movementTransferKey(leg.from, leg.nonce)) || leg.status === "unknown" && leg.txHash === void 0 && leg.reason === void 0 && leg.retryable === void 0) {
47596
+ return leg;
47597
+ }
47598
+ changed = true;
47599
+ return unknownLeg(leg);
47600
+ });
47601
+ return changed ? movementSchema.parse({ ...movement, legs }) : movement;
47602
+ }
47603
+ function parseMovement(value) {
47604
+ const current = movementSchema.safeParse(value);
47605
+ if (current.success) return current.data;
47606
+ const legacy = legacyMovementSchema.parse(value);
47607
+ return movementSchema.parse({
47608
+ ...legacy,
47609
+ v: 2,
47610
+ legs: legacy.legs.map((leg) => ({
47611
+ ...leg,
47612
+ from: legacy.from,
47613
+ purpose: "send"
47614
+ }))
47615
+ });
47616
+ }
47617
+ function movementSenders(movement) {
47618
+ return sortedUniqueSenders(movement.legs.map((leg) => leg.from));
47619
+ }
47620
+ function sortedUniqueSenders(senders) {
47621
+ return [...new Set(senders)].sort();
47622
+ }
47623
+ function parseMovementId(value) {
47624
+ const parsed = movementIdSchema.safeParse(value);
47625
+ if (!parsed.success) throw new MovementError("invalid_movement", "The movement id is invalid.");
47626
+ return parsed.data;
47627
+ }
47628
+ function movementsDirectory(home) {
47629
+ return join6(home, "movements");
47630
+ }
47631
+ async function writeMovement(home, movement) {
47632
+ const parsed = movementSchema.parse(movement);
47633
+ const directory = movementsDirectory(home);
47634
+ await mkdir6(directory, { recursive: true, mode: 448 });
47635
+ await chmod(directory, 448);
47636
+ const path = join6(directory, `${parsed.id}.json`);
47637
+ const temporary = join6(
47638
+ directory,
47639
+ `.${parsed.id}.${process.pid}.${randomBytes6(6).toString("hex")}.tmp`
47640
+ );
47641
+ let handle;
47642
+ try {
47643
+ handle = await open5(temporary, "wx", 384);
47644
+ await handle.writeFile(serializeMovement(parsed), "utf8");
47645
+ await handle.sync();
47646
+ await handle.close();
47647
+ handle = void 0;
47648
+ await rename5(temporary, path);
47649
+ const directoryHandle = await open5(directory, "r");
47650
+ try {
47651
+ await directoryHandle.sync();
47652
+ } finally {
47653
+ await directoryHandle.close();
47654
+ }
47655
+ } catch (error61) {
47656
+ await handle?.close().catch(() => void 0);
47657
+ await unlink5(temporary).catch(() => void 0);
47658
+ throw error61;
47659
+ }
47660
+ }
47661
+ function serializeMovement(movement) {
47662
+ return `${JSON.stringify(movementSchema.parse(movement), null, 2)}
47663
+ `;
47664
+ }
47665
+ async function withMovementLock(home, from, timeoutMs, operation) {
47666
+ try {
47667
+ return await withAccountMovementLocks(home, [from], timeoutMs, operation);
47668
+ } catch (error61) {
47669
+ if (error61 instanceof AccountMovementLockedError) {
47670
+ throw new MovementError(
47671
+ "movement_locked",
47672
+ `Another movement is already running for account ${from}.`
47673
+ );
47674
+ }
47675
+ throw error61;
47676
+ }
47677
+ }
47678
+ async function withMovementLocks(home, senders, timeoutMs, operation) {
47679
+ const [sender, ...remaining] = senders;
47680
+ if (sender === void 0) return await operation();
47681
+ return await withMovementLock(
47682
+ home,
47683
+ sender,
47684
+ timeoutMs,
47685
+ async () => withMovementLocks(home, remaining, timeoutMs, operation)
47686
+ );
47687
+ }
47688
+
47689
+ // src/swarm.ts
47690
+ import { readdir as readdir4, readFile as readFile8, stat as stat5, unlink as unlink6 } from "node:fs/promises";
47691
+ import { join as join7 } from "node:path";
47692
+ var SWARM_NAME_PATTERN = /^[a-z][a-z0-9-]{0,15}$/;
47693
+ var SWARM_ROLE_PATTERN = /^[a-z][a-z0-9]{0,7}$/;
47694
+ var atomicSchema = external_exports.string().regex(/^\d+$/);
47695
+ var addressSchema2 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/);
47696
+ var capsSchema = external_exports.strictObject({ perCallAtomic: atomicSchema, perDayAtomic: atomicSchema });
47697
+ var movementIdSchema2 = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/u);
47698
+ var amountUsdSchema = external_exports.string().regex(/^\d+\.\d{2}$/u);
47699
+ var setupFundingStatusSchema = external_exports.enum(["planned", "sent", "incomplete"]);
47700
+ var blockedFundingLegSchema = external_exports.strictObject({
47701
+ to: external_exports.string().trim().min(1),
47702
+ amountUsd: amountUsdSchema,
47703
+ reason: external_exports.string().trim().min(1)
47704
+ });
47705
+ var setupFundingSchema = external_exports.strictObject({
47706
+ amountUsd: amountUsdSchema,
47707
+ from: walletNameSchema,
47708
+ movementId: movementIdSchema2.optional(),
47709
+ status: setupFundingStatusSchema,
47710
+ policy: external_exports.strictObject({
47711
+ strategy: external_exports.enum(["targets", "even", "weights"]),
47712
+ movementId: movementIdSchema2.optional(),
47713
+ status: setupFundingStatusSchema,
47714
+ blocked: external_exports.array(blockedFundingLegSchema).optional()
47715
+ }).optional()
47716
+ });
47717
+ var accountSteps = {
47718
+ creating: external_exports.boolean().default(false),
47719
+ created: external_exports.boolean(),
47720
+ capped: external_exports.boolean(),
47721
+ linked: external_exports.boolean()
47722
+ };
47723
+ var treasurySchema = external_exports.strictObject({
47724
+ account: walletNameSchema,
47725
+ // A planned account has no address until its vault derivation succeeds.
47726
+ address: addressSchema2.optional(),
47727
+ steps: external_exports.strictObject(accountSteps)
47728
+ }).refine(
47729
+ (value) => !value.steps.created || value.address !== void 0,
47730
+ "Created accounts require an address."
47731
+ );
47732
+ var memberSchema = external_exports.strictObject({
47733
+ account: walletNameSchema,
47734
+ address: addressSchema2.optional(),
47735
+ role: external_exports.string().regex(SWARM_ROLE_PATTERN),
47736
+ weight: external_exports.number().int().positive(),
47737
+ targetAtomic: atomicSchema,
47738
+ ceilingAtomic: atomicSchema.nullable(),
47739
+ steps: external_exports.strictObject({ ...accountSteps, profiled: external_exports.boolean() })
47740
+ }).refine(
47741
+ (value) => !value.steps.created || value.address !== void 0,
47742
+ "Created accounts require an address."
47743
+ );
47744
+ var swarmFileSchema = external_exports.strictObject({
47745
+ v: external_exports.literal(1),
47746
+ name: external_exports.string().regex(SWARM_NAME_PATTERN),
47747
+ device: external_exports.string().regex(DEVICE_NAME_PATTERN),
47748
+ network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
47749
+ createdAt: external_exports.iso.datetime(),
47750
+ treasury: treasurySchema,
47751
+ members: external_exports.array(memberSchema),
47752
+ setupFunding: setupFundingSchema.optional(),
47753
+ policy: external_exports.strictObject({
47754
+ strategy: external_exports.enum(["targets", "even", "weights"]),
47755
+ treasuryCaps: capsSchema
47756
+ })
47757
+ }).refine(
47758
+ (value) => (/* @__PURE__ */ new Set([value.treasury.account, ...value.members.map((member) => member.account)])).size === value.members.length + 1,
47759
+ "Swarm accounts must be unique."
47760
+ );
47761
+ var SwarmError = class extends Error {
47762
+ constructor(code, message) {
47763
+ super(message);
47764
+ this.code = code;
47765
+ this.name = "SwarmError";
47766
+ }
47767
+ code;
47768
+ };
47769
+ function swarmsDirectory(home) {
47770
+ return join7(home, "swarms");
47771
+ }
47772
+ function swarmFilePath(home, name) {
47773
+ assertName(name);
47774
+ return join7(swarmsDirectory(home), `${name}.json`);
47775
+ }
47776
+ async function readSwarm(home, name) {
47777
+ const path = swarmFilePath(home, name);
47778
+ try {
47779
+ const swarm = parseSwarm(JSON.parse(await readFile8(path, "utf8")));
47780
+ if (swarm.name !== name)
47781
+ throw new SwarmError("invalid_swarm", "Swarm name does not match its file.");
47782
+ return swarm;
47783
+ } catch (error61) {
47784
+ if (isMissingFile(error61)) throw new SwarmError("swarm_not_found", `No swarm named ${name}.`);
47785
+ if (error61 instanceof SwarmError) throw error61;
47786
+ throw new SwarmError("invalid_swarm", `Invalid swarm file for ${name}.`);
47787
+ }
47788
+ }
47789
+ async function listSwarms(home) {
47790
+ let files;
47791
+ try {
47792
+ files = await readdir4(swarmsDirectory(home));
47793
+ } catch (error61) {
47794
+ if (isMissingFile(error61)) return [];
47795
+ throw error61;
47796
+ }
47797
+ return await Promise.all(
47798
+ files.filter((file2) => file2.endsWith(".json")).sort().map((file2) => readSwarm(home, file2.slice(0, -5)))
47799
+ );
47800
+ }
47801
+ function parseSwarm(value) {
47802
+ const result = swarmFileSchema.safeParse(value);
47803
+ if (!result.success) throw new SwarmError("invalid_swarm", "Invalid swarm state.");
47804
+ return result.data;
47805
+ }
47806
+ function assertName(name) {
47807
+ if (!SWARM_NAME_PATTERN.test(name))
47808
+ throw new SwarmError(
47809
+ "invalid_swarm",
47810
+ "A swarm name must be 1 to 16 lowercase letters, digits or dashes, starting with a letter."
47811
+ );
47812
+ }
47813
+
46491
47814
  // src/backup.ts
46492
47815
  var ERROR_MESSAGES = {
46493
47816
  backup_too_large: "Backup envelope exceeds 65,536 bytes.",
@@ -46496,6 +47819,7 @@ var ERROR_MESSAGES = {
46496
47819
  unsupported_signature: "Unsupported signature.",
46497
47820
  weak_password: "Password must contain at least 12 characters.",
46498
47821
  backup_invalid_input: "Invalid backup input.",
47822
+ backup_snapshot_busy: "Backup files changed while they were being captured. Retry the backup; no backup was created or uploaded.",
46499
47823
  relay_open_failed: "Unable to open relay payload.",
46500
47824
  relay_invalid_key: "Invalid relay key.",
46501
47825
  vault_exists: "A vault already exists."
@@ -46517,6 +47841,15 @@ var SCRYPT_N2 = 131072;
46517
47841
  var SCRYPT_R2 = 8;
46518
47842
  var SCRYPT_P2 = 1;
46519
47843
  var SCRYPT_MAXMEM = 256 * 1024 * 1024;
47844
+ var RESTORE_MARKER_FILE = ".backup-restore.json";
47845
+ var restoreDigestSchema = external_exports.string().regex(/^[0-9a-f]{64}$/u);
47846
+ var restoreMarkerSchema = external_exports.strictObject({
47847
+ v: external_exports.literal(1),
47848
+ fingerprint: restoreDigestSchema,
47849
+ vaultSha256: restoreDigestSchema,
47850
+ registrySha256: restoreDigestSchema,
47851
+ mac: restoreDigestSchema
47852
+ });
46520
47853
  var SECP256K1_ORDER = BigInt(
46521
47854
  "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"
46522
47855
  );
@@ -46537,7 +47870,7 @@ var X25519_PRIVATE_DER_PREFIX = Buffer.from("302e020100300506032b656e04220420",
46537
47870
  var X25519_PUBLIC_DER_PREFIX = Buffer.from("302a300506032b656e032100", "hex");
46538
47871
  var CROCKFORD_BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
46539
47872
  var isoUtcMillisecondsSchema = external_exports.string().refine(isIsoUtcMilliseconds);
46540
- var addressSchema2 = external_exports.custom(
47873
+ var addressSchema3 = external_exports.custom(
46541
47874
  (value) => typeof value === "string" && ADDRESS_PATTERN2.test(value)
46542
47875
  );
46543
47876
  var privateKeySchema = external_exports.custom(
@@ -46546,7 +47879,7 @@ var privateKeySchema = external_exports.custom(
46546
47879
  var safeNonnegativeIntegerSchema = external_exports.number().int().nonnegative().refine(Number.isSafeInteger);
46547
47880
  var accountFields2 = {
46548
47881
  name: walletNameSchema,
46549
- address: addressSchema2,
47882
+ address: addressSchema3,
46550
47883
  createdAt: isoUtcMillisecondsSchema
46551
47884
  };
46552
47885
  var backupAccountSchema = external_exports.discriminatedUnion("kind", [
@@ -46570,26 +47903,189 @@ var backupRegistryAccountSchema = external_exports.object({
46570
47903
  label: external_exports.string().optional(),
46571
47904
  spendCaps: spendCapsSchema.strict()
46572
47905
  }).strict();
46573
- var backupRegistrySchema = external_exports.object({
47906
+ var backupRegistryV1Schema = external_exports.object({
46574
47907
  default: walletNameSchema.optional(),
46575
47908
  accounts: external_exports.array(backupRegistryAccountSchema),
46576
47909
  networks: external_exports.array(external_exports.string().regex(CAIP2_PATTERN))
46577
47910
  }).strict();
46578
- var backupSourceSchema = external_exports.object({
47911
+ var routerRefillSchema2 = external_exports.strictObject({
47912
+ belowUsd: external_exports.number().finite().min(0),
47913
+ tierUsd: external_exports.union([external_exports.literal(1), external_exports.literal(5), external_exports.literal(20), external_exports.literal(50)])
47914
+ });
47915
+ var backupRegistryAccountV2Schema = external_exports.strictObject({
47916
+ name: walletNameSchema,
47917
+ label: external_exports.string().optional(),
47918
+ spendCaps: spendCapsSchema.strict(),
47919
+ ceilingAtomic: external_exports.string().regex(/^\d+$/u).nullable().optional(),
47920
+ routerRefill: routerRefillSchema2.optional()
47921
+ });
47922
+ var backupRegistryV2Schema = external_exports.strictObject({
47923
+ default: walletNameSchema.optional(),
47924
+ accounts: external_exports.array(backupRegistryAccountV2Schema),
47925
+ networks: external_exports.array(external_exports.string().regex(CAIP2_PATTERN))
47926
+ });
47927
+ var backupAgentProfileSchema = external_exports.strictObject({
47928
+ version: external_exports.literal(1),
47929
+ name: walletNameSchema,
47930
+ wallet: external_exports.string(),
47931
+ model: external_exports.string().min(1),
47932
+ instructions: external_exports.string().max(2e4),
47933
+ verifiedOnly: external_exports.boolean(),
47934
+ approveAboveUsd: external_exports.number().min(0),
47935
+ maxSteps: external_exports.number().int().min(1).max(50),
47936
+ paused: external_exports.boolean(),
47937
+ createdAt: external_exports.string(),
47938
+ tools: external_exports.array(external_exports.string().min(1)),
47939
+ grants: external_exports.array(external_exports.enum(["read", "delegate", "allocate"])).min(1).optional()
47940
+ });
47941
+ var movementIdSchema3 = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/u);
47942
+ var movementNonceSchema = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u);
47943
+ var movementAmountSchema = external_exports.string().regex(/^\d+\.\d{2}$/u);
47944
+ var movementStatusSchema = external_exports.enum(["planned", "sent", "failed", "unknown"]);
47945
+ var movementV2StatusSchema = external_exports.enum(["planned", "sent", "failed", "unknown", "cancelled"]);
47946
+ var movementOptionalFields = {
47947
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/u).optional(),
47948
+ reason: external_exports.string().min(1).optional(),
47949
+ retryable: external_exports.boolean().optional()
47950
+ };
47951
+ var backupMovementV1Schema = external_exports.strictObject({
47952
+ v: external_exports.literal(1),
47953
+ id: movementIdSchema3,
47954
+ reason: external_exports.literal("distribute"),
47955
+ from: walletNameSchema,
47956
+ network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
47957
+ createdAt: external_exports.iso.datetime(),
47958
+ legs: external_exports.array(
47959
+ external_exports.strictObject({
47960
+ to: external_exports.string().trim().min(1),
47961
+ amountUsd: movementAmountSchema,
47962
+ nonce: movementNonceSchema,
47963
+ status: movementStatusSchema,
47964
+ ...movementOptionalFields
47965
+ })
47966
+ ).min(1)
47967
+ });
47968
+ var backupMovementV2Schema = external_exports.strictObject({
47969
+ v: external_exports.literal(2),
47970
+ id: movementIdSchema3,
47971
+ reason: external_exports.enum(["distribute", "allocate", "rebalance", "delegate", "sweep", "send"]),
47972
+ from: walletNameSchema,
47973
+ treasury: walletNameSchema.optional(),
47974
+ network: external_exports.enum([BASE_MAINNET_CAIP2, ARC_MAINNET_CAIP2]),
47975
+ createdAt: external_exports.iso.datetime(),
47976
+ legs: external_exports.array(
47977
+ external_exports.strictObject({
47978
+ from: walletNameSchema,
47979
+ to: external_exports.string().trim().min(1),
47980
+ amountUsd: movementAmountSchema,
47981
+ purpose: external_exports.enum(["send", "sweep"]),
47982
+ nonce: movementNonceSchema,
47983
+ status: movementV2StatusSchema,
47984
+ ...movementOptionalFields
47985
+ })
47986
+ ).min(1)
47987
+ });
47988
+ var backupMovementSchema = external_exports.discriminatedUnion("v", [
47989
+ backupMovementV1Schema,
47990
+ backupMovementV2Schema
47991
+ ]);
47992
+ var backupTransferRequestSchema = external_exports.strictObject({
47993
+ authorization: external_exports.strictObject({
47994
+ from: addressSchema3,
47995
+ to: addressSchema3,
47996
+ value: external_exports.string().regex(/^\d+$/u),
47997
+ validAfter: external_exports.string().regex(/^\d+$/u),
47998
+ validBefore: external_exports.string().regex(/^\d+$/u),
47999
+ nonce: movementNonceSchema
48000
+ }),
48001
+ signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/u)
48002
+ });
48003
+ var backupTransferSchema = external_exports.strictObject({
48004
+ to: addressSchema3,
48005
+ toName: external_exports.string().min(1),
48006
+ toKind: external_exports.enum(["owner", "account"]),
48007
+ amountAtomic: external_exports.string().regex(/^\d+$/u),
48008
+ network: external_exports.string().min(1),
48009
+ nonce: movementNonceSchema,
48010
+ status: external_exports.enum(["sent", "unknown", "failed"]),
48011
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/u).nullable(),
48012
+ replayed: external_exports.boolean(),
48013
+ reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/u).optional(),
48014
+ request: backupTransferRequestSchema.optional()
48015
+ });
48016
+ var backupTransferReceiptSchema = external_exports.strictObject({
48017
+ id: external_exports.string().min(1),
48018
+ timestamp: external_exports.iso.datetime(),
48019
+ kind: external_exports.literal("transfer"),
48020
+ wallet: walletNameSchema,
48021
+ resourceUrl: external_exports.url(),
48022
+ quote: external_exports.strictObject({
48023
+ network: external_exports.string().min(1),
48024
+ asset: external_exports.string().min(1),
48025
+ amountAtomic: external_exports.string().regex(/^\d+$/u)
48026
+ }),
48027
+ transfer: backupTransferSchema,
48028
+ error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional()
48029
+ }).superRefine((receipt, context) => {
48030
+ try {
48031
+ parseReceipt(receipt);
48032
+ } catch {
48033
+ context.addIssue({ code: "custom", message: "Invalid transfer receipt." });
48034
+ }
48035
+ });
48036
+ var backupSourceV1Schema = external_exports.object({
46579
48037
  phrase: external_exports.string().min(1),
46580
48038
  nextDerivedIndex: safeNonnegativeIntegerSchema,
46581
48039
  accounts: external_exports.array(backupAccountSchema),
46582
- registry: backupRegistrySchema,
48040
+ registry: backupRegistryV1Schema,
46583
48041
  protected: external_exports.boolean()
46584
48042
  }).strict().superRefine(validateBackupSourceRelationships);
46585
- var backupPlaintextSchema = external_exports.object({
48043
+ var backupSourceV2Schema = external_exports.strictObject({
48044
+ phrase: external_exports.string().min(1),
48045
+ nextDerivedIndex: safeNonnegativeIntegerSchema,
48046
+ accounts: external_exports.array(backupAccountSchema),
48047
+ registry: backupRegistryV2Schema,
48048
+ protected: external_exports.boolean(),
48049
+ agents: external_exports.array(backupAgentProfileSchema),
48050
+ swarms: external_exports.array(swarmFileSchema),
48051
+ movements: external_exports.array(backupMovementSchema),
48052
+ transferReceipts: external_exports.array(backupTransferReceiptSchema),
48053
+ skipped: external_exports.array(
48054
+ external_exports.strictObject({
48055
+ kind: external_exports.literal("agent"),
48056
+ name: external_exports.string().min(1),
48057
+ reason: external_exports.literal("invalid_profile")
48058
+ })
48059
+ ).optional()
48060
+ }).superRefine((source, context) => {
48061
+ validateBackupSourceRelationships(source, context);
48062
+ validateBackupV2Uniqueness(source, context);
48063
+ });
48064
+ var backupSourceSchema = external_exports.union([backupSourceV1Schema, backupSourceV2Schema]);
48065
+ var backupPlaintextV1Schema = external_exports.strictObject({
46586
48066
  v: external_exports.literal(1),
46587
48067
  phrase: external_exports.string().min(1),
46588
48068
  nextDerivedIndex: safeNonnegativeIntegerSchema,
46589
48069
  accounts: external_exports.array(backupAccountSchema),
46590
- registry: backupRegistrySchema,
48070
+ registry: backupRegistryV1Schema,
46591
48071
  protected: external_exports.boolean()
46592
- }).strict().superRefine((plaintext, context) => validateBackupSourceRelationships(plaintext, context));
48072
+ });
48073
+ var backupPlaintextV2Schema = external_exports.strictObject({
48074
+ v: external_exports.literal(2),
48075
+ phrase: external_exports.string().min(1),
48076
+ nextDerivedIndex: safeNonnegativeIntegerSchema,
48077
+ accounts: external_exports.array(backupAccountSchema),
48078
+ registry: backupRegistryV2Schema,
48079
+ protected: external_exports.boolean(),
48080
+ agents: external_exports.array(backupAgentProfileSchema).optional(),
48081
+ swarms: external_exports.array(swarmFileSchema).optional(),
48082
+ movements: external_exports.array(backupMovementSchema).optional(),
48083
+ transferReceipts: external_exports.array(backupTransferReceiptSchema).optional()
48084
+ });
48085
+ var backupPlaintextSchema = external_exports.discriminatedUnion("v", [backupPlaintextV1Schema, backupPlaintextV2Schema]).superRefine((plaintext, context) => {
48086
+ validateBackupSourceRelationships(plaintext, context);
48087
+ if (plaintext.v === 2) validateBackupV2Uniqueness(plaintext, context);
48088
+ });
46593
48089
  function VAULT_BACKUP_TYPED_DATA(owner) {
46594
48090
  const checksummedOwner = checksummedAddress(owner);
46595
48091
  return {
@@ -46711,8 +48207,8 @@ async function createBackup(options) {
46711
48207
  assertDevice(options.device);
46712
48208
  assertOwnerKey(options.ownerKey);
46713
48209
  const createdAt = readCreatedAt(options.now ?? (() => /* @__PURE__ */ new Date()));
46714
- const randomBytes4 = options.randomBytes ?? cryptoRandomBytes;
46715
- const nonce = readRandomBytes(randomBytes4, 12);
48210
+ const randomBytes7 = options.randomBytes ?? cryptoRandomBytes;
48211
+ const nonce = readRandomBytes(randomBytes7, 12);
46716
48212
  const salt = encodeBase64Url(options.ownerKey.salt);
46717
48213
  const kdf = options.ownerKey.kdf === "hkdf-sha256" ? { name: "hkdf-sha256", salt } : { name: "scrypt", salt, N: SCRYPT_N2, r: SCRYPT_R2, p: SCRYPT_P2 };
46718
48214
  const cipher = { name: CIPHER_NAME, nonce: encodeBase64Url(nonce) };
@@ -46725,30 +48221,54 @@ async function createBackup(options) {
46725
48221
  kdf,
46726
48222
  cipher
46727
48223
  };
46728
- const plaintextValue = buildPlaintext(parsed.data);
46729
- const plaintext = Buffer.from(JSON.stringify(plaintextValue), "utf8");
46730
48224
  const key = Buffer.from(options.ownerKey.key);
46731
- let encrypted;
46732
48225
  try {
46733
- encrypted = encryptAesGcm(key, nonce, plaintext, Buffer.from(buildBackupAad(header), "utf8"));
46734
- const envelope = JSON.stringify({
46735
- format: header.format,
46736
- v: header.v,
46737
- owner: header.owner,
46738
- device: header.device,
46739
- createdAt: header.createdAt,
46740
- kdf: header.kdf,
46741
- cipher: header.cipher,
46742
- ciphertext: encodeBase64Url(encrypted)
46743
- });
46744
- const bytes = Buffer.byteLength(envelope, "utf8");
46745
- if (bytes > MAX_BACKUP_BYTES) throw new BackupError("backup_too_large");
46746
- return { envelope, bytes };
48226
+ const candidates = backupCandidates(parsed.data);
48227
+ for (const candidate of candidates) {
48228
+ const plaintext = Buffer.from(JSON.stringify(candidate.plaintext), "utf8");
48229
+ let encrypted;
48230
+ try {
48231
+ encrypted = encryptAesGcm(
48232
+ key,
48233
+ nonce,
48234
+ plaintext,
48235
+ Buffer.from(buildBackupAad(header), "utf8")
48236
+ );
48237
+ const envelope = JSON.stringify({
48238
+ format: header.format,
48239
+ v: header.v,
48240
+ owner: header.owner,
48241
+ device: header.device,
48242
+ createdAt: header.createdAt,
48243
+ kdf: header.kdf,
48244
+ cipher: header.cipher,
48245
+ ciphertext: encodeBase64Url(encrypted)
48246
+ });
48247
+ const bytes = Buffer.byteLength(envelope, "utf8");
48248
+ const relayPayload = buildRelayRestorePayload({
48249
+ owner,
48250
+ device: "d".repeat(32),
48251
+ kdf,
48252
+ key: Buffer.alloc(32),
48253
+ vault: candidate.plaintext
48254
+ });
48255
+ const relayBytes = Buffer.byteLength(relayPayload, "utf8");
48256
+ if (bytes <= MAX_BACKUP_BYTES && relayBytes <= RELAY_PLAINTEXT_LIMIT) {
48257
+ return {
48258
+ envelope,
48259
+ bytes,
48260
+ ...candidate.omitted.length === 0 ? {} : { omitted: candidate.omitted }
48261
+ };
48262
+ }
48263
+ } finally {
48264
+ plaintext.fill(0);
48265
+ encrypted?.fill(0);
48266
+ }
48267
+ }
48268
+ throw new BackupError("backup_too_large");
46747
48269
  } finally {
46748
- plaintext.fill(0);
46749
48270
  key.fill(0);
46750
48271
  nonce.fill(0);
46751
- encrypted?.fill(0);
46752
48272
  }
46753
48273
  }
46754
48274
  async function openBackup(options) {
@@ -46773,7 +48293,7 @@ async function openBackup(options) {
46773
48293
  const value = JSON.parse(json2);
46774
48294
  const validated = backupPlaintextSchema.safeParse(value);
46775
48295
  if (!validated.success) throw new BackupError("backup_open_failed");
46776
- return buildPlaintext(validated.data);
48296
+ return validated.data.v === 1 ? buildPlaintextV1(validated.data) : buildPlaintextV2(validated.data);
46777
48297
  } catch {
46778
48298
  throw new BackupError("backup_open_failed");
46779
48299
  } finally {
@@ -46831,7 +48351,7 @@ function relayCode(publicKey) {
46831
48351
  }
46832
48352
  function sealTo(options) {
46833
48353
  const plaintext = relayPlaintext(options.plaintext);
46834
- const randomBytes4 = options.randomBytes ?? cryptoRandomBytes;
48354
+ const randomBytes7 = options.randomBytes ?? cryptoRandomBytes;
46835
48355
  let recipientPublicKey;
46836
48356
  let ephemeralPrivateKey;
46837
48357
  let ephemeralPublicKey;
@@ -46845,7 +48365,7 @@ function sealTo(options) {
46845
48365
  }
46846
48366
  assertRelayKey(options.recipientPublicKey);
46847
48367
  recipientPublicKey = Buffer.from(options.recipientPublicKey);
46848
- ephemeralPrivateKey = readRelayRandomBytes(randomBytes4, 32);
48368
+ ephemeralPrivateKey = readRelayRandomBytes(randomBytes7, 32);
46849
48369
  try {
46850
48370
  ephemeralPublicKey = x25519PublicFromPrivate(ephemeralPrivateKey);
46851
48371
  shared = x25519SharedSecret(ephemeralPrivateKey, recipientPublicKey);
@@ -46853,7 +48373,7 @@ function sealTo(options) {
46853
48373
  } catch {
46854
48374
  throw new BackupError("relay_invalid_key");
46855
48375
  }
46856
- nonce = readRelayRandomBytes(randomBytes4, 12);
48376
+ nonce = readRelayRandomBytes(randomBytes7, 12);
46857
48377
  const encodedPublicKey = encodeBase64Url(ephemeralPublicKey);
46858
48378
  const encodedNonce = encodeBase64Url(nonce);
46859
48379
  const salt = Buffer.concat([ephemeralPublicKey, recipientPublicKey]);
@@ -46936,6 +48456,30 @@ function openSealed(options) {
46936
48456
  plaintext?.fill(0);
46937
48457
  }
46938
48458
  }
48459
+ function buildRelayRestorePayload(options) {
48460
+ try {
48461
+ const owner = normalizedOwner(options.owner);
48462
+ assertDevice(options.device);
48463
+ assertBytes(options.key, 32);
48464
+ if (!isRecord(options.kdf)) throw new Error();
48465
+ const kdf = parseKdf(options.kdf);
48466
+ const parsed = backupPlaintextSchema.safeParse(options.vault);
48467
+ if (!parsed.success) throw new Error();
48468
+ const vault = parsed.data.v === 1 ? buildPlaintextV1(parsed.data) : buildPlaintextV2(parsed.data);
48469
+ return JSON.stringify({
48470
+ format: "vapi-vault-relay-payload",
48471
+ v: 1,
48472
+ purpose: "restore",
48473
+ owner,
48474
+ device: options.device,
48475
+ kdf,
48476
+ key: encodeBase64Url(options.key),
48477
+ vault
48478
+ });
48479
+ } catch {
48480
+ throw new BackupError("backup_invalid_input");
48481
+ }
48482
+ }
46939
48483
  async function exportBackupSource(options) {
46940
48484
  try {
46941
48485
  assertBytes(options.vaultKey, 32);
@@ -46943,62 +48487,142 @@ async function exportBackupSource(options) {
46943
48487
  throw new BackupError("backup_invalid_input");
46944
48488
  }
46945
48489
  const networks = normalizeNetworks(options.networks ?? []);
46946
- const path = join2(options.store.home, "vault.json");
46947
- const { phrase, file: file2, accounts } = await withVaultLock(path, async () => {
46948
- const [phrase2, vault, file3] = await Promise.all([
46949
- exportVaultPhrase({ path, key: options.vaultKey }),
46950
- openVault({ path, key: options.vaultKey }),
46951
- readVaultFileUnlocked(path)
46952
- ]);
46953
- const accounts2 = [];
46954
- for (const account of vault.accounts()) {
46955
- if (account.kind === "derived") {
46956
- accounts2.push({ ...account });
46957
- } else {
46958
- const privateKey = await exportVaultAccountKey({
46959
- path,
46960
- key: options.vaultKey,
46961
- name: account.name
46962
- });
46963
- accounts2.push({ ...account, privateKey });
46964
- }
48490
+ for (let attempt = 0; attempt < 3; attempt += 1) {
48491
+ try {
48492
+ return await exportBackupSourceAttempt(options, networks);
48493
+ } catch (error61) {
48494
+ if (!(error61 instanceof BackupSnapshotChangedError)) throw error61;
46965
48495
  }
46966
- return { phrase: phrase2, file: file3, accounts: accounts2 };
46967
- });
46968
- const snapshot = await options.store.reload();
46969
- const names = new Set(accounts.map((account) => account.name));
46970
- const source = {
46971
- phrase,
46972
- nextDerivedIndex: file2.nextDerivedIndex ?? accounts.reduce(
46973
- (next, account) => account.kind === "derived" ? Math.max(next, account.index + 1) : next,
46974
- 0
46975
- ),
46976
- accounts,
46977
- registry: {
46978
- ...snapshot.default !== void 0 && names.has(snapshot.default) ? { default: snapshot.default } : {},
46979
- accounts: accounts.map((account) => {
46980
- const entry = snapshot.wallets[account.name];
46981
- return {
46982
- name: account.name,
46983
- ...entry?.label === void 0 ? {} : { label: entry.label },
46984
- spendCaps: {
46985
- perCallAtomic: entry?.spendCaps.perCallAtomic ?? DEFAULT_SPEND_CAPS.perCallAtomic,
46986
- perDayAtomic: entry?.spendCaps.perDayAtomic ?? DEFAULT_SPEND_CAPS.perDayAtomic
46987
- }
46988
- };
46989
- }),
46990
- networks
46991
- },
46992
- protected: file2.protected
46993
- };
46994
- if (!backupSourceSchema.safeParse(source).success) {
46995
- throw new BackupError("backup_invalid_input");
46996
48496
  }
46997
- return source;
46998
- } catch {
48497
+ throw new BackupError("backup_snapshot_busy");
48498
+ } catch (error61) {
48499
+ if (error61 instanceof BackupError && error61.code === "backup_snapshot_busy") throw error61;
46999
48500
  throw new BackupError("backup_invalid_input");
47000
48501
  }
47001
48502
  }
48503
+ var BackupSnapshotChangedError = class extends Error {
48504
+ };
48505
+ async function exportBackupSourceAttempt(options, networks) {
48506
+ const path = join8(options.store.home, "vault.json");
48507
+ const { phrase, file: file2, accounts } = await withVaultLock(path, async () => {
48508
+ const [phrase2, vault, file3] = await Promise.all([
48509
+ exportVaultPhrase({ path, key: options.vaultKey }),
48510
+ openVault({ path, key: options.vaultKey }),
48511
+ readVaultFileUnlocked(path)
48512
+ ]);
48513
+ const accounts2 = [];
48514
+ for (const account of vault.accounts()) {
48515
+ if (account.kind === "derived") {
48516
+ accounts2.push({ ...account });
48517
+ } else {
48518
+ const privateKey = await exportVaultAccountKey({
48519
+ path,
48520
+ key: options.vaultKey,
48521
+ name: account.name
48522
+ });
48523
+ accounts2.push({ ...account, privateKey });
48524
+ }
48525
+ }
48526
+ return { phrase: phrase2, file: file3, accounts: accounts2 };
48527
+ });
48528
+ const snapshot = await options.store.reload();
48529
+ const names = new Set(accounts.map((account) => account.name));
48530
+ const home = options.store.home;
48531
+ const skipped = [];
48532
+ const [agents, swarms, movementSnapshots] = await Promise.all([
48533
+ listAgentProfiles(home, {
48534
+ schema: options.agentProfileSchema ?? agentProfileSchema,
48535
+ warn: () => void 0,
48536
+ onInvalid: (profileFile) => {
48537
+ skipped.push({
48538
+ kind: "agent",
48539
+ name: profileFile.endsWith(".json") ? profileFile.slice(0, -5) : profileFile,
48540
+ reason: "invalid_profile"
48541
+ });
48542
+ }
48543
+ }),
48544
+ listSwarms(home),
48545
+ listUnfinishedMovementSnapshots({ home })
48546
+ ]);
48547
+ const localMovements = await Promise.all(
48548
+ movementSnapshots.map(async ({ summary }) => await readMovement(home, summary.id))
48549
+ );
48550
+ localMovements.sort(compareMovements);
48551
+ const expectedSignedFailedLegs = movementSnapshots.flatMap(
48552
+ ({ signedFailedLegKeys }) => signedFailedLegKeys
48553
+ );
48554
+ const receipts = await readReceiptJournal(getVapiPaths(home).receipts);
48555
+ const receiptLegs = new Set(
48556
+ receipts.flatMap(
48557
+ (receipt) => receipt.kind === "transfer" && receipt.transfer !== void 0 ? [movementTransferKey(receiptWallet(receipt), receipt.transfer.nonce)] : []
48558
+ )
48559
+ );
48560
+ const requiredReceiptLegs = /* @__PURE__ */ new Set([
48561
+ ...expectedSignedFailedLegs,
48562
+ ...localMovements.flatMap(
48563
+ (movement) => movement.legs.filter((leg) => leg.status === "unknown").map((leg) => movementTransferKey(leg.from, leg.nonce))
48564
+ )
48565
+ ]);
48566
+ const verifiedFile = await readVaultFileUnlocked(path);
48567
+ const verifiedSnapshot = await options.store.reload();
48568
+ if ([...requiredReceiptLegs].some((leg) => !receiptLegs.has(leg)) || JSON.stringify(file2) !== JSON.stringify(verifiedFile) || JSON.stringify(snapshot) !== JSON.stringify(verifiedSnapshot)) {
48569
+ throw new BackupSnapshotChangedError();
48570
+ }
48571
+ const movements = localMovements.map(toBackupMovement);
48572
+ const includedLegs = new Set(
48573
+ localMovements.flatMap(
48574
+ (movement) => movement.legs.map((leg) => movementTransferKey(leg.from, leg.nonce))
48575
+ )
48576
+ );
48577
+ const transferReceipts = receipts.filter(
48578
+ (receipt) => receipt.kind === "transfer" && receipt.transfer !== void 0 && includedLegs.has(movementTransferKey(receiptWallet(receipt), receipt.transfer.nonce))
48579
+ ).map(toBackupTransferReceipt);
48580
+ const source = {
48581
+ phrase,
48582
+ nextDerivedIndex: file2.nextDerivedIndex ?? accounts.reduce(
48583
+ (next, account) => account.kind === "derived" ? Math.max(next, account.index + 1) : next,
48584
+ 0
48585
+ ),
48586
+ accounts,
48587
+ registry: {
48588
+ ...snapshot.default !== void 0 && names.has(snapshot.default) ? { default: snapshot.default } : {},
48589
+ accounts: accounts.map((account) => {
48590
+ const entry = snapshot.wallets[account.name];
48591
+ const ceilingAtomic = entry?.ceilingAtomic === null ? null : entry?.ceilingAtomic ?? DEFAULT_CEILING_ATOMIC.toString();
48592
+ return {
48593
+ name: account.name,
48594
+ ...entry?.label === void 0 ? {} : { label: entry.label },
48595
+ spendCaps: {
48596
+ perCallAtomic: entry?.spendCaps.perCallAtomic ?? DEFAULT_SPEND_CAPS.perCallAtomic,
48597
+ perDayAtomic: entry?.spendCaps.perDayAtomic ?? DEFAULT_SPEND_CAPS.perDayAtomic
48598
+ },
48599
+ ...ceilingAtomic === DEFAULT_CEILING_ATOMIC.toString() ? {} : { ceilingAtomic },
48600
+ ...entry?.routerRefill === void 0 ? {} : {
48601
+ routerRefill: {
48602
+ belowUsd: entry.routerRefill.belowUsd,
48603
+ tierUsd: entry.routerRefill.tierUsd
48604
+ }
48605
+ }
48606
+ };
48607
+ }),
48608
+ networks
48609
+ },
48610
+ protected: file2.protected,
48611
+ agents: agents.map(
48612
+ ({ grants, ...profile }) => backupAgentProfileSchema.parse(
48613
+ grants === void 0 || grants.length === 0 ? profile : { ...profile, grants }
48614
+ )
48615
+ ).sort(compareNamedValues),
48616
+ swarms: [...swarms].sort(compareNamedValues),
48617
+ movements,
48618
+ transferReceipts,
48619
+ ...skipped.length === 0 ? {} : { skipped: skipped.sort(compareNamedValues) }
48620
+ };
48621
+ if (!backupSourceSchema.safeParse(source).success) {
48622
+ throw new BackupError("backup_invalid_input");
48623
+ }
48624
+ return source;
48625
+ }
47002
48626
  async function restoreFromBackup(options) {
47003
48627
  return await restoreBackupPlaintext(options);
47004
48628
  }
@@ -47010,20 +48634,24 @@ async function restoreBackupPlaintext(options) {
47010
48634
  if (typeof options.home !== "string" || options.home.length === 0) {
47011
48635
  throw new BackupError("backup_invalid_input");
47012
48636
  }
48637
+ if (options.device !== void 0 && !DEVICE_NAME_PATTERN.test(options.device)) {
48638
+ throw new BackupError("backup_invalid_input");
48639
+ }
47013
48640
  try {
47014
48641
  assertBytes(options.vaultKey, 32);
47015
48642
  } catch {
47016
48643
  throw new BackupError("backup_invalid_input");
47017
48644
  }
47018
- const vaultPath = join2(options.home, "vault.json");
47019
- const registryPath = join2(options.home, "wallets.json");
48645
+ const vaultPath = join8(options.home, "vault.json");
48646
+ const registryPath = join8(options.home, "wallets.json");
47020
48647
  let stagingHome;
47021
48648
  let beforePublishError;
48649
+ let afterPublishError;
47022
48650
  try {
47023
- await mkdir2(options.home, { recursive: true, mode: 448 });
47024
- stagingHome = await mkdtemp(join2(options.home, ".backup-restore-"));
47025
- const stagedVaultPath = join2(stagingHome, "vault.json");
47026
- const stagedRegistryPath = join2(stagingHome, "wallets.json");
48651
+ await mkdir7(options.home, { recursive: true, mode: 448 });
48652
+ stagingHome = await mkdtemp(join8(options.home, ".backup-restore-"));
48653
+ const stagedVaultPath = join8(stagingHome, "vault.json");
48654
+ const stagedRegistryPath = join8(stagingHome, "wallets.json");
47027
48655
  await createVault({
47028
48656
  path: stagedVaultPath,
47029
48657
  key: options.vaultKey,
@@ -47069,16 +48697,59 @@ async function restoreBackupPlaintext(options) {
47069
48697
  } finally {
47070
48698
  await handle.close();
47071
48699
  }
48700
+ const stagedV2 = plaintext.v === 2 ? await stageV2Restore({
48701
+ plaintext,
48702
+ stagingHome,
48703
+ home: options.home,
48704
+ ...options.device === void 0 ? {} : { device: options.device }
48705
+ }) : void 0;
47072
48706
  const accounts = (await openVault({ path: stagedVaultPath, key: options.vaultKey })).accounts();
47073
- const result = {
48707
+ const baseResult = {
47074
48708
  accounts,
47075
48709
  ...plaintext.registry.default === void 0 ? {} : { default: plaintext.registry.default },
47076
48710
  protected: plaintext.protected,
47077
48711
  networks: [...plaintext.registry.networks]
47078
48712
  };
48713
+ const markerPath = join8(options.home, RESTORE_MARKER_FILE);
48714
+ const fingerprint = restoreFingerprint(
48715
+ plaintext,
48716
+ stagedV2?.restoreDevice ?? options.device,
48717
+ options.vaultKey
48718
+ );
47079
48719
  await withVaultLock(vaultPath, async () => {
47080
- if (await pathExists(vaultPath) || await pathExists(registryPath)) {
47081
- throw new BackupError("vault_exists");
48720
+ const existingVault = await pathExists2(vaultPath);
48721
+ const existingRegistry = await pathExists2(registryPath);
48722
+ let marker;
48723
+ if (existingVault || existingRegistry) {
48724
+ if (!existingVault) throw new BackupError("vault_exists");
48725
+ marker = await readRestoreMarker(markerPath, fingerprint, options.vaultKey);
48726
+ if (await sha256File(vaultPath) !== marker.vaultSha256) {
48727
+ throw new BackupError("vault_exists");
48728
+ }
48729
+ if (existingRegistry) {
48730
+ if (await sha256File(registryPath) !== marker.registrySha256) {
48731
+ throw new BackupError("vault_exists");
48732
+ }
48733
+ } else if (await sha256File(stagedRegistryPath) !== marker.registrySha256) {
48734
+ throw new BackupError("vault_exists");
48735
+ }
48736
+ } else {
48737
+ marker = await createRestoreMarker(
48738
+ stagedVaultPath,
48739
+ stagedRegistryPath,
48740
+ fingerprint,
48741
+ options.vaultKey
48742
+ );
48743
+ await writeJsonAtomic(markerPath, marker, { mode: 384 });
48744
+ await notifyRestorePublish(options.afterPublish, { kind: "marker" }, (error61) => {
48745
+ afterPublishError = error61;
48746
+ });
48747
+ }
48748
+ if (stagedV2 !== void 0) {
48749
+ await publishV2RestoreSafety(stagedV2, options.home);
48750
+ await notifyRestorePublish(options.afterPublish, { kind: "safety" }, (error61) => {
48751
+ afterPublishError = error61;
48752
+ });
47082
48753
  }
47083
48754
  try {
47084
48755
  await options.beforePublish?.({ vault: stagedVaultPath, registry: stagedRegistryPath });
@@ -47086,21 +48757,66 @@ async function restoreBackupPlaintext(options) {
47086
48757
  beforePublishError = error61;
47087
48758
  throw error61;
47088
48759
  }
48760
+ if (!existingVault && !existingRegistry) {
48761
+ const refreshedMarker = await createRestoreMarker(
48762
+ stagedVaultPath,
48763
+ stagedRegistryPath,
48764
+ fingerprint,
48765
+ options.vaultKey
48766
+ );
48767
+ if (refreshedMarker.vaultSha256 !== marker.vaultSha256 || refreshedMarker.registrySha256 !== marker.registrySha256) {
48768
+ marker = refreshedMarker;
48769
+ await writeJsonAtomic(markerPath, marker, { mode: 384 });
48770
+ }
48771
+ }
47089
48772
  let publishedVault = false;
47090
- try {
47091
- await link(stagedVaultPath, vaultPath);
47092
- publishedVault = true;
47093
- await link(stagedRegistryPath, registryPath);
47094
- } catch (error61) {
47095
- if (publishedVault) await rm2(vaultPath, { force: true }).catch(() => void 0);
47096
- throw error61;
48773
+ if (!existingVault) {
48774
+ try {
48775
+ await link2(stagedVaultPath, vaultPath);
48776
+ publishedVault = true;
48777
+ } catch (error61) {
48778
+ await rm2(markerPath, { force: true }).catch(() => void 0);
48779
+ throw error61;
48780
+ }
48781
+ await notifyRestorePublish(options.afterPublish, { kind: "vault" }, (error61) => {
48782
+ afterPublishError = error61;
48783
+ });
48784
+ }
48785
+ if (!existingRegistry) {
48786
+ try {
48787
+ await link2(stagedRegistryPath, registryPath);
48788
+ } catch (error61) {
48789
+ if (publishedVault) await rm2(vaultPath, { force: true }).catch(() => void 0);
48790
+ await rm2(markerPath, { force: true }).catch(() => void 0);
48791
+ throw error61;
48792
+ }
48793
+ await notifyRestorePublish(options.afterPublish, { kind: "registry" }, (error61) => {
48794
+ afterPublishError = error61;
48795
+ });
47097
48796
  }
48797
+ if (stagedV2 !== void 0) {
48798
+ await publishV2Restore(stagedV2, options.home, async (step) => {
48799
+ await notifyRestorePublish(options.afterPublish, step, (error61) => {
48800
+ afterPublishError = error61;
48801
+ });
48802
+ });
48803
+ }
48804
+ await rm2(markerPath, { force: true });
47098
48805
  });
47099
- return result;
48806
+ if (stagedV2 === void 0) return baseResult;
48807
+ return {
48808
+ ...baseResult,
48809
+ agents: stagedV2.restoredAgents,
48810
+ swarms: stagedV2.restoredSwarms,
48811
+ movements: stagedV2.restoredMovements,
48812
+ skipped: stagedV2.skipped,
48813
+ conflicts: stagedV2.conflicts
48814
+ };
47100
48815
  } catch (error61) {
47101
48816
  if (error61 === beforePublishError) throw error61;
48817
+ if (error61 === afterPublishError) throw error61;
47102
48818
  if (error61 instanceof BackupError && error61.code === "vault_exists") throw error61;
47103
- if (isExistingFile2(error61) || await pathExists(vaultPath).catch(() => false) || await pathExists(registryPath).catch(() => false)) {
48819
+ if (isExistingFile2(error61) || await pathExists2(vaultPath).catch(() => false) || await pathExists2(registryPath).catch(() => false)) {
47104
48820
  throw new BackupError("vault_exists");
47105
48821
  }
47106
48822
  throw new BackupError("backup_invalid_input");
@@ -47110,6 +48826,397 @@ async function restoreBackupPlaintext(options) {
47110
48826
  }
47111
48827
  }
47112
48828
  }
48829
+ async function stageV2Restore(options) {
48830
+ const skipped = [];
48831
+ const conflicts = [];
48832
+ const accounts = new Map(options.plaintext.accounts.map((account) => [account.name, account]));
48833
+ const validAgents = (options.plaintext.agents ?? []).filter((profile) => {
48834
+ if (accounts.has(profile.wallet)) return true;
48835
+ skipped.push({ kind: "agent", name: profile.name, reason: "missing_account" });
48836
+ return false;
48837
+ });
48838
+ const validSwarms = (options.plaintext.swarms ?? []).filter((swarm) => {
48839
+ const treasury = accounts.get(swarm.treasury.account);
48840
+ if (treasury === void 0) {
48841
+ if (swarm.treasury.steps.created || swarm.treasury.steps.creating) {
48842
+ skipped.push({ kind: "swarm", name: swarm.name, reason: "missing_account" });
48843
+ return false;
48844
+ }
48845
+ } else if (swarm.treasury.address !== void 0 && swarm.treasury.address.toLowerCase() !== treasury.address.toLowerCase()) {
48846
+ skipped.push({ kind: "swarm", name: swarm.name, reason: "address_mismatch" });
48847
+ return false;
48848
+ }
48849
+ for (const member of swarm.members) {
48850
+ const account = accounts.get(member.account);
48851
+ if (account === void 0) {
48852
+ if (member.steps.created || member.steps.creating) {
48853
+ skipped.push({ kind: "swarm", name: swarm.name, reason: "missing_account" });
48854
+ return false;
48855
+ }
48856
+ continue;
48857
+ }
48858
+ if (member.address !== void 0 && member.address.toLowerCase() !== account.address.toLowerCase()) {
48859
+ skipped.push({ kind: "swarm", name: swarm.name, reason: "address_mismatch" });
48860
+ return false;
48861
+ }
48862
+ }
48863
+ return true;
48864
+ });
48865
+ const allMovementLegs = /* @__PURE__ */ new Set();
48866
+ const backupMovementIds = [];
48867
+ const validMovements = [];
48868
+ for (const backupMovement of options.plaintext.movements ?? []) {
48869
+ const movement = currentMovement(backupMovement);
48870
+ backupMovementIds.push(movement.id);
48871
+ const legKeys = movement.legs.map((leg) => movementTransferKey(leg.from, leg.nonce));
48872
+ for (const key of legKeys) allMovementLegs.add(key);
48873
+ const senders = /* @__PURE__ */ new Set([
48874
+ movement.from,
48875
+ ...movement.treasury === void 0 ? [] : [movement.treasury],
48876
+ ...movement.legs.map((leg) => leg.from)
48877
+ ]);
48878
+ if ([...senders].some((sender) => !accounts.has(sender))) {
48879
+ skipped.push({ kind: "movement", name: movement.id, reason: "missing_account" });
48880
+ continue;
48881
+ }
48882
+ validMovements.push(movement);
48883
+ }
48884
+ const validReceipts = [];
48885
+ for (const receipt of options.plaintext.transferReceipts ?? []) {
48886
+ const key = movementTransferKey(receipt.wallet, receipt.transfer.nonce);
48887
+ if (!accounts.has(receipt.wallet)) {
48888
+ skipped.push({ kind: "receipt", name: receipt.id, reason: "missing_account" });
48889
+ } else if (!allMovementLegs.has(key)) {
48890
+ skipped.push({ kind: "receipt", name: receipt.id, reason: "missing_movement" });
48891
+ } else {
48892
+ validReceipts.push({
48893
+ name: receipt.id,
48894
+ line: JSON.stringify(parseReceipt(receipt)),
48895
+ legKey: key
48896
+ });
48897
+ }
48898
+ }
48899
+ let receiptsPath;
48900
+ let stagedReceipts = validReceipts;
48901
+ if (validReceipts.length > 0) {
48902
+ receiptsPath = getVapiPaths(options.stagingHome).receipts;
48903
+ const staged = await stageRestoreBytes(
48904
+ receiptsPath,
48905
+ `${validReceipts.map((receipt) => receipt.line).join("\n")}
48906
+ `
48907
+ );
48908
+ if (!staged) {
48909
+ for (const receipt of validReceipts) {
48910
+ skipped.push({ kind: "receipt", name: receipt.name, reason: "write_failed" });
48911
+ }
48912
+ stagedReceipts = [];
48913
+ receiptsPath = void 0;
48914
+ }
48915
+ }
48916
+ const assumedReceiptKeys = new Set(validReceipts.map((receipt) => receipt.legKey));
48917
+ try {
48918
+ const existingJournal = await readRestoreReceiptJournal(getVapiPaths(options.home).receipts);
48919
+ for (const key of existingJournal.signedKeys) assumedReceiptKeys.add(key);
48920
+ } catch {
48921
+ }
48922
+ const agents = [];
48923
+ for (const profile of validAgents) {
48924
+ const stagedPath = join8(options.stagingHome, "agents", `${profile.name}.json`);
48925
+ if (await stageRestoreBytes(stagedPath, prettyJson(profile))) {
48926
+ agents.push({
48927
+ kind: "agent",
48928
+ name: profile.name,
48929
+ stagedPath,
48930
+ targetPath: join8(options.home, "agents", `${profile.name}.json`)
48931
+ });
48932
+ } else {
48933
+ skipped.push({ kind: "agent", name: profile.name, reason: "write_failed" });
48934
+ }
48935
+ }
48936
+ let restoreDevice = options.device;
48937
+ if (validSwarms.length > 0 && restoreDevice === void 0) {
48938
+ try {
48939
+ restoreDevice = deviceName({ config: await loadConfig(getVapiPaths(options.home).config) });
48940
+ } catch {
48941
+ for (const swarm of validSwarms) {
48942
+ skipped.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
48943
+ }
48944
+ }
48945
+ }
48946
+ const swarms = [];
48947
+ if (restoreDevice !== void 0) {
48948
+ for (const value of validSwarms) {
48949
+ const swarm = swarmFileSchema.parse({ ...value, device: restoreDevice });
48950
+ const stagedPath = join8(options.stagingHome, "swarms", `${swarm.name}.json`);
48951
+ if (await stageRestoreBytes(stagedPath, prettyJson(swarm))) {
48952
+ swarms.push({
48953
+ kind: "swarm",
48954
+ name: swarm.name,
48955
+ stagedPath,
48956
+ targetPath: join8(options.home, "swarms", `${swarm.name}.json`)
48957
+ });
48958
+ } else {
48959
+ skipped.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
48960
+ }
48961
+ }
48962
+ }
48963
+ const movements = [];
48964
+ for (const movement of validMovements) {
48965
+ const restored = reconcileRestoredMovement(movement, assumedReceiptKeys);
48966
+ const stagedPath = join8(options.stagingHome, "movements", `${restored.id}.json`);
48967
+ if (await stageRestoreBytes(stagedPath, serializeMovement(restored))) {
48968
+ movements.push({
48969
+ kind: "movement",
48970
+ name: restored.id,
48971
+ stagedPath,
48972
+ targetPath: join8(options.home, "movements", `${restored.id}.json`),
48973
+ movement: restored
48974
+ });
48975
+ } else {
48976
+ skipped.push({ kind: "movement", name: restored.id, reason: "write_failed" });
48977
+ }
48978
+ }
48979
+ return {
48980
+ agents,
48981
+ swarms,
48982
+ movements,
48983
+ backupMovementIds,
48984
+ receipts: stagedReceipts,
48985
+ signedReceiptKeys: assumedReceiptKeys,
48986
+ ...receiptsPath === void 0 ? {} : { receiptsPath },
48987
+ restoredAgents: [],
48988
+ restoredSwarms: [],
48989
+ restoredMovements: [],
48990
+ skipped,
48991
+ conflicts,
48992
+ ...restoreDevice === void 0 ? {} : { restoreDevice }
48993
+ };
48994
+ }
48995
+ async function publishV2Restore(staged, home, afterPublish) {
48996
+ for (const file2 of staged.agents) {
48997
+ const outcome = await publishRestoreFile(file2, staged);
48998
+ if (outcome === "restored") staged.restoredAgents.push(file2.name);
48999
+ if (outcome === "restored") await afterPublish?.({ kind: "agent", name: file2.name });
49000
+ }
49001
+ for (const file2 of staged.swarms) {
49002
+ const outcome = await publishRestoreFile(file2, staged);
49003
+ if (outcome === "restored") staged.restoredSwarms.push(file2.name);
49004
+ if (outcome === "restored") await afterPublish?.({ kind: "swarm", name: file2.name });
49005
+ }
49006
+ const restoredMovementIds = [];
49007
+ for (const file2 of staged.movements) {
49008
+ const outcome = await publishRestoreFile(file2, staged);
49009
+ if (outcome === "restored") restoredMovementIds.push(file2.movement.id);
49010
+ if (outcome === "restored") await afterPublish?.({ kind: "movement", name: file2.name });
49011
+ }
49012
+ await reconcilePublishedMovements(staged, home);
49013
+ for (const id of restoredMovementIds) {
49014
+ try {
49015
+ staged.restoredMovements.push(movementSummary(await readMovement(home, id)));
49016
+ } catch {
49017
+ staged.skipped.push({ kind: "movement", name: id, reason: "write_failed" });
49018
+ }
49019
+ }
49020
+ }
49021
+ async function publishV2RestoreSafety(staged, home) {
49022
+ for (const id of staged.backupMovementIds) {
49023
+ await markOpenLegsRestored(home, id);
49024
+ }
49025
+ await publishRestoreReceipts(staged, getVapiPaths(home).receipts);
49026
+ await reconcilePublishedMovements(staged, home, true);
49027
+ }
49028
+ async function publishRestoreFile(file2, staged) {
49029
+ try {
49030
+ const directory = dirname4(file2.targetPath);
49031
+ await mkdir7(directory, { recursive: true, mode: 448 });
49032
+ await chmod2(directory, 448);
49033
+ try {
49034
+ await link2(file2.stagedPath, file2.targetPath);
49035
+ await chmod2(file2.targetPath, 384);
49036
+ return "restored";
49037
+ } catch (error61) {
49038
+ if (!isExistingFile2(error61)) throw error61;
49039
+ }
49040
+ let identical = false;
49041
+ try {
49042
+ const [source, target] = await Promise.all([
49043
+ readFile9(file2.stagedPath),
49044
+ readFile9(file2.targetPath)
49045
+ ]);
49046
+ identical = source.equals(target);
49047
+ } catch {
49048
+ }
49049
+ if (identical) {
49050
+ await chmod2(file2.targetPath, 384);
49051
+ return "restored";
49052
+ }
49053
+ staged.conflicts.push({
49054
+ kind: file2.kind,
49055
+ name: file2.name,
49056
+ path: file2.targetPath
49057
+ });
49058
+ return "conflict";
49059
+ } catch {
49060
+ staged.skipped.push({ kind: file2.kind, name: file2.name, reason: "write_failed" });
49061
+ return "failed";
49062
+ }
49063
+ }
49064
+ async function publishRestoreReceipts(staged, targetPath) {
49065
+ return await withReceiptJournalLock(
49066
+ targetPath,
49067
+ async () => publishRestoreReceiptsLocked(staged, targetPath)
49068
+ );
49069
+ }
49070
+ async function publishRestoreReceiptsLocked(staged, targetPath) {
49071
+ const restored = /* @__PURE__ */ new Set();
49072
+ if (staged.receipts.length === 0 || staged.receiptsPath === void 0) return restored;
49073
+ let existing = "";
49074
+ let existingLines = /* @__PURE__ */ new Set();
49075
+ try {
49076
+ await readFile9(staged.receiptsPath, "utf8");
49077
+ await mkdir7(dirname4(targetPath), { recursive: true, mode: 448 });
49078
+ try {
49079
+ const journal = await readRestoreReceiptJournal(targetPath);
49080
+ existing = journal.raw;
49081
+ existingLines = journal.lines;
49082
+ await chmod2(targetPath, 384);
49083
+ } catch (error61) {
49084
+ if (!isMissingFile3(error61)) throw error61;
49085
+ }
49086
+ } catch {
49087
+ for (const receipt of staged.receipts) {
49088
+ staged.skipped.push({ kind: "receipt", name: receipt.name, reason: "write_failed" });
49089
+ }
49090
+ return restored;
49091
+ }
49092
+ let needsLeadingNewline = existing.length > 0 && !existing.endsWith("\n");
49093
+ for (const receipt of staged.receipts) {
49094
+ if (existingLines.has(receipt.line)) {
49095
+ restored.add(receipt.legKey);
49096
+ continue;
49097
+ }
49098
+ let handle;
49099
+ try {
49100
+ handle = await openFile(targetPath, "a", 384);
49101
+ await handle.chmod(384);
49102
+ await handle.writeFile(`${needsLeadingNewline ? "\n" : ""}${receipt.line}
49103
+ `, "utf8");
49104
+ await handle.close();
49105
+ handle = void 0;
49106
+ needsLeadingNewline = false;
49107
+ existingLines.add(receipt.line);
49108
+ restored.add(receipt.legKey);
49109
+ } catch {
49110
+ await handle?.close().catch(() => void 0);
49111
+ staged.skipped.push({ kind: "receipt", name: receipt.name, reason: "write_failed" });
49112
+ }
49113
+ }
49114
+ return restored;
49115
+ }
49116
+ async function reconcilePublishedMovements(staged, home, requireDurableSafety = false) {
49117
+ const signedKeys = new Set(staged.signedReceiptKeys);
49118
+ const journaledKeys = /* @__PURE__ */ new Set();
49119
+ try {
49120
+ const journal = await readRestoreReceiptJournal(getVapiPaths(home).receipts);
49121
+ for (const key of journal.signedKeys) {
49122
+ signedKeys.add(key);
49123
+ journaledKeys.add(key);
49124
+ }
49125
+ } catch {
49126
+ }
49127
+ if (signedKeys.size === 0) return;
49128
+ const unjournaledKeys = new Set([...signedKeys].filter((key) => !journaledKeys.has(key)));
49129
+ let files;
49130
+ try {
49131
+ files = await readdir5(join8(home, "movements"));
49132
+ } catch (error61) {
49133
+ if (isMissingFile3(error61)) return;
49134
+ if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
49135
+ return;
49136
+ }
49137
+ for (const file2 of files) {
49138
+ if (!file2.endsWith(".json")) continue;
49139
+ const id = file2.slice(0, -5);
49140
+ let movement;
49141
+ try {
49142
+ movement = await readMovement(home, id);
49143
+ } catch (error61) {
49144
+ if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
49145
+ continue;
49146
+ }
49147
+ if (!movement.legs.some(
49148
+ (leg) => leg.status !== "sent" && leg.status !== "cancelled" && signedKeys.has(movementTransferKey(leg.from, leg.nonce))
49149
+ )) {
49150
+ continue;
49151
+ }
49152
+ try {
49153
+ await reconcileSignedLegs(home, id, signedKeys);
49154
+ } catch (error61) {
49155
+ staged.skipped.push({ kind: "movement", name: id, reason: "write_failed" });
49156
+ if (requireDurableSafety && movement.legs.some(
49157
+ (leg) => leg.status !== "sent" && leg.status !== "cancelled" && unjournaledKeys.has(movementTransferKey(leg.from, leg.nonce))
49158
+ )) {
49159
+ throw error61;
49160
+ }
49161
+ }
49162
+ }
49163
+ }
49164
+ async function stageRestoreBytes(path, bytes) {
49165
+ let handle;
49166
+ try {
49167
+ await mkdir7(dirname4(path), { recursive: true, mode: 448 });
49168
+ handle = await openFile(path, "wx", 384);
49169
+ await handle.writeFile(bytes, "utf8");
49170
+ await handle.close();
49171
+ return true;
49172
+ } catch {
49173
+ await handle?.close().catch(() => void 0);
49174
+ return false;
49175
+ }
49176
+ }
49177
+ function currentMovement(movement) {
49178
+ if (movement.v === 2) return movement;
49179
+ return {
49180
+ ...movement,
49181
+ v: 2,
49182
+ legs: movement.legs.map((leg) => ({
49183
+ ...leg,
49184
+ from: movement.from,
49185
+ purpose: "send"
49186
+ }))
49187
+ };
49188
+ }
49189
+ function reconcileRestoredMovement(movement, receiptKeys) {
49190
+ return {
49191
+ ...movement,
49192
+ legs: movement.legs.map((leg) => {
49193
+ if (leg.status === "cancelled") return leg;
49194
+ return leg.status !== "sent" && receiptKeys.has(movementTransferKey(leg.from, leg.nonce)) ? {
49195
+ from: leg.from,
49196
+ to: leg.to,
49197
+ amountUsd: leg.amountUsd,
49198
+ purpose: leg.purpose,
49199
+ nonce: leg.nonce,
49200
+ status: "unknown",
49201
+ restored: true
49202
+ } : { ...leg, restored: true };
49203
+ })
49204
+ };
49205
+ }
49206
+ function movementSummary(movement) {
49207
+ return {
49208
+ id: movement.id,
49209
+ from: movement.from,
49210
+ network: movement.network,
49211
+ createdAt: movement.createdAt,
49212
+ pendingLegs: movement.legs.filter((leg) => leg.status === "planned").length,
49213
+ unknownLegs: movement.legs.filter((leg) => leg.status === "unknown").length
49214
+ };
49215
+ }
49216
+ function prettyJson(value) {
49217
+ return `${JSON.stringify(value, null, 2)}
49218
+ `;
49219
+ }
47113
49220
  function parseSealed(sealed) {
47114
49221
  const value = JSON.parse(sealed);
47115
49222
  if (!isRecord(value) || !hasExactKeys(value, RELAY_KEYS) || value.format !== RELAY_FORMAT || value.v !== RELAY_VERSION || typeof value.epk !== "string" || typeof value.nonce !== "string" || typeof value.ciphertext !== "string" || decodeBase64Url(value.epk)?.byteLength !== 32 || decodeBase64Url(value.nonce)?.byteLength !== 12 || (decodeBase64Url(value.ciphertext)?.byteLength ?? 0) < 16) {
@@ -47127,9 +49234,9 @@ function assertRelayKey(value) {
47127
49234
  throw new BackupError("relay_invalid_key");
47128
49235
  }
47129
49236
  }
47130
- function readRelayRandomBytes(randomBytes4, length) {
49237
+ function readRelayRandomBytes(randomBytes7, length) {
47131
49238
  try {
47132
- const value = randomBytes4(length);
49239
+ const value = randomBytes7(length);
47133
49240
  if (!(value instanceof Uint8Array) || value.byteLength !== length) throw new Error();
47134
49241
  return Buffer.from(value);
47135
49242
  } catch {
@@ -47185,7 +49292,7 @@ function validateRestorePlaintext(value) {
47185
49292
  try {
47186
49293
  const parsed = backupPlaintextSchema.safeParse(value);
47187
49294
  if (!parsed.success) throw new Error();
47188
- const plaintext = buildPlaintext(parsed.data);
49295
+ const plaintext = parsed.data.v === 1 ? buildPlaintextV1(parsed.data) : buildPlaintextV2(parsed.data);
47189
49296
  const phrase = validateRecoveryPhrase(plaintext.phrase);
47190
49297
  let seed;
47191
49298
  try {
@@ -47208,12 +49315,22 @@ function buildRestoredRegistry(plaintext) {
47208
49315
  for (let index = 0; index < plaintext.accounts.length; index += 1) {
47209
49316
  const account = plaintext.accounts[index];
47210
49317
  const metadata = plaintext.registry.accounts[index];
49318
+ const metadataV2 = plaintext.v === 2 ? plaintext.registry.accounts[index] : void 0;
47211
49319
  wallets[account.name] = {
47212
49320
  createdAt: account.createdAt,
47213
49321
  ...metadata.label === void 0 ? {} : { label: metadata.label },
47214
49322
  spendCaps: {
47215
49323
  perCallAtomic: metadata.spendCaps.perCallAtomic,
47216
49324
  perDayAtomic: metadata.spendCaps.perDayAtomic
49325
+ },
49326
+ ...metadataV2 === void 0 ? {} : {
49327
+ ceilingAtomic: metadataV2.ceilingAtomic === void 0 ? DEFAULT_CEILING_ATOMIC.toString() : metadataV2.ceilingAtomic,
49328
+ ...metadataV2.routerRefill === void 0 ? {} : {
49329
+ routerRefill: {
49330
+ belowUsd: metadataV2.routerRefill.belowUsd,
49331
+ tierUsd: metadataV2.routerRefill.tierUsd
49332
+ }
49333
+ }
47217
49334
  }
47218
49335
  };
47219
49336
  }
@@ -47223,7 +49340,48 @@ function buildRestoredRegistry(plaintext) {
47223
49340
  wallets
47224
49341
  });
47225
49342
  }
47226
- async function pathExists(path) {
49343
+ function restoreFingerprint(plaintext, device, vaultKey) {
49344
+ return createHmac("sha256", vaultKey).update("vapi-backup-restore/v1\n", "utf8").update(JSON.stringify({ device: device ?? null, plaintext }), "utf8").digest("hex");
49345
+ }
49346
+ async function createRestoreMarker(vaultPath, registryPath, fingerprint, vaultKey) {
49347
+ const marker = {
49348
+ v: 1,
49349
+ fingerprint,
49350
+ vaultSha256: await sha256File(vaultPath),
49351
+ registrySha256: await sha256File(registryPath)
49352
+ };
49353
+ return { ...marker, mac: restoreMarkerMac(marker, vaultKey) };
49354
+ }
49355
+ async function readRestoreMarker(path, fingerprint, vaultKey) {
49356
+ try {
49357
+ const marker = restoreMarkerSchema.parse(JSON.parse(await readFile9(path, "utf8")));
49358
+ const expectedMac = restoreMarkerMac(marker, vaultKey);
49359
+ if (marker.fingerprint !== fingerprint || !timingSafeEqual(Buffer.from(marker.mac, "hex"), Buffer.from(expectedMac, "hex"))) {
49360
+ throw new Error();
49361
+ }
49362
+ return marker;
49363
+ } catch {
49364
+ throw new BackupError("vault_exists");
49365
+ }
49366
+ }
49367
+ function restoreMarkerMac(marker, vaultKey) {
49368
+ return createHmac("sha256", vaultKey).update(
49369
+ `vapi-backup-restore-marker/v1|${marker.fingerprint}|${marker.vaultSha256}|${marker.registrySha256}`,
49370
+ "utf8"
49371
+ ).digest("hex");
49372
+ }
49373
+ async function sha256File(path) {
49374
+ return createHash("sha256").update(await readFile9(path)).digest("hex");
49375
+ }
49376
+ async function notifyRestorePublish(hook, step, rememberError) {
49377
+ try {
49378
+ await hook?.(step);
49379
+ } catch (error61) {
49380
+ rememberError(error61);
49381
+ throw error61;
49382
+ }
49383
+ }
49384
+ async function pathExists2(path) {
47227
49385
  try {
47228
49386
  await lstat(path);
47229
49387
  return true;
@@ -47273,7 +49431,23 @@ function validateBackupSourceRelationships(source, context) {
47273
49431
  }
47274
49432
  }
47275
49433
  }
47276
- function buildPlaintext(source) {
49434
+ function validateBackupV2Uniqueness(source, context) {
49435
+ validateUniqueValues(source.agents, (agent) => agent.name, "agent name", context);
49436
+ validateUniqueValues(source.swarms, (swarm) => swarm.name, "swarm name", context);
49437
+ validateUniqueValues(source.movements, (movement) => movement.id, "movement id", context);
49438
+ }
49439
+ function validateUniqueValues(values, key, label, context) {
49440
+ if (values === void 0) return;
49441
+ const seen = /* @__PURE__ */ new Set();
49442
+ for (const value of values) {
49443
+ const current = key(value);
49444
+ if (seen.has(current)) {
49445
+ context.addIssue({ code: "custom", message: `Duplicate ${label}.` });
49446
+ }
49447
+ seen.add(current);
49448
+ }
49449
+ }
49450
+ function buildPlaintextV1(source) {
47277
49451
  const accounts = source.accounts.map(
47278
49452
  (account) => account.kind === "derived" ? {
47279
49453
  name: account.name,
@@ -47311,6 +49485,227 @@ function buildPlaintext(source) {
47311
49485
  protected: source.protected
47312
49486
  };
47313
49487
  }
49488
+ function buildPlaintextV2(source, included = { agents: true, swarms: true, movements: true }) {
49489
+ const accounts = buildPlaintextV1({
49490
+ phrase: source.phrase,
49491
+ nextDerivedIndex: source.nextDerivedIndex,
49492
+ accounts: source.accounts,
49493
+ registry: {
49494
+ ...source.registry.default === void 0 ? {} : { default: source.registry.default },
49495
+ accounts: source.registry.accounts,
49496
+ networks: source.registry.networks
49497
+ },
49498
+ protected: source.protected
49499
+ }).accounts;
49500
+ const registry2 = {
49501
+ ...source.registry.default === void 0 ? {} : { default: source.registry.default },
49502
+ accounts: source.registry.accounts.map((account) => ({
49503
+ name: account.name,
49504
+ ...account.label === void 0 ? {} : { label: account.label },
49505
+ spendCaps: {
49506
+ perCallAtomic: account.spendCaps.perCallAtomic,
49507
+ perDayAtomic: account.spendCaps.perDayAtomic
49508
+ },
49509
+ ...account.ceilingAtomic === void 0 || account.ceilingAtomic === DEFAULT_CEILING_ATOMIC.toString() ? {} : { ceilingAtomic: account.ceilingAtomic },
49510
+ ...account.routerRefill === void 0 ? {} : {
49511
+ routerRefill: {
49512
+ belowUsd: account.routerRefill.belowUsd,
49513
+ tierUsd: account.routerRefill.tierUsd
49514
+ }
49515
+ }
49516
+ })),
49517
+ networks: [...source.registry.networks]
49518
+ };
49519
+ const agents = source.agents;
49520
+ const swarms = source.swarms;
49521
+ const movements = source.movements;
49522
+ const transferReceipts = source.transferReceipts;
49523
+ return {
49524
+ v: 2,
49525
+ phrase: source.phrase,
49526
+ nextDerivedIndex: source.nextDerivedIndex,
49527
+ accounts,
49528
+ registry: registry2,
49529
+ protected: source.protected,
49530
+ ...included.agents !== false && agents !== void 0 && agents.length > 0 ? { agents: [...agents].sort(compareNamedValues).map(copyAgentProfile) } : {},
49531
+ ...included.swarms !== false && swarms !== void 0 && swarms.length > 0 ? { swarms: [...swarms].sort(compareNamedValues).map(copySwarm) } : {},
49532
+ ...included.movements !== false && movements !== void 0 && movements.length > 0 ? { movements: [...movements].sort(compareMovements).map(copyMovement) } : {},
49533
+ ...included.movements !== false && transferReceipts !== void 0 && transferReceipts.length > 0 ? { transferReceipts: transferReceipts.map(copyTransferReceipt) } : {}
49534
+ };
49535
+ }
49536
+ function backupCandidates(source) {
49537
+ if (!isBackupSourceV2(source)) {
49538
+ return [{ plaintext: buildPlaintextV1(source), omitted: [] }];
49539
+ }
49540
+ const candidates = [];
49541
+ const included = { agents: true, swarms: true, movements: true };
49542
+ const omitted = [];
49543
+ const addCandidate = () => {
49544
+ candidates.push({
49545
+ plaintext: hasV2OnlyData(source, included) ? buildPlaintextV2(source, included) : buildPlaintextV1(source),
49546
+ omitted: [...omitted]
49547
+ });
49548
+ };
49549
+ addCandidate();
49550
+ if (source.agents.length > 0) {
49551
+ included.agents = false;
49552
+ omitted.push("agents");
49553
+ addCandidate();
49554
+ }
49555
+ if (source.swarms.length > 0) {
49556
+ included.swarms = false;
49557
+ omitted.push("swarms");
49558
+ addCandidate();
49559
+ }
49560
+ if (source.movements.length > 0 || source.transferReceipts.length > 0) {
49561
+ included.movements = false;
49562
+ omitted.push("movements");
49563
+ addCandidate();
49564
+ }
49565
+ return candidates;
49566
+ }
49567
+ function hasV2OnlyData(source, included) {
49568
+ return source.registry.accounts.some(
49569
+ (account) => account.ceilingAtomic !== void 0 && account.ceilingAtomic !== DEFAULT_CEILING_ATOMIC.toString() || account.routerRefill !== void 0
49570
+ ) || included.agents !== false && source.agents.length > 0 || included.swarms !== false && source.swarms.length > 0 || included.movements !== false && (source.movements.length > 0 || source.transferReceipts.length > 0);
49571
+ }
49572
+ function isBackupSourceV2(source) {
49573
+ return "agents" in source;
49574
+ }
49575
+ function copyAgentProfile(profile) {
49576
+ return {
49577
+ version: profile.version,
49578
+ name: profile.name,
49579
+ wallet: profile.wallet,
49580
+ model: profile.model,
49581
+ instructions: profile.instructions,
49582
+ verifiedOnly: profile.verifiedOnly,
49583
+ approveAboveUsd: profile.approveAboveUsd,
49584
+ maxSteps: profile.maxSteps,
49585
+ paused: profile.paused,
49586
+ createdAt: profile.createdAt,
49587
+ tools: [...profile.tools],
49588
+ ...profile.grants === void 0 ? {} : { grants: [...profile.grants] }
49589
+ };
49590
+ }
49591
+ function copySwarm(swarm) {
49592
+ return swarmFileSchema.parse(swarm);
49593
+ }
49594
+ function copyMovement(movement) {
49595
+ return toBackupMovement(movement);
49596
+ }
49597
+ function toBackupMovement(movement) {
49598
+ if (movement.v === 1) return backupMovementSchema.parse(movement);
49599
+ return backupMovementSchema.parse({
49600
+ ...movement,
49601
+ legs: movement.legs.map(
49602
+ ({
49603
+ restored: _restored,
49604
+ fromAddress: _fromAddress,
49605
+ toAddress: _toAddress,
49606
+ addressBindingSource: _addressBindingSource,
49607
+ ...leg
49608
+ }) => leg
49609
+ )
49610
+ });
49611
+ }
49612
+ function toBackupTransferReceipt(receipt) {
49613
+ if (receipt.quote?.asset === void 0) throw new BackupError("backup_invalid_input");
49614
+ return copyTransferReceipt({
49615
+ id: receipt.id,
49616
+ timestamp: receipt.timestamp,
49617
+ kind: "transfer",
49618
+ wallet: receiptWallet(receipt),
49619
+ resourceUrl: receipt.resourceUrl,
49620
+ quote: {
49621
+ network: receipt.quote.network,
49622
+ asset: receipt.quote.asset,
49623
+ amountAtomic: receipt.quote.amountAtomic
49624
+ },
49625
+ transfer: receipt.transfer,
49626
+ ...receipt.error === void 0 ? {} : { error: receipt.error }
49627
+ });
49628
+ }
49629
+ function copyTransferReceipt(receipt) {
49630
+ const transfer = receipt.transfer;
49631
+ const request = transfer.request;
49632
+ return backupTransferReceiptSchema.parse({
49633
+ id: receipt.id,
49634
+ timestamp: receipt.timestamp,
49635
+ kind: "transfer",
49636
+ wallet: receipt.wallet,
49637
+ resourceUrl: receipt.resourceUrl,
49638
+ quote: {
49639
+ network: receipt.quote.network,
49640
+ asset: receipt.quote.asset,
49641
+ amountAtomic: receipt.quote.amountAtomic
49642
+ },
49643
+ transfer: {
49644
+ to: transfer.to,
49645
+ toName: transfer.toName,
49646
+ toKind: transfer.toKind,
49647
+ amountAtomic: transfer.amountAtomic,
49648
+ network: transfer.network,
49649
+ nonce: transfer.nonce,
49650
+ status: transfer.status,
49651
+ txHash: transfer.txHash,
49652
+ replayed: transfer.replayed,
49653
+ ...transfer.reservedOn === void 0 ? {} : { reservedOn: transfer.reservedOn },
49654
+ ...request === void 0 ? {} : {
49655
+ request: {
49656
+ authorization: {
49657
+ from: request.authorization.from,
49658
+ to: request.authorization.to,
49659
+ value: request.authorization.value,
49660
+ validAfter: request.authorization.validAfter,
49661
+ validBefore: request.authorization.validBefore,
49662
+ nonce: request.authorization.nonce
49663
+ },
49664
+ signature: request.signature
49665
+ }
49666
+ }
49667
+ },
49668
+ ...receipt.error === void 0 ? {} : { error: { code: receipt.error.code, message: receipt.error.message } }
49669
+ });
49670
+ }
49671
+ async function readReceiptJournal(path) {
49672
+ let raw;
49673
+ try {
49674
+ raw = await readFile9(path, "utf8");
49675
+ } catch (error61) {
49676
+ if (isMissingFile3(error61)) return [];
49677
+ throw error61;
49678
+ }
49679
+ return raw.split("\n").filter((line) => line.trim().length > 0).map((line) => parseReceipt(JSON.parse(line)));
49680
+ }
49681
+ async function readRestoreReceiptJournal(path) {
49682
+ let raw;
49683
+ try {
49684
+ raw = await readFile9(path, "utf8");
49685
+ } catch (error61) {
49686
+ if (isMissingFile3(error61)) return { raw: "", lines: /* @__PURE__ */ new Set(), signedKeys: /* @__PURE__ */ new Set() };
49687
+ throw error61;
49688
+ }
49689
+ const lines = new Set(raw.split("\n"));
49690
+ const signedKeys = /* @__PURE__ */ new Set();
49691
+ for (const line of lines) {
49692
+ if (line.trim().length === 0) continue;
49693
+ try {
49694
+ const receipt = parseReceipt(JSON.parse(line));
49695
+ if (receipt.transfer !== void 0) {
49696
+ signedKeys.add(movementTransferKey(receiptWallet(receipt), receipt.transfer.nonce));
49697
+ }
49698
+ } catch {
49699
+ }
49700
+ }
49701
+ return { raw, lines, signedKeys };
49702
+ }
49703
+ function compareNamedValues(left, right) {
49704
+ return left.name < right.name ? -1 : left.name > right.name ? 1 : 0;
49705
+ }
49706
+ function compareMovements(left, right) {
49707
+ return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
49708
+ }
47314
49709
  function parseEnvelope(envelope) {
47315
49710
  if (typeof envelope !== "string") throw new BackupError("backup_unsupported");
47316
49711
  if (Buffer.byteLength(envelope, "utf8") > MAX_BACKUP_BYTES) {
@@ -47489,8 +49884,8 @@ function assertOwnerKey(ownerKey) {
47489
49884
  assertBytes(ownerKey.key, 32);
47490
49885
  assertBytes(ownerKey.salt, 32);
47491
49886
  }
47492
- function readRandomBytes(randomBytes4, length) {
47493
- const value = randomBytes4(length);
49887
+ function readRandomBytes(randomBytes7, length) {
49888
+ const value = randomBytes7(length);
47494
49889
  if (!(value instanceof Uint8Array) || value.byteLength !== length) {
47495
49890
  throw new BackupError("backup_invalid_input");
47496
49891
  }
@@ -47523,6 +49918,7 @@ function hasExactKeys(value, expected) {
47523
49918
  export {
47524
49919
  BackupError,
47525
49920
  VAULT_BACKUP_TYPED_DATA,
49921
+ buildRelayRestorePayload,
47526
49922
  createBackup,
47527
49923
  createRelayKeyPair,
47528
49924
  deriveKeyFromPassword,