@vapi-network/cli 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
@@ -6672,7 +6672,7 @@ function weierstrass(curveDef) {
6672
6672
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
6673
6673
  if (["recovered", "canonical"].some((k) => k in opts))
6674
6674
  throw new Error("sign() legacy options not supported");
6675
- const { hash: hash5, randomBytes: randomBytes17 } = CURVE;
6675
+ const { hash: hash5, randomBytes: randomBytes18 } = CURVE;
6676
6676
  let { lowS, prehash, extraEntropy: ent } = opts;
6677
6677
  if (lowS == null)
6678
6678
  lowS = true;
@@ -6684,7 +6684,7 @@ function weierstrass(curveDef) {
6684
6684
  const d = normPrivateKeyToScalar(privateKey);
6685
6685
  const seedArgs = [int2octets(d), int2octets(h1int)];
6686
6686
  if (ent != null && ent !== false) {
6687
- const e3 = ent === true ? randomBytes17(Fp.BYTES) : ent;
6687
+ const e3 = ent === true ? randomBytes18(Fp.BYTES) : ent;
6688
6688
  seedArgs.push(ensureBytes("extraEntropy", e3));
6689
6689
  }
6690
6690
  const seed = concatBytes3(...seedArgs);
@@ -10117,8 +10117,8 @@ var init_call = __esm({
10117
10117
 
10118
10118
  // src/cli.ts
10119
10119
  import { spawn as spawn5 } from "node:child_process";
10120
- import { stat as stat16 } from "node:fs/promises";
10121
- import { join as join29 } from "node:path";
10120
+ import { stat as stat18 } from "node:fs/promises";
10121
+ import { join as join30 } from "node:path";
10122
10122
  import { createInterface as createInterface3 } from "node:readline/promises";
10123
10123
 
10124
10124
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/external.js
@@ -45226,9 +45226,9 @@ var X402Error = class extends Error {
45226
45226
  function isValidPaymentId(value) {
45227
45227
  return typeof value === "string" && PAYMENT_ID_PATTERN.test(value);
45228
45228
  }
45229
- function createPaymentId(randomBytes17 = fillRandomBytes) {
45229
+ function createPaymentId(randomBytes18 = fillRandomBytes) {
45230
45230
  const bytes = new Uint8Array(16);
45231
- randomBytes17(bytes);
45231
+ randomBytes18(bytes);
45232
45232
  return `pay_${bytesToHex(bytes).slice(2)}`;
45233
45233
  }
45234
45234
  function buildPaymentExtensions(serverExtensions, options = {}) {
@@ -46619,8 +46619,8 @@ function conciseError(error61) {
46619
46619
  }
46620
46620
 
46621
46621
  // ../core/src/account-add.ts
46622
- import { stat as stat8 } from "node:fs/promises";
46623
- import { join as join9 } from "node:path";
46622
+ import { stat as stat10 } from "node:fs/promises";
46623
+ import { join as join10 } from "node:path";
46624
46624
 
46625
46625
  // ../core/src/agent-link.ts
46626
46626
  import { createHash } from "node:crypto";
@@ -70032,20 +70032,20 @@ async function promptForSecret(prompt, noTerminalHint) {
70032
70032
  }
70033
70033
 
70034
70034
  // ../core/src/wallet-store.ts
70035
- import { randomBytes as randomBytes8 } from "node:crypto";
70035
+ import { randomBytes as randomBytes9 } from "node:crypto";
70036
70036
  import {
70037
70037
  chmod as chmod3,
70038
70038
  lstat as lstat2,
70039
70039
  mkdir as mkdir10,
70040
- open as open7,
70040
+ open as open8,
70041
70041
  readdir as readdir3,
70042
- readFile as readFile11,
70042
+ readFile as readFile12,
70043
70043
  rename as rename7,
70044
- stat as stat7,
70044
+ stat as stat9,
70045
70045
  unlink as unlink6,
70046
70046
  writeFile as writeFile5
70047
70047
  } from "node:fs/promises";
70048
- import { dirname as dirname7, join as join8 } from "node:path";
70048
+ import { dirname as dirname7, join as join9 } from "node:path";
70049
70049
 
70050
70050
  // ../core/src/account-movement-lock.ts
70051
70051
  import { randomBytes as randomBytes4 } from "node:crypto";
@@ -70163,497 +70163,16 @@ function isOpenMovementLeg(leg, journalEvidence) {
70163
70163
  // ../core/src/secret-store.ts
70164
70164
  import { spawn } from "node:child_process";
70165
70165
  import { existsSync } from "node:fs";
70166
- import { delimiter, isAbsolute, join as join6, win32 } from "node:path";
70167
- var SECRET_STORE_SERVICE = "vapi-network";
70168
- var SECURITY_BINARY = "/usr/bin/security";
70169
- var SECRET_TOOL_BINARY = "secret-tool";
70170
- var WINDOWS_POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-Command", "-"];
70171
- var SECURITY_ITEM_NOT_FOUND = 44;
70172
- var WINDOWS_SECRET_SUCCESS = 0;
70173
- var WINDOWS_SECRET_NOT_FOUND = 2;
70174
- var UNSUPPORTED_PLATFORM = "No OS secret store on this platform yet; use VAPI_KEYSTORE_PASSWORD.";
70175
- var SECRET_TOOL_MISSING = [
70176
- "secret-tool is not installed, so the passphrase cannot be kept in the OS secret store.",
70177
- "Install libsecret-tools (Debian, Ubuntu) or libsecret (Fedora, Arch), or use VAPI_KEYSTORE_PASSWORD."
70178
- ].join(" ");
70179
- var POWERSHELL_MISSING = [
70180
- "Windows PowerShell (powershell.exe) was not found, so the passphrase cannot be kept in the OS secret store.",
70181
- "Use VAPI_KEYSTORE_PASSWORD."
70182
- ].join(" ");
70183
- function secretStore(options = {}) {
70184
- const platform2 = options.platform ?? process.platform;
70185
- const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
70186
- const env = options.env ?? process.env;
70187
- const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
70188
- if (platform2 === "darwin") return keychainStore(platform2, run);
70189
- if (platform2 === "win32") return windowsDataProtectionStore(platform2, run, env, installed);
70190
- if (platform2 === "linux") return libsecretStore(platform2, run, installed);
70191
- return unsupportedStore(platform2);
70192
- }
70193
- function memorySecretStore(initial = {}) {
70194
- const entries = new Map(Object.entries(initial));
70195
- return {
70196
- available: true,
70197
- platform: process.platform,
70198
- description: "an in-memory store",
70199
- async get(name) {
70200
- return entries.get(name);
70201
- },
70202
- async has(name) {
70203
- return entries.has(name);
70204
- },
70205
- async set(name, passphrase) {
70206
- entries.set(name, passphrase);
70207
- },
70208
- async remove(name) {
70209
- return entries.delete(name);
70210
- },
70211
- async list() {
70212
- return [...entries.keys()].sort();
70213
- }
70214
- };
70215
- }
70216
- function keychainStore(platform2, run) {
70217
- const find = async (account, withPassword) => await run(SECURITY_BINARY, [
70218
- "find-generic-password",
70219
- "-a",
70220
- account,
70221
- "-s",
70222
- SECRET_STORE_SERVICE,
70223
- ...withPassword ? ["-w"] : []
70224
- ]);
70225
- const read = async (account, what) => {
70226
- const result = await find(account, true);
70227
- if (result.code === SECURITY_ITEM_NOT_FOUND) return void 0;
70228
- requireSuccess(result, what);
70229
- const value = withoutTrailingNewline(result.stdout);
70230
- return value.length === 0 ? void 0 : value;
70231
- };
70232
- const write2 = async (account, value, what) => {
70233
- const result = await run(
70234
- SECURITY_BINARY,
70235
- [
70236
- "add-generic-password",
70237
- "-a",
70238
- account,
70239
- "-s",
70240
- SECRET_STORE_SERVICE,
70241
- "-l",
70242
- `${SECRET_STORE_SERVICE} ${account}`,
70243
- "-U",
70244
- "-w"
70245
- ],
70246
- // `security` asks for the password and then for its confirmation.
70247
- `${value}
70248
- ${value}
70249
- `
70250
- );
70251
- requireSuccess(result, what);
70252
- };
70253
- const erase = async (account, what) => {
70254
- const result = await run(SECURITY_BINARY, [
70255
- "delete-generic-password",
70256
- "-a",
70257
- account,
70258
- "-s",
70259
- SECRET_STORE_SERVICE
70260
- ]);
70261
- if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
70262
- requireSuccess(result, what);
70263
- return true;
70264
- };
70265
- const erasePartsAfter = async (account, keep, what) => {
70266
- for (let part = keep + 1; part <= MAX_KEYCHAIN_PARTS; part += 1) {
70267
- if (!await erase(keychainPart(account, part), what)) return;
70268
- }
70269
- };
70270
- return {
70271
- available: true,
70272
- platform: platform2,
70273
- description: "the macOS Keychain",
70274
- async get(name) {
70275
- const account = accountFor(name);
70276
- const what = `read the passphrase of ${name} from the macOS Keychain`;
70277
- const value = await read(account, what);
70278
- const parts = value === void 0 ? void 0 : chunkedPartCount(value);
70279
- if (value === void 0 || parts === void 0) return value;
70280
- let joined = "";
70281
- for (let part = 1; part <= parts; part += 1) {
70282
- const chunk = await read(keychainPart(account, part), what);
70283
- if (chunk === void 0) {
70284
- throw new KeystoreError(
70285
- `The stored secret ${name} is incomplete in the macOS Keychain. Store it again.`
70286
- );
70287
- }
70288
- joined += chunk;
70289
- }
70290
- return joined;
70291
- },
70292
- async has(name) {
70293
- const result = await find(accountFor(name), false);
70294
- if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
70295
- requireSuccess(result, `look up ${name} in the macOS Keychain`);
70296
- return true;
70297
- },
70298
- async set(name, passphrase) {
70299
- requirePassphrase(passphrase);
70300
- const account = accountFor(name);
70301
- const what = `store the passphrase of ${name} in the macOS Keychain`;
70302
- if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
70303
- await write2(account, passphrase, what);
70304
- return;
70305
- }
70306
- const chunks = [];
70307
- for (let index2 = 0; index2 < passphrase.length; index2 += KEYCHAIN_CHUNK) {
70308
- chunks.push(passphrase.slice(index2, index2 + KEYCHAIN_CHUNK));
70309
- }
70310
- if (chunks.length > MAX_KEYCHAIN_PARTS) {
70311
- throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
70312
- }
70313
- for (const [index2, chunk] of chunks.entries()) {
70314
- await write2(keychainPart(account, index2 + 1), chunk, what);
70315
- }
70316
- await erasePartsAfter(account, chunks.length, what);
70317
- await write2(account, `${CHUNKED_MARKER}${chunks.length}`, what);
70318
- },
70319
- async remove(name) {
70320
- const account = accountFor(name);
70321
- const what = `remove the passphrase of ${name} from the macOS Keychain`;
70322
- const found = await find(account, true);
70323
- if (found.code === SECURITY_ITEM_NOT_FOUND) return false;
70324
- requireSuccess(found, what);
70325
- if (chunkedPartCount(withoutTrailingNewline(found.stdout)) !== void 0) {
70326
- await erasePartsAfter(account, 0, what);
70327
- }
70328
- return await erase(account, what);
70329
- }
70330
- };
70331
- }
70332
- var KEYCHAIN_PROMPT_LIMIT = 128;
70333
- var KEYCHAIN_CHUNK = 120;
70334
- var MAX_KEYCHAIN_PARTS = 32;
70335
- var CHUNKED_MARKER = "vapi-chunked:v1:";
70336
- function keychainPart(account, part) {
70337
- return `${account}#${part}`;
70338
- }
70339
- function chunkedPartCount(value) {
70340
- if (!value.startsWith(CHUNKED_MARKER)) return void 0;
70341
- const parts = Number(value.slice(CHUNKED_MARKER.length));
70342
- return Number.isInteger(parts) && parts > 0 && parts <= MAX_KEYCHAIN_PARTS ? parts : void 0;
70343
- }
70344
- function windowsSecretFileName(account) {
70345
- let encoded = "";
70346
- for (let index2 = 0; index2 < account.length; index2 += 1) {
70347
- const character = account[index2];
70348
- if (/^[a-z0-9._#-]$/u.test(character)) {
70349
- encoded += character;
70350
- continue;
70351
- }
70352
- encoded += `%${account.charCodeAt(index2).toString(16).toUpperCase().padStart(4, "0")}`;
70353
- }
70354
- if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(encoded)) {
70355
- encoded = `%${encoded.charCodeAt(0).toString(16).toUpperCase()}${encoded.slice(1)}`;
70356
- }
70357
- return `${encoded}.bin`;
70358
- }
70359
- function windowsDataProtectionStore(platform2, run, env, installed) {
70360
- const powershell = `${env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
70361
- const fileDetails = (name) => {
70362
- const file2 = windowsSecretFileName(accountFor(name));
70363
- return { file: file2, account: file2.slice(0, -".bin".length) };
70364
- };
70365
- const script = (file2, operations) => [
70366
- "$ErrorActionPreference = 'Stop'",
70367
- "try {",
70368
- " Add-Type -AssemblyName System.Security",
70369
- " $dir = Join-Path $env:LOCALAPPDATA 'vapi-network\\secrets'",
70370
- ` $path = Join-Path $dir '${file2}'`,
70371
- ...operations.map((operation) => ` ${operation}`),
70372
- "} catch {",
70373
- " [Console]::Error.WriteLine($_.Exception.Message)",
70374
- " exit 1",
70375
- "}"
70376
- ].join("\n");
70377
- const execute = async (script2) => {
70378
- const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
70379
-
70380
- `);
70381
- requirePowerShell(result);
70382
- return result;
70383
- };
70384
- return {
70385
- available: installed(powershell),
70386
- platform: platform2,
70387
- description: "Windows Data Protection (DPAPI)",
70388
- async get(name) {
70389
- const { file: file2, account } = fileDetails(name);
70390
- const result = await execute(
70391
- script(file2, [
70392
- `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
70393
- "$blob = [System.IO.File]::ReadAllBytes($path)",
70394
- "$bytes = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
70395
- "[Console]::Out.Write([Convert]::ToBase64String($bytes))",
70396
- `exit ${WINDOWS_SECRET_SUCCESS}`
70397
- ])
70398
- );
70399
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return void 0;
70400
- requireSuccess(result, `read the passphrase of ${name} from Windows Data Protection`);
70401
- const value = Buffer.from(result.stdout.trim(), "base64").toString("utf8");
70402
- return value.length === 0 ? void 0 : value;
70403
- },
70404
- async has(name) {
70405
- const { file: file2, account } = fileDetails(name);
70406
- const result = await execute(
70407
- script(file2, [
70408
- `if (Test-Path -LiteralPath $path) { exit ${WINDOWS_SECRET_SUCCESS} }`,
70409
- `[Console]::Error.WriteLine('No stored secret for ${account}.')`,
70410
- `exit ${WINDOWS_SECRET_NOT_FOUND}`
70411
- ])
70412
- );
70413
- if (result.code === WINDOWS_SECRET_SUCCESS) return true;
70414
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
70415
- requireSuccess(result, `look up ${name} in Windows Data Protection`);
70416
- return false;
70417
- },
70418
- async set(name, passphrase) {
70419
- requirePassphrase(passphrase);
70420
- const { file: file2 } = fileDetails(name);
70421
- const value = Buffer.from(passphrase, "utf8").toString("base64");
70422
- const result = await execute(
70423
- script(file2, [
70424
- "[void][System.IO.Directory]::CreateDirectory($dir)",
70425
- `$bytes = [Convert]::FromBase64String('${value}')`,
70426
- "$blob = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
70427
- "[System.IO.File]::WriteAllBytes($path, $blob)",
70428
- `exit ${WINDOWS_SECRET_SUCCESS}`
70429
- ])
70430
- );
70431
- requireSuccess(result, `store the passphrase of ${name} in Windows Data Protection`);
70432
- },
70433
- async remove(name) {
70434
- const { file: file2, account } = fileDetails(name);
70435
- const result = await execute(
70436
- script(file2, [
70437
- `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
70438
- "Remove-Item -LiteralPath $path -Force",
70439
- `exit ${WINDOWS_SECRET_SUCCESS}`
70440
- ])
70441
- );
70442
- if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
70443
- requireSuccess(result, `remove the passphrase of ${name} from Windows Data Protection`);
70444
- return true;
70445
- }
70446
- };
70447
- }
70448
- function libsecretStore(platform2, run, installed) {
70449
- const lookup2 = async (name) => {
70450
- const result = await run(SECRET_TOOL_BINARY, [
70451
- "lookup",
70452
- "service",
70453
- SECRET_STORE_SERVICE,
70454
- "account",
70455
- accountFor(name)
70456
- ]);
70457
- requireBinary(result);
70458
- const value = withoutTrailingNewline(result.stdout);
70459
- if (result.code === 0) return value.length === 0 ? void 0 : value;
70460
- if (result.stderr.trim().length === 0) return void 0;
70461
- requireSuccess(result, `read the passphrase of ${name} from the secret service`);
70462
- return void 0;
70463
- };
70464
- return {
70465
- available: installed(SECRET_TOOL_BINARY),
70466
- platform: platform2,
70467
- description: "the libsecret keyring",
70468
- get: lookup2,
70469
- async has(name) {
70470
- return await lookup2(name) !== void 0;
70471
- },
70472
- async set(name, passphrase) {
70473
- requirePassphrase(passphrase);
70474
- const account = accountFor(name);
70475
- const result = await run(
70476
- SECRET_TOOL_BINARY,
70477
- [
70478
- "store",
70479
- `--label=${SECRET_STORE_SERVICE} ${account}`,
70480
- "service",
70481
- SECRET_STORE_SERVICE,
70482
- "account",
70483
- account
70484
- ],
70485
- `${passphrase}
70486
- `
70487
- );
70488
- requireBinary(result);
70489
- requireSuccess(result, `store the passphrase of ${name} in the secret service`);
70490
- },
70491
- async remove(name) {
70492
- const existed = await lookup2(name) !== void 0;
70493
- const result = await run(SECRET_TOOL_BINARY, [
70494
- "clear",
70495
- "service",
70496
- SECRET_STORE_SERVICE,
70497
- "account",
70498
- accountFor(name)
70499
- ]);
70500
- requireBinary(result);
70501
- requireSuccess(result, `remove the passphrase of ${name} from the secret service`);
70502
- return existed;
70503
- }
70504
- };
70505
- }
70506
- function unsupportedStore(platform2) {
70507
- const refuse = () => {
70508
- throw new KeystoreError(UNSUPPORTED_PLATFORM);
70509
- };
70510
- return {
70511
- available: false,
70512
- platform: platform2,
70513
- description: "no OS secret store",
70514
- get: async () => refuse(),
70515
- has: async () => refuse(),
70516
- set: async () => refuse(),
70517
- remove: async () => refuse()
70518
- };
70519
- }
70520
- function accountFor(name) {
70521
- const account = name.trim();
70522
- if (account.length === 0) {
70523
- throw new KeystoreError("A wallet name is needed to reach the OS secret store.");
70524
- }
70525
- return account;
70526
- }
70527
- function requirePassphrase(passphrase) {
70528
- if (passphrase.length === 0) {
70529
- throw new KeystoreError("Keystore passphrase cannot be empty.");
70530
- }
70531
- }
70532
- function requireBinary(result) {
70533
- if (result.notFound === true) throw new KeystoreError(SECRET_TOOL_MISSING);
70534
- }
70535
- function requirePowerShell(result) {
70536
- if (result.notFound === true) throw new KeystoreError(POWERSHELL_MISSING);
70537
- }
70538
- function binaryInstalled(file2, env) {
70539
- if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
70540
- return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join6(directory, file2)));
70541
- }
70542
- function requireSuccess(result, what) {
70543
- if (result.code === 0) return;
70544
- const detail = result.stderr.trim() || result.stdout.trim();
70545
- throw new KeystoreError(
70546
- `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail.length === 0 ? "" : ` ${detail}`}`
70547
- );
70548
- }
70549
- function withoutTrailingNewline(value) {
70550
- return value.replace(/\r?\n$/u, "");
70551
- }
70552
- var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve3) => {
70553
- let stdout = "";
70554
- let stderr2 = "";
70555
- let settled = false;
70556
- const finish = (outcome) => {
70557
- if (settled) return;
70558
- settled = true;
70559
- resolve3(outcome);
70560
- };
70561
- const child = spawn(file2, [...args], {
70562
- detached: platform2 !== "win32",
70563
- stdio: ["pipe", "pipe", "pipe"],
70564
- windowsHide: true
70565
- });
70566
- child.stdout?.setEncoding("utf8");
70567
- child.stdout?.on("data", (chunk) => {
70568
- stdout += chunk;
70569
- });
70570
- child.stderr?.setEncoding("utf8");
70571
- child.stderr?.on("data", (chunk) => {
70572
- stderr2 += chunk;
70573
- });
70574
- child.on("error", (error61) => {
70575
- finish({
70576
- code: null,
70577
- stdout,
70578
- stderr: stderr2,
70579
- ...error61.code === "ENOENT" ? { notFound: true } : {}
70580
- });
70581
- });
70582
- child.on("close", (code) => finish({ code, stdout, stderr: stderr2 }));
70583
- child.stdin?.on("error", () => void 0);
70584
- child.stdin?.end(input2 ?? "");
70585
- });
70586
-
70587
- // ../core/src/passphrase.ts
70588
- var PASSPHRASE_ENVIRONMENT_VARIABLE = "VAPI_KEYSTORE_PASSWORD";
70589
- function noPassphraseHint(walletName) {
70590
- return `Set ${PASSPHRASE_ENVIRONMENT_VARIABLE}, or store this wallet's passphrase once with vapi unlock --wallet ${walletName}.`;
70591
- }
70592
- function staleStoredPassphraseMessage(walletName, store) {
70593
- return [
70594
- `The passphrase stored in ${store.description} no longer opens wallet ${walletName}.`,
70595
- `Store the current one with vapi unlock --wallet ${walletName}, or remove it with vapi lock --wallet ${walletName}.`
70596
- ].join(" ");
70597
- }
70598
- async function resolvePassphrase(walletName, options = {}) {
70599
- const env = options.env ?? process.env;
70600
- const fromEnvironment = env[PASSPHRASE_ENVIRONMENT_VARIABLE];
70601
- if (fromEnvironment !== void 0) {
70602
- if (fromEnvironment.length === 0) {
70603
- throw new KeystoreError(`${PASSPHRASE_ENVIRONMENT_VARIABLE} cannot be empty.`);
70604
- }
70605
- return { passphrase: fromEnvironment, source: "environment" };
70606
- }
70607
- if (options.confirm !== true) {
70608
- const stored = await readStored(options.store ?? secretStore(), walletName);
70609
- if (stored !== void 0) return { passphrase: stored, source: "secret-store" };
70610
- }
70611
- const hint = noPassphraseHint(walletName);
70612
- if (options.interactive === false) {
70613
- throw new KeystoreError(
70614
- `No interactive terminal is available for the keystore prompt. ${hint}`
70615
- );
70616
- }
70617
- const prompt = options.prompt ?? promptForSecret;
70618
- const first = await prompt(`Passphrase for ${walletName}: `, hint);
70619
- if (first.length === 0) {
70620
- throw new KeystoreError("Keystore passphrase cannot be empty.");
70621
- }
70622
- if (options.confirm === true) {
70623
- const second = await prompt("Confirm passphrase: ", hint);
70624
- if (first !== second) throw new KeystoreError("Passphrases do not match.");
70625
- }
70626
- return { passphrase: first, source: "prompt" };
70627
- }
70628
- async function readStored(store, walletName) {
70629
- if (!store.available) return void 0;
70630
- try {
70631
- return await store.get(walletName);
70632
- } catch {
70633
- return void 0;
70634
- }
70635
- }
70166
+ import { delimiter, isAbsolute, join as join7, win32 } from "node:path";
70636
70167
 
70637
- // ../core/src/receipts.ts
70168
+ // ../core/src/file-secret-store.ts
70638
70169
  import { randomBytes as randomBytes6 } from "node:crypto";
70639
- import { mkdir as mkdir7, open as open5, readFile as readFile7, rename as rename4, writeFile as writeFile3 } from "node:fs/promises";
70640
- import { dirname as dirname5 } from "node:path";
70170
+ import { readFile as readFile8, stat as stat7 } from "node:fs/promises";
70641
70171
 
70642
- // ../core/src/agent-run.ts
70172
+ // ../core/src/vault.ts
70643
70173
  import { randomBytes as randomBytes5 } from "node:crypto";
70644
- var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
70645
- function isRunId(value) {
70646
- return typeof value === "string" && RUN_ID_PATTERN.test(value);
70647
- }
70648
- function createRunId(random = randomBytes5) {
70649
- return `run_${Buffer.from(random(12)).toString("hex")}`;
70650
- }
70651
- var runRefSchema = external_exports.strictObject({
70652
- id: external_exports.string().regex(RUN_ID_PATTERN),
70653
- swarm: external_exports.string().optional(),
70654
- member: external_exports.string().optional(),
70655
- parentRunId: external_exports.string().optional()
70656
- });
70174
+ 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";
70175
+ import { dirname as dirname5 } from "node:path";
70657
70176
 
70658
70177
  // ../core/src/wallet-name.ts
70659
70178
  var DEFAULT_WALLET_NAME = "main";
@@ -70666,260 +70185,7 @@ function isWalletName(value) {
70666
70185
  return WALLET_NAME_PATTERN.test(value);
70667
70186
  }
70668
70187
 
70669
- // ../core/src/receipts.ts
70670
- var receiptTestHooks;
70671
- var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
70672
- async function withReceiptJournalLock(path, operation) {
70673
- return await withFileLock(`${path}.lock`, operation, {
70674
- lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
70675
- });
70676
- }
70677
- var durationSchema = external_exports.number().nonnegative().finite();
70678
- var receiptSchema = external_exports.strictObject({
70679
- id: external_exports.string().min(1),
70680
- timestamp: external_exports.iso.datetime(),
70681
- run: runRefSchema.optional(),
70682
- kind: external_exports.literal("transfer").optional(),
70683
- wallet: walletNameSchema.optional(),
70684
- resourceUrl: external_exports.url(),
70685
- method: external_exports.string().min(1).optional(),
70686
- source: external_exports.string().min(1).optional(),
70687
- provenance: external_exports.array(
70688
- external_exports.strictObject({
70689
- source: external_exports.string().min(1),
70690
- sourceUrl: external_exports.string().optional(),
70691
- ref: external_exports.string().optional()
70692
- })
70693
- ).optional(),
70694
- quote: external_exports.strictObject({
70695
- network: external_exports.string(),
70696
- asset: external_exports.string().optional(),
70697
- amountAtomic: external_exports.string().regex(/^\d+$/),
70698
- payTo: external_exports.string().optional()
70699
- }).optional(),
70700
- payer: external_exports.string().optional(),
70701
- paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
70702
- authorization: external_exports.strictObject({
70703
- from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70704
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
70705
- validBefore: external_exports.string().regex(/^\d+$/)
70706
- }).optional(),
70707
- transfer: external_exports.strictObject({
70708
- to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70709
- toName: external_exports.string().min(1),
70710
- toKind: external_exports.enum(["owner", "account"]),
70711
- amountAtomic: external_exports.string().regex(/^\d+$/),
70712
- network: external_exports.string().min(1),
70713
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
70714
- status: external_exports.enum(["sent", "unknown", "failed"]),
70715
- txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
70716
- replayed: external_exports.boolean(),
70717
- reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
70718
- request: external_exports.strictObject({
70719
- authorization: external_exports.strictObject({
70720
- from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70721
- to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
70722
- value: external_exports.string().regex(/^\d+$/),
70723
- validAfter: external_exports.string().regex(/^\d+$/),
70724
- validBefore: external_exports.string().regex(/^\d+$/),
70725
- nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
70726
- }),
70727
- signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
70728
- }).optional()
70729
- }).optional(),
70730
- settlement: external_exports.strictObject({
70731
- outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
70732
- transaction: external_exports.string().optional(),
70733
- explorerUrl: external_exports.url().optional(),
70734
- evidence: external_exports.unknown().optional()
70735
- }).optional(),
70736
- latencyMs: external_exports.number().nonnegative().finite().optional(),
70737
- status: external_exports.number().int().min(100).max(599).optional(),
70738
- error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
70739
- phases: external_exports.strictObject({
70740
- discoverMs: durationSchema.optional(),
70741
- quoteMs: durationSchema.optional(),
70742
- signMs: durationSchema.optional(),
70743
- requestMs: durationSchema.optional(),
70744
- settleMs: durationSchema.optional()
70745
- }).optional(),
70746
- listing: external_exports.strictObject({
70747
- name: external_exports.string().min(1).optional(),
70748
- providerHost: external_exports.string().min(1).optional(),
70749
- source: external_exports.string().min(1)
70750
- }).optional(),
70751
- retry: external_exports.number().int().nonnegative().optional(),
70752
- policy: external_exports.strictObject({
70753
- maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
70754
- capsApplied: external_exports.boolean()
70755
- }).optional(),
70756
- client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
70757
- outcome: external_exports.enum([
70758
- "paid",
70759
- "signed_in",
70760
- "declined_policy",
70761
- "failed_request",
70762
- "settlement_rejected",
70763
- "settlement_unknown"
70764
- ]).optional()
70765
- });
70766
- function parseReceipt(value) {
70767
- const receipt = receiptSchema.parse(value);
70768
- const transaction2 = receipt.settlement?.transaction;
70769
- const network = receipt.quote?.network;
70770
- const explorerUrl = transaction2 === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction2);
70771
- if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
70772
- return receipt;
70773
- }
70774
- return {
70775
- ...receipt,
70776
- settlement: {
70777
- outcome: receipt.settlement.outcome,
70778
- ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
70779
- explorerUrl,
70780
- ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
70781
- }
70782
- };
70783
- }
70784
- async function appendReceipt(receipt, path = getVapiPaths().receipts, options = {}) {
70785
- const parsed = parseReceipt(
70786
- receipt.wallet === void 0 && options.wallet !== void 0 ? { ...receipt, wallet: options.wallet } : receipt
70787
- );
70788
- await withReceiptJournalLock(path, async () => {
70789
- await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70790
- const handle = await open5(path, "a", 384);
70791
- try {
70792
- await handle.writeFile(`${JSON.stringify(parsed)}
70793
- `, "utf8");
70794
- } finally {
70795
- await handle.close();
70796
- }
70797
- });
70798
- return parsed;
70799
- }
70800
- async function readReceipts(path = getVapiPaths().receipts, options = {}) {
70801
- let raw;
70802
- try {
70803
- raw = await readFile7(path, "utf8");
70804
- } catch (error61) {
70805
- if (isMissingFile(error61)) return [];
70806
- throw error61;
70807
- }
70808
- const records = coalesceTransferReceiptRevisions(
70809
- raw.split("\n").filter((line) => line.trim().length > 0).map((line, index2) => {
70810
- try {
70811
- return parseReceipt(JSON.parse(line));
70812
- } catch (error61) {
70813
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70814
- }
70815
- })
70816
- );
70817
- const filtered = options.wallet === void 0 ? records : filterReceiptsByWallet(records, options.wallet);
70818
- const limit = options.limit;
70819
- if (limit === void 0) return filtered;
70820
- if (!Number.isSafeInteger(limit) || limit < 0)
70821
- throw new Error("Receipt limit must be a non-negative integer.");
70822
- return limit === 0 ? [] : filtered.slice(-limit);
70823
- }
70824
- function coalesceTransferReceiptRevisions(receipts) {
70825
- const coalesced = [];
70826
- const transferIndexes = /* @__PURE__ */ new Map();
70827
- for (const receipt of receipts) {
70828
- const existing = receipt.kind === "transfer" ? transferIndexes.get(receipt.id) : void 0;
70829
- if (existing === void 0) {
70830
- if (receipt.kind === "transfer") transferIndexes.set(receipt.id, coalesced.length);
70831
- coalesced.push(receipt);
70832
- } else {
70833
- coalesced[existing] = receipt;
70834
- }
70835
- }
70836
- return coalesced;
70837
- }
70838
- function receiptWallet(receipt) {
70839
- return receipt.wallet ?? DEFAULT_WALLET_NAME;
70840
- }
70841
- function filterReceiptsByWallet(receipts, name) {
70842
- return receipts.filter((receipt) => receiptWallet(receipt) === name);
70843
- }
70844
- async function renameReceiptWallet(from16, to, path = getVapiPaths().receipts) {
70845
- return await withReceiptJournalLock(path, async () => {
70846
- let raw;
70847
- try {
70848
- raw = await readFile7(path, "utf8");
70849
- } catch (error61) {
70850
- if (isMissingFile(error61)) return 0;
70851
- throw error61;
70852
- }
70853
- let changed = 0;
70854
- const lines = raw.split("\n").map((line, index2) => {
70855
- if (line.trim().length === 0) return line;
70856
- let parsed;
70857
- try {
70858
- parsed = JSON.parse(line);
70859
- } catch (error61) {
70860
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70861
- }
70862
- const current = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "wallet") : void 0;
70863
- if ((typeof current === "string" ? current : DEFAULT_WALLET_NAME) !== from16) return line;
70864
- changed += 1;
70865
- return JSON.stringify(parseReceipt({ ...parsed, wallet: to }));
70866
- });
70867
- if (changed === 0) return 0;
70868
- await receiptTestHooks?.beforeRenameReplace?.(path);
70869
- await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70870
- const temporaryPath = `${path}.${process.pid}.${randomBytes6(6).toString("hex")}.tmp`;
70871
- await writeFile3(temporaryPath, lines.join("\n"), {
70872
- encoding: "utf8",
70873
- mode: 384,
70874
- flag: "wx"
70875
- });
70876
- await rename4(temporaryPath, path);
70877
- return changed;
70878
- });
70879
- }
70880
-
70881
- // ../core/src/transfer-journal.ts
70882
- import { readFile as readFile8 } from "node:fs/promises";
70883
- async function readTransferJournal(home, from16, nonce) {
70884
- let raw;
70885
- try {
70886
- raw = await readFile8(getVapiPaths(home).receipts, "utf8");
70887
- } catch (error61) {
70888
- if (isMissingFile(error61)) return { signed: false };
70889
- throw error61;
70890
- }
70891
- let latest;
70892
- let request;
70893
- for (const [index2, line] of raw.split("\n").entries()) {
70894
- if (!line.trim()) continue;
70895
- let receipt;
70896
- try {
70897
- receipt = parseReceipt(JSON.parse(line));
70898
- } catch (error61) {
70899
- throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
70900
- }
70901
- if (receiptWallet(receipt) !== from16 || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
70902
- continue;
70903
- }
70904
- latest = receipt;
70905
- if (receipt.transfer.request !== void 0) request = receipt;
70906
- }
70907
- return {
70908
- signed: latest !== void 0,
70909
- ...latest === void 0 ? {} : { latest },
70910
- ...request === void 0 ? {} : { request },
70911
- ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
70912
- ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
70913
- };
70914
- }
70915
-
70916
- // ../core/src/vault-key.ts
70917
- import { randomBytes as cryptoRandomBytes } from "node:crypto";
70918
-
70919
70188
  // ../core/src/vault.ts
70920
- import { randomBytes as randomBytes7 } from "node:crypto";
70921
- 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";
70922
- import { dirname as dirname6 } from "node:path";
70923
70189
  var VaultError = class extends Error {
70924
70190
  code;
70925
70191
  constructor(code, message, options) {
@@ -71305,249 +70571,1227 @@ async function exportVaultAccountKey(args) {
71305
70571
  if (privateKeyToAccount(privateKey).address.toLowerCase() !== account.address.toLowerCase()) {
71306
70572
  throw new VaultError("corrupt", "A vault key does not match its stored address.");
71307
70573
  }
71308
- return privateKey;
71309
- } catch (error61) {
71310
- throw asVaultError(error61, "corrupt", "Unable to export the vault account key.");
70574
+ return privateKey;
70575
+ } catch (error61) {
70576
+ throw asVaultError(error61, "corrupt", "Unable to export the vault account key.");
70577
+ }
70578
+ }
70579
+ async function exportMemberKey(args) {
70580
+ return await exportVaultAccountKey(args);
70581
+ }
70582
+ function assertVaultKey(key2) {
70583
+ if (key2.byteLength !== 32) {
70584
+ throw new VaultError("bad_key", "A device vault key must contain exactly 32 bytes.");
70585
+ }
70586
+ }
70587
+ function assertAccountName(name) {
70588
+ const parsed = walletNameSchema.safeParse(name);
70589
+ if (!parsed.success) {
70590
+ throw new VaultError("name_taken", "The vault account name is not valid.", {
70591
+ cause: parsed.error
70592
+ });
70593
+ }
70594
+ }
70595
+ function assertAvailableName(file2, name) {
70596
+ assertAccountName(name);
70597
+ if (file2.accounts.some((account) => account.name === name)) {
70598
+ throw new VaultError("name_taken", "A vault account already has that name.");
70599
+ }
70600
+ }
70601
+ function nextDerivedIndex(file2) {
70602
+ let next = file2.nextDerivedIndex ?? 0;
70603
+ for (const account of file2.accounts) {
70604
+ if (account.kind === "derived") next = Math.max(next, account.index + 1);
70605
+ }
70606
+ return next;
70607
+ }
70608
+ function copyAccount(account) {
70609
+ if (account.kind === "derived") return { ...account };
70610
+ return {
70611
+ name: account.name,
70612
+ kind: account.kind,
70613
+ address: account.address,
70614
+ createdAt: account.createdAt
70615
+ };
70616
+ }
70617
+ function sealField(key2, plaintext) {
70618
+ const { nonce, ciphertext, tag } = encryptWithKey(key2, plaintext);
70619
+ return [nonce, ciphertext, tag].map((part) => part.toString("base64url")).join(".");
70620
+ }
70621
+ function openField(key2, value) {
70622
+ const [nonce = "", ciphertext = "", tag = ""] = value.split(".");
70623
+ return decryptWithKey(key2, {
70624
+ nonce: Buffer.from(nonce, "base64url"),
70625
+ ciphertext: Buffer.from(ciphertext, "base64url"),
70626
+ tag: Buffer.from(tag, "base64url")
70627
+ });
70628
+ }
70629
+ function decryptField(key2, value) {
70630
+ try {
70631
+ return openField(key2, value);
70632
+ } catch (error61) {
70633
+ throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70634
+ cause: error61
70635
+ });
70636
+ }
70637
+ }
70638
+ function decryptPhraseForOpen(key2, phrase) {
70639
+ try {
70640
+ return openField(key2, phrase);
70641
+ } catch (error61) {
70642
+ throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
70643
+ cause: error61
70644
+ });
70645
+ }
70646
+ }
70647
+ function validateStoredImportedAccount(key2, account) {
70648
+ let plaintext;
70649
+ try {
70650
+ plaintext = decryptField(key2, account.key);
70651
+ if (plaintext.byteLength !== 32) {
70652
+ throw new VaultError("bad_key", "The stored imported key has the wrong length.");
70653
+ }
70654
+ let address4;
70655
+ try {
70656
+ address4 = privateKeyToAccount(`0x${plaintext.toString("hex")}`).address;
70657
+ } catch (error61) {
70658
+ throw new VaultError("bad_key", "The stored imported key is not valid.", {
70659
+ cause: error61
70660
+ });
70661
+ }
70662
+ if (address4.toLowerCase() !== account.address.toLowerCase()) {
70663
+ throw new VaultError("bad_key", "The stored imported key does not match its address.");
70664
+ }
70665
+ } finally {
70666
+ plaintext?.fill(0);
70667
+ }
70668
+ }
70669
+ function validateStoredDerivedAccount(key2, file2, account) {
70670
+ const plaintext = decryptField(key2, file2.phrase);
70671
+ let seed;
70672
+ try {
70673
+ seed = phraseToSeed(plaintext.toString("utf8"));
70674
+ const address4 = privateKeyToAccount(
70675
+ deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${account.index}`)
70676
+ ).address;
70677
+ if (address4.toLowerCase() !== account.address.toLowerCase()) {
70678
+ throw new VaultError("bad_key", "The stored derived account does not match this vault.");
70679
+ }
70680
+ } finally {
70681
+ seed?.fill(0);
70682
+ plaintext.fill(0);
70683
+ }
70684
+ }
70685
+ function parseVaultFile(raw) {
70686
+ let value;
70687
+ try {
70688
+ value = JSON.parse(raw);
70689
+ } catch (error61) {
70690
+ throw new VaultError("corrupt", "The vault file is not valid JSON.", { cause: error61 });
70691
+ }
70692
+ const parsed = vaultFileSchema.safeParse(value);
70693
+ if (!parsed.success) {
70694
+ throw new VaultError("corrupt", "The vault file has an invalid structure.", {
70695
+ cause: parsed.error
70696
+ });
70697
+ }
70698
+ if (parsed.data.protected !== (parsed.data.wrappedKey !== void 0)) {
70699
+ throw new VaultError("corrupt", "The vault protection metadata is inconsistent.");
70700
+ }
70701
+ const names = /* @__PURE__ */ new Set();
70702
+ const indexes = /* @__PURE__ */ new Set();
70703
+ for (const account of parsed.data.accounts) {
70704
+ if (names.has(account.name)) {
70705
+ throw new VaultError("corrupt", "The vault file contains duplicate account names.");
70706
+ }
70707
+ names.add(account.name);
70708
+ if (account.kind === "derived") {
70709
+ if (indexes.has(account.index)) {
70710
+ throw new VaultError("corrupt", "The vault file contains duplicate derived indexes.");
70711
+ }
70712
+ indexes.add(account.index);
70713
+ }
70714
+ }
70715
+ return parsed.data;
70716
+ }
70717
+ async function readVaultFile(path, key2) {
70718
+ const file2 = await readVaultFileUnlocked(path);
70719
+ const plaintext = decryptPhraseForOpen(key2, file2.phrase);
70720
+ try {
70721
+ try {
70722
+ validateRecoveryPhrase(plaintext.toString("utf8"));
70723
+ } catch (error61) {
70724
+ throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
70725
+ cause: error61
70726
+ });
70727
+ }
70728
+ } finally {
70729
+ plaintext.fill(0);
70730
+ }
70731
+ return file2;
70732
+ }
70733
+ async function readVaultFileUnlocked(path) {
70734
+ let raw;
70735
+ try {
70736
+ raw = await readFile7(path, "utf8");
70737
+ } catch (error61) {
70738
+ if (isMissingFile2(error61)) {
70739
+ throw new VaultError("not_found", "No vault file was found at the requested path.", {
70740
+ cause: error61
70741
+ });
70742
+ }
70743
+ throw new VaultError("corrupt", "Unable to read the vault file.", { cause: error61 });
70744
+ }
70745
+ return parseVaultFile(raw);
70746
+ }
70747
+ async function refuseExistingVault(path) {
70748
+ try {
70749
+ await stat6(path);
70750
+ } catch (error61) {
70751
+ if (isMissingFile2(error61)) return;
70752
+ throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
70753
+ cause: error61
70754
+ });
70755
+ }
70756
+ throw new VaultError("corrupt", "A vault already exists at the requested path.");
70757
+ }
70758
+ async function writeVaultFile(path, file2) {
70759
+ await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70760
+ const temporaryPath = `${path}.${process.pid}.${randomBytes5(6).toString("hex")}.tmp`;
70761
+ try {
70762
+ await writeFile3(temporaryPath, `${JSON.stringify(file2, null, 2)}
70763
+ `, {
70764
+ encoding: "utf8",
70765
+ mode: 384,
70766
+ flag: "wx"
70767
+ });
70768
+ await rename4(temporaryPath, path);
70769
+ } catch (error61) {
70770
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
70771
+ throw error61;
70772
+ }
70773
+ }
70774
+ async function withVaultLock(path, operation) {
70775
+ await mkdir7(dirname5(path), { recursive: true, mode: 448 });
70776
+ const lockPath = `${path}.lock`;
70777
+ const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
70778
+ let handle;
70779
+ while (!handle) {
70780
+ try {
70781
+ handle = await open5(lockPath, "wx", 384);
70782
+ } catch (error61) {
70783
+ if (!isExistingFile(error61)) throw error61;
70784
+ await removeStaleVaultLock(lockPath);
70785
+ if (Date.now() >= deadline) {
70786
+ throw new VaultError("corrupt", "Timed out waiting for the vault lock.");
70787
+ }
70788
+ await new Promise((resolve3) => setTimeout(resolve3, 20));
70789
+ }
70790
+ }
70791
+ try {
70792
+ return await operation();
70793
+ } finally {
70794
+ await handle.close();
70795
+ await unlink4(lockPath).catch(() => void 0);
70796
+ }
70797
+ }
70798
+ async function removeStaleVaultLock(path) {
70799
+ try {
70800
+ const metadata = await stat6(path);
70801
+ if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
70802
+ } catch (error61) {
70803
+ if (!isMissingFile2(error61)) throw error61;
70804
+ }
70805
+ }
70806
+ function isMissingFile2(error61) {
70807
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
70808
+ }
70809
+ function isExistingFile(error61) {
70810
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "EEXIST";
70811
+ }
70812
+ function asVaultError(error61, code, message) {
70813
+ return error61 instanceof VaultError ? error61 : new VaultError(code, message, { cause: error61 });
70814
+ }
70815
+
70816
+ // ../core/src/file-secret-store.ts
70817
+ var FILE_SECRET_STORE_PASSWORD_ENV = "VAPI_VAULT_PASSWORD";
70818
+ var FILE_SECRET_STORE_MIN_PASSWORD = 12;
70819
+ var CHECK_VALUE = "vapi-network file secret store";
70820
+ var sealedSchema = external_exports.object({ nonce: external_exports.string(), ciphertext: external_exports.string(), tag: external_exports.string() }).strict();
70821
+ var fileSchema = external_exports.object({
70822
+ v: external_exports.literal(1),
70823
+ salt: external_exports.string(),
70824
+ check: sealedSchema,
70825
+ entries: external_exports.record(external_exports.string(), sealedSchema)
70826
+ }).strict();
70827
+ async function createFileSecretStore(options) {
70828
+ const password = passwordFrom(options.env);
70829
+ if (password.length < FILE_SECRET_STORE_MIN_PASSWORD) {
70830
+ throw new KeystoreError(
70831
+ `${FILE_SECRET_STORE_PASSWORD_ENV} must be at least ${FILE_SECRET_STORE_MIN_PASSWORD} characters.`
70832
+ );
70833
+ }
70834
+ await withVaultLock(options.path, async () => {
70835
+ let exists = true;
70836
+ try {
70837
+ await stat7(options.path);
70838
+ } catch (error61) {
70839
+ if (!isMissingFile(error61)) throw error61;
70840
+ exists = false;
70841
+ }
70842
+ if (exists) {
70843
+ await withKey(options.path, options.env, async () => void 0);
70844
+ return;
70845
+ }
70846
+ const salt = randomBytes6(32);
70847
+ const key2 = await deriveScryptKey(password, salt);
70848
+ try {
70849
+ await writeJsonAtomic(
70850
+ options.path,
70851
+ {
70852
+ v: 1,
70853
+ salt: salt.toString("base64"),
70854
+ check: seal(key2, CHECK_VALUE),
70855
+ entries: {}
70856
+ },
70857
+ { mode: 384 }
70858
+ );
70859
+ } finally {
70860
+ key2.fill(0);
70861
+ }
70862
+ });
70863
+ }
70864
+ function fileSecretStore(options) {
70865
+ const env = options.env ?? process.env;
70866
+ const write2 = async (change) => await withVaultLock(
70867
+ options.path,
70868
+ async () => await withKey(options.path, env, async (file2, key2) => {
70869
+ const changed = change(file2, key2);
70870
+ if (changed) await writeJsonAtomic(options.path, file2, { mode: 384 });
70871
+ return changed;
70872
+ })
70873
+ );
70874
+ const get = async (name) => await withKey(options.path, env, async (file2, key2) => {
70875
+ const sealed = Object.hasOwn(file2.entries, name) ? file2.entries[name] : void 0;
70876
+ return sealed === void 0 ? void 0 : open6(key2, sealed);
70877
+ });
70878
+ return {
70879
+ // A locked backend still exists; it must never enable a plaintext fallback.
70880
+ available: true,
70881
+ platform: process.platform,
70882
+ description: "the encrypted vAPI secrets file",
70883
+ get,
70884
+ async has(name) {
70885
+ return await get(name) !== void 0;
70886
+ },
70887
+ async set(name, value) {
70888
+ if (name === "__proto__") {
70889
+ throw new KeystoreError("The secret name is reserved in the encrypted vAPI secrets file.");
70890
+ }
70891
+ await write2((file2, key2) => {
70892
+ file2.entries[name] = seal(key2, value);
70893
+ return true;
70894
+ });
70895
+ },
70896
+ async remove(name) {
70897
+ return await write2((file2) => {
70898
+ if (!Object.hasOwn(file2.entries, name)) return false;
70899
+ delete file2.entries[name];
70900
+ return true;
70901
+ });
70902
+ }
70903
+ };
70904
+ }
70905
+ async function withKey(path, env, operation) {
70906
+ const file2 = await readStoredFile(path);
70907
+ const key2 = await deriveScryptKey(passwordFrom(env), Buffer.from(file2.salt, "base64"));
70908
+ try {
70909
+ if (open6(key2, file2.check) !== CHECK_VALUE) throw wrongPassword();
70910
+ return await operation(file2, key2);
70911
+ } finally {
70912
+ key2.fill(0);
70913
+ }
70914
+ }
70915
+ function passwordFrom(env) {
70916
+ const password = (env ?? process.env)[FILE_SECRET_STORE_PASSWORD_ENV];
70917
+ if (!password) {
70918
+ throw new KeystoreError(
70919
+ `This vault keeps its secrets in an encrypted file. Set ${FILE_SECRET_STORE_PASSWORD_ENV} to open it.`
70920
+ );
70921
+ }
70922
+ return password;
70923
+ }
70924
+ async function readStoredFile(path) {
70925
+ let raw;
70926
+ try {
70927
+ raw = await readFile8(path, "utf8");
70928
+ } catch (error61) {
70929
+ throw new KeystoreError("The vAPI secrets file is missing. Run vapi setup again.", {
70930
+ cause: error61
70931
+ });
70932
+ }
70933
+ let value;
70934
+ try {
70935
+ value = JSON.parse(raw);
70936
+ } catch {
70937
+ throw new KeystoreError("The vAPI secrets file is damaged.");
70938
+ }
70939
+ const parsed = fileSchema.safeParse(value);
70940
+ if (!parsed.success) throw new KeystoreError("The vAPI secrets file is damaged.");
70941
+ return parsed.data;
70942
+ }
70943
+ function seal(key2, value) {
70944
+ const { nonce, ciphertext, tag } = encryptWithKey(key2, Buffer.from(value, "utf8"));
70945
+ return {
70946
+ nonce: nonce.toString("base64"),
70947
+ ciphertext: ciphertext.toString("base64"),
70948
+ tag: tag.toString("base64")
70949
+ };
70950
+ }
70951
+ function open6(key2, sealed) {
70952
+ try {
70953
+ return decryptWithKey(key2, {
70954
+ nonce: Buffer.from(sealed.nonce, "base64"),
70955
+ ciphertext: Buffer.from(sealed.ciphertext, "base64"),
70956
+ tag: Buffer.from(sealed.tag, "base64")
70957
+ }).toString("utf8");
70958
+ } catch (error61) {
70959
+ throw wrongPassword(error61);
70960
+ }
70961
+ }
70962
+ function wrongPassword(cause) {
70963
+ return new KeystoreError(`Wrong ${FILE_SECRET_STORE_PASSWORD_ENV} for the vAPI secrets file.`, {
70964
+ cause
70965
+ });
70966
+ }
70967
+
70968
+ // ../core/src/secret-backend.ts
70969
+ import { readFileSync } from "node:fs";
70970
+ import { stat as stat8 } from "node:fs/promises";
70971
+ import { join as join6 } from "node:path";
70972
+ var PROBE_ACCOUNT = "setup-probe";
70973
+ var pinSchema = external_exports.object({ v: external_exports.literal(1), backend: external_exports.enum(["os", "file"]) }).strict();
70974
+ function secretBackendPath(home = getVapiPaths().directory) {
70975
+ return join6(home, "secret-store.json");
70976
+ }
70977
+ function secretsFilePath(home = getVapiPaths().directory) {
70978
+ return join6(home, "secrets.json");
70979
+ }
70980
+ function readSecretBackend(home = getVapiPaths().directory) {
70981
+ const path = secretBackendPath(home);
70982
+ try {
70983
+ const parsed = pinSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
70984
+ if (parsed.success) return parsed.data.backend;
70985
+ } catch (error61) {
70986
+ if (isMissingFile(error61)) return "os";
70987
+ }
70988
+ throw new KeystoreError(`The vAPI secret-store pin at ${path} is damaged.`);
70989
+ }
70990
+ async function chooseSecretBackend(options) {
70991
+ const env = options.env ?? process.env;
70992
+ const osWorks = options.os.platform !== "linux" || await osStoreWorks(options.os);
70993
+ const path = secretBackendPath(options.home);
70994
+ return await withVaultLock(path, async () => {
70995
+ if (await fileExists(path)) return readSecretBackend(options.home);
70996
+ if (await fileExists(join6(options.home, "vault.json"))) return "os";
70997
+ let backend;
70998
+ if (osWorks) {
70999
+ backend = "os";
71000
+ } else if (env[FILE_SECRET_STORE_PASSWORD_ENV]) {
71001
+ await createFileSecretStore({ path: secretsFilePath(options.home), env });
71002
+ backend = "file";
71003
+ } else {
71004
+ throw new KeystoreError(
71005
+ [
71006
+ `This machine has no working keyring (${options.os.description}).`,
71007
+ `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,`,
71008
+ "or run vapi on your own computer, or connect Claude from https://api.vapinetwork.ai/connect."
71009
+ ].join(" ")
71010
+ );
71011
+ }
71012
+ await writeJsonAtomic(path, { v: 1, backend }, { mode: 384 });
71013
+ return backend;
71014
+ });
71015
+ }
71016
+ async function fileExists(path) {
71017
+ try {
71018
+ await stat8(path);
71019
+ return true;
71020
+ } catch (error61) {
71021
+ if (isMissingFile(error61)) return false;
71022
+ throw error61;
71023
+ }
71024
+ }
71025
+ async function osStoreWorks(store) {
71026
+ if (!store.available) return false;
71027
+ try {
71028
+ try {
71029
+ await store.set(PROBE_ACCOUNT, "ok");
71030
+ return await store.get(PROBE_ACCOUNT) === "ok";
71031
+ } finally {
71032
+ await store.remove(PROBE_ACCOUNT);
71033
+ }
71034
+ } catch {
71035
+ return false;
71036
+ }
71037
+ }
71038
+
71039
+ // ../core/src/secret-store.ts
71040
+ var SECRET_STORE_SERVICE = "vapi-network";
71041
+ var SECURITY_BINARY = "/usr/bin/security";
71042
+ var SECRET_TOOL_BINARY = "secret-tool";
71043
+ var WINDOWS_POWERSHELL_ARGS = ["-NoProfile", "-NonInteractive", "-Command", "-"];
71044
+ var SECURITY_ITEM_NOT_FOUND = 44;
71045
+ var WINDOWS_SECRET_SUCCESS = 0;
71046
+ var WINDOWS_SECRET_NOT_FOUND = 2;
71047
+ var UNSUPPORTED_PLATFORM = "No OS secret store on this platform yet; use VAPI_KEYSTORE_PASSWORD.";
71048
+ var SECRET_TOOL_MISSING = [
71049
+ "secret-tool is not installed, so the passphrase cannot be kept in the OS secret store.",
71050
+ "Install libsecret-tools (Debian, Ubuntu) or libsecret (Fedora, Arch), or use VAPI_KEYSTORE_PASSWORD."
71051
+ ].join(" ");
71052
+ var POWERSHELL_MISSING = [
71053
+ "Windows PowerShell (powershell.exe) was not found, so the passphrase cannot be kept in the OS secret store.",
71054
+ "Use VAPI_KEYSTORE_PASSWORD."
71055
+ ].join(" ");
71056
+ function secretStore(options = {}) {
71057
+ const home = options.home ?? getVapiPaths().directory;
71058
+ if (readSecretBackend(home) === "file") {
71059
+ return fileSecretStore({ path: secretsFilePath(home), env: options.env ?? process.env });
71060
+ }
71061
+ return osSecretStore(options);
71062
+ }
71063
+ function osSecretStore(options = {}) {
71064
+ const platform2 = options.platform ?? process.platform;
71065
+ const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
71066
+ const env = options.env ?? process.env;
71067
+ const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
71068
+ if (platform2 === "darwin") return keychainStore(platform2, run);
71069
+ if (platform2 === "win32") return windowsDataProtectionStore(platform2, run, env, installed);
71070
+ if (platform2 === "linux") return libsecretStore(platform2, run, installed);
71071
+ return unsupportedStore(platform2);
71072
+ }
71073
+ function memorySecretStore(initial = {}) {
71074
+ const entries = new Map(Object.entries(initial));
71075
+ return {
71076
+ available: true,
71077
+ platform: process.platform,
71078
+ description: "an in-memory store",
71079
+ async get(name) {
71080
+ return entries.get(name);
71081
+ },
71082
+ async has(name) {
71083
+ return entries.has(name);
71084
+ },
71085
+ async set(name, passphrase) {
71086
+ entries.set(name, passphrase);
71087
+ },
71088
+ async remove(name) {
71089
+ return entries.delete(name);
71090
+ },
71091
+ async list() {
71092
+ return [...entries.keys()].sort();
71093
+ }
71094
+ };
71095
+ }
71096
+ function keychainStore(platform2, run) {
71097
+ const find = async (account, withPassword) => await run(SECURITY_BINARY, [
71098
+ "find-generic-password",
71099
+ "-a",
71100
+ account,
71101
+ "-s",
71102
+ SECRET_STORE_SERVICE,
71103
+ ...withPassword ? ["-w"] : []
71104
+ ]);
71105
+ const read = async (account, what) => {
71106
+ const result = await find(account, true);
71107
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return void 0;
71108
+ requireSuccess(result, what);
71109
+ const value = withoutTrailingNewline(result.stdout);
71110
+ return value.length === 0 ? void 0 : value;
71111
+ };
71112
+ const write2 = async (account, value, what) => {
71113
+ const result = await run(
71114
+ SECURITY_BINARY,
71115
+ [
71116
+ "add-generic-password",
71117
+ "-a",
71118
+ account,
71119
+ "-s",
71120
+ SECRET_STORE_SERVICE,
71121
+ "-l",
71122
+ `${SECRET_STORE_SERVICE} ${account}`,
71123
+ "-U",
71124
+ "-w"
71125
+ ],
71126
+ // `security` asks for the password and then for its confirmation.
71127
+ `${value}
71128
+ ${value}
71129
+ `
71130
+ );
71131
+ requireSuccess(result, what);
71132
+ };
71133
+ const erase = async (account, what) => {
71134
+ const result = await run(SECURITY_BINARY, [
71135
+ "delete-generic-password",
71136
+ "-a",
71137
+ account,
71138
+ "-s",
71139
+ SECRET_STORE_SERVICE
71140
+ ]);
71141
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
71142
+ requireSuccess(result, what);
71143
+ return true;
71144
+ };
71145
+ const erasePartsAfter = async (account, keep, what) => {
71146
+ for (let part = keep + 1; part <= MAX_KEYCHAIN_PARTS; part += 1) {
71147
+ if (!await erase(keychainPart(account, part), what)) return;
71148
+ }
71149
+ };
71150
+ return {
71151
+ available: true,
71152
+ platform: platform2,
71153
+ description: "the macOS Keychain",
71154
+ async get(name) {
71155
+ const account = accountFor(name);
71156
+ const what = `read the passphrase of ${name} from the macOS Keychain`;
71157
+ const value = await read(account, what);
71158
+ const parts = value === void 0 ? void 0 : chunkedPartCount(value);
71159
+ if (value === void 0 || parts === void 0) return value;
71160
+ let joined = "";
71161
+ for (let part = 1; part <= parts; part += 1) {
71162
+ const chunk = await read(keychainPart(account, part), what);
71163
+ if (chunk === void 0) {
71164
+ throw new KeystoreError(
71165
+ `The stored secret ${name} is incomplete in the macOS Keychain. Store it again.`
71166
+ );
71167
+ }
71168
+ joined += chunk;
71169
+ }
71170
+ return joined;
71171
+ },
71172
+ async has(name) {
71173
+ const result = await find(accountFor(name), false);
71174
+ if (result.code === SECURITY_ITEM_NOT_FOUND) return false;
71175
+ requireSuccess(result, `look up ${name} in the macOS Keychain`);
71176
+ return true;
71177
+ },
71178
+ async set(name, passphrase) {
71179
+ requirePassphrase(passphrase);
71180
+ const account = accountFor(name);
71181
+ const what = `store the passphrase of ${name} in the macOS Keychain`;
71182
+ if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
71183
+ await write2(account, passphrase, what);
71184
+ return;
71185
+ }
71186
+ const chunks = [];
71187
+ for (let index2 = 0; index2 < passphrase.length; index2 += KEYCHAIN_CHUNK) {
71188
+ chunks.push(passphrase.slice(index2, index2 + KEYCHAIN_CHUNK));
71189
+ }
71190
+ if (chunks.length > MAX_KEYCHAIN_PARTS) {
71191
+ throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
71192
+ }
71193
+ for (const [index2, chunk] of chunks.entries()) {
71194
+ await write2(keychainPart(account, index2 + 1), chunk, what);
71195
+ }
71196
+ await erasePartsAfter(account, chunks.length, what);
71197
+ await write2(account, `${CHUNKED_MARKER}${chunks.length}`, what);
71198
+ },
71199
+ async remove(name) {
71200
+ const account = accountFor(name);
71201
+ const what = `remove the passphrase of ${name} from the macOS Keychain`;
71202
+ const found = await find(account, true);
71203
+ if (found.code === SECURITY_ITEM_NOT_FOUND) return false;
71204
+ requireSuccess(found, what);
71205
+ if (chunkedPartCount(withoutTrailingNewline(found.stdout)) !== void 0) {
71206
+ await erasePartsAfter(account, 0, what);
71207
+ }
71208
+ return await erase(account, what);
71209
+ }
71210
+ };
71211
+ }
71212
+ var KEYCHAIN_PROMPT_LIMIT = 128;
71213
+ var KEYCHAIN_CHUNK = 120;
71214
+ var MAX_KEYCHAIN_PARTS = 32;
71215
+ var CHUNKED_MARKER = "vapi-chunked:v1:";
71216
+ function keychainPart(account, part) {
71217
+ return `${account}#${part}`;
71218
+ }
71219
+ function chunkedPartCount(value) {
71220
+ if (!value.startsWith(CHUNKED_MARKER)) return void 0;
71221
+ const parts = Number(value.slice(CHUNKED_MARKER.length));
71222
+ return Number.isInteger(parts) && parts > 0 && parts <= MAX_KEYCHAIN_PARTS ? parts : void 0;
71223
+ }
71224
+ function windowsSecretFileName(account) {
71225
+ let encoded = "";
71226
+ for (let index2 = 0; index2 < account.length; index2 += 1) {
71227
+ const character = account[index2];
71228
+ if (/^[a-z0-9._#-]$/u.test(character)) {
71229
+ encoded += character;
71230
+ continue;
71231
+ }
71232
+ encoded += `%${account.charCodeAt(index2).toString(16).toUpperCase().padStart(4, "0")}`;
71233
+ }
71234
+ if (/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(encoded)) {
71235
+ encoded = `%${encoded.charCodeAt(0).toString(16).toUpperCase()}${encoded.slice(1)}`;
71236
+ }
71237
+ return `${encoded}.bin`;
71238
+ }
71239
+ function windowsDataProtectionStore(platform2, run, env, installed) {
71240
+ const powershell = `${env.SystemRoot ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
71241
+ const fileDetails = (name) => {
71242
+ const file2 = windowsSecretFileName(accountFor(name));
71243
+ return { file: file2, account: file2.slice(0, -".bin".length) };
71244
+ };
71245
+ const script = (file2, operations) => [
71246
+ "$ErrorActionPreference = 'Stop'",
71247
+ "try {",
71248
+ " Add-Type -AssemblyName System.Security",
71249
+ " $dir = Join-Path $env:LOCALAPPDATA 'vapi-network\\secrets'",
71250
+ ` $path = Join-Path $dir '${file2}'`,
71251
+ ...operations.map((operation) => ` ${operation}`),
71252
+ "} catch {",
71253
+ " [Console]::Error.WriteLine($_.Exception.Message)",
71254
+ " exit 1",
71255
+ "}"
71256
+ ].join("\n");
71257
+ const execute = async (script2) => {
71258
+ const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
71259
+
71260
+ `);
71261
+ requirePowerShell(result);
71262
+ return result;
71263
+ };
71264
+ return {
71265
+ available: installed(powershell),
71266
+ platform: platform2,
71267
+ description: "Windows Data Protection (DPAPI)",
71268
+ async get(name) {
71269
+ const { file: file2, account } = fileDetails(name);
71270
+ const result = await execute(
71271
+ script(file2, [
71272
+ `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
71273
+ "$blob = [System.IO.File]::ReadAllBytes($path)",
71274
+ "$bytes = [System.Security.Cryptography.ProtectedData]::Unprotect($blob, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
71275
+ "[Console]::Out.Write([Convert]::ToBase64String($bytes))",
71276
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71277
+ ])
71278
+ );
71279
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return void 0;
71280
+ requireSuccess(result, `read the passphrase of ${name} from Windows Data Protection`);
71281
+ const value = Buffer.from(result.stdout.trim(), "base64").toString("utf8");
71282
+ return value.length === 0 ? void 0 : value;
71283
+ },
71284
+ async has(name) {
71285
+ const { file: file2, account } = fileDetails(name);
71286
+ const result = await execute(
71287
+ script(file2, [
71288
+ `if (Test-Path -LiteralPath $path) { exit ${WINDOWS_SECRET_SUCCESS} }`,
71289
+ `[Console]::Error.WriteLine('No stored secret for ${account}.')`,
71290
+ `exit ${WINDOWS_SECRET_NOT_FOUND}`
71291
+ ])
71292
+ );
71293
+ if (result.code === WINDOWS_SECRET_SUCCESS) return true;
71294
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
71295
+ requireSuccess(result, `look up ${name} in Windows Data Protection`);
71296
+ return false;
71297
+ },
71298
+ async set(name, passphrase) {
71299
+ requirePassphrase(passphrase);
71300
+ const { file: file2 } = fileDetails(name);
71301
+ const value = Buffer.from(passphrase, "utf8").toString("base64");
71302
+ const result = await execute(
71303
+ script(file2, [
71304
+ "[void][System.IO.Directory]::CreateDirectory($dir)",
71305
+ `$bytes = [Convert]::FromBase64String('${value}')`,
71306
+ "$blob = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)",
71307
+ "[System.IO.File]::WriteAllBytes($path, $blob)",
71308
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71309
+ ])
71310
+ );
71311
+ requireSuccess(result, `store the passphrase of ${name} in Windows Data Protection`);
71312
+ },
71313
+ async remove(name) {
71314
+ const { file: file2, account } = fileDetails(name);
71315
+ const result = await execute(
71316
+ script(file2, [
71317
+ `if (-not (Test-Path -LiteralPath $path)) { [Console]::Error.WriteLine('No stored secret for ${account}.'); exit ${WINDOWS_SECRET_NOT_FOUND} }`,
71318
+ "Remove-Item -LiteralPath $path -Force",
71319
+ `exit ${WINDOWS_SECRET_SUCCESS}`
71320
+ ])
71321
+ );
71322
+ if (result.code === WINDOWS_SECRET_NOT_FOUND) return false;
71323
+ requireSuccess(result, `remove the passphrase of ${name} from Windows Data Protection`);
71324
+ return true;
71325
+ }
71326
+ };
71327
+ }
71328
+ function libsecretStore(platform2, run, installed) {
71329
+ const lookup2 = async (name) => {
71330
+ const result = await run(SECRET_TOOL_BINARY, [
71331
+ "lookup",
71332
+ "service",
71333
+ SECRET_STORE_SERVICE,
71334
+ "account",
71335
+ accountFor(name)
71336
+ ]);
71337
+ requireBinary(result);
71338
+ const value = withoutTrailingNewline(result.stdout);
71339
+ if (result.code === 0) return value.length === 0 ? void 0 : value;
71340
+ if (result.stderr.trim().length === 0) return void 0;
71341
+ requireSuccess(result, `read the passphrase of ${name} from the secret service`);
71342
+ return void 0;
71343
+ };
71344
+ return {
71345
+ available: installed(SECRET_TOOL_BINARY),
71346
+ platform: platform2,
71347
+ description: "the libsecret keyring",
71348
+ get: lookup2,
71349
+ async has(name) {
71350
+ return await lookup2(name) !== void 0;
71351
+ },
71352
+ async set(name, passphrase) {
71353
+ requirePassphrase(passphrase);
71354
+ const account = accountFor(name);
71355
+ const result = await run(
71356
+ SECRET_TOOL_BINARY,
71357
+ [
71358
+ "store",
71359
+ `--label=${SECRET_STORE_SERVICE} ${account}`,
71360
+ "service",
71361
+ SECRET_STORE_SERVICE,
71362
+ "account",
71363
+ account
71364
+ ],
71365
+ `${passphrase}
71366
+ `
71367
+ );
71368
+ requireBinary(result);
71369
+ requireSuccess(result, `store the passphrase of ${name} in the secret service`);
71370
+ },
71371
+ async remove(name) {
71372
+ const existed = await lookup2(name) !== void 0;
71373
+ const result = await run(SECRET_TOOL_BINARY, [
71374
+ "clear",
71375
+ "service",
71376
+ SECRET_STORE_SERVICE,
71377
+ "account",
71378
+ accountFor(name)
71379
+ ]);
71380
+ requireBinary(result);
71381
+ requireSuccess(result, `remove the passphrase of ${name} from the secret service`);
71382
+ return existed;
71383
+ }
71384
+ };
71385
+ }
71386
+ function unsupportedStore(platform2) {
71387
+ const refuse = () => {
71388
+ throw new KeystoreError(UNSUPPORTED_PLATFORM);
71389
+ };
71390
+ return {
71391
+ available: false,
71392
+ platform: platform2,
71393
+ description: "no OS secret store",
71394
+ get: async () => refuse(),
71395
+ has: async () => refuse(),
71396
+ set: async () => refuse(),
71397
+ remove: async () => refuse()
71398
+ };
71399
+ }
71400
+ function accountFor(name) {
71401
+ const account = name.trim();
71402
+ if (account.length === 0) {
71403
+ throw new KeystoreError("A wallet name is needed to reach the OS secret store.");
71404
+ }
71405
+ return account;
71406
+ }
71407
+ function requirePassphrase(passphrase) {
71408
+ if (passphrase.length === 0) {
71409
+ throw new KeystoreError("Keystore passphrase cannot be empty.");
71410
+ }
71411
+ }
71412
+ function requireBinary(result) {
71413
+ if (result.notFound === true) throw new KeystoreError(SECRET_TOOL_MISSING);
71414
+ }
71415
+ function requirePowerShell(result) {
71416
+ if (result.notFound === true) throw new KeystoreError(POWERSHELL_MISSING);
71417
+ }
71418
+ function binaryInstalled(file2, env) {
71419
+ if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
71420
+ return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join7(directory, file2)));
71421
+ }
71422
+ var SAFE_FAILURE_DETAILS = [
71423
+ "Cannot autolaunch D-Bus without X11 $DISPLAY",
71424
+ "Cannot autolaunch D-Bus",
71425
+ "The name org.freedesktop.secrets was not provided by any .service files",
71426
+ "Cannot create an item in a locked collection",
71427
+ "User interaction is not allowed.",
71428
+ "Access to the path is denied."
71429
+ ];
71430
+ function requireSuccess(result, what) {
71431
+ if (result.code === 0) return;
71432
+ const detail = SAFE_FAILURE_DETAILS.find((reason) => result.stderr.includes(reason));
71433
+ throw new KeystoreError(
71434
+ `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail === void 0 ? "" : ` ${detail}`}`
71435
+ );
71436
+ }
71437
+ function withoutTrailingNewline(value) {
71438
+ return value.replace(/\r?\n$/u, "");
71439
+ }
71440
+ var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve3) => {
71441
+ let stdout = "";
71442
+ let stderr2 = "";
71443
+ let settled = false;
71444
+ const finish = (outcome) => {
71445
+ if (settled) return;
71446
+ settled = true;
71447
+ resolve3(outcome);
71448
+ };
71449
+ const child = spawn(file2, [...args], {
71450
+ detached: platform2 !== "win32",
71451
+ stdio: ["pipe", "pipe", "pipe"],
71452
+ windowsHide: true
71453
+ });
71454
+ child.stdout?.setEncoding("utf8");
71455
+ child.stdout?.on("data", (chunk) => {
71456
+ stdout += chunk;
71457
+ });
71458
+ child.stderr?.setEncoding("utf8");
71459
+ child.stderr?.on("data", (chunk) => {
71460
+ stderr2 += chunk;
71461
+ });
71462
+ child.on("error", (error61) => {
71463
+ finish({
71464
+ code: null,
71465
+ stdout,
71466
+ stderr: stderr2,
71467
+ ...error61.code === "ENOENT" ? { notFound: true } : {}
71468
+ });
71469
+ });
71470
+ child.on("close", (code) => finish({ code, stdout, stderr: stderr2 }));
71471
+ child.stdin?.on("error", () => void 0);
71472
+ child.stdin?.end(input2 ?? "");
71473
+ });
71474
+
71475
+ // ../core/src/passphrase.ts
71476
+ var PASSPHRASE_ENVIRONMENT_VARIABLE = "VAPI_KEYSTORE_PASSWORD";
71477
+ function noPassphraseHint(walletName) {
71478
+ return `Set ${PASSPHRASE_ENVIRONMENT_VARIABLE}, or store this wallet's passphrase once with vapi unlock --wallet ${walletName}.`;
71479
+ }
71480
+ function staleStoredPassphraseMessage(walletName, store) {
71481
+ return [
71482
+ `The passphrase stored in ${store.description} no longer opens wallet ${walletName}.`,
71483
+ `Store the current one with vapi unlock --wallet ${walletName}, or remove it with vapi lock --wallet ${walletName}.`
71484
+ ].join(" ");
71485
+ }
71486
+ async function resolvePassphrase(walletName, options = {}) {
71487
+ const env = options.env ?? process.env;
71488
+ const fromEnvironment = env[PASSPHRASE_ENVIRONMENT_VARIABLE];
71489
+ if (fromEnvironment !== void 0) {
71490
+ if (fromEnvironment.length === 0) {
71491
+ throw new KeystoreError(`${PASSPHRASE_ENVIRONMENT_VARIABLE} cannot be empty.`);
71492
+ }
71493
+ return { passphrase: fromEnvironment, source: "environment" };
71311
71494
  }
71312
- }
71313
- async function exportMemberKey(args) {
71314
- return await exportVaultAccountKey(args);
71315
- }
71316
- function assertVaultKey(key2) {
71317
- if (key2.byteLength !== 32) {
71318
- throw new VaultError("bad_key", "A device vault key must contain exactly 32 bytes.");
71495
+ if (options.confirm !== true) {
71496
+ const stored = await readStored(options.store ?? secretStore(), walletName);
71497
+ if (stored !== void 0) return { passphrase: stored, source: "secret-store" };
71319
71498
  }
71320
- }
71321
- function assertAccountName(name) {
71322
- const parsed = walletNameSchema.safeParse(name);
71323
- if (!parsed.success) {
71324
- throw new VaultError("name_taken", "The vault account name is not valid.", {
71325
- cause: parsed.error
71326
- });
71499
+ const hint = noPassphraseHint(walletName);
71500
+ if (options.interactive === false) {
71501
+ throw new KeystoreError(
71502
+ `No interactive terminal is available for the keystore prompt. ${hint}`
71503
+ );
71327
71504
  }
71328
- }
71329
- function assertAvailableName(file2, name) {
71330
- assertAccountName(name);
71331
- if (file2.accounts.some((account) => account.name === name)) {
71332
- throw new VaultError("name_taken", "A vault account already has that name.");
71505
+ const prompt = options.prompt ?? promptForSecret;
71506
+ const first = await prompt(`Passphrase for ${walletName}: `, hint);
71507
+ if (first.length === 0) {
71508
+ throw new KeystoreError("Keystore passphrase cannot be empty.");
71509
+ }
71510
+ if (options.confirm === true) {
71511
+ const second = await prompt("Confirm passphrase: ", hint);
71512
+ if (first !== second) throw new KeystoreError("Passphrases do not match.");
71333
71513
  }
71514
+ return { passphrase: first, source: "prompt" };
71334
71515
  }
71335
- function nextDerivedIndex(file2) {
71336
- let next = file2.nextDerivedIndex ?? 0;
71337
- for (const account of file2.accounts) {
71338
- if (account.kind === "derived") next = Math.max(next, account.index + 1);
71516
+ async function readStored(store, walletName) {
71517
+ if (!store.available) return void 0;
71518
+ try {
71519
+ return await store.get(walletName);
71520
+ } catch {
71521
+ return void 0;
71339
71522
  }
71340
- return next;
71341
71523
  }
71342
- function copyAccount(account) {
71343
- if (account.kind === "derived") return { ...account };
71344
- return {
71345
- name: account.name,
71346
- kind: account.kind,
71347
- address: account.address,
71348
- createdAt: account.createdAt
71349
- };
71524
+
71525
+ // ../core/src/receipts.ts
71526
+ import { randomBytes as randomBytes8 } from "node:crypto";
71527
+ import { mkdir as mkdir8, open as open7, readFile as readFile9, rename as rename5, writeFile as writeFile4 } from "node:fs/promises";
71528
+ import { dirname as dirname6 } from "node:path";
71529
+
71530
+ // ../core/src/agent-run.ts
71531
+ import { randomBytes as randomBytes7 } from "node:crypto";
71532
+ var RUN_ID_PATTERN = /^run_[0-9a-f]{24}$/;
71533
+ function isRunId(value) {
71534
+ return typeof value === "string" && RUN_ID_PATTERN.test(value);
71350
71535
  }
71351
- function sealField(key2, plaintext) {
71352
- const { nonce, ciphertext, tag } = encryptWithKey(key2, plaintext);
71353
- return [nonce, ciphertext, tag].map((part) => part.toString("base64url")).join(".");
71536
+ function createRunId(random = randomBytes7) {
71537
+ return `run_${Buffer.from(random(12)).toString("hex")}`;
71354
71538
  }
71355
- function openField(key2, value) {
71356
- const [nonce = "", ciphertext = "", tag = ""] = value.split(".");
71357
- return decryptWithKey(key2, {
71358
- nonce: Buffer.from(nonce, "base64url"),
71359
- ciphertext: Buffer.from(ciphertext, "base64url"),
71360
- tag: Buffer.from(tag, "base64url")
71539
+ var runRefSchema = external_exports.strictObject({
71540
+ id: external_exports.string().regex(RUN_ID_PATTERN),
71541
+ swarm: external_exports.string().optional(),
71542
+ member: external_exports.string().optional(),
71543
+ parentRunId: external_exports.string().optional()
71544
+ });
71545
+
71546
+ // ../core/src/receipts.ts
71547
+ var receiptTestHooks;
71548
+ var RECEIPT_JOURNAL_BUSY_MESSAGE = "The receipt journal is busy. Wait for the other vapi command to finish, then retry.";
71549
+ async function withReceiptJournalLock(path, operation) {
71550
+ return await withFileLock(`${path}.lock`, operation, {
71551
+ lockedMessage: RECEIPT_JOURNAL_BUSY_MESSAGE
71361
71552
  });
71362
71553
  }
71363
- function decryptField(key2, value) {
71364
- try {
71365
- return openField(key2, value);
71366
- } catch (error61) {
71367
- throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
71368
- cause: error61
71369
- });
71370
- }
71371
- }
71372
- function decryptPhraseForOpen(key2, phrase) {
71373
- try {
71374
- return openField(key2, phrase);
71375
- } catch (error61) {
71376
- throw new VaultError("bad_key", "Unable to decrypt the vault with this device key.", {
71377
- cause: error61
71378
- });
71554
+ var durationSchema = external_exports.number().nonnegative().finite();
71555
+ var receiptSchema = external_exports.strictObject({
71556
+ id: external_exports.string().min(1),
71557
+ timestamp: external_exports.iso.datetime(),
71558
+ run: runRefSchema.optional(),
71559
+ kind: external_exports.literal("transfer").optional(),
71560
+ wallet: walletNameSchema.optional(),
71561
+ resourceUrl: external_exports.url(),
71562
+ method: external_exports.string().min(1).optional(),
71563
+ source: external_exports.string().min(1).optional(),
71564
+ provenance: external_exports.array(
71565
+ external_exports.strictObject({
71566
+ source: external_exports.string().min(1),
71567
+ sourceUrl: external_exports.string().optional(),
71568
+ ref: external_exports.string().optional()
71569
+ })
71570
+ ).optional(),
71571
+ quote: external_exports.strictObject({
71572
+ network: external_exports.string(),
71573
+ asset: external_exports.string().optional(),
71574
+ amountAtomic: external_exports.string().regex(/^\d+$/),
71575
+ payTo: external_exports.string().optional()
71576
+ }).optional(),
71577
+ payer: external_exports.string().optional(),
71578
+ paymentId: external_exports.string().regex(/^[A-Za-z0-9_-]{16,128}$/).optional(),
71579
+ authorization: external_exports.strictObject({
71580
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71581
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
71582
+ validBefore: external_exports.string().regex(/^\d+$/)
71583
+ }).optional(),
71584
+ transfer: external_exports.strictObject({
71585
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71586
+ toName: external_exports.string().min(1),
71587
+ toKind: external_exports.enum(["owner", "account"]),
71588
+ amountAtomic: external_exports.string().regex(/^\d+$/),
71589
+ network: external_exports.string().min(1),
71590
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/),
71591
+ status: external_exports.enum(["sent", "unknown", "failed"]),
71592
+ txHash: external_exports.string().regex(/^0x[0-9a-fA-F]+$/).nullable(),
71593
+ replayed: external_exports.boolean(),
71594
+ reservedOn: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
71595
+ request: external_exports.strictObject({
71596
+ authorization: external_exports.strictObject({
71597
+ from: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71598
+ to: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
71599
+ value: external_exports.string().regex(/^\d+$/),
71600
+ validAfter: external_exports.string().regex(/^\d+$/),
71601
+ validBefore: external_exports.string().regex(/^\d+$/),
71602
+ nonce: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/)
71603
+ }),
71604
+ signature: external_exports.string().regex(/^0x[0-9a-fA-F]+$/)
71605
+ }).optional()
71606
+ }).optional(),
71607
+ settlement: external_exports.strictObject({
71608
+ outcome: external_exports.enum(["succeeded", "rejected", "unknown"]),
71609
+ transaction: external_exports.string().optional(),
71610
+ explorerUrl: external_exports.url().optional(),
71611
+ evidence: external_exports.unknown().optional()
71612
+ }).optional(),
71613
+ latencyMs: external_exports.number().nonnegative().finite().optional(),
71614
+ status: external_exports.number().int().min(100).max(599).optional(),
71615
+ error: external_exports.strictObject({ code: external_exports.string(), message: external_exports.string() }).optional(),
71616
+ phases: external_exports.strictObject({
71617
+ discoverMs: durationSchema.optional(),
71618
+ quoteMs: durationSchema.optional(),
71619
+ signMs: durationSchema.optional(),
71620
+ requestMs: durationSchema.optional(),
71621
+ settleMs: durationSchema.optional()
71622
+ }).optional(),
71623
+ listing: external_exports.strictObject({
71624
+ name: external_exports.string().min(1).optional(),
71625
+ providerHost: external_exports.string().min(1).optional(),
71626
+ source: external_exports.string().min(1)
71627
+ }).optional(),
71628
+ retry: external_exports.number().int().nonnegative().optional(),
71629
+ policy: external_exports.strictObject({
71630
+ maxPriceUsd: external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/).optional(),
71631
+ capsApplied: external_exports.boolean()
71632
+ }).optional(),
71633
+ client: external_exports.strictObject({ name: external_exports.literal("vapi-network"), version: external_exports.string().min(1) }).optional(),
71634
+ outcome: external_exports.enum([
71635
+ "paid",
71636
+ "signed_in",
71637
+ "declined_policy",
71638
+ "failed_request",
71639
+ "settlement_rejected",
71640
+ "settlement_unknown"
71641
+ ]).optional()
71642
+ });
71643
+ function parseReceipt(value) {
71644
+ const receipt = receiptSchema.parse(value);
71645
+ const transaction2 = receipt.settlement?.transaction;
71646
+ const network = receipt.quote?.network;
71647
+ const explorerUrl = transaction2 === void 0 || network === void 0 ? void 0 : explorerTransactionUrl(network, transaction2);
71648
+ if (explorerUrl === void 0 || receipt.settlement?.explorerUrl === explorerUrl) {
71649
+ return receipt;
71379
71650
  }
71380
- }
71381
- function validateStoredImportedAccount(key2, account) {
71382
- let plaintext;
71383
- try {
71384
- plaintext = decryptField(key2, account.key);
71385
- if (plaintext.byteLength !== 32) {
71386
- throw new VaultError("bad_key", "The stored imported key has the wrong length.");
71387
- }
71388
- let address4;
71389
- try {
71390
- address4 = privateKeyToAccount(`0x${plaintext.toString("hex")}`).address;
71391
- } catch (error61) {
71392
- throw new VaultError("bad_key", "The stored imported key is not valid.", {
71393
- cause: error61
71394
- });
71395
- }
71396
- if (address4.toLowerCase() !== account.address.toLowerCase()) {
71397
- throw new VaultError("bad_key", "The stored imported key does not match its address.");
71651
+ return {
71652
+ ...receipt,
71653
+ settlement: {
71654
+ outcome: receipt.settlement.outcome,
71655
+ ...receipt.settlement.transaction ? { transaction: receipt.settlement.transaction } : {},
71656
+ explorerUrl,
71657
+ ...receipt.settlement.evidence === void 0 ? {} : { evidence: receipt.settlement.evidence }
71398
71658
  }
71399
- } finally {
71400
- plaintext?.fill(0);
71401
- }
71659
+ };
71402
71660
  }
71403
- function validateStoredDerivedAccount(key2, file2, account) {
71404
- const plaintext = decryptField(key2, file2.phrase);
71405
- let seed;
71406
- try {
71407
- seed = phraseToSeed(plaintext.toString("utf8"));
71408
- const address4 = privateKeyToAccount(
71409
- deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${account.index}`)
71410
- ).address;
71411
- if (address4.toLowerCase() !== account.address.toLowerCase()) {
71412
- throw new VaultError("bad_key", "The stored derived account does not match this vault.");
71661
+ async function appendReceipt(receipt, path = getVapiPaths().receipts, options = {}) {
71662
+ const parsed = parseReceipt(
71663
+ receipt.wallet === void 0 && options.wallet !== void 0 ? { ...receipt, wallet: options.wallet } : receipt
71664
+ );
71665
+ await withReceiptJournalLock(path, async () => {
71666
+ await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71667
+ const handle = await open7(path, "a", 384);
71668
+ try {
71669
+ await handle.writeFile(`${JSON.stringify(parsed)}
71670
+ `, "utf8");
71671
+ } finally {
71672
+ await handle.close();
71413
71673
  }
71414
- } finally {
71415
- seed?.fill(0);
71416
- plaintext.fill(0);
71417
- }
71674
+ });
71675
+ return parsed;
71418
71676
  }
71419
- function parseVaultFile(raw) {
71420
- let value;
71677
+ async function readReceipts(path = getVapiPaths().receipts, options = {}) {
71678
+ let raw;
71421
71679
  try {
71422
- value = JSON.parse(raw);
71680
+ raw = await readFile9(path, "utf8");
71423
71681
  } catch (error61) {
71424
- throw new VaultError("corrupt", "The vault file is not valid JSON.", { cause: error61 });
71425
- }
71426
- const parsed = vaultFileSchema.safeParse(value);
71427
- if (!parsed.success) {
71428
- throw new VaultError("corrupt", "The vault file has an invalid structure.", {
71429
- cause: parsed.error
71430
- });
71431
- }
71432
- if (parsed.data.protected !== (parsed.data.wrappedKey !== void 0)) {
71433
- throw new VaultError("corrupt", "The vault protection metadata is inconsistent.");
71682
+ if (isMissingFile(error61)) return [];
71683
+ throw error61;
71434
71684
  }
71435
- const names = /* @__PURE__ */ new Set();
71436
- const indexes = /* @__PURE__ */ new Set();
71437
- for (const account of parsed.data.accounts) {
71438
- if (names.has(account.name)) {
71439
- throw new VaultError("corrupt", "The vault file contains duplicate account names.");
71440
- }
71441
- names.add(account.name);
71442
- if (account.kind === "derived") {
71443
- if (indexes.has(account.index)) {
71444
- throw new VaultError("corrupt", "The vault file contains duplicate derived indexes.");
71685
+ const records = coalesceTransferReceiptRevisions(
71686
+ raw.split("\n").filter((line) => line.trim().length > 0).map((line, index2) => {
71687
+ try {
71688
+ return parseReceipt(JSON.parse(line));
71689
+ } catch (error61) {
71690
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71445
71691
  }
71446
- indexes.add(account.index);
71692
+ })
71693
+ );
71694
+ const filtered = options.wallet === void 0 ? records : filterReceiptsByWallet(records, options.wallet);
71695
+ const limit = options.limit;
71696
+ if (limit === void 0) return filtered;
71697
+ if (!Number.isSafeInteger(limit) || limit < 0)
71698
+ throw new Error("Receipt limit must be a non-negative integer.");
71699
+ return limit === 0 ? [] : filtered.slice(-limit);
71700
+ }
71701
+ function coalesceTransferReceiptRevisions(receipts) {
71702
+ const coalesced = [];
71703
+ const transferIndexes = /* @__PURE__ */ new Map();
71704
+ for (const receipt of receipts) {
71705
+ const existing = receipt.kind === "transfer" ? transferIndexes.get(receipt.id) : void 0;
71706
+ if (existing === void 0) {
71707
+ if (receipt.kind === "transfer") transferIndexes.set(receipt.id, coalesced.length);
71708
+ coalesced.push(receipt);
71709
+ } else {
71710
+ coalesced[existing] = receipt;
71447
71711
  }
71448
71712
  }
71449
- return parsed.data;
71713
+ return coalesced;
71450
71714
  }
71451
- async function readVaultFile(path, key2) {
71452
- const file2 = await readVaultFileUnlocked(path);
71453
- const plaintext = decryptPhraseForOpen(key2, file2.phrase);
71454
- try {
71715
+ function receiptWallet(receipt) {
71716
+ return receipt.wallet ?? DEFAULT_WALLET_NAME;
71717
+ }
71718
+ function filterReceiptsByWallet(receipts, name) {
71719
+ return receipts.filter((receipt) => receiptWallet(receipt) === name);
71720
+ }
71721
+ async function renameReceiptWallet(from16, to, path = getVapiPaths().receipts) {
71722
+ return await withReceiptJournalLock(path, async () => {
71723
+ let raw;
71455
71724
  try {
71456
- validateRecoveryPhrase(plaintext.toString("utf8"));
71725
+ raw = await readFile9(path, "utf8");
71457
71726
  } catch (error61) {
71458
- throw new VaultError("corrupt", "The vault recovery phrase is not valid.", {
71459
- cause: error61
71460
- });
71461
- }
71462
- } finally {
71463
- plaintext.fill(0);
71464
- }
71465
- return file2;
71466
- }
71467
- async function readVaultFileUnlocked(path) {
71468
- let raw;
71469
- try {
71470
- raw = await readFile9(path, "utf8");
71471
- } catch (error61) {
71472
- if (isMissingFile2(error61)) {
71473
- throw new VaultError("not_found", "No vault file was found at the requested path.", {
71474
- cause: error61
71475
- });
71727
+ if (isMissingFile(error61)) return 0;
71728
+ throw error61;
71476
71729
  }
71477
- throw new VaultError("corrupt", "Unable to read the vault file.", { cause: error61 });
71478
- }
71479
- return parseVaultFile(raw);
71480
- }
71481
- async function refuseExistingVault(path) {
71482
- try {
71483
- await stat6(path);
71484
- } catch (error61) {
71485
- if (isMissingFile2(error61)) return;
71486
- throw new VaultError("corrupt", "Unable to check whether the vault already exists.", {
71487
- cause: error61
71730
+ let changed = 0;
71731
+ const lines = raw.split("\n").map((line, index2) => {
71732
+ if (line.trim().length === 0) return line;
71733
+ let parsed;
71734
+ try {
71735
+ parsed = JSON.parse(line);
71736
+ } catch (error61) {
71737
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71738
+ }
71739
+ const current = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "wallet") : void 0;
71740
+ if ((typeof current === "string" ? current : DEFAULT_WALLET_NAME) !== from16) return line;
71741
+ changed += 1;
71742
+ return JSON.stringify(parseReceipt({ ...parsed, wallet: to }));
71488
71743
  });
71489
- }
71490
- throw new VaultError("corrupt", "A vault already exists at the requested path.");
71491
- }
71492
- async function writeVaultFile(path, file2) {
71493
- await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71494
- const temporaryPath = `${path}.${process.pid}.${randomBytes7(6).toString("hex")}.tmp`;
71495
- try {
71496
- await writeFile4(temporaryPath, `${JSON.stringify(file2, null, 2)}
71497
- `, {
71744
+ if (changed === 0) return 0;
71745
+ await receiptTestHooks?.beforeRenameReplace?.(path);
71746
+ await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71747
+ const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
71748
+ await writeFile4(temporaryPath, lines.join("\n"), {
71498
71749
  encoding: "utf8",
71499
71750
  mode: 384,
71500
71751
  flag: "wx"
71501
71752
  });
71502
71753
  await rename5(temporaryPath, path);
71754
+ return changed;
71755
+ });
71756
+ }
71757
+
71758
+ // ../core/src/transfer-journal.ts
71759
+ import { readFile as readFile10 } from "node:fs/promises";
71760
+ async function readTransferJournal(home, from16, nonce) {
71761
+ let raw;
71762
+ try {
71763
+ raw = await readFile10(getVapiPaths(home).receipts, "utf8");
71503
71764
  } catch (error61) {
71504
- await rm(temporaryPath, { force: true }).catch(() => void 0);
71765
+ if (isMissingFile(error61)) return { signed: false };
71505
71766
  throw error61;
71506
71767
  }
71507
- }
71508
- async function withVaultLock(path, operation) {
71509
- await mkdir8(dirname6(path), { recursive: true, mode: 448 });
71510
- const lockPath = `${path}.lock`;
71511
- const deadline = Date.now() + VAULT_LOCK_TIMEOUT_MS;
71512
- let handle;
71513
- while (!handle) {
71768
+ let latest;
71769
+ let request;
71770
+ for (const [index2, line] of raw.split("\n").entries()) {
71771
+ if (!line.trim()) continue;
71772
+ let receipt;
71514
71773
  try {
71515
- handle = await open6(lockPath, "wx", 384);
71774
+ receipt = parseReceipt(JSON.parse(line));
71516
71775
  } catch (error61) {
71517
- if (!isExistingFile(error61)) throw error61;
71518
- await removeStaleVaultLock(lockPath);
71519
- if (Date.now() >= deadline) {
71520
- throw new VaultError("corrupt", "Timed out waiting for the vault lock.");
71521
- }
71522
- await new Promise((resolve3) => setTimeout(resolve3, 20));
71776
+ throw new Error(`Invalid receipt on JSONL line ${index2 + 1}.`, { cause: error61 });
71523
71777
  }
71778
+ if (receiptWallet(receipt) !== from16 || receipt.transfer?.nonce.toLowerCase() !== nonce.toLowerCase()) {
71779
+ continue;
71780
+ }
71781
+ latest = receipt;
71782
+ if (receipt.transfer.request !== void 0) request = receipt;
71524
71783
  }
71525
- try {
71526
- return await operation();
71527
- } finally {
71528
- await handle.close();
71529
- await unlink4(lockPath).catch(() => void 0);
71530
- }
71531
- }
71532
- async function removeStaleVaultLock(path) {
71533
- try {
71534
- const metadata = await stat6(path);
71535
- if (Date.now() - metadata.mtimeMs > STALE_VAULT_LOCK_MS) await unlink4(path);
71536
- } catch (error61) {
71537
- if (!isMissingFile2(error61)) throw error61;
71538
- }
71539
- }
71540
- function isMissingFile2(error61) {
71541
- return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "ENOENT";
71542
- }
71543
- function isExistingFile(error61) {
71544
- return typeof error61 === "object" && error61 !== null && "code" in error61 && Reflect.get(error61, "code") === "EEXIST";
71545
- }
71546
- function asVaultError(error61, code, message) {
71547
- return error61 instanceof VaultError ? error61 : new VaultError(code, message, { cause: error61 });
71784
+ return {
71785
+ signed: latest !== void 0,
71786
+ ...latest === void 0 ? {} : { latest },
71787
+ ...request === void 0 ? {} : { request },
71788
+ ...request?.transfer?.request?.authorization.validBefore === void 0 ? {} : { validBefore: request.transfer.request.authorization.validBefore },
71789
+ ...(latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn) === void 0 ? {} : { reservedOn: latest?.transfer?.reservedOn ?? request?.transfer?.reservedOn }
71790
+ };
71548
71791
  }
71549
71792
 
71550
71793
  // ../core/src/vault-key.ts
71794
+ import { randomBytes as cryptoRandomBytes } from "node:crypto";
71551
71795
  var VAULT_KEY_ACCOUNT = "vault-key";
71552
71796
  var VAULT_SESSION_ACCOUNT = "vault-session";
71553
71797
  var DEVICE_KEY_LENGTH = 32;
@@ -71569,7 +71813,7 @@ async function loadOrCreateDeviceKey(args) {
71569
71813
  await args.secrets.set(VAULT_KEY_ACCOUNT, key2.toString("base64"));
71570
71814
  return key2;
71571
71815
  } catch (error61) {
71572
- throw asVaultError2(error61, "Unable to load or create the device vault key.");
71816
+ throw asVaultError2(error61, deviceKeyFailureMessage(error61, args.secrets.platform));
71573
71817
  }
71574
71818
  });
71575
71819
  }
@@ -71775,8 +72019,8 @@ function passwordRequiredError() {
71775
72019
  "A vault password is needed. Pass it or set VAPI_VAULT_PASSWORD."
71776
72020
  );
71777
72021
  }
71778
- function randomKeyBytes(randomBytes17) {
71779
- const key2 = Buffer.from((randomBytes17 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
72022
+ function randomKeyBytes(randomBytes18) {
72023
+ const key2 = Buffer.from((randomBytes18 ?? cryptoRandomBytes)(DEVICE_KEY_LENGTH));
71780
72024
  if (key2.byteLength !== DEVICE_KEY_LENGTH) {
71781
72025
  key2.fill(0);
71782
72026
  throw new VaultError("corrupt", "A generated device vault key has the wrong length.");
@@ -71827,25 +72071,31 @@ function parseJson(value) {
71827
72071
  function asVaultError2(error61, message) {
71828
72072
  return error61 instanceof VaultError ? error61 : new VaultError("corrupt", message, { cause: error61 });
71829
72073
  }
72074
+ 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.";
72075
+ function deviceKeyFailureMessage(error61, platform2) {
72076
+ if (!(error61 instanceof KeystoreError)) return "Unable to load or create the device vault key.";
72077
+ const detail = `Unable to load or create the device vault key: ${error61.message.replace(/\.$/u, "")}.`;
72078
+ return platform2 === "linux" ? `${detail} ${HEADLESS_LINUX_HINT}` : detail;
72079
+ }
71830
72080
 
71831
72081
  // ../core/src/vault-migrate.ts
71832
72082
  import {
71833
72083
  chmod as chmod2,
71834
72084
  lstat,
71835
72085
  mkdir as mkdir9,
71836
- readFile as readFile10,
72086
+ readFile as readFile11,
71837
72087
  readlink,
71838
72088
  readdir as readdir2,
71839
72089
  rename as rename6,
71840
72090
  symlink,
71841
72091
  unlink as unlink5
71842
72092
  } from "node:fs/promises";
71843
- import { join as join7, resolve } from "node:path";
72093
+ import { join as join8, resolve } from "node:path";
71844
72094
  var MIGRATED_DIRECTORY = "wallets.migrated";
71845
72095
  async function legacyKeystoreNames(home) {
71846
72096
  let entries;
71847
72097
  try {
71848
- entries = await readdir2(join7(home, "wallets"), { withFileTypes: true });
72098
+ entries = await readdir2(join8(home, "wallets"), { withFileTypes: true });
71849
72099
  } catch (error61) {
71850
72100
  if (isMissingFile(error61)) return [];
71851
72101
  throw error61;
@@ -71861,14 +72111,14 @@ async function migrateKeystores(args) {
71861
72111
  );
71862
72112
  const result = { imported: [], skipped: [] };
71863
72113
  for (const name of names) {
71864
- const source = join7(args.home, "wallets", `${name}.json`);
72114
+ const source = join8(args.home, "wallets", `${name}.json`);
71865
72115
  if (args.vault.accounts().some((account) => account.name === name)) {
71866
72116
  result.skipped.push({ name, reason: "name_taken" });
71867
72117
  continue;
71868
72118
  }
71869
72119
  let parsed;
71870
72120
  try {
71871
- parsed = parseAnyKeystore(JSON.parse(await readFile10(source, "utf8")));
72121
+ parsed = parseAnyKeystore(JSON.parse(await readFile11(source, "utf8")));
71872
72122
  } catch {
71873
72123
  result.skipped.push({ name, reason: "unreadable" });
71874
72124
  continue;
@@ -71898,15 +72148,15 @@ async function migrateKeystores(args) {
71898
72148
  if (imported.address.toLowerCase() !== parsed.address.toLowerCase()) {
71899
72149
  throw new KeystoreError(`Migrated wallet ${name} does not match its stored address.`);
71900
72150
  }
71901
- const migratedDirectory = join7(args.home, MIGRATED_DIRECTORY);
71902
- const destination = join7(migratedDirectory, `${name}.json`);
72151
+ const migratedDirectory = join8(args.home, MIGRATED_DIRECTORY);
72152
+ const destination = join8(migratedDirectory, `${name}.json`);
71903
72153
  await mkdir9(migratedDirectory, { recursive: true, mode: 448 });
71904
72154
  await archiveExistingDestination(destination, migratedDirectory, name, now);
71905
72155
  await rename6(source, destination);
71906
72156
  await chmod2(destination, 384);
71907
72157
  try {
71908
72158
  await removeCompatibilityLink(args.home, source);
71909
- await symlink(join7("..", MIGRATED_DIRECTORY, `${name}.json`), source);
72159
+ await symlink(join8("..", MIGRATED_DIRECTORY, `${name}.json`), source);
71910
72160
  await audit({
71911
72161
  event: "vault.migrate",
71912
72162
  wallet: name,
@@ -71934,16 +72184,16 @@ async function migrateKeystores(args) {
71934
72184
  async function archiveExistingDestination(destination, directory, name, now) {
71935
72185
  if (!await pathExists2(destination)) return;
71936
72186
  const timestamp = now().toISOString();
71937
- let archive = join7(directory, `${name}.${timestamp}.json`);
72187
+ let archive = join8(directory, `${name}.${timestamp}.json`);
71938
72188
  let suffix = 1;
71939
72189
  while (await pathExists2(archive)) {
71940
- archive = join7(directory, `${name}.${timestamp}.${suffix}.json`);
72190
+ archive = join8(directory, `${name}.${timestamp}.${suffix}.json`);
71941
72191
  suffix += 1;
71942
72192
  }
71943
72193
  await rename6(destination, archive);
71944
72194
  }
71945
72195
  async function removeCompatibilityLink(home, migratedSource) {
71946
- const compatibilityPath = join7(home, "keystore.json");
72196
+ const compatibilityPath = join8(home, "keystore.json");
71947
72197
  let metadata;
71948
72198
  try {
71949
72199
  metadata = await lstat(compatibilityPath);
@@ -72017,7 +72267,7 @@ var WalletStore = class _WalletStore {
72017
72267
  this.home = home;
72018
72268
  this.options = options;
72019
72269
  this.registry = registry2;
72020
- this.secrets = options.secrets ?? secretStore();
72270
+ this.secrets = options.secrets ?? secretStore({ home });
72021
72271
  this.environment = options.env ?? process.env;
72022
72272
  this.passphraseResolver = options.resolvePassphrase ?? defaultPassphraseResolver(this.environment, this.secrets);
72023
72273
  this.audit = options.audit ?? (async (record2) => await appendAudit(this.home, record2, { now: () => this.now() }));
@@ -72064,17 +72314,17 @@ var WalletStore = class _WalletStore {
72064
72314
  return store;
72065
72315
  }
72066
72316
  get registryPath() {
72067
- return join8(this.home, REGISTRY_FILE);
72317
+ return join9(this.home, REGISTRY_FILE);
72068
72318
  }
72069
72319
  get walletsDirectory() {
72070
- return join8(this.home, WALLETS_DIRECTORY);
72320
+ return join9(this.home, WALLETS_DIRECTORY);
72071
72321
  }
72072
72322
  get trashDirectory() {
72073
- return join8(this.walletsDirectory, TRASH_DIRECTORY);
72323
+ return join9(this.walletsDirectory, TRASH_DIRECTORY);
72074
72324
  }
72075
72325
  /** The legacy 0.5 keystore path of a wallet, whether or not it exists. */
72076
72326
  pathFor(name) {
72077
- return join8(this.walletsDirectory, `${assertWalletName(name)}.json`);
72327
+ return join9(this.walletsDirectory, `${assertWalletName(name)}.json`);
72078
72328
  }
72079
72329
  /** The names this machine knows, in registry order. */
72080
72330
  names() {
@@ -72647,7 +72897,7 @@ var WalletStore = class _WalletStore {
72647
72897
  }
72648
72898
  const removedAt = this.now().toISOString();
72649
72899
  await mkdir10(this.trashDirectory, { recursive: true, mode: 448 });
72650
- const trashedPath = join8(this.trashDirectory, `${wallet.name}-${removedAt}.json`);
72900
+ const trashedPath = join9(this.trashDirectory, `${wallet.name}-${removedAt}.json`);
72651
72901
  const storedAccount = (await this.readVaultUnlocked())?.accounts.find(
72652
72902
  (candidate) => candidate.name === wallet.name
72653
72903
  );
@@ -72669,7 +72919,7 @@ var WalletStore = class _WalletStore {
72669
72919
  this.balanceProbe = void 0;
72670
72920
  }
72671
72921
  if (await pathExists3(wallet.path)) {
72672
- const legacyTrashedPath = join8(
72922
+ const legacyTrashedPath = join9(
72673
72923
  this.trashDirectory,
72674
72924
  `${wallet.name}-${removedAt}.legacy.json`
72675
72925
  );
@@ -72759,7 +73009,7 @@ var WalletStore = class _WalletStore {
72759
73009
  if (!match) continue;
72760
73010
  const [, name, removedAt] = match;
72761
73011
  if (name === void 0 || removedAt === void 0 || !isWalletName(name)) continue;
72762
- const path = join8(this.trashDirectory, file2);
73012
+ const path = join9(this.trashDirectory, file2);
72763
73013
  const entry = await readEntrySidecar(entrySidecarPath(path));
72764
73014
  trashed.push({ name, removedAt, path, ...entry ? { entry } : {} });
72765
73015
  }
@@ -72828,7 +73078,7 @@ var WalletStore = class _WalletStore {
72828
73078
  return entry;
72829
73079
  }
72830
73080
  get vaultPath() {
72831
- return join8(this.home, VAULT_FILE);
73081
+ return join9(this.home, VAULT_FILE);
72832
73082
  }
72833
73083
  async readVaultUnlocked() {
72834
73084
  try {
@@ -72933,7 +73183,7 @@ var WalletStore = class _WalletStore {
72933
73183
  async readRegistry() {
72934
73184
  let raw;
72935
73185
  try {
72936
- raw = await readFile11(this.registryPath, "utf8");
73186
+ raw = await readFile12(this.registryPath, "utf8");
72937
73187
  } catch (error61) {
72938
73188
  if (isMissingFile(error61)) return emptyRegistry();
72939
73189
  throw error61;
@@ -72954,7 +73204,7 @@ var WalletStore = class _WalletStore {
72954
73204
  }
72955
73205
  };
72956
73206
  async function swarmReferencingAccount(home, account) {
72957
- const directory = join8(home, "swarms");
73207
+ const directory = join9(home, "swarms");
72958
73208
  let files;
72959
73209
  try {
72960
73210
  files = await readdir3(directory);
@@ -72965,7 +73215,7 @@ async function swarmReferencingAccount(home, account) {
72965
73215
  for (const file2 of files.filter((name) => name.endsWith(".json")).sort()) {
72966
73216
  let value;
72967
73217
  try {
72968
- value = JSON.parse(await readFile11(join8(directory, file2), "utf8"));
73218
+ value = JSON.parse(await readFile12(join9(directory, file2), "utf8"));
72969
73219
  } catch {
72970
73220
  throw new KeystoreError(
72971
73221
  `Cannot verify swarm references because ${file2} is invalid. Repair or remove that swarm file before renaming an account.`
@@ -72997,7 +73247,7 @@ async function swarmReferencingAccount(home, account) {
72997
73247
  return void 0;
72998
73248
  }
72999
73249
  async function unfinishedMovementReferencingAccount(home, account) {
73000
- const directory = join8(home, "movements");
73250
+ const directory = join9(home, "movements");
73001
73251
  let files;
73002
73252
  try {
73003
73253
  files = await readdir3(directory);
@@ -73008,7 +73258,7 @@ async function unfinishedMovementReferencingAccount(home, account) {
73008
73258
  for (const file2 of files.filter((name) => name.endsWith(".json")).sort()) {
73009
73259
  let value;
73010
73260
  try {
73011
- value = JSON.parse(await readFile11(join8(directory, file2), "utf8"));
73261
+ value = JSON.parse(await readFile12(join9(directory, file2), "utf8"));
73012
73262
  } catch {
73013
73263
  throw invalidMovementReferenceError(file2);
73014
73264
  }
@@ -73029,11 +73279,11 @@ async function unfinishedMovementReferencingAccount(home, account) {
73029
73279
  const restored = Reflect.get(leg, "restored");
73030
73280
  const legFrom = Reflect.get(leg, "from") ?? movementFrom;
73031
73281
  const journal = restored !== true && status === "failed" && retryable !== true && typeof nonce === "string" ? await readTransferJournal(home, legFrom, nonce) : void 0;
73032
- const open12 = isOpenMovementLeg(
73282
+ const open13 = isOpenMovementLeg(
73033
73283
  { status, retryable, nonce, restored },
73034
73284
  journal?.signed === true ? "signed" : "unsigned"
73035
73285
  );
73036
- if (open12) movementOpen = true;
73286
+ if (open13) movementOpen = true;
73037
73287
  }
73038
73288
  if (movementOpen && (movementFrom === account || legs.some(
73039
73289
  (leg) => (Reflect.get(leg, "from") ?? movementFrom) === account || Reflect.get(leg, "to") === account
@@ -73069,7 +73319,7 @@ async function withAccountMutationLocks(home, accounts, command, operation) {
73069
73319
  const [account, ...remaining2] = [...new Set(accounts)].sort();
73070
73320
  if (account === void 0) return await operation();
73071
73321
  return await withFileLock(
73072
- join8(home, `.account-${account}.lock`),
73322
+ join9(home, `.account-${account}.lock`),
73073
73323
  async () => await withAccountMutationLocks(home, remaining2, command, operation),
73074
73324
  {
73075
73325
  lockedMessage: `Account ${account} is busy with another account change. Wait for it to finish, then retry ${command}.`
@@ -73144,7 +73394,7 @@ function isLockedVaultError(error61) {
73144
73394
  async function readTrashedVaultAccount(path) {
73145
73395
  let parsed;
73146
73396
  try {
73147
- parsed = JSON.parse(await readFile11(path, "utf8"));
73397
+ parsed = JSON.parse(await readFile12(path, "utf8"));
73148
73398
  } catch {
73149
73399
  return void 0;
73150
73400
  }
@@ -73153,7 +73403,7 @@ async function readTrashedVaultAccount(path) {
73153
73403
  }
73154
73404
  async function readEntrySidecar(path) {
73155
73405
  try {
73156
- const parsed = walletEntrySchema.safeParse(JSON.parse(await readFile11(path, "utf8")));
73406
+ const parsed = walletEntrySchema.safeParse(JSON.parse(await readFile12(path, "utf8")));
73157
73407
  return parsed.success ? parsed.data : void 0;
73158
73408
  } catch {
73159
73409
  return void 0;
@@ -73162,7 +73412,7 @@ async function readEntrySidecar(path) {
73162
73412
  async function readKeystoreSummary(path) {
73163
73413
  let parsed;
73164
73414
  try {
73165
- parsed = JSON.parse(await readFile11(path, "utf8"));
73415
+ parsed = JSON.parse(await readFile12(path, "utf8"));
73166
73416
  } catch {
73167
73417
  return {};
73168
73418
  }
@@ -73180,7 +73430,7 @@ async function readKeystoreSummary(path) {
73180
73430
  }
73181
73431
  async function readConfiguredSpendCaps(configPath) {
73182
73432
  try {
73183
- const parsed = JSON.parse(await readFile11(configPath, "utf8"));
73433
+ const parsed = JSON.parse(await readFile12(configPath, "utf8"));
73184
73434
  const caps = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "spendCaps") : void 0;
73185
73435
  const result = spendCapsSchema.safeParse(caps);
73186
73436
  if (result.success) return result.data;
@@ -73272,7 +73522,7 @@ async function withRegistryLock(path, operation) {
73272
73522
  let handle;
73273
73523
  while (!handle) {
73274
73524
  try {
73275
- handle = await open7(lockPath, "wx", 384);
73525
+ handle = await open8(lockPath, "wx", 384);
73276
73526
  } catch (error61) {
73277
73527
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
73278
73528
  await removeStaleRegistryLock(lockPath);
@@ -73291,7 +73541,7 @@ async function withRegistryLock(path, operation) {
73291
73541
  }
73292
73542
  async function removeStaleRegistryLock(path) {
73293
73543
  try {
73294
- const metadata = await stat7(path);
73544
+ const metadata = await stat9(path);
73295
73545
  if (Date.now() - metadata.mtimeMs > 3e4) await unlink6(path);
73296
73546
  } catch (error61) {
73297
73547
  if (!isMissingFile(error61)) throw error61;
@@ -73299,7 +73549,7 @@ async function removeStaleRegistryLock(path) {
73299
73549
  }
73300
73550
  async function writeJsonFile(path, value) {
73301
73551
  await mkdir10(dirname7(path), { recursive: true, mode: 448 });
73302
- const temporaryPath = `${path}.${process.pid}.${randomBytes8(6).toString("hex")}.tmp`;
73552
+ const temporaryPath = `${path}.${process.pid}.${randomBytes9(6).toString("hex")}.tmp`;
73303
73553
  await writeFile5(temporaryPath, `${JSON.stringify(value, null, 2)}
73304
73554
  `, {
73305
73555
  encoding: "utf8",
@@ -73337,7 +73587,7 @@ async function createAccount(args) {
73337
73587
  created: false
73338
73588
  };
73339
73589
  }
73340
- if (!await fileExists(join9(args.store.home, "vault.json"))) {
73590
+ if (!await fileExists2(join10(args.store.home, "vault.json"))) {
73341
73591
  throw new KeystoreError("No vault yet. Run vapi setup.");
73342
73592
  }
73343
73593
  const spendCaps = resolveNewAccountCaps(args.caps);
@@ -73604,9 +73854,9 @@ async function requireAddress(store, name) {
73604
73854
  if (address4 === void 0) throw new KeystoreError(`No key for wallet ${name} in the vault.`);
73605
73855
  return address4;
73606
73856
  }
73607
- async function fileExists(path) {
73857
+ async function fileExists2(path) {
73608
73858
  try {
73609
- await stat8(path);
73859
+ await stat10(path);
73610
73860
  return true;
73611
73861
  } catch (error61) {
73612
73862
  if (isMissingFile(error61)) return false;
@@ -73668,9 +73918,9 @@ function secretsAllowed(env, streams) {
73668
73918
  }
73669
73919
 
73670
73920
  // ../core/src/agent-profile.ts
73671
- import { randomBytes as randomBytes9 } from "node:crypto";
73672
- import { mkdir as mkdir11, readFile as readFile12, readdir as readdir4, rename as rename8, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
73673
- import { join as join10 } from "node:path";
73921
+ import { randomBytes as randomBytes10 } from "node:crypto";
73922
+ import { mkdir as mkdir11, readFile as readFile13, readdir as readdir4, rename as rename8, unlink as unlink7, writeFile as writeFile6 } from "node:fs/promises";
73923
+ import { join as join11 } from "node:path";
73674
73924
  var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
73675
73925
  var AGENT_GRANTS = ["read", "delegate", "allocate"];
73676
73926
  var agentProfileShape = {
@@ -73700,7 +73950,7 @@ async function readAgentProfile(home, name, options = {}) {
73700
73950
  const path = agentProfilePath(home, name);
73701
73951
  let raw;
73702
73952
  try {
73703
- raw = await readFile12(path, "utf8");
73953
+ raw = await readFile13(path, "utf8");
73704
73954
  } catch (error61) {
73705
73955
  if (isMissingFile(error61)) {
73706
73956
  throw new Error(`No agent named ${name}. Create it with vapi agent create ${name}.`);
@@ -73712,9 +73962,9 @@ async function readAgentProfile(home, name, options = {}) {
73712
73962
  async function writeAgentProfile(home, profile, options = {}) {
73713
73963
  const parsed = (options.schema ?? agentProfileSchema).parse(profile);
73714
73964
  const directory = getVapiPaths(home).agentsDir;
73715
- const path = join10(directory, `${parsed.name}.json`);
73965
+ const path = join11(directory, `${parsed.name}.json`);
73716
73966
  await mkdir11(directory, { recursive: true, mode: 448 });
73717
- const temporaryPath = `${path}.${process.pid}.${randomBytes9(6).toString("hex")}.tmp`;
73967
+ const temporaryPath = `${path}.${process.pid}.${randomBytes10(6).toString("hex")}.tmp`;
73718
73968
  await writeFile6(temporaryPath, `${JSON.stringify(parsed, null, 2)}
73719
73969
  `, {
73720
73970
  encoding: "utf8",
@@ -73739,7 +73989,7 @@ async function listAgentProfiles(home, options = {}) {
73739
73989
  try {
73740
73990
  profiles.push(
73741
73991
  (options.schema ?? agentProfileSchema).parse(
73742
- JSON.parse(await readFile12(join10(directory, file2), "utf8"))
73992
+ JSON.parse(await readFile13(join11(directory, file2), "utf8"))
73743
73993
  )
73744
73994
  );
73745
73995
  } catch {
@@ -73760,11 +74010,11 @@ async function removeAgentProfile(home, name) {
73760
74010
  }
73761
74011
  function agentProfilePath(home, name) {
73762
74012
  const parsedName = walletNameSchema.parse(name);
73763
- return join10(getVapiPaths(home).agentsDir, `${parsedName}.json`);
74013
+ return join11(getVapiPaths(home).agentsDir, `${parsedName}.json`);
73764
74014
  }
73765
74015
 
73766
74016
  // ../core/src/ceiling.ts
73767
- import { randomBytes as randomBytes13 } from "node:crypto";
74017
+ import { randomBytes as randomBytes14 } from "node:crypto";
73768
74018
 
73769
74019
  // ../core/src/authorization-state.ts
73770
74020
  var EIP3009_AUTHORIZATION_STATE_ABI = [
@@ -73829,13 +74079,13 @@ function missingAuthorization(receipt) {
73829
74079
  }
73830
74080
 
73831
74081
  // ../core/src/movement.ts
73832
- import { randomBytes as randomBytes12 } from "node:crypto";
73833
- 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";
73834
- import { join as join11 } from "node:path";
74082
+ import { randomBytes as randomBytes13 } from "node:crypto";
74083
+ 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";
74084
+ import { join as join12 } from "node:path";
73835
74085
 
73836
74086
  // ../core/src/spend-policy.ts
73837
- import { randomBytes as randomBytes10 } from "node:crypto";
73838
- 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";
74087
+ import { randomBytes as randomBytes11 } from "node:crypto";
74088
+ 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";
73839
74089
  import { dirname as dirname8 } from "node:path";
73840
74090
  var ledgerSchema = external_exports.object({
73841
74091
  date: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
@@ -73906,7 +74156,7 @@ async function readSpendLedgerRows(path = getAgentCashPaths().ledger, now = /* @
73906
74156
  async function readStoredSpendLedgerRows(path, now, allDays = false) {
73907
74157
  let raw;
73908
74158
  try {
73909
- raw = await readFile13(path, "utf8");
74159
+ raw = await readFile14(path, "utf8");
73910
74160
  } catch (error61) {
73911
74161
  if (isMissingFile(error61)) return [];
73912
74162
  throw error61;
@@ -74039,7 +74289,7 @@ async function reserveSpend(amountAtomic2, caps, options) {
74039
74289
  { amountAtomic: amountAtomic2, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
74040
74290
  );
74041
74291
  }
74042
- const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes10(16).toString("hex"));
74292
+ const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes11(16).toString("hex"));
74043
74293
  const nextRow = {
74044
74294
  date: utcDateKey(now),
74045
74295
  spentAtomic: nextSpent.toString(),
@@ -74145,7 +74395,7 @@ async function writeLedgerAtomically(path, rows) {
74145
74395
  ...rows[0].reservations === void 0 ? {} : { reservations: rows[0].reservations }
74146
74396
  } : { version: 1, rows };
74147
74397
  await mkdir12(dirname8(path), { recursive: true, mode: 448 });
74148
- const temporaryPath = `${path}.${process.pid}.${randomBytes10(6).toString("hex")}.tmp`;
74398
+ const temporaryPath = `${path}.${process.pid}.${randomBytes11(6).toString("hex")}.tmp`;
74149
74399
  await writeFile7(temporaryPath, `${JSON.stringify(ledger, null, 2)}
74150
74400
  `, {
74151
74401
  encoding: "utf8",
@@ -74161,7 +74411,7 @@ async function withLedgerLock(path, operation) {
74161
74411
  let handle;
74162
74412
  while (!handle) {
74163
74413
  try {
74164
- handle = await open8(lockPath, "wx", 384);
74414
+ handle = await open9(lockPath, "wx", 384);
74165
74415
  } catch (error61) {
74166
74416
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) {
74167
74417
  throw error61;
@@ -74182,7 +74432,7 @@ async function withLedgerLock(path, operation) {
74182
74432
  }
74183
74433
  async function removeStaleLock3(path) {
74184
74434
  try {
74185
- const metadata = await stat9(path);
74435
+ const metadata = await stat11(path);
74186
74436
  if (Date.now() - metadata.mtimeMs > 3e4) {
74187
74437
  await unlink8(path);
74188
74438
  }
@@ -74194,8 +74444,8 @@ async function removeStaleLock3(path) {
74194
74444
  }
74195
74445
 
74196
74446
  // ../core/src/transfer.ts
74197
- import { randomBytes as randomBytes11, randomUUID } from "node:crypto";
74198
- import { mkdir as mkdir13, open as open9, stat as stat10, unlink as unlink9 } from "node:fs/promises";
74447
+ import { randomBytes as randomBytes12, randomUUID } from "node:crypto";
74448
+ import { mkdir as mkdir13, open as open10, stat as stat12, unlink as unlink9 } from "node:fs/promises";
74199
74449
  import { dirname as dirname9 } from "node:path";
74200
74450
 
74201
74451
  // ../core/src/siblings.ts
@@ -74404,7 +74654,7 @@ async function transferBetweenAccounts(args) {
74404
74654
  if (args.resume !== void 0) {
74405
74655
  return await resumeTransfer(context, args.resume);
74406
74656
  }
74407
- const nonce = args.nonce ?? bytesToHex(randomBytes11(32));
74657
+ const nonce = args.nonce ?? bytesToHex(randomBytes12(32));
74408
74658
  if (!NONCE_PATTERN.test(nonce)) {
74409
74659
  throw new TransferError(
74410
74660
  "authorization_invalid",
@@ -74797,7 +75047,7 @@ async function withTransferLock(context, nonce, operation) {
74797
75047
  let handle;
74798
75048
  while (!handle) {
74799
75049
  try {
74800
- handle = await open9(lockPath, "wx", 384);
75050
+ handle = await open10(lockPath, "wx", 384);
74801
75051
  } catch (error61) {
74802
75052
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
74803
75053
  await removeStaleTransferLock(lockPath, staleAfterMs);
@@ -74816,7 +75066,7 @@ async function withTransferLock(context, nonce, operation) {
74816
75066
  }
74817
75067
  async function removeStaleTransferLock(path, staleAfterMs) {
74818
75068
  try {
74819
- const metadata = await stat10(path);
75069
+ const metadata = await stat12(path);
74820
75070
  if (Date.now() - metadata.mtimeMs > staleAfterMs) await unlink9(path);
74821
75071
  } catch (error61) {
74822
75072
  if (!(error61 instanceof Error && "code" in error61 && error61.code === "ENOENT")) throw error61;
@@ -75242,7 +75492,7 @@ async function listUnfinishedMovements(options) {
75242
75492
  }
75243
75493
  const summaries = [];
75244
75494
  for (const name of names.filter((candidate) => candidate.endsWith(".json")).sort()) {
75245
- const movement = parseMovement(JSON.parse(await readFile14(join11(directory, name), "utf8")));
75495
+ const movement = parseMovement(JSON.parse(await readFile15(join12(directory, name), "utf8")));
75246
75496
  if (options.from !== void 0 && !movement.legs.some((leg) => leg.from === options.from)) {
75247
75497
  continue;
75248
75498
  }
@@ -75273,7 +75523,7 @@ async function listUnfinishedMovementSnapshots(options) {
75273
75523
  }
75274
75524
  const snapshots = [];
75275
75525
  for (const name of names.filter((candidate) => candidate.endsWith(".json")).sort()) {
75276
- const movement = parseMovement(JSON.parse(await readFile14(join11(directory, name), "utf8")));
75526
+ const movement = parseMovement(JSON.parse(await readFile15(join12(directory, name), "utf8")));
75277
75527
  if (options.from !== void 0 && !movement.legs.some((leg) => leg.from === options.from)) {
75278
75528
  continue;
75279
75529
  }
@@ -75309,23 +75559,23 @@ async function movementHasOpenLeg(home, movement, from16) {
75309
75559
  return false;
75310
75560
  }
75311
75561
  async function movementOpenEvidence(home, movement, from16) {
75312
- let open12 = false;
75562
+ let open13 = false;
75313
75563
  const signedFailedLegKeys = [];
75314
75564
  for (const leg of movement.legs) {
75315
75565
  if (from16 !== void 0 && leg.from !== from16) continue;
75316
- if (isOpenMovementLeg(leg, "unsigned")) open12 = true;
75566
+ if (isOpenMovementLeg(leg, "unsigned")) open13 = true;
75317
75567
  if (leg.status !== "failed") continue;
75318
75568
  const journal = await readTransferJournal(home, leg.from, leg.nonce);
75319
75569
  if (journal.signed) signedFailedLegKeys.push(movementTransferKey(leg.from, leg.nonce));
75320
- if (isOpenMovementLeg(leg, journal.signed ? "signed" : "unsigned")) open12 = true;
75570
+ if (isOpenMovementLeg(leg, journal.signed ? "signed" : "unsigned")) open13 = true;
75321
75571
  }
75322
- return { open: open12, signedFailedLegKeys };
75572
+ return { open: open13, signedFailedLegKeys };
75323
75573
  }
75324
75574
  async function readMovement(home, id2) {
75325
75575
  const safeId = parseMovementId(id2);
75326
75576
  try {
75327
75577
  return parseMovement(
75328
- JSON.parse(await readFile14(join11(movementsDirectory(home), `${safeId}.json`), "utf8"))
75578
+ JSON.parse(await readFile15(join12(movementsDirectory(home), `${safeId}.json`), "utf8"))
75329
75579
  );
75330
75580
  } catch (error61) {
75331
75581
  if (isMissingFile(error61)) {
@@ -76045,33 +76295,33 @@ function parseMovementId(value) {
76045
76295
  return parsed.data;
76046
76296
  }
76047
76297
  function movementsDirectory(home) {
76048
- return join11(home, "movements");
76298
+ return join12(home, "movements");
76049
76299
  }
76050
76300
  function createMovementId() {
76051
- return `mv_${randomBytes12(12).toString("hex")}`;
76301
+ return `mv_${randomBytes13(12).toString("hex")}`;
76052
76302
  }
76053
76303
  function createMovementNonce() {
76054
- return bytesToHex(randomBytes12(32));
76304
+ return bytesToHex(randomBytes13(32));
76055
76305
  }
76056
76306
  async function writeMovement(home, movement) {
76057
76307
  const parsed = movementSchema.parse(movement);
76058
76308
  const directory = movementsDirectory(home);
76059
76309
  await mkdir14(directory, { recursive: true, mode: 448 });
76060
76310
  await chmod4(directory, 448);
76061
- const path = join11(directory, `${parsed.id}.json`);
76062
- const temporary = join11(
76311
+ const path = join12(directory, `${parsed.id}.json`);
76312
+ const temporary = join12(
76063
76313
  directory,
76064
- `.${parsed.id}.${process.pid}.${randomBytes12(6).toString("hex")}.tmp`
76314
+ `.${parsed.id}.${process.pid}.${randomBytes13(6).toString("hex")}.tmp`
76065
76315
  );
76066
76316
  let handle;
76067
76317
  try {
76068
- handle = await open10(temporary, "wx", 384);
76318
+ handle = await open11(temporary, "wx", 384);
76069
76319
  await handle.writeFile(serializeMovement(parsed), "utf8");
76070
76320
  await handle.sync();
76071
76321
  await handle.close();
76072
76322
  handle = void 0;
76073
76323
  await rename10(temporary, path);
76074
- const directoryHandle = await open10(directory, "r");
76324
+ const directoryHandle = await open11(directory, "r");
76075
76325
  try {
76076
76326
  await directoryHandle.sync();
76077
76327
  } finally {
@@ -76291,7 +76541,7 @@ async function sweepAboveCeilingLocked(args) {
76291
76541
  owner,
76292
76542
  target,
76293
76543
  amountAtomic: amountAtomic2.toString(),
76294
- nonce: (args.randomNonce ?? (() => bytesToHex(randomBytes13(32))))(),
76544
+ nonce: (args.randomNonce ?? (() => bytesToHex(randomBytes14(32))))(),
76295
76545
  createdAt: new Date(now()).toISOString(),
76296
76546
  status: "planned"
76297
76547
  };
@@ -77083,8 +77333,8 @@ function parseDecimal(value, scale) {
77083
77333
  }
77084
77334
 
77085
77335
  // ../core/src/swarm.ts
77086
- import { readdir as readdir6, readFile as readFile15, stat as stat11, unlink as unlink11 } from "node:fs/promises";
77087
- import { join as join12 } from "node:path";
77336
+ import { readdir as readdir6, readFile as readFile16, stat as stat13, unlink as unlink11 } from "node:fs/promises";
77337
+ import { join as join13 } from "node:path";
77088
77338
  var SWARM_NAME_PATTERN = /^[a-z][a-z0-9-]{0,15}$/;
77089
77339
  var SWARM_ROLE_PATTERN = /^[a-z][a-z0-9]{0,7}$/;
77090
77340
  var DEFAULT_SWARM_MODEL = "venice/claude-sonnet-5";
@@ -77165,16 +77415,16 @@ var SwarmError = class extends Error {
77165
77415
  code;
77166
77416
  };
77167
77417
  function swarmsDirectory(home) {
77168
- return join12(home, "swarms");
77418
+ return join13(home, "swarms");
77169
77419
  }
77170
77420
  function swarmFilePath(home, name) {
77171
77421
  assertName(name);
77172
- return join12(swarmsDirectory(home), `${name}.json`);
77422
+ return join13(swarmsDirectory(home), `${name}.json`);
77173
77423
  }
77174
77424
  async function readSwarm(home, name) {
77175
77425
  const path = swarmFilePath(home, name);
77176
77426
  try {
77177
- const swarm = parseSwarm(JSON.parse(await readFile15(path, "utf8")));
77427
+ const swarm = parseSwarm(JSON.parse(await readFile16(path, "utf8")));
77178
77428
  if (swarm.name !== name)
77179
77429
  throw new SwarmError("invalid_swarm", "Swarm name does not match its file.");
77180
77430
  return swarm;
@@ -77202,7 +77452,7 @@ async function writeSwarm(home, value) {
77202
77452
  const bytes = `${JSON.stringify(swarm, null, 2)}
77203
77453
  `;
77204
77454
  try {
77205
- if (await readFile15(path, "utf8") === bytes) return;
77455
+ if (await readFile16(path, "utf8") === bytes) return;
77206
77456
  } catch (error61) {
77207
77457
  if (!isMissingFile(error61)) throw error61;
77208
77458
  }
@@ -77217,7 +77467,7 @@ async function deleteSwarmFile(home, name) {
77217
77467
  }
77218
77468
  async function withSwarmLock(home, name, fn) {
77219
77469
  assertName(name);
77220
- const path = join12(swarmsDirectory(home), `.${name}.lock`);
77470
+ const path = join13(swarmsDirectory(home), `.${name}.lock`);
77221
77471
  try {
77222
77472
  return await withFileLock(path, fn, { lockedMessage: `Swarm ${name} is locked.` });
77223
77473
  } catch (error61) {
@@ -77529,7 +77779,7 @@ async function swarmStatus(opts) {
77529
77779
  );
77530
77780
  let movementFiles;
77531
77781
  try {
77532
- movementFiles = await readdir6(join12(home, "movements"));
77782
+ movementFiles = await readdir6(join13(home, "movements"));
77533
77783
  } catch (error61) {
77534
77784
  if (!isMissingFile(error61)) throw error61;
77535
77785
  movementFiles = [];
@@ -77586,11 +77836,11 @@ async function swarmStatus(opts) {
77586
77836
  })
77587
77837
  );
77588
77838
  const accounts = new Set(swarmAccountNames(swarm));
77589
- const open12 = [];
77839
+ const open13 = [];
77590
77840
  for (const summary2 of await listUnfinishedMovements({ home })) {
77591
77841
  const movement = await readMovement(home, summary2.id);
77592
77842
  if (movement.treasury === swarm.treasury.account || movement.legs.some((leg) => accounts.has(leg.from) || accounts.has(leg.to))) {
77593
- open12.push(summary2);
77843
+ open13.push(summary2);
77594
77844
  }
77595
77845
  }
77596
77846
  return {
@@ -77599,7 +77849,7 @@ async function swarmStatus(opts) {
77599
77849
  strategy: swarm.policy.strategy,
77600
77850
  treasury,
77601
77851
  members: members2,
77602
- openMovements: open12.sort(
77852
+ openMovements: open13.sort(
77603
77853
  (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)
77604
77854
  )
77605
77855
  };
@@ -77698,7 +77948,7 @@ async function assertNoConflicts(home, name, accounts) {
77698
77948
  }
77699
77949
  async function profileExists(home, account) {
77700
77950
  try {
77701
- await stat11(join12(getVapiPaths(home).agentsDir, `${account}.json`));
77951
+ await stat13(join13(getVapiPaths(home).agentsDir, `${account}.json`));
77702
77952
  return true;
77703
77953
  } catch (error61) {
77704
77954
  if (isMissingFile(error61)) return false;
@@ -77711,7 +77961,7 @@ async function refuseTreasuryProfile(home, account) {
77711
77961
  }
77712
77962
 
77713
77963
  // ../core/src/x402-pay.ts
77714
- import { randomBytes as randomBytes14, randomUUID as randomUUID2 } from "node:crypto";
77964
+ import { randomBytes as randomBytes15, randomUUID as randomUUID2 } from "node:crypto";
77715
77965
 
77716
77966
  // ../core/src/run-budget.ts
77717
77967
  var RunBudgetError = class extends Error {
@@ -77752,13 +78002,13 @@ function createRunBudget(args) {
77752
78002
  // ../core/src/support-report.ts
77753
78003
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
77754
78004
  import { arch, platform, release } from "node:os";
77755
- import { join as join13 } from "node:path";
77756
- var VAPI_CLIENT_VERSION = "0.12.0";
78005
+ import { join as join14 } from "node:path";
78006
+ var VAPI_CLIENT_VERSION = "0.13.0";
77757
78007
  async function createSupportReport(options) {
77758
78008
  const message = options.message.trim();
77759
78009
  if (!message) throw new Error("Support report message must not be empty.");
77760
78010
  const paths = getVapiPaths();
77761
- const reportsDirectory = options.reportsDirectory ?? join13(paths.directory, "reports");
78011
+ const reportsDirectory = options.reportsDirectory ?? join14(paths.directory, "reports");
77762
78012
  const receipts = await readReceipts(options.receiptsPath ?? paths.receipts, { limit: 5 });
77763
78013
  const system = options.systemInfo ?? defaultSystemInfo();
77764
78014
  const report = {
@@ -77788,7 +78038,7 @@ async function createSupportReport(options) {
77788
78038
  };
77789
78039
  const now = options.now ?? /* @__PURE__ */ new Date();
77790
78040
  const timestamp = now.toISOString();
77791
- const path = join13(reportsDirectory, `${sanitizeTimestamp(timestamp)}.json`);
78041
+ const path = join14(reportsDirectory, `${sanitizeTimestamp(timestamp)}.json`);
77792
78042
  await mkdir15(reportsDirectory, { recursive: true, mode: 448 });
77793
78043
  const serialized = `${JSON.stringify(report, null, 2)}
77794
78044
  `;
@@ -77984,7 +78234,7 @@ async function completeX402Payment(args) {
77984
78234
  throw walletCapError(error61, quote.amountAtomic, args);
77985
78235
  }
77986
78236
  } else {
77987
- reservationId = args.paymentId ?? `x402_${randomBytes14(12).toString("hex")}`;
78237
+ reservationId = args.paymentId ?? `x402_${randomBytes15(12).toString("hex")}`;
77988
78238
  let reservation;
77989
78239
  try {
77990
78240
  reservation = await reserveSpend(quote.amountAtomic, args.caps, {
@@ -79385,8 +79635,8 @@ function freezeScopeTerms(structuredInput, briefInput) {
79385
79635
  }
79386
79636
 
79387
79637
  // ../core/src/tasks/scope-bindings.ts
79388
- import { readFile as readFile16 } from "node:fs/promises";
79389
- import { join as join14 } from "node:path";
79638
+ import { readFile as readFile17 } from "node:fs/promises";
79639
+ import { join as join15 } from "node:path";
79390
79640
 
79391
79641
  // ../core/src/tasks/chain-port.ts
79392
79642
  var TasksChainError = class extends Error {
@@ -79961,7 +80211,7 @@ var messageSchema = external_exports.looseObject({
79961
80211
  })
79962
80212
  )
79963
80213
  });
79964
- var fileSchema = external_exports.looseObject({
80214
+ var fileSchema2 = external_exports.looseObject({
79965
80215
  id: uuidSchema,
79966
80216
  purpose: workFilePurposeSchema,
79967
80217
  fileName: external_exports.string(),
@@ -80267,11 +80517,11 @@ var tasksResponseSchemas = {
80267
80517
  observedAt: isoDateTimeSchema
80268
80518
  }),
80269
80519
  createUpload: external_exports.looseObject({
80270
- file: fileSchema.extend({ state: external_exports.literal("pending"), sha256: external_exports.null() }),
80520
+ file: fileSchema2.extend({ state: external_exports.literal("pending"), sha256: external_exports.null() }),
80271
80521
  uploadUrl: external_exports.url()
80272
80522
  }),
80273
80523
  finalizeUpload: external_exports.looseObject({
80274
- file: fileSchema.extend({
80524
+ file: fileSchema2.extend({
80275
80525
  state: external_exports.literal("ready"),
80276
80526
  sha256: external_exports.string().regex(/^[0-9a-fA-F]{64}$/)
80277
80527
  })
@@ -80879,10 +81129,10 @@ function key(identity) {
80879
81129
  return `${identity.orderId}:${identity.trancheOrdinal}:${identity.scopeVersion}:${identity.termsHash.toLowerCase()}:${identity.self.toLowerCase()}`;
80880
81130
  }
80881
81131
  function createScopeBindings(home) {
80882
- const path = join14(home, "tasks", "scope-bindings.json");
81132
+ const path = join15(home, "tasks", "scope-bindings.json");
80883
81133
  async function read() {
80884
81134
  try {
80885
- return storeSchema.parse(JSON.parse(await readFile16(path, "utf8")));
81135
+ return storeSchema.parse(JSON.parse(await readFile17(path, "utf8")));
80886
81136
  } catch (error61) {
80887
81137
  if (error61 instanceof Error && "code" in error61 && error61.code === "ENOENT")
80888
81138
  return { version: 1, bindings: {} };
@@ -81563,7 +81813,7 @@ function createTasksChain(options) {
81563
81813
  const { account, client, pending, rpcFor } = options;
81564
81814
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
81565
81815
  const sleep = options.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
81566
- const randomBytes17 = options.randomBytes ?? cryptoRandomBytes2;
81816
+ const randomBytes18 = options.randomBytes ?? cryptoRandomBytes2;
81567
81817
  const confirmations = options.confirmations ?? 2;
81568
81818
  if (!Number.isSafeInteger(confirmations) || confirmations < 1)
81569
81819
  throw new TasksChainError("Tasks confirmations must be a positive integer.", false, {
@@ -82172,7 +82422,7 @@ function createTasksChain(options) {
82172
82422
  await verifyClone(rpcFor(ready.chainId), expected, true);
82173
82423
  if (validBefore <= BigInt(Math.floor(now().getTime() / 1e3)))
82174
82424
  throw new TasksValidationError("The task funding offer has expired.");
82175
- const bytes = randomBytes17(32);
82425
+ const bytes = randomBytes18(32);
82176
82426
  if (bytes.length !== 32)
82177
82427
  throw new TasksValidationError(
82178
82428
  "Funding authorization randomness must contain 32 bytes."
@@ -82450,8 +82700,8 @@ function createTasksRpcFor(config2, options = {}) {
82450
82700
  }
82451
82701
 
82452
82702
  // ../core/src/tasks/pending-transactions.ts
82453
- import { readFile as readFile17 } from "node:fs/promises";
82454
- import { join as join15 } from "node:path";
82703
+ import { readFile as readFile18 } from "node:fs/promises";
82704
+ import { join as join16 } from "node:path";
82455
82705
  var hex3 = external_exports.string().regex(/^0x(?:[0-9a-fA-F]{2})+$/).transform((v) => v);
82456
82706
  var hash4 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform((v) => v);
82457
82707
  var step = external_exports.enum([
@@ -82533,11 +82783,11 @@ function validCheckpointStep(storedStep, response) {
82533
82783
  }[response.operation.kind];
82534
82784
  }
82535
82785
  function createPendingTransactions(home) {
82536
- const path = join15(home, "tasks", "pending.json");
82786
+ const path = join16(home, "tasks", "pending.json");
82537
82787
  const lockPath = `${path}.lock`;
82538
82788
  const read = async () => {
82539
82789
  try {
82540
- const state = stateSchema.parse(JSON.parse(await readFile17(path, "utf8")));
82790
+ const state = stateSchema.parse(JSON.parse(await readFile18(path, "utf8")));
82541
82791
  for (const [key2, value] of Object.entries(state.checkpoints)) {
82542
82792
  const separator = key2.indexOf(":");
82543
82793
  const operationId = key2.slice(0, separator);
@@ -82600,7 +82850,7 @@ function createPendingTransactions(home) {
82600
82850
  },
82601
82851
  withStepLock(operationId, step2, fn) {
82602
82852
  return withFileLock(
82603
- join15(
82853
+ join16(
82604
82854
  home,
82605
82855
  "tasks",
82606
82856
  `step-${encodeURIComponent(operationId)}-${encodeURIComponent(step2)}.lock`
@@ -82612,13 +82862,13 @@ function createPendingTransactions(home) {
82612
82862
  external_exports.number().int().positive().parse(chainId);
82613
82863
  address3.parse(signer);
82614
82864
  return withFileLock(
82615
- join15(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
82865
+ join16(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
82616
82866
  fn
82617
82867
  );
82618
82868
  },
82619
82869
  withFundingLock(milestoneId, fn) {
82620
82870
  milestoneKey(milestoneId);
82621
- return withFileLock(join15(home, "tasks", `fund-${milestoneId}.lock`), fn);
82871
+ return withFileLock(join16(home, "tasks", `fund-${milestoneId}.lock`), fn);
82622
82872
  },
82623
82873
  async nextNonce(chainId, signer) {
82624
82874
  external_exports.number().int().positive().parse(chainId);
@@ -83444,7 +83694,7 @@ function policyAtomic(value) {
83444
83694
  }
83445
83695
 
83446
83696
  // ../core/src/tasks/operation-support.ts
83447
- import { readFile as readFile18, stat as stat12 } from "node:fs/promises";
83697
+ import { readFile as readFile19, stat as stat14 } from "node:fs/promises";
83448
83698
  import { basename as basename3, extname } from "node:path";
83449
83699
  var TaskOperationError = class extends Error {
83450
83700
  constructor(code, message, manifestHash) {
@@ -83612,7 +83862,7 @@ function parseTaskDuration(text, now) {
83612
83862
  async function readTaskFile(path) {
83613
83863
  let details;
83614
83864
  try {
83615
- details = await stat12(path);
83865
+ details = await stat14(path);
83616
83866
  } catch {
83617
83867
  throw new TaskInputError(`Task file ${JSON.stringify(path)} could not be read.`);
83618
83868
  }
@@ -83636,7 +83886,7 @@ async function readTaskFile(path) {
83636
83886
  const contentType = types[extname(path).toLowerCase()];
83637
83887
  if (!contentType)
83638
83888
  throw new TaskInputError("Task files must be images, PDF, ZIP, text, Markdown, JSON or CSV.");
83639
- const bytes = await readFile18(path);
83889
+ const bytes = await readFile19(path);
83640
83890
  if (bytes.length < TASK_LIMITS.uploadBytesMin || bytes.length > TASK_LIMITS.uploadBytesMax)
83641
83891
  throw new TaskInputError("Task files must contain between 1 byte and 50 MiB.");
83642
83892
  return {
@@ -84435,7 +84685,7 @@ async function resolveUnmatchedTaskOperation(context, input2) {
84435
84685
  }
84436
84686
 
84437
84687
  // ../core/src/searches.ts
84438
- import { mkdir as mkdir16, open as open11, readFile as readFile19 } from "node:fs/promises";
84688
+ import { mkdir as mkdir16, open as open12, readFile as readFile20 } from "node:fs/promises";
84439
84689
  import { dirname as dirname10 } from "node:path";
84440
84690
  var searchEventSchema = external_exports.strictObject({
84441
84691
  timestamp: external_exports.iso.datetime(),
@@ -84457,7 +84707,7 @@ function parseSearchEvent(value) {
84457
84707
  async function appendSearchEvent(event, path = getVapiPaths().searches) {
84458
84708
  const parsed = parseSearchEvent(event);
84459
84709
  await mkdir16(dirname10(path), { recursive: true, mode: 448 });
84460
- const handle = await open11(path, "a", 384);
84710
+ const handle = await open12(path, "a", 384);
84461
84711
  try {
84462
84712
  await handle.writeFile(`${JSON.stringify(parsed)}
84463
84713
  `, "utf8");
@@ -84469,7 +84719,7 @@ async function appendSearchEvent(event, path = getVapiPaths().searches) {
84469
84719
  async function readSearchEvents(path = getVapiPaths().searches) {
84470
84720
  let raw;
84471
84721
  try {
84472
- raw = await readFile19(path, "utf8");
84722
+ raw = await readFile20(path, "utf8");
84473
84723
  } catch (error61) {
84474
84724
  if (isMissingFile(error61)) return [];
84475
84725
  throw error61;
@@ -85371,9 +85621,9 @@ function csvCell(value) {
85371
85621
  }
85372
85622
 
85373
85623
  // ../core/src/swarm-capital.ts
85374
- import { createHash as createHash5, randomBytes as randomBytes15 } from "node:crypto";
85375
- import { readFile as readFile20, unlink as unlink12 } from "node:fs/promises";
85376
- import { join as join16 } from "node:path";
85624
+ import { createHash as createHash5, randomBytes as randomBytes16 } from "node:crypto";
85625
+ import { readFile as readFile21, unlink as unlink12 } from "node:fs/promises";
85626
+ import { join as join17 } from "node:path";
85377
85627
  var movementIdSchema3 = external_exports.string().regex(/^mv_[A-Za-z0-9_-]{8,128}$/u);
85378
85628
  var amountSchema2 = external_exports.string().regex(/^\d+\.\d{2}$/u);
85379
85629
  var requestIdSchema = external_exports.string().min(1).max(512);
@@ -86254,7 +86504,7 @@ async function readDelegationRecord(home, movementId) {
86254
86504
  const safeId = runRecordMovementId(movementId);
86255
86505
  try {
86256
86506
  const record2 = delegationRecordSchema.parse(
86257
- JSON.parse(await readFile20(delegationRecordPath(home, safeId), "utf8"))
86507
+ JSON.parse(await readFile21(delegationRecordPath(home, safeId), "utf8"))
86258
86508
  );
86259
86509
  if (record2.movementId !== safeId) {
86260
86510
  throw new SwarmError(
@@ -86281,7 +86531,7 @@ async function readTreasuryRequestRecord(home, movementId) {
86281
86531
  const safeId = runRecordMovementId(movementId);
86282
86532
  try {
86283
86533
  const record2 = treasuryRequestRecordSchema.parse(
86284
- JSON.parse(await readFile20(treasuryRequestRecordPath(home, safeId), "utf8"))
86534
+ JSON.parse(await readFile21(treasuryRequestRecordPath(home, safeId), "utf8"))
86285
86535
  );
86286
86536
  if (record2.movementId !== safeId) {
86287
86537
  throw new SwarmError(
@@ -86312,18 +86562,18 @@ function runRecordMovementId(value) {
86312
86562
  return parsed.data;
86313
86563
  }
86314
86564
  function treasuryRequestRecordPath(home, movementId) {
86315
- return join16(home, "runs", "requests", `${movementId}.json`);
86565
+ return join17(home, "runs", "requests", `${movementId}.json`);
86316
86566
  }
86317
86567
  function delegationRecordPath(home, movementId) {
86318
- return join16(home, "runs", "delegations", `${movementId}.json`);
86568
+ return join17(home, "runs", "delegations", `${movementId}.json`);
86319
86569
  }
86320
86570
  function legacyFundingProgressPath(home, name) {
86321
- return join16(home, "swarms", `.${name}.funding`);
86571
+ return join17(home, "swarms", `.${name}.funding`);
86322
86572
  }
86323
86573
  async function readLegacyFundingProgress(home, name) {
86324
86574
  try {
86325
86575
  const progress = legacyFundingProgressSchema.parse(
86326
- JSON.parse(await readFile20(legacyFundingProgressPath(home, name), "utf8"))
86576
+ JSON.parse(await readFile21(legacyFundingProgressPath(home, name), "utf8"))
86327
86577
  );
86328
86578
  if (progress.name !== name) {
86329
86579
  throw new SwarmError("invalid_swarm", `Invalid funding progress for swarm ${name}.`);
@@ -86552,7 +86802,7 @@ async function optionalMovement(home, id2) {
86552
86802
  }
86553
86803
  }
86554
86804
  function nextMovementId(deps) {
86555
- return movementIdSchema3.parse(deps.randomId?.() ?? `mv_${randomBytes15(12).toString("hex")}`);
86805
+ return movementIdSchema3.parse(deps.randomId?.() ?? `mv_${randomBytes16(12).toString("hex")}`);
86556
86806
  }
86557
86807
  async function executeRecordedMovement(id2, plan, deps, home, options = {}) {
86558
86808
  try {
@@ -86968,7 +87218,7 @@ async function removeMemberLocked(home, swarm, account) {
86968
87218
  }
86969
87219
 
86970
87220
  // ../core/src/status.ts
86971
- import { join as join17 } from "node:path";
87221
+ import { join as join18 } from "node:path";
86972
87222
  var STATUS_TIMEOUT_MS = 2e3;
86973
87223
  async function buildStatus(deps) {
86974
87224
  const timers = deps.timers ?? { setTimeout, clearTimeout };
@@ -87024,7 +87274,7 @@ function formatUsdAmount(value) {
87024
87274
  }
87025
87275
  async function readVaultStatus(deps) {
87026
87276
  const store = deps.secrets.description.replace(/^the /u, "");
87027
- const path = join17(deps.home, "vault.json");
87277
+ const path = join18(deps.home, "vault.json");
87028
87278
  let file2;
87029
87279
  try {
87030
87280
  file2 = await readVaultFileUnlocked(path);
@@ -87730,7 +87980,7 @@ function assertKeyMatchesAddress(bundle) {
87730
87980
  }
87731
87981
 
87732
87982
  // ../core/src/api-key.ts
87733
- import { chmod as chmod5, mkdir as mkdir17, readFile as readFile21, rename as rename11, writeFile as writeFile9 } from "node:fs/promises";
87983
+ import { chmod as chmod5, mkdir as mkdir17, readFile as readFile22, rename as rename11, writeFile as writeFile9 } from "node:fs/promises";
87734
87984
  import { dirname as dirname11 } from "node:path";
87735
87985
  var API_KEY_PREFIX = "vapi_sk_";
87736
87986
  var API_KEY_PATTERN = /^vapi_sk_[A-Za-z0-9_-]{16,128}$/;
@@ -87826,7 +88076,7 @@ async function readConfigApiKey(path) {
87826
88076
  async function readConfigRecord(path) {
87827
88077
  let raw;
87828
88078
  try {
87829
- raw = await readFile21(path, "utf8");
88079
+ raw = await readFile22(path, "utf8");
87830
88080
  } catch (error61) {
87831
88081
  if (isMissingFile(error61)) return void 0;
87832
88082
  throw error61;
@@ -90496,8 +90746,8 @@ function exactPriceFact(value) {
90496
90746
  }
90497
90747
 
90498
90748
  // ../mcp/src/agent/runtime.ts
90499
- import { mkdir as mkdir18, readFile as readFile22, readdir as readdir7, rm as rm2 } from "node:fs/promises";
90500
- import { join as join18 } from "node:path";
90749
+ import { mkdir as mkdir18, readFile as readFile23, readdir as readdir7, rm as rm2 } from "node:fs/promises";
90750
+ import { join as join19 } from "node:path";
90501
90751
 
90502
90752
  // ../mcp/src/agent/run.ts
90503
90753
  var loopSearchResultSchema = external_exports.array(
@@ -91798,19 +92048,19 @@ var runRecordSchema = external_exports.strictObject({
91798
92048
  detail: external_exports.string().optional()
91799
92049
  });
91800
92050
  function runsDirectory(home) {
91801
- return join18(home, "runs");
92051
+ return join19(home, "runs");
91802
92052
  }
91803
92053
  function runRecordPath(home, runId) {
91804
92054
  assertRunId(runId);
91805
- return join18(runsDirectory(home), `${runId}.json`);
92055
+ return join19(runsDirectory(home), `${runId}.json`);
91806
92056
  }
91807
92057
  function runLogPath(home, runId) {
91808
92058
  assertRunId(runId);
91809
- return join18(runsDirectory(home), `${runId}.log`);
92059
+ return join19(runsDirectory(home), `${runId}.log`);
91810
92060
  }
91811
92061
  function runResultPath(home, runId) {
91812
92062
  assertRunId(runId);
91813
- return join18(runsDirectory(home), `${runId}.result.json`);
92063
+ return join19(runsDirectory(home), `${runId}.result.json`);
91814
92064
  }
91815
92065
  async function writeRunRecord(home, record2) {
91816
92066
  const path = runRecordPath(home, record2.runId);
@@ -91821,7 +92071,7 @@ async function writeRunRecord(home, record2) {
91821
92071
  async function readRunRecord(home, runId) {
91822
92072
  const path = runRecordPath(home, runId);
91823
92073
  try {
91824
- return runRecordSchema.parse(JSON.parse(await readFile22(path, "utf8")));
92074
+ return runRecordSchema.parse(JSON.parse(await readFile23(path, "utf8")));
91825
92075
  } catch (error61) {
91826
92076
  if (isMissingFile3(error61)) return void 0;
91827
92077
  throw error61;
@@ -91841,7 +92091,7 @@ async function listRunRecords(home, filter = {}) {
91841
92091
  if (match === null) continue;
91842
92092
  try {
91843
92093
  const record2 = runRecordSchema.parse(
91844
- JSON.parse(await readFile22(join18(runsDirectory(home), file2), "utf8"))
92094
+ JSON.parse(await readFile23(join19(runsDirectory(home), file2), "utf8"))
91845
92095
  );
91846
92096
  if (record2.runId !== match[1]) continue;
91847
92097
  if (filter.swarm !== void 0 && record2.member.swarm !== filter.swarm) continue;
@@ -92118,7 +92368,7 @@ async function stopRun(args) {
92118
92368
  }
92119
92369
  }
92120
92370
  function memberRunLockPath(home, account) {
92121
- return join18(runsDirectory(home), `.member-${account}.lock`);
92371
+ return join19(runsDirectory(home), `.member-${account}.lock`);
92122
92372
  }
92123
92373
  function summarizeRunRecord(record2) {
92124
92374
  return {
@@ -95722,8 +95972,8 @@ function rgbToAnsi256(red, green, blue) {
95722
95972
  }
95723
95973
 
95724
95974
  // src/accounts.ts
95725
- import { readFile as readFile24, stat as stat14 } from "node:fs/promises";
95726
- import { join as join21 } from "node:path";
95975
+ import { readFile as readFile25, stat as stat16 } from "node:fs/promises";
95976
+ import { join as join22 } from "node:path";
95727
95977
 
95728
95978
  // src/dashboard.ts
95729
95979
  import { resolve as resolve2 } from "node:path";
@@ -95734,7 +95984,12 @@ var PROBE_MODES = ["origin", "endpoint", "openapi"];
95734
95984
  var PAYOUT_CHAIN_ID = "eip155:8453";
95735
95985
  var PAYOUT_STATEMENT = "Confirm this wallet receives vAPI Call payouts";
95736
95986
  var CLAIM_STATEMENT_PREFIX = "Claim the vAPI Call listings served from";
95737
- var API_KEY_CONSOLE_PATH = "/account";
95987
+ function apiKeyConsoleUrl(baseUrl) {
95988
+ const url2 = listingsUrl(baseUrl, "/connect");
95989
+ url2.search = "advanced=keys";
95990
+ url2.hash = "api-keys";
95991
+ return url2;
95992
+ }
95738
95993
  var RegistryApiError = class extends Error {
95739
95994
  constructor(status, message, body) {
95740
95995
  super(message);
@@ -95894,7 +96149,7 @@ async function registryError(response, baseUrl) {
95894
96149
  [
95895
96150
  "The vAPI API key was rejected.",
95896
96151
  detail,
95897
- `Create a key in the console at ${listingsUrl(baseUrl, API_KEY_CONSOLE_PATH).href} and store it with vapi auth set-key.`
96152
+ `Create a key in the console at ${apiKeyConsoleUrl(baseUrl).href} and store it with vapi auth set-key.`
95898
96153
  ].filter(Boolean).join(" "),
95899
96154
  body
95900
96155
  );
@@ -96395,12 +96650,12 @@ function shellQuote2(value) {
96395
96650
  }
96396
96651
 
96397
96652
  // src/status.ts
96398
- import { stat as stat13 } from "node:fs/promises";
96653
+ import { stat as stat15 } from "node:fs/promises";
96399
96654
  import { homedir as homedir2 } from "node:os";
96400
96655
  import { sep } from "node:path";
96401
96656
 
96402
96657
  // ../core/src/cloud-backup.ts
96403
- import { join as join20 } from "node:path";
96658
+ import { join as join21 } from "node:path";
96404
96659
 
96405
96660
  // ../core/src/backup.ts
96406
96661
  import {
@@ -96423,11 +96678,11 @@ import {
96423
96678
  mkdir as mkdir19,
96424
96679
  mkdtemp,
96425
96680
  open as openFile,
96426
- readFile as readFile23,
96681
+ readFile as readFile24,
96427
96682
  readdir as readdir8,
96428
96683
  rm as rm3
96429
96684
  } from "node:fs/promises";
96430
- import { dirname as dirname12, join as join19 } from "node:path";
96685
+ import { dirname as dirname12, join as join20 } from "node:path";
96431
96686
  var ERROR_MESSAGES = {
96432
96687
  backup_too_large: "Backup envelope exceeds 65,536 bytes.",
96433
96688
  backup_open_failed: "Unable to open backup.",
@@ -96710,8 +96965,8 @@ async function createBackup(options) {
96710
96965
  assertDevice(options.device);
96711
96966
  assertOwnerKey(options.ownerKey);
96712
96967
  const createdAt = readCreatedAt(options.now ?? (() => /* @__PURE__ */ new Date()));
96713
- const randomBytes17 = options.randomBytes ?? cryptoRandomBytes3;
96714
- const nonce = readRandomBytes(randomBytes17, 12);
96968
+ const randomBytes18 = options.randomBytes ?? cryptoRandomBytes3;
96969
+ const nonce = readRandomBytes(randomBytes18, 12);
96715
96970
  const salt = encodeBase64Url(options.ownerKey.salt);
96716
96971
  const kdf = options.ownerKey.kdf === "hkdf-sha256" ? { name: "hkdf-sha256", salt } : { name: "scrypt", salt, N: SCRYPT_N2, r: SCRYPT_R2, p: SCRYPT_P2 };
96717
96972
  const cipher = { name: CIPHER_NAME, nonce: encodeBase64Url(nonce) };
@@ -96905,7 +97160,7 @@ async function exportBackupSource(options) {
96905
97160
  var BackupSnapshotChangedError = class extends Error {
96906
97161
  };
96907
97162
  async function exportBackupSourceAttempt(options, networks) {
96908
- const path = join19(options.store.home, "vault.json");
97163
+ const path = join20(options.store.home, "vault.json");
96909
97164
  const { phrase, file: file2, accounts } = await withVaultLock(path, async () => {
96910
97165
  const [phrase2, vault, file3] = await Promise.all([
96911
97166
  exportVaultPhrase({ path, key: options.vaultKey }),
@@ -97041,16 +97296,16 @@ async function restoreBackupPlaintext(options) {
97041
97296
  } catch {
97042
97297
  throw new BackupError("backup_invalid_input");
97043
97298
  }
97044
- const vaultPath2 = join19(options.home, "vault.json");
97045
- const registryPath = join19(options.home, "wallets.json");
97299
+ const vaultPath2 = join20(options.home, "vault.json");
97300
+ const registryPath = join20(options.home, "wallets.json");
97046
97301
  let stagingHome;
97047
97302
  let beforePublishError;
97048
97303
  let afterPublishError;
97049
97304
  try {
97050
97305
  await mkdir19(options.home, { recursive: true, mode: 448 });
97051
- stagingHome = await mkdtemp(join19(options.home, ".backup-restore-"));
97052
- const stagedVaultPath = join19(stagingHome, "vault.json");
97053
- const stagedRegistryPath = join19(stagingHome, "wallets.json");
97306
+ stagingHome = await mkdtemp(join20(options.home, ".backup-restore-"));
97307
+ const stagedVaultPath = join20(stagingHome, "vault.json");
97308
+ const stagedRegistryPath = join20(stagingHome, "wallets.json");
97054
97309
  await createVault({
97055
97310
  path: stagedVaultPath,
97056
97311
  key: options.vaultKey,
@@ -97109,7 +97364,7 @@ async function restoreBackupPlaintext(options) {
97109
97364
  protected: plaintext.protected,
97110
97365
  networks: [...plaintext.registry.networks]
97111
97366
  };
97112
- const markerPath = join19(options.home, RESTORE_MARKER_FILE);
97367
+ const markerPath = join20(options.home, RESTORE_MARKER_FILE);
97113
97368
  const fingerprint = restoreFingerprint(
97114
97369
  plaintext,
97115
97370
  stagedV2?.restoreDevice ?? options.device,
@@ -97320,13 +97575,13 @@ async function stageV2Restore(options) {
97320
97575
  }
97321
97576
  const agents = [];
97322
97577
  for (const profile of validAgents) {
97323
- const stagedPath = join19(options.stagingHome, "agents", `${profile.name}.json`);
97578
+ const stagedPath = join20(options.stagingHome, "agents", `${profile.name}.json`);
97324
97579
  if (await stageRestoreBytes(stagedPath, prettyJson(profile))) {
97325
97580
  agents.push({
97326
97581
  kind: "agent",
97327
97582
  name: profile.name,
97328
97583
  stagedPath,
97329
- targetPath: join19(options.home, "agents", `${profile.name}.json`)
97584
+ targetPath: join20(options.home, "agents", `${profile.name}.json`)
97330
97585
  });
97331
97586
  } else {
97332
97587
  skipped2.push({ kind: "agent", name: profile.name, reason: "write_failed" });
@@ -97346,13 +97601,13 @@ async function stageV2Restore(options) {
97346
97601
  if (restoreDevice !== void 0) {
97347
97602
  for (const value of validSwarms) {
97348
97603
  const swarm = swarmFileSchema.parse({ ...value, device: restoreDevice });
97349
- const stagedPath = join19(options.stagingHome, "swarms", `${swarm.name}.json`);
97604
+ const stagedPath = join20(options.stagingHome, "swarms", `${swarm.name}.json`);
97350
97605
  if (await stageRestoreBytes(stagedPath, prettyJson(swarm))) {
97351
97606
  swarms.push({
97352
97607
  kind: "swarm",
97353
97608
  name: swarm.name,
97354
97609
  stagedPath,
97355
- targetPath: join19(options.home, "swarms", `${swarm.name}.json`)
97610
+ targetPath: join20(options.home, "swarms", `${swarm.name}.json`)
97356
97611
  });
97357
97612
  } else {
97358
97613
  skipped2.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
@@ -97362,13 +97617,13 @@ async function stageV2Restore(options) {
97362
97617
  const movements = [];
97363
97618
  for (const movement of validMovements) {
97364
97619
  const restored = reconcileRestoredMovement(movement, assumedReceiptKeys);
97365
- const stagedPath = join19(options.stagingHome, "movements", `${restored.id}.json`);
97620
+ const stagedPath = join20(options.stagingHome, "movements", `${restored.id}.json`);
97366
97621
  if (await stageRestoreBytes(stagedPath, serializeMovement(restored))) {
97367
97622
  movements.push({
97368
97623
  kind: "movement",
97369
97624
  name: restored.id,
97370
97625
  stagedPath,
97371
- targetPath: join19(options.home, "movements", `${restored.id}.json`),
97626
+ targetPath: join20(options.home, "movements", `${restored.id}.json`),
97372
97627
  movement: restored
97373
97628
  });
97374
97629
  } else {
@@ -97439,8 +97694,8 @@ async function publishRestoreFile(file2, staged) {
97439
97694
  let identical = false;
97440
97695
  try {
97441
97696
  const [source, target] = await Promise.all([
97442
- readFile23(file2.stagedPath),
97443
- readFile23(file2.targetPath)
97697
+ readFile24(file2.stagedPath),
97698
+ readFile24(file2.targetPath)
97444
97699
  ]);
97445
97700
  identical = source.equals(target);
97446
97701
  } catch {
@@ -97472,7 +97727,7 @@ async function publishRestoreReceiptsLocked(staged, targetPath) {
97472
97727
  let existing = "";
97473
97728
  let existingLines = /* @__PURE__ */ new Set();
97474
97729
  try {
97475
- await readFile23(staged.receiptsPath, "utf8");
97730
+ await readFile24(staged.receiptsPath, "utf8");
97476
97731
  await mkdir19(dirname12(targetPath), { recursive: true, mode: 448 });
97477
97732
  try {
97478
97733
  const journal = await readRestoreReceiptJournal(targetPath);
@@ -97527,7 +97782,7 @@ async function reconcilePublishedMovements(staged, home, requireDurableSafety =
97527
97782
  const unjournaledKeys = new Set([...signedKeys].filter((key2) => !journaledKeys.has(key2)));
97528
97783
  let files;
97529
97784
  try {
97530
- files = await readdir8(join19(home, "movements"));
97785
+ files = await readdir8(join20(home, "movements"));
97531
97786
  } catch (error61) {
97532
97787
  if (isMissingFile4(error61)) return;
97533
97788
  if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
@@ -97628,9 +97883,9 @@ function assertRelayKey(value) {
97628
97883
  throw new BackupError("relay_invalid_key");
97629
97884
  }
97630
97885
  }
97631
- function readRelayRandomBytes(randomBytes17, length) {
97886
+ function readRelayRandomBytes(randomBytes18, length) {
97632
97887
  try {
97633
- const value = randomBytes17(length);
97888
+ const value = randomBytes18(length);
97634
97889
  if (!(value instanceof Uint8Array) || value.byteLength !== length) throw new Error();
97635
97890
  return Buffer.from(value);
97636
97891
  } catch {
@@ -97748,7 +98003,7 @@ async function createRestoreMarker(vaultPath2, registryPath, fingerprint, vaultK
97748
98003
  }
97749
98004
  async function readRestoreMarker(path, fingerprint, vaultKey) {
97750
98005
  try {
97751
- const marker = restoreMarkerSchema.parse(JSON.parse(await readFile23(path, "utf8")));
98006
+ const marker = restoreMarkerSchema.parse(JSON.parse(await readFile24(path, "utf8")));
97752
98007
  const expectedMac = restoreMarkerMac(marker, vaultKey);
97753
98008
  if (marker.fingerprint !== fingerprint || !timingSafeEqual(Buffer.from(marker.mac, "hex"), Buffer.from(expectedMac, "hex"))) {
97754
98009
  throw new Error();
@@ -97765,7 +98020,7 @@ function restoreMarkerMac(marker, vaultKey) {
97765
98020
  ).digest("hex");
97766
98021
  }
97767
98022
  async function sha256File(path) {
97768
- return createHash6("sha256").update(await readFile23(path)).digest("hex");
98023
+ return createHash6("sha256").update(await readFile24(path)).digest("hex");
97769
98024
  }
97770
98025
  async function notifyRestorePublish(hook, step2, rememberError) {
97771
98026
  try {
@@ -98067,7 +98322,7 @@ function copyTransferReceipt(receipt) {
98067
98322
  async function readReceiptJournal(path) {
98068
98323
  let raw;
98069
98324
  try {
98070
- raw = await readFile23(path, "utf8");
98325
+ raw = await readFile24(path, "utf8");
98071
98326
  } catch (error61) {
98072
98327
  if (isMissingFile4(error61)) return [];
98073
98328
  throw error61;
@@ -98077,7 +98332,7 @@ async function readReceiptJournal(path) {
98077
98332
  async function readRestoreReceiptJournal(path) {
98078
98333
  let raw;
98079
98334
  try {
98080
- raw = await readFile23(path, "utf8");
98335
+ raw = await readFile24(path, "utf8");
98081
98336
  } catch (error61) {
98082
98337
  if (isMissingFile4(error61)) return { raw: "", lines: /* @__PURE__ */ new Set(), signedKeys: /* @__PURE__ */ new Set() };
98083
98338
  throw error61;
@@ -98196,8 +98451,8 @@ function assertOwnerKey(ownerKey) {
98196
98451
  assertBytes(ownerKey.key, 32);
98197
98452
  assertBytes(ownerKey.salt, 32);
98198
98453
  }
98199
- function readRandomBytes(randomBytes17, length) {
98200
- const value = randomBytes17(length);
98454
+ function readRandomBytes(randomBytes18, length) {
98455
+ const value = randomBytes18(length);
98201
98456
  if (!(value instanceof Uint8Array) || value.byteLength !== length) {
98202
98457
  throw new BackupError("backup_invalid_input");
98203
98458
  }
@@ -98436,7 +98691,7 @@ async function uploadBackupLocked(options, signal) {
98436
98691
  try {
98437
98692
  let vaultFile;
98438
98693
  try {
98439
- vaultFile = await readVaultFileUnlocked(join20(options.store.home, "vault.json"));
98694
+ vaultFile = await readVaultFileUnlocked(join21(options.store.home, "vault.json"));
98440
98695
  } catch (error61) {
98441
98696
  if (error61 instanceof VaultError && error61.code === "not_found") {
98442
98697
  return { status: "skipped", reason: "no_vault" };
@@ -98445,7 +98700,7 @@ async function uploadBackupLocked(options, signal) {
98445
98700
  }
98446
98701
  try {
98447
98702
  vaultKey = vaultFile.protected ? await unlockProtectedVault({
98448
- path: join20(options.store.home, "vault.json"),
98703
+ path: join21(options.store.home, "vault.json"),
98449
98704
  secrets: options.secrets,
98450
98705
  env: options.env,
98451
98706
  ...options.now === void 0 ? {} : { now: options.now }
@@ -99118,7 +99373,7 @@ async function readProcessStdin() {
99118
99373
  }
99119
99374
 
99120
99375
  // src/version.ts
99121
- var CLI_VERSION = "0.12.0";
99376
+ var CLI_VERSION = "0.13.0";
99122
99377
 
99123
99378
  // src/status.ts
99124
99379
  async function statusCommand(argv, json2, io, dependencies) {
@@ -99285,7 +99540,7 @@ function withDeadlineSignal3(fetchImpl, deadline) {
99285
99540
  }
99286
99541
  async function statusConfig(path) {
99287
99542
  try {
99288
- await stat13(path);
99543
+ await stat15(path);
99289
99544
  } catch (error61) {
99290
99545
  if (isMissingFile(error61)) return getDefaultConfig(process.env);
99291
99546
  throw error61;
@@ -99483,7 +99738,7 @@ async function siblingsFetchImpl(dependencies) {
99483
99738
  const configPath = getVapiPaths().config;
99484
99739
  let config2;
99485
99740
  try {
99486
- await stat14(configPath);
99741
+ await stat16(configPath);
99487
99742
  config2 = await loadConfig(configPath, process.env);
99488
99743
  } catch (error61) {
99489
99744
  if (!isMissingFile(error61)) throw error61;
@@ -99572,7 +99827,7 @@ ${IMPORT_USAGE}`);
99572
99827
  const passphrase = await secretPrompt(dependencies)(`Passphrase for ${keystorePath}: `);
99573
99828
  privateKey = (await exportKeystoreKeys(passphrase, keystorePath)).evm.privateKey;
99574
99829
  } else if (keyPath !== void 0) {
99575
- privateKey = (await readFile24(keyPath, "utf8")).trim();
99830
+ privateKey = (await readFile25(keyPath, "utf8")).trim();
99576
99831
  } else {
99577
99832
  privateKey = await secretPrompt(dependencies)("Private key: ");
99578
99833
  }
@@ -99620,10 +99875,10 @@ async function accountsRenameCommand(argv, json2, io, dependencies) {
99620
99875
  {
99621
99876
  previous: from16,
99622
99877
  ...address4 === void 0 ? {} : { address: address4 },
99623
- vault: join21(store.home, "vault.json"),
99878
+ vault: join22(store.home, "vault.json"),
99624
99879
  message: `Wallet ${from16} is now ${renamed.name}.`
99625
99880
  },
99626
- [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join21(store.home, "vault.json")}`].join(
99881
+ [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join22(store.home, "vault.json")}`].join(
99627
99882
  "\n"
99628
99883
  )
99629
99884
  );
@@ -99732,13 +99987,13 @@ async function accountsRestoreCommand(argv, json2, io, dependencies) {
99732
99987
  { name: restored.name, ...address4 === void 0 ? {} : { address: address4 } },
99733
99988
  {
99734
99989
  ...address4 === void 0 ? {} : { address: address4 },
99735
- vault: join21(store.home, "vault.json"),
99990
+ vault: join22(store.home, "vault.json"),
99736
99991
  spendCaps: restored.entry.spendCaps,
99737
99992
  message: `Wallet ${restored.name} restored to the device vault.`
99738
99993
  },
99739
99994
  [
99740
99995
  `Wallet ${restored.name} restored to the device vault.`,
99741
- `Vault: ${join21(store.home, "vault.json")}`
99996
+ `Vault: ${join22(store.home, "vault.json")}`
99742
99997
  ].join("\n")
99743
99998
  );
99744
99999
  }
@@ -100068,7 +100323,7 @@ function formatNetworkAccounts(accounts) {
100068
100323
  }
100069
100324
 
100070
100325
  // src/cloud-backup.ts
100071
- import { join as join22 } from "node:path";
100326
+ import { join as join23 } from "node:path";
100072
100327
  var CLOUD_BACKUP_USAGE = "Usage: vapi backup --cloud [off] [--json]";
100073
100328
  var OWNER_RESTORE_USAGE = "Usage: vapi restore --from-owner [--owner <0x\u2026>] [--json]";
100074
100329
  var OWNER_PATTERN2 = /^0x[0-9a-fA-F]{40}$/u;
@@ -100091,7 +100346,7 @@ async function cloudBackupCommand(argv, json2, io, dependencies) {
100091
100346
  }
100092
100347
  async function enrollCloudBackup(json2, io, dependencies) {
100093
100348
  const paths = getVapiPaths();
100094
- if (!await fileExists2(join22(paths.directory, "vault.json"))) {
100349
+ if (!await fileExists3(join23(paths.directory, "vault.json"))) {
100095
100350
  throw new Error("No vault on this device. Run vapi setup first.");
100096
100351
  }
100097
100352
  const context = await cloudContext(io, dependencies);
@@ -100203,7 +100458,7 @@ async function restoreFromOwnerCommand(argv, json2, io, dependencies) {
100203
100458
  }
100204
100459
  const expectedOwner = ownerValue?.toLowerCase();
100205
100460
  const paths = getVapiPaths();
100206
- if (await fileExists2(join22(paths.directory, "vault.json")) && !await fileExists2(join22(paths.directory, ".backup-restore.json"))) {
100461
+ if (await fileExists3(join23(paths.directory, "vault.json")) && !await fileExists3(join23(paths.directory, ".backup-restore.json"))) {
100207
100462
  throw new Error(
100208
100463
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
100209
100464
  );
@@ -100259,7 +100514,7 @@ async function restoreFromOwnerCommand(argv, json2, io, dependencies) {
100259
100514
  env: getEnvironment(dependencies),
100260
100515
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
100261
100516
  });
100262
- if (!await fileExists2(paths.config)) {
100517
+ if (!await fileExists3(paths.config)) {
100263
100518
  const networks = restored.networks.length === 0 ? ["base"] : restored.networks;
100264
100519
  await writeDefaultConfig(paths.config, getEnvironment(dependencies), { networks });
100265
100520
  }
@@ -101300,20 +101555,20 @@ function shortExcerpt(value) {
101300
101555
  }
101301
101556
 
101302
101557
  // src/agent.ts
101303
- import { readFile as readFile26, stat as stat15 } from "node:fs/promises";
101304
- import { join as join25 } from "node:path";
101558
+ import { readFile as readFile27, stat as stat17 } from "node:fs/promises";
101559
+ import { join as join26 } from "node:path";
101305
101560
  import { createInterface as createInterface2 } from "node:readline/promises";
101306
101561
 
101307
101562
  // src/headless.ts
101308
101563
  import { chmod as chmod7, mkdtemp as mkdtemp2, rm as rm4, writeFile as writeFile10 } from "node:fs/promises";
101309
101564
  import { rmSync } from "node:fs";
101310
101565
  import { tmpdir as osTmpdir } from "node:os";
101311
- import { join as join23 } from "node:path";
101566
+ import { join as join24 } from "node:path";
101312
101567
  var BUNDLE_VARIABLE_PATTERN = /^[A-Z_][A-Z0-9_]*$/u;
101313
101568
  var REMOTE_BLOCKED_GRANTS2 = /* @__PURE__ */ new Set(["delegate", "allocate"]);
101314
101569
  var agentProfileOptions = { schema: registeredAgentProfileSchema };
101315
101570
  async function createHeadlessHome(bundle, options = {}) {
101316
- const home = await mkdtemp2(join23(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
101571
+ const home = await mkdtemp2(join24(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
101317
101572
  const cleanup = async () => {
101318
101573
  await rm4(home, { recursive: true, force: true });
101319
101574
  };
@@ -101513,18 +101768,18 @@ import { readFile as nodeReadFile } from "node:fs/promises";
101513
101768
 
101514
101769
  // src/runtime-railway.ts
101515
101770
  import { spawn as spawn2 } from "node:child_process";
101516
- import { randomBytes as randomBytes16 } from "node:crypto";
101771
+ import { randomBytes as randomBytes17 } from "node:crypto";
101517
101772
  import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync as rmSync2, writeSync } from "node:fs";
101518
101773
  import {
101519
101774
  mkdtemp as nodeMkdtemp,
101520
101775
  readdir as readdir9,
101521
- readFile as readFile25,
101776
+ readFile as readFile26,
101522
101777
  rm as nodeRm,
101523
101778
  stat as nodeStat,
101524
101779
  writeFile as nodeWriteFile
101525
101780
  } from "node:fs/promises";
101526
101781
  import { tmpdir as osTmpdir2 } from "node:os";
101527
- import { basename as basename4, dirname as dirname13, join as join24 } from "node:path";
101782
+ import { basename as basename4, dirname as dirname13, join as join25 } from "node:path";
101528
101783
  var RAILWAY_CLI = {
101529
101784
  binary: "railway",
101530
101785
  create: (options) => [
@@ -101696,7 +101951,7 @@ async function assertRemoteSafeMember(args) {
101696
101951
  }
101697
101952
  function railwaySidecarPath(home, runId) {
101698
101953
  if (!isRunId(runId)) throw new RuntimeError("invalid_run_id", `Invalid run id: ${runId}.`);
101699
- return join24(runsDirectory(home), `${runId}.railway.json`);
101954
+ return join25(runsDirectory(home), `${runId}.railway.json`);
101700
101955
  }
101701
101956
  function createRailwayRuntime(options) {
101702
101957
  const { home } = options;
@@ -102021,10 +102276,10 @@ function createRailwayRuntime(options) {
102021
102276
  let createError;
102022
102277
  let cleanupError;
102023
102278
  try {
102024
- directory = await fs.mkdtemp(join24(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
102279
+ directory = await fs.mkdtemp(join25(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
102025
102280
  assertNotInterrupted();
102026
102281
  await assertMode(fs, directory, 448, "env-file directory");
102027
- envFile = join24(directory, "member.env");
102282
+ envFile = join25(directory, "member.env");
102028
102283
  await fs.writeFile(envFile, `${RAILWAY_CLI.bundleVariable}=${bundle}
102029
102284
  `, {
102030
102285
  encoding: "utf8",
@@ -102479,9 +102734,9 @@ async function writeSidecar(home, runId, sidecar) {
102479
102734
  function writeSidecarSync(path, sidecar) {
102480
102735
  const directory = dirname13(path);
102481
102736
  mkdirSync(directory, { recursive: true, mode: 448 });
102482
- const temporary = join24(
102737
+ const temporary = join25(
102483
102738
  directory,
102484
- `.${basename4(path)}.${process.pid}.${randomBytes16(6).toString("hex")}.tmp`
102739
+ `.${basename4(path)}.${process.pid}.${randomBytes17(6).toString("hex")}.tmp`
102485
102740
  );
102486
102741
  try {
102487
102742
  const descriptor2 = openSync(temporary, "wx", 384);
@@ -102519,7 +102774,7 @@ var LEGACY_SIDECAR_KEYS = ["checkpoint", "keepSandbox", "sandboxId", "v"];
102519
102774
  async function readSidecar(home, runId) {
102520
102775
  let parsed;
102521
102776
  try {
102522
- parsed = JSON.parse(await readFile25(railwaySidecarPath(home, runId), "utf8"));
102777
+ parsed = JSON.parse(await readFile26(railwaySidecarPath(home, runId), "utf8"));
102523
102778
  } catch {
102524
102779
  return void 0;
102525
102780
  }
@@ -102577,7 +102832,7 @@ async function assertMode(fs, path, mode, what) {
102577
102832
  }
102578
102833
  }
102579
102834
  async function deviceVaultKey(home, secrets, now) {
102580
- const path = join24(home, "vault.json");
102835
+ const path = join25(home, "vault.json");
102581
102836
  const metadata = await readVaultFileUnlocked(path);
102582
102837
  const key2 = metadata.protected ? await unlockProtectedVault({
102583
102838
  path,
@@ -102632,7 +102887,7 @@ function createLocalRuntime(options) {
102632
102887
  const processCommand = options.processCommand ?? defaultProcessCommand;
102633
102888
  const ownsProcess = (handle, pid) => processCommand(pid)?.includes(runResultPath(home, handle.runId)) === true;
102634
102889
  const closeFd = options.closeFd ?? closeSync2;
102635
- const readFile32 = options.readFile ?? nodeReadFile;
102890
+ const readFile33 = options.readFile ?? nodeReadFile;
102636
102891
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
102637
102892
  const openLog = options.openLog ?? ((path) => {
102638
102893
  mkdirSync2(runsDirectory(home), { recursive: true, mode: 448 });
@@ -102687,7 +102942,7 @@ function createLocalRuntime(options) {
102687
102942
  return handle;
102688
102943
  },
102689
102944
  async status(handle) {
102690
- const result = await readResultFile(readFile32, runResultPath(home, handle.runId));
102945
+ const result = await readResultFile(readFile33, runResultPath(home, handle.runId));
102691
102946
  if (result !== void 0) return result;
102692
102947
  const pid = localPid(handle);
102693
102948
  if (pid === void 0 || handle.kind !== "local") {
@@ -102790,10 +103045,10 @@ function childArguments(member, run) {
102790
103045
  ...run.drawUsd ? ["--draw", run.drawUsd] : []
102791
103046
  ];
102792
103047
  }
102793
- async function readResultFile(readFile32, path) {
103048
+ async function readResultFile(readFile33, path) {
102794
103049
  let text;
102795
103050
  try {
102796
- text = await readFile32(path, "utf8");
103051
+ text = await readFile33(path, "utf8");
102797
103052
  } catch (error61) {
102798
103053
  if (hasCode3(error61, "ENOENT")) return void 0;
102799
103054
  return { state: "failed", detail: "unreadable result file" };
@@ -102918,7 +103173,7 @@ async function createCommand(argv, json2, io, dependencies) {
102918
103173
  if (await profileFileExists(paths.agentsDir, name)) {
102919
103174
  throw new Error(`Agent ${name} already exists.`);
102920
103175
  }
102921
- const instructions = await readFile26(instructionsPath, "utf8");
103176
+ const instructions = await readFile27(instructionsPath, "utf8");
102922
103177
  if (instructions.length > 2e4) {
102923
103178
  throw new UsageError("--instructions must contain at most 20000 characters.");
102924
103179
  }
@@ -103504,7 +103759,7 @@ function explicitWallet(name) {
103504
103759
  }
103505
103760
  async function profileFileExists(directory, name) {
103506
103761
  try {
103507
- await stat15(join25(directory, `${name}.json`));
103762
+ await stat17(join26(directory, `${name}.json`));
103508
103763
  return true;
103509
103764
  } catch (error61) {
103510
103765
  if (isMissingFile(error61)) return false;
@@ -103565,7 +103820,7 @@ function usd(value, minimumDecimals = 0) {
103565
103820
 
103566
103821
  // src/mcp-install.ts
103567
103822
  import { spawn as spawn3 } from "node:child_process";
103568
- import { mkdir as mkdir20, readFile as readFile27, writeFile as writeFile11 } from "node:fs/promises";
103823
+ import { mkdir as mkdir20, readFile as readFile28, writeFile as writeFile11 } from "node:fs/promises";
103569
103824
  import { homedir as systemHomedir } from "node:os";
103570
103825
  import { dirname as dirname14, posix, win32 as win322 } from "node:path";
103571
103826
 
@@ -103945,7 +104200,7 @@ function isRecord12(value) {
103945
104200
  }
103946
104201
  async function readExistingFile(path) {
103947
104202
  try {
103948
- return await readFile27(path, "utf8");
104203
+ return await readFile28(path, "utf8");
103949
104204
  } catch (error61) {
103950
104205
  if (isMissingFile(error61)) return void 0;
103951
104206
  throw error61;
@@ -103953,7 +104208,7 @@ async function readExistingFile(path) {
103953
104208
  }
103954
104209
  async function pathExists5(path) {
103955
104210
  try {
103956
- await readFile27(path);
104211
+ await readFile28(path);
103957
104212
  return true;
103958
104213
  } catch (error61) {
103959
104214
  if (isMissingFile(error61)) return false;
@@ -103963,15 +104218,15 @@ async function pathExists5(path) {
103963
104218
 
103964
104219
  // src/code.ts
103965
104220
  import { constants as constants2 } from "node:fs";
103966
- import { access, mkdir as mkdir21, readFile as readFile28, realpath, unlink as unlink13, writeFile as writeFile12 } from "node:fs/promises";
104221
+ import { access, mkdir as mkdir21, readFile as readFile29, realpath, unlink as unlink13, writeFile as writeFile12 } from "node:fs/promises";
103967
104222
  import { homedir as homedir3 } from "node:os";
103968
- import { basename as basename5, dirname as dirname15, join as join26, posix as posix2, win32 as win323 } from "node:path";
104223
+ import { basename as basename5, dirname as dirname15, join as join27, posix as posix2, win32 as win323 } from "node:path";
103969
104224
  var VAPI_CODEX_PROVIDER = "vapi";
103970
104225
  var VAPI_CODEX_PROFILE = "vapi";
103971
104226
  var VAPI_CODEX_DEFAULT_MODEL = "venice/openai-gpt-61-sol";
103972
104227
  var VAPI_ROUTER_KEY_ENV = "VAPI_ROUTER_KEY";
103973
104228
  function codexConfigPath(env, home) {
103974
- return join26(env.CODEX_HOME || join26(home, ".codex"), "config.toml");
104229
+ return join27(env.CODEX_HOME || join27(home, ".codex"), "config.toml");
103975
104230
  }
103976
104231
  function hasVapiCodexProfile(contents) {
103977
104232
  const roots = new Set(
@@ -104065,7 +104320,7 @@ function aliasContents(original, tools) {
104065
104320
  }
104066
104321
  async function readOptional(path) {
104067
104322
  try {
104068
- return await readFile28(path, "utf8");
104323
+ return await readFile29(path, "utf8");
104069
104324
  } catch (error61) {
104070
104325
  if (isMissingFile(error61)) return void 0;
104071
104326
  throw error61;
@@ -104087,7 +104342,7 @@ async function codeCommand(argv, json2, io, dependencies) {
104087
104342
  const env = getEnvironment(dependencies);
104088
104343
  const home = dependencies.code?.homedir ?? homedir3();
104089
104344
  const config2 = codexConfigPath(env, home);
104090
- const rcPaths = [join26(home, ".zshrc"), join26(home, ".bashrc")];
104345
+ const rcPaths = [join27(home, ".zshrc"), join27(home, ".bashrc")];
104091
104346
  if (command === "uninstall") {
104092
104347
  const removed = [];
104093
104348
  const previous = await readOptional(config2);
@@ -104211,7 +104466,7 @@ async function codeCommand(argv, json2, io, dependencies) {
104211
104466
 
104212
104467
  // src/code-launch.ts
104213
104468
  import { spawn as spawn4 } from "node:child_process";
104214
- import { readFile as readFile29 } from "node:fs/promises";
104469
+ import { readFile as readFile30 } from "node:fs/promises";
104215
104470
  import { constants as constants3, homedir as homedir4 } from "node:os";
104216
104471
  var CLAUDE_MODELS = {
104217
104472
  sonnet: "venice/claude-sonnet-5-5",
@@ -104425,7 +104680,7 @@ function claudeModel(model) {
104425
104680
  async function codexArgs(env, baseURL, model, dependencies) {
104426
104681
  let contents = "";
104427
104682
  try {
104428
- contents = await readFile29(
104683
+ contents = await readFile30(
104429
104684
  codexConfigPath(env, dependencies.code?.homedir ?? homedir4()),
104430
104685
  "utf8"
104431
104686
  );
@@ -104600,7 +104855,7 @@ async function sendConfig(dependencies) {
104600
104855
 
104601
104856
  // src/setup.ts
104602
104857
  import { rm as rm5 } from "node:fs/promises";
104603
- import { join as join27 } from "node:path";
104858
+ import { join as join28 } from "node:path";
104604
104859
  var SETUP_ARGUMENT_ERROR = `vapi setup accepts only --no-cloud-backup and --accounts <n> (1-${MAX_RESTORE_ACCOUNTS}); a recovery phrase is typed at the prompt, never passed on the command line.`;
104605
104860
  var VAULT_CHOICE = "Create a new vault, or restore one from a recovery phrase? [new/restore] ";
104606
104861
  async function setupCommand(argv, json2, io, dependencies) {
@@ -104619,18 +104874,24 @@ async function setupCommand(argv, json2, io, dependencies) {
104619
104874
  const steps = [];
104620
104875
  const humanIo = json2 ? stderrIo(io) : io;
104621
104876
  const accountCount = parseAccountCount(parsed.one("--accounts"));
104622
- if (!await fileExists2(paths.config)) {
104877
+ if (!await fileExists3(paths.config)) {
104623
104878
  await writeDefaultConfig(paths.config, process.env, { networks: ["base"] });
104624
104879
  steps.push("config");
104625
104880
  }
104626
104881
  const config2 = await readConfig(paths.config, humanIo);
104882
+ if (!await fileExists3(join28(paths.directory, "vault.json"))) {
104883
+ const os = dependencies.secretBackendProbe ?? (dependencies.secretStore === void 0 ? osSecretStore() : void 0);
104884
+ if (os !== void 0) {
104885
+ await chooseSecretBackend({ home: paths.directory, os, env: getEnvironment(dependencies) });
104886
+ }
104887
+ }
104627
104888
  let store = await openWalletStore(dependencies);
104628
104889
  let vault = "existing";
104629
104890
  let changedVault = false;
104630
104891
  let changedAccount = false;
104631
104892
  let changedLink = false;
104632
104893
  let scannedAddresses;
104633
- if (!await fileExists2(join27(paths.directory, "vault.json"))) {
104894
+ if (!await fileExists3(join28(paths.directory, "vault.json"))) {
104634
104895
  const choice = await vaultChoice(dependencies);
104635
104896
  if (choice === "restore") {
104636
104897
  if (!isInteractive(dependencies)) {
@@ -104718,7 +104979,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
104718
104979
  let scannedAddresses = 0;
104719
104980
  try {
104720
104981
  const restored = await restoreVault({
104721
- path: join27(paths.directory, "vault.json"),
104982
+ path: join28(paths.directory, "vault.json"),
104722
104983
  key: key2,
104723
104984
  phrase: validatedPhrase,
104724
104985
  probe: async (address4) => await readBalance3(address4) > 0n,
@@ -104729,7 +104990,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
104729
104990
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
104730
104991
  });
104731
104992
  names = restored.accounts().map((account) => account.name);
104732
- await rm5(join27(paths.directory, "wallets.json"), { force: true });
104993
+ await rm5(join28(paths.directory, "wallets.json"), { force: true });
104733
104994
  } finally {
104734
104995
  key2.fill(0);
104735
104996
  }
@@ -104847,7 +105108,7 @@ async function withRouterError2(operation) {
104847
105108
 
104848
105109
  // src/task.ts
104849
105110
  import { randomUUID as randomUUID6 } from "node:crypto";
104850
- import { readFile as readFile30 } from "node:fs/promises";
105111
+ import { readFile as readFile31 } from "node:fs/promises";
104851
105112
  var TASK_HELP = `Usage:
104852
105113
  vapi task search [--open] [--min <usd>] [--tab trending|new|closing|paid] [--limit <n>] [--json]
104853
105114
  vapi task show <id> [--account <name>] [--json]
@@ -105183,7 +105444,7 @@ async function taskCommandInner(argv, json2, io, dependencies) {
105183
105444
  if (maxAwards !== void 0 && maxAwards > TASK_LIMITS.maxAwardsMax)
105184
105445
  throw new UsageError("--max-awards must be between 1 and 50.");
105185
105446
  if (parsed.one("--webhook") !== void 0) httpsUrl2(parsed.one("--webhook"), "--webhook");
105186
- const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile30(briefPath, "utf8");
105447
+ const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile31(briefPath, "utf8");
105187
105448
  const input2 = {
105188
105449
  title: title.trim(),
105189
105450
  description: brief.trim(),
@@ -106861,7 +107122,7 @@ async function referencedSleep(milliseconds, signal) {
106861
107122
  }
106862
107123
 
106863
107124
  // src/vault.ts
106864
- import { join as join28 } from "node:path";
107125
+ import { join as join29 } from "node:path";
106865
107126
  var VAULT_USAGE = "Usage: vapi vault protect|unprotect|lock|unlock|status [--json]";
106866
107127
  var RESTORE_USAGE = "Usage: vapi restore [--accounts <n> | --from-owner [--owner <0x\u2026>]] [--json]";
106867
107128
  var LEGACY_PASSWORD_NOTICE = "VAPI_KEYSTORE_PASSWORD is deprecated for vault passwords; use VAPI_VAULT_PASSWORD instead.";
@@ -106905,13 +107166,13 @@ async function restoreCommand(argv, json2, io, dependencies) {
106905
107166
  }
106906
107167
  const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
106907
107168
  const paths = getVapiPaths();
106908
- const path = join28(paths.directory, "vault.json");
106909
- if (await fileExists2(path)) {
107169
+ const path = join29(paths.directory, "vault.json");
107170
+ if (await fileExists3(path)) {
106910
107171
  throw new Error(
106911
107172
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
106912
107173
  );
106913
107174
  }
106914
- if (!await fileExists2(paths.config)) {
107175
+ if (!await fileExists3(paths.config)) {
106915
107176
  await writeDefaultConfig(paths.config, process.env, { networks: ["base"] });
106916
107177
  }
106917
107178
  const config2 = await readConfig(paths.config, json2 ? quietIo(io) : io);
@@ -107062,7 +107323,7 @@ function requireNoArguments(argv) {
107062
107323
  parseArguments(argv, { valueOptions: /* @__PURE__ */ new Set(), maximumPositionals: 0 });
107063
107324
  }
107064
107325
  function vaultPath() {
107065
- return join28(getVapiPaths().directory, "vault.json");
107326
+ return join29(getVapiPaths().directory, "vault.json");
107066
107327
  }
107067
107328
  function quietIo(io) {
107068
107329
  return { stdout: () => void 0, stderr: io.stderr };
@@ -107513,7 +107774,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
107513
107774
  break;
107514
107775
  case "unlock":
107515
107776
  io.stderr("vapi unlock is now vapi vault unlock; the old name works for one release.");
107516
- if (await fileExists2(join29(getVapiPaths().directory, "vault.json"))) {
107777
+ if (await fileExists3(join30(getVapiPaths().directory, "vault.json"))) {
107517
107778
  parseArguments(args.slice(1), {
107518
107779
  valueOptions: /* @__PURE__ */ new Set([WALLET_OPTION5]),
107519
107780
  maximumPositionals: 0
@@ -107701,7 +107962,7 @@ async function initCommand(argv, json2, io, dependencies) {
107701
107962
  await recordAudit(dependencies, "wallet.create", { wallet: created.name });
107702
107963
  const account = created.account;
107703
107964
  if (!json2) await showRecoveryPhrase(created.recoveryPhrase, io, dependencies);
107704
- if (!await fileExists2(paths.config)) {
107965
+ if (!await fileExists3(paths.config)) {
107705
107966
  await writeDefaultConfig(paths.config, process.env, { networks });
107706
107967
  } else {
107707
107968
  if (enableArc) await enableDefaultNetwork("arc", paths.config);
@@ -107719,7 +107980,7 @@ async function initCommand(argv, json2, io, dependencies) {
107719
107980
  address: account.address,
107720
107981
  accounts,
107721
107982
  config: paths.config,
107722
- vault: join29(paths.directory, "vault.json"),
107983
+ vault: join30(paths.directory, "vault.json"),
107723
107984
  ...configRewrites.length > 0 ? { configRewrites } : {},
107724
107985
  custody: "self",
107725
107986
  warning: CUSTODY_NOTICE,
@@ -107849,7 +108110,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
107849
108110
  await recordAudit(dependencies, "wallet.create", { wallet: created.name });
107850
108111
  const account = created.account;
107851
108112
  if (!json2) await showRecoveryPhrase(created.recoveryPhrase, io, dependencies);
107852
- if (!await fileExists2(paths.config)) {
108113
+ if (!await fileExists3(paths.config)) {
107853
108114
  await writeDefaultConfig(paths.config, process.env, { networks });
107854
108115
  } else {
107855
108116
  if (enableArc) await enableDefaultNetwork("arc", paths.config);
@@ -107858,7 +108119,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
107858
108119
  const result = {
107859
108120
  address: account.address,
107860
108121
  ...account.solana ? { solanaAddress: account.solana.address } : {},
107861
- vault: join29(paths.directory, "vault.json"),
108122
+ vault: join30(paths.directory, "vault.json"),
107862
108123
  ...label === void 0 ? {} : { label },
107863
108124
  spendCaps: created.entry.spendCaps,
107864
108125
  isDefault,
@@ -107898,7 +108159,7 @@ function formatCaps2(caps) {
107898
108159
  function walletListResult(store, wallets, unlocked) {
107899
108160
  return {
107900
108161
  default: store.defaultName ?? null,
107901
- vault: join29(store.home, "vault.json"),
108162
+ vault: join30(store.home, "vault.json"),
107902
108163
  wallets: wallets.map((wallet) => ({
107903
108164
  name: wallet.name,
107904
108165
  ...wallet.address === void 0 ? {} : { address: wallet.address },
@@ -108914,7 +109175,7 @@ function sameOrigin2(left, right) {
108914
109175
  function noApiKeyMessage(baseUrl) {
108915
109176
  return [
108916
109177
  "No vAPI API key on this machine.",
108917
- `Create one in the console at ${listingsUrl(baseUrl, API_KEY_CONSOLE_PATH).href}, then store it with vapi auth set-key.`,
109178
+ `Create one in the console at ${apiKeyConsoleUrl(baseUrl).href}, then store it with vapi auth set-key.`,
108918
109179
  `In CI, set ${API_KEY_ENV} instead.`
108919
109180
  ].join("\n");
108920
109181
  }
@@ -109171,7 +109432,7 @@ function formatClaimed(origin, claimed) {
109171
109432
  }
109172
109433
  var EXPORT_KEY_WARNING = "Anyone with this key can spend the wallet. Never paste it into a website or chat.";
109173
109434
  async function deviceVaultKey2(store, dependencies) {
109174
- const path = join29(store.home, "vault.json");
109435
+ const path = join30(store.home, "vault.json");
109175
109436
  const metadata = await readVaultFileUnlocked(path);
109176
109437
  const secrets = getSecretStore(dependencies);
109177
109438
  const key2 = metadata.protected ? await unlockProtectedVault({
@@ -109264,7 +109525,7 @@ async function backupCommand(argv, json2, io, dependencies) {
109264
109525
  const target = await targetWallet(parsed, dependencies);
109265
109526
  const vaultAccount = await target.store.hasVaultAccount(target.name);
109266
109527
  if (vaultAccount) {
109267
- const vault = await readVaultFileUnlocked(join29(target.store.home, "vault.json"));
109528
+ const vault = await readVaultFileUnlocked(join30(target.store.home, "vault.json"));
109268
109529
  if (vault.accounts.some((account) => account.name === target.name && account.kind === "imported")) {
109269
109530
  throw new KeystoreError(
109270
109531
  `Account ${target.name} was imported and is not recoverable from the vault phrase. Back it up with vapi export-key --account ${target.name}.`
@@ -109341,7 +109602,7 @@ async function importCommand(argv, json2, io, dependencies) {
109341
109602
  const existed = store.has(name);
109342
109603
  if (existed && !parsed.has("--replace")) {
109343
109604
  const address4 = await store.readAddress(name);
109344
- const location = await store.hasVaultAccount(name) ? join29(store.home, "vault.json") : store.pathFor(name);
109605
+ const location = await store.hasVaultAccount(name) ? join30(store.home, "vault.json") : store.pathFor(name);
109345
109606
  throw new Error(
109346
109607
  [
109347
109608
  `Wallet ${name} already exists at ${location}.`,
@@ -109369,7 +109630,7 @@ async function importCommand(argv, json2, io, dependencies) {
109369
109630
  const imported = fromPhrase ? await store.create(name, "", { phrase: secret }) : await store.importKey(name, "", secret);
109370
109631
  await recordAudit(dependencies, "wallet.import", { wallet: imported.name });
109371
109632
  const account = imported.account;
109372
- if (!await fileExists2(paths.config)) {
109633
+ if (!await fileExists3(paths.config)) {
109373
109634
  await writeDefaultConfig(paths.config, process.env, { networks });
109374
109635
  } else {
109375
109636
  if (enableArc) await enableDefaultNetwork("arc", paths.config);
@@ -109377,7 +109638,7 @@ async function importCommand(argv, json2, io, dependencies) {
109377
109638
  const result = {
109378
109639
  address: account.address,
109379
109640
  ...account.solana ? { solanaAddress: account.solana.address } : {},
109380
- vault: join29(paths.directory, "vault.json"),
109641
+ vault: join30(paths.directory, "vault.json"),
109381
109642
  ...previousKeystore ? { previousKeystore } : {},
109382
109643
  message: "Wallet imported. Its encrypted key stays on this machine."
109383
109644
  };
@@ -109985,9 +110246,9 @@ function isHttpUrl(value) {
109985
110246
  return false;
109986
110247
  }
109987
110248
  }
109988
- async function fileExists2(path) {
110249
+ async function fileExists3(path) {
109989
110250
  try {
109990
- await stat16(path);
110251
+ await stat18(path);
109991
110252
  return true;
109992
110253
  } catch (error61) {
109993
110254
  if (isMissingFile(error61)) return false;
@@ -110009,7 +110270,7 @@ function parseInitNetworks(value) {
110009
110270
 
110010
110271
  // src/update-check.ts
110011
110272
  import { lookup } from "node:dns/promises";
110012
- import { mkdir as mkdir22, readFile as readFile31, writeFile as writeFile13 } from "node:fs/promises";
110273
+ import { mkdir as mkdir22, readFile as readFile32, writeFile as writeFile13 } from "node:fs/promises";
110013
110274
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
110014
110275
  var CHECK_TIMEOUT_MS = 1500;
110015
110276
  var LATEST_URL = "https://registry.npmjs.org/vapi-network/latest";
@@ -110053,7 +110314,7 @@ async function latestNotice(options, env, signal) {
110053
110314
  const now = (options.nowMs ?? Date.now)();
110054
110315
  let cached2;
110055
110316
  try {
110056
- const value = JSON.parse(await readFile31(paths.updateCheck, "utf8"));
110317
+ const value = JSON.parse(await readFile32(paths.updateCheck, "utf8"));
110057
110318
  if (isRecord13(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
110058
110319
  cached2 = { checkedAt: value.checkedAt, latest: value.latest };
110059
110320
  }