vapi-network 0.12.1 → 0.13.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
@@ -6672,7 +6672,7 @@ function weierstrass(curveDef) {
6672
6672
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
6673
6673
  if (["recovered", "canonical"].some((k) => k in opts))
6674
6674
  throw new Error("sign() legacy options not supported");
6675
- const { hash: hash5, randomBytes: randomBytes17 } = CURVE;
6675
+ const { hash: hash5, randomBytes: randomBytes18 } = CURVE;
6676
6676
  let { lowS, prehash, extraEntropy: ent } = opts;
6677
6677
  if (lowS == null)
6678
6678
  lowS = true;
@@ -6684,7 +6684,7 @@ function weierstrass(curveDef) {
6684
6684
  const d = normPrivateKeyToScalar(privateKey);
6685
6685
  const seedArgs = [int2octets(d), int2octets(h1int)];
6686
6686
  if (ent != null && ent !== false) {
6687
- const e3 = ent === true ? randomBytes17(Fp.BYTES) : ent;
6687
+ const e3 = ent === true ? randomBytes18(Fp.BYTES) : ent;
6688
6688
  seedArgs.push(ensureBytes("extraEntropy", e3));
6689
6689
  }
6690
6690
  const seed = concatBytes3(...seedArgs);
@@ -10129,8 +10129,8 @@ __export(src_exports4, {
10129
10129
 
10130
10130
  // ../cli/src/cli.ts
10131
10131
  import { spawn as spawn5 } from "node:child_process";
10132
- import { stat as stat16 } from "node:fs/promises";
10133
- import { join as join30 } from "node:path";
10132
+ import { stat as stat18 } from "node:fs/promises";
10133
+ import { join as join31 } from "node:path";
10134
10134
  import { createInterface as createInterface3 } from "node:readline/promises";
10135
10135
 
10136
10136
  // ../core/src/index.ts
@@ -10176,6 +10176,8 @@ __export(src_exports, {
10176
10176
  ERC20_ABI: () => ERC20_ABI,
10177
10177
  EVM_DERIVATION_PATH: () => EVM_DERIVATION_PATH,
10178
10178
  EXECUTION_MODES: () => EXECUTION_MODES,
10179
+ FILE_SECRET_STORE_MIN_PASSWORD: () => FILE_SECRET_STORE_MIN_PASSWORD,
10180
+ FILE_SECRET_STORE_PASSWORD_ENV: () => FILE_SECRET_STORE_PASSWORD_ENV,
10179
10181
  FIRST_PARTY_PROVENANCES: () => FIRST_PARTY_PROVENANCES,
10180
10182
  FileLockedError: () => FileLockedError,
10181
10183
  KeystoreError: () => KeystoreError,
@@ -10268,6 +10270,7 @@ __export(src_exports, {
10268
10270
  ceilingFloorApplies: () => ceilingFloorApplies,
10269
10271
  changeKeystorePassphrase: () => changeKeystorePassphrase,
10270
10272
  checkReceiptSettlement: () => checkReceiptSettlement,
10273
+ chooseSecretBackend: () => chooseSecretBackend,
10271
10274
  classifySettlement: () => classifySettlement,
10272
10275
  completeX402Payment: () => completeX402Payment,
10273
10276
  configSchema: () => configSchema,
@@ -10275,6 +10278,7 @@ __export(src_exports, {
10275
10278
  createAccount: () => createAccount,
10276
10279
  createAgentProfileSchema: () => createAgentProfileSchema,
10277
10280
  createChain: () => createChain,
10281
+ createFileSecretStore: () => createFileSecretStore,
10278
10282
  createKeystore: () => createKeystore,
10279
10283
  createKeystoreFromPrivateKey: () => createKeystoreFromPrivateKey,
10280
10284
  createNetworkHttpTransport: () => createNetworkHttpTransport,
@@ -10314,6 +10318,7 @@ __export(src_exports, {
10314
10318
  explorerAddressUrl: () => explorerAddressUrl,
10315
10319
  explorerTransactionUrl: () => explorerTransactionUrl,
10316
10320
  fetchSiblings: () => fetchSiblings,
10321
+ fileSecretStore: () => fileSecretStore,
10317
10322
  filterReceiptsByRange: () => filterReceiptsByRange,
10318
10323
  filterReceiptsByWallet: () => filterReceiptsByWallet,
10319
10324
  firstPartyProvenanceSchema: () => firstPartyProvenanceSchema,
@@ -10385,6 +10390,7 @@ __export(src_exports, {
10385
10390
  noPassphraseHint: () => noPassphraseHint,
10386
10391
  normalizeResourceUrl: () => normalizeResourceUrl,
10387
10392
  openRequestMarketplaceHitSchema: () => openRequestMarketplaceHitSchema,
10393
+ osSecretStore: () => osSecretStore,
10388
10394
  parse402Challenge: () => parse402Challenge,
10389
10395
  parse402Response: () => parse402Response,
10390
10396
  parseDiscovery: () => parseDiscovery,
@@ -10413,6 +10419,7 @@ __export(src_exports, {
10413
10419
  readMovement: () => readMovement,
10414
10420
  readReceipts: () => readReceipts,
10415
10421
  readSearchEvents: () => readSearchEvents,
10422
+ readSecretBackend: () => readSecretBackend,
10416
10423
  readSolanaGasBalance: () => readSolanaGasBalance,
10417
10424
  readSolanaUsdcBalance: () => readSolanaUsdcBalance,
10418
10425
  readSpendLedger: () => readSpendLedger,
@@ -10440,8 +10447,10 @@ __export(src_exports, {
10440
10447
  scheduleCeilingSweep: () => scheduleCeilingSweep,
10441
10448
  searchDocs: () => searchDocs,
10442
10449
  searchServicesResponseSchema: () => searchServicesResponseSchema,
10450
+ secretBackendPath: () => secretBackendPath,
10443
10451
  secretStore: () => secretStore,
10444
10452
  secretsAllowed: () => secretsAllowed,
10453
+ secretsFilePath: () => secretsFilePath,
10445
10454
  serviceOfferMarketplaceHitSchema: () => serviceOfferMarketplaceHitSchema,
10446
10455
  serviceSummarySchema: () => serviceSummarySchema,
10447
10456
  serviceTierSchema: () => serviceTierSchema,
@@ -45598,9 +45607,9 @@ var X402Error = class extends Error {
45598
45607
  function isValidPaymentId(value) {
45599
45608
  return typeof value === "string" && PAYMENT_ID_PATTERN.test(value);
45600
45609
  }
45601
- function createPaymentId(randomBytes17 = fillRandomBytes) {
45610
+ function createPaymentId(randomBytes18 = fillRandomBytes) {
45602
45611
  const bytes = new Uint8Array(16);
45603
- randomBytes17(bytes);
45612
+ randomBytes18(bytes);
45604
45613
  return `pay_${bytesToHex(bytes).slice(2)}`;
45605
45614
  }
45606
45615
  function buildPaymentExtensions(serverExtensions, options = {}) {
@@ -47004,8 +47013,8 @@ function conciseError(error61) {
47004
47013
  }
47005
47014
 
47006
47015
  // ../core/src/account-add.ts
47007
- import { stat as stat8 } from "node:fs/promises";
47008
- import { join as join9 } from "node:path";
47016
+ import { stat as stat10 } from "node:fs/promises";
47017
+ import { join as join10 } from "node:path";
47009
47018
 
47010
47019
  // ../core/src/agent-link.ts
47011
47020
  import { createHash } from "node:crypto";
@@ -70586,20 +70595,20 @@ async function promptForSecret(prompt, noTerminalHint) {
70586
70595
  }
70587
70596
 
70588
70597
  // ../core/src/wallet-store.ts
70589
- import { randomBytes as randomBytes8 } from "node:crypto";
70598
+ import { randomBytes as randomBytes9 } from "node:crypto";
70590
70599
  import {
70591
70600
  chmod as chmod3,
70592
70601
  lstat as lstat2,
70593
70602
  mkdir as mkdir10,
70594
- open as open7,
70603
+ open as open8,
70595
70604
  readdir as readdir3,
70596
- readFile as readFile11,
70605
+ readFile as readFile12,
70597
70606
  rename as rename7,
70598
- stat as stat7,
70607
+ stat as stat9,
70599
70608
  unlink as unlink6,
70600
70609
  writeFile as writeFile5
70601
70610
  } from "node:fs/promises";
70602
- import { dirname as dirname7, join as join8 } from "node:path";
70611
+ import { dirname as dirname7, join as join9 } from "node:path";
70603
70612
 
70604
70613
  // ../core/src/account-movement-lock.ts
70605
70614
  import { randomBytes as randomBytes4 } from "node:crypto";
@@ -70717,505 +70726,16 @@ function isOpenMovementLeg(leg, journalEvidence) {
70717
70726
  // ../core/src/secret-store.ts
70718
70727
  import { spawn } from "node:child_process";
70719
70728
  import { existsSync } from "node:fs";
70720
- import { delimiter, isAbsolute, join as join6, win32 } from "node:path";
70721
- var SECRET_STORE_SERVICE = "vapi-network";
70722
- var SECURITY_BINARY = "/usr/bin/security";
70723
- var SECRET_TOOL_BINARY = "secret-tool";
70724
- var WINDOWS_POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-Command", "-"];
70725
- var SECURITY_ITEM_NOT_FOUND = 44;
70726
- var WINDOWS_SECRET_SUCCESS = 0;
70727
- var WINDOWS_SECRET_NOT_FOUND = 2;
70728
- var UNSUPPORTED_PLATFORM = "No OS secret store on this platform yet; use VAPI_KEYSTORE_PASSWORD.";
70729
- var SECRET_TOOL_MISSING = [
70730
- "secret-tool is not installed, so the passphrase cannot be kept in the OS secret store.",
70731
- "Install libsecret-tools (Debian, Ubuntu) or libsecret (Fedora, Arch), or use VAPI_KEYSTORE_PASSWORD."
70732
- ].join(" ");
70733
- var POWERSHELL_MISSING = [
70734
- "Windows PowerShell (powershell.exe) was not found, so the passphrase cannot be kept in the OS secret store.",
70735
- "Use VAPI_KEYSTORE_PASSWORD."
70736
- ].join(" ");
70737
- function secretStore(options = {}) {
70738
- const platform2 = options.platform ?? process.platform;
70739
- const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
70740
- const env = options.env ?? process.env;
70741
- const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
70742
- if (platform2 === "darwin") return keychainStore(platform2, run);
70743
- if (platform2 === "win32") return windowsDataProtectionStore(platform2, run, env, installed);
70744
- if (platform2 === "linux") return libsecretStore(platform2, run, installed);
70745
- return unsupportedStore(platform2);
70746
- }
70747
- function memorySecretStore(initial = {}) {
70748
- const entries = new Map(Object.entries(initial));
70749
- return {
70750
- available: true,
70751
- platform: process.platform,
70752
- description: "an in-memory store",
70753
- async get(name) {
70754
- return entries.get(name);
70755
- },
70756
- async has(name) {
70757
- return entries.has(name);
70758
- },
70759
- async set(name, passphrase) {
70760
- entries.set(name, passphrase);
70761
- },
70762
- async remove(name) {
70763
- return entries.delete(name);
70764
- },
70765
- async list() {
70766
- return [...entries.keys()].sort();
70767
- }
70768
- };
70769
- }
70770
- function keychainStore(platform2, run) {
70771
- const find = async (account, withPassword) => await run(SECURITY_BINARY, [
70772
- "find-generic-password",
70773
- "-a",
70774
- account,
70775
- "-s",
70776
- SECRET_STORE_SERVICE,
70777
- ...withPassword ? ["-w"] : []
70778
- ]);
70779
- const read = async (account, what) => {
70780
- const result = await find(account, true);
70781
- if (result.code === SECURITY_ITEM_NOT_FOUND) return void 0;
70782
- requireSuccess(result, what);
70783
- const value = withoutTrailingNewline(result.stdout);
70784
- return value.length === 0 ? void 0 : value;
70785
- };
70786
- const write2 = async (account, value, what) => {
70787
- const result = await run(
70788
- SECURITY_BINARY,
70789
- [
70790
- "add-generic-password",
70791
- "-a",
70792
- account,
70793
- "-s",
70794
- SECRET_STORE_SERVICE,
70795
- "-l",
70796
- `${SECRET_STORE_SERVICE} ${account}`,
70797
- "-U",
70798
- "-w"
70799
- ],
70800
- // `security` asks for the password and then for its confirmation.
70801
- `${value}
70802
- ${value}
70803
- `
70804
- );
70805
- requireSuccess(result, what);
70806
- };
70807
- const erase = async (account, what) => {
70808
- const result = await run(SECURITY_BINARY, [
70809
- "delete-generic-password",
70810
- "-a",
70811
- account,
70812
- "-s",
70813
- SECRET_STORE_SERVICE
70814
- ]);
70815
- if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
70816
- requireSuccess(result, what);
70817
- return true;
70818
- };
70819
- const erasePartsAfter = async (account, keep, what) => {
70820
- for (let part = keep + 1; part <= MAX_KEYCHAIN_PARTS; part += 1) {
70821
- if (!await erase(keychainPart(account, part), what)) return;
70822
- }
70823
- };
70824
- return {
70825
- available: true,
70826
- platform: platform2,
70827
- description: "the macOS Keychain",
70828
- async get(name) {
70829
- const account = accountFor(name);
70830
- const what = `read the passphrase of ${name} from the macOS Keychain`;
70831
- const value = await read(account, what);
70832
- const parts = value === void 0 ? void 0 : chunkedPartCount(value);
70833
- if (value === void 0 || parts === void 0) return value;
70834
- let joined = "";
70835
- for (let part = 1; part <= parts; part += 1) {
70836
- const chunk = await read(keychainPart(account, part), what);
70837
- if (chunk === void 0) {
70838
- throw new KeystoreError(
70839
- `The stored secret ${name} is incomplete in the macOS Keychain. Store it again.`
70840
- );
70841
- }
70842
- joined += chunk;
70843
- }
70844
- return joined;
70845
- },
70846
- async has(name) {
70847
- const result = await find(accountFor(name), false);
70848
- if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
70849
- requireSuccess(result, `look up ${name} in the macOS Keychain`);
70850
- return true;
70851
- },
70852
- async set(name, passphrase) {
70853
- requirePassphrase(passphrase);
70854
- const account = accountFor(name);
70855
- const what = `store the passphrase of ${name} in the macOS Keychain`;
70856
- if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
70857
- await write2(account, passphrase, what);
70858
- return;
70859
- }
70860
- const chunks = [];
70861
- for (let index2 = 0; index2 < passphrase.length; index2 += KEYCHAIN_CHUNK) {
70862
- chunks.push(passphrase.slice(index2, index2 + KEYCHAIN_CHUNK));
70863
- }
70864
- if (chunks.length > MAX_KEYCHAIN_PARTS) {
70865
- throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
70866
- }
70867
- for (const [index2, chunk] of chunks.entries()) {
70868
- await write2(keychainPart(account, index2 + 1), chunk, what);
70869
- }
70870
- await erasePartsAfter(account, chunks.length, what);
70871
- await write2(account, `${CHUNKED_MARKER}${chunks.length}`, what);
70872
- },
70873
- async remove(name) {
70874
- const account = accountFor(name);
70875
- const what = `remove the passphrase of ${name} from the macOS Keychain`;
70876
- const found = await find(account, true);
70877
- if (found.code === SECURITY_ITEM_NOT_FOUND) return false;
70878
- requireSuccess(found, what);
70879
- if (chunkedPartCount(withoutTrailingNewline(found.stdout)) !== void 0) {
70880
- await erasePartsAfter(account, 0, what);
70881
- }
70882
- return await erase(account, what);
70883
- }
70884
- };
70885
- }
70886
- var KEYCHAIN_PROMPT_LIMIT = 128;
70887
- var KEYCHAIN_CHUNK = 120;
70888
- var MAX_KEYCHAIN_PARTS = 32;
70889
- var CHUNKED_MARKER = "vapi-chunked:v1:";
70890
- function keychainPart(account, part) {
70891
- return `${account}#${part}`;
70892
- }
70893
- function chunkedPartCount(value) {
70894
- if (!value.startsWith(CHUNKED_MARKER)) return void 0;
70895
- const parts = Number(value.slice(CHUNKED_MARKER.length));
70896
- return Number.isInteger(parts) && parts > 0 && parts <= MAX_KEYCHAIN_PARTS ? parts : void 0;
70897
- }
70898
- function windowsSecretFileName(account) {
70899
- let encoded = "";
70900
- for (let index2 = 0; index2 < account.length; index2 += 1) {
70901
- const character = account[index2];
70902
- if (/^[a-z0-9._#-]$/u.test(character)) {
70903
- encoded += character;
70904
- continue;
70905
- }
70906
- encoded += `%${account.charCodeAt(index2).toString(16).toUpperCase().padStart(4, "0")}`;
70907
- }
70908
- if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(encoded)) {
70909
- encoded = `%${encoded.charCodeAt(0).toString(16).toUpperCase()}${encoded.slice(1)}`;
70910
- }
70911
- return `${encoded}.bin`;
70912
- }
70913
- function windowsDataProtectionStore(platform2, run, env, installed) {
70914
- const powershell = `${env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
70915
- const fileDetails = (name) => {
70916
- const file2 = windowsSecretFileName(accountFor(name));
70917
- return { file: file2, account: file2.slice(0, -".bin".length) };
70918
- };
70919
- const script = (file2, operations) => [
70920
- "$ErrorActionPreference = 'Stop'",
70921
- "try {",
70922
- " Add-Type -AssemblyName System.Security",
70923
- " $dir = Join-Path $env:LOCALAPPDATA 'vapi-network\\secrets'",
70924
- ` $path = Join-Path $dir '${file2}'`,
70925
- ...operations.map((operation) => ` ${operation}`),
70926
- "} catch {",
70927
- " [Console]::Error.WriteLine($_.Exception.Message)",
70928
- " exit 1",
70929
- "}"
70930
- ].join("\n");
70931
- const execute = async (script2) => {
70932
- const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
70933
-
70934
- `);
70935
- requirePowerShell(result);
70936
- return result;
70937
- };
70938
- return {
70939
- available: installed(powershell),
70940
- platform: platform2,
70941
- description: "Windows Data Protection (DPAPI)",
70942
- async get(name) {
70943
- const { file: file2, account } = fileDetails(name);
70944
- const result = await execute(
70945
- script(file2, [
70946
- `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
70947
- "$blob = [System.IO.File]::ReadAllBytes($path)",
70948
- "$bytes = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
70949
- "[Console]::Out.Write([Convert]::ToBase64String($bytes))",
70950
- `exit ${WINDOWS_SECRET_SUCCESS}`
70951
- ])
70952
- );
70953
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return void 0;
70954
- requireSuccess(result, `read the passphrase of ${name} from Windows Data Protection`);
70955
- const value = Buffer.from(result.stdout.trim(), "base64").toString("utf8");
70956
- return value.length === 0 ? void 0 : value;
70957
- },
70958
- async has(name) {
70959
- const { file: file2, account } = fileDetails(name);
70960
- const result = await execute(
70961
- script(file2, [
70962
- `if (Test-Path -LiteralPath $path) { exit ${WINDOWS_SECRET_SUCCESS} }`,
70963
- `[Console]::Error.WriteLine('No stored secret for ${account}.')`,
70964
- `exit ${WINDOWS_SECRET_NOT_FOUND}`
70965
- ])
70966
- );
70967
- if (result.code === WINDOWS_SECRET_SUCCESS) return true;
70968
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
70969
- requireSuccess(result, `look up ${name} in Windows Data Protection`);
70970
- return false;
70971
- },
70972
- async set(name, passphrase) {
70973
- requirePassphrase(passphrase);
70974
- const { file: file2 } = fileDetails(name);
70975
- const value = Buffer.from(passphrase, "utf8").toString("base64");
70976
- const result = await execute(
70977
- script(file2, [
70978
- "[void][System.IO.Directory]::CreateDirectory($dir)",
70979
- `$bytes = [Convert]::FromBase64String('${value}')`,
70980
- "$blob = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
70981
- "[System.IO.File]::WriteAllBytes($path, $blob)",
70982
- `exit ${WINDOWS_SECRET_SUCCESS}`
70983
- ])
70984
- );
70985
- requireSuccess(result, `store the passphrase of ${name} in Windows Data Protection`);
70986
- },
70987
- async remove(name) {
70988
- const { file: file2, account } = fileDetails(name);
70989
- const result = await execute(
70990
- script(file2, [
70991
- `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
70992
- "Remove-Item -LiteralPath $path -Force",
70993
- `exit ${WINDOWS_SECRET_SUCCESS}`
70994
- ])
70995
- );
70996
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
70997
- requireSuccess(result, `remove the passphrase of ${name} from Windows Data Protection`);
70998
- return true;
70999
- }
71000
- };
71001
- }
71002
- function libsecretStore(platform2, run, installed) {
71003
- const lookup2 = async (name) => {
71004
- const result = await run(SECRET_TOOL_BINARY, [
71005
- "lookup",
71006
- "service",
71007
- SECRET_STORE_SERVICE,
71008
- "account",
71009
- accountFor(name)
71010
- ]);
71011
- requireBinary(result);
71012
- const value = withoutTrailingNewline(result.stdout);
71013
- if (result.code === 0) return value.length === 0 ? void 0 : value;
71014
- if (result.stderr.trim().length === 0) return void 0;
71015
- requireSuccess(result, `read the passphrase of ${name} from the secret service`);
71016
- return void 0;
71017
- };
71018
- return {
71019
- available: installed(SECRET_TOOL_BINARY),
71020
- platform: platform2,
71021
- description: "the libsecret keyring",
71022
- get: lookup2,
71023
- async has(name) {
71024
- return await lookup2(name) !== void 0;
71025
- },
71026
- async set(name, passphrase) {
71027
- requirePassphrase(passphrase);
71028
- const account = accountFor(name);
71029
- const result = await run(
71030
- SECRET_TOOL_BINARY,
71031
- [
71032
- "store",
71033
- `--label=${SECRET_STORE_SERVICE} ${account}`,
71034
- "service",
71035
- SECRET_STORE_SERVICE,
71036
- "account",
71037
- account
71038
- ],
71039
- `${passphrase}
71040
- `
71041
- );
71042
- requireBinary(result);
71043
- requireSuccess(result, `store the passphrase of ${name} in the secret service`);
71044
- },
71045
- async remove(name) {
71046
- const existed = await lookup2(name) !== void 0;
71047
- const result = await run(SECRET_TOOL_BINARY, [
71048
- "clear",
71049
- "service",
71050
- SECRET_STORE_SERVICE,
71051
- "account",
71052
- accountFor(name)
71053
- ]);
71054
- requireBinary(result);
71055
- requireSuccess(result, `remove the passphrase of ${name} from the secret service`);
71056
- return existed;
71057
- }
71058
- };
71059
- }
71060
- function unsupportedStore(platform2) {
71061
- const refuse = () => {
71062
- throw new KeystoreError(UNSUPPORTED_PLATFORM);
71063
- };
71064
- return {
71065
- available: false,
71066
- platform: platform2,
71067
- description: "no OS secret store",
71068
- get: async () => refuse(),
71069
- has: async () => refuse(),
71070
- set: async () => refuse(),
71071
- remove: async () => refuse()
71072
- };
71073
- }
71074
- function accountFor(name) {
71075
- const account = name.trim();
71076
- if (account.length === 0) {
71077
- throw new KeystoreError("A wallet name is needed to reach the OS secret store.");
71078
- }
71079
- return account;
71080
- }
71081
- function requirePassphrase(passphrase) {
71082
- if (passphrase.length === 0) {
71083
- throw new KeystoreError("Keystore passphrase cannot be empty.");
71084
- }
71085
- }
71086
- function requireBinary(result) {
71087
- if (result.notFound === true) throw new KeystoreError(SECRET_TOOL_MISSING);
71088
- }
71089
- function requirePowerShell(result) {
71090
- if (result.notFound === true) throw new KeystoreError(POWERSHELL_MISSING);
71091
- }
71092
- function binaryInstalled(file2, env) {
71093
- if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
71094
- return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join6(directory, file2)));
71095
- }
71096
- var SAFE_FAILURE_DETAILS = [
71097
- "Cannot autolaunch D-Bus without X11 $DISPLAY",
71098
- "Cannot autolaunch D-Bus",
71099
- "The name org.freedesktop.secrets was not provided by any .service files",
71100
- "Cannot create an item in a locked collection",
71101
- "User interaction is not allowed.",
71102
- "Access to the path is denied."
71103
- ];
71104
- function requireSuccess(result, what) {
71105
- if (result.code === 0) return;
71106
- const detail = SAFE_FAILURE_DETAILS.find((reason) => result.stderr.includes(reason));
71107
- throw new KeystoreError(
71108
- `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail === void 0 ? "" : ` ${detail}`}`
71109
- );
71110
- }
71111
- function withoutTrailingNewline(value) {
71112
- return value.replace(/\r?\n$/u, "");
71113
- }
71114
- var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve4) => {
71115
- let stdout = "";
71116
- let stderr2 = "";
71117
- let settled = false;
71118
- const finish = (outcome) => {
71119
- if (settled) return;
71120
- settled = true;
71121
- resolve4(outcome);
71122
- };
71123
- const child = spawn(file2, [...args], {
71124
- detached: platform2 !== "win32",
71125
- stdio: ["pipe", "pipe", "pipe"],
71126
- windowsHide: true
71127
- });
71128
- child.stdout?.setEncoding("utf8");
71129
- child.stdout?.on("data", (chunk) => {
71130
- stdout += chunk;
71131
- });
71132
- child.stderr?.setEncoding("utf8");
71133
- child.stderr?.on("data", (chunk) => {
71134
- stderr2 += chunk;
71135
- });
71136
- child.on("error", (error61) => {
71137
- finish({
71138
- code: null,
71139
- stdout,
71140
- stderr: stderr2,
71141
- ...error61.code === "ENOENT" ? { notFound: true } : {}
71142
- });
71143
- });
71144
- child.on("close", (code) => finish({ code, stdout, stderr: stderr2 }));
71145
- child.stdin?.on("error", () => void 0);
71146
- child.stdin?.end(input2 ?? "");
71147
- });
71148
-
71149
- // ../core/src/passphrase.ts
71150
- var PASSPHRASE_ENVIRONMENT_VARIABLE = "VAPI_KEYSTORE_PASSWORD";
71151
- function noPassphraseHint(walletName) {
71152
- return `Set ${PASSPHRASE_ENVIRONMENT_VARIABLE}, or store this wallet's passphrase once with vapi unlock --wallet ${walletName}.`;
71153
- }
71154
- function staleStoredPassphraseMessage(walletName, store) {
71155
- return [
71156
- `The passphrase stored in ${store.description} no longer opens wallet ${walletName}.`,
71157
- `Store the current one with vapi unlock --wallet ${walletName}, or remove it with vapi lock --wallet ${walletName}.`
71158
- ].join(" ");
71159
- }
71160
- async function resolvePassphrase(walletName, options = {}) {
71161
- const env = options.env ?? process.env;
71162
- const fromEnvironment = env[PASSPHRASE_ENVIRONMENT_VARIABLE];
71163
- if (fromEnvironment !== void 0) {
71164
- if (fromEnvironment.length === 0) {
71165
- throw new KeystoreError(`${PASSPHRASE_ENVIRONMENT_VARIABLE} cannot be empty.`);
71166
- }
71167
- return { passphrase: fromEnvironment, source: "environment" };
71168
- }
71169
- if (options.confirm !== true) {
71170
- const stored = await readStored(options.store ?? secretStore(), walletName);
71171
- if (stored !== void 0) return { passphrase: stored, source: "secret-store" };
71172
- }
71173
- const hint = noPassphraseHint(walletName);
71174
- if (options.interactive === false) {
71175
- throw new KeystoreError(
71176
- `No interactive terminal is available for the keystore prompt. ${hint}`
71177
- );
71178
- }
71179
- const prompt = options.prompt ?? promptForSecret;
71180
- const first = await prompt(`Passphrase for ${walletName}: `, hint);
71181
- if (first.length === 0) {
71182
- throw new KeystoreError("Keystore passphrase cannot be empty.");
71183
- }
71184
- if (options.confirm === true) {
71185
- const second = await prompt("Confirm passphrase: ", hint);
71186
- if (first !== second) throw new KeystoreError("Passphrases do not match.");
71187
- }
71188
- return { passphrase: first, source: "prompt" };
71189
- }
71190
- async function readStored(store, walletName) {
71191
- if (!store.available) return void 0;
71192
- try {
71193
- return await store.get(walletName);
71194
- } catch {
71195
- return void 0;
71196
- }
71197
- }
70729
+ import { delimiter, isAbsolute, join as join7, win32 } from "node:path";
71198
70730
 
71199
- // ../core/src/receipts.ts
70731
+ // ../core/src/file-secret-store.ts
71200
70732
  import { randomBytes as randomBytes6 } from "node:crypto";
71201
- import { mkdir as mkdir7, open as open5, readFile as readFile7, rename as rename4, writeFile as writeFile3 } from "node:fs/promises";
71202
- import { dirname as dirname5 } from "node:path";
70733
+ import { readFile as readFile8, stat as stat7 } from "node:fs/promises";
71203
70734
 
71204
- // ../core/src/agent-run.ts
70735
+ // ../core/src/vault.ts
71205
70736
  import { randomBytes as randomBytes5 } from "node:crypto";
71206
- var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
71207
- function isRunId(value) {
71208
- return typeof value === "string" && RUN_ID_PATTERN.test(value);
71209
- }
71210
- function createRunId(random = randomBytes5) {
71211
- return `run_${Buffer.from(random(12)).toString("hex")}`;
71212
- }
71213
- var runRefSchema = external_exports.strictObject({
71214
- id: external_exports.string().regex(RUN_ID_PATTERN),
71215
- swarm: external_exports.string().optional(),
71216
- member: external_exports.string().optional(),
71217
- parentRunId: external_exports.string().optional()
71218
- });
70737
+ 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";
70738
+ import { dirname as dirname5 } from "node:path";
71219
70739
 
71220
70740
  // ../core/src/wallet-name.ts
71221
70741
  var DEFAULT_WALLET_NAME = "main";
@@ -71228,263 +70748,7 @@ function isWalletName(value) {
71228
70748
  return WALLET_NAME_PATTERN.test(value);
71229
70749
  }
71230
70750
 
71231
- // ../core/src/receipts.ts
71232
- var receiptTestHooks;
71233
- function __setReceiptTestHooks(hooks) {
71234
- receiptTestHooks = hooks;
71235
- }
71236
- var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
71237
- async function withReceiptJournalLock(path, operation) {
71238
- return await withFileLock(`${path}.lock`, operation, {
71239
- lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
71240
- });
71241
- }
71242
- var durationSchema = external_exports.number().nonnegative().finite();
71243
- var receiptSchema = external_exports.strictObject({
71244
- id: external_exports.string().min(1),
71245
- timestamp: external_exports.iso.datetime(),
71246
- run: runRefSchema.optional(),
71247
- kind: external_exports.literal("transfer").optional(),
71248
- wallet: walletNameSchema.optional(),
71249
- resourceUrl: external_exports.url(),
71250
- method: external_exports.string().min(1).optional(),
71251
- source: external_exports.string().min(1).optional(),
71252
- provenance: external_exports.array(
71253
- external_exports.strictObject({
71254
- source: external_exports.string().min(1),
71255
- sourceUrl: external_exports.string().optional(),
71256
- ref: external_exports.string().optional()
71257
- })
71258
- ).optional(),
71259
- quote: external_exports.strictObject({
71260
- network: external_exports.string(),
71261
- asset: external_exports.string().optional(),
71262
- amountAtomic: external_exports.string().regex(/^\d+$/),
71263
- payTo: external_exports.string().optional()
71264
- }).optional(),
71265
- payer: external_exports.string().optional(),
71266
- paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
71267
- authorization: external_exports.strictObject({
71268
- from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71269
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
71270
- validBefore: external_exports.string().regex(/^\d+$/)
71271
- }).optional(),
71272
- transfer: external_exports.strictObject({
71273
- to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71274
- toName: external_exports.string().min(1),
71275
- toKind: external_exports.enum(["owner", "account"]),
71276
- amountAtomic: external_exports.string().regex(/^\d+$/),
71277
- network: external_exports.string().min(1),
71278
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
71279
- status: external_exports.enum(["sent", "unknown", "failed"]),
71280
- txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
71281
- replayed: external_exports.boolean(),
71282
- reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
71283
- request: external_exports.strictObject({
71284
- authorization: external_exports.strictObject({
71285
- from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71286
- to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71287
- value: external_exports.string().regex(/^\d+$/),
71288
- validAfter: external_exports.string().regex(/^\d+$/),
71289
- validBefore: external_exports.string().regex(/^\d+$/),
71290
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
71291
- }),
71292
- signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
71293
- }).optional()
71294
- }).optional(),
71295
- settlement: external_exports.strictObject({
71296
- outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
71297
- transaction: external_exports.string().optional(),
71298
- explorerUrl: external_exports.url().optional(),
71299
- evidence: external_exports.unknown().optional()
71300
- }).optional(),
71301
- latencyMs: external_exports.number().nonnegative().finite().optional(),
71302
- status: external_exports.number().int().min(100).max(599).optional(),
71303
- error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
71304
- phases: external_exports.strictObject({
71305
- discoverMs: durationSchema.optional(),
71306
- quoteMs: durationSchema.optional(),
71307
- signMs: durationSchema.optional(),
71308
- requestMs: durationSchema.optional(),
71309
- settleMs: durationSchema.optional()
71310
- }).optional(),
71311
- listing: external_exports.strictObject({
71312
- name: external_exports.string().min(1).optional(),
71313
- providerHost: external_exports.string().min(1).optional(),
71314
- source: external_exports.string().min(1)
71315
- }).optional(),
71316
- retry: external_exports.number().int().nonnegative().optional(),
71317
- policy: external_exports.strictObject({
71318
- maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
71319
- capsApplied: external_exports.boolean()
71320
- }).optional(),
71321
- client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
71322
- outcome: external_exports.enum([
71323
- "paid",
71324
- "signed_in",
71325
- "declined_policy",
71326
- "failed_request",
71327
- "settlement_rejected",
71328
- "settlement_unknown"
71329
- ]).optional()
71330
- });
71331
- function parseReceipt(value) {
71332
- const receipt = receiptSchema.parse(value);
71333
- const transaction2 = receipt.settlement?.transaction;
71334
- const network = receipt.quote?.network;
71335
- const explorerUrl = transaction2 === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction2);
71336
- if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
71337
- return receipt;
71338
- }
71339
- return {
71340
- ...receipt,
71341
- settlement: {
71342
- outcome: receipt.settlement.outcome,
71343
- ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
71344
- explorerUrl,
71345
- ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
71346
- }
71347
- };
71348
- }
71349
- async function appendReceipt(receipt, path = getVapiPaths().receipts, options = {}) {
71350
- const parsed = parseReceipt(
71351
- receipt.wallet === void 0 && options.wallet !== void 0 ? { ...receipt, wallet: options.wallet } : receipt
71352
- );
71353
- await withReceiptJournalLock(path, async () => {
71354
- await mkdir7(dirname5(path), { recursive: true, mode: 448 });
71355
- const handle = await open5(path, "a", 384);
71356
- try {
71357
- await handle.writeFile(`${JSON.stringify(parsed)}
71358
- `, "utf8");
71359
- } finally {
71360
- await handle.close();
71361
- }
71362
- });
71363
- return parsed;
71364
- }
71365
- async function readReceipts(path = getVapiPaths().receipts, options = {}) {
71366
- let raw;
71367
- try {
71368
- raw = await readFile7(path, "utf8");
71369
- } catch (error61) {
71370
- if (isMissingFile(error61)) return [];
71371
- throw error61;
71372
- }
71373
- const records = coalesceTransferReceiptRevisions(
71374
- raw.split("\n").filter((line) => line.trim().length > 0).map((line, index2) => {
71375
- try {
71376
- return parseReceipt(JSON.parse(line));
71377
- } catch (error61) {
71378
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71379
- }
71380
- })
71381
- );
71382
- const filtered = options.wallet === void 0 ? records : filterReceiptsByWallet(records, options.wallet);
71383
- const limit = options.limit;
71384
- if (limit === void 0) return filtered;
71385
- if (!Number.isSafeInteger(limit) || limit < 0)
71386
- throw new Error("Receipt limit must be a non-negative integer.");
71387
- return limit === 0 ? [] : filtered.slice(-limit);
71388
- }
71389
- function coalesceTransferReceiptRevisions(receipts) {
71390
- const coalesced = [];
71391
- const transferIndexes = /* @__PURE__ */ new Map();
71392
- for (const receipt of receipts) {
71393
- const existing = receipt.kind === "transfer" ? transferIndexes.get(receipt.id) : void 0;
71394
- if (existing === void 0) {
71395
- if (receipt.kind === "transfer") transferIndexes.set(receipt.id, coalesced.length);
71396
- coalesced.push(receipt);
71397
- } else {
71398
- coalesced[existing] = receipt;
71399
- }
71400
- }
71401
- return coalesced;
71402
- }
71403
- function receiptWallet(receipt) {
71404
- return receipt.wallet ?? DEFAULT_WALLET_NAME;
71405
- }
71406
- function filterReceiptsByWallet(receipts, name) {
71407
- return receipts.filter((receipt) => receiptWallet(receipt) === name);
71408
- }
71409
- async function renameReceiptWallet(from16, to, path = getVapiPaths().receipts) {
71410
- return await withReceiptJournalLock(path, async () => {
71411
- let raw;
71412
- try {
71413
- raw = await readFile7(path, "utf8");
71414
- } catch (error61) {
71415
- if (isMissingFile(error61)) return 0;
71416
- throw error61;
71417
- }
71418
- let changed = 0;
71419
- const lines = raw.split("\n").map((line, index2) => {
71420
- if (line.trim().length === 0) return line;
71421
- let parsed;
71422
- try {
71423
- parsed = JSON.parse(line);
71424
- } catch (error61) {
71425
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71426
- }
71427
- const current = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "wallet") : void 0;
71428
- if ((typeof current === "string" ? current : DEFAULT_WALLET_NAME) !== from16) return line;
71429
- changed += 1;
71430
- return JSON.stringify(parseReceipt({ ...parsed, wallet: to }));
71431
- });
71432
- if (changed === 0) return 0;
71433
- await receiptTestHooks?.beforeRenameReplace?.(path);
71434
- await mkdir7(dirname5(path), { recursive: true, mode: 448 });
71435
- const temporaryPath = `${path}.${process.pid}.${randomBytes6(6).toString("hex")}.tmp`;
71436
- await writeFile3(temporaryPath, lines.join("\n"), {
71437
- encoding: "utf8",
71438
- mode: 384,
71439
- flag: "wx"
71440
- });
71441
- await rename4(temporaryPath, path);
71442
- return changed;
71443
- });
71444
- }
71445
-
71446
- // ../core/src/transfer-journal.ts
71447
- import { readFile as readFile8 } from "node:fs/promises";
71448
- async function readTransferJournal(home, from16, nonce) {
71449
- let raw;
71450
- try {
71451
- raw = await readFile8(getVapiPaths(home).receipts, "utf8");
71452
- } catch (error61) {
71453
- if (isMissingFile(error61)) return { signed: false };
71454
- throw error61;
71455
- }
71456
- let latest;
71457
- let request;
71458
- for (const [index2, line] of raw.split("\n").entries()) {
71459
- if (!line.trim()) continue;
71460
- let receipt;
71461
- try {
71462
- receipt = parseReceipt(JSON.parse(line));
71463
- } catch (error61) {
71464
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71465
- }
71466
- if (receiptWallet(receipt) !== from16 || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
71467
- continue;
71468
- }
71469
- latest = receipt;
71470
- if (receipt.transfer.request !== void 0) request = receipt;
71471
- }
71472
- return {
71473
- signed: latest !== void 0,
71474
- ...latest === void 0 ? {} : { latest },
71475
- ...request === void 0 ? {} : { request },
71476
- ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
71477
- ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
71478
- };
71479
- }
71480
-
71481
- // ../core/src/vault-key.ts
71482
- import { randomBytes as cryptoRandomBytes } from "node:crypto";
71483
-
71484
70751
  // ../core/src/vault.ts
71485
- import { randomBytes as randomBytes7 } from "node:crypto";
71486
- 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";
71487
- import { dirname as dirname6 } from "node:path";
71488
70752
  var VaultError = class extends Error {
71489
70753
  code;
71490
70754
  constructor(code, message, options) {
@@ -71870,249 +71134,1230 @@ async function exportVaultAccountKey(args) {
71870
71134
  if (privateKeyToAccount(privateKey).address.toLowerCase() !== account.address.toLowerCase()) {
71871
71135
  throw new VaultError("corrupt", "A vault key does not match its stored address.");
71872
71136
  }
71873
- return privateKey;
71874
- } catch (error61) {
71875
- throw asVaultError(error61, "corrupt", "Unable to export the vault account key.");
71137
+ return privateKey;
71138
+ } catch (error61) {
71139
+ throw asVaultError(error61, "corrupt", "Unable to export the vault account key.");
71140
+ }
71141
+ }
71142
+ async function exportMemberKey(args) {
71143
+ return await exportVaultAccountKey(args);
71144
+ }
71145
+ function assertVaultKey(key2) {
71146
+ if (key2.byteLength !== 32) {
71147
+ throw new VaultError("bad_key", "A device vault key must contain exactly 32 bytes.");
71148
+ }
71149
+ }
71150
+ function assertAccountName(name) {
71151
+ const parsed = walletNameSchema.safeParse(name);
71152
+ if (!parsed.success) {
71153
+ throw new VaultError("name_taken", "The vault account name is not valid.", {
71154
+ cause: parsed.error
71155
+ });
71156
+ }
71157
+ }
71158
+ function assertAvailableName(file2, name) {
71159
+ assertAccountName(name);
71160
+ if (file2.accounts.some((account) => account.name === name)) {
71161
+ throw new VaultError("name_taken", "A vault account already has that name.");
71162
+ }
71163
+ }
71164
+ function nextDerivedIndex(file2) {
71165
+ let next = file2.nextDerivedIndex ?? 0;
71166
+ for (const account of file2.accounts) {
71167
+ if (account.kind === "derived") next = Math.max(next, account.index + 1);
71168
+ }
71169
+ return next;
71170
+ }
71171
+ function copyAccount(account) {
71172
+ if (account.kind === "derived") return { ...account };
71173
+ return {
71174
+ name: account.name,
71175
+ kind: account.kind,
71176
+ address: account.address,
71177
+ createdAt: account.createdAt
71178
+ };
71179
+ }
71180
+ function sealField(key2, plaintext) {
71181
+ const { nonce, ciphertext, tag } = encryptWithKey(key2, plaintext);
71182
+ return [nonce, ciphertext, tag].map((part) => part.toString("base64url")).join(".");
71183
+ }
71184
+ function openField(key2, value) {
71185
+ const [nonce = "", ciphertext = "", tag = ""] = value.split(".");
71186
+ return decryptWithKey(key2, {
71187
+ nonce: Buffer.from(nonce, "base64url"),
71188
+ ciphertext: Buffer.from(ciphertext, "base64url"),
71189
+ tag: Buffer.from(tag, "base64url")
71190
+ });
71191
+ }
71192
+ function decryptField(key2, value) {
71193
+ try {
71194
+ return openField(key2, value);
71195
+ } catch (error61) {
71196
+ throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
71197
+ cause: error61
71198
+ });
71199
+ }
71200
+ }
71201
+ function decryptPhraseForOpen(key2, phrase) {
71202
+ try {
71203
+ return openField(key2, phrase);
71204
+ } catch (error61) {
71205
+ throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
71206
+ cause: error61
71207
+ });
71208
+ }
71209
+ }
71210
+ function validateStoredImportedAccount(key2, account) {
71211
+ let plaintext;
71212
+ try {
71213
+ plaintext = decryptField(key2, account.key);
71214
+ if (plaintext.byteLength !== 32) {
71215
+ throw new VaultError("bad_key", "The stored imported key has the wrong length.");
71216
+ }
71217
+ let address4;
71218
+ try {
71219
+ address4 = privateKeyToAccount(`0x${plaintext.toString("hex")}`).address;
71220
+ } catch (error61) {
71221
+ throw new VaultError("bad_key", "The stored imported key is not valid.", {
71222
+ cause: error61
71223
+ });
71224
+ }
71225
+ if (address4.toLowerCase() !== account.address.toLowerCase()) {
71226
+ throw new VaultError("bad_key", "The stored imported key does not match its address.");
71227
+ }
71228
+ } finally {
71229
+ plaintext?.fill(0);
71230
+ }
71231
+ }
71232
+ function validateStoredDerivedAccount(key2, file2, account) {
71233
+ const plaintext = decryptField(key2, file2.phrase);
71234
+ let seed;
71235
+ try {
71236
+ seed = phraseToSeed(plaintext.toString("utf8"));
71237
+ const address4 = privateKeyToAccount(
71238
+ deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${account.index}`)
71239
+ ).address;
71240
+ if (address4.toLowerCase() !== account.address.toLowerCase()) {
71241
+ throw new VaultError("bad_key", "The stored derived account does not match this vault.");
71242
+ }
71243
+ } finally {
71244
+ seed?.fill(0);
71245
+ plaintext.fill(0);
71246
+ }
71247
+ }
71248
+ function parseVaultFile(raw) {
71249
+ let value;
71250
+ try {
71251
+ value = JSON.parse(raw);
71252
+ } catch (error61) {
71253
+ throw new VaultError("corrupt", "The vault file is not valid JSON.", { cause: error61 });
71254
+ }
71255
+ const parsed = vaultFileSchema.safeParse(value);
71256
+ if (!parsed.success) {
71257
+ throw new VaultError("corrupt", "The vault file has an invalid structure.", {
71258
+ cause: parsed.error
71259
+ });
71260
+ }
71261
+ if (parsed.data.protected !== (parsed.data.wrappedKey !== void 0)) {
71262
+ throw new VaultError("corrupt", "The vault protection metadata is inconsistent.");
71263
+ }
71264
+ const names = /* @__PURE__ */ new Set();
71265
+ const indexes = /* @__PURE__ */ new Set();
71266
+ for (const account of parsed.data.accounts) {
71267
+ if (names.has(account.name)) {
71268
+ throw new VaultError("corrupt", "The vault file contains duplicate account names.");
71269
+ }
71270
+ names.add(account.name);
71271
+ if (account.kind === "derived") {
71272
+ if (indexes.has(account.index)) {
71273
+ throw new VaultError("corrupt", "The vault file contains duplicate derived indexes.");
71274
+ }
71275
+ indexes.add(account.index);
71276
+ }
71277
+ }
71278
+ return parsed.data;
71279
+ }
71280
+ async function readVaultFile(path, key2) {
71281
+ const file2 = await readVaultFileUnlocked(path);
71282
+ const plaintext = decryptPhraseForOpen(key2, file2.phrase);
71283
+ try {
71284
+ try {
71285
+ validateRecoveryPhrase(plaintext.toString("utf8"));
71286
+ } catch (error61) {
71287
+ throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
71288
+ cause: error61
71289
+ });
71290
+ }
71291
+ } finally {
71292
+ plaintext.fill(0);
71293
+ }
71294
+ return file2;
71295
+ }
71296
+ async function readVaultFileUnlocked(path) {
71297
+ let raw;
71298
+ try {
71299
+ raw = await readFile7(path, "utf8");
71300
+ } catch (error61) {
71301
+ if (isMissingFile2(error61)) {
71302
+ throw new VaultError("not_found", "No vault file was found at the requested path.", {
71303
+ cause: error61
71304
+ });
71305
+ }
71306
+ throw new VaultError("corrupt", "Unable to read the vault file.", { cause: error61 });
71307
+ }
71308
+ return parseVaultFile(raw);
71309
+ }
71310
+ async function refuseExistingVault(path) {
71311
+ try {
71312
+ await stat6(path);
71313
+ } catch (error61) {
71314
+ if (isMissingFile2(error61)) return;
71315
+ throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
71316
+ cause: error61
71317
+ });
71318
+ }
71319
+ throw new VaultError("corrupt", "A vault already exists at the requested path.");
71320
+ }
71321
+ async function writeVaultFile(path, file2) {
71322
+ await mkdir7(dirname5(path), { recursive: true, mode: 448 });
71323
+ const temporaryPath = `${path}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
71324
+ try {
71325
+ await writeFile3(temporaryPath, `${JSON.stringify(file2, null, 2)}
71326
+ `, {
71327
+ encoding: "utf8",
71328
+ mode: 384,
71329
+ flag: "wx"
71330
+ });
71331
+ await rename4(temporaryPath, path);
71332
+ } catch (error61) {
71333
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
71334
+ throw error61;
71335
+ }
71336
+ }
71337
+ async function withVaultLock(path, operation) {
71338
+ await mkdir7(dirname5(path), { recursive: true, mode: 448 });
71339
+ const lockPath = `${path}.lock`;
71340
+ const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
71341
+ let handle;
71342
+ while (!handle) {
71343
+ try {
71344
+ handle = await open5(lockPath, "wx", 384);
71345
+ } catch (error61) {
71346
+ if (!isExistingFile(error61)) throw error61;
71347
+ await removeStaleVaultLock(lockPath);
71348
+ if (Date.now() >= deadline) {
71349
+ throw new VaultError("corrupt", "Timed out waiting for the vault lock.");
71350
+ }
71351
+ await new Promise((resolve4) => setTimeout(resolve4, 20));
71352
+ }
71353
+ }
71354
+ try {
71355
+ return await operation();
71356
+ } finally {
71357
+ await handle.close();
71358
+ await unlink4(lockPath).catch(() => void 0);
71359
+ }
71360
+ }
71361
+ async function removeStaleVaultLock(path) {
71362
+ try {
71363
+ const metadata = await stat6(path);
71364
+ if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
71365
+ } catch (error61) {
71366
+ if (!isMissingFile2(error61)) throw error61;
71367
+ }
71368
+ }
71369
+ function isMissingFile2(error61) {
71370
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
71371
+ }
71372
+ function isExistingFile(error61) {
71373
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "EEXIST";
71374
+ }
71375
+ function asVaultError(error61, code, message) {
71376
+ return error61 instanceof VaultError ? error61 : new VaultError(code, message, { cause: error61 });
71377
+ }
71378
+
71379
+ // ../core/src/file-secret-store.ts
71380
+ var FILE_SECRET_STORE_PASSWORD_ENV = "VAPI_VAULT_PASSWORD";
71381
+ var FILE_SECRET_STORE_MIN_PASSWORD = 12;
71382
+ var CHECK_VALUE = "vapi-network file secret store";
71383
+ var sealedSchema = external_exports.object({ nonce: external_exports.string(), ciphertext: external_exports.string(), tag: external_exports.string() }).strict();
71384
+ var fileSchema = external_exports.object({
71385
+ v: external_exports.literal(1),
71386
+ salt: external_exports.string(),
71387
+ check: sealedSchema,
71388
+ entries: external_exports.record(external_exports.string(), sealedSchema)
71389
+ }).strict();
71390
+ async function createFileSecretStore(options) {
71391
+ const password = passwordFrom(options.env);
71392
+ if (password.length < FILE_SECRET_STORE_MIN_PASSWORD) {
71393
+ throw new KeystoreError(
71394
+ `${FILE_SECRET_STORE_PASSWORD_ENV} must be at least ${FILE_SECRET_STORE_MIN_PASSWORD} characters.`
71395
+ );
71396
+ }
71397
+ await withVaultLock(options.path, async () => {
71398
+ let exists = true;
71399
+ try {
71400
+ await stat7(options.path);
71401
+ } catch (error61) {
71402
+ if (!isMissingFile(error61)) throw error61;
71403
+ exists = false;
71404
+ }
71405
+ if (exists) {
71406
+ await withKey(options.path, options.env, async () => void 0);
71407
+ return;
71408
+ }
71409
+ const salt = randomBytes6(32);
71410
+ const key2 = await deriveScryptKey(password, salt);
71411
+ try {
71412
+ await writeJsonAtomic(
71413
+ options.path,
71414
+ {
71415
+ v: 1,
71416
+ salt: salt.toString("base64"),
71417
+ check: seal(key2, CHECK_VALUE),
71418
+ entries: {}
71419
+ },
71420
+ { mode: 384 }
71421
+ );
71422
+ } finally {
71423
+ key2.fill(0);
71424
+ }
71425
+ });
71426
+ }
71427
+ function fileSecretStore(options) {
71428
+ const env = options.env ?? process.env;
71429
+ const write2 = async (change) => await withVaultLock(
71430
+ options.path,
71431
+ async () => await withKey(options.path, env, async (file2, key2) => {
71432
+ const changed = change(file2, key2);
71433
+ if (changed) await writeJsonAtomic(options.path, file2, { mode: 384 });
71434
+ return changed;
71435
+ })
71436
+ );
71437
+ const get = async (name) => await withKey(options.path, env, async (file2, key2) => {
71438
+ const sealed = Object.hasOwn(file2.entries, name) ? file2.entries[name] : void 0;
71439
+ return sealed === void 0 ? void 0 : open6(key2, sealed);
71440
+ });
71441
+ return {
71442
+ // A locked backend still exists; it must never enable a plaintext fallback.
71443
+ available: true,
71444
+ platform: process.platform,
71445
+ description: "the encrypted vAPI secrets file",
71446
+ get,
71447
+ async has(name) {
71448
+ return await get(name) !== void 0;
71449
+ },
71450
+ async set(name, value) {
71451
+ if (name === "__proto__") {
71452
+ throw new KeystoreError("The secret name is reserved in the encrypted vAPI secrets file.");
71453
+ }
71454
+ await write2((file2, key2) => {
71455
+ file2.entries[name] = seal(key2, value);
71456
+ return true;
71457
+ });
71458
+ },
71459
+ async remove(name) {
71460
+ return await write2((file2) => {
71461
+ if (!Object.hasOwn(file2.entries, name)) return false;
71462
+ delete file2.entries[name];
71463
+ return true;
71464
+ });
71465
+ }
71466
+ };
71467
+ }
71468
+ async function withKey(path, env, operation) {
71469
+ const file2 = await readStoredFile(path);
71470
+ const key2 = await deriveScryptKey(passwordFrom(env), Buffer.from(file2.salt, "base64"));
71471
+ try {
71472
+ if (open6(key2, file2.check) !== CHECK_VALUE) throw wrongPassword();
71473
+ return await operation(file2, key2);
71474
+ } finally {
71475
+ key2.fill(0);
71476
+ }
71477
+ }
71478
+ function passwordFrom(env) {
71479
+ const password = (env ?? process.env)[FILE_SECRET_STORE_PASSWORD_ENV];
71480
+ if (!password) {
71481
+ throw new KeystoreError(
71482
+ `This vault keeps its secrets in an encrypted file. Set ${FILE_SECRET_STORE_PASSWORD_ENV} to open it.`
71483
+ );
71484
+ }
71485
+ return password;
71486
+ }
71487
+ async function readStoredFile(path) {
71488
+ let raw;
71489
+ try {
71490
+ raw = await readFile8(path, "utf8");
71491
+ } catch (error61) {
71492
+ throw new KeystoreError("The vAPI secrets file is missing. Run vapi setup again.", {
71493
+ cause: error61
71494
+ });
71495
+ }
71496
+ let value;
71497
+ try {
71498
+ value = JSON.parse(raw);
71499
+ } catch {
71500
+ throw new KeystoreError("The vAPI secrets file is damaged.");
71501
+ }
71502
+ const parsed = fileSchema.safeParse(value);
71503
+ if (!parsed.success) throw new KeystoreError("The vAPI secrets file is damaged.");
71504
+ return parsed.data;
71505
+ }
71506
+ function seal(key2, value) {
71507
+ const { nonce, ciphertext, tag } = encryptWithKey(key2, Buffer.from(value, "utf8"));
71508
+ return {
71509
+ nonce: nonce.toString("base64"),
71510
+ ciphertext: ciphertext.toString("base64"),
71511
+ tag: tag.toString("base64")
71512
+ };
71513
+ }
71514
+ function open6(key2, sealed) {
71515
+ try {
71516
+ return decryptWithKey(key2, {
71517
+ nonce: Buffer.from(sealed.nonce, "base64"),
71518
+ ciphertext: Buffer.from(sealed.ciphertext, "base64"),
71519
+ tag: Buffer.from(sealed.tag, "base64")
71520
+ }).toString("utf8");
71521
+ } catch (error61) {
71522
+ throw wrongPassword(error61);
71523
+ }
71524
+ }
71525
+ function wrongPassword(cause) {
71526
+ return new KeystoreError(`Wrong ${FILE_SECRET_STORE_PASSWORD_ENV} for the vAPI secrets file.`, {
71527
+ cause
71528
+ });
71529
+ }
71530
+
71531
+ // ../core/src/secret-backend.ts
71532
+ import { readFileSync } from "node:fs";
71533
+ import { stat as stat8 } from "node:fs/promises";
71534
+ import { join as join6 } from "node:path";
71535
+ var PROBE_ACCOUNT = "setup-probe";
71536
+ var pinSchema = external_exports.object({ v: external_exports.literal(1), backend: external_exports.enum(["os", "file"]) }).strict();
71537
+ function secretBackendPath(home = getVapiPaths().directory) {
71538
+ return join6(home, "secret-store.json");
71539
+ }
71540
+ function secretsFilePath(home = getVapiPaths().directory) {
71541
+ return join6(home, "secrets.json");
71542
+ }
71543
+ function readSecretBackend(home = getVapiPaths().directory) {
71544
+ const path = secretBackendPath(home);
71545
+ try {
71546
+ const parsed = pinSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
71547
+ if (parsed.success) return parsed.data.backend;
71548
+ } catch (error61) {
71549
+ if (isMissingFile(error61)) return "os";
71550
+ }
71551
+ throw new KeystoreError(`The vAPI secret-store pin at ${path} is damaged.`);
71552
+ }
71553
+ async function chooseSecretBackend(options) {
71554
+ const env = options.env ?? process.env;
71555
+ const osWorks = options.os.platform !== "linux" || await osStoreWorks(options.os);
71556
+ const path = secretBackendPath(options.home);
71557
+ return await withVaultLock(path, async () => {
71558
+ if (await fileExists(path)) return readSecretBackend(options.home);
71559
+ if (await fileExists(join6(options.home, "vault.json"))) return "os";
71560
+ let backend;
71561
+ if (osWorks) {
71562
+ backend = "os";
71563
+ } else if (env[FILE_SECRET_STORE_PASSWORD_ENV]) {
71564
+ await createFileSecretStore({ path: secretsFilePath(options.home), env });
71565
+ backend = "file";
71566
+ } else {
71567
+ throw new KeystoreError(
71568
+ [
71569
+ `This machine has no working keyring (${options.os.description}).`,
71570
+ `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,`,
71571
+ "or run vapi on your own computer, or connect Claude from https://api.vapinetwork.ai/connect."
71572
+ ].join(" ")
71573
+ );
71574
+ }
71575
+ await writeJsonAtomic(path, { v: 1, backend }, { mode: 384 });
71576
+ return backend;
71577
+ });
71578
+ }
71579
+ async function fileExists(path) {
71580
+ try {
71581
+ await stat8(path);
71582
+ return true;
71583
+ } catch (error61) {
71584
+ if (isMissingFile(error61)) return false;
71585
+ throw error61;
71586
+ }
71587
+ }
71588
+ async function osStoreWorks(store) {
71589
+ if (!store.available) return false;
71590
+ try {
71591
+ try {
71592
+ await store.set(PROBE_ACCOUNT, "ok");
71593
+ return await store.get(PROBE_ACCOUNT) === "ok";
71594
+ } finally {
71595
+ await store.remove(PROBE_ACCOUNT);
71596
+ }
71597
+ } catch {
71598
+ return false;
71599
+ }
71600
+ }
71601
+
71602
+ // ../core/src/secret-store.ts
71603
+ var SECRET_STORE_SERVICE = "vapi-network";
71604
+ var SECURITY_BINARY = "/usr/bin/security";
71605
+ var SECRET_TOOL_BINARY = "secret-tool";
71606
+ var WINDOWS_POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-Command", "-"];
71607
+ var SECURITY_ITEM_NOT_FOUND = 44;
71608
+ var WINDOWS_SECRET_SUCCESS = 0;
71609
+ var WINDOWS_SECRET_NOT_FOUND = 2;
71610
+ var UNSUPPORTED_PLATFORM = "No OS secret store on this platform yet; use VAPI_KEYSTORE_PASSWORD.";
71611
+ var SECRET_TOOL_MISSING = [
71612
+ "secret-tool is not installed, so the passphrase cannot be kept in the OS secret store.",
71613
+ "Install libsecret-tools (Debian, Ubuntu) or libsecret (Fedora, Arch), or use VAPI_KEYSTORE_PASSWORD."
71614
+ ].join(" ");
71615
+ var POWERSHELL_MISSING = [
71616
+ "Windows PowerShell (powershell.exe) was not found, so the passphrase cannot be kept in the OS secret store.",
71617
+ "Use VAPI_KEYSTORE_PASSWORD."
71618
+ ].join(" ");
71619
+ function secretStore(options = {}) {
71620
+ const home = options.home ?? getVapiPaths().directory;
71621
+ if (readSecretBackend(home) === "file") {
71622
+ return fileSecretStore({ path: secretsFilePath(home), env: options.env ?? process.env });
71623
+ }
71624
+ return osSecretStore(options);
71625
+ }
71626
+ function osSecretStore(options = {}) {
71627
+ const platform2 = options.platform ?? process.platform;
71628
+ const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
71629
+ const env = options.env ?? process.env;
71630
+ const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
71631
+ if (platform2 === "darwin") return keychainStore(platform2, run);
71632
+ if (platform2 === "win32") return windowsDataProtectionStore(platform2, run, env, installed);
71633
+ if (platform2 === "linux") return libsecretStore(platform2, run, installed);
71634
+ return unsupportedStore(platform2);
71635
+ }
71636
+ function memorySecretStore(initial = {}) {
71637
+ const entries = new Map(Object.entries(initial));
71638
+ return {
71639
+ available: true,
71640
+ platform: process.platform,
71641
+ description: "an in-memory store",
71642
+ async get(name) {
71643
+ return entries.get(name);
71644
+ },
71645
+ async has(name) {
71646
+ return entries.has(name);
71647
+ },
71648
+ async set(name, passphrase) {
71649
+ entries.set(name, passphrase);
71650
+ },
71651
+ async remove(name) {
71652
+ return entries.delete(name);
71653
+ },
71654
+ async list() {
71655
+ return [...entries.keys()].sort();
71656
+ }
71657
+ };
71658
+ }
71659
+ function keychainStore(platform2, run) {
71660
+ const find = async (account, withPassword) => await run(SECURITY_BINARY, [
71661
+ "find-generic-password",
71662
+ "-a",
71663
+ account,
71664
+ "-s",
71665
+ SECRET_STORE_SERVICE,
71666
+ ...withPassword ? ["-w"] : []
71667
+ ]);
71668
+ const read = async (account, what) => {
71669
+ const result = await find(account, true);
71670
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return void 0;
71671
+ requireSuccess(result, what);
71672
+ const value = withoutTrailingNewline(result.stdout);
71673
+ return value.length === 0 ? void 0 : value;
71674
+ };
71675
+ const write2 = async (account, value, what) => {
71676
+ const result = await run(
71677
+ SECURITY_BINARY,
71678
+ [
71679
+ "add-generic-password",
71680
+ "-a",
71681
+ account,
71682
+ "-s",
71683
+ SECRET_STORE_SERVICE,
71684
+ "-l",
71685
+ `${SECRET_STORE_SERVICE} ${account}`,
71686
+ "-U",
71687
+ "-w"
71688
+ ],
71689
+ // `security` asks for the password and then for its confirmation.
71690
+ `${value}
71691
+ ${value}
71692
+ `
71693
+ );
71694
+ requireSuccess(result, what);
71695
+ };
71696
+ const erase = async (account, what) => {
71697
+ const result = await run(SECURITY_BINARY, [
71698
+ "delete-generic-password",
71699
+ "-a",
71700
+ account,
71701
+ "-s",
71702
+ SECRET_STORE_SERVICE
71703
+ ]);
71704
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
71705
+ requireSuccess(result, what);
71706
+ return true;
71707
+ };
71708
+ const erasePartsAfter = async (account, keep, what) => {
71709
+ for (let part = keep + 1; part <= MAX_KEYCHAIN_PARTS; part += 1) {
71710
+ if (!await erase(keychainPart(account, part), what)) return;
71711
+ }
71712
+ };
71713
+ return {
71714
+ available: true,
71715
+ platform: platform2,
71716
+ description: "the macOS Keychain",
71717
+ async get(name) {
71718
+ const account = accountFor(name);
71719
+ const what = `read the passphrase of ${name} from the macOS Keychain`;
71720
+ const value = await read(account, what);
71721
+ const parts = value === void 0 ? void 0 : chunkedPartCount(value);
71722
+ if (value === void 0 || parts === void 0) return value;
71723
+ let joined = "";
71724
+ for (let part = 1; part <= parts; part += 1) {
71725
+ const chunk = await read(keychainPart(account, part), what);
71726
+ if (chunk === void 0) {
71727
+ throw new KeystoreError(
71728
+ `The stored secret ${name} is incomplete in the macOS Keychain. Store it again.`
71729
+ );
71730
+ }
71731
+ joined += chunk;
71732
+ }
71733
+ return joined;
71734
+ },
71735
+ async has(name) {
71736
+ const result = await find(accountFor(name), false);
71737
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
71738
+ requireSuccess(result, `look up ${name} in the macOS Keychain`);
71739
+ return true;
71740
+ },
71741
+ async set(name, passphrase) {
71742
+ requirePassphrase(passphrase);
71743
+ const account = accountFor(name);
71744
+ const what = `store the passphrase of ${name} in the macOS Keychain`;
71745
+ if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
71746
+ await write2(account, passphrase, what);
71747
+ return;
71748
+ }
71749
+ const chunks = [];
71750
+ for (let index2 = 0; index2 < passphrase.length; index2 += KEYCHAIN_CHUNK) {
71751
+ chunks.push(passphrase.slice(index2, index2 + KEYCHAIN_CHUNK));
71752
+ }
71753
+ if (chunks.length > MAX_KEYCHAIN_PARTS) {
71754
+ throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
71755
+ }
71756
+ for (const [index2, chunk] of chunks.entries()) {
71757
+ await write2(keychainPart(account, index2 + 1), chunk, what);
71758
+ }
71759
+ await erasePartsAfter(account, chunks.length, what);
71760
+ await write2(account, `${CHUNKED_MARKER}${chunks.length}`, what);
71761
+ },
71762
+ async remove(name) {
71763
+ const account = accountFor(name);
71764
+ const what = `remove the passphrase of ${name} from the macOS Keychain`;
71765
+ const found = await find(account, true);
71766
+ if (found.code === SECURITY_ITEM_NOT_FOUND) return false;
71767
+ requireSuccess(found, what);
71768
+ if (chunkedPartCount(withoutTrailingNewline(found.stdout)) !== void 0) {
71769
+ await erasePartsAfter(account, 0, what);
71770
+ }
71771
+ return await erase(account, what);
71772
+ }
71773
+ };
71774
+ }
71775
+ var KEYCHAIN_PROMPT_LIMIT = 128;
71776
+ var KEYCHAIN_CHUNK = 120;
71777
+ var MAX_KEYCHAIN_PARTS = 32;
71778
+ var CHUNKED_MARKER = "vapi-chunked:v1:";
71779
+ function keychainPart(account, part) {
71780
+ return `${account}#${part}`;
71781
+ }
71782
+ function chunkedPartCount(value) {
71783
+ if (!value.startsWith(CHUNKED_MARKER)) return void 0;
71784
+ const parts = Number(value.slice(CHUNKED_MARKER.length));
71785
+ return Number.isInteger(parts) && parts > 0 && parts <= MAX_KEYCHAIN_PARTS ? parts : void 0;
71786
+ }
71787
+ function windowsSecretFileName(account) {
71788
+ let encoded = "";
71789
+ for (let index2 = 0; index2 < account.length; index2 += 1) {
71790
+ const character = account[index2];
71791
+ if (/^[a-z0-9._#-]$/u.test(character)) {
71792
+ encoded += character;
71793
+ continue;
71794
+ }
71795
+ encoded += `%${account.charCodeAt(index2).toString(16).toUpperCase().padStart(4, "0")}`;
71796
+ }
71797
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(encoded)) {
71798
+ encoded = `%${encoded.charCodeAt(0).toString(16).toUpperCase()}${encoded.slice(1)}`;
71799
+ }
71800
+ return `${encoded}.bin`;
71801
+ }
71802
+ function windowsDataProtectionStore(platform2, run, env, installed) {
71803
+ const powershell = `${env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
71804
+ const fileDetails = (name) => {
71805
+ const file2 = windowsSecretFileName(accountFor(name));
71806
+ return { file: file2, account: file2.slice(0, -".bin".length) };
71807
+ };
71808
+ const script = (file2, operations) => [
71809
+ "$ErrorActionPreference = 'Stop'",
71810
+ "try {",
71811
+ " Add-Type -AssemblyName System.Security",
71812
+ " $dir = Join-Path $env:LOCALAPPDATA 'vapi-network\\secrets'",
71813
+ ` $path = Join-Path $dir '${file2}'`,
71814
+ ...operations.map((operation) => ` ${operation}`),
71815
+ "} catch {",
71816
+ " [Console]::Error.WriteLine($_.Exception.Message)",
71817
+ " exit 1",
71818
+ "}"
71819
+ ].join("\n");
71820
+ const execute = async (script2) => {
71821
+ const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
71822
+
71823
+ `);
71824
+ requirePowerShell(result);
71825
+ return result;
71826
+ };
71827
+ return {
71828
+ available: installed(powershell),
71829
+ platform: platform2,
71830
+ description: "Windows Data Protection (DPAPI)",
71831
+ async get(name) {
71832
+ const { file: file2, account } = fileDetails(name);
71833
+ const result = await execute(
71834
+ script(file2, [
71835
+ `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
71836
+ "$blob = [System.IO.File]::ReadAllBytes($path)",
71837
+ "$bytes = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
71838
+ "[Console]::Out.Write([Convert]::ToBase64String($bytes))",
71839
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71840
+ ])
71841
+ );
71842
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return void 0;
71843
+ requireSuccess(result, `read the passphrase of ${name} from Windows Data Protection`);
71844
+ const value = Buffer.from(result.stdout.trim(), "base64").toString("utf8");
71845
+ return value.length === 0 ? void 0 : value;
71846
+ },
71847
+ async has(name) {
71848
+ const { file: file2, account } = fileDetails(name);
71849
+ const result = await execute(
71850
+ script(file2, [
71851
+ `if (Test-Path -LiteralPath $path) { exit ${WINDOWS_SECRET_SUCCESS} }`,
71852
+ `[Console]::Error.WriteLine('No stored secret for ${account}.')`,
71853
+ `exit ${WINDOWS_SECRET_NOT_FOUND}`
71854
+ ])
71855
+ );
71856
+ if (result.code === WINDOWS_SECRET_SUCCESS) return true;
71857
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
71858
+ requireSuccess(result, `look up ${name} in Windows Data Protection`);
71859
+ return false;
71860
+ },
71861
+ async set(name, passphrase) {
71862
+ requirePassphrase(passphrase);
71863
+ const { file: file2 } = fileDetails(name);
71864
+ const value = Buffer.from(passphrase, "utf8").toString("base64");
71865
+ const result = await execute(
71866
+ script(file2, [
71867
+ "[void][System.IO.Directory]::CreateDirectory($dir)",
71868
+ `$bytes = [Convert]::FromBase64String('${value}')`,
71869
+ "$blob = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
71870
+ "[System.IO.File]::WriteAllBytes($path, $blob)",
71871
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71872
+ ])
71873
+ );
71874
+ requireSuccess(result, `store the passphrase of ${name} in Windows Data Protection`);
71875
+ },
71876
+ async remove(name) {
71877
+ const { file: file2, account } = fileDetails(name);
71878
+ const result = await execute(
71879
+ script(file2, [
71880
+ `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
71881
+ "Remove-Item -LiteralPath $path -Force",
71882
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71883
+ ])
71884
+ );
71885
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
71886
+ requireSuccess(result, `remove the passphrase of ${name} from Windows Data Protection`);
71887
+ return true;
71888
+ }
71889
+ };
71890
+ }
71891
+ function libsecretStore(platform2, run, installed) {
71892
+ const lookup2 = async (name) => {
71893
+ const result = await run(SECRET_TOOL_BINARY, [
71894
+ "lookup",
71895
+ "service",
71896
+ SECRET_STORE_SERVICE,
71897
+ "account",
71898
+ accountFor(name)
71899
+ ]);
71900
+ requireBinary(result);
71901
+ const value = withoutTrailingNewline(result.stdout);
71902
+ if (result.code === 0) return value.length === 0 ? void 0 : value;
71903
+ if (result.stderr.trim().length === 0) return void 0;
71904
+ requireSuccess(result, `read the passphrase of ${name} from the secret service`);
71905
+ return void 0;
71906
+ };
71907
+ return {
71908
+ available: installed(SECRET_TOOL_BINARY),
71909
+ platform: platform2,
71910
+ description: "the libsecret keyring",
71911
+ get: lookup2,
71912
+ async has(name) {
71913
+ return await lookup2(name) !== void 0;
71914
+ },
71915
+ async set(name, passphrase) {
71916
+ requirePassphrase(passphrase);
71917
+ const account = accountFor(name);
71918
+ const result = await run(
71919
+ SECRET_TOOL_BINARY,
71920
+ [
71921
+ "store",
71922
+ `--label=${SECRET_STORE_SERVICE} ${account}`,
71923
+ "service",
71924
+ SECRET_STORE_SERVICE,
71925
+ "account",
71926
+ account
71927
+ ],
71928
+ `${passphrase}
71929
+ `
71930
+ );
71931
+ requireBinary(result);
71932
+ requireSuccess(result, `store the passphrase of ${name} in the secret service`);
71933
+ },
71934
+ async remove(name) {
71935
+ const existed = await lookup2(name) !== void 0;
71936
+ const result = await run(SECRET_TOOL_BINARY, [
71937
+ "clear",
71938
+ "service",
71939
+ SECRET_STORE_SERVICE,
71940
+ "account",
71941
+ accountFor(name)
71942
+ ]);
71943
+ requireBinary(result);
71944
+ requireSuccess(result, `remove the passphrase of ${name} from the secret service`);
71945
+ return existed;
71946
+ }
71947
+ };
71948
+ }
71949
+ function unsupportedStore(platform2) {
71950
+ const refuse = () => {
71951
+ throw new KeystoreError(UNSUPPORTED_PLATFORM);
71952
+ };
71953
+ return {
71954
+ available: false,
71955
+ platform: platform2,
71956
+ description: "no OS secret store",
71957
+ get: async () => refuse(),
71958
+ has: async () => refuse(),
71959
+ set: async () => refuse(),
71960
+ remove: async () => refuse()
71961
+ };
71962
+ }
71963
+ function accountFor(name) {
71964
+ const account = name.trim();
71965
+ if (account.length === 0) {
71966
+ throw new KeystoreError("A wallet name is needed to reach the OS secret store.");
71967
+ }
71968
+ return account;
71969
+ }
71970
+ function requirePassphrase(passphrase) {
71971
+ if (passphrase.length === 0) {
71972
+ throw new KeystoreError("Keystore passphrase cannot be empty.");
71973
+ }
71974
+ }
71975
+ function requireBinary(result) {
71976
+ if (result.notFound === true) throw new KeystoreError(SECRET_TOOL_MISSING);
71977
+ }
71978
+ function requirePowerShell(result) {
71979
+ if (result.notFound === true) throw new KeystoreError(POWERSHELL_MISSING);
71980
+ }
71981
+ function binaryInstalled(file2, env) {
71982
+ if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
71983
+ return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join7(directory, file2)));
71984
+ }
71985
+ var SAFE_FAILURE_DETAILS = [
71986
+ "Cannot autolaunch D-Bus without X11 $DISPLAY",
71987
+ "Cannot autolaunch D-Bus",
71988
+ "The name org.freedesktop.secrets was not provided by any .service files",
71989
+ "Cannot create an item in a locked collection",
71990
+ "User interaction is not allowed.",
71991
+ "Access to the path is denied."
71992
+ ];
71993
+ function requireSuccess(result, what) {
71994
+ if (result.code === 0) return;
71995
+ const detail = SAFE_FAILURE_DETAILS.find((reason) => result.stderr.includes(reason));
71996
+ throw new KeystoreError(
71997
+ `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail === void 0 ? "" : ` ${detail}`}`
71998
+ );
71999
+ }
72000
+ function withoutTrailingNewline(value) {
72001
+ return value.replace(/\r?\n$/u, "");
72002
+ }
72003
+ var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve4) => {
72004
+ let stdout = "";
72005
+ let stderr2 = "";
72006
+ let settled = false;
72007
+ const finish = (outcome) => {
72008
+ if (settled) return;
72009
+ settled = true;
72010
+ resolve4(outcome);
72011
+ };
72012
+ const child = spawn(file2, [...args], {
72013
+ detached: platform2 !== "win32",
72014
+ stdio: ["pipe", "pipe", "pipe"],
72015
+ windowsHide: true
72016
+ });
72017
+ child.stdout?.setEncoding("utf8");
72018
+ child.stdout?.on("data", (chunk) => {
72019
+ stdout += chunk;
72020
+ });
72021
+ child.stderr?.setEncoding("utf8");
72022
+ child.stderr?.on("data", (chunk) => {
72023
+ stderr2 += chunk;
72024
+ });
72025
+ child.on("error", (error61) => {
72026
+ finish({
72027
+ code: null,
72028
+ stdout,
72029
+ stderr: stderr2,
72030
+ ...error61.code === "ENOENT" ? { notFound: true } : {}
72031
+ });
72032
+ });
72033
+ child.on("close", (code) => finish({ code, stdout, stderr: stderr2 }));
72034
+ child.stdin?.on("error", () => void 0);
72035
+ child.stdin?.end(input2 ?? "");
72036
+ });
72037
+
72038
+ // ../core/src/passphrase.ts
72039
+ var PASSPHRASE_ENVIRONMENT_VARIABLE = "VAPI_KEYSTORE_PASSWORD";
72040
+ function noPassphraseHint(walletName) {
72041
+ return `Set ${PASSPHRASE_ENVIRONMENT_VARIABLE}, or store this wallet's passphrase once with vapi unlock --wallet ${walletName}.`;
72042
+ }
72043
+ function staleStoredPassphraseMessage(walletName, store) {
72044
+ return [
72045
+ `The passphrase stored in ${store.description} no longer opens wallet ${walletName}.`,
72046
+ `Store the current one with vapi unlock --wallet ${walletName}, or remove it with vapi lock --wallet ${walletName}.`
72047
+ ].join(" ");
72048
+ }
72049
+ async function resolvePassphrase(walletName, options = {}) {
72050
+ const env = options.env ?? process.env;
72051
+ const fromEnvironment = env[PASSPHRASE_ENVIRONMENT_VARIABLE];
72052
+ if (fromEnvironment !== void 0) {
72053
+ if (fromEnvironment.length === 0) {
72054
+ throw new KeystoreError(`${PASSPHRASE_ENVIRONMENT_VARIABLE} cannot be empty.`);
72055
+ }
72056
+ return { passphrase: fromEnvironment, source: "environment" };
71876
72057
  }
71877
- }
71878
- async function exportMemberKey(args) {
71879
- return await exportVaultAccountKey(args);
71880
- }
71881
- function assertVaultKey(key2) {
71882
- if (key2.byteLength !== 32) {
71883
- throw new VaultError("bad_key", "A device vault key must contain exactly 32 bytes.");
72058
+ if (options.confirm !== true) {
72059
+ const stored = await readStored(options.store ?? secretStore(), walletName);
72060
+ if (stored !== void 0) return { passphrase: stored, source: "secret-store" };
71884
72061
  }
71885
- }
71886
- function assertAccountName(name) {
71887
- const parsed = walletNameSchema.safeParse(name);
71888
- if (!parsed.success) {
71889
- throw new VaultError("name_taken", "The vault account name is not valid.", {
71890
- cause: parsed.error
71891
- });
72062
+ const hint = noPassphraseHint(walletName);
72063
+ if (options.interactive === false) {
72064
+ throw new KeystoreError(
72065
+ `No interactive terminal is available for the keystore prompt. ${hint}`
72066
+ );
71892
72067
  }
71893
- }
71894
- function assertAvailableName(file2, name) {
71895
- assertAccountName(name);
71896
- if (file2.accounts.some((account) => account.name === name)) {
71897
- throw new VaultError("name_taken", "A vault account already has that name.");
72068
+ const prompt = options.prompt ?? promptForSecret;
72069
+ const first = await prompt(`Passphrase for ${walletName}: `, hint);
72070
+ if (first.length === 0) {
72071
+ throw new KeystoreError("Keystore passphrase cannot be empty.");
72072
+ }
72073
+ if (options.confirm === true) {
72074
+ const second = await prompt("Confirm passphrase: ", hint);
72075
+ if (first !== second) throw new KeystoreError("Passphrases do not match.");
71898
72076
  }
72077
+ return { passphrase: first, source: "prompt" };
71899
72078
  }
71900
- function nextDerivedIndex(file2) {
71901
- let next = file2.nextDerivedIndex ?? 0;
71902
- for (const account of file2.accounts) {
71903
- if (account.kind === "derived") next = Math.max(next, account.index + 1);
72079
+ async function readStored(store, walletName) {
72080
+ if (!store.available) return void 0;
72081
+ try {
72082
+ return await store.get(walletName);
72083
+ } catch {
72084
+ return void 0;
71904
72085
  }
71905
- return next;
71906
72086
  }
71907
- function copyAccount(account) {
71908
- if (account.kind === "derived") return { ...account };
71909
- return {
71910
- name: account.name,
71911
- kind: account.kind,
71912
- address: account.address,
71913
- createdAt: account.createdAt
71914
- };
72087
+
72088
+ // ../core/src/receipts.ts
72089
+ import { randomBytes as randomBytes8 } from "node:crypto";
72090
+ import { mkdir as mkdir8, open as open7, readFile as readFile9, rename as rename5, writeFile as writeFile4 } from "node:fs/promises";
72091
+ import { dirname as dirname6 } from "node:path";
72092
+
72093
+ // ../core/src/agent-run.ts
72094
+ import { randomBytes as randomBytes7 } from "node:crypto";
72095
+ var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
72096
+ function isRunId(value) {
72097
+ return typeof value === "string" && RUN_ID_PATTERN.test(value);
71915
72098
  }
71916
- function sealField(key2, plaintext) {
71917
- const { nonce, ciphertext, tag } = encryptWithKey(key2, plaintext);
71918
- return [nonce, ciphertext, tag].map((part) => part.toString("base64url")).join(".");
72099
+ function createRunId(random = randomBytes7) {
72100
+ return `run_${Buffer.from(random(12)).toString("hex")}`;
71919
72101
  }
71920
- function openField(key2, value) {
71921
- const [nonce = "", ciphertext = "", tag = ""] = value.split(".");
71922
- return decryptWithKey(key2, {
71923
- nonce: Buffer.from(nonce, "base64url"),
71924
- ciphertext: Buffer.from(ciphertext, "base64url"),
71925
- tag: Buffer.from(tag, "base64url")
71926
- });
72102
+ var runRefSchema = external_exports.strictObject({
72103
+ id: external_exports.string().regex(RUN_ID_PATTERN),
72104
+ swarm: external_exports.string().optional(),
72105
+ member: external_exports.string().optional(),
72106
+ parentRunId: external_exports.string().optional()
72107
+ });
72108
+
72109
+ // ../core/src/receipts.ts
72110
+ var receiptTestHooks;
72111
+ function __setReceiptTestHooks(hooks) {
72112
+ receiptTestHooks = hooks;
71927
72113
  }
71928
- function decryptField(key2, value) {
71929
- try {
71930
- return openField(key2, value);
71931
- } catch (error61) {
71932
- throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
71933
- cause: error61
71934
- });
71935
- }
72114
+ var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
72115
+ async function withReceiptJournalLock(path, operation) {
72116
+ return await withFileLock(`${path}.lock`, operation, {
72117
+ lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
72118
+ });
71936
72119
  }
71937
- function decryptPhraseForOpen(key2, phrase) {
71938
- try {
71939
- return openField(key2, phrase);
71940
- } catch (error61) {
71941
- throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
71942
- cause: error61
71943
- });
72120
+ var durationSchema = external_exports.number().nonnegative().finite();
72121
+ var receiptSchema = external_exports.strictObject({
72122
+ id: external_exports.string().min(1),
72123
+ timestamp: external_exports.iso.datetime(),
72124
+ run: runRefSchema.optional(),
72125
+ kind: external_exports.literal("transfer").optional(),
72126
+ wallet: walletNameSchema.optional(),
72127
+ resourceUrl: external_exports.url(),
72128
+ method: external_exports.string().min(1).optional(),
72129
+ source: external_exports.string().min(1).optional(),
72130
+ provenance: external_exports.array(
72131
+ external_exports.strictObject({
72132
+ source: external_exports.string().min(1),
72133
+ sourceUrl: external_exports.string().optional(),
72134
+ ref: external_exports.string().optional()
72135
+ })
72136
+ ).optional(),
72137
+ quote: external_exports.strictObject({
72138
+ network: external_exports.string(),
72139
+ asset: external_exports.string().optional(),
72140
+ amountAtomic: external_exports.string().regex(/^\d+$/),
72141
+ payTo: external_exports.string().optional()
72142
+ }).optional(),
72143
+ payer: external_exports.string().optional(),
72144
+ paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
72145
+ authorization: external_exports.strictObject({
72146
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
72147
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
72148
+ validBefore: external_exports.string().regex(/^\d+$/)
72149
+ }).optional(),
72150
+ transfer: external_exports.strictObject({
72151
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
72152
+ toName: external_exports.string().min(1),
72153
+ toKind: external_exports.enum(["owner", "account"]),
72154
+ amountAtomic: external_exports.string().regex(/^\d+$/),
72155
+ network: external_exports.string().min(1),
72156
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
72157
+ status: external_exports.enum(["sent", "unknown", "failed"]),
72158
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
72159
+ replayed: external_exports.boolean(),
72160
+ reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
72161
+ request: external_exports.strictObject({
72162
+ authorization: external_exports.strictObject({
72163
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
72164
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
72165
+ value: external_exports.string().regex(/^\d+$/),
72166
+ validAfter: external_exports.string().regex(/^\d+$/),
72167
+ validBefore: external_exports.string().regex(/^\d+$/),
72168
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
72169
+ }),
72170
+ signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
72171
+ }).optional()
72172
+ }).optional(),
72173
+ settlement: external_exports.strictObject({
72174
+ outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
72175
+ transaction: external_exports.string().optional(),
72176
+ explorerUrl: external_exports.url().optional(),
72177
+ evidence: external_exports.unknown().optional()
72178
+ }).optional(),
72179
+ latencyMs: external_exports.number().nonnegative().finite().optional(),
72180
+ status: external_exports.number().int().min(100).max(599).optional(),
72181
+ error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
72182
+ phases: external_exports.strictObject({
72183
+ discoverMs: durationSchema.optional(),
72184
+ quoteMs: durationSchema.optional(),
72185
+ signMs: durationSchema.optional(),
72186
+ requestMs: durationSchema.optional(),
72187
+ settleMs: durationSchema.optional()
72188
+ }).optional(),
72189
+ listing: external_exports.strictObject({
72190
+ name: external_exports.string().min(1).optional(),
72191
+ providerHost: external_exports.string().min(1).optional(),
72192
+ source: external_exports.string().min(1)
72193
+ }).optional(),
72194
+ retry: external_exports.number().int().nonnegative().optional(),
72195
+ policy: external_exports.strictObject({
72196
+ maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
72197
+ capsApplied: external_exports.boolean()
72198
+ }).optional(),
72199
+ client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
72200
+ outcome: external_exports.enum([
72201
+ "paid",
72202
+ "signed_in",
72203
+ "declined_policy",
72204
+ "failed_request",
72205
+ "settlement_rejected",
72206
+ "settlement_unknown"
72207
+ ]).optional()
72208
+ });
72209
+ function parseReceipt(value) {
72210
+ const receipt = receiptSchema.parse(value);
72211
+ const transaction2 = receipt.settlement?.transaction;
72212
+ const network = receipt.quote?.network;
72213
+ const explorerUrl = transaction2 === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction2);
72214
+ if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
72215
+ return receipt;
71944
72216
  }
71945
- }
71946
- function validateStoredImportedAccount(key2, account) {
71947
- let plaintext;
71948
- try {
71949
- plaintext = decryptField(key2, account.key);
71950
- if (plaintext.byteLength !== 32) {
71951
- throw new VaultError("bad_key", "The stored imported key has the wrong length.");
71952
- }
71953
- let address4;
71954
- try {
71955
- address4 = privateKeyToAccount(`0x${plaintext.toString("hex")}`).address;
71956
- } catch (error61) {
71957
- throw new VaultError("bad_key", "The stored imported key is not valid.", {
71958
- cause: error61
71959
- });
71960
- }
71961
- if (address4.toLowerCase() !== account.address.toLowerCase()) {
71962
- throw new VaultError("bad_key", "The stored imported key does not match its address.");
72217
+ return {
72218
+ ...receipt,
72219
+ settlement: {
72220
+ outcome: receipt.settlement.outcome,
72221
+ ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
72222
+ explorerUrl,
72223
+ ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
71963
72224
  }
71964
- } finally {
71965
- plaintext?.fill(0);
71966
- }
72225
+ };
71967
72226
  }
71968
- function validateStoredDerivedAccount(key2, file2, account) {
71969
- const plaintext = decryptField(key2, file2.phrase);
71970
- let seed;
71971
- try {
71972
- seed = phraseToSeed(plaintext.toString("utf8"));
71973
- const address4 = privateKeyToAccount(
71974
- deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${account.index}`)
71975
- ).address;
71976
- if (address4.toLowerCase() !== account.address.toLowerCase()) {
71977
- throw new VaultError("bad_key", "The stored derived account does not match this vault.");
72227
+ async function appendReceipt(receipt, path = getVapiPaths().receipts, options = {}) {
72228
+ const parsed = parseReceipt(
72229
+ receipt.wallet === void 0 && options.wallet !== void 0 ? { ...receipt, wallet: options.wallet } : receipt
72230
+ );
72231
+ await withReceiptJournalLock(path, async () => {
72232
+ await mkdir8(dirname6(path), { recursive: true, mode: 448 });
72233
+ const handle = await open7(path, "a", 384);
72234
+ try {
72235
+ await handle.writeFile(`${JSON.stringify(parsed)}
72236
+ `, "utf8");
72237
+ } finally {
72238
+ await handle.close();
71978
72239
  }
71979
- } finally {
71980
- seed?.fill(0);
71981
- plaintext.fill(0);
71982
- }
72240
+ });
72241
+ return parsed;
71983
72242
  }
71984
- function parseVaultFile(raw) {
71985
- let value;
72243
+ async function readReceipts(path = getVapiPaths().receipts, options = {}) {
72244
+ let raw;
71986
72245
  try {
71987
- value = JSON.parse(raw);
72246
+ raw = await readFile9(path, "utf8");
71988
72247
  } catch (error61) {
71989
- throw new VaultError("corrupt", "The vault file is not valid JSON.", { cause: error61 });
71990
- }
71991
- const parsed = vaultFileSchema.safeParse(value);
71992
- if (!parsed.success) {
71993
- throw new VaultError("corrupt", "The vault file has an invalid structure.", {
71994
- cause: parsed.error
71995
- });
71996
- }
71997
- if (parsed.data.protected !== (parsed.data.wrappedKey !== void 0)) {
71998
- throw new VaultError("corrupt", "The vault protection metadata is inconsistent.");
72248
+ if (isMissingFile(error61)) return [];
72249
+ throw error61;
71999
72250
  }
72000
- const names = /* @__PURE__ */ new Set();
72001
- const indexes = /* @__PURE__ */ new Set();
72002
- for (const account of parsed.data.accounts) {
72003
- if (names.has(account.name)) {
72004
- throw new VaultError("corrupt", "The vault file contains duplicate account names.");
72005
- }
72006
- names.add(account.name);
72007
- if (account.kind === "derived") {
72008
- if (indexes.has(account.index)) {
72009
- throw new VaultError("corrupt", "The vault file contains duplicate derived indexes.");
72251
+ const records = coalesceTransferReceiptRevisions(
72252
+ raw.split("\n").filter((line) => line.trim().length > 0).map((line, index2) => {
72253
+ try {
72254
+ return parseReceipt(JSON.parse(line));
72255
+ } catch (error61) {
72256
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
72010
72257
  }
72011
- indexes.add(account.index);
72258
+ })
72259
+ );
72260
+ const filtered = options.wallet === void 0 ? records : filterReceiptsByWallet(records, options.wallet);
72261
+ const limit = options.limit;
72262
+ if (limit === void 0) return filtered;
72263
+ if (!Number.isSafeInteger(limit) || limit < 0)
72264
+ throw new Error("Receipt limit must be a non-negative integer.");
72265
+ return limit === 0 ? [] : filtered.slice(-limit);
72266
+ }
72267
+ function coalesceTransferReceiptRevisions(receipts) {
72268
+ const coalesced = [];
72269
+ const transferIndexes = /* @__PURE__ */ new Map();
72270
+ for (const receipt of receipts) {
72271
+ const existing = receipt.kind === "transfer" ? transferIndexes.get(receipt.id) : void 0;
72272
+ if (existing === void 0) {
72273
+ if (receipt.kind === "transfer") transferIndexes.set(receipt.id, coalesced.length);
72274
+ coalesced.push(receipt);
72275
+ } else {
72276
+ coalesced[existing] = receipt;
72012
72277
  }
72013
72278
  }
72014
- return parsed.data;
72279
+ return coalesced;
72015
72280
  }
72016
- async function readVaultFile(path, key2) {
72017
- const file2 = await readVaultFileUnlocked(path);
72018
- const plaintext = decryptPhraseForOpen(key2, file2.phrase);
72019
- try {
72281
+ function receiptWallet(receipt) {
72282
+ return receipt.wallet ?? DEFAULT_WALLET_NAME;
72283
+ }
72284
+ function filterReceiptsByWallet(receipts, name) {
72285
+ return receipts.filter((receipt) => receiptWallet(receipt) === name);
72286
+ }
72287
+ async function renameReceiptWallet(from16, to, path = getVapiPaths().receipts) {
72288
+ return await withReceiptJournalLock(path, async () => {
72289
+ let raw;
72020
72290
  try {
72021
- validateRecoveryPhrase(plaintext.toString("utf8"));
72291
+ raw = await readFile9(path, "utf8");
72022
72292
  } catch (error61) {
72023
- throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
72024
- cause: error61
72025
- });
72026
- }
72027
- } finally {
72028
- plaintext.fill(0);
72029
- }
72030
- return file2;
72031
- }
72032
- async function readVaultFileUnlocked(path) {
72033
- let raw;
72034
- try {
72035
- raw = await readFile9(path, "utf8");
72036
- } catch (error61) {
72037
- if (isMissingFile2(error61)) {
72038
- throw new VaultError("not_found", "No vault file was found at the requested path.", {
72039
- cause: error61
72040
- });
72293
+ if (isMissingFile(error61)) return 0;
72294
+ throw error61;
72041
72295
  }
72042
- throw new VaultError("corrupt", "Unable to read the vault file.", { cause: error61 });
72043
- }
72044
- return parseVaultFile(raw);
72045
- }
72046
- async function refuseExistingVault(path) {
72047
- try {
72048
- await stat6(path);
72049
- } catch (error61) {
72050
- if (isMissingFile2(error61)) return;
72051
- throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
72052
- cause: error61
72296
+ let changed = 0;
72297
+ const lines = raw.split("\n").map((line, index2) => {
72298
+ if (line.trim().length === 0) return line;
72299
+ let parsed;
72300
+ try {
72301
+ parsed = JSON.parse(line);
72302
+ } catch (error61) {
72303
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
72304
+ }
72305
+ const current = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "wallet") : void 0;
72306
+ if ((typeof current === "string" ? current : DEFAULT_WALLET_NAME) !== from16) return line;
72307
+ changed += 1;
72308
+ return JSON.stringify(parseReceipt({ ...parsed, wallet: to }));
72053
72309
  });
72054
- }
72055
- throw new VaultError("corrupt", "A vault already exists at the requested path.");
72056
- }
72057
- async function writeVaultFile(path, file2) {
72058
- await mkdir8(dirname6(path), { recursive: true, mode: 448 });
72059
- const temporaryPath = `${path}.${process.pid}.${randomBytes7(6).toString("hex")}.tmp`;
72060
- try {
72061
- await writeFile4(temporaryPath, `${JSON.stringify(file2, null, 2)}
72062
- `, {
72310
+ if (changed === 0) return 0;
72311
+ await receiptTestHooks?.beforeRenameReplace?.(path);
72312
+ await mkdir8(dirname6(path), { recursive: true, mode: 448 });
72313
+ const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
72314
+ await writeFile4(temporaryPath, lines.join("\n"), {
72063
72315
  encoding: "utf8",
72064
72316
  mode: 384,
72065
72317
  flag: "wx"
72066
72318
  });
72067
72319
  await rename5(temporaryPath, path);
72320
+ return changed;
72321
+ });
72322
+ }
72323
+
72324
+ // ../core/src/transfer-journal.ts
72325
+ import { readFile as readFile10 } from "node:fs/promises";
72326
+ async function readTransferJournal(home, from16, nonce) {
72327
+ let raw;
72328
+ try {
72329
+ raw = await readFile10(getVapiPaths(home).receipts, "utf8");
72068
72330
  } catch (error61) {
72069
- await rm(temporaryPath, { force: true }).catch(() => void 0);
72331
+ if (isMissingFile(error61)) return { signed: false };
72070
72332
  throw error61;
72071
72333
  }
72072
- }
72073
- async function withVaultLock(path, operation) {
72074
- await mkdir8(dirname6(path), { recursive: true, mode: 448 });
72075
- const lockPath = `${path}.lock`;
72076
- const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
72077
- let handle;
72078
- while (!handle) {
72334
+ let latest;
72335
+ let request;
72336
+ for (const [index2, line] of raw.split("\n").entries()) {
72337
+ if (!line.trim()) continue;
72338
+ let receipt;
72079
72339
  try {
72080
- handle = await open6(lockPath, "wx", 384);
72340
+ receipt = parseReceipt(JSON.parse(line));
72081
72341
  } catch (error61) {
72082
- if (!isExistingFile(error61)) throw error61;
72083
- await removeStaleVaultLock(lockPath);
72084
- if (Date.now() >= deadline) {
72085
- throw new VaultError("corrupt", "Timed out waiting for the vault lock.");
72086
- }
72087
- await new Promise((resolve4) => setTimeout(resolve4, 20));
72342
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
72088
72343
  }
72344
+ if (receiptWallet(receipt) !== from16 || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
72345
+ continue;
72346
+ }
72347
+ latest = receipt;
72348
+ if (receipt.transfer.request !== void 0) request = receipt;
72089
72349
  }
72090
- try {
72091
- return await operation();
72092
- } finally {
72093
- await handle.close();
72094
- await unlink4(lockPath).catch(() => void 0);
72095
- }
72096
- }
72097
- async function removeStaleVaultLock(path) {
72098
- try {
72099
- const metadata = await stat6(path);
72100
- if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
72101
- } catch (error61) {
72102
- if (!isMissingFile2(error61)) throw error61;
72103
- }
72104
- }
72105
- function isMissingFile2(error61) {
72106
- return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
72107
- }
72108
- function isExistingFile(error61) {
72109
- return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "EEXIST";
72110
- }
72111
- function asVaultError(error61, code, message) {
72112
- return error61 instanceof VaultError ? error61 : new VaultError(code, message, { cause: error61 });
72350
+ return {
72351
+ signed: latest !== void 0,
72352
+ ...latest === void 0 ? {} : { latest },
72353
+ ...request === void 0 ? {} : { request },
72354
+ ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
72355
+ ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
72356
+ };
72113
72357
  }
72114
72358
 
72115
72359
  // ../core/src/vault-key.ts
72360
+ import { randomBytes as cryptoRandomBytes } from "node:crypto";
72116
72361
  var VAULT_KEY_ACCOUNT = "vault-key";
72117
72362
  var VAULT_SESSION_ACCOUNT = "vault-session";
72118
72363
  var DEVICE_KEY_LENGTH = 32;
@@ -72340,8 +72585,8 @@ function passwordRequiredError() {
72340
72585
  "A vault password is needed. Pass it or set VAPI_VAULT_PASSWORD."
72341
72586
  );
72342
72587
  }
72343
- function randomKeyBytes(randomBytes17) {
72344
- const key2 = Buffer.from((randomBytes17 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
72588
+ function randomKeyBytes(randomBytes18) {
72589
+ const key2 = Buffer.from((randomBytes18 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
72345
72590
  if (key2.byteLength !== DEVICE_KEY_LENGTH) {
72346
72591
  key2.fill(0);
72347
72592
  throw new VaultError("corrupt", "A generated device vault key has the wrong length.");
@@ -72392,7 +72637,7 @@ function parseJson(value) {
72392
72637
  function asVaultError2(error61, message) {
72393
72638
  return error61 instanceof VaultError ? error61 : new VaultError("corrupt", message, { cause: error61 });
72394
72639
  }
72395
- 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.";
72640
+ 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.";
72396
72641
  function deviceKeyFailureMessage(error61, platform2) {
72397
72642
  if (!(error61 instanceof KeystoreError)) return "Unable to load or create the device vault key.";
72398
72643
  const detail = `Unable to load or create the device vault key: ${error61.message.replace(/\.$/u, "")}.`;
@@ -72404,19 +72649,19 @@ import {
72404
72649
  chmod as chmod2,
72405
72650
  lstat,
72406
72651
  mkdir as mkdir9,
72407
- readFile as readFile10,
72652
+ readFile as readFile11,
72408
72653
  readlink,
72409
72654
  readdir as readdir2,
72410
72655
  rename as rename6,
72411
72656
  symlink,
72412
72657
  unlink as unlink5
72413
72658
  } from "node:fs/promises";
72414
- import { join as join7, resolve } from "node:path";
72659
+ import { join as join8, resolve } from "node:path";
72415
72660
  var MIGRATED_DIRECTORY = "wallets.migrated";
72416
72661
  async function legacyKeystoreNames(home) {
72417
72662
  let entries;
72418
72663
  try {
72419
- entries = await readdir2(join7(home, "wallets"), { withFileTypes: true });
72664
+ entries = await readdir2(join8(home, "wallets"), { withFileTypes: true });
72420
72665
  } catch (error61) {
72421
72666
  if (isMissingFile(error61)) return [];
72422
72667
  throw error61;
@@ -72432,14 +72677,14 @@ async function migrateKeystores(args) {
72432
72677
  );
72433
72678
  const result = { imported: [], skipped: [] };
72434
72679
  for (const name of names) {
72435
- const source = join7(args.home, "wallets", `${name}.json`);
72680
+ const source = join8(args.home, "wallets", `${name}.json`);
72436
72681
  if (args.vault.accounts().some((account) => account.name === name)) {
72437
72682
  result.skipped.push({ name, reason: "name_taken" });
72438
72683
  continue;
72439
72684
  }
72440
72685
  let parsed;
72441
72686
  try {
72442
- parsed = parseAnyKeystore(JSON.parse(await readFile10(source, "utf8")));
72687
+ parsed = parseAnyKeystore(JSON.parse(await readFile11(source, "utf8")));
72443
72688
  } catch {
72444
72689
  result.skipped.push({ name, reason: "unreadable" });
72445
72690
  continue;
@@ -72469,15 +72714,15 @@ async function migrateKeystores(args) {
72469
72714
  if (imported.address.toLowerCase() !== parsed.address.toLowerCase()) {
72470
72715
  throw new KeystoreError(`Migrated wallet ${name} does not match its stored address.`);
72471
72716
  }
72472
- const migratedDirectory = join7(args.home, MIGRATED_DIRECTORY);
72473
- const destination = join7(migratedDirectory, `${name}.json`);
72717
+ const migratedDirectory = join8(args.home, MIGRATED_DIRECTORY);
72718
+ const destination = join8(migratedDirectory, `${name}.json`);
72474
72719
  await mkdir9(migratedDirectory, { recursive: true, mode: 448 });
72475
72720
  await archiveExistingDestination(destination, migratedDirectory, name, now);
72476
72721
  await rename6(source, destination);
72477
72722
  await chmod2(destination, 384);
72478
72723
  try {
72479
72724
  await removeCompatibilityLink(args.home, source);
72480
- await symlink(join7("..", MIGRATED_DIRECTORY, `${name}.json`), source);
72725
+ await symlink(join8("..", MIGRATED_DIRECTORY, `${name}.json`), source);
72481
72726
  await audit({
72482
72727
  event: "vault.migrate",
72483
72728
  wallet: name,
@@ -72505,16 +72750,16 @@ async function migrateKeystores(args) {
72505
72750
  async function archiveExistingDestination(destination, directory, name, now) {
72506
72751
  if (!await pathExists2(destination)) return;
72507
72752
  const timestamp = now().toISOString();
72508
- let archive = join7(directory, `${name}.${timestamp}.json`);
72753
+ let archive = join8(directory, `${name}.${timestamp}.json`);
72509
72754
  let suffix = 1;
72510
72755
  while (await pathExists2(archive)) {
72511
- archive = join7(directory, `${name}.${timestamp}.${suffix}.json`);
72756
+ archive = join8(directory, `${name}.${timestamp}.${suffix}.json`);
72512
72757
  suffix += 1;
72513
72758
  }
72514
72759
  await rename6(destination, archive);
72515
72760
  }
72516
72761
  async function removeCompatibilityLink(home, migratedSource) {
72517
- const compatibilityPath = join7(home, "keystore.json");
72762
+ const compatibilityPath = join8(home, "keystore.json");
72518
72763
  let metadata;
72519
72764
  try {
72520
72765
  metadata = await lstat(compatibilityPath);
@@ -72588,7 +72833,7 @@ var WalletStore = class _WalletStore {
72588
72833
  this.home = home;
72589
72834
  this.options = options;
72590
72835
  this.registry = registry2;
72591
- this.secrets = options.secrets ?? secretStore();
72836
+ this.secrets = options.secrets ?? secretStore({ home });
72592
72837
  this.environment = options.env ?? process.env;
72593
72838
  this.passphraseResolver = options.resolvePassphrase ?? defaultPassphraseResolver(this.environment, this.secrets);
72594
72839
  this.audit = options.audit ?? (async (record2) => await appendAudit(this.home, record2, { now: () => this.now() }));
@@ -72635,17 +72880,17 @@ var WalletStore = class _WalletStore {
72635
72880
  return store;
72636
72881
  }
72637
72882
  get registryPath() {
72638
- return join8(this.home, REGISTRY_FILE);
72883
+ return join9(this.home, REGISTRY_FILE);
72639
72884
  }
72640
72885
  get walletsDirectory() {
72641
- return join8(this.home, WALLETS_DIRECTORY);
72886
+ return join9(this.home, WALLETS_DIRECTORY);
72642
72887
  }
72643
72888
  get trashDirectory() {
72644
- return join8(this.walletsDirectory, TRASH_DIRECTORY);
72889
+ return join9(this.walletsDirectory, TRASH_DIRECTORY);
72645
72890
  }
72646
72891
  /** The legacy 0.5 keystore path of a wallet, whether or not it exists. */
72647
72892
  pathFor(name) {
72648
- return join8(this.walletsDirectory, `${assertWalletName(name)}.json`);
72893
+ return join9(this.walletsDirectory, `${assertWalletName(name)}.json`);
72649
72894
  }
72650
72895
  /** The names this machine knows, in registry order. */
72651
72896
  names() {
@@ -73218,7 +73463,7 @@ var WalletStore = class _WalletStore {
73218
73463
  }
73219
73464
  const removedAt = this.now().toISOString();
73220
73465
  await mkdir10(this.trashDirectory, { recursive: true, mode: 448 });
73221
- const trashedPath = join8(this.trashDirectory, `${wallet.name}-${removedAt}.json`);
73466
+ const trashedPath = join9(this.trashDirectory, `${wallet.name}-${removedAt}.json`);
73222
73467
  const storedAccount = (await this.readVaultUnlocked())?.accounts.find(
73223
73468
  (candidate) => candidate.name === wallet.name
73224
73469
  );
@@ -73240,7 +73485,7 @@ var WalletStore = class _WalletStore {
73240
73485
  this.balanceProbe = void 0;
73241
73486
  }
73242
73487
  if (await pathExists3(wallet.path)) {
73243
- const legacyTrashedPath = join8(
73488
+ const legacyTrashedPath = join9(
73244
73489
  this.trashDirectory,
73245
73490
  `${wallet.name}-${removedAt}.legacy.json`
73246
73491
  );
@@ -73330,7 +73575,7 @@ var WalletStore = class _WalletStore {
73330
73575
  if (!match) continue;
73331
73576
  const [, name, removedAt] = match;
73332
73577
  if (name === void 0 || removedAt === void 0 || !isWalletName(name)) continue;
73333
- const path = join8(this.trashDirectory, file2);
73578
+ const path = join9(this.trashDirectory, file2);
73334
73579
  const entry = await readEntrySidecar(entrySidecarPath(path));
73335
73580
  trashed.push({ name, removedAt, path, ...entry ? { entry } : {} });
73336
73581
  }
@@ -73399,7 +73644,7 @@ var WalletStore = class _WalletStore {
73399
73644
  return entry;
73400
73645
  }
73401
73646
  get vaultPath() {
73402
- return join8(this.home, VAULT_FILE);
73647
+ return join9(this.home, VAULT_FILE);
73403
73648
  }
73404
73649
  async readVaultUnlocked() {
73405
73650
  try {
@@ -73504,7 +73749,7 @@ var WalletStore = class _WalletStore {
73504
73749
  async readRegistry() {
73505
73750
  let raw;
73506
73751
  try {
73507
- raw = await readFile11(this.registryPath, "utf8");
73752
+ raw = await readFile12(this.registryPath, "utf8");
73508
73753
  } catch (error61) {
73509
73754
  if (isMissingFile(error61)) return emptyRegistry();
73510
73755
  throw error61;
@@ -73525,7 +73770,7 @@ var WalletStore = class _WalletStore {
73525
73770
  }
73526
73771
  };
73527
73772
  async function swarmReferencingAccount(home, account) {
73528
- const directory = join8(home, "swarms");
73773
+ const directory = join9(home, "swarms");
73529
73774
  let files;
73530
73775
  try {
73531
73776
  files = await readdir3(directory);
@@ -73536,7 +73781,7 @@ async function swarmReferencingAccount(home, account) {
73536
73781
  for (const file2 of files.filter((name) => name.endsWith(".json")).sort()) {
73537
73782
  let value;
73538
73783
  try {
73539
- value = JSON.parse(await readFile11(join8(directory, file2), "utf8"));
73784
+ value = JSON.parse(await readFile12(join9(directory, file2), "utf8"));
73540
73785
  } catch {
73541
73786
  throw new KeystoreError(
73542
73787
  `Cannot verify swarm references because ${file2} is invalid. Repair or remove that swarm file before renaming an account.`
@@ -73568,7 +73813,7 @@ async function swarmReferencingAccount(home, account) {
73568
73813
  return void 0;
73569
73814
  }
73570
73815
  async function unfinishedMovementReferencingAccount(home, account) {
73571
- const directory = join8(home, "movements");
73816
+ const directory = join9(home, "movements");
73572
73817
  let files;
73573
73818
  try {
73574
73819
  files = await readdir3(directory);
@@ -73579,7 +73824,7 @@ async function unfinishedMovementReferencingAccount(home, account) {
73579
73824
  for (const file2 of files.filter((name) => name.endsWith(".json")).sort()) {
73580
73825
  let value;
73581
73826
  try {
73582
- value = JSON.parse(await readFile11(join8(directory, file2), "utf8"));
73827
+ value = JSON.parse(await readFile12(join9(directory, file2), "utf8"));
73583
73828
  } catch {
73584
73829
  throw invalidMovementReferenceError(file2);
73585
73830
  }
@@ -73600,11 +73845,11 @@ async function unfinishedMovementReferencingAccount(home, account) {
73600
73845
  const restored = Reflect.get(leg, "restored");
73601
73846
  const legFrom = Reflect.get(leg, "from") ?? movementFrom;
73602
73847
  const journal = restored !== true && status === "failed" && retryable !== true && typeof nonce === "string" ? await readTransferJournal(home, legFrom, nonce) : void 0;
73603
- const open12 = isOpenMovementLeg(
73848
+ const open13 = isOpenMovementLeg(
73604
73849
  { status, retryable, nonce, restored },
73605
73850
  journal?.signed === true ? "signed" : "unsigned"
73606
73851
  );
73607
- if (open12) movementOpen = true;
73852
+ if (open13) movementOpen = true;
73608
73853
  }
73609
73854
  if (movementOpen && (movementFrom === account || legs.some(
73610
73855
  (leg) => (Reflect.get(leg, "from") ?? movementFrom) === account || Reflect.get(leg, "to") === account
@@ -73640,7 +73885,7 @@ async function withAccountMutationLocks(home, accounts, command, operation) {
73640
73885
  const [account, ...remaining2] = [...new Set(accounts)].sort();
73641
73886
  if (account === void 0) return await operation();
73642
73887
  return await withFileLock(
73643
- join8(home, `.account-${account}.lock`),
73888
+ join9(home, `.account-${account}.lock`),
73644
73889
  async () => await withAccountMutationLocks(home, remaining2, command, operation),
73645
73890
  {
73646
73891
  lockedMessage: `Account ${account} is busy with another account change. Wait for it to finish, then retry ${command}.`
@@ -73715,7 +73960,7 @@ function isLockedVaultError(error61) {
73715
73960
  async function readTrashedVaultAccount(path) {
73716
73961
  let parsed;
73717
73962
  try {
73718
- parsed = JSON.parse(await readFile11(path, "utf8"));
73963
+ parsed = JSON.parse(await readFile12(path, "utf8"));
73719
73964
  } catch {
73720
73965
  return void 0;
73721
73966
  }
@@ -73724,7 +73969,7 @@ async function readTrashedVaultAccount(path) {
73724
73969
  }
73725
73970
  async function readEntrySidecar(path) {
73726
73971
  try {
73727
- const parsed = walletEntrySchema.safeParse(JSON.parse(await readFile11(path, "utf8")));
73972
+ const parsed = walletEntrySchema.safeParse(JSON.parse(await readFile12(path, "utf8")));
73728
73973
  return parsed.success ? parsed.data : void 0;
73729
73974
  } catch {
73730
73975
  return void 0;
@@ -73733,7 +73978,7 @@ async function readEntrySidecar(path) {
73733
73978
  async function readKeystoreSummary(path) {
73734
73979
  let parsed;
73735
73980
  try {
73736
- parsed = JSON.parse(await readFile11(path, "utf8"));
73981
+ parsed = JSON.parse(await readFile12(path, "utf8"));
73737
73982
  } catch {
73738
73983
  return {};
73739
73984
  }
@@ -73751,7 +73996,7 @@ async function readKeystoreSummary(path) {
73751
73996
  }
73752
73997
  async function readConfiguredSpendCaps(configPath) {
73753
73998
  try {
73754
- const parsed = JSON.parse(await readFile11(configPath, "utf8"));
73999
+ const parsed = JSON.parse(await readFile12(configPath, "utf8"));
73755
74000
  const caps = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "spendCaps") : void 0;
73756
74001
  const result = spendCapsSchema.safeParse(caps);
73757
74002
  if (result.success) return result.data;
@@ -73843,7 +74088,7 @@ async function withRegistryLock(path, operation) {
73843
74088
  let handle;
73844
74089
  while (!handle) {
73845
74090
  try {
73846
- handle = await open7(lockPath, "wx", 384);
74091
+ handle = await open8(lockPath, "wx", 384);
73847
74092
  } catch (error61) {
73848
74093
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
73849
74094
  await removeStaleRegistryLock(lockPath);
@@ -73862,7 +74107,7 @@ async function withRegistryLock(path, operation) {
73862
74107
  }
73863
74108
  async function removeStaleRegistryLock(path) {
73864
74109
  try {
73865
- const metadata = await stat7(path);
74110
+ const metadata = await stat9(path);
73866
74111
  if (Date.now() - metadata.mtimeMs > 3e4) await unlink6(path);
73867
74112
  } catch (error61) {
73868
74113
  if (!isMissingFile(error61)) throw error61;
@@ -73870,7 +74115,7 @@ async function removeStaleRegistryLock(path) {
73870
74115
  }
73871
74116
  async function writeJsonFile(path, value) {
73872
74117
  await mkdir10(dirname7(path), { recursive: true, mode: 448 });
73873
- const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
74118
+ const temporaryPath = `${path}.${process.pid}.${randomBytes9(6).toString("hex")}.tmp`;
73874
74119
  await writeFile5(temporaryPath, `${JSON.stringify(value, null, 2)}
73875
74120
  `, {
73876
74121
  encoding: "utf8",
@@ -73908,7 +74153,7 @@ async function createAccount(args) {
73908
74153
  created: false
73909
74154
  };
73910
74155
  }
73911
- if (!await fileExists(join9(args.store.home, "vault.json"))) {
74156
+ if (!await fileExists2(join10(args.store.home, "vault.json"))) {
73912
74157
  throw new KeystoreError("No vault yet. Run vapi setup.");
73913
74158
  }
73914
74159
  const spendCaps = resolveNewAccountCaps(args.caps);
@@ -74175,9 +74420,9 @@ async function requireAddress(store, name) {
74175
74420
  if (address4 === void 0) throw new KeystoreError(`No key for wallet ${name} in the vault.`);
74176
74421
  return address4;
74177
74422
  }
74178
- async function fileExists(path) {
74423
+ async function fileExists2(path) {
74179
74424
  try {
74180
- await stat8(path);
74425
+ await stat10(path);
74181
74426
  return true;
74182
74427
  } catch (error61) {
74183
74428
  if (isMissingFile(error61)) return false;
@@ -74239,9 +74484,9 @@ function secretsAllowed(env, streams) {
74239
74484
  }
74240
74485
 
74241
74486
  // ../core/src/agent-profile.ts
74242
- import { randomBytes as randomBytes9 } from "node:crypto";
74243
- import { mkdir as mkdir11, readFile as readFile12, readdir as readdir4, rename as rename8, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
74244
- import { join as join10 } from "node:path";
74487
+ import { randomBytes as randomBytes10 } from "node:crypto";
74488
+ import { mkdir as mkdir11, readFile as readFile13, readdir as readdir4, rename as rename8, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
74489
+ import { join as join11 } from "node:path";
74245
74490
  var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
74246
74491
  var AGENT_GRANTS = ["read", "delegate", "allocate"];
74247
74492
  var agentProfileShape = {
@@ -74271,7 +74516,7 @@ async function readAgentProfile(home, name, options = {}) {
74271
74516
  const path = agentProfilePath(home, name);
74272
74517
  let raw;
74273
74518
  try {
74274
- raw = await readFile12(path, "utf8");
74519
+ raw = await readFile13(path, "utf8");
74275
74520
  } catch (error61) {
74276
74521
  if (isMissingFile(error61)) {
74277
74522
  throw new Error(`No agent named ${name}. Create it with vapi agent create ${name}.`);
@@ -74283,9 +74528,9 @@ async function readAgentProfile(home, name, options = {}) {
74283
74528
  async function writeAgentProfile(home, profile, options = {}) {
74284
74529
  const parsed = (options.schema ?? agentProfileSchema).parse(profile);
74285
74530
  const directory = getVapiPaths(home).agentsDir;
74286
- const path = join10(directory, `${parsed.name}.json`);
74531
+ const path = join11(directory, `${parsed.name}.json`);
74287
74532
  await mkdir11(directory, { recursive: true, mode: 448 });
74288
- const temporaryPath = `${path}.${process.pid}.${randomBytes9(6).toString("hex")}.tmp`;
74533
+ const temporaryPath = `${path}.${process.pid}.${randomBytes10(6).toString("hex")}.tmp`;
74289
74534
  await writeFile6(temporaryPath, `${JSON.stringify(parsed, null, 2)}
74290
74535
  `, {
74291
74536
  encoding: "utf8",
@@ -74310,7 +74555,7 @@ async function listAgentProfiles(home, options = {}) {
74310
74555
  try {
74311
74556
  profiles.push(
74312
74557
  (options.schema ?? agentProfileSchema).parse(
74313
- JSON.parse(await readFile12(join10(directory, file2), "utf8"))
74558
+ JSON.parse(await readFile13(join11(directory, file2), "utf8"))
74314
74559
  )
74315
74560
  );
74316
74561
  } catch {
@@ -74331,11 +74576,11 @@ async function removeAgentProfile(home, name) {
74331
74576
  }
74332
74577
  function agentProfilePath(home, name) {
74333
74578
  const parsedName = walletNameSchema.parse(name);
74334
- return join10(getVapiPaths(home).agentsDir, `${parsedName}.json`);
74579
+ return join11(getVapiPaths(home).agentsDir, `${parsedName}.json`);
74335
74580
  }
74336
74581
 
74337
74582
  // ../core/src/ceiling.ts
74338
- import { randomBytes as randomBytes13 } from "node:crypto";
74583
+ import { randomBytes as randomBytes14 } from "node:crypto";
74339
74584
 
74340
74585
  // ../core/src/authorization-state.ts
74341
74586
  var EIP3009_AUTHORIZATION_STATE_ABI = [
@@ -74400,13 +74645,13 @@ function missingAuthorization(receipt) {
74400
74645
  }
74401
74646
 
74402
74647
  // ../core/src/movement.ts
74403
- import { randomBytes as randomBytes12 } from "node:crypto";
74404
- 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";
74405
- import { join as join11 } from "node:path";
74648
+ import { randomBytes as randomBytes13 } from "node:crypto";
74649
+ 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";
74650
+ import { join as join12 } from "node:path";
74406
74651
 
74407
74652
  // ../core/src/spend-policy.ts
74408
- import { randomBytes as randomBytes10 } from "node:crypto";
74409
- 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";
74653
+ import { randomBytes as randomBytes11 } from "node:crypto";
74654
+ 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";
74410
74655
  import { dirname as dirname8 } from "node:path";
74411
74656
  var ledgerSchema = external_exports.object({
74412
74657
  date: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
@@ -74477,7 +74722,7 @@ async function readSpendLedgerRows(path = getAgentCashPaths().ledger, now = /* @
74477
74722
  async function readStoredSpendLedgerRows(path, now, allDays = false) {
74478
74723
  let raw;
74479
74724
  try {
74480
- raw = await readFile13(path, "utf8");
74725
+ raw = await readFile14(path, "utf8");
74481
74726
  } catch (error61) {
74482
74727
  if (isMissingFile(error61)) return [];
74483
74728
  throw error61;
@@ -74610,7 +74855,7 @@ async function reserveSpend(amountAtomic2, caps, options) {
74610
74855
  { amountAtomic: amountAtomic2, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
74611
74856
  );
74612
74857
  }
74613
- const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes10(16).toString("hex"));
74858
+ const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes11(16).toString("hex"));
74614
74859
  const nextRow = {
74615
74860
  date: utcDateKey(now),
74616
74861
  spentAtomic: nextSpent.toString(),
@@ -74716,7 +74961,7 @@ async function writeLedgerAtomically(path, rows) {
74716
74961
  ...rows[0].reservations === void 0 ? {} : { reservations: rows[0].reservations }
74717
74962
  } : { version: 1, rows };
74718
74963
  await mkdir12(dirname8(path), { recursive: true, mode: 448 });
74719
- const temporaryPath = `${path}.${process.pid}.${randomBytes10(6).toString("hex")}.tmp`;
74964
+ const temporaryPath = `${path}.${process.pid}.${randomBytes11(6).toString("hex")}.tmp`;
74720
74965
  await writeFile7(temporaryPath, `${JSON.stringify(ledger, null, 2)}
74721
74966
  `, {
74722
74967
  encoding: "utf8",
@@ -74732,7 +74977,7 @@ async function withLedgerLock(path, operation) {
74732
74977
  let handle;
74733
74978
  while (!handle) {
74734
74979
  try {
74735
- handle = await open8(lockPath, "wx", 384);
74980
+ handle = await open9(lockPath, "wx", 384);
74736
74981
  } catch (error61) {
74737
74982
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) {
74738
74983
  throw error61;
@@ -74753,7 +74998,7 @@ async function withLedgerLock(path, operation) {
74753
74998
  }
74754
74999
  async function removeStaleLock3(path) {
74755
75000
  try {
74756
- const metadata = await stat9(path);
75001
+ const metadata = await stat11(path);
74757
75002
  if (Date.now() - metadata.mtimeMs > 3e4) {
74758
75003
  await unlink8(path);
74759
75004
  }
@@ -74765,8 +75010,8 @@ async function removeStaleLock3(path) {
74765
75010
  }
74766
75011
 
74767
75012
  // ../core/src/transfer.ts
74768
- import { randomBytes as randomBytes11, randomUUID } from "node:crypto";
74769
- import { mkdir as mkdir13, open as open9, stat as stat10, unlink as unlink9 } from "node:fs/promises";
75013
+ import { randomBytes as randomBytes12, randomUUID } from "node:crypto";
75014
+ import { mkdir as mkdir13, open as open10, stat as stat12, unlink as unlink9 } from "node:fs/promises";
74770
75015
  import { dirname as dirname9 } from "node:path";
74771
75016
 
74772
75017
  // ../core/src/siblings.ts
@@ -74975,7 +75220,7 @@ async function transferBetweenAccounts(args) {
74975
75220
  if (args.resume !== void 0) {
74976
75221
  return await resumeTransfer(context, args.resume);
74977
75222
  }
74978
- const nonce = args.nonce ?? bytesToHex(randomBytes11(32));
75223
+ const nonce = args.nonce ?? bytesToHex(randomBytes12(32));
74979
75224
  if (!NONCE_PATTERN.test(nonce)) {
74980
75225
  throw new TransferError(
74981
75226
  "authorization_invalid",
@@ -75368,7 +75613,7 @@ async function withTransferLock(context, nonce, operation) {
75368
75613
  let handle;
75369
75614
  while (!handle) {
75370
75615
  try {
75371
- handle = await open9(lockPath, "wx", 384);
75616
+ handle = await open10(lockPath, "wx", 384);
75372
75617
  } catch (error61) {
75373
75618
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
75374
75619
  await removeStaleTransferLock(lockPath, staleAfterMs);
@@ -75387,7 +75632,7 @@ async function withTransferLock(context, nonce, operation) {
75387
75632
  }
75388
75633
  async function removeStaleTransferLock(path, staleAfterMs) {
75389
75634
  try {
75390
- const metadata = await stat10(path);
75635
+ const metadata = await stat12(path);
75391
75636
  if (Date.now() - metadata.mtimeMs > staleAfterMs) await unlink9(path);
75392
75637
  } catch (error61) {
75393
75638
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "ENOENT")) throw error61;
@@ -75813,7 +76058,7 @@ async function listUnfinishedMovements(options) {
75813
76058
  }
75814
76059
  const summaries = [];
75815
76060
  for (const name of names.filter((candidate) => candidate.endsWith(".json")).sort()) {
75816
- const movement = parseMovement(JSON.parse(await readFile14(join11(directory, name), "utf8")));
76061
+ const movement = parseMovement(JSON.parse(await readFile15(join12(directory, name), "utf8")));
75817
76062
  if (options.from !== void 0 && !movement.legs.some((leg) => leg.from === options.from)) {
75818
76063
  continue;
75819
76064
  }
@@ -75844,7 +76089,7 @@ async function listUnfinishedMovementSnapshots(options) {
75844
76089
  }
75845
76090
  const snapshots = [];
75846
76091
  for (const name of names.filter((candidate) => candidate.endsWith(".json")).sort()) {
75847
- const movement = parseMovement(JSON.parse(await readFile14(join11(directory, name), "utf8")));
76092
+ const movement = parseMovement(JSON.parse(await readFile15(join12(directory, name), "utf8")));
75848
76093
  if (options.from !== void 0 && !movement.legs.some((leg) => leg.from === options.from)) {
75849
76094
  continue;
75850
76095
  }
@@ -75880,23 +76125,23 @@ async function movementHasOpenLeg(home, movement, from16) {
75880
76125
  return false;
75881
76126
  }
75882
76127
  async function movementOpenEvidence(home, movement, from16) {
75883
- let open12 = false;
76128
+ let open13 = false;
75884
76129
  const signedFailedLegKeys = [];
75885
76130
  for (const leg of movement.legs) {
75886
76131
  if (from16 !== void 0 && leg.from !== from16) continue;
75887
- if (isOpenMovementLeg(leg, "unsigned")) open12 = true;
76132
+ if (isOpenMovementLeg(leg, "unsigned")) open13 = true;
75888
76133
  if (leg.status !== "failed") continue;
75889
76134
  const journal = await readTransferJournal(home, leg.from, leg.nonce);
75890
76135
  if (journal.signed) signedFailedLegKeys.push(movementTransferKey(leg.from, leg.nonce));
75891
- if (isOpenMovementLeg(leg, journal.signed ? "signed" : "unsigned")) open12 = true;
76136
+ if (isOpenMovementLeg(leg, journal.signed ? "signed" : "unsigned")) open13 = true;
75892
76137
  }
75893
- return { open: open12, signedFailedLegKeys };
76138
+ return { open: open13, signedFailedLegKeys };
75894
76139
  }
75895
76140
  async function readMovement(home, id2) {
75896
76141
  const safeId = parseMovementId(id2);
75897
76142
  try {
75898
76143
  return parseMovement(
75899
- JSON.parse(await readFile14(join11(movementsDirectory(home), `${safeId}.json`), "utf8"))
76144
+ JSON.parse(await readFile15(join12(movementsDirectory(home), `${safeId}.json`), "utf8"))
75900
76145
  );
75901
76146
  } catch (error61) {
75902
76147
  if (isMissingFile(error61)) {
@@ -76616,33 +76861,33 @@ function parseMovementId(value) {
76616
76861
  return parsed.data;
76617
76862
  }
76618
76863
  function movementsDirectory(home) {
76619
- return join11(home, "movements");
76864
+ return join12(home, "movements");
76620
76865
  }
76621
76866
  function createMovementId() {
76622
- return `mv_${randomBytes12(12).toString("hex")}`;
76867
+ return `mv_${randomBytes13(12).toString("hex")}`;
76623
76868
  }
76624
76869
  function createMovementNonce() {
76625
- return bytesToHex(randomBytes12(32));
76870
+ return bytesToHex(randomBytes13(32));
76626
76871
  }
76627
76872
  async function writeMovement(home, movement) {
76628
76873
  const parsed = movementSchema.parse(movement);
76629
76874
  const directory = movementsDirectory(home);
76630
76875
  await mkdir14(directory, { recursive: true, mode: 448 });
76631
76876
  await chmod4(directory, 448);
76632
- const path = join11(directory, `${parsed.id}.json`);
76633
- const temporary = join11(
76877
+ const path = join12(directory, `${parsed.id}.json`);
76878
+ const temporary = join12(
76634
76879
  directory,
76635
- `.${parsed.id}.${process.pid}.${randomBytes12(6).toString("hex")}.tmp`
76880
+ `.${parsed.id}.${process.pid}.${randomBytes13(6).toString("hex")}.tmp`
76636
76881
  );
76637
76882
  let handle;
76638
76883
  try {
76639
- handle = await open10(temporary, "wx", 384);
76884
+ handle = await open11(temporary, "wx", 384);
76640
76885
  await handle.writeFile(serializeMovement(parsed), "utf8");
76641
76886
  await handle.sync();
76642
76887
  await handle.close();
76643
76888
  handle = void 0;
76644
76889
  await rename10(temporary, path);
76645
- const directoryHandle = await open10(directory, "r");
76890
+ const directoryHandle = await open11(directory, "r");
76646
76891
  try {
76647
76892
  await directoryHandle.sync();
76648
76893
  } finally {
@@ -76862,7 +77107,7 @@ async function sweepAboveCeilingLocked(args) {
76862
77107
  owner,
76863
77108
  target,
76864
77109
  amountAtomic: amountAtomic2.toString(),
76865
- nonce: (args.randomNonce ?? (() => bytesToHex(randomBytes13(32))))(),
77110
+ nonce: (args.randomNonce ?? (() => bytesToHex(randomBytes14(32))))(),
76866
77111
  createdAt: new Date(now()).toISOString(),
76867
77112
  status: "planned"
76868
77113
  };
@@ -77654,8 +77899,8 @@ function parseDecimal(value, scale) {
77654
77899
  }
77655
77900
 
77656
77901
  // ../core/src/swarm.ts
77657
- import { readdir as readdir6, readFile as readFile15, stat as stat11, unlink as unlink11 } from "node:fs/promises";
77658
- import { join as join12 } from "node:path";
77902
+ import { readdir as readdir6, readFile as readFile16, stat as stat13, unlink as unlink11 } from "node:fs/promises";
77903
+ import { join as join13 } from "node:path";
77659
77904
  var SWARM_NAME_PATTERN = /^[a-z][a-z0-9-]{0,15}$/;
77660
77905
  var SWARM_ROLE_PATTERN = /^[a-z][a-z0-9]{0,7}$/;
77661
77906
  var DEFAULT_SWARM_MODEL = "venice/claude-sonnet-5";
@@ -77736,16 +77981,16 @@ var SwarmError = class extends Error {
77736
77981
  code;
77737
77982
  };
77738
77983
  function swarmsDirectory(home) {
77739
- return join12(home, "swarms");
77984
+ return join13(home, "swarms");
77740
77985
  }
77741
77986
  function swarmFilePath(home, name) {
77742
77987
  assertName(name);
77743
- return join12(swarmsDirectory(home), `${name}.json`);
77988
+ return join13(swarmsDirectory(home), `${name}.json`);
77744
77989
  }
77745
77990
  async function readSwarm(home, name) {
77746
77991
  const path = swarmFilePath(home, name);
77747
77992
  try {
77748
- const swarm = parseSwarm(JSON.parse(await readFile15(path, "utf8")));
77993
+ const swarm = parseSwarm(JSON.parse(await readFile16(path, "utf8")));
77749
77994
  if (swarm.name !== name)
77750
77995
  throw new SwarmError("invalid_swarm", "Swarm name does not match its file.");
77751
77996
  return swarm;
@@ -77773,7 +78018,7 @@ async function writeSwarm(home, value) {
77773
78018
  const bytes = `${JSON.stringify(swarm, null, 2)}
77774
78019
  `;
77775
78020
  try {
77776
- if (await readFile15(path, "utf8") === bytes) return;
78021
+ if (await readFile16(path, "utf8") === bytes) return;
77777
78022
  } catch (error61) {
77778
78023
  if (!isMissingFile(error61)) throw error61;
77779
78024
  }
@@ -77788,7 +78033,7 @@ async function deleteSwarmFile(home, name) {
77788
78033
  }
77789
78034
  async function withSwarmLock(home, name, fn) {
77790
78035
  assertName(name);
77791
- const path = join12(swarmsDirectory(home), `.${name}.lock`);
78036
+ const path = join13(swarmsDirectory(home), `.${name}.lock`);
77792
78037
  try {
77793
78038
  return await withFileLock(path, fn, { lockedMessage: `Swarm ${name} is locked.` });
77794
78039
  } catch (error61) {
@@ -78100,7 +78345,7 @@ async function swarmStatus(opts) {
78100
78345
  );
78101
78346
  let movementFiles;
78102
78347
  try {
78103
- movementFiles = await readdir6(join12(home, "movements"));
78348
+ movementFiles = await readdir6(join13(home, "movements"));
78104
78349
  } catch (error61) {
78105
78350
  if (!isMissingFile(error61)) throw error61;
78106
78351
  movementFiles = [];
@@ -78157,11 +78402,11 @@ async function swarmStatus(opts) {
78157
78402
  })
78158
78403
  );
78159
78404
  const accounts = new Set(swarmAccountNames(swarm));
78160
- const open12 = [];
78405
+ const open13 = [];
78161
78406
  for (const summary2 of await listUnfinishedMovements({ home })) {
78162
78407
  const movement = await readMovement(home, summary2.id);
78163
78408
  if (movement.treasury === swarm.treasury.account || movement.legs.some((leg) => accounts.has(leg.from) || accounts.has(leg.to))) {
78164
- open12.push(summary2);
78409
+ open13.push(summary2);
78165
78410
  }
78166
78411
  }
78167
78412
  return {
@@ -78170,7 +78415,7 @@ async function swarmStatus(opts) {
78170
78415
  strategy: swarm.policy.strategy,
78171
78416
  treasury,
78172
78417
  members: members2,
78173
- openMovements: open12.sort(
78418
+ openMovements: open13.sort(
78174
78419
  (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)
78175
78420
  )
78176
78421
  };
@@ -78269,7 +78514,7 @@ async function assertNoConflicts(home, name, accounts) {
78269
78514
  }
78270
78515
  async function profileExists(home, account) {
78271
78516
  try {
78272
- await stat11(join12(getVapiPaths(home).agentsDir, `${account}.json`));
78517
+ await stat13(join13(getVapiPaths(home).agentsDir, `${account}.json`));
78273
78518
  return true;
78274
78519
  } catch (error61) {
78275
78520
  if (isMissingFile(error61)) return false;
@@ -78282,7 +78527,7 @@ async function refuseTreasuryProfile(home, account) {
78282
78527
  }
78283
78528
 
78284
78529
  // ../core/src/x402-pay.ts
78285
- import { randomBytes as randomBytes14, randomUUID as randomUUID2 } from "node:crypto";
78530
+ import { randomBytes as randomBytes15, randomUUID as randomUUID2 } from "node:crypto";
78286
78531
 
78287
78532
  // ../core/src/run-budget.ts
78288
78533
  var RunBudgetError = class extends Error {
@@ -78323,13 +78568,13 @@ function createRunBudget(args) {
78323
78568
  // ../core/src/support-report.ts
78324
78569
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
78325
78570
  import { arch, platform, release } from "node:os";
78326
- import { join as join13 } from "node:path";
78327
- var VAPI_CLIENT_VERSION = "0.12.1";
78571
+ import { join as join14 } from "node:path";
78572
+ var VAPI_CLIENT_VERSION = "0.13.0";
78328
78573
  async function createSupportReport(options) {
78329
78574
  const message = options.message.trim();
78330
78575
  if (!message) throw new Error("Support report message must not be empty.");
78331
78576
  const paths = getVapiPaths();
78332
- const reportsDirectory = options.reportsDirectory ?? join13(paths.directory, "reports");
78577
+ const reportsDirectory = options.reportsDirectory ?? join14(paths.directory, "reports");
78333
78578
  const receipts = await readReceipts(options.receiptsPath ?? paths.receipts, { limit: 5 });
78334
78579
  const system = options.systemInfo ?? defaultSystemInfo();
78335
78580
  const report = {
@@ -78359,7 +78604,7 @@ async function createSupportReport(options) {
78359
78604
  };
78360
78605
  const now = options.now ?? /* @__PURE__ */ new Date();
78361
78606
  const timestamp = now.toISOString();
78362
- const path = join13(reportsDirectory, `${sanitizeTimestamp(timestamp)}.json`);
78607
+ const path = join14(reportsDirectory, `${sanitizeTimestamp(timestamp)}.json`);
78363
78608
  await mkdir15(reportsDirectory, { recursive: true, mode: 448 });
78364
78609
  const serialized = `${JSON.stringify(report, null, 2)}
78365
78610
  `;
@@ -78555,7 +78800,7 @@ async function completeX402Payment(args) {
78555
78800
  throw walletCapError(error61, quote.amountAtomic, args);
78556
78801
  }
78557
78802
  } else {
78558
- reservationId = args.paymentId ?? `x402_${randomBytes14(12).toString("hex")}`;
78803
+ reservationId = args.paymentId ?? `x402_${randomBytes15(12).toString("hex")}`;
78559
78804
  let reservation;
78560
78805
  try {
78561
78806
  reservation = await reserveSpend(quote.amountAtomic, args.caps, {
@@ -79956,8 +80201,8 @@ function freezeScopeTerms(structuredInput, briefInput) {
79956
80201
  }
79957
80202
 
79958
80203
  // ../core/src/tasks/scope-bindings.ts
79959
- import { readFile as readFile16 } from "node:fs/promises";
79960
- import { join as join14 } from "node:path";
80204
+ import { readFile as readFile17 } from "node:fs/promises";
80205
+ import { join as join15 } from "node:path";
79961
80206
 
79962
80207
  // ../core/src/tasks/chain-port.ts
79963
80208
  var TasksChainError = class extends Error {
@@ -80532,7 +80777,7 @@ var messageSchema = external_exports.looseObject({
80532
80777
  })
80533
80778
  )
80534
80779
  });
80535
- var fileSchema = external_exports.looseObject({
80780
+ var fileSchema2 = external_exports.looseObject({
80536
80781
  id: uuidSchema,
80537
80782
  purpose: workFilePurposeSchema,
80538
80783
  fileName: external_exports.string(),
@@ -80838,11 +81083,11 @@ var tasksResponseSchemas = {
80838
81083
  observedAt: isoDateTimeSchema
80839
81084
  }),
80840
81085
  createUpload: external_exports.looseObject({
80841
- file: fileSchema.extend({ state: external_exports.literal("pending"), sha256: external_exports.null() }),
81086
+ file: fileSchema2.extend({ state: external_exports.literal("pending"), sha256: external_exports.null() }),
80842
81087
  uploadUrl: external_exports.url()
80843
81088
  }),
80844
81089
  finalizeUpload: external_exports.looseObject({
80845
- file: fileSchema.extend({
81090
+ file: fileSchema2.extend({
80846
81091
  state: external_exports.literal("ready"),
80847
81092
  sha256: external_exports.string().regex(/^[0-9a-fA-F]{64}$/)
80848
81093
  })
@@ -81450,10 +81695,10 @@ function key(identity) {
81450
81695
  return `${identity.orderId}:${identity.trancheOrdinal}:${identity.scopeVersion}:${identity.termsHash.toLowerCase()}:${identity.self.toLowerCase()}`;
81451
81696
  }
81452
81697
  function createScopeBindings(home) {
81453
- const path = join14(home, "tasks", "scope-bindings.json");
81698
+ const path = join15(home, "tasks", "scope-bindings.json");
81454
81699
  async function read() {
81455
81700
  try {
81456
- return storeSchema.parse(JSON.parse(await readFile16(path, "utf8")));
81701
+ return storeSchema.parse(JSON.parse(await readFile17(path, "utf8")));
81457
81702
  } catch (error61) {
81458
81703
  if (error61 instanceof Error && "code" in error61 && error61.code === "ENOENT")
81459
81704
  return { version: 1, bindings: {} };
@@ -82134,7 +82379,7 @@ function createTasksChain(options) {
82134
82379
  const { account, client, pending, rpcFor } = options;
82135
82380
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
82136
82381
  const sleep = options.sleep ?? ((ms) => new Promise((resolve4) => setTimeout(resolve4, ms)));
82137
- const randomBytes17 = options.randomBytes ?? cryptoRandomBytes2;
82382
+ const randomBytes18 = options.randomBytes ?? cryptoRandomBytes2;
82138
82383
  const confirmations = options.confirmations ?? 2;
82139
82384
  if (!Number.isSafeInteger(confirmations) || confirmations < 1)
82140
82385
  throw new TasksChainError("Tasks confirmations must be a positive integer.", false, {
@@ -82743,7 +82988,7 @@ function createTasksChain(options) {
82743
82988
  await verifyClone(rpcFor(ready.chainId), expected, true);
82744
82989
  if (validBefore <= BigInt(Math.floor(now().getTime() / 1e3)))
82745
82990
  throw new TasksValidationError("The task funding offer has expired.");
82746
- const bytes = randomBytes17(32);
82991
+ const bytes = randomBytes18(32);
82747
82992
  if (bytes.length !== 32)
82748
82993
  throw new TasksValidationError(
82749
82994
  "Funding authorization randomness must contain 32 bytes."
@@ -83021,8 +83266,8 @@ function createTasksRpcFor(config2, options = {}) {
83021
83266
  }
83022
83267
 
83023
83268
  // ../core/src/tasks/pending-transactions.ts
83024
- import { readFile as readFile17 } from "node:fs/promises";
83025
- import { join as join15 } from "node:path";
83269
+ import { readFile as readFile18 } from "node:fs/promises";
83270
+ import { join as join16 } from "node:path";
83026
83271
  var hex3 = external_exports.string().regex(/^0x(?:[0-9a-fA-F]{2})+$/).transform((v) => v);
83027
83272
  var hash4 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform((v) => v);
83028
83273
  var step = external_exports.enum([
@@ -83104,11 +83349,11 @@ function validCheckpointStep(storedStep, response) {
83104
83349
  }[response.operation.kind];
83105
83350
  }
83106
83351
  function createPendingTransactions(home) {
83107
- const path = join15(home, "tasks", "pending.json");
83352
+ const path = join16(home, "tasks", "pending.json");
83108
83353
  const lockPath = `${path}.lock`;
83109
83354
  const read = async () => {
83110
83355
  try {
83111
- const state = stateSchema.parse(JSON.parse(await readFile17(path, "utf8")));
83356
+ const state = stateSchema.parse(JSON.parse(await readFile18(path, "utf8")));
83112
83357
  for (const [key2, value] of Object.entries(state.checkpoints)) {
83113
83358
  const separator = key2.indexOf(":");
83114
83359
  const operationId = key2.slice(0, separator);
@@ -83171,7 +83416,7 @@ function createPendingTransactions(home) {
83171
83416
  },
83172
83417
  withStepLock(operationId, step2, fn) {
83173
83418
  return withFileLock(
83174
- join15(
83419
+ join16(
83175
83420
  home,
83176
83421
  "tasks",
83177
83422
  `step-${encodeURIComponent(operationId)}-${encodeURIComponent(step2)}.lock`
@@ -83183,13 +83428,13 @@ function createPendingTransactions(home) {
83183
83428
  external_exports.number().int().positive().parse(chainId);
83184
83429
  address3.parse(signer);
83185
83430
  return withFileLock(
83186
- join15(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
83431
+ join16(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
83187
83432
  fn
83188
83433
  );
83189
83434
  },
83190
83435
  withFundingLock(milestoneId, fn) {
83191
83436
  milestoneKey(milestoneId);
83192
- return withFileLock(join15(home, "tasks", `fund-${milestoneId}.lock`), fn);
83437
+ return withFileLock(join16(home, "tasks", `fund-${milestoneId}.lock`), fn);
83193
83438
  },
83194
83439
  async nextNonce(chainId, signer) {
83195
83440
  external_exports.number().int().positive().parse(chainId);
@@ -84015,7 +84260,7 @@ function policyAtomic(value) {
84015
84260
  }
84016
84261
 
84017
84262
  // ../core/src/tasks/operation-support.ts
84018
- import { readFile as readFile18, stat as stat12 } from "node:fs/promises";
84263
+ import { readFile as readFile19, stat as stat14 } from "node:fs/promises";
84019
84264
  import { basename as basename3, extname } from "node:path";
84020
84265
  var TaskOperationError = class extends Error {
84021
84266
  constructor(code, message, manifestHash) {
@@ -84183,7 +84428,7 @@ function parseTaskDuration(text, now) {
84183
84428
  async function readTaskFile(path) {
84184
84429
  let details;
84185
84430
  try {
84186
- details = await stat12(path);
84431
+ details = await stat14(path);
84187
84432
  } catch {
84188
84433
  throw new TaskInputError(`Task file ${JSON.stringify(path)} could not be read.`);
84189
84434
  }
@@ -84207,7 +84452,7 @@ async function readTaskFile(path) {
84207
84452
  const contentType = types[extname(path).toLowerCase()];
84208
84453
  if (!contentType)
84209
84454
  throw new TaskInputError("Task files must be images, PDF, ZIP, text, Markdown, JSON or CSV.");
84210
- const bytes = await readFile18(path);
84455
+ const bytes = await readFile19(path);
84211
84456
  if (bytes.length < TASK_LIMITS.uploadBytesMin || bytes.length > TASK_LIMITS.uploadBytesMax)
84212
84457
  throw new TaskInputError("Task files must contain between 1 byte and 50 MiB.");
84213
84458
  return {
@@ -85006,7 +85251,7 @@ async function resolveUnmatchedTaskOperation(context, input2) {
85006
85251
  }
85007
85252
 
85008
85253
  // ../core/src/searches.ts
85009
- import { mkdir as mkdir16, open as open11, readFile as readFile19 } from "node:fs/promises";
85254
+ import { mkdir as mkdir16, open as open12, readFile as readFile20 } from "node:fs/promises";
85010
85255
  import { dirname as dirname10 } from "node:path";
85011
85256
  var searchEventSchema = external_exports.strictObject({
85012
85257
  timestamp: external_exports.iso.datetime(),
@@ -85028,7 +85273,7 @@ function parseSearchEvent(value) {
85028
85273
  async function appendSearchEvent(event, path = getVapiPaths().searches) {
85029
85274
  const parsed = parseSearchEvent(event);
85030
85275
  await mkdir16(dirname10(path), { recursive: true, mode: 448 });
85031
- const handle = await open11(path, "a", 384);
85276
+ const handle = await open12(path, "a", 384);
85032
85277
  try {
85033
85278
  await handle.writeFile(`${JSON.stringify(parsed)}
85034
85279
  `, "utf8");
@@ -85040,7 +85285,7 @@ async function appendSearchEvent(event, path = getVapiPaths().searches) {
85040
85285
  async function readSearchEvents(path = getVapiPaths().searches) {
85041
85286
  let raw;
85042
85287
  try {
85043
- raw = await readFile19(path, "utf8");
85288
+ raw = await readFile20(path, "utf8");
85044
85289
  } catch (error61) {
85045
85290
  if (isMissingFile(error61)) return [];
85046
85291
  throw error61;
@@ -86145,9 +86390,9 @@ function csvCell(value) {
86145
86390
  }
86146
86391
 
86147
86392
  // ../core/src/swarm-capital.ts
86148
- import { createHash as createHash5, randomBytes as randomBytes15 } from "node:crypto";
86149
- import { readFile as readFile20, unlink as unlink12 } from "node:fs/promises";
86150
- import { join as join16 } from "node:path";
86393
+ import { createHash as createHash5, randomBytes as randomBytes16 } from "node:crypto";
86394
+ import { readFile as readFile21, unlink as unlink12 } from "node:fs/promises";
86395
+ import { join as join17 } from "node:path";
86151
86396
  var movementIdSchema3 = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/u);
86152
86397
  var amountSchema2 = external_exports.string().regex(/^\d+\.\d{2}$/u);
86153
86398
  var requestIdSchema = external_exports.string().min(1).max(512);
@@ -87028,7 +87273,7 @@ async function readDelegationRecord(home, movementId) {
87028
87273
  const safeId = runRecordMovementId(movementId);
87029
87274
  try {
87030
87275
  const record2 = delegationRecordSchema.parse(
87031
- JSON.parse(await readFile20(delegationRecordPath(home, safeId), "utf8"))
87276
+ JSON.parse(await readFile21(delegationRecordPath(home, safeId), "utf8"))
87032
87277
  );
87033
87278
  if (record2.movementId !== safeId) {
87034
87279
  throw new SwarmError(
@@ -87055,7 +87300,7 @@ async function readTreasuryRequestRecord(home, movementId) {
87055
87300
  const safeId = runRecordMovementId(movementId);
87056
87301
  try {
87057
87302
  const record2 = treasuryRequestRecordSchema.parse(
87058
- JSON.parse(await readFile20(treasuryRequestRecordPath(home, safeId), "utf8"))
87303
+ JSON.parse(await readFile21(treasuryRequestRecordPath(home, safeId), "utf8"))
87059
87304
  );
87060
87305
  if (record2.movementId !== safeId) {
87061
87306
  throw new SwarmError(
@@ -87086,18 +87331,18 @@ function runRecordMovementId(value) {
87086
87331
  return parsed.data;
87087
87332
  }
87088
87333
  function treasuryRequestRecordPath(home, movementId) {
87089
- return join16(home, "runs", "requests", `${movementId}.json`);
87334
+ return join17(home, "runs", "requests", `${movementId}.json`);
87090
87335
  }
87091
87336
  function delegationRecordPath(home, movementId) {
87092
- return join16(home, "runs", "delegations", `${movementId}.json`);
87337
+ return join17(home, "runs", "delegations", `${movementId}.json`);
87093
87338
  }
87094
87339
  function legacyFundingProgressPath(home, name) {
87095
- return join16(home, "swarms", `.${name}.funding`);
87340
+ return join17(home, "swarms", `.${name}.funding`);
87096
87341
  }
87097
87342
  async function readLegacyFundingProgress(home, name) {
87098
87343
  try {
87099
87344
  const progress = legacyFundingProgressSchema.parse(
87100
- JSON.parse(await readFile20(legacyFundingProgressPath(home, name), "utf8"))
87345
+ JSON.parse(await readFile21(legacyFundingProgressPath(home, name), "utf8"))
87101
87346
  );
87102
87347
  if (progress.name !== name) {
87103
87348
  throw new SwarmError("invalid_swarm", `Invalid funding progress for swarm ${name}.`);
@@ -87326,7 +87571,7 @@ async function optionalMovement(home, id2) {
87326
87571
  }
87327
87572
  }
87328
87573
  function nextMovementId(deps) {
87329
- return movementIdSchema3.parse(deps.randomId?.() ?? `mv_${randomBytes15(12).toString("hex")}`);
87574
+ return movementIdSchema3.parse(deps.randomId?.() ?? `mv_${randomBytes16(12).toString("hex")}`);
87330
87575
  }
87331
87576
  async function executeRecordedMovement(id2, plan, deps, home, options = {}) {
87332
87577
  try {
@@ -87742,7 +87987,7 @@ async function removeMemberLocked(home, swarm, account) {
87742
87987
  }
87743
87988
 
87744
87989
  // ../core/src/status.ts
87745
- import { join as join17 } from "node:path";
87990
+ import { join as join18 } from "node:path";
87746
87991
  var STATUS_TIMEOUT_MS = 2e3;
87747
87992
  async function buildStatus(deps) {
87748
87993
  const timers = deps.timers ?? { setTimeout, clearTimeout };
@@ -87798,7 +88043,7 @@ function formatUsdAmount(value) {
87798
88043
  }
87799
88044
  async function readVaultStatus(deps) {
87800
88045
  const store = deps.secrets.description.replace(/^the /u, "");
87801
- const path = join17(deps.home, "vault.json");
88046
+ const path = join18(deps.home, "vault.json");
87802
88047
  let file2;
87803
88048
  try {
87804
88049
  file2 = await readVaultFileUnlocked(path);
@@ -88232,7 +88477,7 @@ function isRecord4(value) {
88232
88477
 
88233
88478
  // ../core/src/vault-setup.ts
88234
88479
  import { rm as rm2 } from "node:fs/promises";
88235
- import { join as join18 } from "node:path";
88480
+ import { join as join19 } from "node:path";
88236
88481
  async function createVault2(home, options) {
88237
88482
  if (options.password === "") {
88238
88483
  throw new KeystoreError("A password cannot be empty.");
@@ -88244,7 +88489,7 @@ async function createVault2(home, options) {
88244
88489
  const hadDeviceKey = options.password !== void 0 && await options.secrets.has(VAULT_KEY_ACCOUNT);
88245
88490
  await store.createEmptyVault();
88246
88491
  if (options.password !== void 0) {
88247
- const path = join18(home, "vault.json");
88492
+ const path = join19(home, "vault.json");
88248
88493
  try {
88249
88494
  await protectVault({
88250
88495
  path,
@@ -88600,7 +88845,7 @@ function assertKeyMatchesAddress(bundle) {
88600
88845
  }
88601
88846
 
88602
88847
  // ../core/src/api-key.ts
88603
- import { chmod as chmod5, mkdir as mkdir17, readFile as readFile21, rename as rename11, writeFile as writeFile9 } from "node:fs/promises";
88848
+ import { chmod as chmod5, mkdir as mkdir17, readFile as readFile22, rename as rename11, writeFile as writeFile9 } from "node:fs/promises";
88604
88849
  import { dirname as dirname11 } from "node:path";
88605
88850
  var API_KEY_PREFIX = "vapi_sk_";
88606
88851
  var API_KEY_PATTERN = /^vapi_sk_[A-Za-z0-9_-]{16,128}$/;
@@ -88696,7 +88941,7 @@ async function readConfigApiKey(path) {
88696
88941
  async function readConfigRecord(path) {
88697
88942
  let raw;
88698
88943
  try {
88699
- raw = await readFile21(path, "utf8");
88944
+ raw = await readFile22(path, "utf8");
88700
88945
  } catch (error61) {
88701
88946
  if (isMissingFile(error61)) return void 0;
88702
88947
  throw error61;
@@ -89111,14 +89356,14 @@ function hostname3(resourceUrl) {
89111
89356
  }
89112
89357
 
89113
89358
  // ../sources/src/local-file.ts
89114
- import { readFile as readFile22 } from "node:fs/promises";
89359
+ import { readFile as readFile23 } from "node:fs/promises";
89115
89360
  import { resolve as resolve2 } from "node:path";
89116
89361
  function localFileSource(path) {
89117
89362
  const absolutePath = resolve2(path);
89118
89363
  async function listings() {
89119
89364
  let parsed;
89120
89365
  try {
89121
- parsed = JSON.parse(await readFile22(absolutePath, "utf8"));
89366
+ parsed = JSON.parse(await readFile23(absolutePath, "utf8"));
89122
89367
  } catch (error61) {
89123
89368
  throw new Error(`Could not read local discovery source ${JSON.stringify(absolutePath)}.`, {
89124
89369
  cause: error61
@@ -91887,8 +92132,8 @@ function exactPriceFact(value) {
91887
92132
  }
91888
92133
 
91889
92134
  // ../mcp/src/agent/runtime.ts
91890
- import { mkdir as mkdir18, readFile as readFile23, readdir as readdir7, rm as rm3 } from "node:fs/promises";
91891
- import { join as join19 } from "node:path";
92135
+ import { mkdir as mkdir18, readFile as readFile24, readdir as readdir7, rm as rm3 } from "node:fs/promises";
92136
+ import { join as join20 } from "node:path";
91892
92137
 
91893
92138
  // ../mcp/src/agent/run.ts
91894
92139
  var loopSearchResultSchema = external_exports.array(
@@ -93189,19 +93434,19 @@ var runRecordSchema = external_exports.strictObject({
93189
93434
  detail: external_exports.string().optional()
93190
93435
  });
93191
93436
  function runsDirectory(home) {
93192
- return join19(home, "runs");
93437
+ return join20(home, "runs");
93193
93438
  }
93194
93439
  function runRecordPath(home, runId) {
93195
93440
  assertRunId(runId);
93196
- return join19(runsDirectory(home), `${runId}.json`);
93441
+ return join20(runsDirectory(home), `${runId}.json`);
93197
93442
  }
93198
93443
  function runLogPath(home, runId) {
93199
93444
  assertRunId(runId);
93200
- return join19(runsDirectory(home), `${runId}.log`);
93445
+ return join20(runsDirectory(home), `${runId}.log`);
93201
93446
  }
93202
93447
  function runResultPath(home, runId) {
93203
93448
  assertRunId(runId);
93204
- return join19(runsDirectory(home), `${runId}.result.json`);
93449
+ return join20(runsDirectory(home), `${runId}.result.json`);
93205
93450
  }
93206
93451
  async function writeRunRecord(home, record2) {
93207
93452
  const path = runRecordPath(home, record2.runId);
@@ -93212,7 +93457,7 @@ async function writeRunRecord(home, record2) {
93212
93457
  async function readRunRecord(home, runId) {
93213
93458
  const path = runRecordPath(home, runId);
93214
93459
  try {
93215
- return runRecordSchema.parse(JSON.parse(await readFile23(path, "utf8")));
93460
+ return runRecordSchema.parse(JSON.parse(await readFile24(path, "utf8")));
93216
93461
  } catch (error61) {
93217
93462
  if (isMissingFile3(error61)) return void 0;
93218
93463
  throw error61;
@@ -93232,7 +93477,7 @@ async function listRunRecords(home, filter = {}) {
93232
93477
  if (match === null) continue;
93233
93478
  try {
93234
93479
  const record2 = runRecordSchema.parse(
93235
- JSON.parse(await readFile23(join19(runsDirectory(home), file2), "utf8"))
93480
+ JSON.parse(await readFile24(join20(runsDirectory(home), file2), "utf8"))
93236
93481
  );
93237
93482
  if (record2.runId !== match[1]) continue;
93238
93483
  if (filter.swarm !== void 0 && record2.member.swarm !== filter.swarm) continue;
@@ -93509,7 +93754,7 @@ async function stopRun(args) {
93509
93754
  }
93510
93755
  }
93511
93756
  function memberRunLockPath(home, account) {
93512
- return join19(runsDirectory(home), `.member-${account}.lock`);
93757
+ return join20(runsDirectory(home), `.member-${account}.lock`);
93513
93758
  }
93514
93759
  function summarizeRunRecord(record2) {
93515
93760
  return {
@@ -97116,8 +97361,8 @@ function rgbToAnsi256(red, green, blue) {
97116
97361
  }
97117
97362
 
97118
97363
  // ../cli/src/accounts.ts
97119
- import { readFile as readFile25, stat as stat14 } from "node:fs/promises";
97120
- import { join as join22 } from "node:path";
97364
+ import { readFile as readFile26, stat as stat16 } from "node:fs/promises";
97365
+ import { join as join23 } from "node:path";
97121
97366
 
97122
97367
  // ../cli/src/dashboard.ts
97123
97368
  import { resolve as resolve3 } from "node:path";
@@ -97794,12 +98039,12 @@ function shellQuote2(value) {
97794
98039
  }
97795
98040
 
97796
98041
  // ../cli/src/status.ts
97797
- import { stat as stat13 } from "node:fs/promises";
98042
+ import { stat as stat15 } from "node:fs/promises";
97798
98043
  import { homedir as homedir2 } from "node:os";
97799
98044
  import { sep } from "node:path";
97800
98045
 
97801
98046
  // ../core/src/cloud-backup.ts
97802
- import { join as join21 } from "node:path";
98047
+ import { join as join22 } from "node:path";
97803
98048
 
97804
98049
  // ../core/src/backup.ts
97805
98050
  import {
@@ -97822,11 +98067,11 @@ import {
97822
98067
  mkdir as mkdir19,
97823
98068
  mkdtemp,
97824
98069
  open as openFile,
97825
- readFile as readFile24,
98070
+ readFile as readFile25,
97826
98071
  readdir as readdir8,
97827
98072
  rm as rm4
97828
98073
  } from "node:fs/promises";
97829
- import { dirname as dirname12, join as join20 } from "node:path";
98074
+ import { dirname as dirname12, join as join21 } from "node:path";
97830
98075
  var ERROR_MESSAGES = {
97831
98076
  backup_too_large: "Backup envelope exceeds 65,536 bytes.",
97832
98077
  backup_open_failed: "Unable to open backup.",
@@ -98109,8 +98354,8 @@ async function createBackup(options) {
98109
98354
  assertDevice(options.device);
98110
98355
  assertOwnerKey(options.ownerKey);
98111
98356
  const createdAt = readCreatedAt(options.now ?? (() => /* @__PURE__ */ new Date()));
98112
- const randomBytes17 = options.randomBytes ?? cryptoRandomBytes3;
98113
- const nonce = readRandomBytes(randomBytes17, 12);
98357
+ const randomBytes18 = options.randomBytes ?? cryptoRandomBytes3;
98358
+ const nonce = readRandomBytes(randomBytes18, 12);
98114
98359
  const salt = encodeBase64Url(options.ownerKey.salt);
98115
98360
  const kdf = options.ownerKey.kdf === "hkdf-sha256" ? { name: "hkdf-sha256", salt } : { name: "scrypt", salt, N: SCRYPT_N2, r: SCRYPT_R2, p: SCRYPT_P2 };
98116
98361
  const cipher = { name: CIPHER_NAME, nonce: encodeBase64Url(nonce) };
@@ -98304,7 +98549,7 @@ async function exportBackupSource(options) {
98304
98549
  var BackupSnapshotChangedError = class extends Error {
98305
98550
  };
98306
98551
  async function exportBackupSourceAttempt(options, networks) {
98307
- const path = join20(options.store.home, "vault.json");
98552
+ const path = join21(options.store.home, "vault.json");
98308
98553
  const { phrase, file: file2, accounts } = await withVaultLock(path, async () => {
98309
98554
  const [phrase2, vault, file3] = await Promise.all([
98310
98555
  exportVaultPhrase({ path, key: options.vaultKey }),
@@ -98440,16 +98685,16 @@ async function restoreBackupPlaintext(options) {
98440
98685
  } catch {
98441
98686
  throw new BackupError("backup_invalid_input");
98442
98687
  }
98443
- const vaultPath2 = join20(options.home, "vault.json");
98444
- const registryPath = join20(options.home, "wallets.json");
98688
+ const vaultPath2 = join21(options.home, "vault.json");
98689
+ const registryPath = join21(options.home, "wallets.json");
98445
98690
  let stagingHome;
98446
98691
  let beforePublishError;
98447
98692
  let afterPublishError;
98448
98693
  try {
98449
98694
  await mkdir19(options.home, { recursive: true, mode: 448 });
98450
- stagingHome = await mkdtemp(join20(options.home, ".backup-restore-"));
98451
- const stagedVaultPath = join20(stagingHome, "vault.json");
98452
- const stagedRegistryPath = join20(stagingHome, "wallets.json");
98695
+ stagingHome = await mkdtemp(join21(options.home, ".backup-restore-"));
98696
+ const stagedVaultPath = join21(stagingHome, "vault.json");
98697
+ const stagedRegistryPath = join21(stagingHome, "wallets.json");
98453
98698
  await createVault({
98454
98699
  path: stagedVaultPath,
98455
98700
  key: options.vaultKey,
@@ -98508,7 +98753,7 @@ async function restoreBackupPlaintext(options) {
98508
98753
  protected: plaintext.protected,
98509
98754
  networks: [...plaintext.registry.networks]
98510
98755
  };
98511
- const markerPath = join20(options.home, RESTORE_MARKER_FILE);
98756
+ const markerPath = join21(options.home, RESTORE_MARKER_FILE);
98512
98757
  const fingerprint = restoreFingerprint(
98513
98758
  plaintext,
98514
98759
  stagedV2?.restoreDevice ?? options.device,
@@ -98719,13 +98964,13 @@ async function stageV2Restore(options) {
98719
98964
  }
98720
98965
  const agents = [];
98721
98966
  for (const profile of validAgents) {
98722
- const stagedPath = join20(options.stagingHome, "agents", `${profile.name}.json`);
98967
+ const stagedPath = join21(options.stagingHome, "agents", `${profile.name}.json`);
98723
98968
  if (await stageRestoreBytes(stagedPath, prettyJson(profile))) {
98724
98969
  agents.push({
98725
98970
  kind: "agent",
98726
98971
  name: profile.name,
98727
98972
  stagedPath,
98728
- targetPath: join20(options.home, "agents", `${profile.name}.json`)
98973
+ targetPath: join21(options.home, "agents", `${profile.name}.json`)
98729
98974
  });
98730
98975
  } else {
98731
98976
  skipped2.push({ kind: "agent", name: profile.name, reason: "write_failed" });
@@ -98745,13 +98990,13 @@ async function stageV2Restore(options) {
98745
98990
  if (restoreDevice !== void 0) {
98746
98991
  for (const value of validSwarms) {
98747
98992
  const swarm = swarmFileSchema.parse({ ...value, device: restoreDevice });
98748
- const stagedPath = join20(options.stagingHome, "swarms", `${swarm.name}.json`);
98993
+ const stagedPath = join21(options.stagingHome, "swarms", `${swarm.name}.json`);
98749
98994
  if (await stageRestoreBytes(stagedPath, prettyJson(swarm))) {
98750
98995
  swarms.push({
98751
98996
  kind: "swarm",
98752
98997
  name: swarm.name,
98753
98998
  stagedPath,
98754
- targetPath: join20(options.home, "swarms", `${swarm.name}.json`)
98999
+ targetPath: join21(options.home, "swarms", `${swarm.name}.json`)
98755
99000
  });
98756
99001
  } else {
98757
99002
  skipped2.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
@@ -98761,13 +99006,13 @@ async function stageV2Restore(options) {
98761
99006
  const movements = [];
98762
99007
  for (const movement of validMovements) {
98763
99008
  const restored = reconcileRestoredMovement(movement, assumedReceiptKeys);
98764
- const stagedPath = join20(options.stagingHome, "movements", `${restored.id}.json`);
99009
+ const stagedPath = join21(options.stagingHome, "movements", `${restored.id}.json`);
98765
99010
  if (await stageRestoreBytes(stagedPath, serializeMovement(restored))) {
98766
99011
  movements.push({
98767
99012
  kind: "movement",
98768
99013
  name: restored.id,
98769
99014
  stagedPath,
98770
- targetPath: join20(options.home, "movements", `${restored.id}.json`),
99015
+ targetPath: join21(options.home, "movements", `${restored.id}.json`),
98771
99016
  movement: restored
98772
99017
  });
98773
99018
  } else {
@@ -98838,8 +99083,8 @@ async function publishRestoreFile(file2, staged) {
98838
99083
  let identical = false;
98839
99084
  try {
98840
99085
  const [source, target] = await Promise.all([
98841
- readFile24(file2.stagedPath),
98842
- readFile24(file2.targetPath)
99086
+ readFile25(file2.stagedPath),
99087
+ readFile25(file2.targetPath)
98843
99088
  ]);
98844
99089
  identical = source.equals(target);
98845
99090
  } catch {
@@ -98871,7 +99116,7 @@ async function publishRestoreReceiptsLocked(staged, targetPath) {
98871
99116
  let existing = "";
98872
99117
  let existingLines = /* @__PURE__ */ new Set();
98873
99118
  try {
98874
- await readFile24(staged.receiptsPath, "utf8");
99119
+ await readFile25(staged.receiptsPath, "utf8");
98875
99120
  await mkdir19(dirname12(targetPath), { recursive: true, mode: 448 });
98876
99121
  try {
98877
99122
  const journal = await readRestoreReceiptJournal(targetPath);
@@ -98926,7 +99171,7 @@ async function reconcilePublishedMovements(staged, home, requireDurableSafety =
98926
99171
  const unjournaledKeys = new Set([...signedKeys].filter((key2) => !journaledKeys.has(key2)));
98927
99172
  let files;
98928
99173
  try {
98929
- files = await readdir8(join20(home, "movements"));
99174
+ files = await readdir8(join21(home, "movements"));
98930
99175
  } catch (error61) {
98931
99176
  if (isMissingFile4(error61)) return;
98932
99177
  if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
@@ -99027,9 +99272,9 @@ function assertRelayKey(value) {
99027
99272
  throw new BackupError("relay_invalid_key");
99028
99273
  }
99029
99274
  }
99030
- function readRelayRandomBytes(randomBytes17, length) {
99275
+ function readRelayRandomBytes(randomBytes18, length) {
99031
99276
  try {
99032
- const value = randomBytes17(length);
99277
+ const value = randomBytes18(length);
99033
99278
  if (!(value instanceof Uint8Array) || value.byteLength !== length) throw new Error();
99034
99279
  return Buffer.from(value);
99035
99280
  } catch {
@@ -99147,7 +99392,7 @@ async function createRestoreMarker(vaultPath2, registryPath, fingerprint, vaultK
99147
99392
  }
99148
99393
  async function readRestoreMarker(path, fingerprint, vaultKey) {
99149
99394
  try {
99150
- const marker = restoreMarkerSchema.parse(JSON.parse(await readFile24(path, "utf8")));
99395
+ const marker = restoreMarkerSchema.parse(JSON.parse(await readFile25(path, "utf8")));
99151
99396
  const expectedMac = restoreMarkerMac(marker, vaultKey);
99152
99397
  if (marker.fingerprint !== fingerprint || !timingSafeEqual(Buffer.from(marker.mac, "hex"), Buffer.from(expectedMac, "hex"))) {
99153
99398
  throw new Error();
@@ -99164,7 +99409,7 @@ function restoreMarkerMac(marker, vaultKey) {
99164
99409
  ).digest("hex");
99165
99410
  }
99166
99411
  async function sha256File(path) {
99167
- return createHash6("sha256").update(await readFile24(path)).digest("hex");
99412
+ return createHash6("sha256").update(await readFile25(path)).digest("hex");
99168
99413
  }
99169
99414
  async function notifyRestorePublish(hook, step2, rememberError) {
99170
99415
  try {
@@ -99466,7 +99711,7 @@ function copyTransferReceipt(receipt) {
99466
99711
  async function readReceiptJournal(path) {
99467
99712
  let raw;
99468
99713
  try {
99469
- raw = await readFile24(path, "utf8");
99714
+ raw = await readFile25(path, "utf8");
99470
99715
  } catch (error61) {
99471
99716
  if (isMissingFile4(error61)) return [];
99472
99717
  throw error61;
@@ -99476,7 +99721,7 @@ async function readReceiptJournal(path) {
99476
99721
  async function readRestoreReceiptJournal(path) {
99477
99722
  let raw;
99478
99723
  try {
99479
- raw = await readFile24(path, "utf8");
99724
+ raw = await readFile25(path, "utf8");
99480
99725
  } catch (error61) {
99481
99726
  if (isMissingFile4(error61)) return { raw: "", lines: /* @__PURE__ */ new Set(), signedKeys: /* @__PURE__ */ new Set() };
99482
99727
  throw error61;
@@ -99595,8 +99840,8 @@ function assertOwnerKey(ownerKey) {
99595
99840
  assertBytes(ownerKey.key, 32);
99596
99841
  assertBytes(ownerKey.salt, 32);
99597
99842
  }
99598
- function readRandomBytes(randomBytes17, length) {
99599
- const value = randomBytes17(length);
99843
+ function readRandomBytes(randomBytes18, length) {
99844
+ const value = randomBytes18(length);
99600
99845
  if (!(value instanceof Uint8Array) || value.byteLength !== length) {
99601
99846
  throw new BackupError("backup_invalid_input");
99602
99847
  }
@@ -99835,7 +100080,7 @@ async function uploadBackupLocked(options, signal) {
99835
100080
  try {
99836
100081
  let vaultFile;
99837
100082
  try {
99838
- vaultFile = await readVaultFileUnlocked(join21(options.store.home, "vault.json"));
100083
+ vaultFile = await readVaultFileUnlocked(join22(options.store.home, "vault.json"));
99839
100084
  } catch (error61) {
99840
100085
  if (error61 instanceof VaultError && error61.code === "not_found") {
99841
100086
  return { status: "skipped", reason: "no_vault" };
@@ -99844,7 +100089,7 @@ async function uploadBackupLocked(options, signal) {
99844
100089
  }
99845
100090
  try {
99846
100091
  vaultKey = vaultFile.protected ? await unlockProtectedVault({
99847
- path: join21(options.store.home, "vault.json"),
100092
+ path: join22(options.store.home, "vault.json"),
99848
100093
  secrets: options.secrets,
99849
100094
  env: options.env,
99850
100095
  ...options.now === void 0 ? {} : { now: options.now }
@@ -100517,7 +100762,7 @@ async function readProcessStdin() {
100517
100762
  }
100518
100763
 
100519
100764
  // ../cli/src/version.ts
100520
- var CLI_VERSION = "0.12.1";
100765
+ var CLI_VERSION = "0.13.0";
100521
100766
 
100522
100767
  // ../cli/src/status.ts
100523
100768
  async function statusCommand(argv, json2, io, dependencies) {
@@ -100684,7 +100929,7 @@ function withDeadlineSignal3(fetchImpl, deadline) {
100684
100929
  }
100685
100930
  async function statusConfig(path) {
100686
100931
  try {
100687
- await stat13(path);
100932
+ await stat15(path);
100688
100933
  } catch (error61) {
100689
100934
  if (isMissingFile(error61)) return getDefaultConfig(process.env);
100690
100935
  throw error61;
@@ -100882,7 +101127,7 @@ async function siblingsFetchImpl(dependencies) {
100882
101127
  const configPath = getVapiPaths().config;
100883
101128
  let config2;
100884
101129
  try {
100885
- await stat14(configPath);
101130
+ await stat16(configPath);
100886
101131
  config2 = await loadConfig(configPath, process.env);
100887
101132
  } catch (error61) {
100888
101133
  if (!isMissingFile(error61)) throw error61;
@@ -100971,7 +101216,7 @@ ${IMPORT_USAGE}`);
100971
101216
  const passphrase = await secretPrompt(dependencies)(`Passphrase for ${keystorePath}: `);
100972
101217
  privateKey = (await exportKeystoreKeys(passphrase, keystorePath)).evm.privateKey;
100973
101218
  } else if (keyPath !== void 0) {
100974
- privateKey = (await readFile25(keyPath, "utf8")).trim();
101219
+ privateKey = (await readFile26(keyPath, "utf8")).trim();
100975
101220
  } else {
100976
101221
  privateKey = await secretPrompt(dependencies)("Private key: ");
100977
101222
  }
@@ -101019,10 +101264,10 @@ async function accountsRenameCommand(argv, json2, io, dependencies) {
101019
101264
  {
101020
101265
  previous: from16,
101021
101266
  ...address4 === void 0 ? {} : { address: address4 },
101022
- vault: join22(store.home, "vault.json"),
101267
+ vault: join23(store.home, "vault.json"),
101023
101268
  message: `Wallet ${from16} is now ${renamed.name}.`
101024
101269
  },
101025
- [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join22(store.home, "vault.json")}`].join(
101270
+ [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join23(store.home, "vault.json")}`].join(
101026
101271
  "\n"
101027
101272
  )
101028
101273
  );
@@ -101131,13 +101376,13 @@ async function accountsRestoreCommand(argv, json2, io, dependencies) {
101131
101376
  { name: restored.name, ...address4 === void 0 ? {} : { address: address4 } },
101132
101377
  {
101133
101378
  ...address4 === void 0 ? {} : { address: address4 },
101134
- vault: join22(store.home, "vault.json"),
101379
+ vault: join23(store.home, "vault.json"),
101135
101380
  spendCaps: restored.entry.spendCaps,
101136
101381
  message: `Wallet ${restored.name} restored to the device vault.`
101137
101382
  },
101138
101383
  [
101139
101384
  `Wallet ${restored.name} restored to the device vault.`,
101140
- `Vault: ${join22(store.home, "vault.json")}`
101385
+ `Vault: ${join23(store.home, "vault.json")}`
101141
101386
  ].join("\n")
101142
101387
  );
101143
101388
  }
@@ -101467,7 +101712,7 @@ function formatNetworkAccounts(accounts) {
101467
101712
  }
101468
101713
 
101469
101714
  // ../cli/src/cloud-backup.ts
101470
- import { join as join23 } from "node:path";
101715
+ import { join as join24 } from "node:path";
101471
101716
  var CLOUD_BACKUP_USAGE = "Usage: vapi backup --cloud [off] [--json]";
101472
101717
  var OWNER_RESTORE_USAGE = "Usage: vapi restore --from-owner [--owner <0x\u2026>] [--json]";
101473
101718
  var OWNER_PATTERN2 = /^0x[0-9a-fA-F]{40}$/u;
@@ -101490,7 +101735,7 @@ async function cloudBackupCommand(argv, json2, io, dependencies) {
101490
101735
  }
101491
101736
  async function enrollCloudBackup(json2, io, dependencies) {
101492
101737
  const paths = getVapiPaths();
101493
- if (!await fileExists2(join23(paths.directory, "vault.json"))) {
101738
+ if (!await fileExists3(join24(paths.directory, "vault.json"))) {
101494
101739
  throw new Error("No vault on this device. Run vapi setup first.");
101495
101740
  }
101496
101741
  const context = await cloudContext(io, dependencies);
@@ -101602,7 +101847,7 @@ async function restoreFromOwnerCommand(argv, json2, io, dependencies) {
101602
101847
  }
101603
101848
  const expectedOwner = ownerValue?.toLowerCase();
101604
101849
  const paths = getVapiPaths();
101605
- if (await fileExists2(join23(paths.directory, "vault.json")) && !await fileExists2(join23(paths.directory, ".backup-restore.json"))) {
101850
+ if (await fileExists3(join24(paths.directory, "vault.json")) && !await fileExists3(join24(paths.directory, ".backup-restore.json"))) {
101606
101851
  throw new Error(
101607
101852
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
101608
101853
  );
@@ -101658,7 +101903,7 @@ async function restoreFromOwnerCommand(argv, json2, io, dependencies) {
101658
101903
  env: getEnvironment(dependencies),
101659
101904
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
101660
101905
  });
101661
- if (!await fileExists2(paths.config)) {
101906
+ if (!await fileExists3(paths.config)) {
101662
101907
  const networks = restored.networks.length === 0 ? ["base"] : restored.networks;
101663
101908
  await writeDefaultConfig(paths.config, getEnvironment(dependencies), { networks });
101664
101909
  }
@@ -102699,20 +102944,20 @@ function shortExcerpt(value) {
102699
102944
  }
102700
102945
 
102701
102946
  // ../cli/src/agent.ts
102702
- import { readFile as readFile27, stat as stat15 } from "node:fs/promises";
102703
- import { join as join26 } from "node:path";
102947
+ import { readFile as readFile28, stat as stat17 } from "node:fs/promises";
102948
+ import { join as join27 } from "node:path";
102704
102949
  import { createInterface as createInterface2 } from "node:readline/promises";
102705
102950
 
102706
102951
  // ../cli/src/headless.ts
102707
102952
  import { chmod as chmod7, mkdtemp as mkdtemp2, rm as rm5, writeFile as writeFile10 } from "node:fs/promises";
102708
102953
  import { rmSync } from "node:fs";
102709
102954
  import { tmpdir as osTmpdir } from "node:os";
102710
- import { join as join24 } from "node:path";
102955
+ import { join as join25 } from "node:path";
102711
102956
  var BUNDLE_VARIABLE_PATTERN = /^[A-Z_][A-Z0-9_]*$/u;
102712
102957
  var REMOTE_BLOCKED_GRANTS2 = /* @__PURE__ */ new Set(["delegate", "allocate"]);
102713
102958
  var agentProfileOptions = { schema: registeredAgentProfileSchema };
102714
102959
  async function createHeadlessHome(bundle, options = {}) {
102715
- const home = await mkdtemp2(join24(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
102960
+ const home = await mkdtemp2(join25(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
102716
102961
  const cleanup = async () => {
102717
102962
  await rm5(home, { recursive: true, force: true });
102718
102963
  };
@@ -102912,18 +103157,18 @@ import { readFile as nodeReadFile } from "node:fs/promises";
102912
103157
 
102913
103158
  // ../cli/src/runtime-railway.ts
102914
103159
  import { spawn as spawn2 } from "node:child_process";
102915
- import { randomBytes as randomBytes16 } from "node:crypto";
103160
+ import { randomBytes as randomBytes17 } from "node:crypto";
102916
103161
  import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync as rmSync2, writeSync } from "node:fs";
102917
103162
  import {
102918
103163
  mkdtemp as nodeMkdtemp,
102919
103164
  readdir as readdir9,
102920
- readFile as readFile26,
103165
+ readFile as readFile27,
102921
103166
  rm as nodeRm,
102922
103167
  stat as nodeStat,
102923
103168
  writeFile as nodeWriteFile
102924
103169
  } from "node:fs/promises";
102925
103170
  import { tmpdir as osTmpdir2 } from "node:os";
102926
- import { basename as basename4, dirname as dirname13, join as join25 } from "node:path";
103171
+ import { basename as basename4, dirname as dirname13, join as join26 } from "node:path";
102927
103172
  var RAILWAY_CLI = {
102928
103173
  binary: "railway",
102929
103174
  create: (options) => [
@@ -103095,7 +103340,7 @@ async function assertRemoteSafeMember(args) {
103095
103340
  }
103096
103341
  function railwaySidecarPath(home, runId) {
103097
103342
  if (!isRunId(runId)) throw new RuntimeError("invalid_run_id", `Invalid run id: ${runId}.`);
103098
- return join25(runsDirectory(home), `${runId}.railway.json`);
103343
+ return join26(runsDirectory(home), `${runId}.railway.json`);
103099
103344
  }
103100
103345
  function createRailwayRuntime(options) {
103101
103346
  const { home } = options;
@@ -103420,10 +103665,10 @@ function createRailwayRuntime(options) {
103420
103665
  let createError;
103421
103666
  let cleanupError;
103422
103667
  try {
103423
- directory = await fs.mkdtemp(join25(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
103668
+ directory = await fs.mkdtemp(join26(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
103424
103669
  assertNotInterrupted();
103425
103670
  await assertMode(fs, directory, 448, "env-file directory");
103426
- envFile = join25(directory, "member.env");
103671
+ envFile = join26(directory, "member.env");
103427
103672
  await fs.writeFile(envFile, `${RAILWAY_CLI.bundleVariable}=${bundle}
103428
103673
  `, {
103429
103674
  encoding: "utf8",
@@ -103878,9 +104123,9 @@ async function writeSidecar(home, runId, sidecar) {
103878
104123
  function writeSidecarSync(path, sidecar) {
103879
104124
  const directory = dirname13(path);
103880
104125
  mkdirSync(directory, { recursive: true, mode: 448 });
103881
- const temporary = join25(
104126
+ const temporary = join26(
103882
104127
  directory,
103883
- `.${basename4(path)}.${process.pid}.${randomBytes16(6).toString("hex")}.tmp`
104128
+ `.${basename4(path)}.${process.pid}.${randomBytes17(6).toString("hex")}.tmp`
103884
104129
  );
103885
104130
  try {
103886
104131
  const descriptor2 = openSync(temporary, "wx", 384);
@@ -103918,7 +104163,7 @@ var LEGACY_SIDECAR_KEYS = ["checkpoint", "keepSandbox", "sandboxId", "v"];
103918
104163
  async function readSidecar(home, runId) {
103919
104164
  let parsed;
103920
104165
  try {
103921
- parsed = JSON.parse(await readFile26(railwaySidecarPath(home, runId), "utf8"));
104166
+ parsed = JSON.parse(await readFile27(railwaySidecarPath(home, runId), "utf8"));
103922
104167
  } catch {
103923
104168
  return void 0;
103924
104169
  }
@@ -103976,7 +104221,7 @@ async function assertMode(fs, path, mode, what) {
103976
104221
  }
103977
104222
  }
103978
104223
  async function deviceVaultKey(home, secrets, now) {
103979
- const path = join25(home, "vault.json");
104224
+ const path = join26(home, "vault.json");
103980
104225
  const metadata = await readVaultFileUnlocked(path);
103981
104226
  const key2 = metadata.protected ? await unlockProtectedVault({
103982
104227
  path,
@@ -104031,7 +104276,7 @@ function createLocalRuntime(options) {
104031
104276
  const processCommand = options.processCommand ?? defaultProcessCommand;
104032
104277
  const ownsProcess = (handle, pid) => processCommand(pid)?.includes(runResultPath(home, handle.runId)) === true;
104033
104278
  const closeFd = options.closeFd ?? closeSync2;
104034
- const readFile33 = options.readFile ?? nodeReadFile;
104279
+ const readFile34 = options.readFile ?? nodeReadFile;
104035
104280
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
104036
104281
  const openLog = options.openLog ?? ((path) => {
104037
104282
  mkdirSync2(runsDirectory(home), { recursive: true, mode: 448 });
@@ -104086,7 +104331,7 @@ function createLocalRuntime(options) {
104086
104331
  return handle;
104087
104332
  },
104088
104333
  async status(handle) {
104089
- const result = await readResultFile(readFile33, runResultPath(home, handle.runId));
104334
+ const result = await readResultFile(readFile34, runResultPath(home, handle.runId));
104090
104335
  if (result !== void 0) return result;
104091
104336
  const pid = localPid(handle);
104092
104337
  if (pid === void 0 || handle.kind !== "local") {
@@ -104189,10 +104434,10 @@ function childArguments(member, run) {
104189
104434
  ...run.drawUsd ? ["--draw", run.drawUsd] : []
104190
104435
  ];
104191
104436
  }
104192
- async function readResultFile(readFile33, path) {
104437
+ async function readResultFile(readFile34, path) {
104193
104438
  let text;
104194
104439
  try {
104195
- text = await readFile33(path, "utf8");
104440
+ text = await readFile34(path, "utf8");
104196
104441
  } catch (error61) {
104197
104442
  if (hasCode3(error61, "ENOENT")) return void 0;
104198
104443
  return { state: "failed", detail: "unreadable result file" };
@@ -104317,7 +104562,7 @@ async function createCommand(argv, json2, io, dependencies) {
104317
104562
  if (await profileFileExists(paths.agentsDir, name)) {
104318
104563
  throw new Error(`Agent ${name} already exists.`);
104319
104564
  }
104320
- const instructions = await readFile27(instructionsPath, "utf8");
104565
+ const instructions = await readFile28(instructionsPath, "utf8");
104321
104566
  if (instructions.length > 2e4) {
104322
104567
  throw new UsageError("--instructions must contain at most 20000 characters.");
104323
104568
  }
@@ -104903,7 +105148,7 @@ function explicitWallet(name) {
104903
105148
  }
104904
105149
  async function profileFileExists(directory, name) {
104905
105150
  try {
104906
- await stat15(join26(directory, `${name}.json`));
105151
+ await stat17(join27(directory, `${name}.json`));
104907
105152
  return true;
104908
105153
  } catch (error61) {
104909
105154
  if (isMissingFile(error61)) return false;
@@ -104964,7 +105209,7 @@ function usd(value, minimumDecimals = 0) {
104964
105209
 
104965
105210
  // ../cli/src/mcp-install.ts
104966
105211
  import { spawn as spawn3 } from "node:child_process";
104967
- import { mkdir as mkdir20, readFile as readFile28, writeFile as writeFile11 } from "node:fs/promises";
105212
+ import { mkdir as mkdir20, readFile as readFile29, writeFile as writeFile11 } from "node:fs/promises";
104968
105213
  import { homedir as systemHomedir } from "node:os";
104969
105214
  import { dirname as dirname14, posix, win32 as win322 } from "node:path";
104970
105215
 
@@ -105344,7 +105589,7 @@ function isRecord12(value) {
105344
105589
  }
105345
105590
  async function readExistingFile(path) {
105346
105591
  try {
105347
- return await readFile28(path, "utf8");
105592
+ return await readFile29(path, "utf8");
105348
105593
  } catch (error61) {
105349
105594
  if (isMissingFile(error61)) return void 0;
105350
105595
  throw error61;
@@ -105352,7 +105597,7 @@ async function readExistingFile(path) {
105352
105597
  }
105353
105598
  async function pathExists5(path) {
105354
105599
  try {
105355
- await readFile28(path);
105600
+ await readFile29(path);
105356
105601
  return true;
105357
105602
  } catch (error61) {
105358
105603
  if (isMissingFile(error61)) return false;
@@ -105362,15 +105607,15 @@ async function pathExists5(path) {
105362
105607
 
105363
105608
  // ../cli/src/code.ts
105364
105609
  import { constants as constants2 } from "node:fs";
105365
- import { access, mkdir as mkdir21, readFile as readFile29, realpath, unlink as unlink13, writeFile as writeFile12 } from "node:fs/promises";
105610
+ import { access, mkdir as mkdir21, readFile as readFile30, realpath, unlink as unlink13, writeFile as writeFile12 } from "node:fs/promises";
105366
105611
  import { homedir as homedir3 } from "node:os";
105367
- import { basename as basename5, dirname as dirname15, join as join27, posix as posix2, win32 as win323 } from "node:path";
105612
+ import { basename as basename5, dirname as dirname15, join as join28, posix as posix2, win32 as win323 } from "node:path";
105368
105613
  var VAPI_CODEX_PROVIDER = "vapi";
105369
105614
  var VAPI_CODEX_PROFILE = "vapi";
105370
105615
  var VAPI_CODEX_DEFAULT_MODEL = "venice/openai-gpt-61-sol";
105371
105616
  var VAPI_ROUTER_KEY_ENV = "VAPI_ROUTER_KEY";
105372
105617
  function codexConfigPath(env, home) {
105373
- return join27(env.CODEX_HOME || join27(home, ".codex"), "config.toml");
105618
+ return join28(env.CODEX_HOME || join28(home, ".codex"), "config.toml");
105374
105619
  }
105375
105620
  function hasVapiCodexProfile(contents) {
105376
105621
  const roots = new Set(
@@ -105464,7 +105709,7 @@ function aliasContents(original, tools) {
105464
105709
  }
105465
105710
  async function readOptional(path) {
105466
105711
  try {
105467
- return await readFile29(path, "utf8");
105712
+ return await readFile30(path, "utf8");
105468
105713
  } catch (error61) {
105469
105714
  if (isMissingFile(error61)) return void 0;
105470
105715
  throw error61;
@@ -105486,7 +105731,7 @@ async function codeCommand(argv, json2, io, dependencies) {
105486
105731
  const env = getEnvironment(dependencies);
105487
105732
  const home = dependencies.code?.homedir ?? homedir3();
105488
105733
  const config2 = codexConfigPath(env, home);
105489
- const rcPaths = [join27(home, ".zshrc"), join27(home, ".bashrc")];
105734
+ const rcPaths = [join28(home, ".zshrc"), join28(home, ".bashrc")];
105490
105735
  if (command === "uninstall") {
105491
105736
  const removed = [];
105492
105737
  const previous = await readOptional(config2);
@@ -105610,7 +105855,7 @@ async function codeCommand(argv, json2, io, dependencies) {
105610
105855
 
105611
105856
  // ../cli/src/code-launch.ts
105612
105857
  import { spawn as spawn4 } from "node:child_process";
105613
- import { readFile as readFile30 } from "node:fs/promises";
105858
+ import { readFile as readFile31 } from "node:fs/promises";
105614
105859
  import { constants as constants3, homedir as homedir4 } from "node:os";
105615
105860
  var CLAUDE_MODELS = {
105616
105861
  sonnet: "venice/claude-sonnet-5-5",
@@ -105824,7 +106069,7 @@ function claudeModel(model) {
105824
106069
  async function codexArgs(env, baseURL, model, dependencies) {
105825
106070
  let contents = "";
105826
106071
  try {
105827
- contents = await readFile30(
106072
+ contents = await readFile31(
105828
106073
  codexConfigPath(env, dependencies.code?.homedir ?? homedir4()),
105829
106074
  "utf8"
105830
106075
  );
@@ -105999,7 +106244,7 @@ async function sendConfig(dependencies) {
105999
106244
 
106000
106245
  // ../cli/src/setup.ts
106001
106246
  import { rm as rm6 } from "node:fs/promises";
106002
- import { join as join28 } from "node:path";
106247
+ import { join as join29 } from "node:path";
106003
106248
  var SETUP_ARGUMENT_ERROR = `vapi setup accepts only --no-cloud-backup and --accounts <n> (1-${MAX_RESTORE_ACCOUNTS}); a recovery phrase is typed at the prompt, never passed on the command line.`;
106004
106249
  var VAULT_CHOICE = "Create a new vault, or restore one from a recovery phrase? [new/restore] ";
106005
106250
  async function setupCommand(argv, json2, io, dependencies) {
@@ -106018,18 +106263,24 @@ async function setupCommand(argv, json2, io, dependencies) {
106018
106263
  const steps = [];
106019
106264
  const humanIo = json2 ? stderrIo(io) : io;
106020
106265
  const accountCount = parseAccountCount(parsed.one("--accounts"));
106021
- if (!await fileExists2(paths.config)) {
106266
+ if (!await fileExists3(paths.config)) {
106022
106267
  await writeDefaultConfig(paths.config, process.env, { networks: ["base"] });
106023
106268
  steps.push("config");
106024
106269
  }
106025
106270
  const config2 = await readConfig(paths.config, humanIo);
106271
+ if (!await fileExists3(join29(paths.directory, "vault.json"))) {
106272
+ const os = dependencies.secretBackendProbe ?? (dependencies.secretStore === void 0 ? osSecretStore() : void 0);
106273
+ if (os !== void 0) {
106274
+ await chooseSecretBackend({ home: paths.directory, os, env: getEnvironment(dependencies) });
106275
+ }
106276
+ }
106026
106277
  let store = await openWalletStore(dependencies);
106027
106278
  let vault = "existing";
106028
106279
  let changedVault = false;
106029
106280
  let changedAccount = false;
106030
106281
  let changedLink = false;
106031
106282
  let scannedAddresses;
106032
- if (!await fileExists2(join28(paths.directory, "vault.json"))) {
106283
+ if (!await fileExists3(join29(paths.directory, "vault.json"))) {
106033
106284
  const choice = await vaultChoice(dependencies);
106034
106285
  if (choice === "restore") {
106035
106286
  if (!isInteractive(dependencies)) {
@@ -106117,7 +106368,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
106117
106368
  let scannedAddresses = 0;
106118
106369
  try {
106119
106370
  const restored = await restoreVault({
106120
- path: join28(paths.directory, "vault.json"),
106371
+ path: join29(paths.directory, "vault.json"),
106121
106372
  key: key2,
106122
106373
  phrase: validatedPhrase,
106123
106374
  probe: async (address4) => await readBalance3(address4) > 0n,
@@ -106128,7 +106379,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
106128
106379
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
106129
106380
  });
106130
106381
  names = restored.accounts().map((account) => account.name);
106131
- await rm6(join28(paths.directory, "wallets.json"), { force: true });
106382
+ await rm6(join29(paths.directory, "wallets.json"), { force: true });
106132
106383
  } finally {
106133
106384
  key2.fill(0);
106134
106385
  }
@@ -106246,7 +106497,7 @@ async function withRouterError2(operation) {
106246
106497
 
106247
106498
  // ../cli/src/task.ts
106248
106499
  import { randomUUID as randomUUID6 } from "node:crypto";
106249
- import { readFile as readFile31 } from "node:fs/promises";
106500
+ import { readFile as readFile32 } from "node:fs/promises";
106250
106501
  var TASK_HELP = `Usage:
106251
106502
  vapi task search [--open] [--min <usd>] [--tab trending|new|closing|paid] [--limit <n>] [--json]
106252
106503
  vapi task show <id> [--account <name>] [--json]
@@ -106582,7 +106833,7 @@ async function taskCommandInner(argv, json2, io, dependencies) {
106582
106833
  if (maxAwards !== void 0 && maxAwards > TASK_LIMITS.maxAwardsMax)
106583
106834
  throw new UsageError("--max-awards must be between 1 and 50.");
106584
106835
  if (parsed.one("--webhook") !== void 0) httpsUrl2(parsed.one("--webhook"), "--webhook");
106585
- const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile31(briefPath, "utf8");
106836
+ const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile32(briefPath, "utf8");
106586
106837
  const input2 = {
106587
106838
  title: title.trim(),
106588
106839
  description: brief.trim(),
@@ -108260,7 +108511,7 @@ async function referencedSleep(milliseconds, signal) {
108260
108511
  }
108261
108512
 
108262
108513
  // ../cli/src/vault.ts
108263
- import { join as join29 } from "node:path";
108514
+ import { join as join30 } from "node:path";
108264
108515
  var VAULT_USAGE = "Usage: vapi vault protect|unprotect|lock|unlock|status [--json]";
108265
108516
  var RESTORE_USAGE = "Usage: vapi restore [--accounts <n> | --from-owner [--owner <0x\u2026>]] [--json]";
108266
108517
  var LEGACY_PASSWORD_NOTICE = "VAPI_KEYSTORE_PASSWORD is deprecated for vault passwords; use VAPI_VAULT_PASSWORD instead.";
@@ -108304,13 +108555,13 @@ async function restoreCommand(argv, json2, io, dependencies) {
108304
108555
  }
108305
108556
  const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
108306
108557
  const paths = getVapiPaths();
108307
- const path = join29(paths.directory, "vault.json");
108308
- if (await fileExists2(path)) {
108558
+ const path = join30(paths.directory, "vault.json");
108559
+ if (await fileExists3(path)) {
108309
108560
  throw new Error(
108310
108561
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
108311
108562
  );
108312
108563
  }
108313
- if (!await fileExists2(paths.config)) {
108564
+ if (!await fileExists3(paths.config)) {
108314
108565
  await writeDefaultConfig(paths.config, process.env, { networks: ["base"] });
108315
108566
  }
108316
108567
  const config2 = await readConfig(paths.config, json2 ? quietIo(io) : io);
@@ -108461,7 +108712,7 @@ function requireNoArguments(argv) {
108461
108712
  parseArguments(argv, { valueOptions: /* @__PURE__ */ new Set(), maximumPositionals: 0 });
108462
108713
  }
108463
108714
  function vaultPath() {
108464
- return join29(getVapiPaths().directory, "vault.json");
108715
+ return join30(getVapiPaths().directory, "vault.json");
108465
108716
  }
108466
108717
  function quietIo(io) {
108467
108718
  return { stdout: () => void 0, stderr: io.stderr };
@@ -108912,7 +109163,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
108912
109163
  break;
108913
109164
  case "unlock":
108914
109165
  io.stderr("vapi unlock is now vapi vault unlock; the old name works for one release.");
108915
- if (await fileExists2(join30(getVapiPaths().directory, "vault.json"))) {
109166
+ if (await fileExists3(join31(getVapiPaths().directory, "vault.json"))) {
108916
109167
  parseArguments(args.slice(1), {
108917
109168
  valueOptions: /* @__PURE__ */ new Set([WALLET_OPTION5]),
108918
109169
  maximumPositionals: 0
@@ -109100,7 +109351,7 @@ async function initCommand(argv, json2, io, dependencies) {
109100
109351
  await recordAudit(dependencies, "wallet.create", { wallet: created.name });
109101
109352
  const account = created.account;
109102
109353
  if (!json2) await showRecoveryPhrase(created.recoveryPhrase, io, dependencies);
109103
- if (!await fileExists2(paths.config)) {
109354
+ if (!await fileExists3(paths.config)) {
109104
109355
  await writeDefaultConfig(paths.config, process.env, { networks });
109105
109356
  } else {
109106
109357
  if (enableArc) await enableDefaultNetwork("arc", paths.config);
@@ -109118,7 +109369,7 @@ async function initCommand(argv, json2, io, dependencies) {
109118
109369
  address: account.address,
109119
109370
  accounts,
109120
109371
  config: paths.config,
109121
- vault: join30(paths.directory, "vault.json"),
109372
+ vault: join31(paths.directory, "vault.json"),
109122
109373
  ...configRewrites.length > 0 ? { configRewrites } : {},
109123
109374
  custody: "self",
109124
109375
  warning: CUSTODY_NOTICE,
@@ -109248,7 +109499,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
109248
109499
  await recordAudit(dependencies, "wallet.create", { wallet: created.name });
109249
109500
  const account = created.account;
109250
109501
  if (!json2) await showRecoveryPhrase(created.recoveryPhrase, io, dependencies);
109251
- if (!await fileExists2(paths.config)) {
109502
+ if (!await fileExists3(paths.config)) {
109252
109503
  await writeDefaultConfig(paths.config, process.env, { networks });
109253
109504
  } else {
109254
109505
  if (enableArc) await enableDefaultNetwork("arc", paths.config);
@@ -109257,7 +109508,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
109257
109508
  const result = {
109258
109509
  address: account.address,
109259
109510
  ...account.solana ? { solanaAddress: account.solana.address } : {},
109260
- vault: join30(paths.directory, "vault.json"),
109511
+ vault: join31(paths.directory, "vault.json"),
109261
109512
  ...label === void 0 ? {} : { label },
109262
109513
  spendCaps: created.entry.spendCaps,
109263
109514
  isDefault,
@@ -109297,7 +109548,7 @@ function formatCaps2(caps) {
109297
109548
  function walletListResult(store, wallets, unlocked) {
109298
109549
  return {
109299
109550
  default: store.defaultName ?? null,
109300
- vault: join30(store.home, "vault.json"),
109551
+ vault: join31(store.home, "vault.json"),
109301
109552
  wallets: wallets.map((wallet) => ({
109302
109553
  name: wallet.name,
109303
109554
  ...wallet.address === void 0 ? {} : { address: wallet.address },
@@ -110570,7 +110821,7 @@ function formatClaimed(origin, claimed) {
110570
110821
  }
110571
110822
  var EXPORT_KEY_WARNING = "Anyone with this key can spend the wallet. Never paste it into a website or chat.";
110572
110823
  async function deviceVaultKey2(store, dependencies) {
110573
- const path = join30(store.home, "vault.json");
110824
+ const path = join31(store.home, "vault.json");
110574
110825
  const metadata = await readVaultFileUnlocked(path);
110575
110826
  const secrets = getSecretStore(dependencies);
110576
110827
  const key2 = metadata.protected ? await unlockProtectedVault({
@@ -110663,7 +110914,7 @@ async function backupCommand(argv, json2, io, dependencies) {
110663
110914
  const target = await targetWallet(parsed, dependencies);
110664
110915
  const vaultAccount = await target.store.hasVaultAccount(target.name);
110665
110916
  if (vaultAccount) {
110666
- const vault = await readVaultFileUnlocked(join30(target.store.home, "vault.json"));
110917
+ const vault = await readVaultFileUnlocked(join31(target.store.home, "vault.json"));
110667
110918
  if (vault.accounts.some((account) => account.name === target.name && account.kind === "imported")) {
110668
110919
  throw new KeystoreError(
110669
110920
  `Account ${target.name} was imported and is not recoverable from the vault phrase. Back it up with vapi export-key --account ${target.name}.`
@@ -110740,7 +110991,7 @@ async function importCommand(argv, json2, io, dependencies) {
110740
110991
  const existed = store.has(name);
110741
110992
  if (existed && !parsed.has("--replace")) {
110742
110993
  const address4 = await store.readAddress(name);
110743
- const location = await store.hasVaultAccount(name) ? join30(store.home, "vault.json") : store.pathFor(name);
110994
+ const location = await store.hasVaultAccount(name) ? join31(store.home, "vault.json") : store.pathFor(name);
110744
110995
  throw new Error(
110745
110996
  [
110746
110997
  `Wallet ${name} already exists at ${location}.`,
@@ -110768,7 +111019,7 @@ async function importCommand(argv, json2, io, dependencies) {
110768
111019
  const imported = fromPhrase ? await store.create(name, "", { phrase: secret }) : await store.importKey(name, "", secret);
110769
111020
  await recordAudit(dependencies, "wallet.import", { wallet: imported.name });
110770
111021
  const account = imported.account;
110771
- if (!await fileExists2(paths.config)) {
111022
+ if (!await fileExists3(paths.config)) {
110772
111023
  await writeDefaultConfig(paths.config, process.env, { networks });
110773
111024
  } else {
110774
111025
  if (enableArc) await enableDefaultNetwork("arc", paths.config);
@@ -110776,7 +111027,7 @@ async function importCommand(argv, json2, io, dependencies) {
110776
111027
  const result = {
110777
111028
  address: account.address,
110778
111029
  ...account.solana ? { solanaAddress: account.solana.address } : {},
110779
- vault: join30(paths.directory, "vault.json"),
111030
+ vault: join31(paths.directory, "vault.json"),
110780
111031
  ...previousKeystore ? { previousKeystore } : {},
110781
111032
  message: "Wallet imported. Its encrypted key stays on this machine."
110782
111033
  };
@@ -111384,9 +111635,9 @@ function isHttpUrl2(value) {
111384
111635
  return false;
111385
111636
  }
111386
111637
  }
111387
- async function fileExists2(path) {
111638
+ async function fileExists3(path) {
111388
111639
  try {
111389
- await stat16(path);
111640
+ await stat18(path);
111390
111641
  return true;
111391
111642
  } catch (error61) {
111392
111643
  if (isMissingFile(error61)) return false;
@@ -111408,7 +111659,7 @@ function parseInitNetworks(value) {
111408
111659
 
111409
111660
  // ../cli/src/update-check.ts
111410
111661
  import { lookup } from "node:dns/promises";
111411
- import { mkdir as mkdir22, readFile as readFile32, writeFile as writeFile13 } from "node:fs/promises";
111662
+ import { mkdir as mkdir22, readFile as readFile33, writeFile as writeFile13 } from "node:fs/promises";
111412
111663
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
111413
111664
  var CHECK_TIMEOUT_MS = 1500;
111414
111665
  var LATEST_URL = "https://registry.npmjs.org/vapi-network/latest";
@@ -111452,7 +111703,7 @@ async function latestNotice(options, env, signal) {
111452
111703
  const now = (options.nowMs ?? Date.now)();
111453
111704
  let cached2;
111454
111705
  try {
111455
- const value = JSON.parse(await readFile32(paths.updateCheck, "utf8"));
111706
+ const value = JSON.parse(await readFile33(paths.updateCheck, "utf8"));
111456
111707
  if (isRecord13(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
111457
111708
  cached2 = { checkedAt: value.checkedAt, latest: value.latest };
111458
111709
  }
@@ -111534,14 +111785,14 @@ function isNewerVersion(latest, current) {
111534
111785
 
111535
111786
  // src/client.ts
111536
111787
  import { homedir as homedir5 } from "node:os";
111537
- import { join as join31 } from "node:path";
111788
+ import { join as join32 } from "node:path";
111538
111789
  var ACCOUNT_NOT_LINKED = "Not linked. Run vapi login on this machine, or set VAPI_HOME to a linked home.";
111539
111790
  var DISCOVERY_PATH2 = "/api/call/discovery";
111540
111791
  var warnedWalletOption = false;
111541
111792
  async function createVapiClient(options = {}) {
111542
111793
  if (options.wallet !== void 0) warnWalletOption();
111543
111794
  const env = options.env ?? process.env;
111544
- const home = options.home ?? (env.VAPI_HOME?.trim() || join31(homedir5(), ".vapi"));
111795
+ const home = options.home ?? (env.VAPI_HOME?.trim() || join32(homedir5(), ".vapi"));
111545
111796
  const paths = getVapiPaths(home);
111546
111797
  const requestedName = typeof options.account === "string" ? options.account : options.wallet;
111547
111798
  const injected = typeof options.account === "object" ? options.account : void 0;