@vapi-network/core 0.14.0 → 0.15.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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-link.d.ts +1 -0
  3. package/dist/agent-link.d.ts.map +1 -1
  4. package/dist/agent-link.js +209 -96
  5. package/dist/agent-link.js.map +3 -3
  6. package/dist/atomic-file.d.ts +4 -0
  7. package/dist/atomic-file.d.ts.map +1 -1
  8. package/dist/backup.d.ts.map +1 -1
  9. package/dist/backup.js +202 -146
  10. package/dist/backup.js.map +3 -3
  11. package/dist/cloud-backup.js +312 -197
  12. package/dist/cloud-backup.js.map +3 -3
  13. package/dist/discovery.d.ts +2 -0
  14. package/dist/discovery.d.ts.map +1 -1
  15. package/dist/http-response.d.ts +7 -0
  16. package/dist/http-response.d.ts.map +1 -0
  17. package/dist/index.d.ts +3 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +3269 -2242
  20. package/dist/index.js.map +3 -3
  21. package/dist/keystore-error.d.ts +4 -0
  22. package/dist/keystore-error.d.ts.map +1 -0
  23. package/dist/keystore.d.ts +1 -4
  24. package/dist/keystore.d.ts.map +1 -1
  25. package/dist/payment-warning.d.ts +12 -0
  26. package/dist/payment-warning.d.ts.map +1 -0
  27. package/dist/receipts.d.ts +5 -0
  28. package/dist/receipts.d.ts.map +1 -1
  29. package/dist/router-client.d.ts +107 -7
  30. package/dist/router-client.d.ts.map +1 -1
  31. package/dist/router-client.js +17442 -16631
  32. package/dist/router-client.js.map +3 -3
  33. package/dist/secrets.js +65 -42
  34. package/dist/secrets.js.map +2 -2
  35. package/dist/spend-policy.d.ts.map +1 -1
  36. package/dist/support-report.d.ts +1 -1
  37. package/dist/svm.d.ts.map +1 -1
  38. package/dist/swarm-capital.d.ts +70 -0
  39. package/dist/swarm-capital.d.ts.map +1 -1
  40. package/dist/swarm-workers.d.ts +4 -0
  41. package/dist/swarm-workers.d.ts.map +1 -0
  42. package/dist/swarm.d.ts +1 -1
  43. package/dist/swarm.d.ts.map +1 -1
  44. package/dist/tasks.js +139 -69
  45. package/dist/tasks.js.map +2 -2
  46. package/dist/transfer.d.ts.map +1 -1
  47. package/dist/wallet-store.d.ts +77 -0
  48. package/dist/wallet-store.d.ts.map +1 -1
  49. package/dist/x402-pay.d.ts +10 -2
  50. package/dist/x402-pay.d.ts.map +1 -1
  51. package/dist/x402.d.ts +10 -6
  52. package/dist/x402.d.ts.map +1 -1
  53. package/package.json +1 -1
@@ -45543,11 +45543,14 @@ async function writeJsonAtomic(path, value, options = {}) {
45543
45543
  await handle.close();
45544
45544
  handle = void 0;
45545
45545
  await rename(temporaryPath, path);
45546
- const directoryHandle = await open2(directory, "r");
45547
- try {
45548
- await directoryHandle.sync();
45549
- } finally {
45550
- await directoryHandle.close();
45546
+ if (process.platform !== "win32") {
45547
+ const directoryHandle = await open2(directory, "r");
45548
+ try {
45549
+ await atomicFileTestHooks?.beforeDirectorySync?.(directory);
45550
+ await directoryHandle.sync();
45551
+ } finally {
45552
+ await directoryHandle.close();
45553
+ }
45551
45554
  }
45552
45555
  } catch (error61) {
45553
45556
  await handle?.close().catch(() => void 0);
@@ -45565,38 +45568,43 @@ async function withFileLock(lockPath, fn, options = {}) {
45565
45568
  const owner = JSON.stringify(ownerRecord);
45566
45569
  const releasedOwner = JSON.stringify({ ...ownerRecord, released: true });
45567
45570
  let handle;
45568
- while (handle === void 0) {
45569
- await atomicFileTestHooks?.beforeLockAttempt?.(lockPath);
45570
- try {
45571
- const candidate = await open2(lockPath, "wx", 384);
45571
+ try {
45572
+ while (handle === void 0) {
45573
+ await atomicFileTestHooks?.beforeLockAttempt?.(lockPath);
45572
45574
  try {
45573
- await candidate.writeFile(owner, "utf8");
45574
- await candidate.sync();
45575
- await atomicFileTestHooks?.afterLockCreate?.(lockPath);
45576
- if (await lockTakeoverInProgress(lockPath)) {
45577
- await candidate.close();
45578
- await removeOwnedLock(lockPath, [owner]);
45579
- await removeAbandonedLockTombs(lockPath);
45580
- if (Date.now() >= deadline) {
45581
- throw new FileLockedError(options.lockedMessage);
45575
+ const candidate = await open2(lockPath, "wx", 384);
45576
+ try {
45577
+ await candidate.writeFile(owner, "utf8");
45578
+ await candidate.sync();
45579
+ await atomicFileTestHooks?.afterLockCreate?.(lockPath);
45580
+ if (await lockTakeoverInProgress(lockPath)) {
45581
+ await candidate.close();
45582
+ await removeOwnedLock(lockPath, [owner]);
45583
+ await removeAbandonedLockTombs(lockPath);
45584
+ if (Date.now() >= deadline) {
45585
+ throw new FileLockedError(options.lockedMessage);
45586
+ }
45587
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
45588
+ continue;
45582
45589
  }
45583
- await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
45584
- continue;
45590
+ handle = candidate;
45591
+ } catch (error61) {
45592
+ await candidate.close().catch(() => void 0);
45593
+ await removeOwnedLock(lockPath, [owner]).catch(() => void 0);
45594
+ throw error61;
45585
45595
  }
45586
- handle = candidate;
45587
45596
  } catch (error61) {
45588
- await candidate.close().catch(() => void 0);
45589
- await removeOwnedLock(lockPath, [owner]).catch(() => void 0);
45590
- throw error61;
45591
- }
45592
- } catch (error61) {
45593
- if (!hasCode(error61, "EEXIST")) throw error61;
45594
- await removeStaleLock(lockPath);
45595
- if (Date.now() >= deadline) {
45596
- throw new FileLockedError(options.lockedMessage);
45597
+ if (!hasCode(error61, "EEXIST")) throw error61;
45598
+ await removeStaleLock(lockPath);
45599
+ if (Date.now() >= deadline) {
45600
+ throw new FileLockedError(options.lockedMessage);
45601
+ }
45602
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
45597
45603
  }
45598
- await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
45599
45604
  }
45605
+ } catch (error61) {
45606
+ await removeOwnedTombs(lockPath, [owner]).catch(() => void 0);
45607
+ throw error61;
45600
45608
  }
45601
45609
  const ownedHandle = handle;
45602
45610
  const heartbeat = setInterval(() => {
@@ -45609,13 +45617,18 @@ async function withFileLock(lockPath, fn, options = {}) {
45609
45617
  } finally {
45610
45618
  clearInterval(heartbeat);
45611
45619
  try {
45612
- await markLockReleased(ownedHandle, releasedOwner);
45613
- } finally {
45614
45620
  try {
45615
- await ownedHandle.close();
45621
+ await atomicFileTestHooks?.beforeLockRelease?.(lockPath);
45622
+ await markLockReleased(ownedHandle, releasedOwner);
45616
45623
  } finally {
45617
- await removeOwnedLock(lockPath, [owner, releasedOwner]);
45624
+ try {
45625
+ await ownedHandle.close();
45626
+ await atomicFileTestHooks?.afterLockHandleClose?.(lockPath);
45627
+ } finally {
45628
+ await removeOwnedLock(lockPath, [owner, releasedOwner]);
45629
+ }
45618
45630
  }
45631
+ } catch {
45619
45632
  }
45620
45633
  }
45621
45634
  }
@@ -45652,8 +45665,9 @@ async function removeOwnedLock(path, owners) {
45652
45665
  throw error61;
45653
45666
  }
45654
45667
  let pendingError;
45668
+ let renamedOwner;
45655
45669
  try {
45656
- const renamedOwner = await readFile(tombPath, "utf8");
45670
+ renamedOwner = await readFile(tombPath, "utf8");
45657
45671
  if (!owners.includes(renamedOwner) && !lockOwnerReleased(renamedOwner)) {
45658
45672
  await atomicFileTestHooks?.afterMismatchedLockRename?.(path);
45659
45673
  const currentOwner = await readFile(tombPath, "utf8");
@@ -45664,9 +45678,13 @@ async function removeOwnedLock(path, owners) {
45664
45678
  pendingError = error61;
45665
45679
  }
45666
45680
  try {
45681
+ await atomicFileTestHooks?.beforeTombUnlink?.(tombPath);
45667
45682
  await unlink(tombPath);
45668
45683
  } catch (error61) {
45669
- if (!hasCode(error61, "ENOENT") && pendingError === void 0) {
45684
+ if (!tombUnlinkTolerated(
45685
+ error61,
45686
+ renamedOwner !== void 0 && lockOwnerReleased(renamedOwner) && owners.includes(renamedOwner)
45687
+ ) && pendingError === void 0) {
45670
45688
  pendingError = error61;
45671
45689
  }
45672
45690
  }
@@ -45691,7 +45709,7 @@ async function removeAbandonedLockTombs(path) {
45691
45709
  const abandoned = lockOwnerReleased(owner) || Date.now() - metadata.mtimeMs > LOCK_STALE_AFTER_MS && (pid === void 0 || !processIsAlive(pid));
45692
45710
  if (!abandoned) continue;
45693
45711
  await unlink(tombPath).catch((error61) => {
45694
- if (!hasCode(error61, "ENOENT")) throw error61;
45712
+ if (!tombUnlinkTolerated(error61, true)) throw error61;
45695
45713
  });
45696
45714
  }
45697
45715
  }
@@ -45703,9 +45721,12 @@ async function removeOwnedTombs(path, owners) {
45703
45721
  const tombPath = join2(directory, entry);
45704
45722
  const owner = await readFile(tombPath, "utf8").catch(() => void 0);
45705
45723
  if (owner === void 0 || !owners.includes(owner)) continue;
45706
- await unlink(tombPath).catch((error61) => {
45707
- if (!hasCode(error61, "ENOENT")) throw error61;
45708
- });
45724
+ try {
45725
+ await atomicFileTestHooks?.beforeTombUnlink?.(tombPath);
45726
+ await unlink(tombPath);
45727
+ } catch (error61) {
45728
+ if (!tombUnlinkTolerated(error61, lockOwnerReleased(owner))) throw error61;
45729
+ }
45709
45730
  }
45710
45731
  }
45711
45732
  async function restoreRenamedLock(path, tombPath) {
@@ -45755,6 +45776,9 @@ function processIsAlive(pid) {
45755
45776
  return hasCode(error61, "EPERM");
45756
45777
  }
45757
45778
  }
45779
+ function tombUnlinkTolerated(error61, reapable) {
45780
+ return hasCode(error61, "ENOENT") || reapable && process.platform === "win32" && (hasCode(error61, "EPERM") || hasCode(error61, "EBUSY"));
45781
+ }
45758
45782
  function hasCode(error61, code) {
45759
45783
  return error61 instanceof Error && "code" in error61 && error61.code === code;
45760
45784
  }
@@ -46565,136 +46589,13 @@ function deviceName(args = {}) {
46565
46589
  return slugifyDeviceName(args.hostname ?? operatingSystemHostname());
46566
46590
  }
46567
46591
 
46568
- // src/keystore.ts
46569
- import { createCipheriv, createDecipheriv, randomBytes as randomBytes3, scrypt } from "node:crypto";
46570
- var SCRYPT_N = 2 ** 15;
46571
- var SCRYPT_R = 8;
46572
- var SCRYPT_P = 1;
46573
- var KEY_LENGTH = 32;
46574
- var SCRYPT_MAX_MEMORY = 64 * 1024 * 1024;
46575
- var AUTH_TAG_LENGTH = 16;
46576
- var cryptoSchema = external_exports.object({
46577
- cipher: external_exports.literal("aes-256-gcm"),
46578
- ciphertext: external_exports.string(),
46579
- iv: external_exports.string(),
46580
- authTag: external_exports.string(),
46581
- kdf: external_exports.literal("scrypt"),
46582
- salt: external_exports.string(),
46583
- kdfParams: external_exports.object({
46584
- n: external_exports.literal(SCRYPT_N),
46585
- r: external_exports.literal(SCRYPT_R),
46586
- p: external_exports.literal(SCRYPT_P),
46587
- dkLen: external_exports.literal(KEY_LENGTH)
46588
- })
46589
- });
46590
- var legacyKeystoreSchema = external_exports.object({
46591
- version: external_exports.literal(1),
46592
- address: external_exports.string(),
46593
- crypto: cryptoSchema
46594
- });
46595
- var keystoreSchema = external_exports.object({
46596
- version: external_exports.literal(2),
46597
- address: external_exports.string(),
46598
- keys: external_exports.object({
46599
- evm: external_exports.object({
46600
- type: external_exports.literal("secp256k1"),
46601
- address: external_exports.string()
46602
- }),
46603
- solana: external_exports.object({
46604
- type: external_exports.literal("ed25519"),
46605
- address: external_exports.string()
46606
- }).optional()
46607
- }),
46608
- crypto: cryptoSchema
46609
- });
46610
- var keystoreV3Schema = external_exports.object({
46611
- version: external_exports.literal(3),
46612
- address: external_exports.string(),
46613
- keys: external_exports.object({
46614
- evm: external_exports.object({
46615
- type: external_exports.literal("secp256k1"),
46616
- address: external_exports.string(),
46617
- path: external_exports.string()
46618
- }),
46619
- solana: external_exports.object({
46620
- type: external_exports.literal("ed25519"),
46621
- address: external_exports.string(),
46622
- path: external_exports.string()
46623
- }).optional()
46624
- }),
46625
- crypto: cryptoSchema
46626
- });
46627
- var encryptedKeysSchema = external_exports.object({
46628
- keys: external_exports.object({
46629
- evm: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
46630
- solana: external_exports.string().optional()
46631
- })
46632
- });
46633
- var encryptedEntropySchema = external_exports.object({ entropy: external_exports.string() });
46592
+ // src/keystore-error.ts
46634
46593
  var KeystoreError = class extends Error {
46635
46594
  constructor(message, options) {
46636
46595
  super(message, options);
46637
46596
  this.name = "KeystoreError";
46638
46597
  }
46639
46598
  };
46640
- function encryptWithKey(key, plaintext) {
46641
- if (key.byteLength !== KEY_LENGTH) {
46642
- throw new Error(`Expected a ${KEY_LENGTH}-byte AES-256-GCM key.`);
46643
- }
46644
- const nonce = randomBytes3(12);
46645
- const cipher = createCipheriv("aes-256-gcm", key, nonce, {
46646
- authTagLength: AUTH_TAG_LENGTH
46647
- });
46648
- const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
46649
- return { nonce, ciphertext, tag: cipher.getAuthTag() };
46650
- }
46651
- function decryptWithKey(key, sealed) {
46652
- if (key.byteLength !== KEY_LENGTH) {
46653
- throw new Error(`Expected a ${KEY_LENGTH}-byte AES-256-GCM key.`);
46654
- }
46655
- if (sealed.nonce.byteLength !== 12) {
46656
- throw new Error("Expected a 12-byte AES-GCM nonce.");
46657
- }
46658
- if (sealed.tag.byteLength !== AUTH_TAG_LENGTH) {
46659
- throw new Error(`Expected a ${AUTH_TAG_LENGTH}-byte AES-GCM authentication tag.`);
46660
- }
46661
- const decipher = createDecipheriv("aes-256-gcm", key, sealed.nonce, {
46662
- authTagLength: AUTH_TAG_LENGTH
46663
- });
46664
- decipher.setAuthTag(sealed.tag);
46665
- return Buffer.concat([decipher.update(sealed.ciphertext), decipher.final()]);
46666
- }
46667
- async function deriveScryptKey(passphrase, salt) {
46668
- return await new Promise((resolve, reject) => {
46669
- scrypt(
46670
- passphrase,
46671
- salt,
46672
- KEY_LENGTH,
46673
- {
46674
- N: SCRYPT_N,
46675
- r: SCRYPT_R,
46676
- p: SCRYPT_P,
46677
- maxmem: SCRYPT_MAX_MEMORY
46678
- },
46679
- (error61, derivedKey) => {
46680
- if (error61) {
46681
- reject(error61);
46682
- return;
46683
- }
46684
- resolve(derivedKey);
46685
- }
46686
- );
46687
- });
46688
- }
46689
- function validatePrivateKey(value) {
46690
- const normalized = value.trim().toLowerCase();
46691
- if (!/^0x[0-9a-f]{64}$/u.test(normalized)) {
46692
- throw new KeystoreError(
46693
- "A private key is 0x followed by 64 hexadecimal characters. Check for a missing character."
46694
- );
46695
- }
46696
- return normalized;
46697
- }
46698
46599
 
46699
46600
  // src/hd.ts
46700
46601
  var EVM_DERIVATION_PATH = "m/44'/60'/0'/0/0";
@@ -46735,7 +46636,7 @@ import { chmod, mkdir as mkdir7, open as open6, readFile as readFile7, readdir a
46735
46636
  import { join as join6 } from "node:path";
46736
46637
 
46737
46638
  // src/account-movement-lock.ts
46738
- import { randomBytes as randomBytes4 } from "node:crypto";
46639
+ import { randomBytes as randomBytes3 } from "node:crypto";
46739
46640
  import { mkdir as mkdir4, open as open3, readFile as readFile4, stat as stat3, unlink as unlink3 } from "node:fs/promises";
46740
46641
  import { join as join5 } from "node:path";
46741
46642
  var AccountMovementLockedError = class extends Error {
@@ -46752,7 +46653,7 @@ async function withAccountMovementLock(home, account, timeoutMs, operation, sign
46752
46653
  await mkdir4(directory, { recursive: true, mode: 448 });
46753
46654
  const path = join5(directory, `.${account}.lock`);
46754
46655
  const deadline = Date.now() + (timeoutMs ?? 2e3);
46755
- const owner = JSON.stringify({ pid: process.pid, token: randomBytes4(16).toString("hex") });
46656
+ const owner = JSON.stringify({ pid: process.pid, token: randomBytes3(16).toString("hex") });
46756
46657
  let handle;
46757
46658
  while (handle === void 0) {
46758
46659
  signal?.throwIfAborted();
@@ -46991,13 +46892,30 @@ var agentSecretAccounts = (wallet) => ({
46991
46892
  routerStake: `vapi.agent.${wallet}.router.stake`,
46992
46893
  routerBalance: `vapi.agent.${wallet}.router.balance`
46993
46894
  });
46895
+ async function withCredentialPublishLock(wallets, wallet, operation) {
46896
+ const digest = createHash("sha256").update(wallet).digest("hex").slice(0, 24);
46897
+ const lockPath = `${wallets.registryPath}.${digest}.agent-publish.lock`;
46898
+ return await withCredentialLockFile(lockPath, operation);
46899
+ }
46994
46900
  async function agentFetch(args, url2, init) {
46901
+ return await agentFetchWithin(args, url2, init, void 0);
46902
+ }
46903
+ async function agentFetchWithin(args, url2, init, signal) {
46995
46904
  const fetchImpl = args.fetchImpl ?? publicFetch;
46996
- const accessToken = await resolveAgentAccessToken(args, {});
46997
- const response = await safeAgentFetch(fetchImpl, url2, withBearer(init, accessToken));
46905
+ const accessToken = await resolveAgentAccessToken(args, { signal });
46906
+ const response = await abortable(
46907
+ signal,
46908
+ () => safeAgentFetch(fetchImpl, url2, withBearer(init, accessToken))
46909
+ );
46998
46910
  if (response.status !== 401) return response;
46999
- const refreshedToken = await resolveAgentAccessToken(args, { rejectedAccessToken: accessToken });
47000
- const refreshedResponse = await safeAgentFetch(fetchImpl, url2, withBearer(init, refreshedToken));
46911
+ const refreshedToken = await resolveAgentAccessToken(args, {
46912
+ rejectedAccessToken: accessToken,
46913
+ signal
46914
+ });
46915
+ const refreshedResponse = await abortable(
46916
+ signal,
46917
+ () => safeAgentFetch(fetchImpl, url2, withBearer(init, refreshedToken))
46918
+ );
47001
46919
  if (refreshedResponse.status === 401) {
47002
46920
  throw new AgentLinkError("not_linked", AGENT_LINK_REVOKED_MESSAGE);
47003
46921
  }
@@ -47015,35 +46933,47 @@ async function resolveAgentAccessToken(args, options) {
47015
46933
  return tokens.accessToken;
47016
46934
  }
47017
46935
  return await withAgentCredentialLock(args.wallets, link3.clientId, async () => {
47018
- await args.wallets.reload();
47019
- const currentLink = args.wallets.entry(args.wallet)?.link;
47020
- if (currentLink === void 0) throw notLinkedError();
47021
- const currentAccounts = agentSecretAccounts(args.wallet);
47022
- const current = parseTokens(await safeGetSecret(args.secrets, currentAccounts.tokens));
47023
- if (current === void 0) throw notLinkedError();
46936
+ options.signal?.throwIfAborted();
46937
+ const { currentLink, currentAccounts, current } = await withCredentialPublishLock(
46938
+ args.wallets,
46939
+ args.wallet,
46940
+ async () => {
46941
+ await args.wallets.reload();
46942
+ const currentLink2 = args.wallets.entry(args.wallet)?.link;
46943
+ if (currentLink2 === void 0) throw notLinkedError();
46944
+ const currentAccounts2 = agentSecretAccounts(args.wallet);
46945
+ const current2 = parseTokens(await safeGetSecret(args.secrets, currentAccounts2.tokens));
46946
+ if (current2 === void 0) throw notLinkedError();
46947
+ return { currentLink: currentLink2, currentAccounts: currentAccounts2, current: current2 };
46948
+ }
46949
+ );
47024
46950
  if (options.rejectedAccessToken !== void 0 && current.accessToken !== options.rejectedAccessToken) {
47025
46951
  return current.accessToken;
47026
46952
  }
47027
46953
  if (options.rejectedAccessToken === void 0 && current.expiresAt - 6e4 > now()) {
47028
46954
  return current.accessToken;
47029
46955
  }
47030
- if (current.refreshToken === void 0) {
46956
+ const refreshToken = current.refreshToken;
46957
+ if (refreshToken === void 0) {
47031
46958
  throw new AgentLinkError("not_linked", REMOTE_AGENT_TOKEN_EXPIRED_MESSAGE);
47032
46959
  }
47033
- const response = await safeFetch(
47034
- args.fetchImpl ?? publicFetch,
47035
- apiEndpoint(currentLink.apiBase, "/oauth/token"),
47036
- {
47037
- method: "POST",
47038
- headers: { "content-type": "application/x-www-form-urlencoded" },
47039
- body: new URLSearchParams({
47040
- grant_type: "refresh_token",
47041
- refresh_token: current.refreshToken,
47042
- client_id: currentLink.clientId
47043
- })
47044
- }
47045
- );
47046
- const payload = await responseRecord(response);
46960
+ const { response, payload } = await abortable(options.signal, async () => {
46961
+ const response2 = await safeFetch(
46962
+ args.fetchImpl ?? publicFetch,
46963
+ apiEndpoint(currentLink.apiBase, "/oauth/token"),
46964
+ {
46965
+ method: "POST",
46966
+ headers: { "content-type": "application/x-www-form-urlencoded" },
46967
+ body: new URLSearchParams({
46968
+ grant_type: "refresh_token",
46969
+ refresh_token: refreshToken,
46970
+ client_id: currentLink.clientId
46971
+ }),
46972
+ ...options.signal === void 0 ? {} : { signal: options.signal }
46973
+ }
46974
+ );
46975
+ return { response: response2, payload: await responseRecord(response2) };
46976
+ });
47047
46977
  if (!response.ok) {
47048
46978
  if (response.status === 400 && stringField(payload, "error") === "invalid_grant") {
47049
46979
  throw new AgentLinkError("not_linked", AGENT_LINK_REVOKED_MESSAGE);
@@ -47052,17 +46982,43 @@ async function resolveAgentAccessToken(args, options) {
47052
46982
  }
47053
46983
  const refreshed = {
47054
46984
  accessToken: requiredString(payload, "access_token"),
47055
- refreshToken: stringField(payload, "refresh_token") ?? current.refreshToken,
46985
+ refreshToken: stringField(payload, "refresh_token") ?? refreshToken,
47056
46986
  expiresAt: now() + requiredNumber(payload, "expires_in") * 1e3,
47057
46987
  scopes: stringField(payload, "scope") === void 0 ? [...current.scopes] : splitScopes(requiredString(payload, "scope"))
47058
46988
  };
47059
- await safeSetSecret(args.secrets, currentAccounts.tokens, JSON.stringify(refreshed));
47060
- return refreshed.accessToken;
46989
+ return await withCredentialPublishLock(args.wallets, args.wallet, async () => {
46990
+ await args.wallets.reload();
46991
+ if (args.wallets.entry(args.wallet)?.link === void 0) throw notLinkedError();
46992
+ const stored = parseTokens(await safeGetSecret(args.secrets, currentAccounts.tokens));
46993
+ if (stored === void 0 || stored.refreshToken !== refreshToken || stored.accessToken !== current.accessToken) {
46994
+ throw notLinkedError();
46995
+ }
46996
+ options.signal?.throwIfAborted();
46997
+ await safeSetSecret(args.secrets, currentAccounts.tokens, JSON.stringify(refreshed));
46998
+ return refreshed.accessToken;
46999
+ });
47061
47000
  });
47062
47001
  }
47002
+ async function abortable(signal, operation) {
47003
+ if (signal === void 0) return await operation();
47004
+ signal.throwIfAborted();
47005
+ let onAbort = () => void 0;
47006
+ const aborted2 = new Promise((_, reject) => {
47007
+ onAbort = () => reject(signal.reason);
47008
+ signal.addEventListener("abort", onAbort, { once: true });
47009
+ });
47010
+ try {
47011
+ return await Promise.race([operation(), aborted2]);
47012
+ } finally {
47013
+ signal.removeEventListener("abort", onAbort);
47014
+ }
47015
+ }
47063
47016
  async function withAgentCredentialLock(wallets, clientId, operation) {
47064
47017
  const digest = createHash("sha256").update(clientId).digest("hex").slice(0, 24);
47065
47018
  const lockPath = `${wallets.registryPath}.${digest}.agent-link.lock`;
47019
+ return await withCredentialLockFile(lockPath, operation);
47020
+ }
47021
+ async function withCredentialLockFile(lockPath, operation) {
47066
47022
  await mkdir5(dirname3(lockPath), { recursive: true, mode: 448 });
47067
47023
  const deadline = Date.now() + 3e4;
47068
47024
  let handle;
@@ -47163,9 +47119,13 @@ async function responseRecord(response) {
47163
47119
  try {
47164
47120
  payload = await response.json();
47165
47121
  } catch {
47122
+ if (!response.ok) return {};
47123
+ throw httpError("The vAPI agent link response was invalid.");
47124
+ }
47125
+ if (!isRecord(payload)) {
47126
+ if (!response.ok) return {};
47166
47127
  throw httpError("The vAPI agent link response was invalid.");
47167
47128
  }
47168
- if (!isRecord(payload)) throw httpError("The vAPI agent link response was invalid.");
47169
47129
  return payload;
47170
47130
  }
47171
47131
  function isRecord(value) {
@@ -47193,6 +47153,131 @@ function splitScopes(scope) {
47193
47153
  return scope.split(/\s+/u).filter(Boolean);
47194
47154
  }
47195
47155
 
47156
+ // src/keystore.ts
47157
+ import { createCipheriv, createDecipheriv, randomBytes as randomBytes4, scrypt } from "node:crypto";
47158
+ var SCRYPT_N = 2 ** 15;
47159
+ var SCRYPT_R = 8;
47160
+ var SCRYPT_P = 1;
47161
+ var KEY_LENGTH = 32;
47162
+ var SCRYPT_MAX_MEMORY = 64 * 1024 * 1024;
47163
+ var AUTH_TAG_LENGTH = 16;
47164
+ var cryptoSchema = external_exports.object({
47165
+ cipher: external_exports.literal("aes-256-gcm"),
47166
+ ciphertext: external_exports.string(),
47167
+ iv: external_exports.string(),
47168
+ authTag: external_exports.string(),
47169
+ kdf: external_exports.literal("scrypt"),
47170
+ salt: external_exports.string(),
47171
+ kdfParams: external_exports.object({
47172
+ n: external_exports.literal(SCRYPT_N),
47173
+ r: external_exports.literal(SCRYPT_R),
47174
+ p: external_exports.literal(SCRYPT_P),
47175
+ dkLen: external_exports.literal(KEY_LENGTH)
47176
+ })
47177
+ });
47178
+ var legacyKeystoreSchema = external_exports.object({
47179
+ version: external_exports.literal(1),
47180
+ address: external_exports.string(),
47181
+ crypto: cryptoSchema
47182
+ });
47183
+ var keystoreSchema = external_exports.object({
47184
+ version: external_exports.literal(2),
47185
+ address: external_exports.string(),
47186
+ keys: external_exports.object({
47187
+ evm: external_exports.object({
47188
+ type: external_exports.literal("secp256k1"),
47189
+ address: external_exports.string()
47190
+ }),
47191
+ solana: external_exports.object({
47192
+ type: external_exports.literal("ed25519"),
47193
+ address: external_exports.string()
47194
+ }).optional()
47195
+ }),
47196
+ crypto: cryptoSchema
47197
+ });
47198
+ var keystoreV3Schema = external_exports.object({
47199
+ version: external_exports.literal(3),
47200
+ address: external_exports.string(),
47201
+ keys: external_exports.object({
47202
+ evm: external_exports.object({
47203
+ type: external_exports.literal("secp256k1"),
47204
+ address: external_exports.string(),
47205
+ path: external_exports.string()
47206
+ }),
47207
+ solana: external_exports.object({
47208
+ type: external_exports.literal("ed25519"),
47209
+ address: external_exports.string(),
47210
+ path: external_exports.string()
47211
+ }).optional()
47212
+ }),
47213
+ crypto: cryptoSchema
47214
+ });
47215
+ var encryptedKeysSchema = external_exports.object({
47216
+ keys: external_exports.object({
47217
+ evm: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
47218
+ solana: external_exports.string().optional()
47219
+ })
47220
+ });
47221
+ var encryptedEntropySchema = external_exports.object({ entropy: external_exports.string() });
47222
+ function encryptWithKey(key, plaintext) {
47223
+ if (key.byteLength !== KEY_LENGTH) {
47224
+ throw new Error(`Expected a ${KEY_LENGTH}-byte AES-256-GCM key.`);
47225
+ }
47226
+ const nonce = randomBytes4(12);
47227
+ const cipher = createCipheriv("aes-256-gcm", key, nonce, {
47228
+ authTagLength: AUTH_TAG_LENGTH
47229
+ });
47230
+ const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
47231
+ return { nonce, ciphertext, tag: cipher.getAuthTag() };
47232
+ }
47233
+ function decryptWithKey(key, sealed) {
47234
+ if (key.byteLength !== KEY_LENGTH) {
47235
+ throw new Error(`Expected a ${KEY_LENGTH}-byte AES-256-GCM key.`);
47236
+ }
47237
+ if (sealed.nonce.byteLength !== 12) {
47238
+ throw new Error("Expected a 12-byte AES-GCM nonce.");
47239
+ }
47240
+ if (sealed.tag.byteLength !== AUTH_TAG_LENGTH) {
47241
+ throw new Error(`Expected a ${AUTH_TAG_LENGTH}-byte AES-GCM authentication tag.`);
47242
+ }
47243
+ const decipher = createDecipheriv("aes-256-gcm", key, sealed.nonce, {
47244
+ authTagLength: AUTH_TAG_LENGTH
47245
+ });
47246
+ decipher.setAuthTag(sealed.tag);
47247
+ return Buffer.concat([decipher.update(sealed.ciphertext), decipher.final()]);
47248
+ }
47249
+ async function deriveScryptKey(passphrase, salt) {
47250
+ return await new Promise((resolve, reject) => {
47251
+ scrypt(
47252
+ passphrase,
47253
+ salt,
47254
+ KEY_LENGTH,
47255
+ {
47256
+ N: SCRYPT_N,
47257
+ r: SCRYPT_R,
47258
+ p: SCRYPT_P,
47259
+ maxmem: SCRYPT_MAX_MEMORY
47260
+ },
47261
+ (error61, derivedKey) => {
47262
+ if (error61) {
47263
+ reject(error61);
47264
+ return;
47265
+ }
47266
+ resolve(derivedKey);
47267
+ }
47268
+ );
47269
+ });
47270
+ }
47271
+ function validatePrivateKey(value) {
47272
+ const normalized = value.trim().toLowerCase();
47273
+ if (!/^0x[0-9a-f]{64}$/u.test(normalized)) {
47274
+ throw new KeystoreError(
47275
+ "A private key is 0x followed by 64 hexadecimal characters. Check for a missing character."
47276
+ );
47277
+ }
47278
+ return normalized;
47279
+ }
47280
+
47196
47281
  // src/movement-open.ts
47197
47282
  function isOpenMovementLeg(leg, journalEvidence) {
47198
47283
  if (leg.status === "sent" || leg.status === "cancelled") return false;
@@ -48074,6 +48159,35 @@ var routerRefillSchema = external_exports.object({
48074
48159
  belowUsd: external_exports.number().finite().min(0),
48075
48160
  tierUsd: external_exports.union([external_exports.literal(1), external_exports.literal(5), external_exports.literal(20), external_exports.literal(50)])
48076
48161
  });
48162
+ var routerPendingPurchaseSchema = external_exports.strictObject({
48163
+ receiptId: external_exports.string().min(1),
48164
+ status: external_exports.enum(["prepared", "signed", "settled", "unknown"]),
48165
+ createdAt: external_exports.iso.datetime(),
48166
+ tierUsd: external_exports.union([external_exports.literal(1), external_exports.literal(5), external_exports.literal(20), external_exports.literal(50)]),
48167
+ link: agentLinkSchema,
48168
+ baselinePurchasedUsd: external_exports.number().finite().nonnegative().optional(),
48169
+ network: external_exports.string().min(1).optional(),
48170
+ amountAtomic: external_exports.string().regex(/^\d+$/u).optional(),
48171
+ transaction: external_exports.string().optional(),
48172
+ authorization: external_exports.strictObject({
48173
+ token: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u),
48174
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u),
48175
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u),
48176
+ validBefore: external_exports.string().regex(/^\d+$/u)
48177
+ }).optional()
48178
+ }).superRefine((pending, context) => {
48179
+ if (pending.status === "signed" && (pending.authorization === void 0 || pending.network === void 0)) {
48180
+ context.addIssue({
48181
+ code: "custom",
48182
+ message: "Signed purchases require public authorization evidence."
48183
+ });
48184
+ }
48185
+ });
48186
+ var routerPurchaseStateSchema = external_exports.strictObject({
48187
+ version: external_exports.literal(1),
48188
+ pending: routerPendingPurchaseSchema.optional(),
48189
+ completedReceiptId: external_exports.string().optional()
48190
+ });
48077
48191
  var ceilingSweepPendingSchema = external_exports.strictObject({
48078
48192
  owner: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
48079
48193
  target: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/).optional(),
@@ -48092,6 +48206,7 @@ var walletEntrySchema = external_exports.object({
48092
48206
  ceilingSweepAttemptedAt: external_exports.iso.datetime().optional(),
48093
48207
  ceilingSweepPending: ceilingSweepPendingSchema.optional(),
48094
48208
  routerRefill: routerRefillSchema.optional(),
48209
+ routerPendingPurchase: routerPendingPurchaseSchema.optional(),
48095
48210
  link: agentLinkSchema.optional()
48096
48211
  });
48097
48212
  var walletRegistrySchema = external_exports.object({
@@ -49082,7 +49197,7 @@ async function exportBackupSourceAttempt(options, networks) {
49082
49197
  registry: {
49083
49198
  ...snapshot.default !== void 0 && names.has(snapshot.default) ? { default: snapshot.default } : {},
49084
49199
  accounts: accounts.map((account) => {
49085
- const entry = snapshot.wallets[account.name];
49200
+ const entry = Object.hasOwn(snapshot.wallets, account.name) ? snapshot.wallets[account.name] : void 0;
49086
49201
  const ceilingAtomic = entry?.ceilingAtomic === null ? null : entry?.ceilingAtomic ?? DEFAULT_CEILING_ATOMIC.toString();
49087
49202
  return {
49088
49203
  name: account.name,