@vapi-network/core 0.12.1 → 0.14.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.
package/dist/index.js CHANGED
@@ -3511,6 +3511,9 @@ function carry(digits) {
3511
3511
  }
3512
3512
  return `1${out.join("")}`;
3513
3513
  }
3514
+ function fromGwei(gwei, unit = "wei") {
3515
+ return from(gwei, exponents.gwei - exponents[unit]);
3516
+ }
3514
3517
  var exponents, InvalidDecimalNumberError, InvalidDecimalsError;
3515
3518
  var init_Value = __esm({
3516
3519
  "../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/utils/unit/Value.js"() {
@@ -6603,7 +6606,7 @@ function weierstrass(curveDef) {
6603
6606
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
6604
6607
  if (["recovered", "canonical"].some((k) => k in opts))
6605
6608
  throw new Error("sign() legacy options not supported");
6606
- const { hash: hash4, randomBytes: randomBytes16 } = CURVE;
6609
+ const { hash: hash4, randomBytes: randomBytes17 } = CURVE;
6607
6610
  let { lowS, prehash, extraEntropy: ent } = opts;
6608
6611
  if (lowS == null)
6609
6612
  lowS = true;
@@ -6615,7 +6618,7 @@ function weierstrass(curveDef) {
6615
6618
  const d = normPrivateKeyToScalar(privateKey);
6616
6619
  const seedArgs = [int2octets(d), int2octets(h1int)];
6617
6620
  if (ent != null && ent !== false) {
6618
- const e3 = ent === true ? randomBytes16(Fp.BYTES) : ent;
6621
+ const e3 = ent === true ? randomBytes17(Fp.BYTES) : ent;
6619
6622
  seedArgs.push(ensureBytes("extraEntropy", e3));
6620
6623
  }
6621
6624
  const seed = concatBytes3(...seedArgs);
@@ -35471,6 +35474,12 @@ function formatUnits(value, decimals) {
35471
35474
  return format(value, decimals);
35472
35475
  }
35473
35476
 
35477
+ // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/utils/unit/parseGwei.js
35478
+ init_Value();
35479
+ function parseGwei(ether, unit = "wei") {
35480
+ return fromGwei(ether, unit);
35481
+ }
35482
+
35474
35483
  // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/utils/unit/parseUnits.js
35475
35484
  init_Value();
35476
35485
  function parseUnits(value, decimals) {
@@ -35614,7 +35623,7 @@ init_createBatchScheduler();
35614
35623
  init_stringify();
35615
35624
  async function multicall(client, parameters) {
35616
35625
  const { account, authorizationList, allowFailure = true, blockHash, blockNumber, blockOverrides, blockTag, requireCanonical, stateOverride } = parameters;
35617
- const contracts = parameters.contracts;
35626
+ const contracts2 = parameters.contracts;
35618
35627
  const batch = typeof client.batch?.multicall === "object" ? client.batch.multicall : {};
35619
35628
  const batchSize = parameters.batchSize ?? batch.batchSize ?? 1024;
35620
35629
  const deployless = parameters.deployless ?? batch.deployless ?? false;
@@ -35635,8 +35644,8 @@ async function multicall(client, parameters) {
35635
35644
  const chunkedCalls = [[]];
35636
35645
  let currentChunk = 0;
35637
35646
  let currentChunkSize = 0;
35638
- for (let i = 0; i < contracts.length; i++) {
35639
- const { abi: abi2, address: address2, args, functionName } = contracts[i];
35647
+ for (let i = 0; i < contracts2.length; i++) {
35648
+ const { abi: abi2, address: address2, args, functionName } = contracts2[i];
35640
35649
  try {
35641
35650
  const callData = encodeFunctionData({ abi: abi2, args, functionName });
35642
35651
  currentChunkSize += (callData.length - 2) / 2;
@@ -35730,7 +35739,7 @@ async function multicall(client, parameters) {
35730
35739
  for (let j = 0; j < aggregate3Result.length; j++) {
35731
35740
  const { returnData, success: success2 } = aggregate3Result[j];
35732
35741
  const { callData } = batches[i][j];
35733
- const { abi: abi2, address: address2, functionName, args } = contracts[results.length];
35742
+ const { abi: abi2, address: address2, functionName, args } = contracts2[results.length];
35734
35743
  try {
35735
35744
  if (callData === "0x")
35736
35745
  throw new AbiDecodingZeroDataError();
@@ -35757,7 +35766,7 @@ async function multicall(client, parameters) {
35757
35766
  }
35758
35767
  }
35759
35768
  }
35760
- if (results.length !== contracts.length)
35769
+ if (results.length !== contracts2.length)
35761
35770
  throw new BaseError2("multicall results mismatch");
35762
35771
  return results;
35763
35772
  }
@@ -38705,6 +38714,7 @@ init_isAddress();
38705
38714
  init_toBytes();
38706
38715
  init_toHex();
38707
38716
  init_keccak256();
38717
+ init_formatEther();
38708
38718
 
38709
38719
  // src/x402-networks.ts
38710
38720
  var BASE_MAINNET_CAIP2 = "eip155:8453";
@@ -44676,9 +44686,9 @@ var X402Error = class extends Error {
44676
44686
  function isValidPaymentId(value) {
44677
44687
  return typeof value === "string" && PAYMENT_ID_PATTERN.test(value);
44678
44688
  }
44679
- function createPaymentId(randomBytes16 = fillRandomBytes) {
44689
+ function createPaymentId(randomBytes17 = fillRandomBytes) {
44680
44690
  const bytes = new Uint8Array(16);
44681
- randomBytes16(bytes);
44691
+ randomBytes17(bytes);
44682
44692
  return `pay_${bytesToHex(bytes).slice(2)}`;
44683
44693
  }
44684
44694
  function buildPaymentExtensions(serverExtensions, options = {}) {
@@ -45757,6 +45767,143 @@ function rawServiceId(raw, serviceIndex) {
45757
45767
  return typeof id === "string" ? id : void 0;
45758
45768
  }
45759
45769
 
45770
+ // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/op-stack/contracts.js
45771
+ var contracts = {
45772
+ gasPriceOracle: { address: "0x420000000000000000000000000000000000000F" },
45773
+ l1Block: { address: "0x4200000000000000000000000000000000000015" },
45774
+ l2CrossDomainMessenger: {
45775
+ address: "0x4200000000000000000000000000000000000007"
45776
+ },
45777
+ l2Erc721Bridge: { address: "0x4200000000000000000000000000000000000014" },
45778
+ l2StandardBridge: { address: "0x4200000000000000000000000000000000000010" },
45779
+ l2ToL1MessagePasser: {
45780
+ address: "0x4200000000000000000000000000000000000016"
45781
+ }
45782
+ };
45783
+
45784
+ // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/op-stack/abis.js
45785
+ var gasPriceOracleAbi = [
45786
+ { inputs: [], stateMutability: "nonpayable", type: "constructor" },
45787
+ {
45788
+ inputs: [],
45789
+ name: "DECIMALS",
45790
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45791
+ stateMutability: "view",
45792
+ type: "function"
45793
+ },
45794
+ {
45795
+ inputs: [],
45796
+ name: "baseFee",
45797
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45798
+ stateMutability: "view",
45799
+ type: "function"
45800
+ },
45801
+ {
45802
+ inputs: [],
45803
+ name: "decimals",
45804
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45805
+ stateMutability: "pure",
45806
+ type: "function"
45807
+ },
45808
+ {
45809
+ inputs: [],
45810
+ name: "gasPrice",
45811
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45812
+ stateMutability: "view",
45813
+ type: "function"
45814
+ },
45815
+ {
45816
+ inputs: [{ internalType: "bytes", name: "_data", type: "bytes" }],
45817
+ name: "getL1Fee",
45818
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45819
+ stateMutability: "view",
45820
+ type: "function"
45821
+ },
45822
+ {
45823
+ inputs: [{ internalType: "bytes", name: "_data", type: "bytes" }],
45824
+ name: "getL1GasUsed",
45825
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45826
+ stateMutability: "view",
45827
+ type: "function"
45828
+ },
45829
+ {
45830
+ inputs: [{ internalType: "uint256", name: "_gasUsed", type: "uint256" }],
45831
+ name: "getOperatorFee",
45832
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45833
+ stateMutability: "view",
45834
+ type: "function"
45835
+ },
45836
+ {
45837
+ inputs: [],
45838
+ name: "isJovian",
45839
+ outputs: [{ internalType: "bool", name: "", type: "bool" }],
45840
+ stateMutability: "view",
45841
+ type: "function"
45842
+ },
45843
+ {
45844
+ inputs: [],
45845
+ name: "l1BaseFee",
45846
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45847
+ stateMutability: "view",
45848
+ type: "function"
45849
+ },
45850
+ {
45851
+ inputs: [],
45852
+ name: "overhead",
45853
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45854
+ stateMutability: "view",
45855
+ type: "function"
45856
+ },
45857
+ {
45858
+ inputs: [],
45859
+ name: "scalar",
45860
+ outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
45861
+ stateMutability: "view",
45862
+ type: "function"
45863
+ },
45864
+ {
45865
+ inputs: [],
45866
+ name: "version",
45867
+ outputs: [{ internalType: "string", name: "", type: "string" }],
45868
+ stateMutability: "view",
45869
+ type: "function"
45870
+ }
45871
+ ];
45872
+
45873
+ // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/op-stack/actions/estimateL1Fee.js
45874
+ init_getChainContractAddress();
45875
+ async function estimateL1Fee(client, args) {
45876
+ const { chain: chain2 = client.chain, gasPriceOracleAddress: gasPriceOracleAddress_ } = args;
45877
+ const gasPriceOracleAddress = (() => {
45878
+ if (gasPriceOracleAddress_)
45879
+ return gasPriceOracleAddress_;
45880
+ if (chain2)
45881
+ return getChainContractAddress({
45882
+ chain: chain2,
45883
+ contract: "gasPriceOracle"
45884
+ });
45885
+ return contracts.gasPriceOracle.address;
45886
+ })();
45887
+ const transaction = serializeTransaction({
45888
+ ...args,
45889
+ chainId: chain2?.id ?? 1,
45890
+ type: "eip1559",
45891
+ // Set upper-limit-ish stub values. Shouldn't affect the estimate too much as we are
45892
+ // tweaking dust bytes here (as opposed to long `data` bytes).
45893
+ // See: https://github.com/ethereum-optimism/optimism/blob/54d02df55523c9e1b4b38ed082c12a42087323a0/packages/contracts-bedrock/src/L2/GasPriceOracle.sol#L242-L248.
45894
+ gas: args.data ? 300000n : 21000n,
45895
+ maxFeePerGas: parseGwei("5"),
45896
+ maxPriorityFeePerGas: parseGwei("1"),
45897
+ nonce: 1
45898
+ });
45899
+ return readContract(client, {
45900
+ abi: gasPriceOracleAbi,
45901
+ address: gasPriceOracleAddress,
45902
+ functionName: "getL1Fee",
45903
+ args: [transaction]
45904
+ });
45905
+ }
45906
+
45760
45907
  // src/sweep.ts
45761
45908
  var ERC20_ABI = [
45762
45909
  {
@@ -45915,6 +46062,100 @@ async function sweepBack(args) {
45915
46062
  transaction
45916
46063
  };
45917
46064
  }
46065
+ var NATIVE_ETH_L1_FEE_FALLBACK_WEI = 10000000000000n;
46066
+ var NATIVE_ETH_FEE_MARGIN_PERCENT = 20n;
46067
+ function supportsNativeEthSweep(network) {
46068
+ return network === BASE_MAINNET_CAIP2 || network === "eip155:84532";
46069
+ }
46070
+ async function sweepNativeEth(args) {
46071
+ const configured = configuredNetworkFor(args.config.networks, args.network);
46072
+ if (!configured) throw new Error(`Network ${args.network} is not configured.`);
46073
+ if (isSolanaNetwork(args.network)) {
46074
+ throw new Error("Solana has no native ETH; use vapi sweep --asset usdc.");
46075
+ }
46076
+ if (usesUsdcGas(args.network)) {
46077
+ throw new Error("Arc has no native ETH; use vapi sweep --asset usdc.");
46078
+ }
46079
+ if (!supportsNativeEthSweep(args.network)) {
46080
+ throw new Error("Native ETH sweeps are supported only on Base mainnet and Base Sepolia.");
46081
+ }
46082
+ const rpcUrl = requireRpcUrl(args.network, configured);
46083
+ const chain2 = createChain(args.network, rpcUrl);
46084
+ const options = {
46085
+ allowPrivateNetwork: args.config.allowPrivateNetwork,
46086
+ ...args.fetchImpl ? { fetch: args.fetchImpl } : {},
46087
+ ...args.lookup ? { lookup: args.lookup } : {}
46088
+ };
46089
+ const publicClient = createNetworkPublicClient(args.network, configured, options);
46090
+ const to = getAddress(args.destination);
46091
+ const balance = await publicClient.getBalance({ address: args.account.address });
46092
+ const estimateTransferGas = async (value) => {
46093
+ try {
46094
+ return await publicClient.estimateGas({ account: args.account.address, to, value });
46095
+ } catch (error61) {
46096
+ const code = await publicClient.getCode({ address: to });
46097
+ if (code && code !== "0x") throw error61;
46098
+ return 21000n;
46099
+ }
46100
+ };
46101
+ let gas = await estimateTransferGas(1n);
46102
+ const { maxFeePerGas, maxPriorityFeePerGas } = await publicClient.estimateFeesPerGas();
46103
+ let l1Fee;
46104
+ try {
46105
+ l1Fee = await estimateL1Fee(publicClient, {
46106
+ chain: chain2,
46107
+ account: args.account.address,
46108
+ to,
46109
+ value: balance,
46110
+ gas,
46111
+ maxFeePerGas,
46112
+ maxPriorityFeePerGas,
46113
+ gasPriceOracleAddress: "0x420000000000000000000000000000000000000F"
46114
+ });
46115
+ } catch {
46116
+ l1Fee = NATIVE_ETH_L1_FEE_FALLBACK_WEI;
46117
+ }
46118
+ let amount = 0n;
46119
+ let validated = false;
46120
+ for (let attempt = 0; attempt < 5; attempt += 1) {
46121
+ const fee = (maxFeePerGas * gas + l1Fee) * (100n + NATIVE_ETH_FEE_MARGIN_PERCENT) / 100n;
46122
+ amount = balance - fee;
46123
+ if (amount <= 0n) {
46124
+ const name = getNetworkDefinition(args.network).name;
46125
+ throw new Error(
46126
+ `The ETH balance on ${name} (${formatEther2(balance)} ETH) is too small to cover the ${name} network fee.`
46127
+ );
46128
+ }
46129
+ const requiredGas = await estimateTransferGas(amount);
46130
+ if (requiredGas <= gas) {
46131
+ validated = true;
46132
+ break;
46133
+ }
46134
+ gas = requiredGas;
46135
+ }
46136
+ if (!validated) {
46137
+ throw new Error(
46138
+ "Could not safely estimate gas for the ETH withdrawal; no transaction was sent."
46139
+ );
46140
+ }
46141
+ const walletClient = createWalletClient({
46142
+ account: args.account,
46143
+ chain: chain2,
46144
+ transport: createNetworkHttpTransport(rpcUrl, options)
46145
+ });
46146
+ const transaction = await walletClient.sendTransaction({
46147
+ to,
46148
+ value: amount,
46149
+ gas,
46150
+ maxFeePerGas,
46151
+ maxPriorityFeePerGas
46152
+ });
46153
+ const receipt = await publicClient.waitForTransactionReceipt({ hash: transaction });
46154
+ if (receipt.status !== "success") {
46155
+ throw new Error(`Sweep transaction ${transaction} reverted on ${args.network}.`);
46156
+ }
46157
+ return { network: args.network, amountAtomic: amount.toString(), transaction };
46158
+ }
45918
46159
  function isInsufficientGasError(error61) {
45919
46160
  const seen = /* @__PURE__ */ new Set();
45920
46161
  let current = error61;
@@ -46082,8 +46323,8 @@ function conciseError(error61) {
46082
46323
  }
46083
46324
 
46084
46325
  // src/account-add.ts
46085
- import { stat as stat8 } from "node:fs/promises";
46086
- import { join as join9 } from "node:path";
46326
+ import { stat as stat10 } from "node:fs/promises";
46327
+ import { join as join10 } from "node:path";
46087
46328
 
46088
46329
  // src/agent-link.ts
46089
46330
  import { createHash } from "node:crypto";
@@ -69588,20 +69829,20 @@ async function promptForSecret(prompt, noTerminalHint) {
69588
69829
  }
69589
69830
 
69590
69831
  // src/wallet-store.ts
69591
- import { randomBytes as randomBytes8 } from "node:crypto";
69832
+ import { randomBytes as randomBytes9 } from "node:crypto";
69592
69833
  import {
69593
69834
  chmod as chmod3,
69594
69835
  lstat as lstat2,
69595
69836
  mkdir as mkdir10,
69596
- open as open7,
69837
+ open as open8,
69597
69838
  readdir as readdir3,
69598
- readFile as readFile11,
69839
+ readFile as readFile12,
69599
69840
  rename as rename7,
69600
- stat as stat7,
69841
+ stat as stat9,
69601
69842
  unlink as unlink6,
69602
69843
  writeFile as writeFile5
69603
69844
  } from "node:fs/promises";
69604
- import { dirname as dirname7, join as join8 } from "node:path";
69845
+ import { dirname as dirname7, join as join9 } from "node:path";
69605
69846
 
69606
69847
  // src/account-movement-lock.ts
69607
69848
  import { randomBytes as randomBytes4 } from "node:crypto";
@@ -69719,1358 +69960,1594 @@ function isOpenMovementLeg(leg, journalEvidence) {
69719
69960
  // src/secret-store.ts
69720
69961
  import { spawn } from "node:child_process";
69721
69962
  import { existsSync } from "node:fs";
69722
- import { delimiter, isAbsolute, join as join6, win32 } from "node:path";
69723
- var SECRET_STORE_SERVICE = "vapi-network";
69724
- var SECURITY_BINARY = "/usr/bin/security";
69725
- var SECRET_TOOL_BINARY = "secret-tool";
69726
- var WINDOWS_POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-Command", "-"];
69727
- var SECURITY_ITEM_NOT_FOUND = 44;
69728
- var WINDOWS_SECRET_SUCCESS = 0;
69729
- var WINDOWS_SECRET_NOT_FOUND = 2;
69730
- var UNSUPPORTED_PLATFORM = "No OS secret store on this platform yet; use VAPI_KEYSTORE_PASSWORD.";
69731
- var SECRET_TOOL_MISSING = [
69732
- "secret-tool is not installed, so the passphrase cannot be kept in the OS secret store.",
69733
- "Install libsecret-tools (Debian, Ubuntu) or libsecret (Fedora, Arch), or use VAPI_KEYSTORE_PASSWORD."
69734
- ].join(" ");
69735
- var POWERSHELL_MISSING = [
69736
- "Windows PowerShell (powershell.exe) was not found, so the passphrase cannot be kept in the OS secret store.",
69737
- "Use VAPI_KEYSTORE_PASSWORD."
69738
- ].join(" ");
69739
- function secretStore(options = {}) {
69740
- const platform2 = options.platform ?? process.platform;
69741
- const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
69742
- const env = options.env ?? process.env;
69743
- const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
69744
- if (platform2 === "darwin") return keychainStore(platform2, run);
69745
- if (platform2 === "win32") return windowsDataProtectionStore(platform2, run, env, installed);
69746
- if (platform2 === "linux") return libsecretStore(platform2, run, installed);
69747
- return unsupportedStore(platform2);
69963
+ import { delimiter, isAbsolute, join as join7, win32 } from "node:path";
69964
+
69965
+ // src/file-secret-store.ts
69966
+ import { randomBytes as randomBytes6 } from "node:crypto";
69967
+ import { readFile as readFile8, stat as stat7 } from "node:fs/promises";
69968
+
69969
+ // src/vault.ts
69970
+ import { randomBytes as randomBytes5 } from "node:crypto";
69971
+ import { mkdir as mkdir7, open as open5, readFile as readFile7, rename as rename4, rm, stat as stat6, unlink as unlink4, writeFile as writeFile3 } from "node:fs/promises";
69972
+ import { dirname as dirname5 } from "node:path";
69973
+
69974
+ // src/wallet-name.ts
69975
+ var DEFAULT_WALLET_NAME = "main";
69976
+ var WALLET_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
69977
+ var walletNameSchema = external_exports.string().regex(
69978
+ WALLET_NAME_PATTERN,
69979
+ "A wallet name is 1 to 32 characters of lowercase letters, digits and dashes, starting with a letter or digit."
69980
+ );
69981
+ function isWalletName(value) {
69982
+ return WALLET_NAME_PATTERN.test(value);
69748
69983
  }
69749
- function memorySecretStore(initial = {}) {
69750
- const entries = new Map(Object.entries(initial));
69751
- return {
69752
- available: true,
69753
- platform: process.platform,
69754
- description: "an in-memory store",
69755
- async get(name) {
69756
- return entries.get(name);
69757
- },
69758
- async has(name) {
69759
- return entries.has(name);
69760
- },
69761
- async set(name, passphrase) {
69762
- entries.set(name, passphrase);
69763
- },
69764
- async remove(name) {
69765
- return entries.delete(name);
69766
- },
69767
- async list() {
69768
- return [...entries.keys()].sort();
69984
+
69985
+ // src/vault.ts
69986
+ var VaultError = class extends Error {
69987
+ code;
69988
+ constructor(code, message, options) {
69989
+ super(message, options);
69990
+ this.name = "VaultError";
69991
+ this.code = code;
69992
+ }
69993
+ };
69994
+ var SEALED_FIELD_PATTERN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/u;
69995
+ var WRAPPED_KEY_PATTERN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/u;
69996
+ var ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/u;
69997
+ var VAULT_LOCK_TIMEOUT_MS = 2e3;
69998
+ var STALE_VAULT_LOCK_MS = 3e4;
69999
+ var sealedFieldSchema = external_exports.string().regex(SEALED_FIELD_PATTERN);
70000
+ var addressSchema = external_exports.string().regex(ADDRESS_PATTERN);
70001
+ var accountFields = {
70002
+ name: walletNameSchema,
70003
+ address: addressSchema,
70004
+ createdAt: external_exports.string()
70005
+ };
70006
+ var storedAccountSchema = external_exports.discriminatedUnion("kind", [
70007
+ external_exports.object({
70008
+ ...accountFields,
70009
+ kind: external_exports.literal("derived"),
70010
+ index: external_exports.number().int().nonnegative().refine(Number.isSafeInteger, "Derived account index must be a safe integer.")
70011
+ }).strict(),
70012
+ external_exports.object({
70013
+ ...accountFields,
70014
+ kind: external_exports.literal("imported"),
70015
+ key: sealedFieldSchema
70016
+ }).strict()
70017
+ ]);
70018
+ var vaultFileSchema = external_exports.object({
70019
+ version: external_exports.literal(2),
70020
+ kdf: external_exports.literal("device-key"),
70021
+ cipher: external_exports.literal("aes-256-gcm"),
70022
+ phrase: sealedFieldSchema,
70023
+ accounts: external_exports.array(storedAccountSchema),
70024
+ nextDerivedIndex: external_exports.number().int().nonnegative().refine(Number.isSafeInteger, "Next derived account index must be a safe integer.").optional(),
70025
+ protected: external_exports.boolean(),
70026
+ wrappedKey: external_exports.string().regex(WRAPPED_KEY_PATTERN).optional()
70027
+ }).strict();
70028
+ var DeviceVault = class {
70029
+ file;
70030
+ path;
70031
+ key;
70032
+ balanceOf;
70033
+ now;
70034
+ constructor(options, file2) {
70035
+ this.path = options.path;
70036
+ this.key = options.key;
70037
+ this.balanceOf = options.balanceOf;
70038
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
70039
+ this.file = file2;
70040
+ }
70041
+ accounts() {
70042
+ return this.file.accounts.map(copyAccount);
70043
+ }
70044
+ async deriveAccount(name) {
70045
+ try {
70046
+ return await this.update(async (file2) => {
70047
+ assertAvailableName(file2, name);
70048
+ const index2 = nextDerivedIndex(file2);
70049
+ const plaintext = decryptField(this.key, file2.phrase);
70050
+ let seed;
70051
+ let address2;
70052
+ try {
70053
+ seed = phraseToSeed(plaintext.toString("utf8"));
70054
+ address2 = privateKeyToAccount(
70055
+ deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${index2}`)
70056
+ ).address;
70057
+ } finally {
70058
+ seed?.fill(0);
70059
+ plaintext.fill(0);
70060
+ }
70061
+ const account = {
70062
+ name,
70063
+ kind: "derived",
70064
+ index: index2,
70065
+ address: address2,
70066
+ createdAt: this.now().toISOString()
70067
+ };
70068
+ file2.accounts.push(account);
70069
+ file2.nextDerivedIndex = index2 + 1;
70070
+ return copyAccount(account);
70071
+ });
70072
+ } catch (error61) {
70073
+ throw asVaultError(error61, "corrupt", "Unable to derive a vault account.");
69769
70074
  }
69770
- };
69771
- }
69772
- function keychainStore(platform2, run) {
69773
- const find = async (account, withPassword) => await run(SECURITY_BINARY, [
69774
- "find-generic-password",
69775
- "-a",
69776
- account,
69777
- "-s",
69778
- SECRET_STORE_SERVICE,
69779
- ...withPassword ? ["-w"] : []
69780
- ]);
69781
- const read = async (account, what) => {
69782
- const result = await find(account, true);
69783
- if (result.code === SECURITY_ITEM_NOT_FOUND) return void 0;
69784
- requireSuccess(result, what);
69785
- const value = withoutTrailingNewline(result.stdout);
69786
- return value.length === 0 ? void 0 : value;
69787
- };
69788
- const write = async (account, value, what) => {
69789
- const result = await run(
69790
- SECURITY_BINARY,
69791
- [
69792
- "add-generic-password",
69793
- "-a",
69794
- account,
69795
- "-s",
69796
- SECRET_STORE_SERVICE,
69797
- "-l",
69798
- `${SECRET_STORE_SERVICE} ${account}`,
69799
- "-U",
69800
- "-w"
69801
- ],
69802
- // `security` asks for the password and then for its confirmation.
69803
- `${value}
69804
- ${value}
69805
- `
69806
- );
69807
- requireSuccess(result, what);
69808
- };
69809
- const erase = async (account, what) => {
69810
- const result = await run(SECURITY_BINARY, [
69811
- "delete-generic-password",
69812
- "-a",
69813
- account,
69814
- "-s",
69815
- SECRET_STORE_SERVICE
69816
- ]);
69817
- if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
69818
- requireSuccess(result, what);
69819
- return true;
69820
- };
69821
- const erasePartsAfter = async (account, keep, what) => {
69822
- for (let part = keep + 1; part <= MAX_KEYCHAIN_PARTS; part += 1) {
69823
- if (!await erase(keychainPart(account, part), what)) return;
70075
+ }
70076
+ async importAccount(name, privateKey) {
70077
+ try {
70078
+ return await this.update(async (file2) => {
70079
+ assertAvailableName(file2, name);
70080
+ let validated;
70081
+ let address2;
70082
+ try {
70083
+ validated = validatePrivateKey(privateKey);
70084
+ address2 = privateKeyToAccount(validated).address;
70085
+ } catch (error61) {
70086
+ throw new VaultError("bad_key", "The imported private key is not valid.", {
70087
+ cause: error61
70088
+ });
70089
+ }
70090
+ const plaintext = Buffer.from(validated.slice(2), "hex");
70091
+ let account;
70092
+ try {
70093
+ account = {
70094
+ name,
70095
+ kind: "imported",
70096
+ address: address2,
70097
+ key: sealField(this.key, plaintext),
70098
+ createdAt: this.now().toISOString()
70099
+ };
70100
+ } finally {
70101
+ plaintext.fill(0);
70102
+ }
70103
+ file2.accounts.push(account);
70104
+ return copyAccount(account);
70105
+ });
70106
+ } catch (error61) {
70107
+ throw asVaultError(error61, "corrupt", "Unable to import a vault account.");
69824
70108
  }
69825
- };
69826
- return {
69827
- available: true,
69828
- platform: platform2,
69829
- description: "the macOS Keychain",
69830
- async get(name) {
69831
- const account = accountFor(name);
69832
- const what = `read the passphrase of ${name} from the macOS Keychain`;
69833
- const value = await read(account, what);
69834
- const parts = value === void 0 ? void 0 : chunkedPartCount(value);
69835
- if (value === void 0 || parts === void 0) return value;
69836
- let joined = "";
69837
- for (let part = 1; part <= parts; part += 1) {
69838
- const chunk = await read(keychainPart(account, part), what);
69839
- if (chunk === void 0) {
69840
- throw new KeystoreError(
69841
- `The stored secret ${name} is incomplete in the macOS Keychain. Store it again.`
70109
+ }
70110
+ async removeAccount(name) {
70111
+ try {
70112
+ await this.update(async (file2) => {
70113
+ const account = file2.accounts.find((candidate) => candidate.name === name);
70114
+ if (!account) {
70115
+ throw new VaultError("not_found", "No vault account has that name.");
70116
+ }
70117
+ if (!this.balanceOf) {
70118
+ throw new VaultError(
70119
+ "has_balance",
70120
+ "The account balance could not be verified, so the key was not removed."
69842
70121
  );
69843
70122
  }
69844
- joined += chunk;
69845
- }
69846
- return joined;
69847
- },
69848
- async has(name) {
69849
- const result = await find(accountFor(name), false);
69850
- if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
69851
- requireSuccess(result, `look up ${name} in the macOS Keychain`);
69852
- return true;
69853
- },
69854
- async set(name, passphrase) {
69855
- requirePassphrase(passphrase);
69856
- const account = accountFor(name);
69857
- const what = `store the passphrase of ${name} in the macOS Keychain`;
69858
- if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
69859
- await write(account, passphrase, what);
69860
- return;
69861
- }
69862
- const chunks = [];
69863
- for (let index2 = 0; index2 < passphrase.length; index2 += KEYCHAIN_CHUNK) {
69864
- chunks.push(passphrase.slice(index2, index2 + KEYCHAIN_CHUNK));
69865
- }
69866
- if (chunks.length > MAX_KEYCHAIN_PARTS) {
69867
- throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
70123
+ if (await this.balanceOf(account.address) > 0n) {
70124
+ throw new VaultError(
70125
+ "has_balance",
70126
+ "This account still has a balance. Run vapi sweep before removing it."
70127
+ );
70128
+ }
70129
+ file2.nextDerivedIndex = nextDerivedIndex(file2);
70130
+ const currentIndex = file2.accounts.findIndex((candidate) => candidate.name === name);
70131
+ if (currentIndex === -1) {
70132
+ throw new VaultError("not_found", "No vault account has that name.");
70133
+ }
70134
+ file2.accounts.splice(currentIndex, 1);
70135
+ });
70136
+ } catch (error61) {
70137
+ throw asVaultError(error61, "corrupt", "Unable to remove the vault account.");
70138
+ }
70139
+ }
70140
+ async rename(from16, to) {
70141
+ try {
70142
+ await this.update(async (file2) => {
70143
+ const account = file2.accounts.find((candidate) => candidate.name === from16);
70144
+ if (!account) {
70145
+ throw new VaultError("not_found", "No vault account has that name.");
70146
+ }
70147
+ if (from16 === to) return;
70148
+ assertAccountName(to);
70149
+ if (file2.accounts.some((candidate) => candidate.name === to)) {
70150
+ throw new VaultError("name_taken", "A vault account already has that name.");
70151
+ }
70152
+ account.name = to;
70153
+ });
70154
+ } catch (error61) {
70155
+ throw asVaultError(error61, "corrupt", "Unable to rename the vault account.");
70156
+ }
70157
+ }
70158
+ async signer(name) {
70159
+ try {
70160
+ const latest = await readVaultFile(this.path, this.key);
70161
+ this.file = latest;
70162
+ const stored = latest.accounts.find((account2) => account2.name === name);
70163
+ if (!stored) {
70164
+ throw new VaultError("not_found", "No vault account has that name.");
69868
70165
  }
69869
- for (const [index2, chunk] of chunks.entries()) {
69870
- await write(keychainPart(account, index2 + 1), chunk, what);
70166
+ let account;
70167
+ if (stored.kind === "derived") {
70168
+ const plaintext = decryptField(this.key, latest.phrase);
70169
+ let seed;
70170
+ try {
70171
+ seed = phraseToSeed(plaintext.toString("utf8"));
70172
+ account = privateKeyToAccount(
70173
+ deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${stored.index}`)
70174
+ );
70175
+ } finally {
70176
+ seed?.fill(0);
70177
+ plaintext.fill(0);
70178
+ }
70179
+ } else {
70180
+ const plaintext = decryptField(this.key, stored.key);
70181
+ try {
70182
+ if (plaintext.byteLength !== 32) {
70183
+ throw new VaultError("corrupt", "An imported vault key has the wrong length.");
70184
+ }
70185
+ const privateKey = `0x${plaintext.toString("hex")}`;
70186
+ account = privateKeyToAccount(privateKey);
70187
+ } finally {
70188
+ plaintext.fill(0);
70189
+ }
69871
70190
  }
69872
- await erasePartsAfter(account, chunks.length, what);
69873
- await write(account, `${CHUNKED_MARKER}${chunks.length}`, what);
69874
- },
69875
- async remove(name) {
69876
- const account = accountFor(name);
69877
- const what = `remove the passphrase of ${name} from the macOS Keychain`;
69878
- const found = await find(account, true);
69879
- if (found.code === SECURITY_ITEM_NOT_FOUND) return false;
69880
- requireSuccess(found, what);
69881
- if (chunkedPartCount(withoutTrailingNewline(found.stdout)) !== void 0) {
69882
- await erasePartsAfter(account, 0, what);
70191
+ if (account.address.toLowerCase() !== stored.address.toLowerCase()) {
70192
+ throw new VaultError("corrupt", "A vault key does not match its stored address.");
69883
70193
  }
69884
- return await erase(account, what);
70194
+ return account;
70195
+ } catch (error61) {
70196
+ throw asVaultError(error61, "corrupt", "Unable to open the vault account signer.");
69885
70197
  }
69886
- };
69887
- }
69888
- var KEYCHAIN_PROMPT_LIMIT = 128;
69889
- var KEYCHAIN_CHUNK = 120;
69890
- var MAX_KEYCHAIN_PARTS = 32;
69891
- var CHUNKED_MARKER = "vapi-chunked:v1:";
69892
- function keychainPart(account, part) {
69893
- return `${account}#${part}`;
69894
- }
69895
- function chunkedPartCount(value) {
69896
- if (!value.startsWith(CHUNKED_MARKER)) return void 0;
69897
- const parts = Number(value.slice(CHUNKED_MARKER.length));
69898
- return Number.isInteger(parts) && parts > 0 && parts <= MAX_KEYCHAIN_PARTS ? parts : void 0;
69899
- }
69900
- function windowsSecretFileName(account) {
69901
- let encoded = "";
69902
- for (let index2 = 0; index2 < account.length; index2 += 1) {
69903
- const character = account[index2];
69904
- if (/^[a-z0-9._#-]$/u.test(character)) {
69905
- encoded += character;
69906
- continue;
70198
+ }
70199
+ async phrase() {
70200
+ const latest = await readVaultFile(this.path, this.key);
70201
+ this.file = latest;
70202
+ const plaintext = decryptField(this.key, latest.phrase);
70203
+ try {
70204
+ try {
70205
+ return validateRecoveryPhrase(plaintext.toString("utf8"));
70206
+ } catch (error61) {
70207
+ throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
70208
+ cause: error61
70209
+ });
70210
+ }
70211
+ } finally {
70212
+ plaintext.fill(0);
69907
70213
  }
69908
- encoded += `%${account.charCodeAt(index2).toString(16).toUpperCase().padStart(4, "0")}`;
69909
70214
  }
69910
- if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(encoded)) {
69911
- encoded = `%${encoded.charCodeAt(0).toString(16).toUpperCase()}${encoded.slice(1)}`;
70215
+ async save() {
70216
+ try {
70217
+ await this.update(async () => void 0);
70218
+ } catch (error61) {
70219
+ throw asVaultError(error61, "corrupt", "Unable to save the vault.");
70220
+ }
69912
70221
  }
69913
- return `${encoded}.bin`;
69914
- }
69915
- function windowsDataProtectionStore(platform2, run, env, installed) {
69916
- const powershell = `${env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
69917
- const fileDetails = (name) => {
69918
- const file2 = windowsSecretFileName(accountFor(name));
69919
- return { file: file2, account: file2.slice(0, -".bin".length) };
69920
- };
69921
- const script = (file2, operations) => [
69922
- "$ErrorActionPreference = 'Stop'",
69923
- "try {",
69924
- " Add-Type -AssemblyName System.Security",
69925
- " $dir = Join-Path $env:LOCALAPPDATA 'vapi-network\\secrets'",
69926
- ` $path = Join-Path $dir '${file2}'`,
69927
- ...operations.map((operation) => ` ${operation}`),
69928
- "} catch {",
69929
- " [Console]::Error.WriteLine($_.Exception.Message)",
69930
- " exit 1",
69931
- "}"
69932
- ].join("\n");
69933
- const execute = async (script2) => {
69934
- const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
69935
-
69936
- `);
69937
- requirePowerShell(result);
69938
- return result;
69939
- };
69940
- return {
69941
- available: installed(powershell),
69942
- platform: platform2,
69943
- description: "Windows Data Protection (DPAPI)",
69944
- async get(name) {
69945
- const { file: file2, account } = fileDetails(name);
69946
- const result = await execute(
69947
- script(file2, [
69948
- `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
69949
- "$blob = [System.IO.File]::ReadAllBytes($path)",
69950
- "$bytes = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
69951
- "[Console]::Out.Write([Convert]::ToBase64String($bytes))",
69952
- `exit ${WINDOWS_SECRET_SUCCESS}`
69953
- ])
69954
- );
69955
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return void 0;
69956
- requireSuccess(result, `read the passphrase of ${name} from Windows Data Protection`);
69957
- const value = Buffer.from(result.stdout.trim(), "base64").toString("utf8");
69958
- return value.length === 0 ? void 0 : value;
69959
- },
69960
- async has(name) {
69961
- const { file: file2, account } = fileDetails(name);
69962
- const result = await execute(
69963
- script(file2, [
69964
- `if (Test-Path -LiteralPath $path) { exit ${WINDOWS_SECRET_SUCCESS} }`,
69965
- `[Console]::Error.WriteLine('No stored secret for ${account}.')`,
69966
- `exit ${WINDOWS_SECRET_NOT_FOUND}`
69967
- ])
69968
- );
69969
- if (result.code === WINDOWS_SECRET_SUCCESS) return true;
69970
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
69971
- requireSuccess(result, `look up ${name} in Windows Data Protection`);
69972
- return false;
69973
- },
69974
- async set(name, passphrase) {
69975
- requirePassphrase(passphrase);
69976
- const { file: file2 } = fileDetails(name);
69977
- const value = Buffer.from(passphrase, "utf8").toString("base64");
69978
- const result = await execute(
69979
- script(file2, [
69980
- "[void][System.IO.Directory]::CreateDirectory($dir)",
69981
- `$bytes = [Convert]::FromBase64String('${value}')`,
69982
- "$blob = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
69983
- "[System.IO.File]::WriteAllBytes($path, $blob)",
69984
- `exit ${WINDOWS_SECRET_SUCCESS}`
69985
- ])
69986
- );
69987
- requireSuccess(result, `store the passphrase of ${name} in Windows Data Protection`);
69988
- },
69989
- async remove(name) {
69990
- const { file: file2, account } = fileDetails(name);
69991
- const result = await execute(
69992
- script(file2, [
69993
- `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
69994
- "Remove-Item -LiteralPath $path -Force",
69995
- `exit ${WINDOWS_SECRET_SUCCESS}`
69996
- ])
69997
- );
69998
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
69999
- requireSuccess(result, `remove the passphrase of ${name} from Windows Data Protection`);
70000
- return true;
70222
+ resealSecrets(file2) {
70223
+ const phrase = decryptField(this.key, file2.phrase);
70224
+ try {
70225
+ const accounts = file2.accounts.map((account) => {
70226
+ if (account.kind === "derived") return { ...account };
70227
+ const privateKey = decryptField(this.key, account.key);
70228
+ try {
70229
+ if (privateKey.byteLength !== 32) {
70230
+ throw new VaultError("corrupt", "An imported vault key has the wrong length.");
70231
+ }
70232
+ return { ...account, key: sealField(this.key, privateKey) };
70233
+ } finally {
70234
+ privateKey.fill(0);
70235
+ }
70236
+ });
70237
+ return {
70238
+ ...file2,
70239
+ phrase: sealField(this.key, phrase),
70240
+ accounts
70241
+ };
70242
+ } finally {
70243
+ phrase.fill(0);
70001
70244
  }
70002
- };
70003
- }
70004
- function libsecretStore(platform2, run, installed) {
70005
- const lookup = async (name) => {
70006
- const result = await run(SECRET_TOOL_BINARY, [
70007
- "lookup",
70008
- "service",
70009
- SECRET_STORE_SERVICE,
70010
- "account",
70011
- accountFor(name)
70012
- ]);
70013
- requireBinary(result);
70014
- const value = withoutTrailingNewline(result.stdout);
70015
- if (result.code === 0) return value.length === 0 ? void 0 : value;
70016
- if (result.stderr.trim().length === 0) return void 0;
70017
- requireSuccess(result, `read the passphrase of ${name} from the secret service`);
70018
- return void 0;
70019
- };
70020
- return {
70021
- available: installed(SECRET_TOOL_BINARY),
70022
- platform: platform2,
70023
- description: "the libsecret keyring",
70024
- get: lookup,
70025
- async has(name) {
70026
- return await lookup(name) !== void 0;
70027
- },
70028
- async set(name, passphrase) {
70029
- requirePassphrase(passphrase);
70030
- const account = accountFor(name);
70031
- const result = await run(
70032
- SECRET_TOOL_BINARY,
70033
- [
70034
- "store",
70035
- `--label=${SECRET_STORE_SERVICE} ${account}`,
70036
- "service",
70037
- SECRET_STORE_SERVICE,
70038
- "account",
70039
- account
70040
- ],
70041
- `${passphrase}
70042
- `
70043
- );
70044
- requireBinary(result);
70045
- requireSuccess(result, `store the passphrase of ${name} in the secret service`);
70046
- },
70047
- async remove(name) {
70048
- const existed = await lookup(name) !== void 0;
70049
- const result = await run(SECRET_TOOL_BINARY, [
70050
- "clear",
70051
- "service",
70052
- SECRET_STORE_SERVICE,
70053
- "account",
70054
- accountFor(name)
70055
- ]);
70056
- requireBinary(result);
70057
- requireSuccess(result, `remove the passphrase of ${name} from the secret service`);
70058
- return existed;
70245
+ }
70246
+ async update(operation) {
70247
+ return await withVaultLock(this.path, async () => {
70248
+ const latest = await readVaultFile(this.path, this.key);
70249
+ const result = await operation(latest);
70250
+ const rewritten = this.resealSecrets(latest);
70251
+ await writeVaultFile(this.path, rewritten);
70252
+ this.file = rewritten;
70253
+ return result;
70254
+ });
70255
+ }
70256
+ };
70257
+ async function createVault(args) {
70258
+ assertVaultKey(args.key);
70259
+ let phrase;
70260
+ if (args.phrase === void 0) {
70261
+ try {
70262
+ phrase = generateRecoveryPhrase();
70263
+ } catch (error61) {
70264
+ throw new VaultError("corrupt", "Unable to generate a vault recovery phrase.", {
70265
+ cause: error61
70266
+ });
70059
70267
  }
70060
- };
70268
+ } else {
70269
+ phrase = validateRecoveryPhrase(args.phrase);
70270
+ }
70271
+ try {
70272
+ return await withVaultLock(args.path, async () => {
70273
+ await refuseExistingVault(args.path);
70274
+ const plaintext = Buffer.from(phrase, "utf8");
70275
+ let sealedPhrase;
70276
+ try {
70277
+ sealedPhrase = sealField(args.key, plaintext);
70278
+ } finally {
70279
+ plaintext.fill(0);
70280
+ }
70281
+ const file2 = {
70282
+ version: 2,
70283
+ kdf: "device-key",
70284
+ cipher: "aes-256-gcm",
70285
+ phrase: sealedPhrase,
70286
+ accounts: [],
70287
+ nextDerivedIndex: 0,
70288
+ protected: false
70289
+ };
70290
+ await writeVaultFile(args.path, file2);
70291
+ return new DeviceVault(args, file2);
70292
+ });
70293
+ } catch (error61) {
70294
+ throw asVaultError(error61, "corrupt", "Unable to create the vault.");
70295
+ }
70061
70296
  }
70062
- function unsupportedStore(platform2) {
70063
- const refuse = () => {
70064
- throw new KeystoreError(UNSUPPORTED_PLATFORM);
70065
- };
70066
- return {
70067
- available: false,
70068
- platform: platform2,
70069
- description: "no OS secret store",
70070
- get: async () => refuse(),
70071
- has: async () => refuse(),
70072
- set: async () => refuse(),
70073
- remove: async () => refuse()
70074
- };
70297
+ async function openVault(args) {
70298
+ assertVaultKey(args.key);
70299
+ return new DeviceVault(args, await readVaultFile(args.path, args.key));
70075
70300
  }
70076
- function accountFor(name) {
70077
- const account = name.trim();
70078
- if (account.length === 0) {
70079
- throw new KeystoreError("A wallet name is needed to reach the OS secret store.");
70301
+ async function reinstateVaultAccount(args) {
70302
+ const parsedAccount = storedAccountSchema.safeParse(args.account);
70303
+ if (!parsedAccount.success) {
70304
+ throw new VaultError("corrupt", "The stored vault account has an invalid structure.", {
70305
+ cause: parsedAccount.error
70306
+ });
70307
+ }
70308
+ assertVaultKey(args.key);
70309
+ try {
70310
+ return await withVaultLock(args.path, async () => {
70311
+ const file2 = await readVaultFile(args.path, args.key);
70312
+ const account = parsedAccount.data;
70313
+ assertAvailableName(file2, account.name);
70314
+ if (account.kind === "derived" && file2.accounts.some(
70315
+ (candidate) => candidate.kind === "derived" && candidate.index === account.index
70316
+ )) {
70317
+ throw new VaultError("name_taken", "A vault account already uses that derived index.");
70318
+ }
70319
+ if (account.kind === "derived") validateStoredDerivedAccount(args.key, file2, account);
70320
+ else validateStoredImportedAccount(args.key, account);
70321
+ const updated = parseVaultFile(
70322
+ JSON.stringify({
70323
+ ...file2,
70324
+ accounts: [...file2.accounts, account],
70325
+ ...account.kind === "derived" ? { nextDerivedIndex: Math.max(nextDerivedIndex(file2), account.index + 1) } : {}
70326
+ })
70327
+ );
70328
+ await writeVaultFile(args.path, updated);
70329
+ return copyAccount(account);
70330
+ });
70331
+ } catch (error61) {
70332
+ throw asVaultError(error61, "corrupt", "Unable to reinstate the vault account.");
70080
70333
  }
70081
- return account;
70082
70334
  }
70083
- function requirePassphrase(passphrase) {
70084
- if (passphrase.length === 0) {
70085
- throw new KeystoreError("Keystore passphrase cannot be empty.");
70335
+ function assertVaultKey(key) {
70336
+ if (key.byteLength !== 32) {
70337
+ throw new VaultError("bad_key", "A device vault key must contain exactly 32 bytes.");
70086
70338
  }
70087
70339
  }
70088
- function requireBinary(result) {
70089
- if (result.notFound === true) throw new KeystoreError(SECRET_TOOL_MISSING);
70340
+ function assertAccountName(name) {
70341
+ const parsed = walletNameSchema.safeParse(name);
70342
+ if (!parsed.success) {
70343
+ throw new VaultError("name_taken", "The vault account name is not valid.", {
70344
+ cause: parsed.error
70345
+ });
70346
+ }
70090
70347
  }
70091
- function requirePowerShell(result) {
70092
- if (result.notFound === true) throw new KeystoreError(POWERSHELL_MISSING);
70348
+ function assertAvailableName(file2, name) {
70349
+ assertAccountName(name);
70350
+ if (file2.accounts.some((account) => account.name === name)) {
70351
+ throw new VaultError("name_taken", "A vault account already has that name.");
70352
+ }
70093
70353
  }
70094
- function binaryInstalled(file2, env) {
70095
- if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
70096
- return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join6(directory, file2)));
70354
+ function nextDerivedIndex(file2) {
70355
+ let next = file2.nextDerivedIndex ?? 0;
70356
+ for (const account of file2.accounts) {
70357
+ if (account.kind === "derived") next = Math.max(next, account.index + 1);
70358
+ }
70359
+ return next;
70097
70360
  }
70098
- var SAFE_FAILURE_DETAILS = [
70099
- "Cannot autolaunch D-Bus without X11 $DISPLAY",
70100
- "Cannot autolaunch D-Bus",
70101
- "The name org.freedesktop.secrets was not provided by any .service files",
70102
- "Cannot create an item in a locked collection",
70103
- "User interaction is not allowed.",
70104
- "Access to the path is denied."
70105
- ];
70106
- function requireSuccess(result, what) {
70107
- if (result.code === 0) return;
70108
- const detail = SAFE_FAILURE_DETAILS.find((reason) => result.stderr.includes(reason));
70109
- throw new KeystoreError(
70110
- `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail === void 0 ? "" : ` ${detail}`}`
70111
- );
70361
+ function copyAccount(account) {
70362
+ if (account.kind === "derived") return { ...account };
70363
+ return {
70364
+ name: account.name,
70365
+ kind: account.kind,
70366
+ address: account.address,
70367
+ createdAt: account.createdAt
70368
+ };
70112
70369
  }
70113
- function withoutTrailingNewline(value) {
70114
- return value.replace(/\r?\n$/u, "");
70370
+ function sealField(key, plaintext) {
70371
+ const { nonce, ciphertext, tag } = encryptWithKey(key, plaintext);
70372
+ return [nonce, ciphertext, tag].map((part) => part.toString("base64url")).join(".");
70115
70373
  }
70116
- var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve2) => {
70117
- let stdout = "";
70118
- let stderr2 = "";
70119
- let settled = false;
70120
- const finish = (outcome) => {
70121
- if (settled) return;
70122
- settled = true;
70123
- resolve2(outcome);
70124
- };
70125
- const child = spawn(file2, [...args], {
70126
- detached: platform2 !== "win32",
70127
- stdio: ["pipe", "pipe", "pipe"],
70128
- windowsHide: true
70129
- });
70130
- child.stdout?.setEncoding("utf8");
70131
- child.stdout?.on("data", (chunk) => {
70132
- stdout += chunk;
70133
- });
70134
- child.stderr?.setEncoding("utf8");
70135
- child.stderr?.on("data", (chunk) => {
70136
- stderr2 += chunk;
70374
+ function openField(key, value) {
70375
+ const [nonce = "", ciphertext = "", tag = ""] = value.split(".");
70376
+ return decryptWithKey(key, {
70377
+ nonce: Buffer.from(nonce, "base64url"),
70378
+ ciphertext: Buffer.from(ciphertext, "base64url"),
70379
+ tag: Buffer.from(tag, "base64url")
70137
70380
  });
70138
- child.on("error", (error61) => {
70139
- finish({
70140
- code: null,
70141
- stdout,
70142
- stderr: stderr2,
70143
- ...error61.code === "ENOENT" ? { notFound: true } : {}
70381
+ }
70382
+ function decryptField(key, value) {
70383
+ try {
70384
+ return openField(key, value);
70385
+ } catch (error61) {
70386
+ throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70387
+ cause: error61
70144
70388
  });
70145
- });
70146
- child.on("close", (code) => finish({ code, stdout, stderr: stderr2 }));
70147
- child.stdin?.on("error", () => void 0);
70148
- child.stdin?.end(input2 ?? "");
70149
- });
70150
-
70151
- // src/passphrase.ts
70152
- var PASSPHRASE_ENVIRONMENT_VARIABLE = "VAPI_KEYSTORE_PASSWORD";
70153
- function noPassphraseHint(walletName) {
70154
- return `Set ${PASSPHRASE_ENVIRONMENT_VARIABLE}, or store this wallet's passphrase once with vapi unlock --wallet ${walletName}.`;
70389
+ }
70155
70390
  }
70156
- function staleStoredPassphraseMessage(walletName, store) {
70157
- return [
70158
- `The passphrase stored in ${store.description} no longer opens wallet ${walletName}.`,
70159
- `Store the current one with vapi unlock --wallet ${walletName}, or remove it with vapi lock --wallet ${walletName}.`
70160
- ].join(" ");
70391
+ function decryptPhraseForOpen(key, phrase) {
70392
+ try {
70393
+ return openField(key, phrase);
70394
+ } catch (error61) {
70395
+ throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70396
+ cause: error61
70397
+ });
70398
+ }
70161
70399
  }
70162
- async function resolvePassphrase(walletName, options = {}) {
70163
- const env = options.env ?? process.env;
70164
- const fromEnvironment = env[PASSPHRASE_ENVIRONMENT_VARIABLE];
70165
- if (fromEnvironment !== void 0) {
70166
- if (fromEnvironment.length === 0) {
70167
- throw new KeystoreError(`${PASSPHRASE_ENVIRONMENT_VARIABLE} cannot be empty.`);
70400
+ function validateStoredImportedAccount(key, account) {
70401
+ let plaintext;
70402
+ try {
70403
+ plaintext = decryptField(key, account.key);
70404
+ if (plaintext.byteLength !== 32) {
70405
+ throw new VaultError("bad_key", "The stored imported key has the wrong length.");
70168
70406
  }
70169
- return { passphrase: fromEnvironment, source: "environment" };
70170
- }
70171
- if (options.confirm !== true) {
70172
- const stored = await readStored(options.store ?? secretStore(), walletName);
70173
- if (stored !== void 0) return { passphrase: stored, source: "secret-store" };
70174
- }
70175
- const hint = noPassphraseHint(walletName);
70176
- if (options.interactive === false) {
70177
- throw new KeystoreError(
70178
- `No interactive terminal is available for the keystore prompt. ${hint}`
70179
- );
70180
- }
70181
- const prompt = options.prompt ?? promptForSecret;
70182
- const first = await prompt(`Passphrase for ${walletName}: `, hint);
70183
- if (first.length === 0) {
70184
- throw new KeystoreError("Keystore passphrase cannot be empty.");
70185
- }
70186
- if (options.confirm === true) {
70187
- const second = await prompt("Confirm passphrase: ", hint);
70188
- if (first !== second) throw new KeystoreError("Passphrases do not match.");
70407
+ let address2;
70408
+ try {
70409
+ address2 = privateKeyToAccount(`0x${plaintext.toString("hex")}`).address;
70410
+ } catch (error61) {
70411
+ throw new VaultError("bad_key", "The stored imported key is not valid.", {
70412
+ cause: error61
70413
+ });
70414
+ }
70415
+ if (address2.toLowerCase() !== account.address.toLowerCase()) {
70416
+ throw new VaultError("bad_key", "The stored imported key does not match its address.");
70417
+ }
70418
+ } finally {
70419
+ plaintext?.fill(0);
70189
70420
  }
70190
- return { passphrase: first, source: "prompt" };
70191
70421
  }
70192
- async function readStored(store, walletName) {
70193
- if (!store.available) return void 0;
70422
+ function validateStoredDerivedAccount(key, file2, account) {
70423
+ const plaintext = decryptField(key, file2.phrase);
70424
+ let seed;
70194
70425
  try {
70195
- return await store.get(walletName);
70196
- } catch {
70197
- return void 0;
70426
+ seed = phraseToSeed(plaintext.toString("utf8"));
70427
+ const address2 = privateKeyToAccount(
70428
+ deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${account.index}`)
70429
+ ).address;
70430
+ if (address2.toLowerCase() !== account.address.toLowerCase()) {
70431
+ throw new VaultError("bad_key", "The stored derived account does not match this vault.");
70432
+ }
70433
+ } finally {
70434
+ seed?.fill(0);
70435
+ plaintext.fill(0);
70198
70436
  }
70199
70437
  }
70200
-
70201
- // src/receipts.ts
70202
- import { randomBytes as randomBytes6 } from "node:crypto";
70203
- import { mkdir as mkdir7, open as open5, readFile as readFile7, rename as rename4, writeFile as writeFile3 } from "node:fs/promises";
70204
- import { dirname as dirname5 } from "node:path";
70205
-
70206
- // src/agent-run.ts
70207
- import { randomBytes as randomBytes5 } from "node:crypto";
70208
- var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
70209
- function isRunId(value) {
70210
- return typeof value === "string" && RUN_ID_PATTERN.test(value);
70211
- }
70212
- function createRunId(random = randomBytes5) {
70213
- return `run_${Buffer.from(random(12)).toString("hex")}`;
70214
- }
70215
- var runRefSchema = external_exports.strictObject({
70216
- id: external_exports.string().regex(RUN_ID_PATTERN),
70217
- swarm: external_exports.string().optional(),
70218
- member: external_exports.string().optional(),
70219
- parentRunId: external_exports.string().optional()
70220
- });
70221
-
70222
- // src/wallet-name.ts
70223
- var DEFAULT_WALLET_NAME = "main";
70224
- var WALLET_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
70225
- var walletNameSchema = external_exports.string().regex(
70226
- WALLET_NAME_PATTERN,
70227
- "A wallet name is 1 to 32 characters of lowercase letters, digits and dashes, starting with a letter or digit."
70228
- );
70229
- function isWalletName(value) {
70230
- return WALLET_NAME_PATTERN.test(value);
70231
- }
70232
-
70233
- // src/receipts.ts
70234
- var receiptTestHooks;
70235
- function __setReceiptTestHooks(hooks) {
70236
- receiptTestHooks = hooks;
70237
- }
70238
- var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
70239
- async function withReceiptJournalLock(path, operation) {
70240
- return await withFileLock(`${path}.lock`, operation, {
70241
- lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
70242
- });
70243
- }
70244
- var durationSchema = external_exports.number().nonnegative().finite();
70245
- var receiptSchema = external_exports.strictObject({
70246
- id: external_exports.string().min(1),
70247
- timestamp: external_exports.iso.datetime(),
70248
- run: runRefSchema.optional(),
70249
- kind: external_exports.literal("transfer").optional(),
70250
- wallet: walletNameSchema.optional(),
70251
- resourceUrl: external_exports.url(),
70252
- method: external_exports.string().min(1).optional(),
70253
- source: external_exports.string().min(1).optional(),
70254
- provenance: external_exports.array(
70255
- external_exports.strictObject({
70256
- source: external_exports.string().min(1),
70257
- sourceUrl: external_exports.string().optional(),
70258
- ref: external_exports.string().optional()
70259
- })
70260
- ).optional(),
70261
- quote: external_exports.strictObject({
70262
- network: external_exports.string(),
70263
- asset: external_exports.string().optional(),
70264
- amountAtomic: external_exports.string().regex(/^\d+$/),
70265
- payTo: external_exports.string().optional()
70266
- }).optional(),
70267
- payer: external_exports.string().optional(),
70268
- paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
70269
- authorization: external_exports.strictObject({
70270
- from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70271
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
70272
- validBefore: external_exports.string().regex(/^\d+$/)
70273
- }).optional(),
70274
- transfer: external_exports.strictObject({
70275
- to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70276
- toName: external_exports.string().min(1),
70277
- toKind: external_exports.enum(["owner", "account"]),
70278
- amountAtomic: external_exports.string().regex(/^\d+$/),
70279
- network: external_exports.string().min(1),
70280
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
70281
- status: external_exports.enum(["sent", "unknown", "failed"]),
70282
- txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
70283
- replayed: external_exports.boolean(),
70284
- reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
70285
- request: external_exports.strictObject({
70286
- authorization: external_exports.strictObject({
70287
- from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70288
- to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70289
- value: external_exports.string().regex(/^\d+$/),
70290
- validAfter: external_exports.string().regex(/^\d+$/),
70291
- validBefore: external_exports.string().regex(/^\d+$/),
70292
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
70293
- }),
70294
- signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
70295
- }).optional()
70296
- }).optional(),
70297
- settlement: external_exports.strictObject({
70298
- outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
70299
- transaction: external_exports.string().optional(),
70300
- explorerUrl: external_exports.url().optional(),
70301
- evidence: external_exports.unknown().optional()
70302
- }).optional(),
70303
- latencyMs: external_exports.number().nonnegative().finite().optional(),
70304
- status: external_exports.number().int().min(100).max(599).optional(),
70305
- error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
70306
- phases: external_exports.strictObject({
70307
- discoverMs: durationSchema.optional(),
70308
- quoteMs: durationSchema.optional(),
70309
- signMs: durationSchema.optional(),
70310
- requestMs: durationSchema.optional(),
70311
- settleMs: durationSchema.optional()
70312
- }).optional(),
70313
- listing: external_exports.strictObject({
70314
- name: external_exports.string().min(1).optional(),
70315
- providerHost: external_exports.string().min(1).optional(),
70316
- source: external_exports.string().min(1)
70317
- }).optional(),
70318
- retry: external_exports.number().int().nonnegative().optional(),
70319
- policy: external_exports.strictObject({
70320
- maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
70321
- capsApplied: external_exports.boolean()
70322
- }).optional(),
70323
- client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
70324
- outcome: external_exports.enum([
70325
- "paid",
70326
- "signed_in",
70327
- "declined_policy",
70328
- "failed_request",
70329
- "settlement_rejected",
70330
- "settlement_unknown"
70331
- ]).optional()
70332
- });
70333
- function parseReceipt(value) {
70334
- const receipt = receiptSchema.parse(value);
70335
- const transaction = receipt.settlement?.transaction;
70336
- const network = receipt.quote?.network;
70337
- const explorerUrl = transaction === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction);
70338
- if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
70339
- return receipt;
70438
+ function parseVaultFile(raw) {
70439
+ let value;
70440
+ try {
70441
+ value = JSON.parse(raw);
70442
+ } catch (error61) {
70443
+ throw new VaultError("corrupt", "The vault file is not valid JSON.", { cause: error61 });
70340
70444
  }
70341
- return {
70342
- ...receipt,
70343
- settlement: {
70344
- outcome: receipt.settlement.outcome,
70345
- ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
70346
- explorerUrl,
70347
- ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
70445
+ const parsed = vaultFileSchema.safeParse(value);
70446
+ if (!parsed.success) {
70447
+ throw new VaultError("corrupt", "The vault file has an invalid structure.", {
70448
+ cause: parsed.error
70449
+ });
70450
+ }
70451
+ if (parsed.data.protected !== (parsed.data.wrappedKey !== void 0)) {
70452
+ throw new VaultError("corrupt", "The vault protection metadata is inconsistent.");
70453
+ }
70454
+ const names = /* @__PURE__ */ new Set();
70455
+ const indexes = /* @__PURE__ */ new Set();
70456
+ for (const account of parsed.data.accounts) {
70457
+ if (names.has(account.name)) {
70458
+ throw new VaultError("corrupt", "The vault file contains duplicate account names.");
70348
70459
  }
70349
- };
70460
+ names.add(account.name);
70461
+ if (account.kind === "derived") {
70462
+ if (indexes.has(account.index)) {
70463
+ throw new VaultError("corrupt", "The vault file contains duplicate derived indexes.");
70464
+ }
70465
+ indexes.add(account.index);
70466
+ }
70467
+ }
70468
+ return parsed.data;
70350
70469
  }
70351
- async function appendReceipt(receipt, path = getVapiPaths().receipts, options = {}) {
70352
- const parsed = parseReceipt(
70353
- receipt.wallet === void 0 && options.wallet !== void 0 ? { ...receipt, wallet: options.wallet } : receipt
70354
- );
70355
- await withReceiptJournalLock(path, async () => {
70356
- await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70357
- const handle = await open5(path, "a", 384);
70470
+ async function readVaultFile(path, key) {
70471
+ const file2 = await readVaultFileUnlocked(path);
70472
+ const plaintext = decryptPhraseForOpen(key, file2.phrase);
70473
+ try {
70358
70474
  try {
70359
- await handle.writeFile(`${JSON.stringify(parsed)}
70360
- `, "utf8");
70361
- } finally {
70362
- await handle.close();
70475
+ validateRecoveryPhrase(plaintext.toString("utf8"));
70476
+ } catch (error61) {
70477
+ throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
70478
+ cause: error61
70479
+ });
70363
70480
  }
70364
- });
70365
- return parsed;
70481
+ } finally {
70482
+ plaintext.fill(0);
70483
+ }
70484
+ return file2;
70366
70485
  }
70367
- async function readReceipts(path = getVapiPaths().receipts, options = {}) {
70486
+ async function readVaultFileUnlocked(path) {
70368
70487
  let raw;
70369
70488
  try {
70370
70489
  raw = await readFile7(path, "utf8");
70371
70490
  } catch (error61) {
70372
- if (isMissingFile(error61)) return [];
70373
- throw error61;
70374
- }
70375
- const records = coalesceTransferReceiptRevisions(
70376
- raw.split("\n").filter((line) => line.trim().length > 0).map((line, index2) => {
70377
- try {
70378
- return parseReceipt(JSON.parse(line));
70379
- } catch (error61) {
70380
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70381
- }
70382
- })
70383
- );
70384
- const filtered = options.wallet === void 0 ? records : filterReceiptsByWallet(records, options.wallet);
70385
- const limit = options.limit;
70386
- if (limit === void 0) return filtered;
70387
- if (!Number.isSafeInteger(limit) || limit < 0)
70388
- throw new Error("Receipt limit must be a non-negative integer.");
70389
- return limit === 0 ? [] : filtered.slice(-limit);
70390
- }
70391
- function coalesceTransferReceiptRevisions(receipts) {
70392
- const coalesced = [];
70393
- const transferIndexes = /* @__PURE__ */ new Map();
70394
- for (const receipt of receipts) {
70395
- const existing = receipt.kind === "transfer" ? transferIndexes.get(receipt.id) : void 0;
70396
- if (existing === void 0) {
70397
- if (receipt.kind === "transfer") transferIndexes.set(receipt.id, coalesced.length);
70398
- coalesced.push(receipt);
70399
- } else {
70400
- coalesced[existing] = receipt;
70491
+ if (isMissingFile2(error61)) {
70492
+ throw new VaultError("not_found", "No vault file was found at the requested path.", {
70493
+ cause: error61
70494
+ });
70401
70495
  }
70496
+ throw new VaultError("corrupt", "Unable to read the vault file.", { cause: error61 });
70402
70497
  }
70403
- return coalesced;
70404
- }
70405
- function receiptWallet(receipt) {
70406
- return receipt.wallet ?? DEFAULT_WALLET_NAME;
70407
- }
70408
- function filterReceiptsByWallet(receipts, name) {
70409
- return receipts.filter((receipt) => receiptWallet(receipt) === name);
70498
+ return parseVaultFile(raw);
70410
70499
  }
70411
- async function renameReceiptWallet(from16, to, path = getVapiPaths().receipts) {
70412
- return await withReceiptJournalLock(path, async () => {
70413
- let raw;
70414
- try {
70415
- raw = await readFile7(path, "utf8");
70416
- } catch (error61) {
70417
- if (isMissingFile(error61)) return 0;
70418
- throw error61;
70419
- }
70420
- let changed = 0;
70421
- const lines = raw.split("\n").map((line, index2) => {
70422
- if (line.trim().length === 0) return line;
70423
- let parsed;
70424
- try {
70425
- parsed = JSON.parse(line);
70426
- } catch (error61) {
70427
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70428
- }
70429
- const current = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "wallet") : void 0;
70430
- if ((typeof current === "string" ? current : DEFAULT_WALLET_NAME) !== from16) return line;
70431
- changed += 1;
70432
- return JSON.stringify(parseReceipt({ ...parsed, wallet: to }));
70500
+ async function refuseExistingVault(path) {
70501
+ try {
70502
+ await stat6(path);
70503
+ } catch (error61) {
70504
+ if (isMissingFile2(error61)) return;
70505
+ throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
70506
+ cause: error61
70433
70507
  });
70434
- if (changed === 0) return 0;
70435
- await receiptTestHooks?.beforeRenameReplace?.(path);
70436
- await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70437
- const temporaryPath = `${path}.${process.pid}.${randomBytes6(6).toString("hex")}.tmp`;
70438
- await writeFile3(temporaryPath, lines.join("\n"), {
70508
+ }
70509
+ throw new VaultError("corrupt", "A vault already exists at the requested path.");
70510
+ }
70511
+ async function writeVaultFile(path, file2) {
70512
+ await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70513
+ const temporaryPath = `${path}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
70514
+ try {
70515
+ await writeFile3(temporaryPath, `${JSON.stringify(file2, null, 2)}
70516
+ `, {
70439
70517
  encoding: "utf8",
70440
70518
  mode: 384,
70441
70519
  flag: "wx"
70442
70520
  });
70443
70521
  await rename4(temporaryPath, path);
70444
- return changed;
70445
- });
70446
- }
70447
-
70448
- // src/transfer-journal.ts
70449
- import { readFile as readFile8 } from "node:fs/promises";
70450
- async function readTransferJournal(home, from16, nonce) {
70451
- let raw;
70452
- try {
70453
- raw = await readFile8(getVapiPaths(home).receipts, "utf8");
70454
70522
  } catch (error61) {
70455
- if (isMissingFile(error61)) return { signed: false };
70523
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
70456
70524
  throw error61;
70457
70525
  }
70458
- let latest;
70459
- let request;
70460
- for (const [index2, line] of raw.split("\n").entries()) {
70461
- if (!line.trim()) continue;
70462
- let receipt;
70526
+ }
70527
+ async function withVaultLock(path, operation) {
70528
+ await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70529
+ const lockPath = `${path}.lock`;
70530
+ const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
70531
+ let handle;
70532
+ while (!handle) {
70463
70533
  try {
70464
- receipt = parseReceipt(JSON.parse(line));
70534
+ handle = await open5(lockPath, "wx", 384);
70465
70535
  } catch (error61) {
70466
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70467
- }
70468
- if (receiptWallet(receipt) !== from16 || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
70469
- continue;
70536
+ if (!isExistingFile(error61)) throw error61;
70537
+ await removeStaleVaultLock(lockPath);
70538
+ if (Date.now() >= deadline) {
70539
+ throw new VaultError("corrupt", "Timed out waiting for the vault lock.");
70540
+ }
70541
+ await new Promise((resolve2) => setTimeout(resolve2, 20));
70470
70542
  }
70471
- latest = receipt;
70472
- if (receipt.transfer.request !== void 0) request = receipt;
70473
70543
  }
70474
- return {
70475
- signed: latest !== void 0,
70476
- ...latest === void 0 ? {} : { latest },
70477
- ...request === void 0 ? {} : { request },
70478
- ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
70479
- ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
70480
- };
70544
+ try {
70545
+ return await operation();
70546
+ } finally {
70547
+ await handle.close();
70548
+ await unlink4(lockPath).catch(() => void 0);
70549
+ }
70481
70550
  }
70482
-
70483
- // src/vault-key.ts
70484
- import { randomBytes as cryptoRandomBytes } from "node:crypto";
70485
-
70486
- // src/vault.ts
70487
- import { randomBytes as randomBytes7 } from "node:crypto";
70488
- import { mkdir as mkdir8, open as open6, readFile as readFile9, rename as rename5, rm, stat as stat6, unlink as unlink4, writeFile as writeFile4 } from "node:fs/promises";
70489
- import { dirname as dirname6 } from "node:path";
70490
- var VaultError = class extends Error {
70491
- code;
70492
- constructor(code, message, options) {
70493
- super(message, options);
70494
- this.name = "VaultError";
70495
- this.code = code;
70551
+ async function removeStaleVaultLock(path) {
70552
+ try {
70553
+ const metadata = await stat6(path);
70554
+ if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
70555
+ } catch (error61) {
70556
+ if (!isMissingFile2(error61)) throw error61;
70496
70557
  }
70497
- };
70498
- var SEALED_FIELD_PATTERN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/u;
70499
- var WRAPPED_KEY_PATTERN = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/u;
70500
- var ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/u;
70501
- var VAULT_LOCK_TIMEOUT_MS = 2e3;
70502
- var STALE_VAULT_LOCK_MS = 3e4;
70503
- var sealedFieldSchema = external_exports.string().regex(SEALED_FIELD_PATTERN);
70504
- var addressSchema = external_exports.string().regex(ADDRESS_PATTERN);
70505
- var accountFields = {
70506
- name: walletNameSchema,
70507
- address: addressSchema,
70508
- createdAt: external_exports.string()
70509
- };
70510
- var storedAccountSchema = external_exports.discriminatedUnion("kind", [
70511
- external_exports.object({
70512
- ...accountFields,
70513
- kind: external_exports.literal("derived"),
70514
- index: external_exports.number().int().nonnegative().refine(Number.isSafeInteger, "Derived account index must be a safe integer.")
70515
- }).strict(),
70516
- external_exports.object({
70517
- ...accountFields,
70518
- kind: external_exports.literal("imported"),
70519
- key: sealedFieldSchema
70520
- }).strict()
70521
- ]);
70522
- var vaultFileSchema = external_exports.object({
70523
- version: external_exports.literal(2),
70524
- kdf: external_exports.literal("device-key"),
70525
- cipher: external_exports.literal("aes-256-gcm"),
70526
- phrase: sealedFieldSchema,
70527
- accounts: external_exports.array(storedAccountSchema),
70528
- nextDerivedIndex: external_exports.number().int().nonnegative().refine(Number.isSafeInteger, "Next derived account index must be a safe integer.").optional(),
70529
- protected: external_exports.boolean(),
70530
- wrappedKey: external_exports.string().regex(WRAPPED_KEY_PATTERN).optional()
70558
+ }
70559
+ function isMissingFile2(error61) {
70560
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
70561
+ }
70562
+ function isExistingFile(error61) {
70563
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "EEXIST";
70564
+ }
70565
+ function asVaultError(error61, code, message) {
70566
+ return error61 instanceof VaultError ? error61 : new VaultError(code, message, { cause: error61 });
70567
+ }
70568
+
70569
+ // src/file-secret-store.ts
70570
+ var FILE_SECRET_STORE_PASSWORD_ENV = "VAPI_VAULT_PASSWORD";
70571
+ var FILE_SECRET_STORE_MIN_PASSWORD = 12;
70572
+ var CHECK_VALUE = "vapi-network file secret store";
70573
+ var sealedSchema = external_exports.object({ nonce: external_exports.string(), ciphertext: external_exports.string(), tag: external_exports.string() }).strict();
70574
+ var fileSchema = external_exports.object({
70575
+ v: external_exports.literal(1),
70576
+ salt: external_exports.string(),
70577
+ check: sealedSchema,
70578
+ entries: external_exports.record(external_exports.string(), sealedSchema)
70531
70579
  }).strict();
70532
- var DeviceVault = class {
70533
- file;
70534
- path;
70535
- key;
70536
- balanceOf;
70537
- now;
70538
- constructor(options, file2) {
70539
- this.path = options.path;
70540
- this.key = options.key;
70541
- this.balanceOf = options.balanceOf;
70542
- this.now = options.now ?? (() => /* @__PURE__ */ new Date());
70543
- this.file = file2;
70544
- }
70545
- accounts() {
70546
- return this.file.accounts.map(copyAccount);
70580
+ async function createFileSecretStore(options) {
70581
+ const password = passwordFrom(options.env);
70582
+ if (password.length < FILE_SECRET_STORE_MIN_PASSWORD) {
70583
+ throw new KeystoreError(
70584
+ `${FILE_SECRET_STORE_PASSWORD_ENV} must be at least ${FILE_SECRET_STORE_MIN_PASSWORD} characters.`
70585
+ );
70547
70586
  }
70548
- async deriveAccount(name) {
70587
+ await withVaultLock(options.path, async () => {
70588
+ let exists = true;
70549
70589
  try {
70550
- return await this.update(async (file2) => {
70551
- assertAvailableName(file2, name);
70552
- const index2 = nextDerivedIndex(file2);
70553
- const plaintext = decryptField(this.key, file2.phrase);
70554
- let seed;
70555
- let address2;
70556
- try {
70557
- seed = phraseToSeed(plaintext.toString("utf8"));
70558
- address2 = privateKeyToAccount(
70559
- deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${index2}`)
70560
- ).address;
70561
- } finally {
70562
- seed?.fill(0);
70563
- plaintext.fill(0);
70564
- }
70565
- const account = {
70566
- name,
70567
- kind: "derived",
70568
- index: index2,
70569
- address: address2,
70570
- createdAt: this.now().toISOString()
70571
- };
70572
- file2.accounts.push(account);
70573
- file2.nextDerivedIndex = index2 + 1;
70574
- return copyAccount(account);
70575
- });
70590
+ await stat7(options.path);
70576
70591
  } catch (error61) {
70577
- throw asVaultError(error61, "corrupt", "Unable to derive a vault account.");
70592
+ if (!isMissingFile(error61)) throw error61;
70593
+ exists = false;
70578
70594
  }
70579
- }
70580
- async importAccount(name, privateKey) {
70581
- try {
70582
- return await this.update(async (file2) => {
70583
- assertAvailableName(file2, name);
70584
- let validated;
70585
- let address2;
70586
- try {
70587
- validated = validatePrivateKey(privateKey);
70588
- address2 = privateKeyToAccount(validated).address;
70589
- } catch (error61) {
70590
- throw new VaultError("bad_key", "The imported private key is not valid.", {
70591
- cause: error61
70592
- });
70593
- }
70594
- const plaintext = Buffer.from(validated.slice(2), "hex");
70595
- let account;
70596
- try {
70597
- account = {
70598
- name,
70599
- kind: "imported",
70600
- address: address2,
70601
- key: sealField(this.key, plaintext),
70602
- createdAt: this.now().toISOString()
70603
- };
70604
- } finally {
70605
- plaintext.fill(0);
70606
- }
70607
- file2.accounts.push(account);
70608
- return copyAccount(account);
70609
- });
70610
- } catch (error61) {
70611
- throw asVaultError(error61, "corrupt", "Unable to import a vault account.");
70595
+ if (exists) {
70596
+ await withKey(options.path, options.env, async () => void 0);
70597
+ return;
70612
70598
  }
70613
- }
70614
- async removeAccount(name) {
70599
+ const salt = randomBytes6(32);
70600
+ const key = await deriveScryptKey(password, salt);
70615
70601
  try {
70616
- await this.update(async (file2) => {
70617
- const account = file2.accounts.find((candidate) => candidate.name === name);
70618
- if (!account) {
70619
- throw new VaultError("not_found", "No vault account has that name.");
70620
- }
70621
- if (!this.balanceOf) {
70622
- throw new VaultError(
70623
- "has_balance",
70624
- "The account balance could not be verified, so the key was not removed."
70625
- );
70626
- }
70627
- if (await this.balanceOf(account.address) > 0n) {
70628
- throw new VaultError(
70629
- "has_balance",
70630
- "This account still has a balance. Run vapi sweep before removing it."
70631
- );
70632
- }
70633
- file2.nextDerivedIndex = nextDerivedIndex(file2);
70634
- const currentIndex = file2.accounts.findIndex((candidate) => candidate.name === name);
70635
- if (currentIndex === -1) {
70636
- throw new VaultError("not_found", "No vault account has that name.");
70637
- }
70638
- file2.accounts.splice(currentIndex, 1);
70602
+ await writeJsonAtomic(
70603
+ options.path,
70604
+ {
70605
+ v: 1,
70606
+ salt: salt.toString("base64"),
70607
+ check: seal(key, CHECK_VALUE),
70608
+ entries: {}
70609
+ },
70610
+ { mode: 384 }
70611
+ );
70612
+ } finally {
70613
+ key.fill(0);
70614
+ }
70615
+ });
70616
+ }
70617
+ function fileSecretStore(options) {
70618
+ const env = options.env ?? process.env;
70619
+ const write = async (change) => await withVaultLock(
70620
+ options.path,
70621
+ async () => await withKey(options.path, env, async (file2, key) => {
70622
+ const changed = change(file2, key);
70623
+ if (changed) await writeJsonAtomic(options.path, file2, { mode: 384 });
70624
+ return changed;
70625
+ })
70626
+ );
70627
+ const get = async (name) => await withKey(options.path, env, async (file2, key) => {
70628
+ const sealed = Object.hasOwn(file2.entries, name) ? file2.entries[name] : void 0;
70629
+ return sealed === void 0 ? void 0 : open6(key, sealed);
70630
+ });
70631
+ return {
70632
+ // A locked backend still exists; it must never enable a plaintext fallback.
70633
+ available: true,
70634
+ platform: process.platform,
70635
+ description: "the encrypted vAPI secrets file",
70636
+ get,
70637
+ async has(name) {
70638
+ return await get(name) !== void 0;
70639
+ },
70640
+ async set(name, value) {
70641
+ if (name === "__proto__") {
70642
+ throw new KeystoreError("The secret name is reserved in the encrypted vAPI secrets file.");
70643
+ }
70644
+ await write((file2, key) => {
70645
+ file2.entries[name] = seal(key, value);
70646
+ return true;
70647
+ });
70648
+ },
70649
+ async remove(name) {
70650
+ return await write((file2) => {
70651
+ if (!Object.hasOwn(file2.entries, name)) return false;
70652
+ delete file2.entries[name];
70653
+ return true;
70639
70654
  });
70640
- } catch (error61) {
70641
- throw asVaultError(error61, "corrupt", "Unable to remove the vault account.");
70642
70655
  }
70656
+ };
70657
+ }
70658
+ async function withKey(path, env, operation) {
70659
+ const file2 = await readStoredFile(path);
70660
+ const key = await deriveScryptKey(passwordFrom(env), Buffer.from(file2.salt, "base64"));
70661
+ try {
70662
+ if (open6(key, file2.check) !== CHECK_VALUE) throw wrongPassword();
70663
+ return await operation(file2, key);
70664
+ } finally {
70665
+ key.fill(0);
70643
70666
  }
70644
- async rename(from16, to) {
70645
- try {
70646
- await this.update(async (file2) => {
70647
- const account = file2.accounts.find((candidate) => candidate.name === from16);
70648
- if (!account) {
70649
- throw new VaultError("not_found", "No vault account has that name.");
70650
- }
70651
- if (from16 === to) return;
70652
- assertAccountName(to);
70653
- if (file2.accounts.some((candidate) => candidate.name === to)) {
70654
- throw new VaultError("name_taken", "A vault account already has that name.");
70655
- }
70656
- account.name = to;
70657
- });
70658
- } catch (error61) {
70659
- throw asVaultError(error61, "corrupt", "Unable to rename the vault account.");
70660
- }
70667
+ }
70668
+ function passwordFrom(env) {
70669
+ const password = (env ?? process.env)[FILE_SECRET_STORE_PASSWORD_ENV];
70670
+ if (!password) {
70671
+ throw new KeystoreError(
70672
+ `This vault keeps its secrets in an encrypted file. Set ${FILE_SECRET_STORE_PASSWORD_ENV} to open it.`
70673
+ );
70661
70674
  }
70662
- async signer(name) {
70663
- try {
70664
- const latest = await readVaultFile(this.path, this.key);
70665
- this.file = latest;
70666
- const stored = latest.accounts.find((account2) => account2.name === name);
70667
- if (!stored) {
70668
- throw new VaultError("not_found", "No vault account has that name.");
70669
- }
70670
- let account;
70671
- if (stored.kind === "derived") {
70672
- const plaintext = decryptField(this.key, latest.phrase);
70673
- let seed;
70674
- try {
70675
- seed = phraseToSeed(plaintext.toString("utf8"));
70676
- account = privateKeyToAccount(
70677
- deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${stored.index}`)
70678
- );
70679
- } finally {
70680
- seed?.fill(0);
70681
- plaintext.fill(0);
70682
- }
70683
- } else {
70684
- const plaintext = decryptField(this.key, stored.key);
70685
- try {
70686
- if (plaintext.byteLength !== 32) {
70687
- throw new VaultError("corrupt", "An imported vault key has the wrong length.");
70688
- }
70689
- const privateKey = `0x${plaintext.toString("hex")}`;
70690
- account = privateKeyToAccount(privateKey);
70691
- } finally {
70692
- plaintext.fill(0);
70693
- }
70694
- }
70695
- if (account.address.toLowerCase() !== stored.address.toLowerCase()) {
70696
- throw new VaultError("corrupt", "A vault key does not match its stored address.");
70697
- }
70698
- return account;
70699
- } catch (error61) {
70700
- throw asVaultError(error61, "corrupt", "Unable to open the vault account signer.");
70675
+ return password;
70676
+ }
70677
+ async function readStoredFile(path) {
70678
+ let raw;
70679
+ try {
70680
+ raw = await readFile8(path, "utf8");
70681
+ } catch (error61) {
70682
+ throw new KeystoreError("The vAPI secrets file is missing. Run vapi setup again.", {
70683
+ cause: error61
70684
+ });
70685
+ }
70686
+ let value;
70687
+ try {
70688
+ value = JSON.parse(raw);
70689
+ } catch {
70690
+ throw new KeystoreError("The vAPI secrets file is damaged.");
70691
+ }
70692
+ const parsed = fileSchema.safeParse(value);
70693
+ if (!parsed.success) throw new KeystoreError("The vAPI secrets file is damaged.");
70694
+ return parsed.data;
70695
+ }
70696
+ function seal(key, value) {
70697
+ const { nonce, ciphertext, tag } = encryptWithKey(key, Buffer.from(value, "utf8"));
70698
+ return {
70699
+ nonce: nonce.toString("base64"),
70700
+ ciphertext: ciphertext.toString("base64"),
70701
+ tag: tag.toString("base64")
70702
+ };
70703
+ }
70704
+ function open6(key, sealed) {
70705
+ try {
70706
+ return decryptWithKey(key, {
70707
+ nonce: Buffer.from(sealed.nonce, "base64"),
70708
+ ciphertext: Buffer.from(sealed.ciphertext, "base64"),
70709
+ tag: Buffer.from(sealed.tag, "base64")
70710
+ }).toString("utf8");
70711
+ } catch (error61) {
70712
+ throw wrongPassword(error61);
70713
+ }
70714
+ }
70715
+ function wrongPassword(cause) {
70716
+ return new KeystoreError(`Wrong ${FILE_SECRET_STORE_PASSWORD_ENV} for the vAPI secrets file.`, {
70717
+ cause
70718
+ });
70719
+ }
70720
+
70721
+ // src/secret-backend.ts
70722
+ import { readFileSync } from "node:fs";
70723
+ import { stat as stat8 } from "node:fs/promises";
70724
+ import { join as join6 } from "node:path";
70725
+ var PROBE_ACCOUNT = "setup-probe";
70726
+ var pinSchema = external_exports.object({ v: external_exports.literal(1), backend: external_exports.enum(["os", "file"]) }).strict();
70727
+ function secretBackendPath(home = getVapiPaths().directory) {
70728
+ return join6(home, "secret-store.json");
70729
+ }
70730
+ function secretsFilePath(home = getVapiPaths().directory) {
70731
+ return join6(home, "secrets.json");
70732
+ }
70733
+ function readSecretBackend(home = getVapiPaths().directory) {
70734
+ const path = secretBackendPath(home);
70735
+ try {
70736
+ const parsed = pinSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
70737
+ if (parsed.success) return parsed.data.backend;
70738
+ } catch (error61) {
70739
+ if (isMissingFile(error61)) return "os";
70740
+ }
70741
+ throw new KeystoreError(`The vAPI secret-store pin at ${path} is damaged.`);
70742
+ }
70743
+ async function chooseSecretBackend(options) {
70744
+ const env = options.env ?? process.env;
70745
+ const osWorks = options.os.platform !== "linux" || await osStoreWorks(options.os);
70746
+ const path = secretBackendPath(options.home);
70747
+ return await withVaultLock(path, async () => {
70748
+ if (await fileExists(path)) return readSecretBackend(options.home);
70749
+ if (await fileExists(join6(options.home, "vault.json"))) return "os";
70750
+ let backend;
70751
+ if (osWorks) {
70752
+ backend = "os";
70753
+ } else if (env[FILE_SECRET_STORE_PASSWORD_ENV]) {
70754
+ await createFileSecretStore({ path: secretsFilePath(options.home), env });
70755
+ backend = "file";
70756
+ } else {
70757
+ throw new KeystoreError(
70758
+ [
70759
+ `This machine has no working keyring (${options.os.description}).`,
70760
+ `Set ${FILE_SECRET_STORE_PASSWORD_ENV} (at least ${FILE_SECRET_STORE_MIN_PASSWORD} characters; in a GitHub Codespace add it as a Codespaces secret) and run vapi setup again,`,
70761
+ "or run vapi on your own computer, or connect Claude from https://api.vapinetwork.ai/connect."
70762
+ ].join(" ")
70763
+ );
70701
70764
  }
70765
+ await writeJsonAtomic(path, { v: 1, backend }, { mode: 384 });
70766
+ return backend;
70767
+ });
70768
+ }
70769
+ async function fileExists(path) {
70770
+ try {
70771
+ await stat8(path);
70772
+ return true;
70773
+ } catch (error61) {
70774
+ if (isMissingFile(error61)) return false;
70775
+ throw error61;
70702
70776
  }
70703
- async phrase() {
70704
- const latest = await readVaultFile(this.path, this.key);
70705
- this.file = latest;
70706
- const plaintext = decryptField(this.key, latest.phrase);
70777
+ }
70778
+ async function osStoreWorks(store) {
70779
+ if (!store.available) return false;
70780
+ try {
70707
70781
  try {
70708
- try {
70709
- return validateRecoveryPhrase(plaintext.toString("utf8"));
70710
- } catch (error61) {
70711
- throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
70712
- cause: error61
70713
- });
70714
- }
70782
+ await store.set(PROBE_ACCOUNT, "ok");
70783
+ return await store.get(PROBE_ACCOUNT) === "ok";
70715
70784
  } finally {
70716
- plaintext.fill(0);
70785
+ await store.remove(PROBE_ACCOUNT);
70717
70786
  }
70787
+ } catch {
70788
+ return false;
70718
70789
  }
70719
- async save() {
70720
- try {
70721
- await this.update(async () => void 0);
70722
- } catch (error61) {
70723
- throw asVaultError(error61, "corrupt", "Unable to save the vault.");
70724
- }
70790
+ }
70791
+
70792
+ // src/secret-store.ts
70793
+ var SECRET_STORE_SERVICE = "vapi-network";
70794
+ var SECURITY_BINARY = "/usr/bin/security";
70795
+ var SECRET_TOOL_BINARY = "secret-tool";
70796
+ var WINDOWS_POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-Command", "-"];
70797
+ var SECURITY_ITEM_NOT_FOUND = 44;
70798
+ var WINDOWS_SECRET_SUCCESS = 0;
70799
+ var WINDOWS_SECRET_NOT_FOUND = 2;
70800
+ var UNSUPPORTED_PLATFORM = "No OS secret store on this platform yet; use VAPI_KEYSTORE_PASSWORD.";
70801
+ var SECRET_TOOL_MISSING = [
70802
+ "secret-tool is not installed, so the passphrase cannot be kept in the OS secret store.",
70803
+ "Install libsecret-tools (Debian, Ubuntu) or libsecret (Fedora, Arch), or use VAPI_KEYSTORE_PASSWORD."
70804
+ ].join(" ");
70805
+ var POWERSHELL_MISSING = [
70806
+ "Windows PowerShell (powershell.exe) was not found, so the passphrase cannot be kept in the OS secret store.",
70807
+ "Use VAPI_KEYSTORE_PASSWORD."
70808
+ ].join(" ");
70809
+ function secretStore(options = {}) {
70810
+ const home = options.home ?? getVapiPaths().directory;
70811
+ if (readSecretBackend(home) === "file") {
70812
+ return fileSecretStore({ path: secretsFilePath(home), env: options.env ?? process.env });
70725
70813
  }
70726
- resealSecrets(file2) {
70727
- const phrase = decryptField(this.key, file2.phrase);
70728
- try {
70729
- const accounts = file2.accounts.map((account) => {
70730
- if (account.kind === "derived") return { ...account };
70731
- const privateKey = decryptField(this.key, account.key);
70732
- try {
70733
- if (privateKey.byteLength !== 32) {
70734
- throw new VaultError("corrupt", "An imported vault key has the wrong length.");
70735
- }
70736
- return { ...account, key: sealField(this.key, privateKey) };
70737
- } finally {
70738
- privateKey.fill(0);
70814
+ return osSecretStore(options);
70815
+ }
70816
+ function osSecretStore(options = {}) {
70817
+ const platform2 = options.platform ?? process.platform;
70818
+ const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
70819
+ const env = options.env ?? process.env;
70820
+ const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
70821
+ if (platform2 === "darwin") return keychainStore(platform2, run);
70822
+ if (platform2 === "win32") return windowsDataProtectionStore(platform2, run, env, installed);
70823
+ if (platform2 === "linux") return libsecretStore(platform2, run, installed);
70824
+ return unsupportedStore(platform2);
70825
+ }
70826
+ function memorySecretStore(initial = {}) {
70827
+ const entries = new Map(Object.entries(initial));
70828
+ return {
70829
+ available: true,
70830
+ platform: process.platform,
70831
+ description: "an in-memory store",
70832
+ async get(name) {
70833
+ return entries.get(name);
70834
+ },
70835
+ async has(name) {
70836
+ return entries.has(name);
70837
+ },
70838
+ async set(name, passphrase) {
70839
+ entries.set(name, passphrase);
70840
+ },
70841
+ async remove(name) {
70842
+ return entries.delete(name);
70843
+ },
70844
+ async list() {
70845
+ return [...entries.keys()].sort();
70846
+ }
70847
+ };
70848
+ }
70849
+ function keychainStore(platform2, run) {
70850
+ const find = async (account, withPassword) => await run(SECURITY_BINARY, [
70851
+ "find-generic-password",
70852
+ "-a",
70853
+ account,
70854
+ "-s",
70855
+ SECRET_STORE_SERVICE,
70856
+ ...withPassword ? ["-w"] : []
70857
+ ]);
70858
+ const read = async (account, what) => {
70859
+ const result = await find(account, true);
70860
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return void 0;
70861
+ requireSuccess(result, what);
70862
+ const value = withoutTrailingNewline(result.stdout);
70863
+ return value.length === 0 ? void 0 : value;
70864
+ };
70865
+ const write = async (account, value, what) => {
70866
+ const result = await run(
70867
+ SECURITY_BINARY,
70868
+ [
70869
+ "add-generic-password",
70870
+ "-a",
70871
+ account,
70872
+ "-s",
70873
+ SECRET_STORE_SERVICE,
70874
+ "-l",
70875
+ `${SECRET_STORE_SERVICE} ${account}`,
70876
+ "-U",
70877
+ "-w"
70878
+ ],
70879
+ // `security` asks for the password and then for its confirmation.
70880
+ `${value}
70881
+ ${value}
70882
+ `
70883
+ );
70884
+ requireSuccess(result, what);
70885
+ };
70886
+ const erase = async (account, what) => {
70887
+ const result = await run(SECURITY_BINARY, [
70888
+ "delete-generic-password",
70889
+ "-a",
70890
+ account,
70891
+ "-s",
70892
+ SECRET_STORE_SERVICE
70893
+ ]);
70894
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
70895
+ requireSuccess(result, what);
70896
+ return true;
70897
+ };
70898
+ const erasePartsAfter = async (account, keep, what) => {
70899
+ for (let part = keep + 1; part <= MAX_KEYCHAIN_PARTS; part += 1) {
70900
+ if (!await erase(keychainPart(account, part), what)) return;
70901
+ }
70902
+ };
70903
+ return {
70904
+ available: true,
70905
+ platform: platform2,
70906
+ description: "the macOS Keychain",
70907
+ async get(name) {
70908
+ const account = accountFor(name);
70909
+ const what = `read the passphrase of ${name} from the macOS Keychain`;
70910
+ const value = await read(account, what);
70911
+ const parts = value === void 0 ? void 0 : chunkedPartCount(value);
70912
+ if (value === void 0 || parts === void 0) return value;
70913
+ let joined = "";
70914
+ for (let part = 1; part <= parts; part += 1) {
70915
+ const chunk = await read(keychainPart(account, part), what);
70916
+ if (chunk === void 0) {
70917
+ throw new KeystoreError(
70918
+ `The stored secret ${name} is incomplete in the macOS Keychain. Store it again.`
70919
+ );
70739
70920
  }
70740
- });
70741
- return {
70742
- ...file2,
70743
- phrase: sealField(this.key, phrase),
70744
- accounts
70745
- };
70746
- } finally {
70747
- phrase.fill(0);
70921
+ joined += chunk;
70922
+ }
70923
+ return joined;
70924
+ },
70925
+ async has(name) {
70926
+ const result = await find(accountFor(name), false);
70927
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
70928
+ requireSuccess(result, `look up ${name} in the macOS Keychain`);
70929
+ return true;
70930
+ },
70931
+ async set(name, passphrase) {
70932
+ requirePassphrase(passphrase);
70933
+ const account = accountFor(name);
70934
+ const what = `store the passphrase of ${name} in the macOS Keychain`;
70935
+ if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
70936
+ await write(account, passphrase, what);
70937
+ return;
70938
+ }
70939
+ const chunks = [];
70940
+ for (let index2 = 0; index2 < passphrase.length; index2 += KEYCHAIN_CHUNK) {
70941
+ chunks.push(passphrase.slice(index2, index2 + KEYCHAIN_CHUNK));
70942
+ }
70943
+ if (chunks.length > MAX_KEYCHAIN_PARTS) {
70944
+ throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
70945
+ }
70946
+ for (const [index2, chunk] of chunks.entries()) {
70947
+ await write(keychainPart(account, index2 + 1), chunk, what);
70948
+ }
70949
+ await erasePartsAfter(account, chunks.length, what);
70950
+ await write(account, `${CHUNKED_MARKER}${chunks.length}`, what);
70951
+ },
70952
+ async remove(name) {
70953
+ const account = accountFor(name);
70954
+ const what = `remove the passphrase of ${name} from the macOS Keychain`;
70955
+ const found = await find(account, true);
70956
+ if (found.code === SECURITY_ITEM_NOT_FOUND) return false;
70957
+ requireSuccess(found, what);
70958
+ if (chunkedPartCount(withoutTrailingNewline(found.stdout)) !== void 0) {
70959
+ await erasePartsAfter(account, 0, what);
70960
+ }
70961
+ return await erase(account, what);
70962
+ }
70963
+ };
70964
+ }
70965
+ var KEYCHAIN_PROMPT_LIMIT = 128;
70966
+ var KEYCHAIN_CHUNK = 120;
70967
+ var MAX_KEYCHAIN_PARTS = 32;
70968
+ var CHUNKED_MARKER = "vapi-chunked:v1:";
70969
+ function keychainPart(account, part) {
70970
+ return `${account}#${part}`;
70971
+ }
70972
+ function chunkedPartCount(value) {
70973
+ if (!value.startsWith(CHUNKED_MARKER)) return void 0;
70974
+ const parts = Number(value.slice(CHUNKED_MARKER.length));
70975
+ return Number.isInteger(parts) && parts > 0 && parts <= MAX_KEYCHAIN_PARTS ? parts : void 0;
70976
+ }
70977
+ function windowsSecretFileName(account) {
70978
+ let encoded = "";
70979
+ for (let index2 = 0; index2 < account.length; index2 += 1) {
70980
+ const character = account[index2];
70981
+ if (/^[a-z0-9._#-]$/u.test(character)) {
70982
+ encoded += character;
70983
+ continue;
70748
70984
  }
70985
+ encoded += `%${account.charCodeAt(index2).toString(16).toUpperCase().padStart(4, "0")}`;
70749
70986
  }
70750
- async update(operation) {
70751
- return await withVaultLock(this.path, async () => {
70752
- const latest = await readVaultFile(this.path, this.key);
70753
- const result = await operation(latest);
70754
- const rewritten = this.resealSecrets(latest);
70755
- await writeVaultFile(this.path, rewritten);
70756
- this.file = rewritten;
70757
- return result;
70758
- });
70987
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(encoded)) {
70988
+ encoded = `%${encoded.charCodeAt(0).toString(16).toUpperCase()}${encoded.slice(1)}`;
70759
70989
  }
70760
- };
70761
- async function createVault(args) {
70762
- assertVaultKey(args.key);
70763
- let phrase;
70764
- if (args.phrase === void 0) {
70765
- try {
70766
- phrase = generateRecoveryPhrase();
70767
- } catch (error61) {
70768
- throw new VaultError("corrupt", "Unable to generate a vault recovery phrase.", {
70769
- cause: error61
70770
- });
70990
+ return `${encoded}.bin`;
70991
+ }
70992
+ function windowsDataProtectionStore(platform2, run, env, installed) {
70993
+ const powershell = `${env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
70994
+ const fileDetails = (name) => {
70995
+ const file2 = windowsSecretFileName(accountFor(name));
70996
+ return { file: file2, account: file2.slice(0, -".bin".length) };
70997
+ };
70998
+ const script = (file2, operations) => [
70999
+ "$ErrorActionPreference = 'Stop'",
71000
+ "try {",
71001
+ " Add-Type -AssemblyName System.Security",
71002
+ " $dir = Join-Path $env:LOCALAPPDATA 'vapi-network\\secrets'",
71003
+ ` $path = Join-Path $dir '${file2}'`,
71004
+ ...operations.map((operation) => ` ${operation}`),
71005
+ "} catch {",
71006
+ " [Console]::Error.WriteLine($_.Exception.Message)",
71007
+ " exit 1",
71008
+ "}"
71009
+ ].join("\n");
71010
+ const execute = async (script2) => {
71011
+ const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
71012
+
71013
+ `);
71014
+ requirePowerShell(result);
71015
+ return result;
71016
+ };
71017
+ return {
71018
+ available: installed(powershell),
71019
+ platform: platform2,
71020
+ description: "Windows Data Protection (DPAPI)",
71021
+ async get(name) {
71022
+ const { file: file2, account } = fileDetails(name);
71023
+ const result = await execute(
71024
+ script(file2, [
71025
+ `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
71026
+ "$blob = [System.IO.File]::ReadAllBytes($path)",
71027
+ "$bytes = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
71028
+ "[Console]::Out.Write([Convert]::ToBase64String($bytes))",
71029
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71030
+ ])
71031
+ );
71032
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return void 0;
71033
+ requireSuccess(result, `read the passphrase of ${name} from Windows Data Protection`);
71034
+ const value = Buffer.from(result.stdout.trim(), "base64").toString("utf8");
71035
+ return value.length === 0 ? void 0 : value;
71036
+ },
71037
+ async has(name) {
71038
+ const { file: file2, account } = fileDetails(name);
71039
+ const result = await execute(
71040
+ script(file2, [
71041
+ `if (Test-Path -LiteralPath $path) { exit ${WINDOWS_SECRET_SUCCESS} }`,
71042
+ `[Console]::Error.WriteLine('No stored secret for ${account}.')`,
71043
+ `exit ${WINDOWS_SECRET_NOT_FOUND}`
71044
+ ])
71045
+ );
71046
+ if (result.code === WINDOWS_SECRET_SUCCESS) return true;
71047
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
71048
+ requireSuccess(result, `look up ${name} in Windows Data Protection`);
71049
+ return false;
71050
+ },
71051
+ async set(name, passphrase) {
71052
+ requirePassphrase(passphrase);
71053
+ const { file: file2 } = fileDetails(name);
71054
+ const value = Buffer.from(passphrase, "utf8").toString("base64");
71055
+ const result = await execute(
71056
+ script(file2, [
71057
+ "[void][System.IO.Directory]::CreateDirectory($dir)",
71058
+ `$bytes = [Convert]::FromBase64String('${value}')`,
71059
+ "$blob = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
71060
+ "[System.IO.File]::WriteAllBytes($path, $blob)",
71061
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71062
+ ])
71063
+ );
71064
+ requireSuccess(result, `store the passphrase of ${name} in Windows Data Protection`);
71065
+ },
71066
+ async remove(name) {
71067
+ const { file: file2, account } = fileDetails(name);
71068
+ const result = await execute(
71069
+ script(file2, [
71070
+ `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
71071
+ "Remove-Item -LiteralPath $path -Force",
71072
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71073
+ ])
71074
+ );
71075
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
71076
+ requireSuccess(result, `remove the passphrase of ${name} from Windows Data Protection`);
71077
+ return true;
70771
71078
  }
70772
- } else {
70773
- phrase = validateRecoveryPhrase(args.phrase);
71079
+ };
71080
+ }
71081
+ function libsecretStore(platform2, run, installed) {
71082
+ const lookup = async (name) => {
71083
+ const result = await run(SECRET_TOOL_BINARY, [
71084
+ "lookup",
71085
+ "service",
71086
+ SECRET_STORE_SERVICE,
71087
+ "account",
71088
+ accountFor(name)
71089
+ ]);
71090
+ requireBinary(result);
71091
+ const value = withoutTrailingNewline(result.stdout);
71092
+ if (result.code === 0) return value.length === 0 ? void 0 : value;
71093
+ if (result.stderr.trim().length === 0) return void 0;
71094
+ requireSuccess(result, `read the passphrase of ${name} from the secret service`);
71095
+ return void 0;
71096
+ };
71097
+ return {
71098
+ available: installed(SECRET_TOOL_BINARY),
71099
+ platform: platform2,
71100
+ description: "the libsecret keyring",
71101
+ get: lookup,
71102
+ async has(name) {
71103
+ return await lookup(name) !== void 0;
71104
+ },
71105
+ async set(name, passphrase) {
71106
+ requirePassphrase(passphrase);
71107
+ const account = accountFor(name);
71108
+ const result = await run(
71109
+ SECRET_TOOL_BINARY,
71110
+ [
71111
+ "store",
71112
+ `--label=${SECRET_STORE_SERVICE} ${account}`,
71113
+ "service",
71114
+ SECRET_STORE_SERVICE,
71115
+ "account",
71116
+ account
71117
+ ],
71118
+ `${passphrase}
71119
+ `
71120
+ );
71121
+ requireBinary(result);
71122
+ requireSuccess(result, `store the passphrase of ${name} in the secret service`);
71123
+ },
71124
+ async remove(name) {
71125
+ const existed = await lookup(name) !== void 0;
71126
+ const result = await run(SECRET_TOOL_BINARY, [
71127
+ "clear",
71128
+ "service",
71129
+ SECRET_STORE_SERVICE,
71130
+ "account",
71131
+ accountFor(name)
71132
+ ]);
71133
+ requireBinary(result);
71134
+ requireSuccess(result, `remove the passphrase of ${name} from the secret service`);
71135
+ return existed;
71136
+ }
71137
+ };
71138
+ }
71139
+ function unsupportedStore(platform2) {
71140
+ const refuse = () => {
71141
+ throw new KeystoreError(UNSUPPORTED_PLATFORM);
71142
+ };
71143
+ return {
71144
+ available: false,
71145
+ platform: platform2,
71146
+ description: "no OS secret store",
71147
+ get: async () => refuse(),
71148
+ has: async () => refuse(),
71149
+ set: async () => refuse(),
71150
+ remove: async () => refuse()
71151
+ };
71152
+ }
71153
+ function accountFor(name) {
71154
+ const account = name.trim();
71155
+ if (account.length === 0) {
71156
+ throw new KeystoreError("A wallet name is needed to reach the OS secret store.");
70774
71157
  }
70775
- try {
70776
- return await withVaultLock(args.path, async () => {
70777
- await refuseExistingVault(args.path);
70778
- const plaintext = Buffer.from(phrase, "utf8");
70779
- let sealedPhrase;
70780
- try {
70781
- sealedPhrase = sealField(args.key, plaintext);
70782
- } finally {
70783
- plaintext.fill(0);
70784
- }
70785
- const file2 = {
70786
- version: 2,
70787
- kdf: "device-key",
70788
- cipher: "aes-256-gcm",
70789
- phrase: sealedPhrase,
70790
- accounts: [],
70791
- nextDerivedIndex: 0,
70792
- protected: false
70793
- };
70794
- await writeVaultFile(args.path, file2);
70795
- return new DeviceVault(args, file2);
71158
+ return account;
71159
+ }
71160
+ function requirePassphrase(passphrase) {
71161
+ if (passphrase.length === 0) {
71162
+ throw new KeystoreError("Keystore passphrase cannot be empty.");
71163
+ }
71164
+ }
71165
+ function requireBinary(result) {
71166
+ if (result.notFound === true) throw new KeystoreError(SECRET_TOOL_MISSING);
71167
+ }
71168
+ function requirePowerShell(result) {
71169
+ if (result.notFound === true) throw new KeystoreError(POWERSHELL_MISSING);
71170
+ }
71171
+ function binaryInstalled(file2, env) {
71172
+ if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
71173
+ return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join7(directory, file2)));
71174
+ }
71175
+ var SAFE_FAILURE_DETAILS = [
71176
+ "Cannot autolaunch D-Bus without X11 $DISPLAY",
71177
+ "Cannot autolaunch D-Bus",
71178
+ "The name org.freedesktop.secrets was not provided by any .service files",
71179
+ "Cannot create an item in a locked collection",
71180
+ "User interaction is not allowed.",
71181
+ "Access to the path is denied."
71182
+ ];
71183
+ function requireSuccess(result, what) {
71184
+ if (result.code === 0) return;
71185
+ const detail = SAFE_FAILURE_DETAILS.find((reason) => result.stderr.includes(reason));
71186
+ throw new KeystoreError(
71187
+ `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail === void 0 ? "" : ` ${detail}`}`
71188
+ );
71189
+ }
71190
+ function withoutTrailingNewline(value) {
71191
+ return value.replace(/\r?\n$/u, "");
71192
+ }
71193
+ var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve2) => {
71194
+ let stdout = "";
71195
+ let stderr2 = "";
71196
+ let settled = false;
71197
+ const finish = (outcome) => {
71198
+ if (settled) return;
71199
+ settled = true;
71200
+ resolve2(outcome);
71201
+ };
71202
+ const child = spawn(file2, [...args], {
71203
+ detached: platform2 !== "win32",
71204
+ stdio: ["pipe", "pipe", "pipe"],
71205
+ windowsHide: true
71206
+ });
71207
+ child.stdout?.setEncoding("utf8");
71208
+ child.stdout?.on("data", (chunk) => {
71209
+ stdout += chunk;
71210
+ });
71211
+ child.stderr?.setEncoding("utf8");
71212
+ child.stderr?.on("data", (chunk) => {
71213
+ stderr2 += chunk;
71214
+ });
71215
+ child.on("error", (error61) => {
71216
+ finish({
71217
+ code: null,
71218
+ stdout,
71219
+ stderr: stderr2,
71220
+ ...error61.code === "ENOENT" ? { notFound: true } : {}
70796
71221
  });
70797
- } catch (error61) {
70798
- throw asVaultError(error61, "corrupt", "Unable to create the vault.");
71222
+ });
71223
+ child.on("close", (code) => finish({ code, stdout, stderr: stderr2 }));
71224
+ child.stdin?.on("error", () => void 0);
71225
+ child.stdin?.end(input2 ?? "");
71226
+ });
71227
+
71228
+ // src/passphrase.ts
71229
+ var PASSPHRASE_ENVIRONMENT_VARIABLE = "VAPI_KEYSTORE_PASSWORD";
71230
+ function noPassphraseHint(walletName) {
71231
+ return `Set ${PASSPHRASE_ENVIRONMENT_VARIABLE}, or store this wallet's passphrase once with vapi unlock --wallet ${walletName}.`;
71232
+ }
71233
+ function staleStoredPassphraseMessage(walletName, store) {
71234
+ return [
71235
+ `The passphrase stored in ${store.description} no longer opens wallet ${walletName}.`,
71236
+ `Store the current one with vapi unlock --wallet ${walletName}, or remove it with vapi lock --wallet ${walletName}.`
71237
+ ].join(" ");
71238
+ }
71239
+ async function resolvePassphrase(walletName, options = {}) {
71240
+ const env = options.env ?? process.env;
71241
+ const fromEnvironment = env[PASSPHRASE_ENVIRONMENT_VARIABLE];
71242
+ if (fromEnvironment !== void 0) {
71243
+ if (fromEnvironment.length === 0) {
71244
+ throw new KeystoreError(`${PASSPHRASE_ENVIRONMENT_VARIABLE} cannot be empty.`);
71245
+ }
71246
+ return { passphrase: fromEnvironment, source: "environment" };
70799
71247
  }
70800
- }
70801
- async function openVault(args) {
70802
- assertVaultKey(args.key);
70803
- return new DeviceVault(args, await readVaultFile(args.path, args.key));
70804
- }
70805
- async function reinstateVaultAccount(args) {
70806
- const parsedAccount = storedAccountSchema.safeParse(args.account);
70807
- if (!parsedAccount.success) {
70808
- throw new VaultError("corrupt", "The stored vault account has an invalid structure.", {
70809
- cause: parsedAccount.error
70810
- });
71248
+ if (options.confirm !== true) {
71249
+ const stored = await readStored(options.store ?? secretStore(), walletName);
71250
+ if (stored !== void 0) return { passphrase: stored, source: "secret-store" };
70811
71251
  }
70812
- assertVaultKey(args.key);
70813
- try {
70814
- return await withVaultLock(args.path, async () => {
70815
- const file2 = await readVaultFile(args.path, args.key);
70816
- const account = parsedAccount.data;
70817
- assertAvailableName(file2, account.name);
70818
- if (account.kind === "derived" && file2.accounts.some(
70819
- (candidate) => candidate.kind === "derived" && candidate.index === account.index
70820
- )) {
70821
- throw new VaultError("name_taken", "A vault account already uses that derived index.");
70822
- }
70823
- if (account.kind === "derived") validateStoredDerivedAccount(args.key, file2, account);
70824
- else validateStoredImportedAccount(args.key, account);
70825
- const updated = parseVaultFile(
70826
- JSON.stringify({
70827
- ...file2,
70828
- accounts: [...file2.accounts, account],
70829
- ...account.kind === "derived" ? { nextDerivedIndex: Math.max(nextDerivedIndex(file2), account.index + 1) } : {}
70830
- })
70831
- );
70832
- await writeVaultFile(args.path, updated);
70833
- return copyAccount(account);
70834
- });
70835
- } catch (error61) {
70836
- throw asVaultError(error61, "corrupt", "Unable to reinstate the vault account.");
71252
+ const hint = noPassphraseHint(walletName);
71253
+ if (options.interactive === false) {
71254
+ throw new KeystoreError(
71255
+ `No interactive terminal is available for the keystore prompt. ${hint}`
71256
+ );
70837
71257
  }
70838
- }
70839
- function assertVaultKey(key) {
70840
- if (key.byteLength !== 32) {
70841
- throw new VaultError("bad_key", "A device vault key must contain exactly 32 bytes.");
71258
+ const prompt = options.prompt ?? promptForSecret;
71259
+ const first = await prompt(`Passphrase for ${walletName}: `, hint);
71260
+ if (first.length === 0) {
71261
+ throw new KeystoreError("Keystore passphrase cannot be empty.");
70842
71262
  }
70843
- }
70844
- function assertAccountName(name) {
70845
- const parsed = walletNameSchema.safeParse(name);
70846
- if (!parsed.success) {
70847
- throw new VaultError("name_taken", "The vault account name is not valid.", {
70848
- cause: parsed.error
70849
- });
71263
+ if (options.confirm === true) {
71264
+ const second = await prompt("Confirm passphrase: ", hint);
71265
+ if (first !== second) throw new KeystoreError("Passphrases do not match.");
70850
71266
  }
71267
+ return { passphrase: first, source: "prompt" };
70851
71268
  }
70852
- function assertAvailableName(file2, name) {
70853
- assertAccountName(name);
70854
- if (file2.accounts.some((account) => account.name === name)) {
70855
- throw new VaultError("name_taken", "A vault account already has that name.");
71269
+ async function readStored(store, walletName) {
71270
+ if (!store.available) return void 0;
71271
+ try {
71272
+ return await store.get(walletName);
71273
+ } catch {
71274
+ return void 0;
70856
71275
  }
70857
71276
  }
70858
- function nextDerivedIndex(file2) {
70859
- let next = file2.nextDerivedIndex ?? 0;
70860
- for (const account of file2.accounts) {
70861
- if (account.kind === "derived") next = Math.max(next, account.index + 1);
70862
- }
70863
- return next;
71277
+
71278
+ // src/receipts.ts
71279
+ import { randomBytes as randomBytes8 } from "node:crypto";
71280
+ import { mkdir as mkdir8, open as open7, readFile as readFile9, rename as rename5, writeFile as writeFile4 } from "node:fs/promises";
71281
+ import { dirname as dirname6 } from "node:path";
71282
+
71283
+ // src/agent-run.ts
71284
+ import { randomBytes as randomBytes7 } from "node:crypto";
71285
+ var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
71286
+ function isRunId(value) {
71287
+ return typeof value === "string" && RUN_ID_PATTERN.test(value);
70864
71288
  }
70865
- function copyAccount(account) {
70866
- if (account.kind === "derived") return { ...account };
70867
- return {
70868
- name: account.name,
70869
- kind: account.kind,
70870
- address: account.address,
70871
- createdAt: account.createdAt
70872
- };
71289
+ function createRunId(random = randomBytes7) {
71290
+ return `run_${Buffer.from(random(12)).toString("hex")}`;
70873
71291
  }
70874
- function sealField(key, plaintext) {
70875
- const { nonce, ciphertext, tag } = encryptWithKey(key, plaintext);
70876
- return [nonce, ciphertext, tag].map((part) => part.toString("base64url")).join(".");
71292
+ var runRefSchema = external_exports.strictObject({
71293
+ id: external_exports.string().regex(RUN_ID_PATTERN),
71294
+ swarm: external_exports.string().optional(),
71295
+ member: external_exports.string().optional(),
71296
+ parentRunId: external_exports.string().optional()
71297
+ });
71298
+
71299
+ // src/receipts.ts
71300
+ var receiptTestHooks;
71301
+ function __setReceiptTestHooks(hooks) {
71302
+ receiptTestHooks = hooks;
70877
71303
  }
70878
- function openField(key, value) {
70879
- const [nonce = "", ciphertext = "", tag = ""] = value.split(".");
70880
- return decryptWithKey(key, {
70881
- nonce: Buffer.from(nonce, "base64url"),
70882
- ciphertext: Buffer.from(ciphertext, "base64url"),
70883
- tag: Buffer.from(tag, "base64url")
71304
+ var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
71305
+ async function withReceiptJournalLock(path, operation) {
71306
+ return await withFileLock(`${path}.lock`, operation, {
71307
+ lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
70884
71308
  });
70885
71309
  }
70886
- function decryptField(key, value) {
70887
- try {
70888
- return openField(key, value);
70889
- } catch (error61) {
70890
- throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70891
- cause: error61
70892
- });
70893
- }
70894
- }
70895
- function decryptPhraseForOpen(key, phrase) {
70896
- try {
70897
- return openField(key, phrase);
70898
- } catch (error61) {
70899
- throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70900
- cause: error61
70901
- });
71310
+ var durationSchema = external_exports.number().nonnegative().finite();
71311
+ var receiptSchema = external_exports.strictObject({
71312
+ id: external_exports.string().min(1),
71313
+ timestamp: external_exports.iso.datetime(),
71314
+ run: runRefSchema.optional(),
71315
+ kind: external_exports.literal("transfer").optional(),
71316
+ wallet: walletNameSchema.optional(),
71317
+ resourceUrl: external_exports.url(),
71318
+ method: external_exports.string().min(1).optional(),
71319
+ source: external_exports.string().min(1).optional(),
71320
+ provenance: external_exports.array(
71321
+ external_exports.strictObject({
71322
+ source: external_exports.string().min(1),
71323
+ sourceUrl: external_exports.string().optional(),
71324
+ ref: external_exports.string().optional()
71325
+ })
71326
+ ).optional(),
71327
+ quote: external_exports.strictObject({
71328
+ network: external_exports.string(),
71329
+ asset: external_exports.string().optional(),
71330
+ amountAtomic: external_exports.string().regex(/^\d+$/),
71331
+ payTo: external_exports.string().optional()
71332
+ }).optional(),
71333
+ payer: external_exports.string().optional(),
71334
+ paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
71335
+ authorization: external_exports.strictObject({
71336
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71337
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
71338
+ validBefore: external_exports.string().regex(/^\d+$/)
71339
+ }).optional(),
71340
+ transfer: external_exports.strictObject({
71341
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71342
+ toName: external_exports.string().min(1),
71343
+ toKind: external_exports.enum(["owner", "account"]),
71344
+ amountAtomic: external_exports.string().regex(/^\d+$/),
71345
+ network: external_exports.string().min(1),
71346
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
71347
+ status: external_exports.enum(["sent", "unknown", "failed"]),
71348
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
71349
+ replayed: external_exports.boolean(),
71350
+ reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
71351
+ request: external_exports.strictObject({
71352
+ authorization: external_exports.strictObject({
71353
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71354
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71355
+ value: external_exports.string().regex(/^\d+$/),
71356
+ validAfter: external_exports.string().regex(/^\d+$/),
71357
+ validBefore: external_exports.string().regex(/^\d+$/),
71358
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
71359
+ }),
71360
+ signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
71361
+ }).optional()
71362
+ }).optional(),
71363
+ settlement: external_exports.strictObject({
71364
+ outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
71365
+ transaction: external_exports.string().optional(),
71366
+ explorerUrl: external_exports.url().optional(),
71367
+ evidence: external_exports.unknown().optional()
71368
+ }).optional(),
71369
+ latencyMs: external_exports.number().nonnegative().finite().optional(),
71370
+ status: external_exports.number().int().min(100).max(599).optional(),
71371
+ error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
71372
+ phases: external_exports.strictObject({
71373
+ discoverMs: durationSchema.optional(),
71374
+ quoteMs: durationSchema.optional(),
71375
+ signMs: durationSchema.optional(),
71376
+ requestMs: durationSchema.optional(),
71377
+ settleMs: durationSchema.optional()
71378
+ }).optional(),
71379
+ listing: external_exports.strictObject({
71380
+ name: external_exports.string().min(1).optional(),
71381
+ providerHost: external_exports.string().min(1).optional(),
71382
+ source: external_exports.string().min(1)
71383
+ }).optional(),
71384
+ retry: external_exports.number().int().nonnegative().optional(),
71385
+ policy: external_exports.strictObject({
71386
+ maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
71387
+ capsApplied: external_exports.boolean()
71388
+ }).optional(),
71389
+ client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
71390
+ outcome: external_exports.enum([
71391
+ "paid",
71392
+ "signed_in",
71393
+ "declined_policy",
71394
+ "failed_request",
71395
+ "settlement_rejected",
71396
+ "settlement_unknown"
71397
+ ]).optional()
71398
+ });
71399
+ function parseReceipt(value) {
71400
+ const receipt = receiptSchema.parse(value);
71401
+ const transaction = receipt.settlement?.transaction;
71402
+ const network = receipt.quote?.network;
71403
+ const explorerUrl = transaction === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction);
71404
+ if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
71405
+ return receipt;
70902
71406
  }
70903
- }
70904
- function validateStoredImportedAccount(key, account) {
70905
- let plaintext;
70906
- try {
70907
- plaintext = decryptField(key, account.key);
70908
- if (plaintext.byteLength !== 32) {
70909
- throw new VaultError("bad_key", "The stored imported key has the wrong length.");
70910
- }
70911
- let address2;
70912
- try {
70913
- address2 = privateKeyToAccount(`0x${plaintext.toString("hex")}`).address;
70914
- } catch (error61) {
70915
- throw new VaultError("bad_key", "The stored imported key is not valid.", {
70916
- cause: error61
70917
- });
70918
- }
70919
- if (address2.toLowerCase() !== account.address.toLowerCase()) {
70920
- throw new VaultError("bad_key", "The stored imported key does not match its address.");
71407
+ return {
71408
+ ...receipt,
71409
+ settlement: {
71410
+ outcome: receipt.settlement.outcome,
71411
+ ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
71412
+ explorerUrl,
71413
+ ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
70921
71414
  }
70922
- } finally {
70923
- plaintext?.fill(0);
70924
- }
71415
+ };
70925
71416
  }
70926
- function validateStoredDerivedAccount(key, file2, account) {
70927
- const plaintext = decryptField(key, file2.phrase);
70928
- let seed;
70929
- try {
70930
- seed = phraseToSeed(plaintext.toString("utf8"));
70931
- const address2 = privateKeyToAccount(
70932
- deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${account.index}`)
70933
- ).address;
70934
- if (address2.toLowerCase() !== account.address.toLowerCase()) {
70935
- throw new VaultError("bad_key", "The stored derived account does not match this vault.");
71417
+ async function appendReceipt(receipt, path = getVapiPaths().receipts, options = {}) {
71418
+ const parsed = parseReceipt(
71419
+ receipt.wallet === void 0 && options.wallet !== void 0 ? { ...receipt, wallet: options.wallet } : receipt
71420
+ );
71421
+ await withReceiptJournalLock(path, async () => {
71422
+ await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71423
+ const handle = await open7(path, "a", 384);
71424
+ try {
71425
+ await handle.writeFile(`${JSON.stringify(parsed)}
71426
+ `, "utf8");
71427
+ } finally {
71428
+ await handle.close();
70936
71429
  }
70937
- } finally {
70938
- seed?.fill(0);
70939
- plaintext.fill(0);
70940
- }
71430
+ });
71431
+ return parsed;
70941
71432
  }
70942
- function parseVaultFile(raw) {
70943
- let value;
71433
+ async function readReceipts(path = getVapiPaths().receipts, options = {}) {
71434
+ let raw;
70944
71435
  try {
70945
- value = JSON.parse(raw);
71436
+ raw = await readFile9(path, "utf8");
70946
71437
  } catch (error61) {
70947
- throw new VaultError("corrupt", "The vault file is not valid JSON.", { cause: error61 });
70948
- }
70949
- const parsed = vaultFileSchema.safeParse(value);
70950
- if (!parsed.success) {
70951
- throw new VaultError("corrupt", "The vault file has an invalid structure.", {
70952
- cause: parsed.error
70953
- });
70954
- }
70955
- if (parsed.data.protected !== (parsed.data.wrappedKey !== void 0)) {
70956
- throw new VaultError("corrupt", "The vault protection metadata is inconsistent.");
71438
+ if (isMissingFile(error61)) return [];
71439
+ throw error61;
70957
71440
  }
70958
- const names = /* @__PURE__ */ new Set();
70959
- const indexes = /* @__PURE__ */ new Set();
70960
- for (const account of parsed.data.accounts) {
70961
- if (names.has(account.name)) {
70962
- throw new VaultError("corrupt", "The vault file contains duplicate account names.");
70963
- }
70964
- names.add(account.name);
70965
- if (account.kind === "derived") {
70966
- if (indexes.has(account.index)) {
70967
- throw new VaultError("corrupt", "The vault file contains duplicate derived indexes.");
71441
+ const records = coalesceTransferReceiptRevisions(
71442
+ raw.split("\n").filter((line) => line.trim().length > 0).map((line, index2) => {
71443
+ try {
71444
+ return parseReceipt(JSON.parse(line));
71445
+ } catch (error61) {
71446
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70968
71447
  }
70969
- indexes.add(account.index);
71448
+ })
71449
+ );
71450
+ const filtered = options.wallet === void 0 ? records : filterReceiptsByWallet(records, options.wallet);
71451
+ const limit = options.limit;
71452
+ if (limit === void 0) return filtered;
71453
+ if (!Number.isSafeInteger(limit) || limit < 0)
71454
+ throw new Error("Receipt limit must be a non-negative integer.");
71455
+ return limit === 0 ? [] : filtered.slice(-limit);
71456
+ }
71457
+ function coalesceTransferReceiptRevisions(receipts) {
71458
+ const coalesced = [];
71459
+ const transferIndexes = /* @__PURE__ */ new Map();
71460
+ for (const receipt of receipts) {
71461
+ const existing = receipt.kind === "transfer" ? transferIndexes.get(receipt.id) : void 0;
71462
+ if (existing === void 0) {
71463
+ if (receipt.kind === "transfer") transferIndexes.set(receipt.id, coalesced.length);
71464
+ coalesced.push(receipt);
71465
+ } else {
71466
+ coalesced[existing] = receipt;
70970
71467
  }
70971
71468
  }
70972
- return parsed.data;
71469
+ return coalesced;
70973
71470
  }
70974
- async function readVaultFile(path, key) {
70975
- const file2 = await readVaultFileUnlocked(path);
70976
- const plaintext = decryptPhraseForOpen(key, file2.phrase);
70977
- try {
71471
+ function receiptWallet(receipt) {
71472
+ return receipt.wallet ?? DEFAULT_WALLET_NAME;
71473
+ }
71474
+ function filterReceiptsByWallet(receipts, name) {
71475
+ return receipts.filter((receipt) => receiptWallet(receipt) === name);
71476
+ }
71477
+ async function renameReceiptWallet(from16, to, path = getVapiPaths().receipts) {
71478
+ return await withReceiptJournalLock(path, async () => {
71479
+ let raw;
70978
71480
  try {
70979
- validateRecoveryPhrase(plaintext.toString("utf8"));
71481
+ raw = await readFile9(path, "utf8");
70980
71482
  } catch (error61) {
70981
- throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
70982
- cause: error61
70983
- });
70984
- }
70985
- } finally {
70986
- plaintext.fill(0);
70987
- }
70988
- return file2;
70989
- }
70990
- async function readVaultFileUnlocked(path) {
70991
- let raw;
70992
- try {
70993
- raw = await readFile9(path, "utf8");
70994
- } catch (error61) {
70995
- if (isMissingFile2(error61)) {
70996
- throw new VaultError("not_found", "No vault file was found at the requested path.", {
70997
- cause: error61
70998
- });
71483
+ if (isMissingFile(error61)) return 0;
71484
+ throw error61;
70999
71485
  }
71000
- throw new VaultError("corrupt", "Unable to read the vault file.", { cause: error61 });
71001
- }
71002
- return parseVaultFile(raw);
71003
- }
71004
- async function refuseExistingVault(path) {
71005
- try {
71006
- await stat6(path);
71007
- } catch (error61) {
71008
- if (isMissingFile2(error61)) return;
71009
- throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
71010
- cause: error61
71486
+ let changed = 0;
71487
+ const lines = raw.split("\n").map((line, index2) => {
71488
+ if (line.trim().length === 0) return line;
71489
+ let parsed;
71490
+ try {
71491
+ parsed = JSON.parse(line);
71492
+ } catch (error61) {
71493
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71494
+ }
71495
+ const current = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "wallet") : void 0;
71496
+ if ((typeof current === "string" ? current : DEFAULT_WALLET_NAME) !== from16) return line;
71497
+ changed += 1;
71498
+ return JSON.stringify(parseReceipt({ ...parsed, wallet: to }));
71011
71499
  });
71012
- }
71013
- throw new VaultError("corrupt", "A vault already exists at the requested path.");
71014
- }
71015
- async function writeVaultFile(path, file2) {
71016
- await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71017
- const temporaryPath = `${path}.${process.pid}.${randomBytes7(6).toString("hex")}.tmp`;
71018
- try {
71019
- await writeFile4(temporaryPath, `${JSON.stringify(file2, null, 2)}
71020
- `, {
71500
+ if (changed === 0) return 0;
71501
+ await receiptTestHooks?.beforeRenameReplace?.(path);
71502
+ await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71503
+ const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
71504
+ await writeFile4(temporaryPath, lines.join("\n"), {
71021
71505
  encoding: "utf8",
71022
71506
  mode: 384,
71023
71507
  flag: "wx"
71024
71508
  });
71025
71509
  await rename5(temporaryPath, path);
71510
+ return changed;
71511
+ });
71512
+ }
71513
+
71514
+ // src/transfer-journal.ts
71515
+ import { readFile as readFile10 } from "node:fs/promises";
71516
+ async function readTransferJournal(home, from16, nonce) {
71517
+ let raw;
71518
+ try {
71519
+ raw = await readFile10(getVapiPaths(home).receipts, "utf8");
71026
71520
  } catch (error61) {
71027
- await rm(temporaryPath, { force: true }).catch(() => void 0);
71521
+ if (isMissingFile(error61)) return { signed: false };
71028
71522
  throw error61;
71029
71523
  }
71030
- }
71031
- async function withVaultLock(path, operation) {
71032
- await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71033
- const lockPath = `${path}.lock`;
71034
- const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
71035
- let handle;
71036
- while (!handle) {
71524
+ let latest;
71525
+ let request;
71526
+ for (const [index2, line] of raw.split("\n").entries()) {
71527
+ if (!line.trim()) continue;
71528
+ let receipt;
71037
71529
  try {
71038
- handle = await open6(lockPath, "wx", 384);
71530
+ receipt = parseReceipt(JSON.parse(line));
71039
71531
  } catch (error61) {
71040
- if (!isExistingFile(error61)) throw error61;
71041
- await removeStaleVaultLock(lockPath);
71042
- if (Date.now() >= deadline) {
71043
- throw new VaultError("corrupt", "Timed out waiting for the vault lock.");
71044
- }
71045
- await new Promise((resolve2) => setTimeout(resolve2, 20));
71532
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71046
71533
  }
71534
+ if (receiptWallet(receipt) !== from16 || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
71535
+ continue;
71536
+ }
71537
+ latest = receipt;
71538
+ if (receipt.transfer.request !== void 0) request = receipt;
71047
71539
  }
71048
- try {
71049
- return await operation();
71050
- } finally {
71051
- await handle.close();
71052
- await unlink4(lockPath).catch(() => void 0);
71053
- }
71054
- }
71055
- async function removeStaleVaultLock(path) {
71056
- try {
71057
- const metadata = await stat6(path);
71058
- if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
71059
- } catch (error61) {
71060
- if (!isMissingFile2(error61)) throw error61;
71061
- }
71062
- }
71063
- function isMissingFile2(error61) {
71064
- return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
71065
- }
71066
- function isExistingFile(error61) {
71067
- return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "EEXIST";
71068
- }
71069
- function asVaultError(error61, code, message) {
71070
- return error61 instanceof VaultError ? error61 : new VaultError(code, message, { cause: error61 });
71540
+ return {
71541
+ signed: latest !== void 0,
71542
+ ...latest === void 0 ? {} : { latest },
71543
+ ...request === void 0 ? {} : { request },
71544
+ ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
71545
+ ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
71546
+ };
71071
71547
  }
71072
71548
 
71073
71549
  // src/vault-key.ts
71550
+ import { randomBytes as cryptoRandomBytes } from "node:crypto";
71074
71551
  var VAULT_KEY_ACCOUNT = "vault-key";
71075
71552
  var VAULT_SESSION_ACCOUNT = "vault-session";
71076
71553
  var DEVICE_KEY_LENGTH = 32;
@@ -71298,8 +71775,8 @@ function passwordRequiredError() {
71298
71775
  "A vault password is needed. Pass it or set VAPI_VAULT_PASSWORD."
71299
71776
  );
71300
71777
  }
71301
- function randomKeyBytes(randomBytes16) {
71302
- const key = Buffer.from((randomBytes16 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
71778
+ function randomKeyBytes(randomBytes17) {
71779
+ const key = Buffer.from((randomBytes17 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
71303
71780
  if (key.byteLength !== DEVICE_KEY_LENGTH) {
71304
71781
  key.fill(0);
71305
71782
  throw new VaultError("corrupt", "A generated device vault key has the wrong length.");
@@ -71350,7 +71827,7 @@ function parseJson(value) {
71350
71827
  function asVaultError2(error61, message) {
71351
71828
  return error61 instanceof VaultError ? error61 : new VaultError("corrupt", message, { cause: error61 });
71352
71829
  }
71353
- var HEADLESS_LINUX_HINT = "A server, container or GitHub Codespace usually has no keyring. Run vapi on your own computer, or connect Claude from https://api.vapinetwork.ai/connect.";
71830
+ var HEADLESS_LINUX_HINT = "A server, container or GitHub Codespace usually has no keyring. Set VAPI_VAULT_PASSWORD and run vapi setup again, or run vapi on your own computer.";
71354
71831
  function deviceKeyFailureMessage(error61, platform2) {
71355
71832
  if (!(error61 instanceof KeystoreError)) return "Unable to load or create the device vault key.";
71356
71833
  const detail = `Unable to load or create the device vault key: ${error61.message.replace(/\.$/u, "")}.`;
@@ -71362,19 +71839,19 @@ import {
71362
71839
  chmod as chmod2,
71363
71840
  lstat,
71364
71841
  mkdir as mkdir9,
71365
- readFile as readFile10,
71842
+ readFile as readFile11,
71366
71843
  readlink,
71367
71844
  readdir as readdir2,
71368
71845
  rename as rename6,
71369
71846
  symlink,
71370
71847
  unlink as unlink5
71371
71848
  } from "node:fs/promises";
71372
- import { join as join7, resolve } from "node:path";
71849
+ import { join as join8, resolve } from "node:path";
71373
71850
  var MIGRATED_DIRECTORY = "wallets.migrated";
71374
71851
  async function legacyKeystoreNames(home) {
71375
71852
  let entries;
71376
71853
  try {
71377
- entries = await readdir2(join7(home, "wallets"), { withFileTypes: true });
71854
+ entries = await readdir2(join8(home, "wallets"), { withFileTypes: true });
71378
71855
  } catch (error61) {
71379
71856
  if (isMissingFile(error61)) return [];
71380
71857
  throw error61;
@@ -71390,14 +71867,14 @@ async function migrateKeystores(args) {
71390
71867
  );
71391
71868
  const result = { imported: [], skipped: [] };
71392
71869
  for (const name of names) {
71393
- const source = join7(args.home, "wallets", `${name}.json`);
71870
+ const source = join8(args.home, "wallets", `${name}.json`);
71394
71871
  if (args.vault.accounts().some((account) => account.name === name)) {
71395
71872
  result.skipped.push({ name, reason: "name_taken" });
71396
71873
  continue;
71397
71874
  }
71398
71875
  let parsed;
71399
71876
  try {
71400
- parsed = parseAnyKeystore(JSON.parse(await readFile10(source, "utf8")));
71877
+ parsed = parseAnyKeystore(JSON.parse(await readFile11(source, "utf8")));
71401
71878
  } catch {
71402
71879
  result.skipped.push({ name, reason: "unreadable" });
71403
71880
  continue;
@@ -71427,15 +71904,15 @@ async function migrateKeystores(args) {
71427
71904
  if (imported.address.toLowerCase() !== parsed.address.toLowerCase()) {
71428
71905
  throw new KeystoreError(`Migrated wallet ${name} does not match its stored address.`);
71429
71906
  }
71430
- const migratedDirectory = join7(args.home, MIGRATED_DIRECTORY);
71431
- const destination = join7(migratedDirectory, `${name}.json`);
71907
+ const migratedDirectory = join8(args.home, MIGRATED_DIRECTORY);
71908
+ const destination = join8(migratedDirectory, `${name}.json`);
71432
71909
  await mkdir9(migratedDirectory, { recursive: true, mode: 448 });
71433
71910
  await archiveExistingDestination(destination, migratedDirectory, name, now);
71434
71911
  await rename6(source, destination);
71435
71912
  await chmod2(destination, 384);
71436
71913
  try {
71437
71914
  await removeCompatibilityLink(args.home, source);
71438
- await symlink(join7("..", MIGRATED_DIRECTORY, `${name}.json`), source);
71915
+ await symlink(join8("..", MIGRATED_DIRECTORY, `${name}.json`), source);
71439
71916
  await audit({
71440
71917
  event: "vault.migrate",
71441
71918
  wallet: name,
@@ -71463,16 +71940,16 @@ async function migrateKeystores(args) {
71463
71940
  async function archiveExistingDestination(destination, directory, name, now) {
71464
71941
  if (!await pathExists2(destination)) return;
71465
71942
  const timestamp = now().toISOString();
71466
- let archive = join7(directory, `${name}.${timestamp}.json`);
71943
+ let archive = join8(directory, `${name}.${timestamp}.json`);
71467
71944
  let suffix = 1;
71468
71945
  while (await pathExists2(archive)) {
71469
- archive = join7(directory, `${name}.${timestamp}.${suffix}.json`);
71946
+ archive = join8(directory, `${name}.${timestamp}.${suffix}.json`);
71470
71947
  suffix += 1;
71471
71948
  }
71472
71949
  await rename6(destination, archive);
71473
71950
  }
71474
71951
  async function removeCompatibilityLink(home, migratedSource) {
71475
- const compatibilityPath = join7(home, "keystore.json");
71952
+ const compatibilityPath = join8(home, "keystore.json");
71476
71953
  let metadata;
71477
71954
  try {
71478
71955
  metadata = await lstat(compatibilityPath);
@@ -71546,7 +72023,7 @@ var WalletStore = class _WalletStore {
71546
72023
  this.home = home;
71547
72024
  this.options = options;
71548
72025
  this.registry = registry2;
71549
- this.secrets = options.secrets ?? secretStore();
72026
+ this.secrets = options.secrets ?? secretStore({ home });
71550
72027
  this.environment = options.env ?? process.env;
71551
72028
  this.passphraseResolver = options.resolvePassphrase ?? defaultPassphraseResolver(this.environment, this.secrets);
71552
72029
  this.audit = options.audit ?? (async (record2) => await appendAudit(this.home, record2, { now: () => this.now() }));
@@ -71593,17 +72070,17 @@ var WalletStore = class _WalletStore {
71593
72070
  return store;
71594
72071
  }
71595
72072
  get registryPath() {
71596
- return join8(this.home, REGISTRY_FILE);
72073
+ return join9(this.home, REGISTRY_FILE);
71597
72074
  }
71598
72075
  get walletsDirectory() {
71599
- return join8(this.home, WALLETS_DIRECTORY);
72076
+ return join9(this.home, WALLETS_DIRECTORY);
71600
72077
  }
71601
72078
  get trashDirectory() {
71602
- return join8(this.walletsDirectory, TRASH_DIRECTORY);
72079
+ return join9(this.walletsDirectory, TRASH_DIRECTORY);
71603
72080
  }
71604
72081
  /** The legacy 0.5 keystore path of a wallet, whether or not it exists. */
71605
72082
  pathFor(name) {
71606
- return join8(this.walletsDirectory, `${assertWalletName(name)}.json`);
72083
+ return join9(this.walletsDirectory, `${assertWalletName(name)}.json`);
71607
72084
  }
71608
72085
  /** The names this machine knows, in registry order. */
71609
72086
  names() {
@@ -72176,7 +72653,7 @@ var WalletStore = class _WalletStore {
72176
72653
  }
72177
72654
  const removedAt = this.now().toISOString();
72178
72655
  await mkdir10(this.trashDirectory, { recursive: true, mode: 448 });
72179
- const trashedPath = join8(this.trashDirectory, `${wallet.name}-${removedAt}.json`);
72656
+ const trashedPath = join9(this.trashDirectory, `${wallet.name}-${removedAt}.json`);
72180
72657
  const storedAccount = (await this.readVaultUnlocked())?.accounts.find(
72181
72658
  (candidate) => candidate.name === wallet.name
72182
72659
  );
@@ -72198,7 +72675,7 @@ var WalletStore = class _WalletStore {
72198
72675
  this.balanceProbe = void 0;
72199
72676
  }
72200
72677
  if (await pathExists3(wallet.path)) {
72201
- const legacyTrashedPath = join8(
72678
+ const legacyTrashedPath = join9(
72202
72679
  this.trashDirectory,
72203
72680
  `${wallet.name}-${removedAt}.legacy.json`
72204
72681
  );
@@ -72288,7 +72765,7 @@ var WalletStore = class _WalletStore {
72288
72765
  if (!match) continue;
72289
72766
  const [, name, removedAt] = match;
72290
72767
  if (name === void 0 || removedAt === void 0 || !isWalletName(name)) continue;
72291
- const path = join8(this.trashDirectory, file2);
72768
+ const path = join9(this.trashDirectory, file2);
72292
72769
  const entry = await readEntrySidecar(entrySidecarPath(path));
72293
72770
  trashed.push({ name, removedAt, path, ...entry ? { entry } : {} });
72294
72771
  }
@@ -72357,7 +72834,7 @@ var WalletStore = class _WalletStore {
72357
72834
  return entry;
72358
72835
  }
72359
72836
  get vaultPath() {
72360
- return join8(this.home, VAULT_FILE);
72837
+ return join9(this.home, VAULT_FILE);
72361
72838
  }
72362
72839
  async readVaultUnlocked() {
72363
72840
  try {
@@ -72462,7 +72939,7 @@ var WalletStore = class _WalletStore {
72462
72939
  async readRegistry() {
72463
72940
  let raw;
72464
72941
  try {
72465
- raw = await readFile11(this.registryPath, "utf8");
72942
+ raw = await readFile12(this.registryPath, "utf8");
72466
72943
  } catch (error61) {
72467
72944
  if (isMissingFile(error61)) return emptyRegistry();
72468
72945
  throw error61;
@@ -72483,7 +72960,7 @@ var WalletStore = class _WalletStore {
72483
72960
  }
72484
72961
  };
72485
72962
  async function swarmReferencingAccount(home, account) {
72486
- const directory = join8(home, "swarms");
72963
+ const directory = join9(home, "swarms");
72487
72964
  let files;
72488
72965
  try {
72489
72966
  files = await readdir3(directory);
@@ -72494,7 +72971,7 @@ async function swarmReferencingAccount(home, account) {
72494
72971
  for (const file2 of files.filter((name) => name.endsWith(".json")).sort()) {
72495
72972
  let value;
72496
72973
  try {
72497
- value = JSON.parse(await readFile11(join8(directory, file2), "utf8"));
72974
+ value = JSON.parse(await readFile12(join9(directory, file2), "utf8"));
72498
72975
  } catch {
72499
72976
  throw new KeystoreError(
72500
72977
  `Cannot verify swarm references because ${file2} is invalid. Repair or remove that swarm file before renaming an account.`
@@ -72526,7 +73003,7 @@ async function swarmReferencingAccount(home, account) {
72526
73003
  return void 0;
72527
73004
  }
72528
73005
  async function unfinishedMovementReferencingAccount(home, account) {
72529
- const directory = join8(home, "movements");
73006
+ const directory = join9(home, "movements");
72530
73007
  let files;
72531
73008
  try {
72532
73009
  files = await readdir3(directory);
@@ -72537,7 +73014,7 @@ async function unfinishedMovementReferencingAccount(home, account) {
72537
73014
  for (const file2 of files.filter((name) => name.endsWith(".json")).sort()) {
72538
73015
  let value;
72539
73016
  try {
72540
- value = JSON.parse(await readFile11(join8(directory, file2), "utf8"));
73017
+ value = JSON.parse(await readFile12(join9(directory, file2), "utf8"));
72541
73018
  } catch {
72542
73019
  throw invalidMovementReferenceError(file2);
72543
73020
  }
@@ -72558,11 +73035,11 @@ async function unfinishedMovementReferencingAccount(home, account) {
72558
73035
  const restored = Reflect.get(leg, "restored");
72559
73036
  const legFrom = Reflect.get(leg, "from") ?? movementFrom;
72560
73037
  const journal = restored !== true && status === "failed" && retryable !== true && typeof nonce === "string" ? await readTransferJournal(home, legFrom, nonce) : void 0;
72561
- const open12 = isOpenMovementLeg(
73038
+ const open13 = isOpenMovementLeg(
72562
73039
  { status, retryable, nonce, restored },
72563
73040
  journal?.signed === true ? "signed" : "unsigned"
72564
73041
  );
72565
- if (open12) movementOpen = true;
73042
+ if (open13) movementOpen = true;
72566
73043
  }
72567
73044
  if (movementOpen && (movementFrom === account || legs.some(
72568
73045
  (leg) => (Reflect.get(leg, "from") ?? movementFrom) === account || Reflect.get(leg, "to") === account
@@ -72598,7 +73075,7 @@ async function withAccountMutationLocks(home, accounts, command, operation) {
72598
73075
  const [account, ...remaining] = [...new Set(accounts)].sort();
72599
73076
  if (account === void 0) return await operation();
72600
73077
  return await withFileLock(
72601
- join8(home, `.account-${account}.lock`),
73078
+ join9(home, `.account-${account}.lock`),
72602
73079
  async () => await withAccountMutationLocks(home, remaining, command, operation),
72603
73080
  {
72604
73081
  lockedMessage: `Account ${account} is busy with another account change. Wait for it to finish, then retry ${command}.`
@@ -72673,7 +73150,7 @@ function isLockedVaultError(error61) {
72673
73150
  async function readTrashedVaultAccount(path) {
72674
73151
  let parsed;
72675
73152
  try {
72676
- parsed = JSON.parse(await readFile11(path, "utf8"));
73153
+ parsed = JSON.parse(await readFile12(path, "utf8"));
72677
73154
  } catch {
72678
73155
  return void 0;
72679
73156
  }
@@ -72682,7 +73159,7 @@ async function readTrashedVaultAccount(path) {
72682
73159
  }
72683
73160
  async function readEntrySidecar(path) {
72684
73161
  try {
72685
- const parsed = walletEntrySchema.safeParse(JSON.parse(await readFile11(path, "utf8")));
73162
+ const parsed = walletEntrySchema.safeParse(JSON.parse(await readFile12(path, "utf8")));
72686
73163
  return parsed.success ? parsed.data : void 0;
72687
73164
  } catch {
72688
73165
  return void 0;
@@ -72691,7 +73168,7 @@ async function readEntrySidecar(path) {
72691
73168
  async function readKeystoreSummary(path) {
72692
73169
  let parsed;
72693
73170
  try {
72694
- parsed = JSON.parse(await readFile11(path, "utf8"));
73171
+ parsed = JSON.parse(await readFile12(path, "utf8"));
72695
73172
  } catch {
72696
73173
  return {};
72697
73174
  }
@@ -72709,7 +73186,7 @@ async function readKeystoreSummary(path) {
72709
73186
  }
72710
73187
  async function readConfiguredSpendCaps(configPath) {
72711
73188
  try {
72712
- const parsed = JSON.parse(await readFile11(configPath, "utf8"));
73189
+ const parsed = JSON.parse(await readFile12(configPath, "utf8"));
72713
73190
  const caps = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "spendCaps") : void 0;
72714
73191
  const result = spendCapsSchema.safeParse(caps);
72715
73192
  if (result.success) return result.data;
@@ -72801,7 +73278,7 @@ async function withRegistryLock(path, operation) {
72801
73278
  let handle;
72802
73279
  while (!handle) {
72803
73280
  try {
72804
- handle = await open7(lockPath, "wx", 384);
73281
+ handle = await open8(lockPath, "wx", 384);
72805
73282
  } catch (error61) {
72806
73283
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
72807
73284
  await removeStaleRegistryLock(lockPath);
@@ -72820,7 +73297,7 @@ async function withRegistryLock(path, operation) {
72820
73297
  }
72821
73298
  async function removeStaleRegistryLock(path) {
72822
73299
  try {
72823
- const metadata = await stat7(path);
73300
+ const metadata = await stat9(path);
72824
73301
  if (Date.now() - metadata.mtimeMs > 3e4) await unlink6(path);
72825
73302
  } catch (error61) {
72826
73303
  if (!isMissingFile(error61)) throw error61;
@@ -72828,7 +73305,7 @@ async function removeStaleRegistryLock(path) {
72828
73305
  }
72829
73306
  async function writeJsonFile(path, value) {
72830
73307
  await mkdir10(dirname7(path), { recursive: true, mode: 448 });
72831
- const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
73308
+ const temporaryPath = `${path}.${process.pid}.${randomBytes9(6).toString("hex")}.tmp`;
72832
73309
  await writeFile5(temporaryPath, `${JSON.stringify(value, null, 2)}
72833
73310
  `, {
72834
73311
  encoding: "utf8",
@@ -72866,7 +73343,7 @@ async function createAccount(args) {
72866
73343
  created: false
72867
73344
  };
72868
73345
  }
72869
- if (!await fileExists(join9(args.store.home, "vault.json"))) {
73346
+ if (!await fileExists2(join10(args.store.home, "vault.json"))) {
72870
73347
  throw new KeystoreError("No vault yet. Run vapi setup.");
72871
73348
  }
72872
73349
  const spendCaps = resolveNewAccountCaps(args.caps);
@@ -73133,9 +73610,9 @@ async function requireAddress(store, name) {
73133
73610
  if (address2 === void 0) throw new KeystoreError(`No key for wallet ${name} in the vault.`);
73134
73611
  return address2;
73135
73612
  }
73136
- async function fileExists(path) {
73613
+ async function fileExists2(path) {
73137
73614
  try {
73138
- await stat8(path);
73615
+ await stat10(path);
73139
73616
  return true;
73140
73617
  } catch (error61) {
73141
73618
  if (isMissingFile(error61)) return false;
@@ -73197,9 +73674,9 @@ function secretsAllowed(env, streams) {
73197
73674
  }
73198
73675
 
73199
73676
  // src/agent-profile.ts
73200
- import { randomBytes as randomBytes9 } from "node:crypto";
73201
- import { mkdir as mkdir11, readFile as readFile12, readdir as readdir4, rename as rename8, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
73202
- import { join as join10 } from "node:path";
73677
+ import { randomBytes as randomBytes10 } from "node:crypto";
73678
+ import { mkdir as mkdir11, readFile as readFile13, readdir as readdir4, rename as rename8, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
73679
+ import { join as join11 } from "node:path";
73203
73680
  var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
73204
73681
  var AGENT_GRANTS = ["read", "delegate", "allocate"];
73205
73682
  var agentProfileShape = {
@@ -73229,7 +73706,7 @@ async function readAgentProfile(home, name, options = {}) {
73229
73706
  const path = agentProfilePath(home, name);
73230
73707
  let raw;
73231
73708
  try {
73232
- raw = await readFile12(path, "utf8");
73709
+ raw = await readFile13(path, "utf8");
73233
73710
  } catch (error61) {
73234
73711
  if (isMissingFile(error61)) {
73235
73712
  throw new Error(`No agent named ${name}. Create it with vapi agent create ${name}.`);
@@ -73241,9 +73718,9 @@ async function readAgentProfile(home, name, options = {}) {
73241
73718
  async function writeAgentProfile(home, profile, options = {}) {
73242
73719
  const parsed = (options.schema ?? agentProfileSchema).parse(profile);
73243
73720
  const directory = getVapiPaths(home).agentsDir;
73244
- const path = join10(directory, `${parsed.name}.json`);
73721
+ const path = join11(directory, `${parsed.name}.json`);
73245
73722
  await mkdir11(directory, { recursive: true, mode: 448 });
73246
- const temporaryPath = `${path}.${process.pid}.${randomBytes9(6).toString("hex")}.tmp`;
73723
+ const temporaryPath = `${path}.${process.pid}.${randomBytes10(6).toString("hex")}.tmp`;
73247
73724
  await writeFile6(temporaryPath, `${JSON.stringify(parsed, null, 2)}
73248
73725
  `, {
73249
73726
  encoding: "utf8",
@@ -73268,7 +73745,7 @@ async function listAgentProfiles(home, options = {}) {
73268
73745
  try {
73269
73746
  profiles.push(
73270
73747
  (options.schema ?? agentProfileSchema).parse(
73271
- JSON.parse(await readFile12(join10(directory, file2), "utf8"))
73748
+ JSON.parse(await readFile13(join11(directory, file2), "utf8"))
73272
73749
  )
73273
73750
  );
73274
73751
  } catch {
@@ -73289,11 +73766,11 @@ async function removeAgentProfile(home, name) {
73289
73766
  }
73290
73767
  function agentProfilePath(home, name) {
73291
73768
  const parsedName = walletNameSchema.parse(name);
73292
- return join10(getVapiPaths(home).agentsDir, `${parsedName}.json`);
73769
+ return join11(getVapiPaths(home).agentsDir, `${parsedName}.json`);
73293
73770
  }
73294
73771
 
73295
73772
  // src/ceiling.ts
73296
- import { randomBytes as randomBytes13 } from "node:crypto";
73773
+ import { randomBytes as randomBytes14 } from "node:crypto";
73297
73774
 
73298
73775
  // src/authorization-state.ts
73299
73776
  var EIP3009_AUTHORIZATION_STATE_ABI = [
@@ -73358,13 +73835,13 @@ function missingAuthorization(receipt) {
73358
73835
  }
73359
73836
 
73360
73837
  // src/movement.ts
73361
- import { randomBytes as randomBytes12 } from "node:crypto";
73362
- import { chmod as chmod4, mkdir as mkdir14, open as open10, readFile as readFile14, readdir as readdir5, rename as rename10, unlink as unlink10 } from "node:fs/promises";
73363
- import { join as join11 } from "node:path";
73838
+ import { randomBytes as randomBytes13 } from "node:crypto";
73839
+ import { chmod as chmod4, mkdir as mkdir14, open as open11, readFile as readFile15, readdir as readdir5, rename as rename10, unlink as unlink10 } from "node:fs/promises";
73840
+ import { join as join12 } from "node:path";
73364
73841
 
73365
73842
  // src/spend-policy.ts
73366
- import { randomBytes as randomBytes10 } from "node:crypto";
73367
- import { mkdir as mkdir12, open as open8, readFile as readFile13, rename as rename9, stat as stat9, unlink as unlink8, writeFile as writeFile7 } from "node:fs/promises";
73843
+ import { randomBytes as randomBytes11 } from "node:crypto";
73844
+ import { mkdir as mkdir12, open as open9, readFile as readFile14, rename as rename9, stat as stat11, unlink as unlink8, writeFile as writeFile7 } from "node:fs/promises";
73368
73845
  import { dirname as dirname8 } from "node:path";
73369
73846
  var ledgerSchema = external_exports.object({
73370
73847
  date: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
@@ -73435,7 +73912,7 @@ async function readSpendLedgerRows(path = getAgentCashPaths().ledger, now = /* @
73435
73912
  async function readStoredSpendLedgerRows(path, now, allDays = false) {
73436
73913
  let raw;
73437
73914
  try {
73438
- raw = await readFile13(path, "utf8");
73915
+ raw = await readFile14(path, "utf8");
73439
73916
  } catch (error61) {
73440
73917
  if (isMissingFile(error61)) return [];
73441
73918
  throw error61;
@@ -73568,7 +74045,7 @@ async function reserveSpend(amountAtomic, caps, options) {
73568
74045
  { amountAtomic, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
73569
74046
  );
73570
74047
  }
73571
- const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes10(16).toString("hex"));
74048
+ const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes11(16).toString("hex"));
73572
74049
  const nextRow = {
73573
74050
  date: utcDateKey(now),
73574
74051
  spentAtomic: nextSpent.toString(),
@@ -73674,7 +74151,7 @@ async function writeLedgerAtomically(path, rows) {
73674
74151
  ...rows[0].reservations === void 0 ? {} : { reservations: rows[0].reservations }
73675
74152
  } : { version: 1, rows };
73676
74153
  await mkdir12(dirname8(path), { recursive: true, mode: 448 });
73677
- const temporaryPath = `${path}.${process.pid}.${randomBytes10(6).toString("hex")}.tmp`;
74154
+ const temporaryPath = `${path}.${process.pid}.${randomBytes11(6).toString("hex")}.tmp`;
73678
74155
  await writeFile7(temporaryPath, `${JSON.stringify(ledger, null, 2)}
73679
74156
  `, {
73680
74157
  encoding: "utf8",
@@ -73690,7 +74167,7 @@ async function withLedgerLock(path, operation) {
73690
74167
  let handle;
73691
74168
  while (!handle) {
73692
74169
  try {
73693
- handle = await open8(lockPath, "wx", 384);
74170
+ handle = await open9(lockPath, "wx", 384);
73694
74171
  } catch (error61) {
73695
74172
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) {
73696
74173
  throw error61;
@@ -73711,7 +74188,7 @@ async function withLedgerLock(path, operation) {
73711
74188
  }
73712
74189
  async function removeStaleLock3(path) {
73713
74190
  try {
73714
- const metadata = await stat9(path);
74191
+ const metadata = await stat11(path);
73715
74192
  if (Date.now() - metadata.mtimeMs > 3e4) {
73716
74193
  await unlink8(path);
73717
74194
  }
@@ -73723,8 +74200,8 @@ async function removeStaleLock3(path) {
73723
74200
  }
73724
74201
 
73725
74202
  // src/transfer.ts
73726
- import { randomBytes as randomBytes11, randomUUID } from "node:crypto";
73727
- import { mkdir as mkdir13, open as open9, stat as stat10, unlink as unlink9 } from "node:fs/promises";
74203
+ import { randomBytes as randomBytes12, randomUUID } from "node:crypto";
74204
+ import { mkdir as mkdir13, open as open10, stat as stat12, unlink as unlink9 } from "node:fs/promises";
73728
74205
  import { dirname as dirname9 } from "node:path";
73729
74206
 
73730
74207
  // src/siblings.ts
@@ -73933,7 +74410,7 @@ async function transferBetweenAccounts(args) {
73933
74410
  if (args.resume !== void 0) {
73934
74411
  return await resumeTransfer(context, args.resume);
73935
74412
  }
73936
- const nonce = args.nonce ?? bytesToHex(randomBytes11(32));
74413
+ const nonce = args.nonce ?? bytesToHex(randomBytes12(32));
73937
74414
  if (!NONCE_PATTERN.test(nonce)) {
73938
74415
  throw new TransferError(
73939
74416
  "authorization_invalid",
@@ -74326,7 +74803,7 @@ async function withTransferLock(context, nonce, operation) {
74326
74803
  let handle;
74327
74804
  while (!handle) {
74328
74805
  try {
74329
- handle = await open9(lockPath, "wx", 384);
74806
+ handle = await open10(lockPath, "wx", 384);
74330
74807
  } catch (error61) {
74331
74808
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
74332
74809
  await removeStaleTransferLock(lockPath, staleAfterMs);
@@ -74345,7 +74822,7 @@ async function withTransferLock(context, nonce, operation) {
74345
74822
  }
74346
74823
  async function removeStaleTransferLock(path, staleAfterMs) {
74347
74824
  try {
74348
- const metadata = await stat10(path);
74825
+ const metadata = await stat12(path);
74349
74826
  if (Date.now() - metadata.mtimeMs > staleAfterMs) await unlink9(path);
74350
74827
  } catch (error61) {
74351
74828
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "ENOENT")) throw error61;
@@ -74771,7 +75248,7 @@ async function listUnfinishedMovements(options) {
74771
75248
  }
74772
75249
  const summaries = [];
74773
75250
  for (const name of names.filter((candidate) => candidate.endsWith(".json")).sort()) {
74774
- const movement = parseMovement(JSON.parse(await readFile14(join11(directory, name), "utf8")));
75251
+ const movement = parseMovement(JSON.parse(await readFile15(join12(directory, name), "utf8")));
74775
75252
  if (options.from !== void 0 && !movement.legs.some((leg) => leg.from === options.from)) {
74776
75253
  continue;
74777
75254
  }
@@ -74805,7 +75282,7 @@ async function readMovement(home, id) {
74805
75282
  const safeId = parseMovementId(id);
74806
75283
  try {
74807
75284
  return parseMovement(
74808
- JSON.parse(await readFile14(join11(movementsDirectory(home), `${safeId}.json`), "utf8"))
75285
+ JSON.parse(await readFile15(join12(movementsDirectory(home), `${safeId}.json`), "utf8"))
74809
75286
  );
74810
75287
  } catch (error61) {
74811
75288
  if (isMissingFile(error61)) {
@@ -75477,33 +75954,33 @@ function parseMovementId(value) {
75477
75954
  return parsed.data;
75478
75955
  }
75479
75956
  function movementsDirectory(home) {
75480
- return join11(home, "movements");
75957
+ return join12(home, "movements");
75481
75958
  }
75482
75959
  function createMovementId() {
75483
- return `mv_${randomBytes12(12).toString("hex")}`;
75960
+ return `mv_${randomBytes13(12).toString("hex")}`;
75484
75961
  }
75485
75962
  function createMovementNonce() {
75486
- return bytesToHex(randomBytes12(32));
75963
+ return bytesToHex(randomBytes13(32));
75487
75964
  }
75488
75965
  async function writeMovement(home, movement) {
75489
75966
  const parsed = movementSchema.parse(movement);
75490
75967
  const directory = movementsDirectory(home);
75491
75968
  await mkdir14(directory, { recursive: true, mode: 448 });
75492
75969
  await chmod4(directory, 448);
75493
- const path = join11(directory, `${parsed.id}.json`);
75494
- const temporary = join11(
75970
+ const path = join12(directory, `${parsed.id}.json`);
75971
+ const temporary = join12(
75495
75972
  directory,
75496
- `.${parsed.id}.${process.pid}.${randomBytes12(6).toString("hex")}.tmp`
75973
+ `.${parsed.id}.${process.pid}.${randomBytes13(6).toString("hex")}.tmp`
75497
75974
  );
75498
75975
  let handle;
75499
75976
  try {
75500
- handle = await open10(temporary, "wx", 384);
75977
+ handle = await open11(temporary, "wx", 384);
75501
75978
  await handle.writeFile(serializeMovement(parsed), "utf8");
75502
75979
  await handle.sync();
75503
75980
  await handle.close();
75504
75981
  handle = void 0;
75505
75982
  await rename10(temporary, path);
75506
- const directoryHandle = await open10(directory, "r");
75983
+ const directoryHandle = await open11(directory, "r");
75507
75984
  try {
75508
75985
  await directoryHandle.sync();
75509
75986
  } finally {
@@ -75723,7 +76200,7 @@ async function sweepAboveCeilingLocked(args) {
75723
76200
  owner,
75724
76201
  target,
75725
76202
  amountAtomic: amountAtomic.toString(),
75726
- nonce: (args.randomNonce ?? (() => bytesToHex(randomBytes13(32))))(),
76203
+ nonce: (args.randomNonce ?? (() => bytesToHex(randomBytes14(32))))(),
75727
76204
  createdAt: new Date(now()).toISOString(),
75728
76205
  status: "planned"
75729
76206
  };
@@ -76515,8 +76992,8 @@ function parseDecimal(value, scale) {
76515
76992
  }
76516
76993
 
76517
76994
  // src/swarm.ts
76518
- import { readdir as readdir6, readFile as readFile15, stat as stat11, unlink as unlink11 } from "node:fs/promises";
76519
- import { join as join12 } from "node:path";
76995
+ import { readdir as readdir6, readFile as readFile16, stat as stat13, unlink as unlink11 } from "node:fs/promises";
76996
+ import { join as join13 } from "node:path";
76520
76997
  var SWARM_NAME_PATTERN = /^[a-z][a-z0-9-]{0,15}$/;
76521
76998
  var SWARM_ROLE_PATTERN = /^[a-z][a-z0-9]{0,7}$/;
76522
76999
  var DEFAULT_SWARM_MODEL = "venice/claude-sonnet-5";
@@ -76597,16 +77074,16 @@ var SwarmError = class extends Error {
76597
77074
  code;
76598
77075
  };
76599
77076
  function swarmsDirectory(home) {
76600
- return join12(home, "swarms");
77077
+ return join13(home, "swarms");
76601
77078
  }
76602
77079
  function swarmFilePath(home, name) {
76603
77080
  assertName(name);
76604
- return join12(swarmsDirectory(home), `${name}.json`);
77081
+ return join13(swarmsDirectory(home), `${name}.json`);
76605
77082
  }
76606
77083
  async function readSwarm(home, name) {
76607
77084
  const path = swarmFilePath(home, name);
76608
77085
  try {
76609
- const swarm = parseSwarm(JSON.parse(await readFile15(path, "utf8")));
77086
+ const swarm = parseSwarm(JSON.parse(await readFile16(path, "utf8")));
76610
77087
  if (swarm.name !== name)
76611
77088
  throw new SwarmError("invalid_swarm", "Swarm name does not match its file.");
76612
77089
  return swarm;
@@ -76634,7 +77111,7 @@ async function writeSwarm(home, value) {
76634
77111
  const bytes = `${JSON.stringify(swarm, null, 2)}
76635
77112
  `;
76636
77113
  try {
76637
- if (await readFile15(path, "utf8") === bytes) return;
77114
+ if (await readFile16(path, "utf8") === bytes) return;
76638
77115
  } catch (error61) {
76639
77116
  if (!isMissingFile(error61)) throw error61;
76640
77117
  }
@@ -76649,7 +77126,7 @@ async function deleteSwarmFile(home, name) {
76649
77126
  }
76650
77127
  async function withSwarmLock(home, name, fn) {
76651
77128
  assertName(name);
76652
- const path = join12(swarmsDirectory(home), `.${name}.lock`);
77129
+ const path = join13(swarmsDirectory(home), `.${name}.lock`);
76653
77130
  try {
76654
77131
  return await withFileLock(path, fn, { lockedMessage: `Swarm ${name} is locked.` });
76655
77132
  } catch (error61) {
@@ -76961,7 +77438,7 @@ async function swarmStatus(opts) {
76961
77438
  );
76962
77439
  let movementFiles;
76963
77440
  try {
76964
- movementFiles = await readdir6(join12(home, "movements"));
77441
+ movementFiles = await readdir6(join13(home, "movements"));
76965
77442
  } catch (error61) {
76966
77443
  if (!isMissingFile(error61)) throw error61;
76967
77444
  movementFiles = [];
@@ -77018,11 +77495,11 @@ async function swarmStatus(opts) {
77018
77495
  })
77019
77496
  );
77020
77497
  const accounts = new Set(swarmAccountNames(swarm));
77021
- const open12 = [];
77498
+ const open13 = [];
77022
77499
  for (const summary2 of await listUnfinishedMovements({ home })) {
77023
77500
  const movement = await readMovement(home, summary2.id);
77024
77501
  if (movement.treasury === swarm.treasury.account || movement.legs.some((leg) => accounts.has(leg.from) || accounts.has(leg.to))) {
77025
- open12.push(summary2);
77502
+ open13.push(summary2);
77026
77503
  }
77027
77504
  }
77028
77505
  return {
@@ -77031,7 +77508,7 @@ async function swarmStatus(opts) {
77031
77508
  strategy: swarm.policy.strategy,
77032
77509
  treasury,
77033
77510
  members: members2,
77034
- openMovements: open12.sort(
77511
+ openMovements: open13.sort(
77035
77512
  (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)
77036
77513
  )
77037
77514
  };
@@ -77130,7 +77607,7 @@ async function assertNoConflicts(home, name, accounts) {
77130
77607
  }
77131
77608
  async function profileExists(home, account) {
77132
77609
  try {
77133
- await stat11(join12(getVapiPaths(home).agentsDir, `${account}.json`));
77610
+ await stat13(join13(getVapiPaths(home).agentsDir, `${account}.json`));
77134
77611
  return true;
77135
77612
  } catch (error61) {
77136
77613
  if (isMissingFile(error61)) return false;
@@ -77143,7 +77620,7 @@ async function refuseTreasuryProfile(home, account) {
77143
77620
  }
77144
77621
 
77145
77622
  // src/x402-pay.ts
77146
- import { randomBytes as randomBytes14, randomUUID as randomUUID2 } from "node:crypto";
77623
+ import { randomBytes as randomBytes15, randomUUID as randomUUID2 } from "node:crypto";
77147
77624
 
77148
77625
  // src/run-budget.ts
77149
77626
  var RunBudgetError = class extends Error {
@@ -77184,13 +77661,13 @@ function createRunBudget(args) {
77184
77661
  // src/support-report.ts
77185
77662
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
77186
77663
  import { arch, platform, release } from "node:os";
77187
- import { join as join13 } from "node:path";
77188
- var VAPI_CLIENT_VERSION = "0.12.1";
77664
+ import { join as join14 } from "node:path";
77665
+ var VAPI_CLIENT_VERSION = "0.14.0";
77189
77666
  async function createSupportReport(options) {
77190
77667
  const message = options.message.trim();
77191
77668
  if (!message) throw new Error("Support report message must not be empty.");
77192
77669
  const paths = getVapiPaths();
77193
- const reportsDirectory = options.reportsDirectory ?? join13(paths.directory, "reports");
77670
+ const reportsDirectory = options.reportsDirectory ?? join14(paths.directory, "reports");
77194
77671
  const receipts = await readReceipts(options.receiptsPath ?? paths.receipts, { limit: 5 });
77195
77672
  const system = options.systemInfo ?? defaultSystemInfo();
77196
77673
  const report = {
@@ -77220,7 +77697,7 @@ async function createSupportReport(options) {
77220
77697
  };
77221
77698
  const now = options.now ?? /* @__PURE__ */ new Date();
77222
77699
  const timestamp = now.toISOString();
77223
- const path = join13(reportsDirectory, `${sanitizeTimestamp(timestamp)}.json`);
77700
+ const path = join14(reportsDirectory, `${sanitizeTimestamp(timestamp)}.json`);
77224
77701
  await mkdir15(reportsDirectory, { recursive: true, mode: 448 });
77225
77702
  const serialized = `${JSON.stringify(report, null, 2)}
77226
77703
  `;
@@ -77416,7 +77893,7 @@ async function completeX402Payment(args) {
77416
77893
  throw walletCapError(error61, quote.amountAtomic, args);
77417
77894
  }
77418
77895
  } else {
77419
- reservationId = args.paymentId ?? `x402_${randomBytes14(12).toString("hex")}`;
77896
+ reservationId = args.paymentId ?? `x402_${randomBytes15(12).toString("hex")}`;
77420
77897
  let reservation;
77421
77898
  try {
77422
77899
  reservation = await reserveSpend(quote.amountAtomic, args.caps, {
@@ -78444,7 +78921,7 @@ function validateAmount(amountUsd) {
78444
78921
  }
78445
78922
 
78446
78923
  // src/searches.ts
78447
- import { mkdir as mkdir16, open as open11, readFile as readFile16 } from "node:fs/promises";
78924
+ import { mkdir as mkdir16, open as open12, readFile as readFile17 } from "node:fs/promises";
78448
78925
  import { dirname as dirname10 } from "node:path";
78449
78926
  var searchEventSchema = external_exports.strictObject({
78450
78927
  timestamp: external_exports.iso.datetime(),
@@ -78466,7 +78943,7 @@ function parseSearchEvent(value) {
78466
78943
  async function appendSearchEvent(event, path = getVapiPaths().searches) {
78467
78944
  const parsed = parseSearchEvent(event);
78468
78945
  await mkdir16(dirname10(path), { recursive: true, mode: 448 });
78469
- const handle = await open11(path, "a", 384);
78946
+ const handle = await open12(path, "a", 384);
78470
78947
  try {
78471
78948
  await handle.writeFile(`${JSON.stringify(parsed)}
78472
78949
  `, "utf8");
@@ -78478,7 +78955,7 @@ async function appendSearchEvent(event, path = getVapiPaths().searches) {
78478
78955
  async function readSearchEvents(path = getVapiPaths().searches) {
78479
78956
  let raw;
78480
78957
  try {
78481
- raw = await readFile16(path, "utf8");
78958
+ raw = await readFile17(path, "utf8");
78482
78959
  } catch (error61) {
78483
78960
  if (isMissingFile(error61)) return [];
78484
78961
  throw error61;
@@ -79583,9 +80060,9 @@ function csvCell(value) {
79583
80060
  }
79584
80061
 
79585
80062
  // src/swarm-capital.ts
79586
- import { createHash as createHash3, randomBytes as randomBytes15 } from "node:crypto";
79587
- import { readFile as readFile17, unlink as unlink12 } from "node:fs/promises";
79588
- import { join as join14 } from "node:path";
80063
+ import { createHash as createHash3, randomBytes as randomBytes16 } from "node:crypto";
80064
+ import { readFile as readFile18, unlink as unlink12 } from "node:fs/promises";
80065
+ import { join as join15 } from "node:path";
79589
80066
  var movementIdSchema3 = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/u);
79590
80067
  var amountSchema2 = external_exports.string().regex(/^\d+\.\d{2}$/u);
79591
80068
  var requestIdSchema = external_exports.string().min(1).max(512);
@@ -80466,7 +80943,7 @@ async function readDelegationRecord(home, movementId) {
80466
80943
  const safeId = runRecordMovementId(movementId);
80467
80944
  try {
80468
80945
  const record2 = delegationRecordSchema.parse(
80469
- JSON.parse(await readFile17(delegationRecordPath(home, safeId), "utf8"))
80946
+ JSON.parse(await readFile18(delegationRecordPath(home, safeId), "utf8"))
80470
80947
  );
80471
80948
  if (record2.movementId !== safeId) {
80472
80949
  throw new SwarmError(
@@ -80493,7 +80970,7 @@ async function readTreasuryRequestRecord(home, movementId) {
80493
80970
  const safeId = runRecordMovementId(movementId);
80494
80971
  try {
80495
80972
  const record2 = treasuryRequestRecordSchema.parse(
80496
- JSON.parse(await readFile17(treasuryRequestRecordPath(home, safeId), "utf8"))
80973
+ JSON.parse(await readFile18(treasuryRequestRecordPath(home, safeId), "utf8"))
80497
80974
  );
80498
80975
  if (record2.movementId !== safeId) {
80499
80976
  throw new SwarmError(
@@ -80524,18 +81001,18 @@ function runRecordMovementId(value) {
80524
81001
  return parsed.data;
80525
81002
  }
80526
81003
  function treasuryRequestRecordPath(home, movementId) {
80527
- return join14(home, "runs", "requests", `${movementId}.json`);
81004
+ return join15(home, "runs", "requests", `${movementId}.json`);
80528
81005
  }
80529
81006
  function delegationRecordPath(home, movementId) {
80530
- return join14(home, "runs", "delegations", `${movementId}.json`);
81007
+ return join15(home, "runs", "delegations", `${movementId}.json`);
80531
81008
  }
80532
81009
  function legacyFundingProgressPath(home, name) {
80533
- return join14(home, "swarms", `.${name}.funding`);
81010
+ return join15(home, "swarms", `.${name}.funding`);
80534
81011
  }
80535
81012
  async function readLegacyFundingProgress(home, name) {
80536
81013
  try {
80537
81014
  const progress = legacyFundingProgressSchema.parse(
80538
- JSON.parse(await readFile17(legacyFundingProgressPath(home, name), "utf8"))
81015
+ JSON.parse(await readFile18(legacyFundingProgressPath(home, name), "utf8"))
80539
81016
  );
80540
81017
  if (progress.name !== name) {
80541
81018
  throw new SwarmError("invalid_swarm", `Invalid funding progress for swarm ${name}.`);
@@ -80764,7 +81241,7 @@ async function optionalMovement(home, id) {
80764
81241
  }
80765
81242
  }
80766
81243
  function nextMovementId(deps) {
80767
- return movementIdSchema3.parse(deps.randomId?.() ?? `mv_${randomBytes15(12).toString("hex")}`);
81244
+ return movementIdSchema3.parse(deps.randomId?.() ?? `mv_${randomBytes16(12).toString("hex")}`);
80768
81245
  }
80769
81246
  async function executeRecordedMovement(id, plan, deps, home, options = {}) {
80770
81247
  try {
@@ -81180,7 +81657,7 @@ async function removeMemberLocked(home, swarm, account) {
81180
81657
  }
81181
81658
 
81182
81659
  // src/status.ts
81183
- import { join as join15 } from "node:path";
81660
+ import { join as join16 } from "node:path";
81184
81661
  var STATUS_TIMEOUT_MS = 2e3;
81185
81662
  async function buildStatus(deps) {
81186
81663
  const timers = deps.timers ?? { setTimeout, clearTimeout };
@@ -81236,7 +81713,7 @@ function formatUsdAmount(value) {
81236
81713
  }
81237
81714
  async function readVaultStatus(deps) {
81238
81715
  const store = deps.secrets.description.replace(/^the /u, "");
81239
- const path = join15(deps.home, "vault.json");
81716
+ const path = join16(deps.home, "vault.json");
81240
81717
  let file2;
81241
81718
  try {
81242
81719
  file2 = await readVaultFileUnlocked(path);
@@ -81670,7 +82147,7 @@ function isRecord4(value) {
81670
82147
 
81671
82148
  // src/vault-setup.ts
81672
82149
  import { rm as rm2 } from "node:fs/promises";
81673
- import { join as join16 } from "node:path";
82150
+ import { join as join17 } from "node:path";
81674
82151
  async function createVault2(home, options) {
81675
82152
  if (options.password === "") {
81676
82153
  throw new KeystoreError("A password cannot be empty.");
@@ -81682,7 +82159,7 @@ async function createVault2(home, options) {
81682
82159
  const hadDeviceKey = options.password !== void 0 && await options.secrets.has(VAULT_KEY_ACCOUNT);
81683
82160
  await store.createEmptyVault();
81684
82161
  if (options.password !== void 0) {
81685
- const path = join16(home, "vault.json");
82162
+ const path = join17(home, "vault.json");
81686
82163
  try {
81687
82164
  await protectVault({
81688
82165
  path,
@@ -81804,6 +82281,8 @@ export {
81804
82281
  ERC20_ABI,
81805
82282
  EVM_DERIVATION_PATH,
81806
82283
  EXECUTION_MODES,
82284
+ FILE_SECRET_STORE_MIN_PASSWORD,
82285
+ FILE_SECRET_STORE_PASSWORD_ENV,
81807
82286
  FIRST_PARTY_PROVENANCES,
81808
82287
  FileLockedError,
81809
82288
  KeystoreError,
@@ -81817,6 +82296,8 @@ export {
81817
82296
  MARKETPLACE_RANKING_VERSION,
81818
82297
  MAX_RESTORE_ACCOUNTS,
81819
82298
  MovementError,
82299
+ NATIVE_ETH_FEE_MARGIN_PERCENT,
82300
+ NATIVE_ETH_L1_FEE_FALLBACK_WEI,
81820
82301
  NETWORKS2 as NETWORKS,
81821
82302
  ONRAMP_FALLBACK_INSTRUCTIONS,
81822
82303
  ONRAMP_NETWORK,
@@ -81896,6 +82377,7 @@ export {
81896
82377
  ceilingFloorApplies,
81897
82378
  changeKeystorePassphrase,
81898
82379
  checkReceiptSettlement,
82380
+ chooseSecretBackend,
81899
82381
  classifySettlement,
81900
82382
  completeX402Payment,
81901
82383
  configSchema,
@@ -81903,6 +82385,7 @@ export {
81903
82385
  createAccount,
81904
82386
  createAgentProfileSchema,
81905
82387
  createChain,
82388
+ createFileSecretStore,
81906
82389
  createKeystore,
81907
82390
  createKeystoreFromPrivateKey,
81908
82391
  createNetworkHttpTransport,
@@ -81942,6 +82425,7 @@ export {
81942
82425
  explorerAddressUrl,
81943
82426
  explorerTransactionUrl,
81944
82427
  fetchSiblings,
82428
+ fileSecretStore,
81945
82429
  filterReceiptsByRange,
81946
82430
  filterReceiptsByWallet,
81947
82431
  firstPartyProvenanceSchema,
@@ -82013,6 +82497,7 @@ export {
82013
82497
  noPassphraseHint,
82014
82498
  normalizeResourceUrl,
82015
82499
  openRequestMarketplaceHitSchema,
82500
+ osSecretStore,
82016
82501
  parse402Challenge,
82017
82502
  parse402Response,
82018
82503
  parseDiscovery,
@@ -82041,6 +82526,7 @@ export {
82041
82526
  readMovement,
82042
82527
  readReceipts,
82043
82528
  readSearchEvents,
82529
+ readSecretBackend,
82044
82530
  readSolanaGasBalance,
82045
82531
  readSolanaUsdcBalance,
82046
82532
  readSpendLedger,
@@ -82068,8 +82554,10 @@ export {
82068
82554
  scheduleCeilingSweep,
82069
82555
  searchDocs,
82070
82556
  searchServicesResponseSchema,
82557
+ secretBackendPath,
82071
82558
  secretStore,
82072
82559
  secretsAllowed,
82560
+ secretsFilePath,
82073
82561
  serviceOfferMarketplaceHitSchema,
82074
82562
  serviceSummarySchema,
82075
82563
  serviceTierSchema,
@@ -82080,6 +82568,7 @@ export {
82080
82568
  spendCapsSchema,
82081
82569
  staleStoredPassphraseMessage,
82082
82570
  startAccountLink,
82571
+ supportsNativeEthSweep,
82083
82572
  swarmAccountNames,
82084
82573
  swarmFilePath,
82085
82574
  swarmFileSchema,
@@ -82091,6 +82580,7 @@ export {
82091
82580
  sweepAboveCeiling,
82092
82581
  sweepAllAboveCeiling,
82093
82582
  sweepBack,
82583
+ sweepNativeEth,
82094
82584
  sweepSolanaUsdc,
82095
82585
  sweepTarget,
82096
82586
  taskReservedAtomic,