@vapi-network/core 0.12.0 → 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
@@ -6603,7 +6603,7 @@ function weierstrass(curveDef) {
6603
6603
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
6604
6604
  if (["recovered", "canonical"].some((k) => k in opts))
6605
6605
  throw new Error("sign() legacy options not supported");
6606
- const { hash: hash4, randomBytes: randomBytes16 } = CURVE;
6606
+ const { hash: hash4, randomBytes: randomBytes17 } = CURVE;
6607
6607
  let { lowS, prehash, extraEntropy: ent } = opts;
6608
6608
  if (lowS == null)
6609
6609
  lowS = true;
@@ -6615,7 +6615,7 @@ function weierstrass(curveDef) {
6615
6615
  const d = normPrivateKeyToScalar(privateKey);
6616
6616
  const seedArgs = [int2octets(d), int2octets(h1int)];
6617
6617
  if (ent != null && ent !== false) {
6618
- const e3 = ent === true ? randomBytes16(Fp.BYTES) : ent;
6618
+ const e3 = ent === true ? randomBytes17(Fp.BYTES) : ent;
6619
6619
  seedArgs.push(ensureBytes("extraEntropy", e3));
6620
6620
  }
6621
6621
  const seed = concatBytes3(...seedArgs);
@@ -44676,9 +44676,9 @@ var X402Error = class extends Error {
44676
44676
  function isValidPaymentId(value) {
44677
44677
  return typeof value === "string" && PAYMENT_ID_PATTERN.test(value);
44678
44678
  }
44679
- function createPaymentId(randomBytes16 = fillRandomBytes) {
44679
+ function createPaymentId(randomBytes17 = fillRandomBytes) {
44680
44680
  const bytes = new Uint8Array(16);
44681
- randomBytes16(bytes);
44681
+ randomBytes17(bytes);
44682
44682
  return `pay_${bytesToHex(bytes).slice(2)}`;
44683
44683
  }
44684
44684
  function buildPaymentExtensions(serverExtensions, options = {}) {
@@ -46082,8 +46082,8 @@ function conciseError(error61) {
46082
46082
  }
46083
46083
 
46084
46084
  // src/account-add.ts
46085
- import { stat as stat8 } from "node:fs/promises";
46086
- import { join as join9 } from "node:path";
46085
+ import { stat as stat10 } from "node:fs/promises";
46086
+ import { join as join10 } from "node:path";
46087
46087
 
46088
46088
  // src/agent-link.ts
46089
46089
  import { createHash } from "node:crypto";
@@ -69588,20 +69588,20 @@ async function promptForSecret(prompt, noTerminalHint) {
69588
69588
  }
69589
69589
 
69590
69590
  // src/wallet-store.ts
69591
- import { randomBytes as randomBytes8 } from "node:crypto";
69591
+ import { randomBytes as randomBytes9 } from "node:crypto";
69592
69592
  import {
69593
69593
  chmod as chmod3,
69594
69594
  lstat as lstat2,
69595
69595
  mkdir as mkdir10,
69596
- open as open7,
69596
+ open as open8,
69597
69597
  readdir as readdir3,
69598
- readFile as readFile11,
69598
+ readFile as readFile12,
69599
69599
  rename as rename7,
69600
- stat as stat7,
69600
+ stat as stat9,
69601
69601
  unlink as unlink6,
69602
69602
  writeFile as writeFile5
69603
69603
  } from "node:fs/promises";
69604
- import { dirname as dirname7, join as join8 } from "node:path";
69604
+ import { dirname as dirname7, join as join9 } from "node:path";
69605
69605
 
69606
69606
  // src/account-movement-lock.ts
69607
69607
  import { randomBytes as randomBytes4 } from "node:crypto";
@@ -69719,497 +69719,16 @@ function isOpenMovementLeg(leg, journalEvidence) {
69719
69719
  // src/secret-store.ts
69720
69720
  import { spawn } from "node:child_process";
69721
69721
  import { existsSync } from "node:fs";
69722
- import { delimiter, isAbsolute, join as join6, win32 } from "node:path";
69723
- var SECRET_STORE_SERVICE = "vapi-network";
69724
- var SECURITY_BINARY = "/usr/bin/security";
69725
- var SECRET_TOOL_BINARY = "secret-tool";
69726
- var WINDOWS_POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-Command", "-"];
69727
- var SECURITY_ITEM_NOT_FOUND = 44;
69728
- var WINDOWS_SECRET_SUCCESS = 0;
69729
- var WINDOWS_SECRET_NOT_FOUND = 2;
69730
- var UNSUPPORTED_PLATFORM = "No OS secret store on this platform yet; use VAPI_KEYSTORE_PASSWORD.";
69731
- var SECRET_TOOL_MISSING = [
69732
- "secret-tool is not installed, so the passphrase cannot be kept in the OS secret store.",
69733
- "Install libsecret-tools (Debian, Ubuntu) or libsecret (Fedora, Arch), or use VAPI_KEYSTORE_PASSWORD."
69734
- ].join(" ");
69735
- var POWERSHELL_MISSING = [
69736
- "Windows PowerShell (powershell.exe) was not found, so the passphrase cannot be kept in the OS secret store.",
69737
- "Use VAPI_KEYSTORE_PASSWORD."
69738
- ].join(" ");
69739
- function secretStore(options = {}) {
69740
- const platform2 = options.platform ?? process.platform;
69741
- const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
69742
- const env = options.env ?? process.env;
69743
- const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
69744
- if (platform2 === "darwin") return keychainStore(platform2, run);
69745
- if (platform2 === "win32") return windowsDataProtectionStore(platform2, run, env, installed);
69746
- if (platform2 === "linux") return libsecretStore(platform2, run, installed);
69747
- return unsupportedStore(platform2);
69748
- }
69749
- function memorySecretStore(initial = {}) {
69750
- const entries = new Map(Object.entries(initial));
69751
- return {
69752
- available: true,
69753
- platform: process.platform,
69754
- description: "an in-memory store",
69755
- async get(name) {
69756
- return entries.get(name);
69757
- },
69758
- async has(name) {
69759
- return entries.has(name);
69760
- },
69761
- async set(name, passphrase) {
69762
- entries.set(name, passphrase);
69763
- },
69764
- async remove(name) {
69765
- return entries.delete(name);
69766
- },
69767
- async list() {
69768
- return [...entries.keys()].sort();
69769
- }
69770
- };
69771
- }
69772
- function keychainStore(platform2, run) {
69773
- const find = async (account, withPassword) => await run(SECURITY_BINARY, [
69774
- "find-generic-password",
69775
- "-a",
69776
- account,
69777
- "-s",
69778
- SECRET_STORE_SERVICE,
69779
- ...withPassword ? ["-w"] : []
69780
- ]);
69781
- const read = async (account, what) => {
69782
- const result = await find(account, true);
69783
- if (result.code === SECURITY_ITEM_NOT_FOUND) return void 0;
69784
- requireSuccess(result, what);
69785
- const value = withoutTrailingNewline(result.stdout);
69786
- return value.length === 0 ? void 0 : value;
69787
- };
69788
- const write = async (account, value, what) => {
69789
- const result = await run(
69790
- SECURITY_BINARY,
69791
- [
69792
- "add-generic-password",
69793
- "-a",
69794
- account,
69795
- "-s",
69796
- SECRET_STORE_SERVICE,
69797
- "-l",
69798
- `${SECRET_STORE_SERVICE} ${account}`,
69799
- "-U",
69800
- "-w"
69801
- ],
69802
- // `security` asks for the password and then for its confirmation.
69803
- `${value}
69804
- ${value}
69805
- `
69806
- );
69807
- requireSuccess(result, what);
69808
- };
69809
- const erase = async (account, what) => {
69810
- const result = await run(SECURITY_BINARY, [
69811
- "delete-generic-password",
69812
- "-a",
69813
- account,
69814
- "-s",
69815
- SECRET_STORE_SERVICE
69816
- ]);
69817
- if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
69818
- requireSuccess(result, what);
69819
- return true;
69820
- };
69821
- const erasePartsAfter = async (account, keep, what) => {
69822
- for (let part = keep + 1; part <= MAX_KEYCHAIN_PARTS; part += 1) {
69823
- if (!await erase(keychainPart(account, part), what)) return;
69824
- }
69825
- };
69826
- return {
69827
- available: true,
69828
- platform: platform2,
69829
- description: "the macOS Keychain",
69830
- async get(name) {
69831
- const account = accountFor(name);
69832
- const what = `read the passphrase of ${name} from the macOS Keychain`;
69833
- const value = await read(account, what);
69834
- const parts = value === void 0 ? void 0 : chunkedPartCount(value);
69835
- if (value === void 0 || parts === void 0) return value;
69836
- let joined = "";
69837
- for (let part = 1; part <= parts; part += 1) {
69838
- const chunk = await read(keychainPart(account, part), what);
69839
- if (chunk === void 0) {
69840
- throw new KeystoreError(
69841
- `The stored secret ${name} is incomplete in the macOS Keychain. Store it again.`
69842
- );
69843
- }
69844
- joined += chunk;
69845
- }
69846
- return joined;
69847
- },
69848
- async has(name) {
69849
- const result = await find(accountFor(name), false);
69850
- if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
69851
- requireSuccess(result, `look up ${name} in the macOS Keychain`);
69852
- return true;
69853
- },
69854
- async set(name, passphrase) {
69855
- requirePassphrase(passphrase);
69856
- const account = accountFor(name);
69857
- const what = `store the passphrase of ${name} in the macOS Keychain`;
69858
- if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
69859
- await write(account, passphrase, what);
69860
- return;
69861
- }
69862
- const chunks = [];
69863
- for (let index2 = 0; index2 < passphrase.length; index2 += KEYCHAIN_CHUNK) {
69864
- chunks.push(passphrase.slice(index2, index2 + KEYCHAIN_CHUNK));
69865
- }
69866
- if (chunks.length > MAX_KEYCHAIN_PARTS) {
69867
- throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
69868
- }
69869
- for (const [index2, chunk] of chunks.entries()) {
69870
- await write(keychainPart(account, index2 + 1), chunk, what);
69871
- }
69872
- await erasePartsAfter(account, chunks.length, what);
69873
- await write(account, `${CHUNKED_MARKER}${chunks.length}`, what);
69874
- },
69875
- async remove(name) {
69876
- const account = accountFor(name);
69877
- const what = `remove the passphrase of ${name} from the macOS Keychain`;
69878
- const found = await find(account, true);
69879
- if (found.code === SECURITY_ITEM_NOT_FOUND) return false;
69880
- requireSuccess(found, what);
69881
- if (chunkedPartCount(withoutTrailingNewline(found.stdout)) !== void 0) {
69882
- await erasePartsAfter(account, 0, what);
69883
- }
69884
- return await erase(account, what);
69885
- }
69886
- };
69887
- }
69888
- var KEYCHAIN_PROMPT_LIMIT = 128;
69889
- var KEYCHAIN_CHUNK = 120;
69890
- var MAX_KEYCHAIN_PARTS = 32;
69891
- var CHUNKED_MARKER = "vapi-chunked:v1:";
69892
- function keychainPart(account, part) {
69893
- return `${account}#${part}`;
69894
- }
69895
- function chunkedPartCount(value) {
69896
- if (!value.startsWith(CHUNKED_MARKER)) return void 0;
69897
- const parts = Number(value.slice(CHUNKED_MARKER.length));
69898
- return Number.isInteger(parts) && parts > 0 && parts <= MAX_KEYCHAIN_PARTS ? parts : void 0;
69899
- }
69900
- function windowsSecretFileName(account) {
69901
- let encoded = "";
69902
- for (let index2 = 0; index2 < account.length; index2 += 1) {
69903
- const character = account[index2];
69904
- if (/^[a-z0-9._#-]$/u.test(character)) {
69905
- encoded += character;
69906
- continue;
69907
- }
69908
- encoded += `%${account.charCodeAt(index2).toString(16).toUpperCase().padStart(4, "0")}`;
69909
- }
69910
- if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(encoded)) {
69911
- encoded = `%${encoded.charCodeAt(0).toString(16).toUpperCase()}${encoded.slice(1)}`;
69912
- }
69913
- return `${encoded}.bin`;
69914
- }
69915
- function windowsDataProtectionStore(platform2, run, env, installed) {
69916
- const powershell = `${env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
69917
- const fileDetails = (name) => {
69918
- const file2 = windowsSecretFileName(accountFor(name));
69919
- return { file: file2, account: file2.slice(0, -".bin".length) };
69920
- };
69921
- const script = (file2, operations) => [
69922
- "$ErrorActionPreference = 'Stop'",
69923
- "try {",
69924
- " Add-Type -AssemblyName System.Security",
69925
- " $dir = Join-Path $env:LOCALAPPDATA 'vapi-network\\secrets'",
69926
- ` $path = Join-Path $dir '${file2}'`,
69927
- ...operations.map((operation) => ` ${operation}`),
69928
- "} catch {",
69929
- " [Console]::Error.WriteLine($_.Exception.Message)",
69930
- " exit 1",
69931
- "}"
69932
- ].join("\n");
69933
- const execute = async (script2) => {
69934
- const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
69935
-
69936
- `);
69937
- requirePowerShell(result);
69938
- return result;
69939
- };
69940
- return {
69941
- available: installed(powershell),
69942
- platform: platform2,
69943
- description: "Windows Data Protection (DPAPI)",
69944
- async get(name) {
69945
- const { file: file2, account } = fileDetails(name);
69946
- const result = await execute(
69947
- script(file2, [
69948
- `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
69949
- "$blob = [System.IO.File]::ReadAllBytes($path)",
69950
- "$bytes = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
69951
- "[Console]::Out.Write([Convert]::ToBase64String($bytes))",
69952
- `exit ${WINDOWS_SECRET_SUCCESS}`
69953
- ])
69954
- );
69955
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return void 0;
69956
- requireSuccess(result, `read the passphrase of ${name} from Windows Data Protection`);
69957
- const value = Buffer.from(result.stdout.trim(), "base64").toString("utf8");
69958
- return value.length === 0 ? void 0 : value;
69959
- },
69960
- async has(name) {
69961
- const { file: file2, account } = fileDetails(name);
69962
- const result = await execute(
69963
- script(file2, [
69964
- `if (Test-Path -LiteralPath $path) { exit ${WINDOWS_SECRET_SUCCESS} }`,
69965
- `[Console]::Error.WriteLine('No stored secret for ${account}.')`,
69966
- `exit ${WINDOWS_SECRET_NOT_FOUND}`
69967
- ])
69968
- );
69969
- if (result.code === WINDOWS_SECRET_SUCCESS) return true;
69970
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
69971
- requireSuccess(result, `look up ${name} in Windows Data Protection`);
69972
- return false;
69973
- },
69974
- async set(name, passphrase) {
69975
- requirePassphrase(passphrase);
69976
- const { file: file2 } = fileDetails(name);
69977
- const value = Buffer.from(passphrase, "utf8").toString("base64");
69978
- const result = await execute(
69979
- script(file2, [
69980
- "[void][System.IO.Directory]::CreateDirectory($dir)",
69981
- `$bytes = [Convert]::FromBase64String('${value}')`,
69982
- "$blob = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
69983
- "[System.IO.File]::WriteAllBytes($path, $blob)",
69984
- `exit ${WINDOWS_SECRET_SUCCESS}`
69985
- ])
69986
- );
69987
- requireSuccess(result, `store the passphrase of ${name} in Windows Data Protection`);
69988
- },
69989
- async remove(name) {
69990
- const { file: file2, account } = fileDetails(name);
69991
- const result = await execute(
69992
- script(file2, [
69993
- `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
69994
- "Remove-Item -LiteralPath $path -Force",
69995
- `exit ${WINDOWS_SECRET_SUCCESS}`
69996
- ])
69997
- );
69998
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
69999
- requireSuccess(result, `remove the passphrase of ${name} from Windows Data Protection`);
70000
- return true;
70001
- }
70002
- };
70003
- }
70004
- function libsecretStore(platform2, run, installed) {
70005
- const lookup = async (name) => {
70006
- const result = await run(SECRET_TOOL_BINARY, [
70007
- "lookup",
70008
- "service",
70009
- SECRET_STORE_SERVICE,
70010
- "account",
70011
- accountFor(name)
70012
- ]);
70013
- requireBinary(result);
70014
- const value = withoutTrailingNewline(result.stdout);
70015
- if (result.code === 0) return value.length === 0 ? void 0 : value;
70016
- if (result.stderr.trim().length === 0) return void 0;
70017
- requireSuccess(result, `read the passphrase of ${name} from the secret service`);
70018
- return void 0;
70019
- };
70020
- return {
70021
- available: installed(SECRET_TOOL_BINARY),
70022
- platform: platform2,
70023
- description: "the libsecret keyring",
70024
- get: lookup,
70025
- async has(name) {
70026
- return await lookup(name) !== void 0;
70027
- },
70028
- async set(name, passphrase) {
70029
- requirePassphrase(passphrase);
70030
- const account = accountFor(name);
70031
- const result = await run(
70032
- SECRET_TOOL_BINARY,
70033
- [
70034
- "store",
70035
- `--label=${SECRET_STORE_SERVICE} ${account}`,
70036
- "service",
70037
- SECRET_STORE_SERVICE,
70038
- "account",
70039
- account
70040
- ],
70041
- `${passphrase}
70042
- `
70043
- );
70044
- requireBinary(result);
70045
- requireSuccess(result, `store the passphrase of ${name} in the secret service`);
70046
- },
70047
- async remove(name) {
70048
- const existed = await lookup(name) !== void 0;
70049
- const result = await run(SECRET_TOOL_BINARY, [
70050
- "clear",
70051
- "service",
70052
- SECRET_STORE_SERVICE,
70053
- "account",
70054
- accountFor(name)
70055
- ]);
70056
- requireBinary(result);
70057
- requireSuccess(result, `remove the passphrase of ${name} from the secret service`);
70058
- return existed;
70059
- }
70060
- };
70061
- }
70062
- function unsupportedStore(platform2) {
70063
- const refuse = () => {
70064
- throw new KeystoreError(UNSUPPORTED_PLATFORM);
70065
- };
70066
- return {
70067
- available: false,
70068
- platform: platform2,
70069
- description: "no OS secret store",
70070
- get: async () => refuse(),
70071
- has: async () => refuse(),
70072
- set: async () => refuse(),
70073
- remove: async () => refuse()
70074
- };
70075
- }
70076
- function accountFor(name) {
70077
- const account = name.trim();
70078
- if (account.length === 0) {
70079
- throw new KeystoreError("A wallet name is needed to reach the OS secret store.");
70080
- }
70081
- return account;
70082
- }
70083
- function requirePassphrase(passphrase) {
70084
- if (passphrase.length === 0) {
70085
- throw new KeystoreError("Keystore passphrase cannot be empty.");
70086
- }
70087
- }
70088
- function requireBinary(result) {
70089
- if (result.notFound === true) throw new KeystoreError(SECRET_TOOL_MISSING);
70090
- }
70091
- function requirePowerShell(result) {
70092
- if (result.notFound === true) throw new KeystoreError(POWERSHELL_MISSING);
70093
- }
70094
- function binaryInstalled(file2, env) {
70095
- if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
70096
- return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join6(directory, file2)));
70097
- }
70098
- function requireSuccess(result, what) {
70099
- if (result.code === 0) return;
70100
- const detail = result.stderr.trim() || result.stdout.trim();
70101
- throw new KeystoreError(
70102
- `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail.length === 0 ? "" : ` ${detail}`}`
70103
- );
70104
- }
70105
- function withoutTrailingNewline(value) {
70106
- return value.replace(/\r?\n$/u, "");
70107
- }
70108
- var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve2) => {
70109
- let stdout = "";
70110
- let stderr2 = "";
70111
- let settled = false;
70112
- const finish = (outcome) => {
70113
- if (settled) return;
70114
- settled = true;
70115
- resolve2(outcome);
70116
- };
70117
- const child = spawn(file2, [...args], {
70118
- detached: platform2 !== "win32",
70119
- stdio: ["pipe", "pipe", "pipe"],
70120
- windowsHide: true
70121
- });
70122
- child.stdout?.setEncoding("utf8");
70123
- child.stdout?.on("data", (chunk) => {
70124
- stdout += chunk;
70125
- });
70126
- child.stderr?.setEncoding("utf8");
70127
- child.stderr?.on("data", (chunk) => {
70128
- stderr2 += chunk;
70129
- });
70130
- child.on("error", (error61) => {
70131
- finish({
70132
- code: null,
70133
- stdout,
70134
- stderr: stderr2,
70135
- ...error61.code === "ENOENT" ? { notFound: true } : {}
70136
- });
70137
- });
70138
- child.on("close", (code) => finish({ code, stdout, stderr: stderr2 }));
70139
- child.stdin?.on("error", () => void 0);
70140
- child.stdin?.end(input2 ?? "");
70141
- });
70142
-
70143
- // src/passphrase.ts
70144
- var PASSPHRASE_ENVIRONMENT_VARIABLE = "VAPI_KEYSTORE_PASSWORD";
70145
- function noPassphraseHint(walletName) {
70146
- return `Set ${PASSPHRASE_ENVIRONMENT_VARIABLE}, or store this wallet's passphrase once with vapi unlock --wallet ${walletName}.`;
70147
- }
70148
- function staleStoredPassphraseMessage(walletName, store) {
70149
- return [
70150
- `The passphrase stored in ${store.description} no longer opens wallet ${walletName}.`,
70151
- `Store the current one with vapi unlock --wallet ${walletName}, or remove it with vapi lock --wallet ${walletName}.`
70152
- ].join(" ");
70153
- }
70154
- async function resolvePassphrase(walletName, options = {}) {
70155
- const env = options.env ?? process.env;
70156
- const fromEnvironment = env[PASSPHRASE_ENVIRONMENT_VARIABLE];
70157
- if (fromEnvironment !== void 0) {
70158
- if (fromEnvironment.length === 0) {
70159
- throw new KeystoreError(`${PASSPHRASE_ENVIRONMENT_VARIABLE} cannot be empty.`);
70160
- }
70161
- return { passphrase: fromEnvironment, source: "environment" };
70162
- }
70163
- if (options.confirm !== true) {
70164
- const stored = await readStored(options.store ?? secretStore(), walletName);
70165
- if (stored !== void 0) return { passphrase: stored, source: "secret-store" };
70166
- }
70167
- const hint = noPassphraseHint(walletName);
70168
- if (options.interactive === false) {
70169
- throw new KeystoreError(
70170
- `No interactive terminal is available for the keystore prompt. ${hint}`
70171
- );
70172
- }
70173
- const prompt = options.prompt ?? promptForSecret;
70174
- const first = await prompt(`Passphrase for ${walletName}: `, hint);
70175
- if (first.length === 0) {
70176
- throw new KeystoreError("Keystore passphrase cannot be empty.");
70177
- }
70178
- if (options.confirm === true) {
70179
- const second = await prompt("Confirm passphrase: ", hint);
70180
- if (first !== second) throw new KeystoreError("Passphrases do not match.");
70181
- }
70182
- return { passphrase: first, source: "prompt" };
70183
- }
70184
- async function readStored(store, walletName) {
70185
- if (!store.available) return void 0;
70186
- try {
70187
- return await store.get(walletName);
70188
- } catch {
70189
- return void 0;
70190
- }
70191
- }
69722
+ import { delimiter, isAbsolute, join as join7, win32 } from "node:path";
70192
69723
 
70193
- // src/receipts.ts
69724
+ // src/file-secret-store.ts
70194
69725
  import { randomBytes as randomBytes6 } from "node:crypto";
70195
- import { mkdir as mkdir7, open as open5, readFile as readFile7, rename as rename4, writeFile as writeFile3 } from "node:fs/promises";
70196
- import { dirname as dirname5 } from "node:path";
69726
+ import { readFile as readFile8, stat as stat7 } from "node:fs/promises";
70197
69727
 
70198
- // src/agent-run.ts
69728
+ // src/vault.ts
70199
69729
  import { randomBytes as randomBytes5 } from "node:crypto";
70200
- var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
70201
- function isRunId(value) {
70202
- return typeof value === "string" && RUN_ID_PATTERN.test(value);
70203
- }
70204
- function createRunId(random = randomBytes5) {
70205
- return `run_${Buffer.from(random(12)).toString("hex")}`;
70206
- }
70207
- var runRefSchema = external_exports.strictObject({
70208
- id: external_exports.string().regex(RUN_ID_PATTERN),
70209
- swarm: external_exports.string().optional(),
70210
- member: external_exports.string().optional(),
70211
- parentRunId: external_exports.string().optional()
70212
- });
69730
+ 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";
69731
+ import { dirname as dirname5 } from "node:path";
70213
69732
 
70214
69733
  // src/wallet-name.ts
70215
69734
  var DEFAULT_WALLET_NAME = "main";
@@ -70222,263 +69741,7 @@ function isWalletName(value) {
70222
69741
  return WALLET_NAME_PATTERN.test(value);
70223
69742
  }
70224
69743
 
70225
- // src/receipts.ts
70226
- var receiptTestHooks;
70227
- function __setReceiptTestHooks(hooks) {
70228
- receiptTestHooks = hooks;
70229
- }
70230
- var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
70231
- async function withReceiptJournalLock(path, operation) {
70232
- return await withFileLock(`${path}.lock`, operation, {
70233
- lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
70234
- });
70235
- }
70236
- var durationSchema = external_exports.number().nonnegative().finite();
70237
- var receiptSchema = external_exports.strictObject({
70238
- id: external_exports.string().min(1),
70239
- timestamp: external_exports.iso.datetime(),
70240
- run: runRefSchema.optional(),
70241
- kind: external_exports.literal("transfer").optional(),
70242
- wallet: walletNameSchema.optional(),
70243
- resourceUrl: external_exports.url(),
70244
- method: external_exports.string().min(1).optional(),
70245
- source: external_exports.string().min(1).optional(),
70246
- provenance: external_exports.array(
70247
- external_exports.strictObject({
70248
- source: external_exports.string().min(1),
70249
- sourceUrl: external_exports.string().optional(),
70250
- ref: external_exports.string().optional()
70251
- })
70252
- ).optional(),
70253
- quote: external_exports.strictObject({
70254
- network: external_exports.string(),
70255
- asset: external_exports.string().optional(),
70256
- amountAtomic: external_exports.string().regex(/^\d+$/),
70257
- payTo: external_exports.string().optional()
70258
- }).optional(),
70259
- payer: external_exports.string().optional(),
70260
- paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
70261
- authorization: external_exports.strictObject({
70262
- from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70263
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
70264
- validBefore: external_exports.string().regex(/^\d+$/)
70265
- }).optional(),
70266
- transfer: external_exports.strictObject({
70267
- to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70268
- toName: external_exports.string().min(1),
70269
- toKind: external_exports.enum(["owner", "account"]),
70270
- amountAtomic: external_exports.string().regex(/^\d+$/),
70271
- network: external_exports.string().min(1),
70272
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
70273
- status: external_exports.enum(["sent", "unknown", "failed"]),
70274
- txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
70275
- replayed: external_exports.boolean(),
70276
- reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
70277
- request: external_exports.strictObject({
70278
- authorization: external_exports.strictObject({
70279
- from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70280
- to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70281
- value: external_exports.string().regex(/^\d+$/),
70282
- validAfter: external_exports.string().regex(/^\d+$/),
70283
- validBefore: external_exports.string().regex(/^\d+$/),
70284
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
70285
- }),
70286
- signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
70287
- }).optional()
70288
- }).optional(),
70289
- settlement: external_exports.strictObject({
70290
- outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
70291
- transaction: external_exports.string().optional(),
70292
- explorerUrl: external_exports.url().optional(),
70293
- evidence: external_exports.unknown().optional()
70294
- }).optional(),
70295
- latencyMs: external_exports.number().nonnegative().finite().optional(),
70296
- status: external_exports.number().int().min(100).max(599).optional(),
70297
- error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
70298
- phases: external_exports.strictObject({
70299
- discoverMs: durationSchema.optional(),
70300
- quoteMs: durationSchema.optional(),
70301
- signMs: durationSchema.optional(),
70302
- requestMs: durationSchema.optional(),
70303
- settleMs: durationSchema.optional()
70304
- }).optional(),
70305
- listing: external_exports.strictObject({
70306
- name: external_exports.string().min(1).optional(),
70307
- providerHost: external_exports.string().min(1).optional(),
70308
- source: external_exports.string().min(1)
70309
- }).optional(),
70310
- retry: external_exports.number().int().nonnegative().optional(),
70311
- policy: external_exports.strictObject({
70312
- maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
70313
- capsApplied: external_exports.boolean()
70314
- }).optional(),
70315
- client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
70316
- outcome: external_exports.enum([
70317
- "paid",
70318
- "signed_in",
70319
- "declined_policy",
70320
- "failed_request",
70321
- "settlement_rejected",
70322
- "settlement_unknown"
70323
- ]).optional()
70324
- });
70325
- function parseReceipt(value) {
70326
- const receipt = receiptSchema.parse(value);
70327
- const transaction = receipt.settlement?.transaction;
70328
- const network = receipt.quote?.network;
70329
- const explorerUrl = transaction === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction);
70330
- if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
70331
- return receipt;
70332
- }
70333
- return {
70334
- ...receipt,
70335
- settlement: {
70336
- outcome: receipt.settlement.outcome,
70337
- ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
70338
- explorerUrl,
70339
- ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
70340
- }
70341
- };
70342
- }
70343
- async function appendReceipt(receipt, path = getVapiPaths().receipts, options = {}) {
70344
- const parsed = parseReceipt(
70345
- receipt.wallet === void 0 && options.wallet !== void 0 ? { ...receipt, wallet: options.wallet } : receipt
70346
- );
70347
- await withReceiptJournalLock(path, async () => {
70348
- await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70349
- const handle = await open5(path, "a", 384);
70350
- try {
70351
- await handle.writeFile(`${JSON.stringify(parsed)}
70352
- `, "utf8");
70353
- } finally {
70354
- await handle.close();
70355
- }
70356
- });
70357
- return parsed;
70358
- }
70359
- async function readReceipts(path = getVapiPaths().receipts, options = {}) {
70360
- let raw;
70361
- try {
70362
- raw = await readFile7(path, "utf8");
70363
- } catch (error61) {
70364
- if (isMissingFile(error61)) return [];
70365
- throw error61;
70366
- }
70367
- const records = coalesceTransferReceiptRevisions(
70368
- raw.split("\n").filter((line) => line.trim().length > 0).map((line, index2) => {
70369
- try {
70370
- return parseReceipt(JSON.parse(line));
70371
- } catch (error61) {
70372
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70373
- }
70374
- })
70375
- );
70376
- const filtered = options.wallet === void 0 ? records : filterReceiptsByWallet(records, options.wallet);
70377
- const limit = options.limit;
70378
- if (limit === void 0) return filtered;
70379
- if (!Number.isSafeInteger(limit) || limit < 0)
70380
- throw new Error("Receipt limit must be a non-negative integer.");
70381
- return limit === 0 ? [] : filtered.slice(-limit);
70382
- }
70383
- function coalesceTransferReceiptRevisions(receipts) {
70384
- const coalesced = [];
70385
- const transferIndexes = /* @__PURE__ */ new Map();
70386
- for (const receipt of receipts) {
70387
- const existing = receipt.kind === "transfer" ? transferIndexes.get(receipt.id) : void 0;
70388
- if (existing === void 0) {
70389
- if (receipt.kind === "transfer") transferIndexes.set(receipt.id, coalesced.length);
70390
- coalesced.push(receipt);
70391
- } else {
70392
- coalesced[existing] = receipt;
70393
- }
70394
- }
70395
- return coalesced;
70396
- }
70397
- function receiptWallet(receipt) {
70398
- return receipt.wallet ?? DEFAULT_WALLET_NAME;
70399
- }
70400
- function filterReceiptsByWallet(receipts, name) {
70401
- return receipts.filter((receipt) => receiptWallet(receipt) === name);
70402
- }
70403
- async function renameReceiptWallet(from16, to, path = getVapiPaths().receipts) {
70404
- return await withReceiptJournalLock(path, async () => {
70405
- let raw;
70406
- try {
70407
- raw = await readFile7(path, "utf8");
70408
- } catch (error61) {
70409
- if (isMissingFile(error61)) return 0;
70410
- throw error61;
70411
- }
70412
- let changed = 0;
70413
- const lines = raw.split("\n").map((line, index2) => {
70414
- if (line.trim().length === 0) return line;
70415
- let parsed;
70416
- try {
70417
- parsed = JSON.parse(line);
70418
- } catch (error61) {
70419
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70420
- }
70421
- const current = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "wallet") : void 0;
70422
- if ((typeof current === "string" ? current : DEFAULT_WALLET_NAME) !== from16) return line;
70423
- changed += 1;
70424
- return JSON.stringify(parseReceipt({ ...parsed, wallet: to }));
70425
- });
70426
- if (changed === 0) return 0;
70427
- await receiptTestHooks?.beforeRenameReplace?.(path);
70428
- await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70429
- const temporaryPath = `${path}.${process.pid}.${randomBytes6(6).toString("hex")}.tmp`;
70430
- await writeFile3(temporaryPath, lines.join("\n"), {
70431
- encoding: "utf8",
70432
- mode: 384,
70433
- flag: "wx"
70434
- });
70435
- await rename4(temporaryPath, path);
70436
- return changed;
70437
- });
70438
- }
70439
-
70440
- // src/transfer-journal.ts
70441
- import { readFile as readFile8 } from "node:fs/promises";
70442
- async function readTransferJournal(home, from16, nonce) {
70443
- let raw;
70444
- try {
70445
- raw = await readFile8(getVapiPaths(home).receipts, "utf8");
70446
- } catch (error61) {
70447
- if (isMissingFile(error61)) return { signed: false };
70448
- throw error61;
70449
- }
70450
- let latest;
70451
- let request;
70452
- for (const [index2, line] of raw.split("\n").entries()) {
70453
- if (!line.trim()) continue;
70454
- let receipt;
70455
- try {
70456
- receipt = parseReceipt(JSON.parse(line));
70457
- } catch (error61) {
70458
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70459
- }
70460
- if (receiptWallet(receipt) !== from16 || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
70461
- continue;
70462
- }
70463
- latest = receipt;
70464
- if (receipt.transfer.request !== void 0) request = receipt;
70465
- }
70466
- return {
70467
- signed: latest !== void 0,
70468
- ...latest === void 0 ? {} : { latest },
70469
- ...request === void 0 ? {} : { request },
70470
- ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
70471
- ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
70472
- };
70473
- }
70474
-
70475
- // src/vault-key.ts
70476
- import { randomBytes as cryptoRandomBytes } from "node:crypto";
70477
-
70478
69744
  // src/vault.ts
70479
- import { randomBytes as randomBytes7 } from "node:crypto";
70480
- 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";
70481
- import { dirname as dirname6 } from "node:path";
70482
69745
  var VaultError = class extends Error {
70483
69746
  code;
70484
69747
  constructor(code, message, options) {
@@ -70789,280 +70052,1261 @@ async function createVault(args) {
70789
70052
  } catch (error61) {
70790
70053
  throw asVaultError(error61, "corrupt", "Unable to create the vault.");
70791
70054
  }
70792
- }
70793
- async function openVault(args) {
70794
- assertVaultKey(args.key);
70795
- return new DeviceVault(args, await readVaultFile(args.path, args.key));
70796
- }
70797
- async function reinstateVaultAccount(args) {
70798
- const parsedAccount = storedAccountSchema.safeParse(args.account);
70799
- if (!parsedAccount.success) {
70800
- throw new VaultError("corrupt", "The stored vault account has an invalid structure.", {
70801
- cause: parsedAccount.error
70802
- });
70055
+ }
70056
+ async function openVault(args) {
70057
+ assertVaultKey(args.key);
70058
+ return new DeviceVault(args, await readVaultFile(args.path, args.key));
70059
+ }
70060
+ async function reinstateVaultAccount(args) {
70061
+ const parsedAccount = storedAccountSchema.safeParse(args.account);
70062
+ if (!parsedAccount.success) {
70063
+ throw new VaultError("corrupt", "The stored vault account has an invalid structure.", {
70064
+ cause: parsedAccount.error
70065
+ });
70066
+ }
70067
+ assertVaultKey(args.key);
70068
+ try {
70069
+ return await withVaultLock(args.path, async () => {
70070
+ const file2 = await readVaultFile(args.path, args.key);
70071
+ const account = parsedAccount.data;
70072
+ assertAvailableName(file2, account.name);
70073
+ if (account.kind === "derived" && file2.accounts.some(
70074
+ (candidate) => candidate.kind === "derived" && candidate.index === account.index
70075
+ )) {
70076
+ throw new VaultError("name_taken", "A vault account already uses that derived index.");
70077
+ }
70078
+ if (account.kind === "derived") validateStoredDerivedAccount(args.key, file2, account);
70079
+ else validateStoredImportedAccount(args.key, account);
70080
+ const updated = parseVaultFile(
70081
+ JSON.stringify({
70082
+ ...file2,
70083
+ accounts: [...file2.accounts, account],
70084
+ ...account.kind === "derived" ? { nextDerivedIndex: Math.max(nextDerivedIndex(file2), account.index + 1) } : {}
70085
+ })
70086
+ );
70087
+ await writeVaultFile(args.path, updated);
70088
+ return copyAccount(account);
70089
+ });
70090
+ } catch (error61) {
70091
+ throw asVaultError(error61, "corrupt", "Unable to reinstate the vault account.");
70092
+ }
70093
+ }
70094
+ function assertVaultKey(key) {
70095
+ if (key.byteLength !== 32) {
70096
+ throw new VaultError("bad_key", "A device vault key must contain exactly 32 bytes.");
70097
+ }
70098
+ }
70099
+ function assertAccountName(name) {
70100
+ const parsed = walletNameSchema.safeParse(name);
70101
+ if (!parsed.success) {
70102
+ throw new VaultError("name_taken", "The vault account name is not valid.", {
70103
+ cause: parsed.error
70104
+ });
70105
+ }
70106
+ }
70107
+ function assertAvailableName(file2, name) {
70108
+ assertAccountName(name);
70109
+ if (file2.accounts.some((account) => account.name === name)) {
70110
+ throw new VaultError("name_taken", "A vault account already has that name.");
70111
+ }
70112
+ }
70113
+ function nextDerivedIndex(file2) {
70114
+ let next = file2.nextDerivedIndex ?? 0;
70115
+ for (const account of file2.accounts) {
70116
+ if (account.kind === "derived") next = Math.max(next, account.index + 1);
70117
+ }
70118
+ return next;
70119
+ }
70120
+ function copyAccount(account) {
70121
+ if (account.kind === "derived") return { ...account };
70122
+ return {
70123
+ name: account.name,
70124
+ kind: account.kind,
70125
+ address: account.address,
70126
+ createdAt: account.createdAt
70127
+ };
70128
+ }
70129
+ function sealField(key, plaintext) {
70130
+ const { nonce, ciphertext, tag } = encryptWithKey(key, plaintext);
70131
+ return [nonce, ciphertext, tag].map((part) => part.toString("base64url")).join(".");
70132
+ }
70133
+ function openField(key, value) {
70134
+ const [nonce = "", ciphertext = "", tag = ""] = value.split(".");
70135
+ return decryptWithKey(key, {
70136
+ nonce: Buffer.from(nonce, "base64url"),
70137
+ ciphertext: Buffer.from(ciphertext, "base64url"),
70138
+ tag: Buffer.from(tag, "base64url")
70139
+ });
70140
+ }
70141
+ function decryptField(key, value) {
70142
+ try {
70143
+ return openField(key, value);
70144
+ } catch (error61) {
70145
+ throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70146
+ cause: error61
70147
+ });
70148
+ }
70149
+ }
70150
+ function decryptPhraseForOpen(key, phrase) {
70151
+ try {
70152
+ return openField(key, phrase);
70153
+ } catch (error61) {
70154
+ throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70155
+ cause: error61
70156
+ });
70157
+ }
70158
+ }
70159
+ function validateStoredImportedAccount(key, account) {
70160
+ let plaintext;
70161
+ try {
70162
+ plaintext = decryptField(key, account.key);
70163
+ if (plaintext.byteLength !== 32) {
70164
+ throw new VaultError("bad_key", "The stored imported key has the wrong length.");
70165
+ }
70166
+ let address2;
70167
+ try {
70168
+ address2 = privateKeyToAccount(`0x${plaintext.toString("hex")}`).address;
70169
+ } catch (error61) {
70170
+ throw new VaultError("bad_key", "The stored imported key is not valid.", {
70171
+ cause: error61
70172
+ });
70173
+ }
70174
+ if (address2.toLowerCase() !== account.address.toLowerCase()) {
70175
+ throw new VaultError("bad_key", "The stored imported key does not match its address.");
70176
+ }
70177
+ } finally {
70178
+ plaintext?.fill(0);
70179
+ }
70180
+ }
70181
+ function validateStoredDerivedAccount(key, file2, account) {
70182
+ const plaintext = decryptField(key, file2.phrase);
70183
+ let seed;
70184
+ try {
70185
+ seed = phraseToSeed(plaintext.toString("utf8"));
70186
+ const address2 = privateKeyToAccount(
70187
+ deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${account.index}`)
70188
+ ).address;
70189
+ if (address2.toLowerCase() !== account.address.toLowerCase()) {
70190
+ throw new VaultError("bad_key", "The stored derived account does not match this vault.");
70191
+ }
70192
+ } finally {
70193
+ seed?.fill(0);
70194
+ plaintext.fill(0);
70195
+ }
70196
+ }
70197
+ function parseVaultFile(raw) {
70198
+ let value;
70199
+ try {
70200
+ value = JSON.parse(raw);
70201
+ } catch (error61) {
70202
+ throw new VaultError("corrupt", "The vault file is not valid JSON.", { cause: error61 });
70203
+ }
70204
+ const parsed = vaultFileSchema.safeParse(value);
70205
+ if (!parsed.success) {
70206
+ throw new VaultError("corrupt", "The vault file has an invalid structure.", {
70207
+ cause: parsed.error
70208
+ });
70209
+ }
70210
+ if (parsed.data.protected !== (parsed.data.wrappedKey !== void 0)) {
70211
+ throw new VaultError("corrupt", "The vault protection metadata is inconsistent.");
70212
+ }
70213
+ const names = /* @__PURE__ */ new Set();
70214
+ const indexes = /* @__PURE__ */ new Set();
70215
+ for (const account of parsed.data.accounts) {
70216
+ if (names.has(account.name)) {
70217
+ throw new VaultError("corrupt", "The vault file contains duplicate account names.");
70218
+ }
70219
+ names.add(account.name);
70220
+ if (account.kind === "derived") {
70221
+ if (indexes.has(account.index)) {
70222
+ throw new VaultError("corrupt", "The vault file contains duplicate derived indexes.");
70223
+ }
70224
+ indexes.add(account.index);
70225
+ }
70226
+ }
70227
+ return parsed.data;
70228
+ }
70229
+ async function readVaultFile(path, key) {
70230
+ const file2 = await readVaultFileUnlocked(path);
70231
+ const plaintext = decryptPhraseForOpen(key, file2.phrase);
70232
+ try {
70233
+ try {
70234
+ validateRecoveryPhrase(plaintext.toString("utf8"));
70235
+ } catch (error61) {
70236
+ throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
70237
+ cause: error61
70238
+ });
70239
+ }
70240
+ } finally {
70241
+ plaintext.fill(0);
70242
+ }
70243
+ return file2;
70244
+ }
70245
+ async function readVaultFileUnlocked(path) {
70246
+ let raw;
70247
+ try {
70248
+ raw = await readFile7(path, "utf8");
70249
+ } catch (error61) {
70250
+ if (isMissingFile2(error61)) {
70251
+ throw new VaultError("not_found", "No vault file was found at the requested path.", {
70252
+ cause: error61
70253
+ });
70254
+ }
70255
+ throw new VaultError("corrupt", "Unable to read the vault file.", { cause: error61 });
70256
+ }
70257
+ return parseVaultFile(raw);
70258
+ }
70259
+ async function refuseExistingVault(path) {
70260
+ try {
70261
+ await stat6(path);
70262
+ } catch (error61) {
70263
+ if (isMissingFile2(error61)) return;
70264
+ throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
70265
+ cause: error61
70266
+ });
70267
+ }
70268
+ throw new VaultError("corrupt", "A vault already exists at the requested path.");
70269
+ }
70270
+ async function writeVaultFile(path, file2) {
70271
+ await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70272
+ const temporaryPath = `${path}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
70273
+ try {
70274
+ await writeFile3(temporaryPath, `${JSON.stringify(file2, null, 2)}
70275
+ `, {
70276
+ encoding: "utf8",
70277
+ mode: 384,
70278
+ flag: "wx"
70279
+ });
70280
+ await rename4(temporaryPath, path);
70281
+ } catch (error61) {
70282
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
70283
+ throw error61;
70284
+ }
70285
+ }
70286
+ async function withVaultLock(path, operation) {
70287
+ await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70288
+ const lockPath = `${path}.lock`;
70289
+ const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
70290
+ let handle;
70291
+ while (!handle) {
70292
+ try {
70293
+ handle = await open5(lockPath, "wx", 384);
70294
+ } catch (error61) {
70295
+ if (!isExistingFile(error61)) throw error61;
70296
+ await removeStaleVaultLock(lockPath);
70297
+ if (Date.now() >= deadline) {
70298
+ throw new VaultError("corrupt", "Timed out waiting for the vault lock.");
70299
+ }
70300
+ await new Promise((resolve2) => setTimeout(resolve2, 20));
70301
+ }
70302
+ }
70303
+ try {
70304
+ return await operation();
70305
+ } finally {
70306
+ await handle.close();
70307
+ await unlink4(lockPath).catch(() => void 0);
70308
+ }
70309
+ }
70310
+ async function removeStaleVaultLock(path) {
70311
+ try {
70312
+ const metadata = await stat6(path);
70313
+ if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
70314
+ } catch (error61) {
70315
+ if (!isMissingFile2(error61)) throw error61;
70316
+ }
70317
+ }
70318
+ function isMissingFile2(error61) {
70319
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
70320
+ }
70321
+ function isExistingFile(error61) {
70322
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "EEXIST";
70323
+ }
70324
+ function asVaultError(error61, code, message) {
70325
+ return error61 instanceof VaultError ? error61 : new VaultError(code, message, { cause: error61 });
70326
+ }
70327
+
70328
+ // src/file-secret-store.ts
70329
+ var FILE_SECRET_STORE_PASSWORD_ENV = "VAPI_VAULT_PASSWORD";
70330
+ var FILE_SECRET_STORE_MIN_PASSWORD = 12;
70331
+ var CHECK_VALUE = "vapi-network file secret store";
70332
+ var sealedSchema = external_exports.object({ nonce: external_exports.string(), ciphertext: external_exports.string(), tag: external_exports.string() }).strict();
70333
+ var fileSchema = external_exports.object({
70334
+ v: external_exports.literal(1),
70335
+ salt: external_exports.string(),
70336
+ check: sealedSchema,
70337
+ entries: external_exports.record(external_exports.string(), sealedSchema)
70338
+ }).strict();
70339
+ async function createFileSecretStore(options) {
70340
+ const password = passwordFrom(options.env);
70341
+ if (password.length < FILE_SECRET_STORE_MIN_PASSWORD) {
70342
+ throw new KeystoreError(
70343
+ `${FILE_SECRET_STORE_PASSWORD_ENV} must be at least ${FILE_SECRET_STORE_MIN_PASSWORD} characters.`
70344
+ );
70345
+ }
70346
+ await withVaultLock(options.path, async () => {
70347
+ let exists = true;
70348
+ try {
70349
+ await stat7(options.path);
70350
+ } catch (error61) {
70351
+ if (!isMissingFile(error61)) throw error61;
70352
+ exists = false;
70353
+ }
70354
+ if (exists) {
70355
+ await withKey(options.path, options.env, async () => void 0);
70356
+ return;
70357
+ }
70358
+ const salt = randomBytes6(32);
70359
+ const key = await deriveScryptKey(password, salt);
70360
+ try {
70361
+ await writeJsonAtomic(
70362
+ options.path,
70363
+ {
70364
+ v: 1,
70365
+ salt: salt.toString("base64"),
70366
+ check: seal(key, CHECK_VALUE),
70367
+ entries: {}
70368
+ },
70369
+ { mode: 384 }
70370
+ );
70371
+ } finally {
70372
+ key.fill(0);
70373
+ }
70374
+ });
70375
+ }
70376
+ function fileSecretStore(options) {
70377
+ const env = options.env ?? process.env;
70378
+ const write = async (change) => await withVaultLock(
70379
+ options.path,
70380
+ async () => await withKey(options.path, env, async (file2, key) => {
70381
+ const changed = change(file2, key);
70382
+ if (changed) await writeJsonAtomic(options.path, file2, { mode: 384 });
70383
+ return changed;
70384
+ })
70385
+ );
70386
+ const get = async (name) => await withKey(options.path, env, async (file2, key) => {
70387
+ const sealed = Object.hasOwn(file2.entries, name) ? file2.entries[name] : void 0;
70388
+ return sealed === void 0 ? void 0 : open6(key, sealed);
70389
+ });
70390
+ return {
70391
+ // A locked backend still exists; it must never enable a plaintext fallback.
70392
+ available: true,
70393
+ platform: process.platform,
70394
+ description: "the encrypted vAPI secrets file",
70395
+ get,
70396
+ async has(name) {
70397
+ return await get(name) !== void 0;
70398
+ },
70399
+ async set(name, value) {
70400
+ if (name === "__proto__") {
70401
+ throw new KeystoreError("The secret name is reserved in the encrypted vAPI secrets file.");
70402
+ }
70403
+ await write((file2, key) => {
70404
+ file2.entries[name] = seal(key, value);
70405
+ return true;
70406
+ });
70407
+ },
70408
+ async remove(name) {
70409
+ return await write((file2) => {
70410
+ if (!Object.hasOwn(file2.entries, name)) return false;
70411
+ delete file2.entries[name];
70412
+ return true;
70413
+ });
70414
+ }
70415
+ };
70416
+ }
70417
+ async function withKey(path, env, operation) {
70418
+ const file2 = await readStoredFile(path);
70419
+ const key = await deriveScryptKey(passwordFrom(env), Buffer.from(file2.salt, "base64"));
70420
+ try {
70421
+ if (open6(key, file2.check) !== CHECK_VALUE) throw wrongPassword();
70422
+ return await operation(file2, key);
70423
+ } finally {
70424
+ key.fill(0);
70425
+ }
70426
+ }
70427
+ function passwordFrom(env) {
70428
+ const password = (env ?? process.env)[FILE_SECRET_STORE_PASSWORD_ENV];
70429
+ if (!password) {
70430
+ throw new KeystoreError(
70431
+ `This vault keeps its secrets in an encrypted file. Set ${FILE_SECRET_STORE_PASSWORD_ENV} to open it.`
70432
+ );
70433
+ }
70434
+ return password;
70435
+ }
70436
+ async function readStoredFile(path) {
70437
+ let raw;
70438
+ try {
70439
+ raw = await readFile8(path, "utf8");
70440
+ } catch (error61) {
70441
+ throw new KeystoreError("The vAPI secrets file is missing. Run vapi setup again.", {
70442
+ cause: error61
70443
+ });
70444
+ }
70445
+ let value;
70446
+ try {
70447
+ value = JSON.parse(raw);
70448
+ } catch {
70449
+ throw new KeystoreError("The vAPI secrets file is damaged.");
70450
+ }
70451
+ const parsed = fileSchema.safeParse(value);
70452
+ if (!parsed.success) throw new KeystoreError("The vAPI secrets file is damaged.");
70453
+ return parsed.data;
70454
+ }
70455
+ function seal(key, value) {
70456
+ const { nonce, ciphertext, tag } = encryptWithKey(key, Buffer.from(value, "utf8"));
70457
+ return {
70458
+ nonce: nonce.toString("base64"),
70459
+ ciphertext: ciphertext.toString("base64"),
70460
+ tag: tag.toString("base64")
70461
+ };
70462
+ }
70463
+ function open6(key, sealed) {
70464
+ try {
70465
+ return decryptWithKey(key, {
70466
+ nonce: Buffer.from(sealed.nonce, "base64"),
70467
+ ciphertext: Buffer.from(sealed.ciphertext, "base64"),
70468
+ tag: Buffer.from(sealed.tag, "base64")
70469
+ }).toString("utf8");
70470
+ } catch (error61) {
70471
+ throw wrongPassword(error61);
70472
+ }
70473
+ }
70474
+ function wrongPassword(cause) {
70475
+ return new KeystoreError(`Wrong ${FILE_SECRET_STORE_PASSWORD_ENV} for the vAPI secrets file.`, {
70476
+ cause
70477
+ });
70478
+ }
70479
+
70480
+ // src/secret-backend.ts
70481
+ import { readFileSync } from "node:fs";
70482
+ import { stat as stat8 } from "node:fs/promises";
70483
+ import { join as join6 } from "node:path";
70484
+ var PROBE_ACCOUNT = "setup-probe";
70485
+ var pinSchema = external_exports.object({ v: external_exports.literal(1), backend: external_exports.enum(["os", "file"]) }).strict();
70486
+ function secretBackendPath(home = getVapiPaths().directory) {
70487
+ return join6(home, "secret-store.json");
70488
+ }
70489
+ function secretsFilePath(home = getVapiPaths().directory) {
70490
+ return join6(home, "secrets.json");
70491
+ }
70492
+ function readSecretBackend(home = getVapiPaths().directory) {
70493
+ const path = secretBackendPath(home);
70494
+ try {
70495
+ const parsed = pinSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
70496
+ if (parsed.success) return parsed.data.backend;
70497
+ } catch (error61) {
70498
+ if (isMissingFile(error61)) return "os";
70499
+ }
70500
+ throw new KeystoreError(`The vAPI secret-store pin at ${path} is damaged.`);
70501
+ }
70502
+ async function chooseSecretBackend(options) {
70503
+ const env = options.env ?? process.env;
70504
+ const osWorks = options.os.platform !== "linux" || await osStoreWorks(options.os);
70505
+ const path = secretBackendPath(options.home);
70506
+ return await withVaultLock(path, async () => {
70507
+ if (await fileExists(path)) return readSecretBackend(options.home);
70508
+ if (await fileExists(join6(options.home, "vault.json"))) return "os";
70509
+ let backend;
70510
+ if (osWorks) {
70511
+ backend = "os";
70512
+ } else if (env[FILE_SECRET_STORE_PASSWORD_ENV]) {
70513
+ await createFileSecretStore({ path: secretsFilePath(options.home), env });
70514
+ backend = "file";
70515
+ } else {
70516
+ throw new KeystoreError(
70517
+ [
70518
+ `This machine has no working keyring (${options.os.description}).`,
70519
+ `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,`,
70520
+ "or run vapi on your own computer, or connect Claude from https://api.vapinetwork.ai/connect."
70521
+ ].join(" ")
70522
+ );
70523
+ }
70524
+ await writeJsonAtomic(path, { v: 1, backend }, { mode: 384 });
70525
+ return backend;
70526
+ });
70527
+ }
70528
+ async function fileExists(path) {
70529
+ try {
70530
+ await stat8(path);
70531
+ return true;
70532
+ } catch (error61) {
70533
+ if (isMissingFile(error61)) return false;
70534
+ throw error61;
70535
+ }
70536
+ }
70537
+ async function osStoreWorks(store) {
70538
+ if (!store.available) return false;
70539
+ try {
70540
+ try {
70541
+ await store.set(PROBE_ACCOUNT, "ok");
70542
+ return await store.get(PROBE_ACCOUNT) === "ok";
70543
+ } finally {
70544
+ await store.remove(PROBE_ACCOUNT);
70545
+ }
70546
+ } catch {
70547
+ return false;
70548
+ }
70549
+ }
70550
+
70551
+ // src/secret-store.ts
70552
+ var SECRET_STORE_SERVICE = "vapi-network";
70553
+ var SECURITY_BINARY = "/usr/bin/security";
70554
+ var SECRET_TOOL_BINARY = "secret-tool";
70555
+ var WINDOWS_POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-Command", "-"];
70556
+ var SECURITY_ITEM_NOT_FOUND = 44;
70557
+ var WINDOWS_SECRET_SUCCESS = 0;
70558
+ var WINDOWS_SECRET_NOT_FOUND = 2;
70559
+ var UNSUPPORTED_PLATFORM = "No OS secret store on this platform yet; use VAPI_KEYSTORE_PASSWORD.";
70560
+ var SECRET_TOOL_MISSING = [
70561
+ "secret-tool is not installed, so the passphrase cannot be kept in the OS secret store.",
70562
+ "Install libsecret-tools (Debian, Ubuntu) or libsecret (Fedora, Arch), or use VAPI_KEYSTORE_PASSWORD."
70563
+ ].join(" ");
70564
+ var POWERSHELL_MISSING = [
70565
+ "Windows PowerShell (powershell.exe) was not found, so the passphrase cannot be kept in the OS secret store.",
70566
+ "Use VAPI_KEYSTORE_PASSWORD."
70567
+ ].join(" ");
70568
+ function secretStore(options = {}) {
70569
+ const home = options.home ?? getVapiPaths().directory;
70570
+ if (readSecretBackend(home) === "file") {
70571
+ return fileSecretStore({ path: secretsFilePath(home), env: options.env ?? process.env });
70572
+ }
70573
+ return osSecretStore(options);
70574
+ }
70575
+ function osSecretStore(options = {}) {
70576
+ const platform2 = options.platform ?? process.platform;
70577
+ const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
70578
+ const env = options.env ?? process.env;
70579
+ const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
70580
+ if (platform2 === "darwin") return keychainStore(platform2, run);
70581
+ if (platform2 === "win32") return windowsDataProtectionStore(platform2, run, env, installed);
70582
+ if (platform2 === "linux") return libsecretStore(platform2, run, installed);
70583
+ return unsupportedStore(platform2);
70584
+ }
70585
+ function memorySecretStore(initial = {}) {
70586
+ const entries = new Map(Object.entries(initial));
70587
+ return {
70588
+ available: true,
70589
+ platform: process.platform,
70590
+ description: "an in-memory store",
70591
+ async get(name) {
70592
+ return entries.get(name);
70593
+ },
70594
+ async has(name) {
70595
+ return entries.has(name);
70596
+ },
70597
+ async set(name, passphrase) {
70598
+ entries.set(name, passphrase);
70599
+ },
70600
+ async remove(name) {
70601
+ return entries.delete(name);
70602
+ },
70603
+ async list() {
70604
+ return [...entries.keys()].sort();
70605
+ }
70606
+ };
70607
+ }
70608
+ function keychainStore(platform2, run) {
70609
+ const find = async (account, withPassword) => await run(SECURITY_BINARY, [
70610
+ "find-generic-password",
70611
+ "-a",
70612
+ account,
70613
+ "-s",
70614
+ SECRET_STORE_SERVICE,
70615
+ ...withPassword ? ["-w"] : []
70616
+ ]);
70617
+ const read = async (account, what) => {
70618
+ const result = await find(account, true);
70619
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return void 0;
70620
+ requireSuccess(result, what);
70621
+ const value = withoutTrailingNewline(result.stdout);
70622
+ return value.length === 0 ? void 0 : value;
70623
+ };
70624
+ const write = async (account, value, what) => {
70625
+ const result = await run(
70626
+ SECURITY_BINARY,
70627
+ [
70628
+ "add-generic-password",
70629
+ "-a",
70630
+ account,
70631
+ "-s",
70632
+ SECRET_STORE_SERVICE,
70633
+ "-l",
70634
+ `${SECRET_STORE_SERVICE} ${account}`,
70635
+ "-U",
70636
+ "-w"
70637
+ ],
70638
+ // `security` asks for the password and then for its confirmation.
70639
+ `${value}
70640
+ ${value}
70641
+ `
70642
+ );
70643
+ requireSuccess(result, what);
70644
+ };
70645
+ const erase = async (account, what) => {
70646
+ const result = await run(SECURITY_BINARY, [
70647
+ "delete-generic-password",
70648
+ "-a",
70649
+ account,
70650
+ "-s",
70651
+ SECRET_STORE_SERVICE
70652
+ ]);
70653
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
70654
+ requireSuccess(result, what);
70655
+ return true;
70656
+ };
70657
+ const erasePartsAfter = async (account, keep, what) => {
70658
+ for (let part = keep + 1; part <= MAX_KEYCHAIN_PARTS; part += 1) {
70659
+ if (!await erase(keychainPart(account, part), what)) return;
70660
+ }
70661
+ };
70662
+ return {
70663
+ available: true,
70664
+ platform: platform2,
70665
+ description: "the macOS Keychain",
70666
+ async get(name) {
70667
+ const account = accountFor(name);
70668
+ const what = `read the passphrase of ${name} from the macOS Keychain`;
70669
+ const value = await read(account, what);
70670
+ const parts = value === void 0 ? void 0 : chunkedPartCount(value);
70671
+ if (value === void 0 || parts === void 0) return value;
70672
+ let joined = "";
70673
+ for (let part = 1; part <= parts; part += 1) {
70674
+ const chunk = await read(keychainPart(account, part), what);
70675
+ if (chunk === void 0) {
70676
+ throw new KeystoreError(
70677
+ `The stored secret ${name} is incomplete in the macOS Keychain. Store it again.`
70678
+ );
70679
+ }
70680
+ joined += chunk;
70681
+ }
70682
+ return joined;
70683
+ },
70684
+ async has(name) {
70685
+ const result = await find(accountFor(name), false);
70686
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
70687
+ requireSuccess(result, `look up ${name} in the macOS Keychain`);
70688
+ return true;
70689
+ },
70690
+ async set(name, passphrase) {
70691
+ requirePassphrase(passphrase);
70692
+ const account = accountFor(name);
70693
+ const what = `store the passphrase of ${name} in the macOS Keychain`;
70694
+ if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
70695
+ await write(account, passphrase, what);
70696
+ return;
70697
+ }
70698
+ const chunks = [];
70699
+ for (let index2 = 0; index2 < passphrase.length; index2 += KEYCHAIN_CHUNK) {
70700
+ chunks.push(passphrase.slice(index2, index2 + KEYCHAIN_CHUNK));
70701
+ }
70702
+ if (chunks.length > MAX_KEYCHAIN_PARTS) {
70703
+ throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
70704
+ }
70705
+ for (const [index2, chunk] of chunks.entries()) {
70706
+ await write(keychainPart(account, index2 + 1), chunk, what);
70707
+ }
70708
+ await erasePartsAfter(account, chunks.length, what);
70709
+ await write(account, `${CHUNKED_MARKER}${chunks.length}`, what);
70710
+ },
70711
+ async remove(name) {
70712
+ const account = accountFor(name);
70713
+ const what = `remove the passphrase of ${name} from the macOS Keychain`;
70714
+ const found = await find(account, true);
70715
+ if (found.code === SECURITY_ITEM_NOT_FOUND) return false;
70716
+ requireSuccess(found, what);
70717
+ if (chunkedPartCount(withoutTrailingNewline(found.stdout)) !== void 0) {
70718
+ await erasePartsAfter(account, 0, what);
70719
+ }
70720
+ return await erase(account, what);
70721
+ }
70722
+ };
70723
+ }
70724
+ var KEYCHAIN_PROMPT_LIMIT = 128;
70725
+ var KEYCHAIN_CHUNK = 120;
70726
+ var MAX_KEYCHAIN_PARTS = 32;
70727
+ var CHUNKED_MARKER = "vapi-chunked:v1:";
70728
+ function keychainPart(account, part) {
70729
+ return `${account}#${part}`;
70730
+ }
70731
+ function chunkedPartCount(value) {
70732
+ if (!value.startsWith(CHUNKED_MARKER)) return void 0;
70733
+ const parts = Number(value.slice(CHUNKED_MARKER.length));
70734
+ return Number.isInteger(parts) && parts > 0 && parts <= MAX_KEYCHAIN_PARTS ? parts : void 0;
70735
+ }
70736
+ function windowsSecretFileName(account) {
70737
+ let encoded = "";
70738
+ for (let index2 = 0; index2 < account.length; index2 += 1) {
70739
+ const character = account[index2];
70740
+ if (/^[a-z0-9._#-]$/u.test(character)) {
70741
+ encoded += character;
70742
+ continue;
70743
+ }
70744
+ encoded += `%${account.charCodeAt(index2).toString(16).toUpperCase().padStart(4, "0")}`;
70745
+ }
70746
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(encoded)) {
70747
+ encoded = `%${encoded.charCodeAt(0).toString(16).toUpperCase()}${encoded.slice(1)}`;
70748
+ }
70749
+ return `${encoded}.bin`;
70750
+ }
70751
+ function windowsDataProtectionStore(platform2, run, env, installed) {
70752
+ const powershell = `${env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
70753
+ const fileDetails = (name) => {
70754
+ const file2 = windowsSecretFileName(accountFor(name));
70755
+ return { file: file2, account: file2.slice(0, -".bin".length) };
70756
+ };
70757
+ const script = (file2, operations) => [
70758
+ "$ErrorActionPreference = 'Stop'",
70759
+ "try {",
70760
+ " Add-Type -AssemblyName System.Security",
70761
+ " $dir = Join-Path $env:LOCALAPPDATA 'vapi-network\\secrets'",
70762
+ ` $path = Join-Path $dir '${file2}'`,
70763
+ ...operations.map((operation) => ` ${operation}`),
70764
+ "} catch {",
70765
+ " [Console]::Error.WriteLine($_.Exception.Message)",
70766
+ " exit 1",
70767
+ "}"
70768
+ ].join("\n");
70769
+ const execute = async (script2) => {
70770
+ const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
70771
+
70772
+ `);
70773
+ requirePowerShell(result);
70774
+ return result;
70775
+ };
70776
+ return {
70777
+ available: installed(powershell),
70778
+ platform: platform2,
70779
+ description: "Windows Data Protection (DPAPI)",
70780
+ async get(name) {
70781
+ const { file: file2, account } = fileDetails(name);
70782
+ const result = await execute(
70783
+ script(file2, [
70784
+ `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
70785
+ "$blob = [System.IO.File]::ReadAllBytes($path)",
70786
+ "$bytes = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
70787
+ "[Console]::Out.Write([Convert]::ToBase64String($bytes))",
70788
+ `exit ${WINDOWS_SECRET_SUCCESS}`
70789
+ ])
70790
+ );
70791
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return void 0;
70792
+ requireSuccess(result, `read the passphrase of ${name} from Windows Data Protection`);
70793
+ const value = Buffer.from(result.stdout.trim(), "base64").toString("utf8");
70794
+ return value.length === 0 ? void 0 : value;
70795
+ },
70796
+ async has(name) {
70797
+ const { file: file2, account } = fileDetails(name);
70798
+ const result = await execute(
70799
+ script(file2, [
70800
+ `if (Test-Path -LiteralPath $path) { exit ${WINDOWS_SECRET_SUCCESS} }`,
70801
+ `[Console]::Error.WriteLine('No stored secret for ${account}.')`,
70802
+ `exit ${WINDOWS_SECRET_NOT_FOUND}`
70803
+ ])
70804
+ );
70805
+ if (result.code === WINDOWS_SECRET_SUCCESS) return true;
70806
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
70807
+ requireSuccess(result, `look up ${name} in Windows Data Protection`);
70808
+ return false;
70809
+ },
70810
+ async set(name, passphrase) {
70811
+ requirePassphrase(passphrase);
70812
+ const { file: file2 } = fileDetails(name);
70813
+ const value = Buffer.from(passphrase, "utf8").toString("base64");
70814
+ const result = await execute(
70815
+ script(file2, [
70816
+ "[void][System.IO.Directory]::CreateDirectory($dir)",
70817
+ `$bytes = [Convert]::FromBase64String('${value}')`,
70818
+ "$blob = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
70819
+ "[System.IO.File]::WriteAllBytes($path, $blob)",
70820
+ `exit ${WINDOWS_SECRET_SUCCESS}`
70821
+ ])
70822
+ );
70823
+ requireSuccess(result, `store the passphrase of ${name} in Windows Data Protection`);
70824
+ },
70825
+ async remove(name) {
70826
+ const { file: file2, account } = fileDetails(name);
70827
+ const result = await execute(
70828
+ script(file2, [
70829
+ `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
70830
+ "Remove-Item -LiteralPath $path -Force",
70831
+ `exit ${WINDOWS_SECRET_SUCCESS}`
70832
+ ])
70833
+ );
70834
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
70835
+ requireSuccess(result, `remove the passphrase of ${name} from Windows Data Protection`);
70836
+ return true;
70837
+ }
70838
+ };
70839
+ }
70840
+ function libsecretStore(platform2, run, installed) {
70841
+ const lookup = async (name) => {
70842
+ const result = await run(SECRET_TOOL_BINARY, [
70843
+ "lookup",
70844
+ "service",
70845
+ SECRET_STORE_SERVICE,
70846
+ "account",
70847
+ accountFor(name)
70848
+ ]);
70849
+ requireBinary(result);
70850
+ const value = withoutTrailingNewline(result.stdout);
70851
+ if (result.code === 0) return value.length === 0 ? void 0 : value;
70852
+ if (result.stderr.trim().length === 0) return void 0;
70853
+ requireSuccess(result, `read the passphrase of ${name} from the secret service`);
70854
+ return void 0;
70855
+ };
70856
+ return {
70857
+ available: installed(SECRET_TOOL_BINARY),
70858
+ platform: platform2,
70859
+ description: "the libsecret keyring",
70860
+ get: lookup,
70861
+ async has(name) {
70862
+ return await lookup(name) !== void 0;
70863
+ },
70864
+ async set(name, passphrase) {
70865
+ requirePassphrase(passphrase);
70866
+ const account = accountFor(name);
70867
+ const result = await run(
70868
+ SECRET_TOOL_BINARY,
70869
+ [
70870
+ "store",
70871
+ `--label=${SECRET_STORE_SERVICE} ${account}`,
70872
+ "service",
70873
+ SECRET_STORE_SERVICE,
70874
+ "account",
70875
+ account
70876
+ ],
70877
+ `${passphrase}
70878
+ `
70879
+ );
70880
+ requireBinary(result);
70881
+ requireSuccess(result, `store the passphrase of ${name} in the secret service`);
70882
+ },
70883
+ async remove(name) {
70884
+ const existed = await lookup(name) !== void 0;
70885
+ const result = await run(SECRET_TOOL_BINARY, [
70886
+ "clear",
70887
+ "service",
70888
+ SECRET_STORE_SERVICE,
70889
+ "account",
70890
+ accountFor(name)
70891
+ ]);
70892
+ requireBinary(result);
70893
+ requireSuccess(result, `remove the passphrase of ${name} from the secret service`);
70894
+ return existed;
70895
+ }
70896
+ };
70897
+ }
70898
+ function unsupportedStore(platform2) {
70899
+ const refuse = () => {
70900
+ throw new KeystoreError(UNSUPPORTED_PLATFORM);
70901
+ };
70902
+ return {
70903
+ available: false,
70904
+ platform: platform2,
70905
+ description: "no OS secret store",
70906
+ get: async () => refuse(),
70907
+ has: async () => refuse(),
70908
+ set: async () => refuse(),
70909
+ remove: async () => refuse()
70910
+ };
70911
+ }
70912
+ function accountFor(name) {
70913
+ const account = name.trim();
70914
+ if (account.length === 0) {
70915
+ throw new KeystoreError("A wallet name is needed to reach the OS secret store.");
70916
+ }
70917
+ return account;
70918
+ }
70919
+ function requirePassphrase(passphrase) {
70920
+ if (passphrase.length === 0) {
70921
+ throw new KeystoreError("Keystore passphrase cannot be empty.");
70922
+ }
70923
+ }
70924
+ function requireBinary(result) {
70925
+ if (result.notFound === true) throw new KeystoreError(SECRET_TOOL_MISSING);
70926
+ }
70927
+ function requirePowerShell(result) {
70928
+ if (result.notFound === true) throw new KeystoreError(POWERSHELL_MISSING);
70929
+ }
70930
+ function binaryInstalled(file2, env) {
70931
+ if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
70932
+ return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join7(directory, file2)));
70933
+ }
70934
+ var SAFE_FAILURE_DETAILS = [
70935
+ "Cannot autolaunch D-Bus without X11 $DISPLAY",
70936
+ "Cannot autolaunch D-Bus",
70937
+ "The name org.freedesktop.secrets was not provided by any .service files",
70938
+ "Cannot create an item in a locked collection",
70939
+ "User interaction is not allowed.",
70940
+ "Access to the path is denied."
70941
+ ];
70942
+ function requireSuccess(result, what) {
70943
+ if (result.code === 0) return;
70944
+ const detail = SAFE_FAILURE_DETAILS.find((reason) => result.stderr.includes(reason));
70945
+ throw new KeystoreError(
70946
+ `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail === void 0 ? "" : ` ${detail}`}`
70947
+ );
70948
+ }
70949
+ function withoutTrailingNewline(value) {
70950
+ return value.replace(/\r?\n$/u, "");
70951
+ }
70952
+ var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve2) => {
70953
+ let stdout = "";
70954
+ let stderr2 = "";
70955
+ let settled = false;
70956
+ const finish = (outcome) => {
70957
+ if (settled) return;
70958
+ settled = true;
70959
+ resolve2(outcome);
70960
+ };
70961
+ const child = spawn(file2, [...args], {
70962
+ detached: platform2 !== "win32",
70963
+ stdio: ["pipe", "pipe", "pipe"],
70964
+ windowsHide: true
70965
+ });
70966
+ child.stdout?.setEncoding("utf8");
70967
+ child.stdout?.on("data", (chunk) => {
70968
+ stdout += chunk;
70969
+ });
70970
+ child.stderr?.setEncoding("utf8");
70971
+ child.stderr?.on("data", (chunk) => {
70972
+ stderr2 += chunk;
70973
+ });
70974
+ child.on("error", (error61) => {
70975
+ finish({
70976
+ code: null,
70977
+ stdout,
70978
+ stderr: stderr2,
70979
+ ...error61.code === "ENOENT" ? { notFound: true } : {}
70980
+ });
70981
+ });
70982
+ child.on("close", (code) => finish({ code, stdout, stderr: stderr2 }));
70983
+ child.stdin?.on("error", () => void 0);
70984
+ child.stdin?.end(input2 ?? "");
70985
+ });
70986
+
70987
+ // src/passphrase.ts
70988
+ var PASSPHRASE_ENVIRONMENT_VARIABLE = "VAPI_KEYSTORE_PASSWORD";
70989
+ function noPassphraseHint(walletName) {
70990
+ return `Set ${PASSPHRASE_ENVIRONMENT_VARIABLE}, or store this wallet's passphrase once with vapi unlock --wallet ${walletName}.`;
70991
+ }
70992
+ function staleStoredPassphraseMessage(walletName, store) {
70993
+ return [
70994
+ `The passphrase stored in ${store.description} no longer opens wallet ${walletName}.`,
70995
+ `Store the current one with vapi unlock --wallet ${walletName}, or remove it with vapi lock --wallet ${walletName}.`
70996
+ ].join(" ");
70997
+ }
70998
+ async function resolvePassphrase(walletName, options = {}) {
70999
+ const env = options.env ?? process.env;
71000
+ const fromEnvironment = env[PASSPHRASE_ENVIRONMENT_VARIABLE];
71001
+ if (fromEnvironment !== void 0) {
71002
+ if (fromEnvironment.length === 0) {
71003
+ throw new KeystoreError(`${PASSPHRASE_ENVIRONMENT_VARIABLE} cannot be empty.`);
71004
+ }
71005
+ return { passphrase: fromEnvironment, source: "environment" };
71006
+ }
71007
+ if (options.confirm !== true) {
71008
+ const stored = await readStored(options.store ?? secretStore(), walletName);
71009
+ if (stored !== void 0) return { passphrase: stored, source: "secret-store" };
70803
71010
  }
70804
- assertVaultKey(args.key);
70805
- try {
70806
- return await withVaultLock(args.path, async () => {
70807
- const file2 = await readVaultFile(args.path, args.key);
70808
- const account = parsedAccount.data;
70809
- assertAvailableName(file2, account.name);
70810
- if (account.kind === "derived" && file2.accounts.some(
70811
- (candidate) => candidate.kind === "derived" && candidate.index === account.index
70812
- )) {
70813
- throw new VaultError("name_taken", "A vault account already uses that derived index.");
70814
- }
70815
- if (account.kind === "derived") validateStoredDerivedAccount(args.key, file2, account);
70816
- else validateStoredImportedAccount(args.key, account);
70817
- const updated = parseVaultFile(
70818
- JSON.stringify({
70819
- ...file2,
70820
- accounts: [...file2.accounts, account],
70821
- ...account.kind === "derived" ? { nextDerivedIndex: Math.max(nextDerivedIndex(file2), account.index + 1) } : {}
70822
- })
70823
- );
70824
- await writeVaultFile(args.path, updated);
70825
- return copyAccount(account);
70826
- });
70827
- } catch (error61) {
70828
- throw asVaultError(error61, "corrupt", "Unable to reinstate the vault account.");
71011
+ const hint = noPassphraseHint(walletName);
71012
+ if (options.interactive === false) {
71013
+ throw new KeystoreError(
71014
+ `No interactive terminal is available for the keystore prompt. ${hint}`
71015
+ );
70829
71016
  }
70830
- }
70831
- function assertVaultKey(key) {
70832
- if (key.byteLength !== 32) {
70833
- throw new VaultError("bad_key", "A device vault key must contain exactly 32 bytes.");
71017
+ const prompt = options.prompt ?? promptForSecret;
71018
+ const first = await prompt(`Passphrase for ${walletName}: `, hint);
71019
+ if (first.length === 0) {
71020
+ throw new KeystoreError("Keystore passphrase cannot be empty.");
70834
71021
  }
70835
- }
70836
- function assertAccountName(name) {
70837
- const parsed = walletNameSchema.safeParse(name);
70838
- if (!parsed.success) {
70839
- throw new VaultError("name_taken", "The vault account name is not valid.", {
70840
- cause: parsed.error
70841
- });
71022
+ if (options.confirm === true) {
71023
+ const second = await prompt("Confirm passphrase: ", hint);
71024
+ if (first !== second) throw new KeystoreError("Passphrases do not match.");
70842
71025
  }
71026
+ return { passphrase: first, source: "prompt" };
70843
71027
  }
70844
- function assertAvailableName(file2, name) {
70845
- assertAccountName(name);
70846
- if (file2.accounts.some((account) => account.name === name)) {
70847
- throw new VaultError("name_taken", "A vault account already has that name.");
71028
+ async function readStored(store, walletName) {
71029
+ if (!store.available) return void 0;
71030
+ try {
71031
+ return await store.get(walletName);
71032
+ } catch {
71033
+ return void 0;
70848
71034
  }
70849
71035
  }
70850
- function nextDerivedIndex(file2) {
70851
- let next = file2.nextDerivedIndex ?? 0;
70852
- for (const account of file2.accounts) {
70853
- if (account.kind === "derived") next = Math.max(next, account.index + 1);
70854
- }
70855
- return next;
71036
+
71037
+ // src/receipts.ts
71038
+ import { randomBytes as randomBytes8 } from "node:crypto";
71039
+ import { mkdir as mkdir8, open as open7, readFile as readFile9, rename as rename5, writeFile as writeFile4 } from "node:fs/promises";
71040
+ import { dirname as dirname6 } from "node:path";
71041
+
71042
+ // src/agent-run.ts
71043
+ import { randomBytes as randomBytes7 } from "node:crypto";
71044
+ var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
71045
+ function isRunId(value) {
71046
+ return typeof value === "string" && RUN_ID_PATTERN.test(value);
70856
71047
  }
70857
- function copyAccount(account) {
70858
- if (account.kind === "derived") return { ...account };
70859
- return {
70860
- name: account.name,
70861
- kind: account.kind,
70862
- address: account.address,
70863
- createdAt: account.createdAt
70864
- };
71048
+ function createRunId(random = randomBytes7) {
71049
+ return `run_${Buffer.from(random(12)).toString("hex")}`;
70865
71050
  }
70866
- function sealField(key, plaintext) {
70867
- const { nonce, ciphertext, tag } = encryptWithKey(key, plaintext);
70868
- return [nonce, ciphertext, tag].map((part) => part.toString("base64url")).join(".");
71051
+ var runRefSchema = external_exports.strictObject({
71052
+ id: external_exports.string().regex(RUN_ID_PATTERN),
71053
+ swarm: external_exports.string().optional(),
71054
+ member: external_exports.string().optional(),
71055
+ parentRunId: external_exports.string().optional()
71056
+ });
71057
+
71058
+ // src/receipts.ts
71059
+ var receiptTestHooks;
71060
+ function __setReceiptTestHooks(hooks) {
71061
+ receiptTestHooks = hooks;
70869
71062
  }
70870
- function openField(key, value) {
70871
- const [nonce = "", ciphertext = "", tag = ""] = value.split(".");
70872
- return decryptWithKey(key, {
70873
- nonce: Buffer.from(nonce, "base64url"),
70874
- ciphertext: Buffer.from(ciphertext, "base64url"),
70875
- tag: Buffer.from(tag, "base64url")
71063
+ var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
71064
+ async function withReceiptJournalLock(path, operation) {
71065
+ return await withFileLock(`${path}.lock`, operation, {
71066
+ lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
70876
71067
  });
70877
71068
  }
70878
- function decryptField(key, value) {
70879
- try {
70880
- return openField(key, value);
70881
- } catch (error61) {
70882
- throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70883
- cause: error61
70884
- });
70885
- }
70886
- }
70887
- function decryptPhraseForOpen(key, phrase) {
70888
- try {
70889
- return openField(key, phrase);
70890
- } catch (error61) {
70891
- throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70892
- cause: error61
70893
- });
71069
+ var durationSchema = external_exports.number().nonnegative().finite();
71070
+ var receiptSchema = external_exports.strictObject({
71071
+ id: external_exports.string().min(1),
71072
+ timestamp: external_exports.iso.datetime(),
71073
+ run: runRefSchema.optional(),
71074
+ kind: external_exports.literal("transfer").optional(),
71075
+ wallet: walletNameSchema.optional(),
71076
+ resourceUrl: external_exports.url(),
71077
+ method: external_exports.string().min(1).optional(),
71078
+ source: external_exports.string().min(1).optional(),
71079
+ provenance: external_exports.array(
71080
+ external_exports.strictObject({
71081
+ source: external_exports.string().min(1),
71082
+ sourceUrl: external_exports.string().optional(),
71083
+ ref: external_exports.string().optional()
71084
+ })
71085
+ ).optional(),
71086
+ quote: external_exports.strictObject({
71087
+ network: external_exports.string(),
71088
+ asset: external_exports.string().optional(),
71089
+ amountAtomic: external_exports.string().regex(/^\d+$/),
71090
+ payTo: external_exports.string().optional()
71091
+ }).optional(),
71092
+ payer: external_exports.string().optional(),
71093
+ paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
71094
+ authorization: external_exports.strictObject({
71095
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71096
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
71097
+ validBefore: external_exports.string().regex(/^\d+$/)
71098
+ }).optional(),
71099
+ transfer: external_exports.strictObject({
71100
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71101
+ toName: external_exports.string().min(1),
71102
+ toKind: external_exports.enum(["owner", "account"]),
71103
+ amountAtomic: external_exports.string().regex(/^\d+$/),
71104
+ network: external_exports.string().min(1),
71105
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
71106
+ status: external_exports.enum(["sent", "unknown", "failed"]),
71107
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
71108
+ replayed: external_exports.boolean(),
71109
+ reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
71110
+ request: external_exports.strictObject({
71111
+ authorization: external_exports.strictObject({
71112
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71113
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71114
+ value: external_exports.string().regex(/^\d+$/),
71115
+ validAfter: external_exports.string().regex(/^\d+$/),
71116
+ validBefore: external_exports.string().regex(/^\d+$/),
71117
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
71118
+ }),
71119
+ signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
71120
+ }).optional()
71121
+ }).optional(),
71122
+ settlement: external_exports.strictObject({
71123
+ outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
71124
+ transaction: external_exports.string().optional(),
71125
+ explorerUrl: external_exports.url().optional(),
71126
+ evidence: external_exports.unknown().optional()
71127
+ }).optional(),
71128
+ latencyMs: external_exports.number().nonnegative().finite().optional(),
71129
+ status: external_exports.number().int().min(100).max(599).optional(),
71130
+ error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
71131
+ phases: external_exports.strictObject({
71132
+ discoverMs: durationSchema.optional(),
71133
+ quoteMs: durationSchema.optional(),
71134
+ signMs: durationSchema.optional(),
71135
+ requestMs: durationSchema.optional(),
71136
+ settleMs: durationSchema.optional()
71137
+ }).optional(),
71138
+ listing: external_exports.strictObject({
71139
+ name: external_exports.string().min(1).optional(),
71140
+ providerHost: external_exports.string().min(1).optional(),
71141
+ source: external_exports.string().min(1)
71142
+ }).optional(),
71143
+ retry: external_exports.number().int().nonnegative().optional(),
71144
+ policy: external_exports.strictObject({
71145
+ maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
71146
+ capsApplied: external_exports.boolean()
71147
+ }).optional(),
71148
+ client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
71149
+ outcome: external_exports.enum([
71150
+ "paid",
71151
+ "signed_in",
71152
+ "declined_policy",
71153
+ "failed_request",
71154
+ "settlement_rejected",
71155
+ "settlement_unknown"
71156
+ ]).optional()
71157
+ });
71158
+ function parseReceipt(value) {
71159
+ const receipt = receiptSchema.parse(value);
71160
+ const transaction = receipt.settlement?.transaction;
71161
+ const network = receipt.quote?.network;
71162
+ const explorerUrl = transaction === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction);
71163
+ if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
71164
+ return receipt;
70894
71165
  }
70895
- }
70896
- function validateStoredImportedAccount(key, account) {
70897
- let plaintext;
70898
- try {
70899
- plaintext = decryptField(key, account.key);
70900
- if (plaintext.byteLength !== 32) {
70901
- throw new VaultError("bad_key", "The stored imported key has the wrong length.");
70902
- }
70903
- let address2;
70904
- try {
70905
- address2 = privateKeyToAccount(`0x${plaintext.toString("hex")}`).address;
70906
- } catch (error61) {
70907
- throw new VaultError("bad_key", "The stored imported key is not valid.", {
70908
- cause: error61
70909
- });
70910
- }
70911
- if (address2.toLowerCase() !== account.address.toLowerCase()) {
70912
- throw new VaultError("bad_key", "The stored imported key does not match its address.");
71166
+ return {
71167
+ ...receipt,
71168
+ settlement: {
71169
+ outcome: receipt.settlement.outcome,
71170
+ ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
71171
+ explorerUrl,
71172
+ ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
70913
71173
  }
70914
- } finally {
70915
- plaintext?.fill(0);
70916
- }
71174
+ };
70917
71175
  }
70918
- function validateStoredDerivedAccount(key, file2, account) {
70919
- const plaintext = decryptField(key, file2.phrase);
70920
- let seed;
70921
- try {
70922
- seed = phraseToSeed(plaintext.toString("utf8"));
70923
- const address2 = privateKeyToAccount(
70924
- deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${account.index}`)
70925
- ).address;
70926
- if (address2.toLowerCase() !== account.address.toLowerCase()) {
70927
- throw new VaultError("bad_key", "The stored derived account does not match this vault.");
71176
+ async function appendReceipt(receipt, path = getVapiPaths().receipts, options = {}) {
71177
+ const parsed = parseReceipt(
71178
+ receipt.wallet === void 0 && options.wallet !== void 0 ? { ...receipt, wallet: options.wallet } : receipt
71179
+ );
71180
+ await withReceiptJournalLock(path, async () => {
71181
+ await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71182
+ const handle = await open7(path, "a", 384);
71183
+ try {
71184
+ await handle.writeFile(`${JSON.stringify(parsed)}
71185
+ `, "utf8");
71186
+ } finally {
71187
+ await handle.close();
70928
71188
  }
70929
- } finally {
70930
- seed?.fill(0);
70931
- plaintext.fill(0);
70932
- }
71189
+ });
71190
+ return parsed;
70933
71191
  }
70934
- function parseVaultFile(raw) {
70935
- let value;
71192
+ async function readReceipts(path = getVapiPaths().receipts, options = {}) {
71193
+ let raw;
70936
71194
  try {
70937
- value = JSON.parse(raw);
71195
+ raw = await readFile9(path, "utf8");
70938
71196
  } catch (error61) {
70939
- throw new VaultError("corrupt", "The vault file is not valid JSON.", { cause: error61 });
70940
- }
70941
- const parsed = vaultFileSchema.safeParse(value);
70942
- if (!parsed.success) {
70943
- throw new VaultError("corrupt", "The vault file has an invalid structure.", {
70944
- cause: parsed.error
70945
- });
70946
- }
70947
- if (parsed.data.protected !== (parsed.data.wrappedKey !== void 0)) {
70948
- throw new VaultError("corrupt", "The vault protection metadata is inconsistent.");
71197
+ if (isMissingFile(error61)) return [];
71198
+ throw error61;
70949
71199
  }
70950
- const names = /* @__PURE__ */ new Set();
70951
- const indexes = /* @__PURE__ */ new Set();
70952
- for (const account of parsed.data.accounts) {
70953
- if (names.has(account.name)) {
70954
- throw new VaultError("corrupt", "The vault file contains duplicate account names.");
70955
- }
70956
- names.add(account.name);
70957
- if (account.kind === "derived") {
70958
- if (indexes.has(account.index)) {
70959
- throw new VaultError("corrupt", "The vault file contains duplicate derived indexes.");
71200
+ const records = coalesceTransferReceiptRevisions(
71201
+ raw.split("\n").filter((line) => line.trim().length > 0).map((line, index2) => {
71202
+ try {
71203
+ return parseReceipt(JSON.parse(line));
71204
+ } catch (error61) {
71205
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70960
71206
  }
70961
- indexes.add(account.index);
71207
+ })
71208
+ );
71209
+ const filtered = options.wallet === void 0 ? records : filterReceiptsByWallet(records, options.wallet);
71210
+ const limit = options.limit;
71211
+ if (limit === void 0) return filtered;
71212
+ if (!Number.isSafeInteger(limit) || limit < 0)
71213
+ throw new Error("Receipt limit must be a non-negative integer.");
71214
+ return limit === 0 ? [] : filtered.slice(-limit);
71215
+ }
71216
+ function coalesceTransferReceiptRevisions(receipts) {
71217
+ const coalesced = [];
71218
+ const transferIndexes = /* @__PURE__ */ new Map();
71219
+ for (const receipt of receipts) {
71220
+ const existing = receipt.kind === "transfer" ? transferIndexes.get(receipt.id) : void 0;
71221
+ if (existing === void 0) {
71222
+ if (receipt.kind === "transfer") transferIndexes.set(receipt.id, coalesced.length);
71223
+ coalesced.push(receipt);
71224
+ } else {
71225
+ coalesced[existing] = receipt;
70962
71226
  }
70963
71227
  }
70964
- return parsed.data;
71228
+ return coalesced;
70965
71229
  }
70966
- async function readVaultFile(path, key) {
70967
- const file2 = await readVaultFileUnlocked(path);
70968
- const plaintext = decryptPhraseForOpen(key, file2.phrase);
70969
- try {
71230
+ function receiptWallet(receipt) {
71231
+ return receipt.wallet ?? DEFAULT_WALLET_NAME;
71232
+ }
71233
+ function filterReceiptsByWallet(receipts, name) {
71234
+ return receipts.filter((receipt) => receiptWallet(receipt) === name);
71235
+ }
71236
+ async function renameReceiptWallet(from16, to, path = getVapiPaths().receipts) {
71237
+ return await withReceiptJournalLock(path, async () => {
71238
+ let raw;
70970
71239
  try {
70971
- validateRecoveryPhrase(plaintext.toString("utf8"));
71240
+ raw = await readFile9(path, "utf8");
70972
71241
  } catch (error61) {
70973
- throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
70974
- cause: error61
70975
- });
70976
- }
70977
- } finally {
70978
- plaintext.fill(0);
70979
- }
70980
- return file2;
70981
- }
70982
- async function readVaultFileUnlocked(path) {
70983
- let raw;
70984
- try {
70985
- raw = await readFile9(path, "utf8");
70986
- } catch (error61) {
70987
- if (isMissingFile2(error61)) {
70988
- throw new VaultError("not_found", "No vault file was found at the requested path.", {
70989
- cause: error61
70990
- });
71242
+ if (isMissingFile(error61)) return 0;
71243
+ throw error61;
70991
71244
  }
70992
- throw new VaultError("corrupt", "Unable to read the vault file.", { cause: error61 });
70993
- }
70994
- return parseVaultFile(raw);
70995
- }
70996
- async function refuseExistingVault(path) {
70997
- try {
70998
- await stat6(path);
70999
- } catch (error61) {
71000
- if (isMissingFile2(error61)) return;
71001
- throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
71002
- cause: error61
71245
+ let changed = 0;
71246
+ const lines = raw.split("\n").map((line, index2) => {
71247
+ if (line.trim().length === 0) return line;
71248
+ let parsed;
71249
+ try {
71250
+ parsed = JSON.parse(line);
71251
+ } catch (error61) {
71252
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71253
+ }
71254
+ const current = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "wallet") : void 0;
71255
+ if ((typeof current === "string" ? current : DEFAULT_WALLET_NAME) !== from16) return line;
71256
+ changed += 1;
71257
+ return JSON.stringify(parseReceipt({ ...parsed, wallet: to }));
71003
71258
  });
71004
- }
71005
- throw new VaultError("corrupt", "A vault already exists at the requested path.");
71006
- }
71007
- async function writeVaultFile(path, file2) {
71008
- await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71009
- const temporaryPath = `${path}.${process.pid}.${randomBytes7(6).toString("hex")}.tmp`;
71010
- try {
71011
- await writeFile4(temporaryPath, `${JSON.stringify(file2, null, 2)}
71012
- `, {
71259
+ if (changed === 0) return 0;
71260
+ await receiptTestHooks?.beforeRenameReplace?.(path);
71261
+ await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71262
+ const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
71263
+ await writeFile4(temporaryPath, lines.join("\n"), {
71013
71264
  encoding: "utf8",
71014
71265
  mode: 384,
71015
71266
  flag: "wx"
71016
71267
  });
71017
71268
  await rename5(temporaryPath, path);
71269
+ return changed;
71270
+ });
71271
+ }
71272
+
71273
+ // src/transfer-journal.ts
71274
+ import { readFile as readFile10 } from "node:fs/promises";
71275
+ async function readTransferJournal(home, from16, nonce) {
71276
+ let raw;
71277
+ try {
71278
+ raw = await readFile10(getVapiPaths(home).receipts, "utf8");
71018
71279
  } catch (error61) {
71019
- await rm(temporaryPath, { force: true }).catch(() => void 0);
71280
+ if (isMissingFile(error61)) return { signed: false };
71020
71281
  throw error61;
71021
71282
  }
71022
- }
71023
- async function withVaultLock(path, operation) {
71024
- await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71025
- const lockPath = `${path}.lock`;
71026
- const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
71027
- let handle;
71028
- while (!handle) {
71283
+ let latest;
71284
+ let request;
71285
+ for (const [index2, line] of raw.split("\n").entries()) {
71286
+ if (!line.trim()) continue;
71287
+ let receipt;
71029
71288
  try {
71030
- handle = await open6(lockPath, "wx", 384);
71289
+ receipt = parseReceipt(JSON.parse(line));
71031
71290
  } catch (error61) {
71032
- if (!isExistingFile(error61)) throw error61;
71033
- await removeStaleVaultLock(lockPath);
71034
- if (Date.now() >= deadline) {
71035
- throw new VaultError("corrupt", "Timed out waiting for the vault lock.");
71036
- }
71037
- await new Promise((resolve2) => setTimeout(resolve2, 20));
71291
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71038
71292
  }
71293
+ if (receiptWallet(receipt) !== from16 || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
71294
+ continue;
71295
+ }
71296
+ latest = receipt;
71297
+ if (receipt.transfer.request !== void 0) request = receipt;
71039
71298
  }
71040
- try {
71041
- return await operation();
71042
- } finally {
71043
- await handle.close();
71044
- await unlink4(lockPath).catch(() => void 0);
71045
- }
71046
- }
71047
- async function removeStaleVaultLock(path) {
71048
- try {
71049
- const metadata = await stat6(path);
71050
- if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
71051
- } catch (error61) {
71052
- if (!isMissingFile2(error61)) throw error61;
71053
- }
71054
- }
71055
- function isMissingFile2(error61) {
71056
- return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
71057
- }
71058
- function isExistingFile(error61) {
71059
- return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "EEXIST";
71060
- }
71061
- function asVaultError(error61, code, message) {
71062
- return error61 instanceof VaultError ? error61 : new VaultError(code, message, { cause: error61 });
71299
+ return {
71300
+ signed: latest !== void 0,
71301
+ ...latest === void 0 ? {} : { latest },
71302
+ ...request === void 0 ? {} : { request },
71303
+ ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
71304
+ ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
71305
+ };
71063
71306
  }
71064
71307
 
71065
71308
  // src/vault-key.ts
71309
+ import { randomBytes as cryptoRandomBytes } from "node:crypto";
71066
71310
  var VAULT_KEY_ACCOUNT = "vault-key";
71067
71311
  var VAULT_SESSION_ACCOUNT = "vault-session";
71068
71312
  var DEVICE_KEY_LENGTH = 32;
@@ -71084,7 +71328,7 @@ async function loadOrCreateDeviceKey(args) {
71084
71328
  await args.secrets.set(VAULT_KEY_ACCOUNT, key.toString("base64"));
71085
71329
  return key;
71086
71330
  } catch (error61) {
71087
- throw asVaultError2(error61, "Unable to load or create the device vault key.");
71331
+ throw asVaultError2(error61, deviceKeyFailureMessage(error61, args.secrets.platform));
71088
71332
  }
71089
71333
  });
71090
71334
  }
@@ -71290,8 +71534,8 @@ function passwordRequiredError() {
71290
71534
  "A vault password is needed. Pass it or set VAPI_VAULT_PASSWORD."
71291
71535
  );
71292
71536
  }
71293
- function randomKeyBytes(randomBytes16) {
71294
- const key = Buffer.from((randomBytes16 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
71537
+ function randomKeyBytes(randomBytes17) {
71538
+ const key = Buffer.from((randomBytes17 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
71295
71539
  if (key.byteLength !== DEVICE_KEY_LENGTH) {
71296
71540
  key.fill(0);
71297
71541
  throw new VaultError("corrupt", "A generated device vault key has the wrong length.");
@@ -71342,25 +71586,31 @@ function parseJson(value) {
71342
71586
  function asVaultError2(error61, message) {
71343
71587
  return error61 instanceof VaultError ? error61 : new VaultError("corrupt", message, { cause: error61 });
71344
71588
  }
71589
+ 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.";
71590
+ function deviceKeyFailureMessage(error61, platform2) {
71591
+ if (!(error61 instanceof KeystoreError)) return "Unable to load or create the device vault key.";
71592
+ const detail = `Unable to load or create the device vault key: ${error61.message.replace(/\.$/u, "")}.`;
71593
+ return platform2 === "linux" ? `${detail} ${HEADLESS_LINUX_HINT}` : detail;
71594
+ }
71345
71595
 
71346
71596
  // src/vault-migrate.ts
71347
71597
  import {
71348
71598
  chmod as chmod2,
71349
71599
  lstat,
71350
71600
  mkdir as mkdir9,
71351
- readFile as readFile10,
71601
+ readFile as readFile11,
71352
71602
  readlink,
71353
71603
  readdir as readdir2,
71354
71604
  rename as rename6,
71355
71605
  symlink,
71356
71606
  unlink as unlink5
71357
71607
  } from "node:fs/promises";
71358
- import { join as join7, resolve } from "node:path";
71608
+ import { join as join8, resolve } from "node:path";
71359
71609
  var MIGRATED_DIRECTORY = "wallets.migrated";
71360
71610
  async function legacyKeystoreNames(home) {
71361
71611
  let entries;
71362
71612
  try {
71363
- entries = await readdir2(join7(home, "wallets"), { withFileTypes: true });
71613
+ entries = await readdir2(join8(home, "wallets"), { withFileTypes: true });
71364
71614
  } catch (error61) {
71365
71615
  if (isMissingFile(error61)) return [];
71366
71616
  throw error61;
@@ -71376,14 +71626,14 @@ async function migrateKeystores(args) {
71376
71626
  );
71377
71627
  const result = { imported: [], skipped: [] };
71378
71628
  for (const name of names) {
71379
- const source = join7(args.home, "wallets", `${name}.json`);
71629
+ const source = join8(args.home, "wallets", `${name}.json`);
71380
71630
  if (args.vault.accounts().some((account) => account.name === name)) {
71381
71631
  result.skipped.push({ name, reason: "name_taken" });
71382
71632
  continue;
71383
71633
  }
71384
71634
  let parsed;
71385
71635
  try {
71386
- parsed = parseAnyKeystore(JSON.parse(await readFile10(source, "utf8")));
71636
+ parsed = parseAnyKeystore(JSON.parse(await readFile11(source, "utf8")));
71387
71637
  } catch {
71388
71638
  result.skipped.push({ name, reason: "unreadable" });
71389
71639
  continue;
@@ -71413,15 +71663,15 @@ async function migrateKeystores(args) {
71413
71663
  if (imported.address.toLowerCase() !== parsed.address.toLowerCase()) {
71414
71664
  throw new KeystoreError(`Migrated wallet ${name} does not match its stored address.`);
71415
71665
  }
71416
- const migratedDirectory = join7(args.home, MIGRATED_DIRECTORY);
71417
- const destination = join7(migratedDirectory, `${name}.json`);
71666
+ const migratedDirectory = join8(args.home, MIGRATED_DIRECTORY);
71667
+ const destination = join8(migratedDirectory, `${name}.json`);
71418
71668
  await mkdir9(migratedDirectory, { recursive: true, mode: 448 });
71419
71669
  await archiveExistingDestination(destination, migratedDirectory, name, now);
71420
71670
  await rename6(source, destination);
71421
71671
  await chmod2(destination, 384);
71422
71672
  try {
71423
71673
  await removeCompatibilityLink(args.home, source);
71424
- await symlink(join7("..", MIGRATED_DIRECTORY, `${name}.json`), source);
71674
+ await symlink(join8("..", MIGRATED_DIRECTORY, `${name}.json`), source);
71425
71675
  await audit({
71426
71676
  event: "vault.migrate",
71427
71677
  wallet: name,
@@ -71449,16 +71699,16 @@ async function migrateKeystores(args) {
71449
71699
  async function archiveExistingDestination(destination, directory, name, now) {
71450
71700
  if (!await pathExists2(destination)) return;
71451
71701
  const timestamp = now().toISOString();
71452
- let archive = join7(directory, `${name}.${timestamp}.json`);
71702
+ let archive = join8(directory, `${name}.${timestamp}.json`);
71453
71703
  let suffix = 1;
71454
71704
  while (await pathExists2(archive)) {
71455
- archive = join7(directory, `${name}.${timestamp}.${suffix}.json`);
71705
+ archive = join8(directory, `${name}.${timestamp}.${suffix}.json`);
71456
71706
  suffix += 1;
71457
71707
  }
71458
71708
  await rename6(destination, archive);
71459
71709
  }
71460
71710
  async function removeCompatibilityLink(home, migratedSource) {
71461
- const compatibilityPath = join7(home, "keystore.json");
71711
+ const compatibilityPath = join8(home, "keystore.json");
71462
71712
  let metadata;
71463
71713
  try {
71464
71714
  metadata = await lstat(compatibilityPath);
@@ -71532,7 +71782,7 @@ var WalletStore = class _WalletStore {
71532
71782
  this.home = home;
71533
71783
  this.options = options;
71534
71784
  this.registry = registry2;
71535
- this.secrets = options.secrets ?? secretStore();
71785
+ this.secrets = options.secrets ?? secretStore({ home });
71536
71786
  this.environment = options.env ?? process.env;
71537
71787
  this.passphraseResolver = options.resolvePassphrase ?? defaultPassphraseResolver(this.environment, this.secrets);
71538
71788
  this.audit = options.audit ?? (async (record2) => await appendAudit(this.home, record2, { now: () => this.now() }));
@@ -71579,17 +71829,17 @@ var WalletStore = class _WalletStore {
71579
71829
  return store;
71580
71830
  }
71581
71831
  get registryPath() {
71582
- return join8(this.home, REGISTRY_FILE);
71832
+ return join9(this.home, REGISTRY_FILE);
71583
71833
  }
71584
71834
  get walletsDirectory() {
71585
- return join8(this.home, WALLETS_DIRECTORY);
71835
+ return join9(this.home, WALLETS_DIRECTORY);
71586
71836
  }
71587
71837
  get trashDirectory() {
71588
- return join8(this.walletsDirectory, TRASH_DIRECTORY);
71838
+ return join9(this.walletsDirectory, TRASH_DIRECTORY);
71589
71839
  }
71590
71840
  /** The legacy 0.5 keystore path of a wallet, whether or not it exists. */
71591
71841
  pathFor(name) {
71592
- return join8(this.walletsDirectory, `${assertWalletName(name)}.json`);
71842
+ return join9(this.walletsDirectory, `${assertWalletName(name)}.json`);
71593
71843
  }
71594
71844
  /** The names this machine knows, in registry order. */
71595
71845
  names() {
@@ -72162,7 +72412,7 @@ var WalletStore = class _WalletStore {
72162
72412
  }
72163
72413
  const removedAt = this.now().toISOString();
72164
72414
  await mkdir10(this.trashDirectory, { recursive: true, mode: 448 });
72165
- const trashedPath = join8(this.trashDirectory, `${wallet.name}-${removedAt}.json`);
72415
+ const trashedPath = join9(this.trashDirectory, `${wallet.name}-${removedAt}.json`);
72166
72416
  const storedAccount = (await this.readVaultUnlocked())?.accounts.find(
72167
72417
  (candidate) => candidate.name === wallet.name
72168
72418
  );
@@ -72184,7 +72434,7 @@ var WalletStore = class _WalletStore {
72184
72434
  this.balanceProbe = void 0;
72185
72435
  }
72186
72436
  if (await pathExists3(wallet.path)) {
72187
- const legacyTrashedPath = join8(
72437
+ const legacyTrashedPath = join9(
72188
72438
  this.trashDirectory,
72189
72439
  `${wallet.name}-${removedAt}.legacy.json`
72190
72440
  );
@@ -72274,7 +72524,7 @@ var WalletStore = class _WalletStore {
72274
72524
  if (!match) continue;
72275
72525
  const [, name, removedAt] = match;
72276
72526
  if (name === void 0 || removedAt === void 0 || !isWalletName(name)) continue;
72277
- const path = join8(this.trashDirectory, file2);
72527
+ const path = join9(this.trashDirectory, file2);
72278
72528
  const entry = await readEntrySidecar(entrySidecarPath(path));
72279
72529
  trashed.push({ name, removedAt, path, ...entry ? { entry } : {} });
72280
72530
  }
@@ -72343,7 +72593,7 @@ var WalletStore = class _WalletStore {
72343
72593
  return entry;
72344
72594
  }
72345
72595
  get vaultPath() {
72346
- return join8(this.home, VAULT_FILE);
72596
+ return join9(this.home, VAULT_FILE);
72347
72597
  }
72348
72598
  async readVaultUnlocked() {
72349
72599
  try {
@@ -72448,7 +72698,7 @@ var WalletStore = class _WalletStore {
72448
72698
  async readRegistry() {
72449
72699
  let raw;
72450
72700
  try {
72451
- raw = await readFile11(this.registryPath, "utf8");
72701
+ raw = await readFile12(this.registryPath, "utf8");
72452
72702
  } catch (error61) {
72453
72703
  if (isMissingFile(error61)) return emptyRegistry();
72454
72704
  throw error61;
@@ -72469,7 +72719,7 @@ var WalletStore = class _WalletStore {
72469
72719
  }
72470
72720
  };
72471
72721
  async function swarmReferencingAccount(home, account) {
72472
- const directory = join8(home, "swarms");
72722
+ const directory = join9(home, "swarms");
72473
72723
  let files;
72474
72724
  try {
72475
72725
  files = await readdir3(directory);
@@ -72480,7 +72730,7 @@ async function swarmReferencingAccount(home, account) {
72480
72730
  for (const file2 of files.filter((name) => name.endsWith(".json")).sort()) {
72481
72731
  let value;
72482
72732
  try {
72483
- value = JSON.parse(await readFile11(join8(directory, file2), "utf8"));
72733
+ value = JSON.parse(await readFile12(join9(directory, file2), "utf8"));
72484
72734
  } catch {
72485
72735
  throw new KeystoreError(
72486
72736
  `Cannot verify swarm references because ${file2} is invalid. Repair or remove that swarm file before renaming an account.`
@@ -72512,7 +72762,7 @@ async function swarmReferencingAccount(home, account) {
72512
72762
  return void 0;
72513
72763
  }
72514
72764
  async function unfinishedMovementReferencingAccount(home, account) {
72515
- const directory = join8(home, "movements");
72765
+ const directory = join9(home, "movements");
72516
72766
  let files;
72517
72767
  try {
72518
72768
  files = await readdir3(directory);
@@ -72523,7 +72773,7 @@ async function unfinishedMovementReferencingAccount(home, account) {
72523
72773
  for (const file2 of files.filter((name) => name.endsWith(".json")).sort()) {
72524
72774
  let value;
72525
72775
  try {
72526
- value = JSON.parse(await readFile11(join8(directory, file2), "utf8"));
72776
+ value = JSON.parse(await readFile12(join9(directory, file2), "utf8"));
72527
72777
  } catch {
72528
72778
  throw invalidMovementReferenceError(file2);
72529
72779
  }
@@ -72544,11 +72794,11 @@ async function unfinishedMovementReferencingAccount(home, account) {
72544
72794
  const restored = Reflect.get(leg, "restored");
72545
72795
  const legFrom = Reflect.get(leg, "from") ?? movementFrom;
72546
72796
  const journal = restored !== true && status === "failed" && retryable !== true && typeof nonce === "string" ? await readTransferJournal(home, legFrom, nonce) : void 0;
72547
- const open12 = isOpenMovementLeg(
72797
+ const open13 = isOpenMovementLeg(
72548
72798
  { status, retryable, nonce, restored },
72549
72799
  journal?.signed === true ? "signed" : "unsigned"
72550
72800
  );
72551
- if (open12) movementOpen = true;
72801
+ if (open13) movementOpen = true;
72552
72802
  }
72553
72803
  if (movementOpen && (movementFrom === account || legs.some(
72554
72804
  (leg) => (Reflect.get(leg, "from") ?? movementFrom) === account || Reflect.get(leg, "to") === account
@@ -72584,7 +72834,7 @@ async function withAccountMutationLocks(home, accounts, command, operation) {
72584
72834
  const [account, ...remaining] = [...new Set(accounts)].sort();
72585
72835
  if (account === void 0) return await operation();
72586
72836
  return await withFileLock(
72587
- join8(home, `.account-${account}.lock`),
72837
+ join9(home, `.account-${account}.lock`),
72588
72838
  async () => await withAccountMutationLocks(home, remaining, command, operation),
72589
72839
  {
72590
72840
  lockedMessage: `Account ${account} is busy with another account change. Wait for it to finish, then retry ${command}.`
@@ -72659,7 +72909,7 @@ function isLockedVaultError(error61) {
72659
72909
  async function readTrashedVaultAccount(path) {
72660
72910
  let parsed;
72661
72911
  try {
72662
- parsed = JSON.parse(await readFile11(path, "utf8"));
72912
+ parsed = JSON.parse(await readFile12(path, "utf8"));
72663
72913
  } catch {
72664
72914
  return void 0;
72665
72915
  }
@@ -72668,7 +72918,7 @@ async function readTrashedVaultAccount(path) {
72668
72918
  }
72669
72919
  async function readEntrySidecar(path) {
72670
72920
  try {
72671
- const parsed = walletEntrySchema.safeParse(JSON.parse(await readFile11(path, "utf8")));
72921
+ const parsed = walletEntrySchema.safeParse(JSON.parse(await readFile12(path, "utf8")));
72672
72922
  return parsed.success ? parsed.data : void 0;
72673
72923
  } catch {
72674
72924
  return void 0;
@@ -72677,7 +72927,7 @@ async function readEntrySidecar(path) {
72677
72927
  async function readKeystoreSummary(path) {
72678
72928
  let parsed;
72679
72929
  try {
72680
- parsed = JSON.parse(await readFile11(path, "utf8"));
72930
+ parsed = JSON.parse(await readFile12(path, "utf8"));
72681
72931
  } catch {
72682
72932
  return {};
72683
72933
  }
@@ -72695,7 +72945,7 @@ async function readKeystoreSummary(path) {
72695
72945
  }
72696
72946
  async function readConfiguredSpendCaps(configPath) {
72697
72947
  try {
72698
- const parsed = JSON.parse(await readFile11(configPath, "utf8"));
72948
+ const parsed = JSON.parse(await readFile12(configPath, "utf8"));
72699
72949
  const caps = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "spendCaps") : void 0;
72700
72950
  const result = spendCapsSchema.safeParse(caps);
72701
72951
  if (result.success) return result.data;
@@ -72787,7 +73037,7 @@ async function withRegistryLock(path, operation) {
72787
73037
  let handle;
72788
73038
  while (!handle) {
72789
73039
  try {
72790
- handle = await open7(lockPath, "wx", 384);
73040
+ handle = await open8(lockPath, "wx", 384);
72791
73041
  } catch (error61) {
72792
73042
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
72793
73043
  await removeStaleRegistryLock(lockPath);
@@ -72806,7 +73056,7 @@ async function withRegistryLock(path, operation) {
72806
73056
  }
72807
73057
  async function removeStaleRegistryLock(path) {
72808
73058
  try {
72809
- const metadata = await stat7(path);
73059
+ const metadata = await stat9(path);
72810
73060
  if (Date.now() - metadata.mtimeMs > 3e4) await unlink6(path);
72811
73061
  } catch (error61) {
72812
73062
  if (!isMissingFile(error61)) throw error61;
@@ -72814,7 +73064,7 @@ async function removeStaleRegistryLock(path) {
72814
73064
  }
72815
73065
  async function writeJsonFile(path, value) {
72816
73066
  await mkdir10(dirname7(path), { recursive: true, mode: 448 });
72817
- const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
73067
+ const temporaryPath = `${path}.${process.pid}.${randomBytes9(6).toString("hex")}.tmp`;
72818
73068
  await writeFile5(temporaryPath, `${JSON.stringify(value, null, 2)}
72819
73069
  `, {
72820
73070
  encoding: "utf8",
@@ -72852,7 +73102,7 @@ async function createAccount(args) {
72852
73102
  created: false
72853
73103
  };
72854
73104
  }
72855
- if (!await fileExists(join9(args.store.home, "vault.json"))) {
73105
+ if (!await fileExists2(join10(args.store.home, "vault.json"))) {
72856
73106
  throw new KeystoreError("No vault yet. Run vapi setup.");
72857
73107
  }
72858
73108
  const spendCaps = resolveNewAccountCaps(args.caps);
@@ -73119,9 +73369,9 @@ async function requireAddress(store, name) {
73119
73369
  if (address2 === void 0) throw new KeystoreError(`No key for wallet ${name} in the vault.`);
73120
73370
  return address2;
73121
73371
  }
73122
- async function fileExists(path) {
73372
+ async function fileExists2(path) {
73123
73373
  try {
73124
- await stat8(path);
73374
+ await stat10(path);
73125
73375
  return true;
73126
73376
  } catch (error61) {
73127
73377
  if (isMissingFile(error61)) return false;
@@ -73183,9 +73433,9 @@ function secretsAllowed(env, streams) {
73183
73433
  }
73184
73434
 
73185
73435
  // src/agent-profile.ts
73186
- import { randomBytes as randomBytes9 } from "node:crypto";
73187
- import { mkdir as mkdir11, readFile as readFile12, readdir as readdir4, rename as rename8, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
73188
- import { join as join10 } from "node:path";
73436
+ import { randomBytes as randomBytes10 } from "node:crypto";
73437
+ import { mkdir as mkdir11, readFile as readFile13, readdir as readdir4, rename as rename8, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
73438
+ import { join as join11 } from "node:path";
73189
73439
  var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
73190
73440
  var AGENT_GRANTS = ["read", "delegate", "allocate"];
73191
73441
  var agentProfileShape = {
@@ -73215,7 +73465,7 @@ async function readAgentProfile(home, name, options = {}) {
73215
73465
  const path = agentProfilePath(home, name);
73216
73466
  let raw;
73217
73467
  try {
73218
- raw = await readFile12(path, "utf8");
73468
+ raw = await readFile13(path, "utf8");
73219
73469
  } catch (error61) {
73220
73470
  if (isMissingFile(error61)) {
73221
73471
  throw new Error(`No agent named ${name}. Create it with vapi agent create ${name}.`);
@@ -73227,9 +73477,9 @@ async function readAgentProfile(home, name, options = {}) {
73227
73477
  async function writeAgentProfile(home, profile, options = {}) {
73228
73478
  const parsed = (options.schema ?? agentProfileSchema).parse(profile);
73229
73479
  const directory = getVapiPaths(home).agentsDir;
73230
- const path = join10(directory, `${parsed.name}.json`);
73480
+ const path = join11(directory, `${parsed.name}.json`);
73231
73481
  await mkdir11(directory, { recursive: true, mode: 448 });
73232
- const temporaryPath = `${path}.${process.pid}.${randomBytes9(6).toString("hex")}.tmp`;
73482
+ const temporaryPath = `${path}.${process.pid}.${randomBytes10(6).toString("hex")}.tmp`;
73233
73483
  await writeFile6(temporaryPath, `${JSON.stringify(parsed, null, 2)}
73234
73484
  `, {
73235
73485
  encoding: "utf8",
@@ -73254,7 +73504,7 @@ async function listAgentProfiles(home, options = {}) {
73254
73504
  try {
73255
73505
  profiles.push(
73256
73506
  (options.schema ?? agentProfileSchema).parse(
73257
- JSON.parse(await readFile12(join10(directory, file2), "utf8"))
73507
+ JSON.parse(await readFile13(join11(directory, file2), "utf8"))
73258
73508
  )
73259
73509
  );
73260
73510
  } catch {
@@ -73275,11 +73525,11 @@ async function removeAgentProfile(home, name) {
73275
73525
  }
73276
73526
  function agentProfilePath(home, name) {
73277
73527
  const parsedName = walletNameSchema.parse(name);
73278
- return join10(getVapiPaths(home).agentsDir, `${parsedName}.json`);
73528
+ return join11(getVapiPaths(home).agentsDir, `${parsedName}.json`);
73279
73529
  }
73280
73530
 
73281
73531
  // src/ceiling.ts
73282
- import { randomBytes as randomBytes13 } from "node:crypto";
73532
+ import { randomBytes as randomBytes14 } from "node:crypto";
73283
73533
 
73284
73534
  // src/authorization-state.ts
73285
73535
  var EIP3009_AUTHORIZATION_STATE_ABI = [
@@ -73344,13 +73594,13 @@ function missingAuthorization(receipt) {
73344
73594
  }
73345
73595
 
73346
73596
  // src/movement.ts
73347
- import { randomBytes as randomBytes12 } from "node:crypto";
73348
- 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";
73349
- import { join as join11 } from "node:path";
73597
+ import { randomBytes as randomBytes13 } from "node:crypto";
73598
+ 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";
73599
+ import { join as join12 } from "node:path";
73350
73600
 
73351
73601
  // src/spend-policy.ts
73352
- import { randomBytes as randomBytes10 } from "node:crypto";
73353
- 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";
73602
+ import { randomBytes as randomBytes11 } from "node:crypto";
73603
+ 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";
73354
73604
  import { dirname as dirname8 } from "node:path";
73355
73605
  var ledgerSchema = external_exports.object({
73356
73606
  date: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
@@ -73421,7 +73671,7 @@ async function readSpendLedgerRows(path = getAgentCashPaths().ledger, now = /* @
73421
73671
  async function readStoredSpendLedgerRows(path, now, allDays = false) {
73422
73672
  let raw;
73423
73673
  try {
73424
- raw = await readFile13(path, "utf8");
73674
+ raw = await readFile14(path, "utf8");
73425
73675
  } catch (error61) {
73426
73676
  if (isMissingFile(error61)) return [];
73427
73677
  throw error61;
@@ -73554,7 +73804,7 @@ async function reserveSpend(amountAtomic, caps, options) {
73554
73804
  { amountAtomic, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
73555
73805
  );
73556
73806
  }
73557
- const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes10(16).toString("hex"));
73807
+ const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes11(16).toString("hex"));
73558
73808
  const nextRow = {
73559
73809
  date: utcDateKey(now),
73560
73810
  spentAtomic: nextSpent.toString(),
@@ -73660,7 +73910,7 @@ async function writeLedgerAtomically(path, rows) {
73660
73910
  ...rows[0].reservations === void 0 ? {} : { reservations: rows[0].reservations }
73661
73911
  } : { version: 1, rows };
73662
73912
  await mkdir12(dirname8(path), { recursive: true, mode: 448 });
73663
- const temporaryPath = `${path}.${process.pid}.${randomBytes10(6).toString("hex")}.tmp`;
73913
+ const temporaryPath = `${path}.${process.pid}.${randomBytes11(6).toString("hex")}.tmp`;
73664
73914
  await writeFile7(temporaryPath, `${JSON.stringify(ledger, null, 2)}
73665
73915
  `, {
73666
73916
  encoding: "utf8",
@@ -73676,7 +73926,7 @@ async function withLedgerLock(path, operation) {
73676
73926
  let handle;
73677
73927
  while (!handle) {
73678
73928
  try {
73679
- handle = await open8(lockPath, "wx", 384);
73929
+ handle = await open9(lockPath, "wx", 384);
73680
73930
  } catch (error61) {
73681
73931
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) {
73682
73932
  throw error61;
@@ -73697,7 +73947,7 @@ async function withLedgerLock(path, operation) {
73697
73947
  }
73698
73948
  async function removeStaleLock3(path) {
73699
73949
  try {
73700
- const metadata = await stat9(path);
73950
+ const metadata = await stat11(path);
73701
73951
  if (Date.now() - metadata.mtimeMs > 3e4) {
73702
73952
  await unlink8(path);
73703
73953
  }
@@ -73709,8 +73959,8 @@ async function removeStaleLock3(path) {
73709
73959
  }
73710
73960
 
73711
73961
  // src/transfer.ts
73712
- import { randomBytes as randomBytes11, randomUUID } from "node:crypto";
73713
- import { mkdir as mkdir13, open as open9, stat as stat10, unlink as unlink9 } from "node:fs/promises";
73962
+ import { randomBytes as randomBytes12, randomUUID } from "node:crypto";
73963
+ import { mkdir as mkdir13, open as open10, stat as stat12, unlink as unlink9 } from "node:fs/promises";
73714
73964
  import { dirname as dirname9 } from "node:path";
73715
73965
 
73716
73966
  // src/siblings.ts
@@ -73919,7 +74169,7 @@ async function transferBetweenAccounts(args) {
73919
74169
  if (args.resume !== void 0) {
73920
74170
  return await resumeTransfer(context, args.resume);
73921
74171
  }
73922
- const nonce = args.nonce ?? bytesToHex(randomBytes11(32));
74172
+ const nonce = args.nonce ?? bytesToHex(randomBytes12(32));
73923
74173
  if (!NONCE_PATTERN.test(nonce)) {
73924
74174
  throw new TransferError(
73925
74175
  "authorization_invalid",
@@ -74312,7 +74562,7 @@ async function withTransferLock(context, nonce, operation) {
74312
74562
  let handle;
74313
74563
  while (!handle) {
74314
74564
  try {
74315
- handle = await open9(lockPath, "wx", 384);
74565
+ handle = await open10(lockPath, "wx", 384);
74316
74566
  } catch (error61) {
74317
74567
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
74318
74568
  await removeStaleTransferLock(lockPath, staleAfterMs);
@@ -74331,7 +74581,7 @@ async function withTransferLock(context, nonce, operation) {
74331
74581
  }
74332
74582
  async function removeStaleTransferLock(path, staleAfterMs) {
74333
74583
  try {
74334
- const metadata = await stat10(path);
74584
+ const metadata = await stat12(path);
74335
74585
  if (Date.now() - metadata.mtimeMs > staleAfterMs) await unlink9(path);
74336
74586
  } catch (error61) {
74337
74587
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "ENOENT")) throw error61;
@@ -74757,7 +75007,7 @@ async function listUnfinishedMovements(options) {
74757
75007
  }
74758
75008
  const summaries = [];
74759
75009
  for (const name of names.filter((candidate) => candidate.endsWith(".json")).sort()) {
74760
- const movement = parseMovement(JSON.parse(await readFile14(join11(directory, name), "utf8")));
75010
+ const movement = parseMovement(JSON.parse(await readFile15(join12(directory, name), "utf8")));
74761
75011
  if (options.from !== void 0 && !movement.legs.some((leg) => leg.from === options.from)) {
74762
75012
  continue;
74763
75013
  }
@@ -74791,7 +75041,7 @@ async function readMovement(home, id) {
74791
75041
  const safeId = parseMovementId(id);
74792
75042
  try {
74793
75043
  return parseMovement(
74794
- JSON.parse(await readFile14(join11(movementsDirectory(home), `${safeId}.json`), "utf8"))
75044
+ JSON.parse(await readFile15(join12(movementsDirectory(home), `${safeId}.json`), "utf8"))
74795
75045
  );
74796
75046
  } catch (error61) {
74797
75047
  if (isMissingFile(error61)) {
@@ -75463,33 +75713,33 @@ function parseMovementId(value) {
75463
75713
  return parsed.data;
75464
75714
  }
75465
75715
  function movementsDirectory(home) {
75466
- return join11(home, "movements");
75716
+ return join12(home, "movements");
75467
75717
  }
75468
75718
  function createMovementId() {
75469
- return `mv_${randomBytes12(12).toString("hex")}`;
75719
+ return `mv_${randomBytes13(12).toString("hex")}`;
75470
75720
  }
75471
75721
  function createMovementNonce() {
75472
- return bytesToHex(randomBytes12(32));
75722
+ return bytesToHex(randomBytes13(32));
75473
75723
  }
75474
75724
  async function writeMovement(home, movement) {
75475
75725
  const parsed = movementSchema.parse(movement);
75476
75726
  const directory = movementsDirectory(home);
75477
75727
  await mkdir14(directory, { recursive: true, mode: 448 });
75478
75728
  await chmod4(directory, 448);
75479
- const path = join11(directory, `${parsed.id}.json`);
75480
- const temporary = join11(
75729
+ const path = join12(directory, `${parsed.id}.json`);
75730
+ const temporary = join12(
75481
75731
  directory,
75482
- `.${parsed.id}.${process.pid}.${randomBytes12(6).toString("hex")}.tmp`
75732
+ `.${parsed.id}.${process.pid}.${randomBytes13(6).toString("hex")}.tmp`
75483
75733
  );
75484
75734
  let handle;
75485
75735
  try {
75486
- handle = await open10(temporary, "wx", 384);
75736
+ handle = await open11(temporary, "wx", 384);
75487
75737
  await handle.writeFile(serializeMovement(parsed), "utf8");
75488
75738
  await handle.sync();
75489
75739
  await handle.close();
75490
75740
  handle = void 0;
75491
75741
  await rename10(temporary, path);
75492
- const directoryHandle = await open10(directory, "r");
75742
+ const directoryHandle = await open11(directory, "r");
75493
75743
  try {
75494
75744
  await directoryHandle.sync();
75495
75745
  } finally {
@@ -75709,7 +75959,7 @@ async function sweepAboveCeilingLocked(args) {
75709
75959
  owner,
75710
75960
  target,
75711
75961
  amountAtomic: amountAtomic.toString(),
75712
- nonce: (args.randomNonce ?? (() => bytesToHex(randomBytes13(32))))(),
75962
+ nonce: (args.randomNonce ?? (() => bytesToHex(randomBytes14(32))))(),
75713
75963
  createdAt: new Date(now()).toISOString(),
75714
75964
  status: "planned"
75715
75965
  };
@@ -76501,8 +76751,8 @@ function parseDecimal(value, scale) {
76501
76751
  }
76502
76752
 
76503
76753
  // src/swarm.ts
76504
- import { readdir as readdir6, readFile as readFile15, stat as stat11, unlink as unlink11 } from "node:fs/promises";
76505
- import { join as join12 } from "node:path";
76754
+ import { readdir as readdir6, readFile as readFile16, stat as stat13, unlink as unlink11 } from "node:fs/promises";
76755
+ import { join as join13 } from "node:path";
76506
76756
  var SWARM_NAME_PATTERN = /^[a-z][a-z0-9-]{0,15}$/;
76507
76757
  var SWARM_ROLE_PATTERN = /^[a-z][a-z0-9]{0,7}$/;
76508
76758
  var DEFAULT_SWARM_MODEL = "venice/claude-sonnet-5";
@@ -76583,16 +76833,16 @@ var SwarmError = class extends Error {
76583
76833
  code;
76584
76834
  };
76585
76835
  function swarmsDirectory(home) {
76586
- return join12(home, "swarms");
76836
+ return join13(home, "swarms");
76587
76837
  }
76588
76838
  function swarmFilePath(home, name) {
76589
76839
  assertName(name);
76590
- return join12(swarmsDirectory(home), `${name}.json`);
76840
+ return join13(swarmsDirectory(home), `${name}.json`);
76591
76841
  }
76592
76842
  async function readSwarm(home, name) {
76593
76843
  const path = swarmFilePath(home, name);
76594
76844
  try {
76595
- const swarm = parseSwarm(JSON.parse(await readFile15(path, "utf8")));
76845
+ const swarm = parseSwarm(JSON.parse(await readFile16(path, "utf8")));
76596
76846
  if (swarm.name !== name)
76597
76847
  throw new SwarmError("invalid_swarm", "Swarm name does not match its file.");
76598
76848
  return swarm;
@@ -76620,7 +76870,7 @@ async function writeSwarm(home, value) {
76620
76870
  const bytes = `${JSON.stringify(swarm, null, 2)}
76621
76871
  `;
76622
76872
  try {
76623
- if (await readFile15(path, "utf8") === bytes) return;
76873
+ if (await readFile16(path, "utf8") === bytes) return;
76624
76874
  } catch (error61) {
76625
76875
  if (!isMissingFile(error61)) throw error61;
76626
76876
  }
@@ -76635,7 +76885,7 @@ async function deleteSwarmFile(home, name) {
76635
76885
  }
76636
76886
  async function withSwarmLock(home, name, fn) {
76637
76887
  assertName(name);
76638
- const path = join12(swarmsDirectory(home), `.${name}.lock`);
76888
+ const path = join13(swarmsDirectory(home), `.${name}.lock`);
76639
76889
  try {
76640
76890
  return await withFileLock(path, fn, { lockedMessage: `Swarm ${name} is locked.` });
76641
76891
  } catch (error61) {
@@ -76947,7 +77197,7 @@ async function swarmStatus(opts) {
76947
77197
  );
76948
77198
  let movementFiles;
76949
77199
  try {
76950
- movementFiles = await readdir6(join12(home, "movements"));
77200
+ movementFiles = await readdir6(join13(home, "movements"));
76951
77201
  } catch (error61) {
76952
77202
  if (!isMissingFile(error61)) throw error61;
76953
77203
  movementFiles = [];
@@ -77004,11 +77254,11 @@ async function swarmStatus(opts) {
77004
77254
  })
77005
77255
  );
77006
77256
  const accounts = new Set(swarmAccountNames(swarm));
77007
- const open12 = [];
77257
+ const open13 = [];
77008
77258
  for (const summary2 of await listUnfinishedMovements({ home })) {
77009
77259
  const movement = await readMovement(home, summary2.id);
77010
77260
  if (movement.treasury === swarm.treasury.account || movement.legs.some((leg) => accounts.has(leg.from) || accounts.has(leg.to))) {
77011
- open12.push(summary2);
77261
+ open13.push(summary2);
77012
77262
  }
77013
77263
  }
77014
77264
  return {
@@ -77017,7 +77267,7 @@ async function swarmStatus(opts) {
77017
77267
  strategy: swarm.policy.strategy,
77018
77268
  treasury,
77019
77269
  members: members2,
77020
- openMovements: open12.sort(
77270
+ openMovements: open13.sort(
77021
77271
  (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)
77022
77272
  )
77023
77273
  };
@@ -77116,7 +77366,7 @@ async function assertNoConflicts(home, name, accounts) {
77116
77366
  }
77117
77367
  async function profileExists(home, account) {
77118
77368
  try {
77119
- await stat11(join12(getVapiPaths(home).agentsDir, `${account}.json`));
77369
+ await stat13(join13(getVapiPaths(home).agentsDir, `${account}.json`));
77120
77370
  return true;
77121
77371
  } catch (error61) {
77122
77372
  if (isMissingFile(error61)) return false;
@@ -77129,7 +77379,7 @@ async function refuseTreasuryProfile(home, account) {
77129
77379
  }
77130
77380
 
77131
77381
  // src/x402-pay.ts
77132
- import { randomBytes as randomBytes14, randomUUID as randomUUID2 } from "node:crypto";
77382
+ import { randomBytes as randomBytes15, randomUUID as randomUUID2 } from "node:crypto";
77133
77383
 
77134
77384
  // src/run-budget.ts
77135
77385
  var RunBudgetError = class extends Error {
@@ -77170,13 +77420,13 @@ function createRunBudget(args) {
77170
77420
  // src/support-report.ts
77171
77421
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
77172
77422
  import { arch, platform, release } from "node:os";
77173
- import { join as join13 } from "node:path";
77174
- var VAPI_CLIENT_VERSION = "0.12.0";
77423
+ import { join as join14 } from "node:path";
77424
+ var VAPI_CLIENT_VERSION = "0.13.0";
77175
77425
  async function createSupportReport(options) {
77176
77426
  const message = options.message.trim();
77177
77427
  if (!message) throw new Error("Support report message must not be empty.");
77178
77428
  const paths = getVapiPaths();
77179
- const reportsDirectory = options.reportsDirectory ?? join13(paths.directory, "reports");
77429
+ const reportsDirectory = options.reportsDirectory ?? join14(paths.directory, "reports");
77180
77430
  const receipts = await readReceipts(options.receiptsPath ?? paths.receipts, { limit: 5 });
77181
77431
  const system = options.systemInfo ?? defaultSystemInfo();
77182
77432
  const report = {
@@ -77206,7 +77456,7 @@ async function createSupportReport(options) {
77206
77456
  };
77207
77457
  const now = options.now ?? /* @__PURE__ */ new Date();
77208
77458
  const timestamp = now.toISOString();
77209
- const path = join13(reportsDirectory, `${sanitizeTimestamp(timestamp)}.json`);
77459
+ const path = join14(reportsDirectory, `${sanitizeTimestamp(timestamp)}.json`);
77210
77460
  await mkdir15(reportsDirectory, { recursive: true, mode: 448 });
77211
77461
  const serialized = `${JSON.stringify(report, null, 2)}
77212
77462
  `;
@@ -77402,7 +77652,7 @@ async function completeX402Payment(args) {
77402
77652
  throw walletCapError(error61, quote.amountAtomic, args);
77403
77653
  }
77404
77654
  } else {
77405
- reservationId = args.paymentId ?? `x402_${randomBytes14(12).toString("hex")}`;
77655
+ reservationId = args.paymentId ?? `x402_${randomBytes15(12).toString("hex")}`;
77406
77656
  let reservation;
77407
77657
  try {
77408
77658
  reservation = await reserveSpend(quote.amountAtomic, args.caps, {
@@ -78430,7 +78680,7 @@ function validateAmount(amountUsd) {
78430
78680
  }
78431
78681
 
78432
78682
  // src/searches.ts
78433
- import { mkdir as mkdir16, open as open11, readFile as readFile16 } from "node:fs/promises";
78683
+ import { mkdir as mkdir16, open as open12, readFile as readFile17 } from "node:fs/promises";
78434
78684
  import { dirname as dirname10 } from "node:path";
78435
78685
  var searchEventSchema = external_exports.strictObject({
78436
78686
  timestamp: external_exports.iso.datetime(),
@@ -78452,7 +78702,7 @@ function parseSearchEvent(value) {
78452
78702
  async function appendSearchEvent(event, path = getVapiPaths().searches) {
78453
78703
  const parsed = parseSearchEvent(event);
78454
78704
  await mkdir16(dirname10(path), { recursive: true, mode: 448 });
78455
- const handle = await open11(path, "a", 384);
78705
+ const handle = await open12(path, "a", 384);
78456
78706
  try {
78457
78707
  await handle.writeFile(`${JSON.stringify(parsed)}
78458
78708
  `, "utf8");
@@ -78464,7 +78714,7 @@ async function appendSearchEvent(event, path = getVapiPaths().searches) {
78464
78714
  async function readSearchEvents(path = getVapiPaths().searches) {
78465
78715
  let raw;
78466
78716
  try {
78467
- raw = await readFile16(path, "utf8");
78717
+ raw = await readFile17(path, "utf8");
78468
78718
  } catch (error61) {
78469
78719
  if (isMissingFile(error61)) return [];
78470
78720
  throw error61;
@@ -79569,9 +79819,9 @@ function csvCell(value) {
79569
79819
  }
79570
79820
 
79571
79821
  // src/swarm-capital.ts
79572
- import { createHash as createHash3, randomBytes as randomBytes15 } from "node:crypto";
79573
- import { readFile as readFile17, unlink as unlink12 } from "node:fs/promises";
79574
- import { join as join14 } from "node:path";
79822
+ import { createHash as createHash3, randomBytes as randomBytes16 } from "node:crypto";
79823
+ import { readFile as readFile18, unlink as unlink12 } from "node:fs/promises";
79824
+ import { join as join15 } from "node:path";
79575
79825
  var movementIdSchema3 = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/u);
79576
79826
  var amountSchema2 = external_exports.string().regex(/^\d+\.\d{2}$/u);
79577
79827
  var requestIdSchema = external_exports.string().min(1).max(512);
@@ -80452,7 +80702,7 @@ async function readDelegationRecord(home, movementId) {
80452
80702
  const safeId = runRecordMovementId(movementId);
80453
80703
  try {
80454
80704
  const record2 = delegationRecordSchema.parse(
80455
- JSON.parse(await readFile17(delegationRecordPath(home, safeId), "utf8"))
80705
+ JSON.parse(await readFile18(delegationRecordPath(home, safeId), "utf8"))
80456
80706
  );
80457
80707
  if (record2.movementId !== safeId) {
80458
80708
  throw new SwarmError(
@@ -80479,7 +80729,7 @@ async function readTreasuryRequestRecord(home, movementId) {
80479
80729
  const safeId = runRecordMovementId(movementId);
80480
80730
  try {
80481
80731
  const record2 = treasuryRequestRecordSchema.parse(
80482
- JSON.parse(await readFile17(treasuryRequestRecordPath(home, safeId), "utf8"))
80732
+ JSON.parse(await readFile18(treasuryRequestRecordPath(home, safeId), "utf8"))
80483
80733
  );
80484
80734
  if (record2.movementId !== safeId) {
80485
80735
  throw new SwarmError(
@@ -80510,18 +80760,18 @@ function runRecordMovementId(value) {
80510
80760
  return parsed.data;
80511
80761
  }
80512
80762
  function treasuryRequestRecordPath(home, movementId) {
80513
- return join14(home, "runs", "requests", `${movementId}.json`);
80763
+ return join15(home, "runs", "requests", `${movementId}.json`);
80514
80764
  }
80515
80765
  function delegationRecordPath(home, movementId) {
80516
- return join14(home, "runs", "delegations", `${movementId}.json`);
80766
+ return join15(home, "runs", "delegations", `${movementId}.json`);
80517
80767
  }
80518
80768
  function legacyFundingProgressPath(home, name) {
80519
- return join14(home, "swarms", `.${name}.funding`);
80769
+ return join15(home, "swarms", `.${name}.funding`);
80520
80770
  }
80521
80771
  async function readLegacyFundingProgress(home, name) {
80522
80772
  try {
80523
80773
  const progress = legacyFundingProgressSchema.parse(
80524
- JSON.parse(await readFile17(legacyFundingProgressPath(home, name), "utf8"))
80774
+ JSON.parse(await readFile18(legacyFundingProgressPath(home, name), "utf8"))
80525
80775
  );
80526
80776
  if (progress.name !== name) {
80527
80777
  throw new SwarmError("invalid_swarm", `Invalid funding progress for swarm ${name}.`);
@@ -80750,7 +81000,7 @@ async function optionalMovement(home, id) {
80750
81000
  }
80751
81001
  }
80752
81002
  function nextMovementId(deps) {
80753
- return movementIdSchema3.parse(deps.randomId?.() ?? `mv_${randomBytes15(12).toString("hex")}`);
81003
+ return movementIdSchema3.parse(deps.randomId?.() ?? `mv_${randomBytes16(12).toString("hex")}`);
80754
81004
  }
80755
81005
  async function executeRecordedMovement(id, plan, deps, home, options = {}) {
80756
81006
  try {
@@ -81166,7 +81416,7 @@ async function removeMemberLocked(home, swarm, account) {
81166
81416
  }
81167
81417
 
81168
81418
  // src/status.ts
81169
- import { join as join15 } from "node:path";
81419
+ import { join as join16 } from "node:path";
81170
81420
  var STATUS_TIMEOUT_MS = 2e3;
81171
81421
  async function buildStatus(deps) {
81172
81422
  const timers = deps.timers ?? { setTimeout, clearTimeout };
@@ -81222,7 +81472,7 @@ function formatUsdAmount(value) {
81222
81472
  }
81223
81473
  async function readVaultStatus(deps) {
81224
81474
  const store = deps.secrets.description.replace(/^the /u, "");
81225
- const path = join15(deps.home, "vault.json");
81475
+ const path = join16(deps.home, "vault.json");
81226
81476
  let file2;
81227
81477
  try {
81228
81478
  file2 = await readVaultFileUnlocked(path);
@@ -81656,7 +81906,7 @@ function isRecord4(value) {
81656
81906
 
81657
81907
  // src/vault-setup.ts
81658
81908
  import { rm as rm2 } from "node:fs/promises";
81659
- import { join as join16 } from "node:path";
81909
+ import { join as join17 } from "node:path";
81660
81910
  async function createVault2(home, options) {
81661
81911
  if (options.password === "") {
81662
81912
  throw new KeystoreError("A password cannot be empty.");
@@ -81668,7 +81918,7 @@ async function createVault2(home, options) {
81668
81918
  const hadDeviceKey = options.password !== void 0 && await options.secrets.has(VAULT_KEY_ACCOUNT);
81669
81919
  await store.createEmptyVault();
81670
81920
  if (options.password !== void 0) {
81671
- const path = join16(home, "vault.json");
81921
+ const path = join17(home, "vault.json");
81672
81922
  try {
81673
81923
  await protectVault({
81674
81924
  path,
@@ -81790,6 +82040,8 @@ export {
81790
82040
  ERC20_ABI,
81791
82041
  EVM_DERIVATION_PATH,
81792
82042
  EXECUTION_MODES,
82043
+ FILE_SECRET_STORE_MIN_PASSWORD,
82044
+ FILE_SECRET_STORE_PASSWORD_ENV,
81793
82045
  FIRST_PARTY_PROVENANCES,
81794
82046
  FileLockedError,
81795
82047
  KeystoreError,
@@ -81882,6 +82134,7 @@ export {
81882
82134
  ceilingFloorApplies,
81883
82135
  changeKeystorePassphrase,
81884
82136
  checkReceiptSettlement,
82137
+ chooseSecretBackend,
81885
82138
  classifySettlement,
81886
82139
  completeX402Payment,
81887
82140
  configSchema,
@@ -81889,6 +82142,7 @@ export {
81889
82142
  createAccount,
81890
82143
  createAgentProfileSchema,
81891
82144
  createChain,
82145
+ createFileSecretStore,
81892
82146
  createKeystore,
81893
82147
  createKeystoreFromPrivateKey,
81894
82148
  createNetworkHttpTransport,
@@ -81928,6 +82182,7 @@ export {
81928
82182
  explorerAddressUrl,
81929
82183
  explorerTransactionUrl,
81930
82184
  fetchSiblings,
82185
+ fileSecretStore,
81931
82186
  filterReceiptsByRange,
81932
82187
  filterReceiptsByWallet,
81933
82188
  firstPartyProvenanceSchema,
@@ -81999,6 +82254,7 @@ export {
81999
82254
  noPassphraseHint,
82000
82255
  normalizeResourceUrl,
82001
82256
  openRequestMarketplaceHitSchema,
82257
+ osSecretStore,
82002
82258
  parse402Challenge,
82003
82259
  parse402Response,
82004
82260
  parseDiscovery,
@@ -82027,6 +82283,7 @@ export {
82027
82283
  readMovement,
82028
82284
  readReceipts,
82029
82285
  readSearchEvents,
82286
+ readSecretBackend,
82030
82287
  readSolanaGasBalance,
82031
82288
  readSolanaUsdcBalance,
82032
82289
  readSpendLedger,
@@ -82054,8 +82311,10 @@ export {
82054
82311
  scheduleCeilingSweep,
82055
82312
  searchDocs,
82056
82313
  searchServicesResponseSchema,
82314
+ secretBackendPath,
82057
82315
  secretStore,
82058
82316
  secretsAllowed,
82317
+ secretsFilePath,
82059
82318
  serviceOfferMarketplaceHitSchema,
82060
82319
  serviceSummarySchema,
82061
82320
  serviceTierSchema,