@vapi-network/cli 0.11.0 → 0.12.1

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/cli.js CHANGED
@@ -10118,7 +10118,7 @@ var init_call = __esm({
10118
10118
 
10119
10119
  // src/update-check.ts
10120
10120
  import { lookup } from "node:dns/promises";
10121
- import { mkdir as mkdir21, readFile as readFile29, writeFile as writeFile12 } from "node:fs/promises";
10121
+ import { mkdir as mkdir22, readFile as readFile31, writeFile as writeFile13 } from "node:fs/promises";
10122
10122
 
10123
10123
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/external.js
10124
10124
  var external_exports = {};
@@ -70102,13 +70102,13 @@ async function withAccountMovementLocks(home, accounts, timeoutMs, operation) {
70102
70102
  );
70103
70103
  }
70104
70104
  async function acquireAccountMovementLocks(home, accounts, timeoutMs, operation) {
70105
- const [account, ...remaining] = accounts;
70105
+ const [account, ...remaining2] = accounts;
70106
70106
  if (account === void 0) return await operation();
70107
70107
  return await withAccountMovementLock(
70108
70108
  home,
70109
70109
  account,
70110
70110
  timeoutMs,
70111
- async () => acquireAccountMovementLocks(home, remaining, timeoutMs, operation)
70111
+ async () => acquireAccountMovementLocks(home, remaining2, timeoutMs, operation)
70112
70112
  );
70113
70113
  }
70114
70114
  async function removeStaleLock2(path) {
@@ -70181,7 +70181,7 @@ var POWERSHELL_MISSING = [
70181
70181
  ].join(" ");
70182
70182
  function secretStore(options = {}) {
70183
70183
  const platform2 = options.platform ?? process.platform;
70184
- const run = options.run ?? spawnRunner;
70184
+ const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
70185
70185
  const env = options.env ?? process.env;
70186
70186
  const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
70187
70187
  if (platform2 === "darwin") return keychainStore(platform2, run);
@@ -70375,6 +70375,7 @@ function windowsDataProtectionStore(platform2, run, env, installed) {
70375
70375
  ].join("\n");
70376
70376
  const execute = async (script2) => {
70377
70377
  const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
70378
+
70378
70379
  `);
70379
70380
  requirePowerShell(result);
70380
70381
  return result;
@@ -70537,17 +70538,25 @@ function binaryInstalled(file2, env) {
70537
70538
  if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
70538
70539
  return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join6(directory, file2)));
70539
70540
  }
70541
+ var SAFE_FAILURE_DETAILS = [
70542
+ "Cannot autolaunch D-Bus without X11 $DISPLAY",
70543
+ "Cannot autolaunch D-Bus",
70544
+ "The name org.freedesktop.secrets was not provided by any .service files",
70545
+ "Cannot create an item in a locked collection",
70546
+ "User interaction is not allowed.",
70547
+ "Access to the path is denied."
70548
+ ];
70540
70549
  function requireSuccess(result, what) {
70541
70550
  if (result.code === 0) return;
70542
- const detail = result.stderr.trim() || result.stdout.trim();
70551
+ const detail = SAFE_FAILURE_DETAILS.find((reason) => result.stderr.includes(reason));
70543
70552
  throw new KeystoreError(
70544
- `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail.length === 0 ? "" : ` ${detail}`}`
70553
+ `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail === void 0 ? "" : ` ${detail}`}`
70545
70554
  );
70546
70555
  }
70547
70556
  function withoutTrailingNewline(value) {
70548
70557
  return value.replace(/\r?\n$/u, "");
70549
70558
  }
70550
- var spawnRunner = async (file2, args, input2) => await new Promise((resolve3) => {
70559
+ var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve3) => {
70551
70560
  let stdout = "";
70552
70561
  let stderr2 = "";
70553
70562
  let settled = false;
@@ -70557,7 +70566,7 @@ var spawnRunner = async (file2, args, input2) => await new Promise((resolve3) =>
70557
70566
  resolve3(outcome);
70558
70567
  };
70559
70568
  const child = spawn(file2, [...args], {
70560
- detached: true,
70569
+ detached: platform2 !== "win32",
70561
70570
  stdio: ["pipe", "pipe", "pipe"],
70562
70571
  windowsHide: true
70563
70572
  });
@@ -71567,7 +71576,7 @@ async function loadOrCreateDeviceKey(args) {
71567
71576
  await args.secrets.set(VAULT_KEY_ACCOUNT, key2.toString("base64"));
71568
71577
  return key2;
71569
71578
  } catch (error61) {
71570
- throw asVaultError2(error61, "Unable to load or create the device vault key.");
71579
+ throw asVaultError2(error61, deviceKeyFailureMessage(error61, args.secrets.platform));
71571
71580
  }
71572
71581
  });
71573
71582
  }
@@ -71825,6 +71834,12 @@ function parseJson(value) {
71825
71834
  function asVaultError2(error61, message) {
71826
71835
  return error61 instanceof VaultError ? error61 : new VaultError("corrupt", message, { cause: error61 });
71827
71836
  }
71837
+ var HEADLESS_LINUX_HINT = "A server, container or GitHub Codespace usually has no keyring. Run vapi on your own computer, or connect Claude from https://api.vapinetwork.ai/connect.";
71838
+ function deviceKeyFailureMessage(error61, platform2) {
71839
+ if (!(error61 instanceof KeystoreError)) return "Unable to load or create the device vault key.";
71840
+ const detail = `Unable to load or create the device vault key: ${error61.message.replace(/\.$/u, "")}.`;
71841
+ return platform2 === "linux" ? `${detail} ${HEADLESS_LINUX_HINT}` : detail;
71842
+ }
71828
71843
 
71829
71844
  // ../core/src/vault-migrate.ts
71830
71845
  import {
@@ -72173,6 +72188,17 @@ var WalletStore = class _WalletStore {
72173
72188
  );
72174
72189
  return account?.address ?? (await readKeystoreSummary(this.pathFor(target))).address;
72175
72190
  }
72191
+ /**
72192
+ * Creates the vault without deriving an account, for apps that create every
72193
+ * account by name. Refuses when a vault already exists in this home.
72194
+ */
72195
+ async createEmptyVault() {
72196
+ if (await this.readVaultUnlocked() !== void 0) {
72197
+ throw new KeystoreError("A vault already exists in this home.");
72198
+ }
72199
+ await this.openVault({ create: true });
72200
+ this.dropVaultCache();
72201
+ }
72176
72202
  async create(name, passphrase, options = {}) {
72177
72203
  void passphrase;
72178
72204
  void options.enableSolana;
@@ -73053,11 +73079,11 @@ function accountChangeBusyError(account, command) {
73053
73079
  );
73054
73080
  }
73055
73081
  async function withAccountMutationLocks(home, accounts, command, operation) {
73056
- const [account, ...remaining] = [...new Set(accounts)].sort();
73082
+ const [account, ...remaining2] = [...new Set(accounts)].sort();
73057
73083
  if (account === void 0) return await operation();
73058
73084
  return await withFileLock(
73059
73085
  join8(home, `.account-${account}.lock`),
73060
- async () => await withAccountMutationLocks(home, remaining, command, operation),
73086
+ async () => await withAccountMutationLocks(home, remaining2, command, operation),
73061
73087
  {
73062
73088
  lockedMessage: `Account ${account} is busy with another account change. Wait for it to finish, then retry ${command}.`
73063
73089
  }
@@ -73865,8 +73891,8 @@ async function escrowFundingDayRemainingAtomic(input2) {
73865
73891
  const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now);
73866
73892
  const row = rows.find((candidate) => candidate.wallet === input2.wallet);
73867
73893
  const reserved = input2.reservationId ? row?.reservations?.find((candidate) => candidate.id === input2.reservationId) : void 0;
73868
- const remaining = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
73869
- return remaining > 0n ? remaining : 0n;
73894
+ const remaining2 = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
73895
+ return remaining2 > 0n ? remaining2 : 0n;
73870
73896
  }
73871
73897
  async function taskReservedAtomic(input2) {
73872
73898
  const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now, true);
@@ -75206,13 +75232,13 @@ function splitMovementPlanAtRelayLimit(plan) {
75206
75232
  const legs = plan.legs.flatMap((leg) => {
75207
75233
  const purpose = leg.purpose ?? "send";
75208
75234
  const split2 = purpose === "sweep" || plan.reason === "send" && plan.treasury !== void 0 && leg.to === plan.treasury;
75209
- let remaining = parseUsdCents(leg.amountUsd);
75210
- if (!split2 || remaining <= maximumCents) return [leg];
75235
+ let remaining2 = parseUsdCents(leg.amountUsd);
75236
+ if (!split2 || remaining2 <= maximumCents) return [leg];
75211
75237
  const parts = [];
75212
- while (remaining > 0n) {
75213
- const cents = remaining > maximumCents ? maximumCents : remaining;
75238
+ while (remaining2 > 0n) {
75239
+ const cents = remaining2 > maximumCents ? maximumCents : remaining2;
75214
75240
  parts.push({ ...leg, amountUsd: formatUsdCents(cents) });
75215
- remaining -= cents;
75241
+ remaining2 -= cents;
75216
75242
  }
75217
75243
  return parts;
75218
75244
  });
@@ -76088,13 +76114,13 @@ async function withMovementLock(home, from16, timeoutMs, operation) {
76088
76114
  }
76089
76115
  }
76090
76116
  async function withMovementLocks(home, senders, timeoutMs, operation) {
76091
- const [sender, ...remaining] = senders;
76117
+ const [sender, ...remaining2] = senders;
76092
76118
  if (sender === void 0) return await operation();
76093
76119
  return await withMovementLock(
76094
76120
  home,
76095
76121
  sender,
76096
76122
  timeoutMs,
76097
- async () => withMovementLocks(home, remaining, timeoutMs, operation)
76123
+ async () => withMovementLocks(home, remaining2, timeoutMs, operation)
76098
76124
  );
76099
76125
  }
76100
76126
  async function assertNoPendingCeilingSweep(deps, senders) {
@@ -76901,11 +76927,11 @@ function planTargets(input2) {
76901
76927
  function splitCandidateAtRelayMaximum(candidate, relayMaxAtomic) {
76902
76928
  const maximumCents = relayMaxAtomic / 10000n;
76903
76929
  const legs = [];
76904
- let remaining = candidate.cents;
76905
- while (remaining > 0n) {
76906
- const cents = remaining > maximumCents ? maximumCents : remaining;
76930
+ let remaining2 = candidate.cents;
76931
+ while (remaining2 > 0n) {
76932
+ const cents = remaining2 > maximumCents ? maximumCents : remaining2;
76907
76933
  legs.push(allocationLeg(candidate.from, candidate.to, cents, candidate.purpose));
76908
- remaining -= cents;
76934
+ remaining2 -= cents;
76909
76935
  }
76910
76936
  return legs;
76911
76937
  }
@@ -77740,7 +77766,7 @@ function createRunBudget(args) {
77740
77766
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
77741
77767
  import { arch, platform, release } from "node:os";
77742
77768
  import { join as join13 } from "node:path";
77743
- var VAPI_CLIENT_VERSION = "0.11.0";
77769
+ var VAPI_CLIENT_VERSION = "0.12.1";
77744
77770
  async function createSupportReport(options) {
77745
77771
  const message = options.message.trim();
77746
77772
  if (!message) throw new Error("Support report message must not be empty.");
@@ -79132,8 +79158,15 @@ async function ownerStake(deps) {
79132
79158
  stakeUrl: parsed.data.stakeUrl
79133
79159
  };
79134
79160
  }
79135
- async function routerCredentials(deps) {
79136
- const { routerBaseUrl, routerKey } = await routerCredentialSnapshot(deps);
79161
+ async function routerCredentials(deps, options = {}) {
79162
+ const credentials = options.funding === "balance" ? await routerBalanceCredentialSnapshot(deps) : await routerCredentialSnapshot(deps);
79163
+ if (credentials === void 0) {
79164
+ throw new RouterClientError(
79165
+ "no_router_key",
79166
+ "No Router balance key is stored for this wallet."
79167
+ );
79168
+ }
79169
+ const { routerBaseUrl, routerKey } = credentials;
79137
79170
  return { baseURL: `${routerBaseUrl}/v1`, apiKey: routerKey };
79138
79171
  }
79139
79172
  async function routerCredentialSnapshot(deps) {
@@ -82357,10 +82390,10 @@ async function waitForMilestone(client, input2) {
82357
82390
  return { reached, milestone, polls, elapsedMs: now().getTime() - started };
82358
82391
  }
82359
82392
  for (; ; ) {
82360
- const remaining = deadline - now().getTime();
82361
- if (remaining <= 0) return result(false);
82393
+ const remaining2 = deadline - now().getTime();
82394
+ if (remaining2 <= 0) return result(false);
82362
82395
  const controller = new AbortController();
82363
- const timer = setTimeout(() => controller.abort(), remaining);
82396
+ const timer = setTimeout(() => controller.abort(), remaining2);
82364
82397
  let response;
82365
82398
  polls++;
82366
82399
  try {
@@ -83024,7 +83057,7 @@ async function feeTask(input2, action) {
83024
83057
  );
83025
83058
  let approvalGranted = input2.approval !== void 0 && "granted" in input2.approval && input2.approval.granted;
83026
83059
  const checkPolicy = async (reservationId) => {
83027
- const remaining = await escrowFundingDayRemainingAtomic({
83060
+ const remaining2 = await escrowFundingDayRemainingAtomic({
83028
83061
  caps: input2.caps,
83029
83062
  ledgerPath: input2.ledgerPath,
83030
83063
  wallet: input2.wallet,
@@ -83041,13 +83074,13 @@ async function feeTask(input2, action) {
83041
83074
  const maxPerTaskAtomic = policyAtomic(input2.policy.maxPerTaskUsd);
83042
83075
  if (feeAtomic > maxPerTaskAtomic || taskReserved + feeAtomic > maxPerTaskAtomic)
83043
83076
  return { outcome: "refused", reason: "policy.perTask", money: money2, disputeFee: fee };
83044
- if (feeAtomic > remaining)
83077
+ if (feeAtomic > remaining2)
83045
83078
  return { outcome: "refused", reason: "policy.perDay", money: money2, disputeFee: fee };
83046
83079
  if (feeAtomic > policyAtomic(input2.policy.approveAboveUsd) && !approvalGranted) {
83047
83080
  if (input2.approval && "ask" in input2.approval) {
83048
83081
  approvalGranted = await input2.approval.ask({
83049
83082
  money: money2,
83050
- dayRemainingUsd: Number(formatBaseUnitsUsd(remaining))
83083
+ dayRemainingUsd: Number(formatBaseUnitsUsd(remaining2))
83051
83084
  });
83052
83085
  if (!approvalGranted) return { outcome: "declined", money: money2, disputeFee: fee };
83053
83086
  } else return { outcome: "approval_needed", money: money2, disputeFee: fee };
@@ -87437,9 +87470,9 @@ function isRecord4(value) {
87437
87470
  }
87438
87471
 
87439
87472
  // src/cli.ts
87440
- import { spawn as spawn4 } from "node:child_process";
87473
+ import { spawn as spawn5 } from "node:child_process";
87441
87474
  import { stat as stat16 } from "node:fs/promises";
87442
- import { join as join28 } from "node:path";
87475
+ import { join as join29 } from "node:path";
87443
87476
  import { createInterface as createInterface3 } from "node:readline/promises";
87444
87477
 
87445
87478
  // ../core/src/member-bundle.ts
@@ -91569,8 +91602,8 @@ async function memberBudgetAtomic(account, configured, deps) {
91569
91602
  deps.now?.() ?? /* @__PURE__ */ new Date(),
91570
91603
  account
91571
91604
  );
91572
- const remaining = BigInt(caps.perDayAtomic) - BigInt(ledger.spentAtomic);
91573
- return remaining < 0n ? 0n : remaining;
91605
+ const remaining2 = BigInt(caps.perDayAtomic) - BigInt(ledger.spentAtomic);
91606
+ return remaining2 < 0n ? 0n : remaining2;
91574
91607
  }
91575
91608
  function withoutTreasuryGrants(profile) {
91576
91609
  return {
@@ -93565,9 +93598,9 @@ async function watchEvents(ctx, input2, now, sleep, deadline, signal, progress)
93565
93598
  const reached = input2.until !== void 0 && next.events.some((event) => taskStateMatches(input2.until, taskEventState(event)));
93566
93599
  if (next.events.length || reached)
93567
93600
  return { ...next, ...reached ? { reached: input2.until } : {}, timedOut: false };
93568
- const remaining = deadline - now().getTime();
93569
- if (remaining <= 0) return { ...next, timedOut: true };
93570
- await sleep(Math.min(TASK_LIMITS.watchIntervalMinMs, remaining), signal);
93601
+ const remaining2 = deadline - now().getTime();
93602
+ if (remaining2 <= 0) return { ...next, timedOut: true };
93603
+ await sleep(Math.min(TASK_LIMITS.watchIntervalMinMs, remaining2), signal);
93571
93604
  if (now().getTime() >= deadline)
93572
93605
  return { events: [], nextCursor: progress.cursor, timedOut: true };
93573
93606
  }
@@ -94610,9 +94643,15 @@ var VapiMcpServer = class {
94610
94643
  return tool.deprecatedReplacement ? withDeprecation(result, tool.deprecatedReplacement) : result;
94611
94644
  }
94612
94645
  }
94613
- connectStdio() {
94646
+ #output = process.stdout;
94647
+ /**
94648
+ * Serves JSON-RPC lines from `input` and answers on `output`. The desktop
94649
+ * app hands in a socket; the CLI hands in stdio through connectStdio().
94650
+ */
94651
+ connect(input2, output4) {
94614
94652
  if (this.#stdio) return;
94615
- this.#stdio = createInterface({ input: process.stdin, crlfDelay: Infinity });
94653
+ this.#output = output4;
94654
+ this.#stdio = createInterface({ input: input2, crlfDelay: Infinity });
94616
94655
  this.#stdio.on("line", (line) => {
94617
94656
  void this.#handleLine(line);
94618
94657
  });
@@ -94621,6 +94660,9 @@ var VapiMcpServer = class {
94621
94660
  this.#onClose?.();
94622
94661
  });
94623
94662
  }
94663
+ connectStdio() {
94664
+ this.connect(process.stdin, process.stdout);
94665
+ }
94624
94666
  async close() {
94625
94667
  this.#stdio?.close();
94626
94668
  this.#stdio = void 0;
@@ -94701,7 +94743,7 @@ var VapiMcpServer = class {
94701
94743
  }
94702
94744
  }
94703
94745
  #write(message) {
94704
- process.stdout.write(`${JSON.stringify(message)}
94746
+ this.#output.write(`${JSON.stringify(message)}
94705
94747
  `);
94706
94748
  }
94707
94749
  };
@@ -95711,7 +95753,12 @@ var PROBE_MODES = ["origin", "endpoint", "openapi"];
95711
95753
  var PAYOUT_CHAIN_ID = "eip155:8453";
95712
95754
  var PAYOUT_STATEMENT = "Confirm this wallet receives vAPI Call payouts";
95713
95755
  var CLAIM_STATEMENT_PREFIX = "Claim the vAPI Call listings served from";
95714
- var API_KEY_CONSOLE_PATH = "/account";
95756
+ function apiKeyConsoleUrl(baseUrl) {
95757
+ const url2 = listingsUrl(baseUrl, "/connect");
95758
+ url2.search = "advanced=keys";
95759
+ url2.hash = "api-keys";
95760
+ return url2;
95761
+ }
95715
95762
  var RegistryApiError = class extends Error {
95716
95763
  constructor(status, message, body) {
95717
95764
  super(message);
@@ -95871,7 +95918,7 @@ async function registryError(response, baseUrl) {
95871
95918
  [
95872
95919
  "The vAPI API key was rejected.",
95873
95920
  detail,
95874
- `Create a key in the console at ${listingsUrl(baseUrl, API_KEY_CONSOLE_PATH).href} and store it with vapi auth set-key.`
95921
+ `Create a key in the console at ${apiKeyConsoleUrl(baseUrl).href} and store it with vapi auth set-key.`
95875
95922
  ].filter(Boolean).join(" "),
95876
95923
  body
95877
95924
  );
@@ -98283,10 +98330,10 @@ async function awaitRelay(options) {
98283
98330
  if (!Number.isFinite(deadline)) throw new CloudBackupError("relay_expired");
98284
98331
  while (true) {
98285
98332
  if (isAborted(options.signal)) throw new CloudBackupError("relay_aborted");
98286
- const remaining = deadline - readNow(now).getTime();
98287
- if (remaining <= 0) throw new CloudBackupError("relay_expired");
98333
+ const remaining2 = deadline - readNow(now).getTime();
98334
+ if (remaining2 <= 0) throw new CloudBackupError("relay_expired");
98288
98335
  let response;
98289
- const requestDeadline = AbortSignal.timeout(Math.max(1, remaining));
98336
+ const requestDeadline = AbortSignal.timeout(Math.max(1, remaining2));
98290
98337
  const requestSignal = options.signal === void 0 ? requestDeadline : AbortSignal.any([options.signal, requestDeadline]);
98291
98338
  try {
98292
98339
  response = await (options.fetchImpl ?? publicFetch5)(
@@ -98305,7 +98352,7 @@ async function awaitRelay(options) {
98305
98352
  return await readRelayResult(response, options);
98306
98353
  }
98307
98354
  try {
98308
- await sleep(Math.min(Math.max(0, pollMs), remaining), options.signal);
98355
+ await sleep(Math.min(Math.max(0, pollMs), remaining2), options.signal);
98309
98356
  } catch {
98310
98357
  if (isAborted(options.signal)) throw new CloudBackupError("relay_aborted");
98311
98358
  }
@@ -99095,7 +99142,7 @@ async function readProcessStdin() {
99095
99142
  }
99096
99143
 
99097
99144
  // src/version.ts
99098
- var CLI_VERSION = "0.11.0";
99145
+ var CLI_VERSION = "0.12.1";
99099
99146
 
99100
99147
  // src/status.ts
99101
99148
  async function statusCommand(argv, json2, io, dependencies) {
@@ -102320,9 +102367,9 @@ async function reserveRemoteAllowance(args) {
102320
102367
  const perDayAtomic = BigInt(args.caps.perDayAtomic);
102321
102368
  const ledgerPath = getVapiPaths(args.home).ledger;
102322
102369
  const spent = BigInt((await readSpendLedger(ledgerPath, args.now, args.account)).spentAtomic);
102323
- const remaining = spent >= perDayAtomic ? 0n : perDayAtomic - spent;
102324
- const requested = args.run.budgetUsd === void 0 ? remaining : usdToAtomic(args.run.budgetUsd);
102325
- const reserved = requested < remaining ? requested : remaining;
102370
+ const remaining2 = spent >= perDayAtomic ? 0n : perDayAtomic - spent;
102371
+ const requested = args.run.budgetUsd === void 0 ? remaining2 : usdToAtomic(args.run.budgetUsd);
102372
+ const reserved = requested < remaining2 ? requested : remaining2;
102326
102373
  if (reserved === 0n) {
102327
102374
  throw new RemoteKeyRefusedError(
102328
102375
  "no_daily_allowance",
@@ -102604,12 +102651,12 @@ function createLocalRuntime(options) {
102604
102651
  const { home } = options;
102605
102652
  const entry = options.entry ?? realpathSync(process.argv[1]);
102606
102653
  const execPath = options.execPath ?? process.execPath;
102607
- const spawn5 = options.spawn ?? nodeSpawn;
102654
+ const spawn6 = options.spawn ?? nodeSpawn;
102608
102655
  const kill = options.kill ?? ((pid, signal) => process.kill(pid, signal));
102609
102656
  const processCommand = options.processCommand ?? defaultProcessCommand;
102610
102657
  const ownsProcess = (handle, pid) => processCommand(pid)?.includes(runResultPath(home, handle.runId)) === true;
102611
102658
  const closeFd = options.closeFd ?? closeSync2;
102612
- const readFile30 = options.readFile ?? nodeReadFile;
102659
+ const readFile32 = options.readFile ?? nodeReadFile;
102613
102660
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
102614
102661
  const openLog = options.openLog ?? ((path) => {
102615
102662
  mkdirSync2(runsDirectory(home), { recursive: true, mode: 448 });
@@ -102627,7 +102674,7 @@ function createLocalRuntime(options) {
102627
102674
  const logFd = openLog(logPath);
102628
102675
  let child;
102629
102676
  try {
102630
- child = spawn5(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
102677
+ child = spawn6(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
102631
102678
  detached: true,
102632
102679
  stdio: ["ignore", logFd, logFd],
102633
102680
  env: {
@@ -102664,7 +102711,7 @@ function createLocalRuntime(options) {
102664
102711
  return handle;
102665
102712
  },
102666
102713
  async status(handle) {
102667
- const result = await readResultFile(readFile30, runResultPath(home, handle.runId));
102714
+ const result = await readResultFile(readFile32, runResultPath(home, handle.runId));
102668
102715
  if (result !== void 0) return result;
102669
102716
  const pid = localPid(handle);
102670
102717
  if (pid === void 0 || handle.kind !== "local") {
@@ -102767,10 +102814,10 @@ function childArguments(member, run) {
102767
102814
  ...run.drawUsd ? ["--draw", run.drawUsd] : []
102768
102815
  ];
102769
102816
  }
102770
- async function readResultFile(readFile30, path) {
102817
+ async function readResultFile(readFile32, path) {
102771
102818
  let text;
102772
102819
  try {
102773
- text = await readFile30(path, "utf8");
102820
+ text = await readFile32(path, "utf8");
102774
102821
  } catch (error61) {
102775
102822
  if (hasCode3(error61, "ENOENT")) return void 0;
102776
102823
  return { state: "failed", detail: "unreadable result file" };
@@ -103545,6 +103592,80 @@ import { spawn as spawn3 } from "node:child_process";
103545
103592
  import { mkdir as mkdir20, readFile as readFile27, writeFile as writeFile11 } from "node:fs/promises";
103546
103593
  import { homedir as systemHomedir } from "node:os";
103547
103594
  import { dirname as dirname14, posix, win32 as win322 } from "node:path";
103595
+
103596
+ // src/toml-config.ts
103597
+ function removeTomlTables(contents, isTarget) {
103598
+ let removing = false;
103599
+ let retained = "";
103600
+ for (const { line, table } of tomlLines(contents)) {
103601
+ if (table !== void 0) removing = isTarget(tomlKeyPath(table));
103602
+ if (!removing) retained += line;
103603
+ }
103604
+ return retained;
103605
+ }
103606
+ function* tomlLines(contents) {
103607
+ let multiline;
103608
+ for (const line of contents.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
103609
+ yield { line, table: multiline === void 0 ? tomlTableName(line) : void 0 };
103610
+ for (let index2 = 0; index2 < line.length; index2 += 1) {
103611
+ const char = line[index2];
103612
+ if (multiline !== void 0) {
103613
+ if (multiline === '"""' && char === "\\") {
103614
+ index2 += 1;
103615
+ continue;
103616
+ }
103617
+ if (line.startsWith(multiline, index2)) {
103618
+ index2 += 2;
103619
+ multiline = void 0;
103620
+ }
103621
+ } else {
103622
+ if (char === "#") break;
103623
+ if (char !== "'" && char !== '"') continue;
103624
+ const delimiter2 = char.repeat(3);
103625
+ if (line.startsWith(delimiter2, index2)) {
103626
+ multiline = delimiter2;
103627
+ index2 += 2;
103628
+ } else {
103629
+ for (index2 += 1; index2 < line.length; index2 += 1) {
103630
+ if (char === '"' && line[index2] === "\\") index2 += 1;
103631
+ else if (line[index2] === char) break;
103632
+ }
103633
+ }
103634
+ }
103635
+ }
103636
+ }
103637
+ }
103638
+ function tomlKeyPath(table) {
103639
+ const key2 = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
103640
+ const pattern = new RegExp(`^\\s*(${key2})(?:\\s*\\.\\s*(${key2}))*\\s*$`);
103641
+ if (!pattern.test(table)) return [];
103642
+ return [...table.matchAll(new RegExp(key2, "g"))].map(([part]) => unquoteTomlKey(part));
103643
+ }
103644
+ function tomlTableName(line) {
103645
+ const header = line.replace(/\r?\n$/, "");
103646
+ const match = /^\s*(?:\[\[\s*(.*?)\s*\]\]|\[\s*(.*?)\s*\])\s*(?:#.*)?$/.exec(header);
103647
+ return match?.[1] ?? match?.[2];
103648
+ }
103649
+ function unquoteTomlKey(key2) {
103650
+ if (key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
103651
+ if (key2.startsWith('"') && key2.endsWith('"')) {
103652
+ try {
103653
+ return JSON.parse(key2);
103654
+ } catch {
103655
+ return key2;
103656
+ }
103657
+ }
103658
+ return key2;
103659
+ }
103660
+ function tomlSeparator(contents) {
103661
+ if (contents.length === 0 || /(?:\r?\n)[ \t]*(?:\r?\n)$/.test(contents)) return "";
103662
+ return /\r?\n$/.test(contents) ? "\n" : "\n\n";
103663
+ }
103664
+ function escapeToml(value) {
103665
+ return JSON.stringify(value).slice(1, -1);
103666
+ }
103667
+
103668
+ // src/mcp-install.ts
103548
103669
  var MCP_INSTALL_USAGE = "Usage: vapi mcp install <claude-code|claude-desktop|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]";
103549
103670
  var APPS = /* @__PURE__ */ new Set(["claude-code", "claude-desktop", "cursor", "codex"]);
103550
103671
  var CLAUDE_ALIAS_NOTICE = "vapi mcp install claude installs into Claude Desktop; for the Claude Code CLI use: vapi mcp install claude-code";
@@ -103830,7 +103951,10 @@ function jsonConfig(path, existing, entry) {
103830
103951
  `;
103831
103952
  }
103832
103953
  function tomlConfig(existing, entry) {
103833
- const retained = removeVapiTomlTables(existing);
103954
+ const retained = removeTomlTables(
103955
+ existing,
103956
+ ([root, name]) => root === "mcp_servers" && name === "vapi"
103957
+ );
103834
103958
  const block = [
103835
103959
  "[mcp_servers.vapi]",
103836
103960
  'command = "npx"',
@@ -103840,46 +103964,6 @@ function tomlConfig(existing, entry) {
103840
103964
  ].join("\n");
103841
103965
  return `${retained}${tomlSeparator(retained)}${block}`;
103842
103966
  }
103843
- function removeVapiTomlTables(contents) {
103844
- const lines = contents.match(/[^\n]*\n|[^\n]+$/g) ?? [];
103845
- let removing = false;
103846
- let retained = "";
103847
- for (const line of lines) {
103848
- const table = tomlTableName(line);
103849
- if (table !== void 0) removing = isVapiTomlTable(table);
103850
- if (!removing) retained += line;
103851
- }
103852
- return retained;
103853
- }
103854
- function tomlTableName(line) {
103855
- const header = line.replace(/\r?\n$/, "");
103856
- const match = /^\s*(?:\[\[\s*(.*?)\s*\]\]|\[\s*(.*?)\s*\])\s*(?:#.*)?$/.exec(header);
103857
- return match?.[1] ?? match?.[2];
103858
- }
103859
- function isVapiTomlTable(table) {
103860
- const key2 = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
103861
- const match = new RegExp(`^\\s*(${key2})\\s*\\.\\s*(${key2})(?:\\s*\\.|\\s*$)`).exec(table);
103862
- if (match === null) return false;
103863
- return unquoteTomlKey(match[1]) === "mcp_servers" && unquoteTomlKey(match[2]) === "vapi";
103864
- }
103865
- function unquoteTomlKey(key2) {
103866
- if (key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
103867
- if (key2.startsWith('"') && key2.endsWith('"')) {
103868
- try {
103869
- return JSON.parse(key2);
103870
- } catch {
103871
- return key2;
103872
- }
103873
- }
103874
- return key2;
103875
- }
103876
- function tomlSeparator(contents) {
103877
- if (contents.length === 0 || /(?:\r?\n)[ \t]*(?:\r?\n)$/.test(contents)) return "";
103878
- return /\r?\n$/.test(contents) ? "\n" : "\n\n";
103879
- }
103880
- function escapeToml(value) {
103881
- return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
103882
- }
103883
103967
  function isRecord12(value) {
103884
103968
  return typeof value === "object" && value !== null && !Array.isArray(value);
103885
103969
  }
@@ -103901,6 +103985,546 @@ async function pathExists5(path) {
103901
103985
  }
103902
103986
  }
103903
103987
 
103988
+ // src/code.ts
103989
+ import { constants as constants2 } from "node:fs";
103990
+ import { access, mkdir as mkdir21, readFile as readFile28, realpath, unlink as unlink13, writeFile as writeFile12 } from "node:fs/promises";
103991
+ import { homedir as homedir3 } from "node:os";
103992
+ import { basename as basename5, dirname as dirname15, join as join26, posix as posix2, win32 as win323 } from "node:path";
103993
+ var VAPI_CODEX_PROVIDER = "vapi";
103994
+ var VAPI_CODEX_PROFILE = "vapi";
103995
+ var VAPI_CODEX_DEFAULT_MODEL = "venice/openai-gpt-61-sol";
103996
+ var VAPI_ROUTER_KEY_ENV = "VAPI_ROUTER_KEY";
103997
+ function codexConfigPath(env, home) {
103998
+ return join26(env.CODEX_HOME || join26(home, ".codex"), "config.toml");
103999
+ }
104000
+ function hasVapiCodexProfile(contents) {
104001
+ const roots = new Set(
104002
+ [...tomlLines(contents)].flatMap(({ table }) => {
104003
+ const path = table === void 0 ? [] : tomlKeyPath(table);
104004
+ return path.length === 2 && path[1] === "vapi" ? [path[0]] : [];
104005
+ })
104006
+ );
104007
+ return roots.has("model_providers") && roots.has("profiles");
104008
+ }
104009
+ async function resolveBinary(name, options) {
104010
+ const windows = (options.platform ?? process.platform) === "win32";
104011
+ const path = options.env.PATH ?? (windows ? Object.entries(options.env).find(([key2]) => key2.toLowerCase() === "path")?.[1] : void 0);
104012
+ if (path === void 0) return void 0;
104013
+ const paths = windows ? win323 : posix2;
104014
+ const canonical = options.realpath ?? realpath;
104015
+ const executable = options.isExecutable ?? (async (candidate) => {
104016
+ try {
104017
+ await access(candidate, constants2.X_OK);
104018
+ return true;
104019
+ } catch (error61) {
104020
+ if (isMissingFile(error61) || error61.code === "EACCES")
104021
+ return false;
104022
+ throw error61;
104023
+ }
104024
+ });
104025
+ const self = options.selfPath ?? process.argv[1];
104026
+ const selfReal = self === void 0 ? void 0 : await canonical(self);
104027
+ const extensions = windows ? ["", ...(options.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";")] : [""];
104028
+ for (const directory of path.split(windows ? ";" : ":")) {
104029
+ for (const extension of extensions) {
104030
+ const candidate = paths.resolve(directory.replace(/^"|"$/gu, ""), `${name}${extension}`);
104031
+ if (!await executable(candidate)) continue;
104032
+ const resolved = await canonical(candidate);
104033
+ if (selfReal !== void 0 && (windows ? resolved.toLowerCase() === selfReal.toLowerCase() : resolved === selfReal))
104034
+ continue;
104035
+ return candidate;
104036
+ }
104037
+ }
104038
+ return void 0;
104039
+ }
104040
+ var RC_START = "# >>> vapi code >>>";
104041
+ var RC_END = "# <<< vapi code <<<";
104042
+ var CONFIG_END = "# <<< vapi code config <<<\n";
104043
+ var isCodeTable = ([root, name]) => name === "vapi" && (root === "model_providers" || root === "profiles");
104044
+ function cleanConfig(contents) {
104045
+ let created = false;
104046
+ const cleaned = contents.replace(
104047
+ /(\n?)\[model_providers\.vapi\]\n# >>> vapi code config (created|existing) (0|1) >>>\n([\s\S]*?)# <<< vapi code config <<<\n/gu,
104048
+ (_, prefix, kind, separator, body) => {
104049
+ created ||= kind === "created";
104050
+ return (separator === "1" ? "" : prefix) + removeTomlTables(`[model_providers.vapi]
104051
+ ${body}`, isCodeTable);
104052
+ }
104053
+ );
104054
+ return { contents: removeTomlTables(cleaned, isCodeTable), created };
104055
+ }
104056
+ function configContents(existing, baseURL) {
104057
+ const clean2 = cleanConfig(existing ?? "");
104058
+ const retained = clean2.contents;
104059
+ const separator = retained.length > 0 && !retained.endsWith("\n") ? "\n" : "";
104060
+ return `${retained}${separator}[model_providers.vapi]
104061
+ # >>> vapi code config ${existing === void 0 || clean2.created ? "created" : "existing"} ${separator.length} >>>
104062
+ ` + [
104063
+ 'name = "vAPI Router"',
104064
+ `base_url = "${escapeToml(baseURL)}"`,
104065
+ `env_key = "${VAPI_ROUTER_KEY_ENV}"`,
104066
+ 'wire_api = "responses"',
104067
+ "",
104068
+ "[profiles.vapi]",
104069
+ `model_provider = "${VAPI_CODEX_PROVIDER}"`,
104070
+ `model = "${VAPI_CODEX_DEFAULT_MODEL}"`,
104071
+ ""
104072
+ ].join("\n") + CONFIG_END;
104073
+ }
104074
+ function removeAliases(contents) {
104075
+ return contents.replace(
104076
+ /(^|\n)# >>> vapi code >>>\r?\n[\s\S]*?^# <<< vapi code <<<(\r?\n|$)/gmu,
104077
+ (_, prefix, suffix) => suffix === "" ? "" : prefix
104078
+ );
104079
+ }
104080
+ function aliasContents(original, tools) {
104081
+ const existing = original ?? "";
104082
+ const block = [RC_START, ...tools.map((tool) => `alias ${tool}="vapi ${tool}"`), RC_END].join(
104083
+ "\n"
104084
+ );
104085
+ const match = /^# >>> vapi code >>>\r?\n[\s\S]*?^# <<< vapi code <<</gmu;
104086
+ if (match.test(existing)) return existing.replace(match, block);
104087
+ const separator = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
104088
+ return `${existing}${separator}${block}${original === "" || existing.endsWith("\n") ? "\n" : ""}`;
104089
+ }
104090
+ async function readOptional(path) {
104091
+ try {
104092
+ return await readFile28(path, "utf8");
104093
+ } catch (error61) {
104094
+ if (isMissingFile(error61)) return void 0;
104095
+ throw error61;
104096
+ }
104097
+ }
104098
+ async function writeConfig(path, contents) {
104099
+ await mkdir21(dirname15(path), { recursive: true });
104100
+ await writeFile12(path, contents);
104101
+ }
104102
+ async function codeCommand(argv, json2, io, dependencies) {
104103
+ const command = argv[0];
104104
+ if (command !== "install" && command !== "uninstall")
104105
+ throw new UsageError("Usage: vapi code <install|uninstall>.");
104106
+ const parsed = parseArguments(argv.slice(1), {
104107
+ valueOptions: new Set(command === "install" ? ["--wallet"] : []),
104108
+ booleanOptions: new Set(command === "install" ? ["--yes", "--no-alias"] : []),
104109
+ maximumPositionals: 0
104110
+ });
104111
+ const env = getEnvironment(dependencies);
104112
+ const home = dependencies.code?.homedir ?? homedir3();
104113
+ const config2 = codexConfigPath(env, home);
104114
+ const rcPaths = [join26(home, ".zshrc"), join26(home, ".bashrc")];
104115
+ if (command === "uninstall") {
104116
+ const removed = [];
104117
+ const previous = await readOptional(config2);
104118
+ if (previous !== void 0) {
104119
+ const clean2 = cleanConfig(previous);
104120
+ if (clean2.contents !== previous) {
104121
+ if (clean2.contents === "" && clean2.created) await unlink13(config2);
104122
+ else await writeFile12(config2, clean2.contents);
104123
+ removed.push(config2);
104124
+ }
104125
+ }
104126
+ for (const path of rcPaths) {
104127
+ const previous2 = await readOptional(path);
104128
+ if (previous2 === void 0) continue;
104129
+ const clean2 = removeAliases(previous2);
104130
+ if (clean2 !== previous2) {
104131
+ if (clean2 === "" && previous2.startsWith(RC_START) && !previous2.endsWith("\n"))
104132
+ await unlink13(path);
104133
+ else await writeFile12(path, clean2);
104134
+ removed.push(path);
104135
+ }
104136
+ }
104137
+ io.stdout(
104138
+ json2 ? JSON.stringify({ command: "code uninstall", removed }) : removed.length === 0 ? "Nothing to remove." : `Removed vAPI code settings from: ${removed.join(", ")}`
104139
+ );
104140
+ return 0;
104141
+ }
104142
+ const tools = [];
104143
+ const skipped2 = [];
104144
+ for (const name of ["claude", "codex"]) {
104145
+ const binary = await resolveBinary(name, { ...dependencies.code, env });
104146
+ if (binary === void 0)
104147
+ skipped2.push(
104148
+ `Skipped ${name === "claude" ? "Claude Code" : "Codex"}: \`${name}\` is not on PATH.`
104149
+ );
104150
+ else tools.push(name);
104151
+ }
104152
+ if (tools.length === 0) {
104153
+ const message = "Neither claude nor codex is on PATH; nothing was installed.";
104154
+ if (json2) io.stdout(JSON.stringify({ installed: [], skipped: skipped2, error: message }));
104155
+ else {
104156
+ skipped2.forEach(io.stderr);
104157
+ io.stderr(message);
104158
+ }
104159
+ return 1;
104160
+ }
104161
+ let target = await targetWallet(parsed, dependencies);
104162
+ const credentials = dependencies.router?.routerCredentials ?? routerCredentials;
104163
+ let linked = false;
104164
+ let rotated = false;
104165
+ let result;
104166
+ for (; ; ) {
104167
+ try {
104168
+ result = await credentials(routerDeps2(target, dependencies));
104169
+ break;
104170
+ } catch (error61) {
104171
+ if (error61 instanceof RouterClientError && error61.code === "not_linked" && !linked) {
104172
+ linked = true;
104173
+ const account = parsed.one("--wallet");
104174
+ await (dependencies.code?.login ?? runLoginFlow)(
104175
+ account === void 0 ? [] : ["--account", account],
104176
+ json2,
104177
+ { ...io, stdout: io.stderr },
104178
+ json2 ? { ...dependencies, interactive: false, stdinIsTTY: false } : dependencies
104179
+ );
104180
+ target = await targetWallet(parsed, dependencies);
104181
+ } else if (error61 instanceof RouterClientError && error61.code === "no_router_key" && !rotated) {
104182
+ rotated = true;
104183
+ await (dependencies.router?.rotateRouterKey ?? rotateRouterKey)(
104184
+ routerDeps2(target, dependencies)
104185
+ );
104186
+ } else throw error61;
104187
+ }
104188
+ }
104189
+ const installed = [];
104190
+ if (tools.includes("claude")) installed.push("Claude Code: ready, launch with `vapi claude`");
104191
+ if (tools.includes("codex")) {
104192
+ await writeConfig(config2, configContents(await readOptional(config2), result.baseURL));
104193
+ installed.push(`Codex: installed ${config2}`);
104194
+ }
104195
+ let alias = "Aliases: skipped.";
104196
+ if (!parsed.has("--no-alias")) {
104197
+ if ((dependencies.code?.platform ?? process.platform) === "win32")
104198
+ alias = "Aliases: skipped on Windows.";
104199
+ else {
104200
+ const yes = parsed.has("--yes") || !json2 && isInteractive(dependencies) && isStdinInteractive(dependencies) && /^y(?:es)?$/iu.test(
104201
+ (await getLinePrompt(dependencies)(
104202
+ "Make `claude` and `codex` use your vAPI Compute first from now on? [y/N] "
104203
+ )).trim()
104204
+ );
104205
+ if (yes) {
104206
+ const shell = basename5(env.SHELL ?? "");
104207
+ const rc = shell === "zsh" ? rcPaths[0] : shell === "bash" ? rcPaths[1] : await readOptional(rcPaths[0]) !== void 0 ? rcPaths[0] : rcPaths[1];
104208
+ await writeConfig(rc, aliasContents(await readOptional(rc), tools));
104209
+ alias = `Aliases: installed in ${rc}. Open a new terminal or run: source ${rc}`;
104210
+ }
104211
+ }
104212
+ }
104213
+ let compute;
104214
+ try {
104215
+ const usage = await (dependencies.router?.routerUsage ?? routerUsage)(
104216
+ routerDeps2(target, dependencies)
104217
+ );
104218
+ const reset = new Date(usage.compute.resetsAt);
104219
+ if (!Number.isFinite(reset.getTime())) throw new Error("invalid reset time");
104220
+ compute = `$${usage.compute.remainingTodayUsd.toFixed(2)} left today (resets ${reset.toISOString().slice(11, 16)} UTC)`;
104221
+ } catch (error61) {
104222
+ compute = `Compute today: unavailable (${error61 instanceof RouterClientError ? error61.code : "request failed"})`;
104223
+ }
104224
+ const start = `Start with \`vapi ${tools.includes("claude") ? "claude" : "codex"}\``;
104225
+ if (json2)
104226
+ io.stdout(
104227
+ JSON.stringify({ command: "code install", installed, skipped: skipped2, alias, compute, start })
104228
+ );
104229
+ else {
104230
+ skipped2.forEach(io.stderr);
104231
+ [...installed, alias, compute, start].forEach(io.stdout);
104232
+ }
104233
+ return 0;
104234
+ }
104235
+
104236
+ // src/code-launch.ts
104237
+ import { spawn as spawn4 } from "node:child_process";
104238
+ import { readFile as readFile29 } from "node:fs/promises";
104239
+ import { constants as constants3, homedir as homedir4 } from "node:os";
104240
+ var CLAUDE_MODELS = {
104241
+ sonnet: "venice/claude-sonnet-5-5",
104242
+ opus: "venice/claude-opus-5-5",
104243
+ haiku: "venice/claude-haiku-5-5"
104244
+ };
104245
+ async function claudeCommand(argv, json2, io, dependencies) {
104246
+ return await launch("claude", argv, json2, io, dependencies);
104247
+ }
104248
+ async function codexCommand(argv, json2, io, dependencies) {
104249
+ return await launch("codex", argv, json2, io, dependencies);
104250
+ }
104251
+ function parseLaunch(argv) {
104252
+ const result = { own: false, vapi: false, balance: false, forwarded: [] };
104253
+ for (let index2 = 0; index2 < argv.length; index2 += 1) {
104254
+ const arg = argv[index2];
104255
+ if (arg === "--") {
104256
+ result.forwarded.push(...argv.slice(index2 + 1));
104257
+ break;
104258
+ }
104259
+ if (arg === "--own") result.own = true;
104260
+ else if (arg === "--vapi") result.vapi = true;
104261
+ else if (arg === "--use-balance") result.balance = true;
104262
+ else if (arg === "--model" || arg === "--account") {
104263
+ const value = argv[++index2];
104264
+ if (!value || value.startsWith("--")) throw new UsageError(`Expected ${arg} <value>.`);
104265
+ if (arg === "--model") result.model = value;
104266
+ else result.account = value;
104267
+ } else result.forwarded.push(arg);
104268
+ }
104269
+ if (result.own && result.vapi) throw new UsageError("--vapi and --own cannot be used together.");
104270
+ return result;
104271
+ }
104272
+ var LaunchTimeout = class extends Error {
104273
+ constructor() {
104274
+ super("timed out");
104275
+ }
104276
+ };
104277
+ async function bounded(operation, milliseconds) {
104278
+ const controller = new AbortController();
104279
+ let timer;
104280
+ try {
104281
+ return await Promise.race([
104282
+ new Promise((_resolve, reject) => {
104283
+ timer = setTimeout(() => {
104284
+ const error61 = new LaunchTimeout();
104285
+ controller.abort(error61);
104286
+ reject(error61);
104287
+ }, milliseconds);
104288
+ }),
104289
+ operation(controller.signal)
104290
+ ]);
104291
+ } finally {
104292
+ clearTimeout(timer);
104293
+ controller.abort();
104294
+ }
104295
+ }
104296
+ function abortableDeps(deps, signal) {
104297
+ const fetchImpl = deps.fetchImpl ?? createPublicFetch({ allowPrivateNetwork: false });
104298
+ return {
104299
+ ...deps,
104300
+ fetchImpl: (input2, init) => fetchImpl(input2, {
104301
+ ...init,
104302
+ signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal
104303
+ })
104304
+ };
104305
+ }
104306
+ function shortReason(error61, env, credentials) {
104307
+ if (error61 instanceof RouterClientError) {
104308
+ if (error61.code === "not_linked") return "not linked, run vapi code install";
104309
+ if (error61.code === "no_router_key") return "no Router key, run vapi code install";
104310
+ }
104311
+ let message = error61 instanceof Error ? error61.message : String(error61);
104312
+ for (const secret of [
104313
+ credentials?.apiKey,
104314
+ env.ANTHROPIC_API_KEY,
104315
+ env.ANTHROPIC_AUTH_TOKEN,
104316
+ env[VAPI_ROUTER_KEY_ENV]
104317
+ ]) {
104318
+ if (secret) message = message.replaceAll(secret, "[redacted]");
104319
+ }
104320
+ return message.replace(/\s+/gu, " ").trim().slice(0, 160) || "request failed";
104321
+ }
104322
+ async function chooseRoute(options, env, dependencies) {
104323
+ if (options.own) return { kind: "own" };
104324
+ const timeout = dependencies.code?.usageTimeoutMs ?? 4e3;
104325
+ let credentials;
104326
+ let deps;
104327
+ let balanceKeyRequired = false;
104328
+ try {
104329
+ credentials = await bounded(async (signal) => {
104330
+ const target = await targetWallet(
104331
+ { one: (name) => name === "--wallet" ? options.account : void 0 },
104332
+ dependencies,
104333
+ env.VAPI_HOME
104334
+ );
104335
+ signal.throwIfAborted();
104336
+ deps = routerDeps2(target, dependencies);
104337
+ return await (dependencies.router?.routerCredentials ?? routerCredentials)(
104338
+ abortableDeps(deps, signal)
104339
+ );
104340
+ }, timeout);
104341
+ let usage;
104342
+ try {
104343
+ usage = await bounded(
104344
+ (signal) => (dependencies.router?.routerUsage ?? routerUsage)(abortableDeps(deps, signal)),
104345
+ timeout
104346
+ );
104347
+ if (!Number.isFinite(new Date(usage.compute.resetsAt).getTime()))
104348
+ throw new Error("invalid Compute reset time");
104349
+ } catch (error61) {
104350
+ if (options.vapi) return { kind: "vapi", credentials };
104351
+ throw error61;
104352
+ }
104353
+ if (options.vapi || remaining(usage, options.balance) >= 0.5) {
104354
+ if (options.balance && usage.compute.remainingTodayUsd < 0.5 && (usage.balance?.remainingUsd ?? 0) > 0) {
104355
+ balanceKeyRequired = true;
104356
+ credentials = await bounded(
104357
+ (signal) => (dependencies.router?.routerCredentials ?? routerCredentials)(
104358
+ abortableDeps(deps, signal),
104359
+ { funding: "balance" }
104360
+ ),
104361
+ timeout
104362
+ );
104363
+ }
104364
+ return { kind: "vapi", credentials, usage };
104365
+ }
104366
+ return { kind: "own", exhausted: true };
104367
+ } catch (error61) {
104368
+ const reason = balanceKeyRequired && error61 instanceof RouterClientError && error61.code === "no_router_key" ? "no Router balance key is stored" : shortReason(error61, env, credentials);
104369
+ if (options.vapi) return { kind: "unavailable", reason };
104370
+ return { kind: "own", reason };
104371
+ }
104372
+ }
104373
+ function remaining(usage, useBalance) {
104374
+ return usage.compute.remainingTodayUsd + (useBalance ? usage.balance?.remainingUsd ?? 0 : 0);
104375
+ }
104376
+ async function launch(tool, argv, json2, io, dependencies) {
104377
+ if (json2) throw new UsageError(`vapi ${tool} is interactive and does not support --json.`);
104378
+ const options = parseLaunch(argv);
104379
+ const env = getEnvironment(dependencies);
104380
+ let binary;
104381
+ try {
104382
+ binary = await resolveBinary(tool, { ...dependencies.code, env });
104383
+ } catch (error61) {
104384
+ io.stderr(shortReason(error61, env));
104385
+ return 127;
104386
+ }
104387
+ if (binary === void 0) {
104388
+ io.stderr(
104389
+ `\`${tool}\` is not on PATH. Install ${tool === "claude" ? "Claude Code" : "Codex"} first.`
104390
+ );
104391
+ return 127;
104392
+ }
104393
+ const route = await chooseRoute(options, env, dependencies);
104394
+ if (route.kind === "unavailable") {
104395
+ io.stderr(route.reason);
104396
+ return 1;
104397
+ }
104398
+ let args = options.forwarded;
104399
+ let childEnv = env;
104400
+ const own2 = tool === "claude" ? "your own Claude subscription" : "your own Codex/ChatGPT login";
104401
+ if (route.kind === "own") {
104402
+ if (route.exhausted) io.stderr(`\u25CF Compute used up today \u2192 ${own2}`);
104403
+ else if (route.reason !== void 0) io.stderr(`\u25CF vAPI unreachable (${route.reason}) \u2192 ${own2}`);
104404
+ if (options.model !== void 0)
104405
+ args = [tool === "claude" ? "--model" : "-m", options.model, ...args];
104406
+ } else {
104407
+ const { credentials, usage } = route;
104408
+ const model = tool === "claude" ? claudeModel(options.model) : options.model ?? VAPI_CODEX_DEFAULT_MODEL;
104409
+ let status = "\u25CF vAPI Compute";
104410
+ if (usage !== void 0)
104411
+ status += ` \u2014 $${remaining(usage, options.balance).toFixed(2)} left today (resets ${new Date(usage.compute.resetsAt).toISOString().slice(11, 16)} UTC)`;
104412
+ io.stderr(`${status} \xB7 model ${model.slice(model.lastIndexOf("/") + 1)}`);
104413
+ io.stderr(
104414
+ tool === "claude" ? " Compute runs out mid-session? /exit, then: vapi claude --continue" : " Compute runs out mid-session? /quit, then: vapi codex resume --last"
104415
+ );
104416
+ if (tool === "claude") {
104417
+ childEnv = {
104418
+ ...env,
104419
+ ANTHROPIC_BASE_URL: credentials.baseURL.replace(/\/v1\/?$/u, ""),
104420
+ ANTHROPIC_AUTH_TOKEN: credentials.apiKey
104421
+ };
104422
+ delete childEnv.ANTHROPIC_API_KEY;
104423
+ if (args.some((arg) => arg === "--settings" || arg.startsWith("--settings=")))
104424
+ io.stderr("\u25CF Your --settings is passed as is; vAPI model settings were not added.");
104425
+ else
104426
+ args = [
104427
+ "--settings",
104428
+ JSON.stringify({
104429
+ env: {
104430
+ ANTHROPIC_MODEL: model,
104431
+ ANTHROPIC_DEFAULT_SONNET_MODEL: CLAUDE_MODELS.sonnet,
104432
+ ANTHROPIC_DEFAULT_OPUS_MODEL: CLAUDE_MODELS.opus,
104433
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: CLAUDE_MODELS.haiku,
104434
+ CLAUDE_CODE_MAX_RETRIES: "2"
104435
+ }
104436
+ }),
104437
+ ...args
104438
+ ];
104439
+ } else {
104440
+ childEnv = { ...env, [VAPI_ROUTER_KEY_ENV]: credentials.apiKey };
104441
+ args = [...await codexArgs(env, credentials.baseURL, options.model, dependencies), ...args];
104442
+ }
104443
+ }
104444
+ return await runChild(binary, args, childEnv, io, dependencies);
104445
+ }
104446
+ function claudeModel(model) {
104447
+ return model === void 0 ? CLAUDE_MODELS.sonnet : Object.hasOwn(CLAUDE_MODELS, model) ? CLAUDE_MODELS[model] : model;
104448
+ }
104449
+ async function codexArgs(env, baseURL, model, dependencies) {
104450
+ let contents = "";
104451
+ try {
104452
+ contents = await readFile29(
104453
+ codexConfigPath(env, dependencies.code?.homedir ?? homedir4()),
104454
+ "utf8"
104455
+ );
104456
+ } catch (error61) {
104457
+ if (!isMissingFile(error61)) throw error61;
104458
+ }
104459
+ const providerArgs = [
104460
+ "-c",
104461
+ `model_providers.${VAPI_CODEX_PROVIDER}.name="vAPI Router"`,
104462
+ "-c",
104463
+ `model_providers.${VAPI_CODEX_PROVIDER}.base_url=${JSON.stringify(baseURL)}`,
104464
+ "-c",
104465
+ `model_providers.${VAPI_CODEX_PROVIDER}.env_key="${VAPI_ROUTER_KEY_ENV}"`,
104466
+ "-c",
104467
+ `model_providers.${VAPI_CODEX_PROVIDER}.wire_api="responses"`,
104468
+ "-c",
104469
+ `model_provider="${VAPI_CODEX_PROVIDER}"`
104470
+ ];
104471
+ if (hasVapiCodexProfile(contents))
104472
+ return [
104473
+ "--profile",
104474
+ VAPI_CODEX_PROFILE,
104475
+ ...providerArgs,
104476
+ ...model === void 0 ? [] : ["-m", model]
104477
+ ];
104478
+ return [...providerArgs, "-m", model ?? VAPI_CODEX_DEFAULT_MODEL];
104479
+ }
104480
+ async function runChild(binary, args, env, io, dependencies) {
104481
+ const signals = dependencies.code?.processSignals ?? process;
104482
+ let child;
104483
+ const ignore = () => {
104484
+ };
104485
+ const forward = (signal) => () => {
104486
+ try {
104487
+ child?.kill(signal);
104488
+ } catch (error61) {
104489
+ io.stderr(shortReason(error61, env));
104490
+ }
104491
+ };
104492
+ const listeners = [
104493
+ ["SIGINT", ignore],
104494
+ ["SIGQUIT", ignore],
104495
+ ["SIGTERM", forward("SIGTERM")],
104496
+ ["SIGHUP", forward("SIGHUP")]
104497
+ ];
104498
+ try {
104499
+ for (const [signal, listener] of listeners) signals.on(signal, listener);
104500
+ return await new Promise((resolve3) => {
104501
+ let settled = false;
104502
+ const finish = (code) => {
104503
+ if (!settled) {
104504
+ settled = true;
104505
+ resolve3(code);
104506
+ }
104507
+ };
104508
+ try {
104509
+ child = (dependencies.code?.spawn ?? spawn4)(binary, args, { env, stdio: "inherit" });
104510
+ child.once("error", (error61) => {
104511
+ if (!settled) io.stderr(shortReason(error61, env));
104512
+ finish(127);
104513
+ });
104514
+ child.once(
104515
+ "exit",
104516
+ (code, signal) => finish(code ?? (signal === null ? 1 : 128 + (constants3.signals[signal] ?? 0)))
104517
+ );
104518
+ } catch (error61) {
104519
+ io.stderr(shortReason(error61, env));
104520
+ finish(127);
104521
+ }
104522
+ });
104523
+ } finally {
104524
+ for (const [signal, listener] of listeners) signals.removeListener(signal, listener);
104525
+ }
104526
+ }
104527
+
103904
104528
  // src/send.ts
103905
104529
  var SEND_USAGE = "Usage: vapi send <amount> --from <account> --to <account|owner|0x\u2026> [--network base|arc] [--resume <nonce>] [--json]";
103906
104530
  async function sendCommand(argv, json2, io, dependencies) {
@@ -104000,7 +104624,7 @@ async function sendConfig(dependencies) {
104000
104624
 
104001
104625
  // src/setup.ts
104002
104626
  import { rm as rm5 } from "node:fs/promises";
104003
- import { join as join26 } from "node:path";
104627
+ import { join as join27 } from "node:path";
104004
104628
  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.`;
104005
104629
  var VAULT_CHOICE = "Create a new vault, or restore one from a recovery phrase? [new/restore] ";
104006
104630
  async function setupCommand(argv, json2, io, dependencies) {
@@ -104030,7 +104654,7 @@ async function setupCommand(argv, json2, io, dependencies) {
104030
104654
  let changedAccount = false;
104031
104655
  let changedLink = false;
104032
104656
  let scannedAddresses;
104033
- if (!await fileExists2(join26(paths.directory, "vault.json"))) {
104657
+ if (!await fileExists2(join27(paths.directory, "vault.json"))) {
104034
104658
  const choice = await vaultChoice(dependencies);
104035
104659
  if (choice === "restore") {
104036
104660
  if (!isInteractive(dependencies)) {
@@ -104118,7 +104742,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
104118
104742
  let scannedAddresses = 0;
104119
104743
  try {
104120
104744
  const restored = await restoreVault({
104121
- path: join26(paths.directory, "vault.json"),
104745
+ path: join27(paths.directory, "vault.json"),
104122
104746
  key: key2,
104123
104747
  phrase: validatedPhrase,
104124
104748
  probe: async (address4) => await readBalance3(address4) > 0n,
@@ -104129,7 +104753,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
104129
104753
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
104130
104754
  });
104131
104755
  names = restored.accounts().map((account) => account.name);
104132
- await rm5(join26(paths.directory, "wallets.json"), { force: true });
104756
+ await rm5(join27(paths.directory, "wallets.json"), { force: true });
104133
104757
  } finally {
104134
104758
  key2.fill(0);
104135
104759
  }
@@ -104247,7 +104871,7 @@ async function withRouterError2(operation) {
104247
104871
 
104248
104872
  // src/task.ts
104249
104873
  import { randomUUID as randomUUID6 } from "node:crypto";
104250
- import { readFile as readFile28 } from "node:fs/promises";
104874
+ import { readFile as readFile30 } from "node:fs/promises";
104251
104875
  var TASK_HELP = `Usage:
104252
104876
  vapi task search [--open] [--min <usd>] [--tab trending|new|closing|paid] [--limit <n>] [--json]
104253
104877
  vapi task show <id> [--account <name>] [--json]
@@ -104583,7 +105207,7 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104583
105207
  if (maxAwards !== void 0 && maxAwards > TASK_LIMITS.maxAwardsMax)
104584
105208
  throw new UsageError("--max-awards must be between 1 and 50.");
104585
105209
  if (parsed.one("--webhook") !== void 0) httpsUrl2(parsed.one("--webhook"), "--webhook");
104586
- const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile28(briefPath, "utf8");
105210
+ const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile30(briefPath, "utf8");
104587
105211
  const input2 = {
104588
105212
  title: title.trim(),
104589
105213
  description: brief.trim(),
@@ -105169,13 +105793,13 @@ async function watchTask(id2, parsed, json2, io, dependencies, now) {
105169
105793
  }
105170
105794
  }
105171
105795
  cursor2 = Math.max(cursor2, page.nextAfter, ...events.map((event) => event.sequence));
105172
- const remaining = deadline - clock().getTime();
105173
- if (remaining <= 0)
105796
+ const remaining2 = deadline - clock().getTime();
105797
+ if (remaining2 <= 0)
105174
105798
  throw new TaskCommandError(
105175
105799
  "timeout",
105176
105800
  `Task watch timed out after ${parsed.one("--timeout") ?? "7d"}.`
105177
105801
  );
105178
- await context.sleep(Math.min(interval, remaining));
105802
+ await context.sleep(Math.min(interval, remaining2));
105179
105803
  }
105180
105804
  }
105181
105805
  function expandDeliveryFiles(argv) {
@@ -106261,7 +106885,7 @@ async function referencedSleep(milliseconds, signal) {
106261
106885
  }
106262
106886
 
106263
106887
  // src/vault.ts
106264
- import { join as join27 } from "node:path";
106888
+ import { join as join28 } from "node:path";
106265
106889
  var VAULT_USAGE = "Usage: vapi vault protect|unprotect|lock|unlock|status [--json]";
106266
106890
  var RESTORE_USAGE = "Usage: vapi restore [--accounts <n> | --from-owner [--owner <0x\u2026>]] [--json]";
106267
106891
  var LEGACY_PASSWORD_NOTICE = "VAPI_KEYSTORE_PASSWORD is deprecated for vault passwords; use VAPI_VAULT_PASSWORD instead.";
@@ -106305,7 +106929,7 @@ async function restoreCommand(argv, json2, io, dependencies) {
106305
106929
  }
106306
106930
  const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
106307
106931
  const paths = getVapiPaths();
106308
- const path = join27(paths.directory, "vault.json");
106932
+ const path = join28(paths.directory, "vault.json");
106309
106933
  if (await fileExists2(path)) {
106310
106934
  throw new Error(
106311
106935
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
@@ -106462,7 +107086,7 @@ function requireNoArguments(argv) {
106462
107086
  parseArguments(argv, { valueOptions: /* @__PURE__ */ new Set(), maximumPositionals: 0 });
106463
107087
  }
106464
107088
  function vaultPath() {
106465
- return join27(getVapiPaths().directory, "vault.json");
107089
+ return join28(getVapiPaths().directory, "vault.json");
106466
107090
  }
106467
107091
  function quietIo(io) {
106468
107092
  return { stdout: () => void 0, stderr: io.stderr };
@@ -106530,6 +107154,10 @@ Usage:
106530
107154
  vapi login [--account <name>] [--label <name>] [--publish] [--no-browser] [--json]
106531
107155
  vapi logout [--account <name>] [--json]
106532
107156
  vapi whoami [--account <name>] [--json]
107157
+ vapi claude [--vapi|--own] [--model <m>] [--use-balance] [--account <name>] [<claude args>...]
107158
+ vapi codex [--vapi|--own] [--model <id>] [--use-balance] [--account <name>] [<codex args>...]
107159
+ vapi code install [--yes] [--no-alias] [--account <name>] [--json]
107160
+ vapi code uninstall [--json]
106533
107161
  vapi router models [--account <name>] [--json]
106534
107162
  vapi router usage [--account <name>] [--json]
106535
107163
  vapi router chat --model <id> [--system <text>] [--max-tokens <n>] "<prompt>" [--account <name>] [--json]
@@ -106749,6 +107377,8 @@ async function confirmWalletName(name, prompt, refusal, dependencies) {
106749
107377
  if (typed.trim() !== name) throw new KeystoreError(refusal);
106750
107378
  }
106751
107379
  async function runCli(argv = process.argv.slice(2), io = processIo, dependencies = {}) {
107380
+ const firstArgument = argv.find((argument) => argument !== "--json");
107381
+ const codeLaunch = firstArgument === "claude" || firstArgument === "codex";
106752
107382
  let json2 = argv.includes("--json");
106753
107383
  const taskInvocation = argv.find((argument) => argument !== "--json") === "task";
106754
107384
  const resultFile = runResultFile(argv);
@@ -106757,15 +107387,15 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106757
107387
  stderr: (message) => io.stderr(redactDetachedRunText(message, getEnvironment(dependencies)))
106758
107388
  };
106759
107389
  try {
106760
- const parsedInvocation = removeJsonFlag(argv);
107390
+ const parsedInvocation = removeJsonFlag(argv, codeLaunch);
106761
107391
  json2 = parsedInvocation.json;
106762
- const hasWalletOption = parsedInvocation.args.includes(WALLET_OPTION5);
107392
+ const hasWalletOption = !codeLaunch && parsedInvocation.args.includes(WALLET_OPTION5);
106763
107393
  const hasAccountOption = parsedInvocation.args.includes(ACCOUNT_OPTION2);
106764
107394
  if (hasWalletOption && hasAccountOption) {
106765
107395
  throw new UsageError("--wallet and --account cannot be used together.");
106766
107396
  }
106767
107397
  if (hasWalletOption) io.stderr(WALLET_OPTION_DEPRECATION);
106768
- const args = parsedInvocation.args.map(
107398
+ const args = codeLaunch ? parsedInvocation.args : parsedInvocation.args.map(
106769
107399
  (argument) => argument === WALLET_OPTION5 ? ACCOUNT_OPTION2 : argument
106770
107400
  );
106771
107401
  const command = args[0];
@@ -106861,6 +107491,15 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106861
107491
  await whoamiCommand(args.slice(1), json2, io, dependencies);
106862
107492
  exitCode = 0;
106863
107493
  break;
107494
+ case "claude":
107495
+ exitCode = await claudeCommand(args.slice(1), json2, io, dependencies);
107496
+ break;
107497
+ case "codex":
107498
+ exitCode = await codexCommand(args.slice(1), json2, io, dependencies);
107499
+ break;
107500
+ case "code":
107501
+ exitCode = await codeCommand(args.slice(1), json2, io, dependencies);
107502
+ break;
106864
107503
  case "router":
106865
107504
  await routerCommand(args.slice(1), json2, io, dependencies);
106866
107505
  exitCode = 0;
@@ -106898,7 +107537,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106898
107537
  break;
106899
107538
  case "unlock":
106900
107539
  io.stderr("vapi unlock is now vapi vault unlock; the old name works for one release.");
106901
- if (await fileExists2(join28(getVapiPaths().directory, "vault.json"))) {
107540
+ if (await fileExists2(join29(getVapiPaths().directory, "vault.json"))) {
106902
107541
  parseArguments(args.slice(1), {
106903
107542
  valueOptions: /* @__PURE__ */ new Set([WALLET_OPTION5]),
106904
107543
  maximumPositionals: 0
@@ -107104,7 +107743,7 @@ async function initCommand(argv, json2, io, dependencies) {
107104
107743
  address: account.address,
107105
107744
  accounts,
107106
107745
  config: paths.config,
107107
- vault: join28(paths.directory, "vault.json"),
107746
+ vault: join29(paths.directory, "vault.json"),
107108
107747
  ...configRewrites.length > 0 ? { configRewrites } : {},
107109
107748
  custody: "self",
107110
107749
  warning: CUSTODY_NOTICE,
@@ -107243,7 +107882,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
107243
107882
  const result = {
107244
107883
  address: account.address,
107245
107884
  ...account.solana ? { solanaAddress: account.solana.address } : {},
107246
- vault: join28(paths.directory, "vault.json"),
107885
+ vault: join29(paths.directory, "vault.json"),
107247
107886
  ...label === void 0 ? {} : { label },
107248
107887
  spendCaps: created.entry.spendCaps,
107249
107888
  isDefault,
@@ -107283,7 +107922,7 @@ function formatCaps2(caps) {
107283
107922
  function walletListResult(store, wallets, unlocked) {
107284
107923
  return {
107285
107924
  default: store.defaultName ?? null,
107286
- vault: join28(store.home, "vault.json"),
107925
+ vault: join29(store.home, "vault.json"),
107287
107926
  wallets: wallets.map((wallet) => ({
107288
107927
  name: wallet.name,
107289
107928
  ...wallet.address === void 0 ? {} : { address: wallet.address },
@@ -108299,7 +108938,7 @@ function sameOrigin2(left, right) {
108299
108938
  function noApiKeyMessage(baseUrl) {
108300
108939
  return [
108301
108940
  "No vAPI API key on this machine.",
108302
- `Create one in the console at ${listingsUrl(baseUrl, API_KEY_CONSOLE_PATH).href}, then store it with vapi auth set-key.`,
108941
+ `Create one in the console at ${apiKeyConsoleUrl(baseUrl).href}, then store it with vapi auth set-key.`,
108303
108942
  `In CI, set ${API_KEY_ENV} instead.`
108304
108943
  ].join("\n");
108305
108944
  }
@@ -108556,7 +109195,7 @@ function formatClaimed(origin, claimed) {
108556
109195
  }
108557
109196
  var EXPORT_KEY_WARNING = "Anyone with this key can spend the wallet. Never paste it into a website or chat.";
108558
109197
  async function deviceVaultKey2(store, dependencies) {
108559
- const path = join28(store.home, "vault.json");
109198
+ const path = join29(store.home, "vault.json");
108560
109199
  const metadata = await readVaultFileUnlocked(path);
108561
109200
  const secrets = getSecretStore(dependencies);
108562
109201
  const key2 = metadata.protected ? await unlockProtectedVault({
@@ -108649,7 +109288,7 @@ async function backupCommand(argv, json2, io, dependencies) {
108649
109288
  const target = await targetWallet(parsed, dependencies);
108650
109289
  const vaultAccount = await target.store.hasVaultAccount(target.name);
108651
109290
  if (vaultAccount) {
108652
- const vault = await readVaultFileUnlocked(join28(target.store.home, "vault.json"));
109291
+ const vault = await readVaultFileUnlocked(join29(target.store.home, "vault.json"));
108653
109292
  if (vault.accounts.some((account) => account.name === target.name && account.kind === "imported")) {
108654
109293
  throw new KeystoreError(
108655
109294
  `Account ${target.name} was imported and is not recoverable from the vault phrase. Back it up with vapi export-key --account ${target.name}.`
@@ -108726,7 +109365,7 @@ async function importCommand(argv, json2, io, dependencies) {
108726
109365
  const existed = store.has(name);
108727
109366
  if (existed && !parsed.has("--replace")) {
108728
109367
  const address4 = await store.readAddress(name);
108729
- const location = await store.hasVaultAccount(name) ? join28(store.home, "vault.json") : store.pathFor(name);
109368
+ const location = await store.hasVaultAccount(name) ? join29(store.home, "vault.json") : store.pathFor(name);
108730
109369
  throw new Error(
108731
109370
  [
108732
109371
  `Wallet ${name} already exists at ${location}.`,
@@ -108762,7 +109401,7 @@ async function importCommand(argv, json2, io, dependencies) {
108762
109401
  const result = {
108763
109402
  address: account.address,
108764
109403
  ...account.solana ? { solanaAddress: account.solana.address } : {},
108765
- vault: join28(paths.directory, "vault.json"),
109404
+ vault: join29(paths.directory, "vault.json"),
108766
109405
  ...previousKeystore ? { previousKeystore } : {},
108767
109406
  message: "Wallet imported. Its encrypted key stays on this machine."
108768
109407
  };
@@ -109095,7 +109734,7 @@ function formatFund(address4, url2, opened) {
109095
109734
  function openInBrowser(url2) {
109096
109735
  const opener = process.platform === "darwin" ? { command: "open", args: [url2] } : process.platform === "win32" ? { command: "cmd", args: ["/c", "start", "", url2] } : { command: "xdg-open", args: [url2] };
109097
109736
  try {
109098
- const child = spawn4(opener.command, opener.args, { stdio: "ignore", detached: true });
109737
+ const child = spawn5(opener.command, opener.args, { stdio: "ignore", detached: true });
109099
109738
  child.on("error", () => void 0);
109100
109739
  child.unref();
109101
109740
  return true;
@@ -109287,11 +109926,13 @@ function parseArguments(argv, spec) {
109287
109926
  has: (name) => flags.has(name)
109288
109927
  };
109289
109928
  }
109290
- function removeJsonFlag(argv) {
109929
+ function removeJsonFlag(argv, preserveForwarded = false) {
109291
109930
  let json2 = false;
109292
109931
  const args = [];
109932
+ let forwarding = false;
109293
109933
  for (const argument of argv) {
109294
- if (argument !== "--json") {
109934
+ if (preserveForwarded && argument === "--") forwarding = true;
109935
+ if (argument !== "--json" || forwarding) {
109295
109936
  args.push(argument);
109296
109937
  continue;
109297
109938
  }
@@ -109407,7 +110048,7 @@ async function runCliWithUpdateCheck(argv = process.argv.slice(2), io = {
109407
110048
  async function checkForUpdate(options = {}) {
109408
110049
  const env = options.env ?? process.env;
109409
110050
  const argv = options.argv ?? process.argv.slice(2);
109410
- if (!(options.stderrIsTTY ?? process.stderr.isTTY) || argv.includes("--json") || argv[0] === "mcp" && argv[1] !== "install" || env.VAPI_NO_UPDATE_CHECK === "1" || env.CI !== void 0) {
110051
+ if (!(options.stderrIsTTY ?? process.stderr.isTTY) || argv.includes("--json") || argv[0] === "claude" || argv[0] === "codex" || argv[0] === "mcp" && argv[1] !== "install" || env.VAPI_NO_UPDATE_CHECK === "1" || env.CI !== void 0) {
109411
110052
  return void 0;
109412
110053
  }
109413
110054
  const controller = new AbortController();
@@ -109434,7 +110075,7 @@ async function latestNotice(options, env, signal) {
109434
110075
  const now = (options.nowMs ?? Date.now)();
109435
110076
  let cached2;
109436
110077
  try {
109437
- const value = JSON.parse(await readFile29(paths.updateCheck, "utf8"));
110078
+ const value = JSON.parse(await readFile31(paths.updateCheck, "utf8"));
109438
110079
  if (isRecord13(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
109439
110080
  cached2 = { checkedAt: value.checkedAt, latest: value.latest };
109440
110081
  }
@@ -109443,9 +110084,9 @@ async function latestNotice(options, env, signal) {
109443
110084
  signal.throwIfAborted();
109444
110085
  let latest = cached2?.latest ?? CLI_VERSION;
109445
110086
  if (cached2 === void 0 || now - cached2.checkedAt >= CHECK_INTERVAL_MS || now < cached2.checkedAt) {
109446
- await mkdir21(paths.directory, { recursive: true });
110087
+ await mkdir22(paths.directory, { recursive: true });
109447
110088
  signal.throwIfAborted();
109448
- await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
110089
+ await writeFile13(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
109449
110090
  signal.throwIfAborted();
109450
110091
  const fetchImpl = options.fetchImpl ?? createPublicFetch({
109451
110092
  allowPrivateNetwork: false,
@@ -109472,7 +110113,7 @@ async function latestNotice(options, env, signal) {
109472
110113
  return void 0;
109473
110114
  }
109474
110115
  latest = body.version;
109475
- await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
110116
+ await writeFile13(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
109476
110117
  }
109477
110118
  signal.throwIfAborted();
109478
110119
  return isNewerVersion(latest, CLI_VERSION) ? `vapi-network ${latest} is available (you have ${CLI_VERSION}). Update: npm i -g vapi-network@latest` : void 0;
@@ -109517,12 +110158,12 @@ function isNewerVersion(latest, current) {
109517
110158
  // src/main-module.ts
109518
110159
  import { realpathSync as realpathSync2 } from "node:fs";
109519
110160
  import { pathToFileURL } from "node:url";
109520
- function isMainModule(entry, moduleUrl, realpath = realpathSync2) {
110161
+ function isMainModule(entry, moduleUrl, realpath2 = realpathSync2) {
109521
110162
  if (!entry) {
109522
110163
  return false;
109523
110164
  }
109524
110165
  try {
109525
- return pathToFileURL(realpath(entry)).href === moduleUrl;
110166
+ return pathToFileURL(realpath2(entry)).href === moduleUrl;
109526
110167
  } catch {
109527
110168
  return false;
109528
110169
  }