@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/index.js CHANGED
@@ -10116,9 +10116,9 @@ var init_call = __esm({
10116
10116
  });
10117
10117
 
10118
10118
  // src/cli.ts
10119
- import { spawn as spawn4 } from "node:child_process";
10119
+ import { spawn as spawn5 } from "node:child_process";
10120
10120
  import { stat as stat16 } from "node:fs/promises";
10121
- import { join as join28 } from "node:path";
10121
+ import { join as join29 } 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
@@ -70103,13 +70103,13 @@ async function withAccountMovementLocks(home, accounts, timeoutMs, operation) {
70103
70103
  );
70104
70104
  }
70105
70105
  async function acquireAccountMovementLocks(home, accounts, timeoutMs, operation) {
70106
- const [account, ...remaining] = accounts;
70106
+ const [account, ...remaining2] = accounts;
70107
70107
  if (account === void 0) return await operation();
70108
70108
  return await withAccountMovementLock(
70109
70109
  home,
70110
70110
  account,
70111
70111
  timeoutMs,
70112
- async () => acquireAccountMovementLocks(home, remaining, timeoutMs, operation)
70112
+ async () => acquireAccountMovementLocks(home, remaining2, timeoutMs, operation)
70113
70113
  );
70114
70114
  }
70115
70115
  async function removeStaleLock2(path) {
@@ -70182,7 +70182,7 @@ var POWERSHELL_MISSING = [
70182
70182
  ].join(" ");
70183
70183
  function secretStore(options = {}) {
70184
70184
  const platform2 = options.platform ?? process.platform;
70185
- const run = options.run ?? spawnRunner;
70185
+ const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
70186
70186
  const env = options.env ?? process.env;
70187
70187
  const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
70188
70188
  if (platform2 === "darwin") return keychainStore(platform2, run);
@@ -70376,6 +70376,7 @@ function windowsDataProtectionStore(platform2, run, env, installed) {
70376
70376
  ].join("\n");
70377
70377
  const execute = async (script2) => {
70378
70378
  const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
70379
+
70379
70380
  `);
70380
70381
  requirePowerShell(result);
70381
70382
  return result;
@@ -70538,17 +70539,25 @@ function binaryInstalled(file2, env) {
70538
70539
  if (isAbsolute(file2) || win32.isAbsolute(file2)) return existsSync(file2);
70539
70540
  return (env.PATH ?? "").split(delimiter).some((directory) => existsSync(join6(directory, file2)));
70540
70541
  }
70542
+ var SAFE_FAILURE_DETAILS = [
70543
+ "Cannot autolaunch D-Bus without X11 $DISPLAY",
70544
+ "Cannot autolaunch D-Bus",
70545
+ "The name org.freedesktop.secrets was not provided by any .service files",
70546
+ "Cannot create an item in a locked collection",
70547
+ "User interaction is not allowed.",
70548
+ "Access to the path is denied."
70549
+ ];
70541
70550
  function requireSuccess(result, what) {
70542
70551
  if (result.code === 0) return;
70543
- const detail = result.stderr.trim() || result.stdout.trim();
70552
+ const detail = SAFE_FAILURE_DETAILS.find((reason) => result.stderr.includes(reason));
70544
70553
  throw new KeystoreError(
70545
- `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail.length === 0 ? "" : ` ${detail}`}`
70554
+ `Could not ${what}${result.code === null ? "" : ` (exit ${result.code})`}.${detail === void 0 ? "" : ` ${detail}`}`
70546
70555
  );
70547
70556
  }
70548
70557
  function withoutTrailingNewline(value) {
70549
70558
  return value.replace(/\r?\n$/u, "");
70550
70559
  }
70551
- var spawnRunner = async (file2, args, input2) => await new Promise((resolve3) => {
70560
+ var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve3) => {
70552
70561
  let stdout = "";
70553
70562
  let stderr2 = "";
70554
70563
  let settled = false;
@@ -70558,7 +70567,7 @@ var spawnRunner = async (file2, args, input2) => await new Promise((resolve3) =>
70558
70567
  resolve3(outcome);
70559
70568
  };
70560
70569
  const child = spawn(file2, [...args], {
70561
- detached: true,
70570
+ detached: platform2 !== "win32",
70562
70571
  stdio: ["pipe", "pipe", "pipe"],
70563
70572
  windowsHide: true
70564
70573
  });
@@ -71568,7 +71577,7 @@ async function loadOrCreateDeviceKey(args) {
71568
71577
  await args.secrets.set(VAULT_KEY_ACCOUNT, key2.toString("base64"));
71569
71578
  return key2;
71570
71579
  } catch (error61) {
71571
- throw asVaultError2(error61, "Unable to load or create the device vault key.");
71580
+ throw asVaultError2(error61, deviceKeyFailureMessage(error61, args.secrets.platform));
71572
71581
  }
71573
71582
  });
71574
71583
  }
@@ -71826,6 +71835,12 @@ function parseJson(value) {
71826
71835
  function asVaultError2(error61, message) {
71827
71836
  return error61 instanceof VaultError ? error61 : new VaultError("corrupt", message, { cause: error61 });
71828
71837
  }
71838
+ 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.";
71839
+ function deviceKeyFailureMessage(error61, platform2) {
71840
+ if (!(error61 instanceof KeystoreError)) return "Unable to load or create the device vault key.";
71841
+ const detail = `Unable to load or create the device vault key: ${error61.message.replace(/\.$/u, "")}.`;
71842
+ return platform2 === "linux" ? `${detail} ${HEADLESS_LINUX_HINT}` : detail;
71843
+ }
71829
71844
 
71830
71845
  // ../core/src/vault-migrate.ts
71831
71846
  import {
@@ -72174,6 +72189,17 @@ var WalletStore = class _WalletStore {
72174
72189
  );
72175
72190
  return account?.address ?? (await readKeystoreSummary(this.pathFor(target))).address;
72176
72191
  }
72192
+ /**
72193
+ * Creates the vault without deriving an account, for apps that create every
72194
+ * account by name. Refuses when a vault already exists in this home.
72195
+ */
72196
+ async createEmptyVault() {
72197
+ if (await this.readVaultUnlocked() !== void 0) {
72198
+ throw new KeystoreError("A vault already exists in this home.");
72199
+ }
72200
+ await this.openVault({ create: true });
72201
+ this.dropVaultCache();
72202
+ }
72177
72203
  async create(name, passphrase, options = {}) {
72178
72204
  void passphrase;
72179
72205
  void options.enableSolana;
@@ -73054,11 +73080,11 @@ function accountChangeBusyError(account, command) {
73054
73080
  );
73055
73081
  }
73056
73082
  async function withAccountMutationLocks(home, accounts, command, operation) {
73057
- const [account, ...remaining] = [...new Set(accounts)].sort();
73083
+ const [account, ...remaining2] = [...new Set(accounts)].sort();
73058
73084
  if (account === void 0) return await operation();
73059
73085
  return await withFileLock(
73060
73086
  join8(home, `.account-${account}.lock`),
73061
- async () => await withAccountMutationLocks(home, remaining, command, operation),
73087
+ async () => await withAccountMutationLocks(home, remaining2, command, operation),
73062
73088
  {
73063
73089
  lockedMessage: `Account ${account} is busy with another account change. Wait for it to finish, then retry ${command}.`
73064
73090
  }
@@ -73866,8 +73892,8 @@ async function escrowFundingDayRemainingAtomic(input2) {
73866
73892
  const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now);
73867
73893
  const row = rows.find((candidate) => candidate.wallet === input2.wallet);
73868
73894
  const reserved = input2.reservationId ? row?.reservations?.find((candidate) => candidate.id === input2.reservationId) : void 0;
73869
- const remaining = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
73870
- return remaining > 0n ? remaining : 0n;
73895
+ const remaining2 = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
73896
+ return remaining2 > 0n ? remaining2 : 0n;
73871
73897
  }
73872
73898
  async function taskReservedAtomic(input2) {
73873
73899
  const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now, true);
@@ -75207,13 +75233,13 @@ function splitMovementPlanAtRelayLimit(plan) {
75207
75233
  const legs = plan.legs.flatMap((leg) => {
75208
75234
  const purpose = leg.purpose ?? "send";
75209
75235
  const split2 = purpose === "sweep" || plan.reason === "send" && plan.treasury !== void 0 && leg.to === plan.treasury;
75210
- let remaining = parseUsdCents(leg.amountUsd);
75211
- if (!split2 || remaining <= maximumCents) return [leg];
75236
+ let remaining2 = parseUsdCents(leg.amountUsd);
75237
+ if (!split2 || remaining2 <= maximumCents) return [leg];
75212
75238
  const parts = [];
75213
- while (remaining > 0n) {
75214
- const cents = remaining > maximumCents ? maximumCents : remaining;
75239
+ while (remaining2 > 0n) {
75240
+ const cents = remaining2 > maximumCents ? maximumCents : remaining2;
75215
75241
  parts.push({ ...leg, amountUsd: formatUsdCents(cents) });
75216
- remaining -= cents;
75242
+ remaining2 -= cents;
75217
75243
  }
75218
75244
  return parts;
75219
75245
  });
@@ -76089,13 +76115,13 @@ async function withMovementLock(home, from16, timeoutMs, operation) {
76089
76115
  }
76090
76116
  }
76091
76117
  async function withMovementLocks(home, senders, timeoutMs, operation) {
76092
- const [sender, ...remaining] = senders;
76118
+ const [sender, ...remaining2] = senders;
76093
76119
  if (sender === void 0) return await operation();
76094
76120
  return await withMovementLock(
76095
76121
  home,
76096
76122
  sender,
76097
76123
  timeoutMs,
76098
- async () => withMovementLocks(home, remaining, timeoutMs, operation)
76124
+ async () => withMovementLocks(home, remaining2, timeoutMs, operation)
76099
76125
  );
76100
76126
  }
76101
76127
  async function assertNoPendingCeilingSweep(deps, senders) {
@@ -76902,11 +76928,11 @@ function planTargets(input2) {
76902
76928
  function splitCandidateAtRelayMaximum(candidate, relayMaxAtomic) {
76903
76929
  const maximumCents = relayMaxAtomic / 10000n;
76904
76930
  const legs = [];
76905
- let remaining = candidate.cents;
76906
- while (remaining > 0n) {
76907
- const cents = remaining > maximumCents ? maximumCents : remaining;
76931
+ let remaining2 = candidate.cents;
76932
+ while (remaining2 > 0n) {
76933
+ const cents = remaining2 > maximumCents ? maximumCents : remaining2;
76908
76934
  legs.push(allocationLeg(candidate.from, candidate.to, cents, candidate.purpose));
76909
- remaining -= cents;
76935
+ remaining2 -= cents;
76910
76936
  }
76911
76937
  return legs;
76912
76938
  }
@@ -77741,7 +77767,7 @@ function createRunBudget(args) {
77741
77767
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
77742
77768
  import { arch, platform, release } from "node:os";
77743
77769
  import { join as join13 } from "node:path";
77744
- var VAPI_CLIENT_VERSION = "0.11.0";
77770
+ var VAPI_CLIENT_VERSION = "0.12.1";
77745
77771
  async function createSupportReport(options) {
77746
77772
  const message = options.message.trim();
77747
77773
  if (!message) throw new Error("Support report message must not be empty.");
@@ -79133,8 +79159,15 @@ async function ownerStake(deps) {
79133
79159
  stakeUrl: parsed.data.stakeUrl
79134
79160
  };
79135
79161
  }
79136
- async function routerCredentials(deps) {
79137
- const { routerBaseUrl, routerKey } = await routerCredentialSnapshot(deps);
79162
+ async function routerCredentials(deps, options = {}) {
79163
+ const credentials = options.funding === "balance" ? await routerBalanceCredentialSnapshot(deps) : await routerCredentialSnapshot(deps);
79164
+ if (credentials === void 0) {
79165
+ throw new RouterClientError(
79166
+ "no_router_key",
79167
+ "No Router balance key is stored for this wallet."
79168
+ );
79169
+ }
79170
+ const { routerBaseUrl, routerKey } = credentials;
79138
79171
  return { baseURL: `${routerBaseUrl}/v1`, apiKey: routerKey };
79139
79172
  }
79140
79173
  async function routerCredentialSnapshot(deps) {
@@ -82358,10 +82391,10 @@ async function waitForMilestone(client, input2) {
82358
82391
  return { reached, milestone, polls, elapsedMs: now().getTime() - started };
82359
82392
  }
82360
82393
  for (; ; ) {
82361
- const remaining = deadline - now().getTime();
82362
- if (remaining <= 0) return result(false);
82394
+ const remaining2 = deadline - now().getTime();
82395
+ if (remaining2 <= 0) return result(false);
82363
82396
  const controller = new AbortController();
82364
- const timer = setTimeout(() => controller.abort(), remaining);
82397
+ const timer = setTimeout(() => controller.abort(), remaining2);
82365
82398
  let response;
82366
82399
  polls++;
82367
82400
  try {
@@ -83025,7 +83058,7 @@ async function feeTask(input2, action) {
83025
83058
  );
83026
83059
  let approvalGranted = input2.approval !== void 0 && "granted" in input2.approval && input2.approval.granted;
83027
83060
  const checkPolicy = async (reservationId) => {
83028
- const remaining = await escrowFundingDayRemainingAtomic({
83061
+ const remaining2 = await escrowFundingDayRemainingAtomic({
83029
83062
  caps: input2.caps,
83030
83063
  ledgerPath: input2.ledgerPath,
83031
83064
  wallet: input2.wallet,
@@ -83042,13 +83075,13 @@ async function feeTask(input2, action) {
83042
83075
  const maxPerTaskAtomic = policyAtomic(input2.policy.maxPerTaskUsd);
83043
83076
  if (feeAtomic > maxPerTaskAtomic || taskReserved + feeAtomic > maxPerTaskAtomic)
83044
83077
  return { outcome: "refused", reason: "policy.perTask", money: money2, disputeFee: fee };
83045
- if (feeAtomic > remaining)
83078
+ if (feeAtomic > remaining2)
83046
83079
  return { outcome: "refused", reason: "policy.perDay", money: money2, disputeFee: fee };
83047
83080
  if (feeAtomic > policyAtomic(input2.policy.approveAboveUsd) && !approvalGranted) {
83048
83081
  if (input2.approval && "ask" in input2.approval) {
83049
83082
  approvalGranted = await input2.approval.ask({
83050
83083
  money: money2,
83051
- dayRemainingUsd: Number(formatBaseUnitsUsd(remaining))
83084
+ dayRemainingUsd: Number(formatBaseUnitsUsd(remaining2))
83052
83085
  });
83053
83086
  if (!approvalGranted) return { outcome: "declined", money: money2, disputeFee: fee };
83054
83087
  } else return { outcome: "approval_needed", money: money2, disputeFee: fee };
@@ -91564,8 +91597,8 @@ async function memberBudgetAtomic(account, configured, deps) {
91564
91597
  deps.now?.() ?? /* @__PURE__ */ new Date(),
91565
91598
  account
91566
91599
  );
91567
- const remaining = BigInt(caps.perDayAtomic) - BigInt(ledger.spentAtomic);
91568
- return remaining < 0n ? 0n : remaining;
91600
+ const remaining2 = BigInt(caps.perDayAtomic) - BigInt(ledger.spentAtomic);
91601
+ return remaining2 < 0n ? 0n : remaining2;
91569
91602
  }
91570
91603
  function withoutTreasuryGrants(profile) {
91571
91604
  return {
@@ -93560,9 +93593,9 @@ async function watchEvents(ctx, input2, now, sleep, deadline, signal, progress)
93560
93593
  const reached = input2.until !== void 0 && next.events.some((event) => taskStateMatches(input2.until, taskEventState(event)));
93561
93594
  if (next.events.length || reached)
93562
93595
  return { ...next, ...reached ? { reached: input2.until } : {}, timedOut: false };
93563
- const remaining = deadline - now().getTime();
93564
- if (remaining <= 0) return { ...next, timedOut: true };
93565
- await sleep(Math.min(TASK_LIMITS.watchIntervalMinMs, remaining), signal);
93596
+ const remaining2 = deadline - now().getTime();
93597
+ if (remaining2 <= 0) return { ...next, timedOut: true };
93598
+ await sleep(Math.min(TASK_LIMITS.watchIntervalMinMs, remaining2), signal);
93566
93599
  if (now().getTime() >= deadline)
93567
93600
  return { events: [], nextCursor: progress.cursor, timedOut: true };
93568
93601
  }
@@ -94605,9 +94638,15 @@ var VapiMcpServer = class {
94605
94638
  return tool.deprecatedReplacement ? withDeprecation(result, tool.deprecatedReplacement) : result;
94606
94639
  }
94607
94640
  }
94608
- connectStdio() {
94641
+ #output = process.stdout;
94642
+ /**
94643
+ * Serves JSON-RPC lines from `input` and answers on `output`. The desktop
94644
+ * app hands in a socket; the CLI hands in stdio through connectStdio().
94645
+ */
94646
+ connect(input2, output4) {
94609
94647
  if (this.#stdio) return;
94610
- this.#stdio = createInterface({ input: process.stdin, crlfDelay: Infinity });
94648
+ this.#output = output4;
94649
+ this.#stdio = createInterface({ input: input2, crlfDelay: Infinity });
94611
94650
  this.#stdio.on("line", (line) => {
94612
94651
  void this.#handleLine(line);
94613
94652
  });
@@ -94616,6 +94655,9 @@ var VapiMcpServer = class {
94616
94655
  this.#onClose?.();
94617
94656
  });
94618
94657
  }
94658
+ connectStdio() {
94659
+ this.connect(process.stdin, process.stdout);
94660
+ }
94619
94661
  async close() {
94620
94662
  this.#stdio?.close();
94621
94663
  this.#stdio = void 0;
@@ -94696,7 +94738,7 @@ var VapiMcpServer = class {
94696
94738
  }
94697
94739
  }
94698
94740
  #write(message) {
94699
- process.stdout.write(`${JSON.stringify(message)}
94741
+ this.#output.write(`${JSON.stringify(message)}
94700
94742
  `);
94701
94743
  }
94702
94744
  };
@@ -95706,7 +95748,12 @@ var PROBE_MODES = ["origin", "endpoint", "openapi"];
95706
95748
  var PAYOUT_CHAIN_ID = "eip155:8453";
95707
95749
  var PAYOUT_STATEMENT = "Confirm this wallet receives vAPI Call payouts";
95708
95750
  var CLAIM_STATEMENT_PREFIX = "Claim the vAPI Call listings served from";
95709
- var API_KEY_CONSOLE_PATH = "/account";
95751
+ function apiKeyConsoleUrl(baseUrl) {
95752
+ const url2 = listingsUrl(baseUrl, "/connect");
95753
+ url2.search = "advanced=keys";
95754
+ url2.hash = "api-keys";
95755
+ return url2;
95756
+ }
95710
95757
  var RegistryApiError = class extends Error {
95711
95758
  constructor(status, message, body) {
95712
95759
  super(message);
@@ -95866,7 +95913,7 @@ async function registryError(response, baseUrl) {
95866
95913
  [
95867
95914
  "The vAPI API key was rejected.",
95868
95915
  detail,
95869
- `Create a key in the console at ${listingsUrl(baseUrl, API_KEY_CONSOLE_PATH).href} and store it with vapi auth set-key.`
95916
+ `Create a key in the console at ${apiKeyConsoleUrl(baseUrl).href} and store it with vapi auth set-key.`
95870
95917
  ].filter(Boolean).join(" "),
95871
95918
  body
95872
95919
  );
@@ -98278,10 +98325,10 @@ async function awaitRelay(options) {
98278
98325
  if (!Number.isFinite(deadline)) throw new CloudBackupError("relay_expired");
98279
98326
  while (true) {
98280
98327
  if (isAborted(options.signal)) throw new CloudBackupError("relay_aborted");
98281
- const remaining = deadline - readNow(now).getTime();
98282
- if (remaining <= 0) throw new CloudBackupError("relay_expired");
98328
+ const remaining2 = deadline - readNow(now).getTime();
98329
+ if (remaining2 <= 0) throw new CloudBackupError("relay_expired");
98283
98330
  let response;
98284
- const requestDeadline = AbortSignal.timeout(Math.max(1, remaining));
98331
+ const requestDeadline = AbortSignal.timeout(Math.max(1, remaining2));
98285
98332
  const requestSignal = options.signal === void 0 ? requestDeadline : AbortSignal.any([options.signal, requestDeadline]);
98286
98333
  try {
98287
98334
  response = await (options.fetchImpl ?? publicFetch5)(
@@ -98300,7 +98347,7 @@ async function awaitRelay(options) {
98300
98347
  return await readRelayResult(response, options);
98301
98348
  }
98302
98349
  try {
98303
- await sleep(Math.min(Math.max(0, pollMs), remaining), options.signal);
98350
+ await sleep(Math.min(Math.max(0, pollMs), remaining2), options.signal);
98304
98351
  } catch {
98305
98352
  if (isAborted(options.signal)) throw new CloudBackupError("relay_aborted");
98306
98353
  }
@@ -99090,7 +99137,7 @@ async function readProcessStdin() {
99090
99137
  }
99091
99138
 
99092
99139
  // src/version.ts
99093
- var CLI_VERSION = "0.11.0";
99140
+ var CLI_VERSION = "0.12.1";
99094
99141
 
99095
99142
  // src/status.ts
99096
99143
  async function statusCommand(argv, json2, io, dependencies) {
@@ -102315,9 +102362,9 @@ async function reserveRemoteAllowance(args) {
102315
102362
  const perDayAtomic = BigInt(args.caps.perDayAtomic);
102316
102363
  const ledgerPath = getVapiPaths(args.home).ledger;
102317
102364
  const spent = BigInt((await readSpendLedger(ledgerPath, args.now, args.account)).spentAtomic);
102318
- const remaining = spent >= perDayAtomic ? 0n : perDayAtomic - spent;
102319
- const requested = args.run.budgetUsd === void 0 ? remaining : usdToAtomic(args.run.budgetUsd);
102320
- const reserved = requested < remaining ? requested : remaining;
102365
+ const remaining2 = spent >= perDayAtomic ? 0n : perDayAtomic - spent;
102366
+ const requested = args.run.budgetUsd === void 0 ? remaining2 : usdToAtomic(args.run.budgetUsd);
102367
+ const reserved = requested < remaining2 ? requested : remaining2;
102321
102368
  if (reserved === 0n) {
102322
102369
  throw new RemoteKeyRefusedError(
102323
102370
  "no_daily_allowance",
@@ -102599,12 +102646,12 @@ function createLocalRuntime(options) {
102599
102646
  const { home } = options;
102600
102647
  const entry = options.entry ?? realpathSync(process.argv[1]);
102601
102648
  const execPath = options.execPath ?? process.execPath;
102602
- const spawn5 = options.spawn ?? nodeSpawn;
102649
+ const spawn6 = options.spawn ?? nodeSpawn;
102603
102650
  const kill = options.kill ?? ((pid, signal) => process.kill(pid, signal));
102604
102651
  const processCommand = options.processCommand ?? defaultProcessCommand;
102605
102652
  const ownsProcess = (handle, pid) => processCommand(pid)?.includes(runResultPath(home, handle.runId)) === true;
102606
102653
  const closeFd = options.closeFd ?? closeSync2;
102607
- const readFile30 = options.readFile ?? nodeReadFile;
102654
+ const readFile32 = options.readFile ?? nodeReadFile;
102608
102655
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
102609
102656
  const openLog = options.openLog ?? ((path) => {
102610
102657
  mkdirSync2(runsDirectory(home), { recursive: true, mode: 448 });
@@ -102622,7 +102669,7 @@ function createLocalRuntime(options) {
102622
102669
  const logFd = openLog(logPath);
102623
102670
  let child;
102624
102671
  try {
102625
- child = spawn5(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
102672
+ child = spawn6(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
102626
102673
  detached: true,
102627
102674
  stdio: ["ignore", logFd, logFd],
102628
102675
  env: {
@@ -102659,7 +102706,7 @@ function createLocalRuntime(options) {
102659
102706
  return handle;
102660
102707
  },
102661
102708
  async status(handle) {
102662
- const result = await readResultFile(readFile30, runResultPath(home, handle.runId));
102709
+ const result = await readResultFile(readFile32, runResultPath(home, handle.runId));
102663
102710
  if (result !== void 0) return result;
102664
102711
  const pid = localPid(handle);
102665
102712
  if (pid === void 0 || handle.kind !== "local") {
@@ -102762,10 +102809,10 @@ function childArguments(member, run) {
102762
102809
  ...run.drawUsd ? ["--draw", run.drawUsd] : []
102763
102810
  ];
102764
102811
  }
102765
- async function readResultFile(readFile30, path) {
102812
+ async function readResultFile(readFile32, path) {
102766
102813
  let text;
102767
102814
  try {
102768
- text = await readFile30(path, "utf8");
102815
+ text = await readFile32(path, "utf8");
102769
102816
  } catch (error61) {
102770
102817
  if (hasCode3(error61, "ENOENT")) return void 0;
102771
102818
  return { state: "failed", detail: "unreadable result file" };
@@ -103540,6 +103587,80 @@ import { spawn as spawn3 } from "node:child_process";
103540
103587
  import { mkdir as mkdir20, readFile as readFile27, writeFile as writeFile11 } from "node:fs/promises";
103541
103588
  import { homedir as systemHomedir } from "node:os";
103542
103589
  import { dirname as dirname14, posix, win32 as win322 } from "node:path";
103590
+
103591
+ // src/toml-config.ts
103592
+ function removeTomlTables(contents, isTarget) {
103593
+ let removing = false;
103594
+ let retained = "";
103595
+ for (const { line, table } of tomlLines(contents)) {
103596
+ if (table !== void 0) removing = isTarget(tomlKeyPath(table));
103597
+ if (!removing) retained += line;
103598
+ }
103599
+ return retained;
103600
+ }
103601
+ function* tomlLines(contents) {
103602
+ let multiline;
103603
+ for (const line of contents.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
103604
+ yield { line, table: multiline === void 0 ? tomlTableName(line) : void 0 };
103605
+ for (let index2 = 0; index2 < line.length; index2 += 1) {
103606
+ const char = line[index2];
103607
+ if (multiline !== void 0) {
103608
+ if (multiline === '"""' && char === "\\") {
103609
+ index2 += 1;
103610
+ continue;
103611
+ }
103612
+ if (line.startsWith(multiline, index2)) {
103613
+ index2 += 2;
103614
+ multiline = void 0;
103615
+ }
103616
+ } else {
103617
+ if (char === "#") break;
103618
+ if (char !== "'" && char !== '"') continue;
103619
+ const delimiter2 = char.repeat(3);
103620
+ if (line.startsWith(delimiter2, index2)) {
103621
+ multiline = delimiter2;
103622
+ index2 += 2;
103623
+ } else {
103624
+ for (index2 += 1; index2 < line.length; index2 += 1) {
103625
+ if (char === '"' && line[index2] === "\\") index2 += 1;
103626
+ else if (line[index2] === char) break;
103627
+ }
103628
+ }
103629
+ }
103630
+ }
103631
+ }
103632
+ }
103633
+ function tomlKeyPath(table) {
103634
+ const key2 = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
103635
+ const pattern = new RegExp(`^\\s*(${key2})(?:\\s*\\.\\s*(${key2}))*\\s*$`);
103636
+ if (!pattern.test(table)) return [];
103637
+ return [...table.matchAll(new RegExp(key2, "g"))].map(([part]) => unquoteTomlKey(part));
103638
+ }
103639
+ function tomlTableName(line) {
103640
+ const header = line.replace(/\r?\n$/, "");
103641
+ const match = /^\s*(?:\[\[\s*(.*?)\s*\]\]|\[\s*(.*?)\s*\])\s*(?:#.*)?$/.exec(header);
103642
+ return match?.[1] ?? match?.[2];
103643
+ }
103644
+ function unquoteTomlKey(key2) {
103645
+ if (key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
103646
+ if (key2.startsWith('"') && key2.endsWith('"')) {
103647
+ try {
103648
+ return JSON.parse(key2);
103649
+ } catch {
103650
+ return key2;
103651
+ }
103652
+ }
103653
+ return key2;
103654
+ }
103655
+ function tomlSeparator(contents) {
103656
+ if (contents.length === 0 || /(?:\r?\n)[ \t]*(?:\r?\n)$/.test(contents)) return "";
103657
+ return /\r?\n$/.test(contents) ? "\n" : "\n\n";
103658
+ }
103659
+ function escapeToml(value) {
103660
+ return JSON.stringify(value).slice(1, -1);
103661
+ }
103662
+
103663
+ // src/mcp-install.ts
103543
103664
  var MCP_INSTALL_USAGE = "Usage: vapi mcp install <claude-code|claude-desktop|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]";
103544
103665
  var APPS = /* @__PURE__ */ new Set(["claude-code", "claude-desktop", "cursor", "codex"]);
103545
103666
  var CLAUDE_ALIAS_NOTICE = "vapi mcp install claude installs into Claude Desktop; for the Claude Code CLI use: vapi mcp install claude-code";
@@ -103825,7 +103946,10 @@ function jsonConfig(path, existing, entry) {
103825
103946
  `;
103826
103947
  }
103827
103948
  function tomlConfig(existing, entry) {
103828
- const retained = removeVapiTomlTables(existing);
103949
+ const retained = removeTomlTables(
103950
+ existing,
103951
+ ([root, name]) => root === "mcp_servers" && name === "vapi"
103952
+ );
103829
103953
  const block = [
103830
103954
  "[mcp_servers.vapi]",
103831
103955
  'command = "npx"',
@@ -103835,46 +103959,6 @@ function tomlConfig(existing, entry) {
103835
103959
  ].join("\n");
103836
103960
  return `${retained}${tomlSeparator(retained)}${block}`;
103837
103961
  }
103838
- function removeVapiTomlTables(contents) {
103839
- const lines = contents.match(/[^\n]*\n|[^\n]+$/g) ?? [];
103840
- let removing = false;
103841
- let retained = "";
103842
- for (const line of lines) {
103843
- const table = tomlTableName(line);
103844
- if (table !== void 0) removing = isVapiTomlTable(table);
103845
- if (!removing) retained += line;
103846
- }
103847
- return retained;
103848
- }
103849
- function tomlTableName(line) {
103850
- const header = line.replace(/\r?\n$/, "");
103851
- const match = /^\s*(?:\[\[\s*(.*?)\s*\]\]|\[\s*(.*?)\s*\])\s*(?:#.*)?$/.exec(header);
103852
- return match?.[1] ?? match?.[2];
103853
- }
103854
- function isVapiTomlTable(table) {
103855
- const key2 = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
103856
- const match = new RegExp(`^\\s*(${key2})\\s*\\.\\s*(${key2})(?:\\s*\\.|\\s*$)`).exec(table);
103857
- if (match === null) return false;
103858
- return unquoteTomlKey(match[1]) === "mcp_servers" && unquoteTomlKey(match[2]) === "vapi";
103859
- }
103860
- function unquoteTomlKey(key2) {
103861
- if (key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
103862
- if (key2.startsWith('"') && key2.endsWith('"')) {
103863
- try {
103864
- return JSON.parse(key2);
103865
- } catch {
103866
- return key2;
103867
- }
103868
- }
103869
- return key2;
103870
- }
103871
- function tomlSeparator(contents) {
103872
- if (contents.length === 0 || /(?:\r?\n)[ \t]*(?:\r?\n)$/.test(contents)) return "";
103873
- return /\r?\n$/.test(contents) ? "\n" : "\n\n";
103874
- }
103875
- function escapeToml(value) {
103876
- return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
103877
- }
103878
103962
  function isRecord12(value) {
103879
103963
  return typeof value === "object" && value !== null && !Array.isArray(value);
103880
103964
  }
@@ -103896,6 +103980,546 @@ async function pathExists5(path) {
103896
103980
  }
103897
103981
  }
103898
103982
 
103983
+ // src/code.ts
103984
+ import { constants as constants2 } from "node:fs";
103985
+ import { access, mkdir as mkdir21, readFile as readFile28, realpath, unlink as unlink13, writeFile as writeFile12 } from "node:fs/promises";
103986
+ import { homedir as homedir3 } from "node:os";
103987
+ import { basename as basename5, dirname as dirname15, join as join26, posix as posix2, win32 as win323 } from "node:path";
103988
+ var VAPI_CODEX_PROVIDER = "vapi";
103989
+ var VAPI_CODEX_PROFILE = "vapi";
103990
+ var VAPI_CODEX_DEFAULT_MODEL = "venice/openai-gpt-61-sol";
103991
+ var VAPI_ROUTER_KEY_ENV = "VAPI_ROUTER_KEY";
103992
+ function codexConfigPath(env, home) {
103993
+ return join26(env.CODEX_HOME || join26(home, ".codex"), "config.toml");
103994
+ }
103995
+ function hasVapiCodexProfile(contents) {
103996
+ const roots = new Set(
103997
+ [...tomlLines(contents)].flatMap(({ table }) => {
103998
+ const path = table === void 0 ? [] : tomlKeyPath(table);
103999
+ return path.length === 2 && path[1] === "vapi" ? [path[0]] : [];
104000
+ })
104001
+ );
104002
+ return roots.has("model_providers") && roots.has("profiles");
104003
+ }
104004
+ async function resolveBinary(name, options) {
104005
+ const windows = (options.platform ?? process.platform) === "win32";
104006
+ const path = options.env.PATH ?? (windows ? Object.entries(options.env).find(([key2]) => key2.toLowerCase() === "path")?.[1] : void 0);
104007
+ if (path === void 0) return void 0;
104008
+ const paths = windows ? win323 : posix2;
104009
+ const canonical = options.realpath ?? realpath;
104010
+ const executable = options.isExecutable ?? (async (candidate) => {
104011
+ try {
104012
+ await access(candidate, constants2.X_OK);
104013
+ return true;
104014
+ } catch (error61) {
104015
+ if (isMissingFile(error61) || error61.code === "EACCES")
104016
+ return false;
104017
+ throw error61;
104018
+ }
104019
+ });
104020
+ const self = options.selfPath ?? process.argv[1];
104021
+ const selfReal = self === void 0 ? void 0 : await canonical(self);
104022
+ const extensions = windows ? ["", ...(options.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";")] : [""];
104023
+ for (const directory of path.split(windows ? ";" : ":")) {
104024
+ for (const extension of extensions) {
104025
+ const candidate = paths.resolve(directory.replace(/^"|"$/gu, ""), `${name}${extension}`);
104026
+ if (!await executable(candidate)) continue;
104027
+ const resolved = await canonical(candidate);
104028
+ if (selfReal !== void 0 && (windows ? resolved.toLowerCase() === selfReal.toLowerCase() : resolved === selfReal))
104029
+ continue;
104030
+ return candidate;
104031
+ }
104032
+ }
104033
+ return void 0;
104034
+ }
104035
+ var RC_START = "# >>> vapi code >>>";
104036
+ var RC_END = "# <<< vapi code <<<";
104037
+ var CONFIG_END = "# <<< vapi code config <<<\n";
104038
+ var isCodeTable = ([root, name]) => name === "vapi" && (root === "model_providers" || root === "profiles");
104039
+ function cleanConfig(contents) {
104040
+ let created = false;
104041
+ const cleaned = contents.replace(
104042
+ /(\n?)\[model_providers\.vapi\]\n# >>> vapi code config (created|existing) (0|1) >>>\n([\s\S]*?)# <<< vapi code config <<<\n/gu,
104043
+ (_, prefix, kind, separator, body) => {
104044
+ created ||= kind === "created";
104045
+ return (separator === "1" ? "" : prefix) + removeTomlTables(`[model_providers.vapi]
104046
+ ${body}`, isCodeTable);
104047
+ }
104048
+ );
104049
+ return { contents: removeTomlTables(cleaned, isCodeTable), created };
104050
+ }
104051
+ function configContents(existing, baseURL) {
104052
+ const clean2 = cleanConfig(existing ?? "");
104053
+ const retained = clean2.contents;
104054
+ const separator = retained.length > 0 && !retained.endsWith("\n") ? "\n" : "";
104055
+ return `${retained}${separator}[model_providers.vapi]
104056
+ # >>> vapi code config ${existing === void 0 || clean2.created ? "created" : "existing"} ${separator.length} >>>
104057
+ ` + [
104058
+ 'name = "vAPI Router"',
104059
+ `base_url = "${escapeToml(baseURL)}"`,
104060
+ `env_key = "${VAPI_ROUTER_KEY_ENV}"`,
104061
+ 'wire_api = "responses"',
104062
+ "",
104063
+ "[profiles.vapi]",
104064
+ `model_provider = "${VAPI_CODEX_PROVIDER}"`,
104065
+ `model = "${VAPI_CODEX_DEFAULT_MODEL}"`,
104066
+ ""
104067
+ ].join("\n") + CONFIG_END;
104068
+ }
104069
+ function removeAliases(contents) {
104070
+ return contents.replace(
104071
+ /(^|\n)# >>> vapi code >>>\r?\n[\s\S]*?^# <<< vapi code <<<(\r?\n|$)/gmu,
104072
+ (_, prefix, suffix) => suffix === "" ? "" : prefix
104073
+ );
104074
+ }
104075
+ function aliasContents(original, tools) {
104076
+ const existing = original ?? "";
104077
+ const block = [RC_START, ...tools.map((tool) => `alias ${tool}="vapi ${tool}"`), RC_END].join(
104078
+ "\n"
104079
+ );
104080
+ const match = /^# >>> vapi code >>>\r?\n[\s\S]*?^# <<< vapi code <<</gmu;
104081
+ if (match.test(existing)) return existing.replace(match, block);
104082
+ const separator = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
104083
+ return `${existing}${separator}${block}${original === "" || existing.endsWith("\n") ? "\n" : ""}`;
104084
+ }
104085
+ async function readOptional(path) {
104086
+ try {
104087
+ return await readFile28(path, "utf8");
104088
+ } catch (error61) {
104089
+ if (isMissingFile(error61)) return void 0;
104090
+ throw error61;
104091
+ }
104092
+ }
104093
+ async function writeConfig(path, contents) {
104094
+ await mkdir21(dirname15(path), { recursive: true });
104095
+ await writeFile12(path, contents);
104096
+ }
104097
+ async function codeCommand(argv, json2, io, dependencies) {
104098
+ const command = argv[0];
104099
+ if (command !== "install" && command !== "uninstall")
104100
+ throw new UsageError("Usage: vapi code <install|uninstall>.");
104101
+ const parsed = parseArguments(argv.slice(1), {
104102
+ valueOptions: new Set(command === "install" ? ["--wallet"] : []),
104103
+ booleanOptions: new Set(command === "install" ? ["--yes", "--no-alias"] : []),
104104
+ maximumPositionals: 0
104105
+ });
104106
+ const env = getEnvironment(dependencies);
104107
+ const home = dependencies.code?.homedir ?? homedir3();
104108
+ const config2 = codexConfigPath(env, home);
104109
+ const rcPaths = [join26(home, ".zshrc"), join26(home, ".bashrc")];
104110
+ if (command === "uninstall") {
104111
+ const removed = [];
104112
+ const previous = await readOptional(config2);
104113
+ if (previous !== void 0) {
104114
+ const clean2 = cleanConfig(previous);
104115
+ if (clean2.contents !== previous) {
104116
+ if (clean2.contents === "" && clean2.created) await unlink13(config2);
104117
+ else await writeFile12(config2, clean2.contents);
104118
+ removed.push(config2);
104119
+ }
104120
+ }
104121
+ for (const path of rcPaths) {
104122
+ const previous2 = await readOptional(path);
104123
+ if (previous2 === void 0) continue;
104124
+ const clean2 = removeAliases(previous2);
104125
+ if (clean2 !== previous2) {
104126
+ if (clean2 === "" && previous2.startsWith(RC_START) && !previous2.endsWith("\n"))
104127
+ await unlink13(path);
104128
+ else await writeFile12(path, clean2);
104129
+ removed.push(path);
104130
+ }
104131
+ }
104132
+ io.stdout(
104133
+ json2 ? JSON.stringify({ command: "code uninstall", removed }) : removed.length === 0 ? "Nothing to remove." : `Removed vAPI code settings from: ${removed.join(", ")}`
104134
+ );
104135
+ return 0;
104136
+ }
104137
+ const tools = [];
104138
+ const skipped2 = [];
104139
+ for (const name of ["claude", "codex"]) {
104140
+ const binary = await resolveBinary(name, { ...dependencies.code, env });
104141
+ if (binary === void 0)
104142
+ skipped2.push(
104143
+ `Skipped ${name === "claude" ? "Claude Code" : "Codex"}: \`${name}\` is not on PATH.`
104144
+ );
104145
+ else tools.push(name);
104146
+ }
104147
+ if (tools.length === 0) {
104148
+ const message = "Neither claude nor codex is on PATH; nothing was installed.";
104149
+ if (json2) io.stdout(JSON.stringify({ installed: [], skipped: skipped2, error: message }));
104150
+ else {
104151
+ skipped2.forEach(io.stderr);
104152
+ io.stderr(message);
104153
+ }
104154
+ return 1;
104155
+ }
104156
+ let target = await targetWallet(parsed, dependencies);
104157
+ const credentials = dependencies.router?.routerCredentials ?? routerCredentials;
104158
+ let linked = false;
104159
+ let rotated = false;
104160
+ let result;
104161
+ for (; ; ) {
104162
+ try {
104163
+ result = await credentials(routerDeps2(target, dependencies));
104164
+ break;
104165
+ } catch (error61) {
104166
+ if (error61 instanceof RouterClientError && error61.code === "not_linked" && !linked) {
104167
+ linked = true;
104168
+ const account = parsed.one("--wallet");
104169
+ await (dependencies.code?.login ?? runLoginFlow)(
104170
+ account === void 0 ? [] : ["--account", account],
104171
+ json2,
104172
+ { ...io, stdout: io.stderr },
104173
+ json2 ? { ...dependencies, interactive: false, stdinIsTTY: false } : dependencies
104174
+ );
104175
+ target = await targetWallet(parsed, dependencies);
104176
+ } else if (error61 instanceof RouterClientError && error61.code === "no_router_key" && !rotated) {
104177
+ rotated = true;
104178
+ await (dependencies.router?.rotateRouterKey ?? rotateRouterKey)(
104179
+ routerDeps2(target, dependencies)
104180
+ );
104181
+ } else throw error61;
104182
+ }
104183
+ }
104184
+ const installed = [];
104185
+ if (tools.includes("claude")) installed.push("Claude Code: ready, launch with `vapi claude`");
104186
+ if (tools.includes("codex")) {
104187
+ await writeConfig(config2, configContents(await readOptional(config2), result.baseURL));
104188
+ installed.push(`Codex: installed ${config2}`);
104189
+ }
104190
+ let alias = "Aliases: skipped.";
104191
+ if (!parsed.has("--no-alias")) {
104192
+ if ((dependencies.code?.platform ?? process.platform) === "win32")
104193
+ alias = "Aliases: skipped on Windows.";
104194
+ else {
104195
+ const yes = parsed.has("--yes") || !json2 && isInteractive(dependencies) && isStdinInteractive(dependencies) && /^y(?:es)?$/iu.test(
104196
+ (await getLinePrompt(dependencies)(
104197
+ "Make `claude` and `codex` use your vAPI Compute first from now on? [y/N] "
104198
+ )).trim()
104199
+ );
104200
+ if (yes) {
104201
+ const shell = basename5(env.SHELL ?? "");
104202
+ const rc = shell === "zsh" ? rcPaths[0] : shell === "bash" ? rcPaths[1] : await readOptional(rcPaths[0]) !== void 0 ? rcPaths[0] : rcPaths[1];
104203
+ await writeConfig(rc, aliasContents(await readOptional(rc), tools));
104204
+ alias = `Aliases: installed in ${rc}. Open a new terminal or run: source ${rc}`;
104205
+ }
104206
+ }
104207
+ }
104208
+ let compute;
104209
+ try {
104210
+ const usage = await (dependencies.router?.routerUsage ?? routerUsage)(
104211
+ routerDeps2(target, dependencies)
104212
+ );
104213
+ const reset = new Date(usage.compute.resetsAt);
104214
+ if (!Number.isFinite(reset.getTime())) throw new Error("invalid reset time");
104215
+ compute = `$${usage.compute.remainingTodayUsd.toFixed(2)} left today (resets ${reset.toISOString().slice(11, 16)} UTC)`;
104216
+ } catch (error61) {
104217
+ compute = `Compute today: unavailable (${error61 instanceof RouterClientError ? error61.code : "request failed"})`;
104218
+ }
104219
+ const start = `Start with \`vapi ${tools.includes("claude") ? "claude" : "codex"}\``;
104220
+ if (json2)
104221
+ io.stdout(
104222
+ JSON.stringify({ command: "code install", installed, skipped: skipped2, alias, compute, start })
104223
+ );
104224
+ else {
104225
+ skipped2.forEach(io.stderr);
104226
+ [...installed, alias, compute, start].forEach(io.stdout);
104227
+ }
104228
+ return 0;
104229
+ }
104230
+
104231
+ // src/code-launch.ts
104232
+ import { spawn as spawn4 } from "node:child_process";
104233
+ import { readFile as readFile29 } from "node:fs/promises";
104234
+ import { constants as constants3, homedir as homedir4 } from "node:os";
104235
+ var CLAUDE_MODELS = {
104236
+ sonnet: "venice/claude-sonnet-5-5",
104237
+ opus: "venice/claude-opus-5-5",
104238
+ haiku: "venice/claude-haiku-5-5"
104239
+ };
104240
+ async function claudeCommand(argv, json2, io, dependencies) {
104241
+ return await launch("claude", argv, json2, io, dependencies);
104242
+ }
104243
+ async function codexCommand(argv, json2, io, dependencies) {
104244
+ return await launch("codex", argv, json2, io, dependencies);
104245
+ }
104246
+ function parseLaunch(argv) {
104247
+ const result = { own: false, vapi: false, balance: false, forwarded: [] };
104248
+ for (let index2 = 0; index2 < argv.length; index2 += 1) {
104249
+ const arg = argv[index2];
104250
+ if (arg === "--") {
104251
+ result.forwarded.push(...argv.slice(index2 + 1));
104252
+ break;
104253
+ }
104254
+ if (arg === "--own") result.own = true;
104255
+ else if (arg === "--vapi") result.vapi = true;
104256
+ else if (arg === "--use-balance") result.balance = true;
104257
+ else if (arg === "--model" || arg === "--account") {
104258
+ const value = argv[++index2];
104259
+ if (!value || value.startsWith("--")) throw new UsageError(`Expected ${arg} <value>.`);
104260
+ if (arg === "--model") result.model = value;
104261
+ else result.account = value;
104262
+ } else result.forwarded.push(arg);
104263
+ }
104264
+ if (result.own && result.vapi) throw new UsageError("--vapi and --own cannot be used together.");
104265
+ return result;
104266
+ }
104267
+ var LaunchTimeout = class extends Error {
104268
+ constructor() {
104269
+ super("timed out");
104270
+ }
104271
+ };
104272
+ async function bounded(operation, milliseconds) {
104273
+ const controller = new AbortController();
104274
+ let timer;
104275
+ try {
104276
+ return await Promise.race([
104277
+ new Promise((_resolve, reject) => {
104278
+ timer = setTimeout(() => {
104279
+ const error61 = new LaunchTimeout();
104280
+ controller.abort(error61);
104281
+ reject(error61);
104282
+ }, milliseconds);
104283
+ }),
104284
+ operation(controller.signal)
104285
+ ]);
104286
+ } finally {
104287
+ clearTimeout(timer);
104288
+ controller.abort();
104289
+ }
104290
+ }
104291
+ function abortableDeps(deps, signal) {
104292
+ const fetchImpl = deps.fetchImpl ?? createPublicFetch({ allowPrivateNetwork: false });
104293
+ return {
104294
+ ...deps,
104295
+ fetchImpl: (input2, init) => fetchImpl(input2, {
104296
+ ...init,
104297
+ signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal
104298
+ })
104299
+ };
104300
+ }
104301
+ function shortReason(error61, env, credentials) {
104302
+ if (error61 instanceof RouterClientError) {
104303
+ if (error61.code === "not_linked") return "not linked, run vapi code install";
104304
+ if (error61.code === "no_router_key") return "no Router key, run vapi code install";
104305
+ }
104306
+ let message = error61 instanceof Error ? error61.message : String(error61);
104307
+ for (const secret of [
104308
+ credentials?.apiKey,
104309
+ env.ANTHROPIC_API_KEY,
104310
+ env.ANTHROPIC_AUTH_TOKEN,
104311
+ env[VAPI_ROUTER_KEY_ENV]
104312
+ ]) {
104313
+ if (secret) message = message.replaceAll(secret, "[redacted]");
104314
+ }
104315
+ return message.replace(/\s+/gu, " ").trim().slice(0, 160) || "request failed";
104316
+ }
104317
+ async function chooseRoute(options, env, dependencies) {
104318
+ if (options.own) return { kind: "own" };
104319
+ const timeout = dependencies.code?.usageTimeoutMs ?? 4e3;
104320
+ let credentials;
104321
+ let deps;
104322
+ let balanceKeyRequired = false;
104323
+ try {
104324
+ credentials = await bounded(async (signal) => {
104325
+ const target = await targetWallet(
104326
+ { one: (name) => name === "--wallet" ? options.account : void 0 },
104327
+ dependencies,
104328
+ env.VAPI_HOME
104329
+ );
104330
+ signal.throwIfAborted();
104331
+ deps = routerDeps2(target, dependencies);
104332
+ return await (dependencies.router?.routerCredentials ?? routerCredentials)(
104333
+ abortableDeps(deps, signal)
104334
+ );
104335
+ }, timeout);
104336
+ let usage;
104337
+ try {
104338
+ usage = await bounded(
104339
+ (signal) => (dependencies.router?.routerUsage ?? routerUsage)(abortableDeps(deps, signal)),
104340
+ timeout
104341
+ );
104342
+ if (!Number.isFinite(new Date(usage.compute.resetsAt).getTime()))
104343
+ throw new Error("invalid Compute reset time");
104344
+ } catch (error61) {
104345
+ if (options.vapi) return { kind: "vapi", credentials };
104346
+ throw error61;
104347
+ }
104348
+ if (options.vapi || remaining(usage, options.balance) >= 0.5) {
104349
+ if (options.balance && usage.compute.remainingTodayUsd < 0.5 && (usage.balance?.remainingUsd ?? 0) > 0) {
104350
+ balanceKeyRequired = true;
104351
+ credentials = await bounded(
104352
+ (signal) => (dependencies.router?.routerCredentials ?? routerCredentials)(
104353
+ abortableDeps(deps, signal),
104354
+ { funding: "balance" }
104355
+ ),
104356
+ timeout
104357
+ );
104358
+ }
104359
+ return { kind: "vapi", credentials, usage };
104360
+ }
104361
+ return { kind: "own", exhausted: true };
104362
+ } catch (error61) {
104363
+ const reason = balanceKeyRequired && error61 instanceof RouterClientError && error61.code === "no_router_key" ? "no Router balance key is stored" : shortReason(error61, env, credentials);
104364
+ if (options.vapi) return { kind: "unavailable", reason };
104365
+ return { kind: "own", reason };
104366
+ }
104367
+ }
104368
+ function remaining(usage, useBalance) {
104369
+ return usage.compute.remainingTodayUsd + (useBalance ? usage.balance?.remainingUsd ?? 0 : 0);
104370
+ }
104371
+ async function launch(tool, argv, json2, io, dependencies) {
104372
+ if (json2) throw new UsageError(`vapi ${tool} is interactive and does not support --json.`);
104373
+ const options = parseLaunch(argv);
104374
+ const env = getEnvironment(dependencies);
104375
+ let binary;
104376
+ try {
104377
+ binary = await resolveBinary(tool, { ...dependencies.code, env });
104378
+ } catch (error61) {
104379
+ io.stderr(shortReason(error61, env));
104380
+ return 127;
104381
+ }
104382
+ if (binary === void 0) {
104383
+ io.stderr(
104384
+ `\`${tool}\` is not on PATH. Install ${tool === "claude" ? "Claude Code" : "Codex"} first.`
104385
+ );
104386
+ return 127;
104387
+ }
104388
+ const route = await chooseRoute(options, env, dependencies);
104389
+ if (route.kind === "unavailable") {
104390
+ io.stderr(route.reason);
104391
+ return 1;
104392
+ }
104393
+ let args = options.forwarded;
104394
+ let childEnv = env;
104395
+ const own2 = tool === "claude" ? "your own Claude subscription" : "your own Codex/ChatGPT login";
104396
+ if (route.kind === "own") {
104397
+ if (route.exhausted) io.stderr(`\u25CF Compute used up today \u2192 ${own2}`);
104398
+ else if (route.reason !== void 0) io.stderr(`\u25CF vAPI unreachable (${route.reason}) \u2192 ${own2}`);
104399
+ if (options.model !== void 0)
104400
+ args = [tool === "claude" ? "--model" : "-m", options.model, ...args];
104401
+ } else {
104402
+ const { credentials, usage } = route;
104403
+ const model = tool === "claude" ? claudeModel(options.model) : options.model ?? VAPI_CODEX_DEFAULT_MODEL;
104404
+ let status = "\u25CF vAPI Compute";
104405
+ if (usage !== void 0)
104406
+ status += ` \u2014 $${remaining(usage, options.balance).toFixed(2)} left today (resets ${new Date(usage.compute.resetsAt).toISOString().slice(11, 16)} UTC)`;
104407
+ io.stderr(`${status} \xB7 model ${model.slice(model.lastIndexOf("/") + 1)}`);
104408
+ io.stderr(
104409
+ tool === "claude" ? " Compute runs out mid-session? /exit, then: vapi claude --continue" : " Compute runs out mid-session? /quit, then: vapi codex resume --last"
104410
+ );
104411
+ if (tool === "claude") {
104412
+ childEnv = {
104413
+ ...env,
104414
+ ANTHROPIC_BASE_URL: credentials.baseURL.replace(/\/v1\/?$/u, ""),
104415
+ ANTHROPIC_AUTH_TOKEN: credentials.apiKey
104416
+ };
104417
+ delete childEnv.ANTHROPIC_API_KEY;
104418
+ if (args.some((arg) => arg === "--settings" || arg.startsWith("--settings=")))
104419
+ io.stderr("\u25CF Your --settings is passed as is; vAPI model settings were not added.");
104420
+ else
104421
+ args = [
104422
+ "--settings",
104423
+ JSON.stringify({
104424
+ env: {
104425
+ ANTHROPIC_MODEL: model,
104426
+ ANTHROPIC_DEFAULT_SONNET_MODEL: CLAUDE_MODELS.sonnet,
104427
+ ANTHROPIC_DEFAULT_OPUS_MODEL: CLAUDE_MODELS.opus,
104428
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: CLAUDE_MODELS.haiku,
104429
+ CLAUDE_CODE_MAX_RETRIES: "2"
104430
+ }
104431
+ }),
104432
+ ...args
104433
+ ];
104434
+ } else {
104435
+ childEnv = { ...env, [VAPI_ROUTER_KEY_ENV]: credentials.apiKey };
104436
+ args = [...await codexArgs(env, credentials.baseURL, options.model, dependencies), ...args];
104437
+ }
104438
+ }
104439
+ return await runChild(binary, args, childEnv, io, dependencies);
104440
+ }
104441
+ function claudeModel(model) {
104442
+ return model === void 0 ? CLAUDE_MODELS.sonnet : Object.hasOwn(CLAUDE_MODELS, model) ? CLAUDE_MODELS[model] : model;
104443
+ }
104444
+ async function codexArgs(env, baseURL, model, dependencies) {
104445
+ let contents = "";
104446
+ try {
104447
+ contents = await readFile29(
104448
+ codexConfigPath(env, dependencies.code?.homedir ?? homedir4()),
104449
+ "utf8"
104450
+ );
104451
+ } catch (error61) {
104452
+ if (!isMissingFile(error61)) throw error61;
104453
+ }
104454
+ const providerArgs = [
104455
+ "-c",
104456
+ `model_providers.${VAPI_CODEX_PROVIDER}.name="vAPI Router"`,
104457
+ "-c",
104458
+ `model_providers.${VAPI_CODEX_PROVIDER}.base_url=${JSON.stringify(baseURL)}`,
104459
+ "-c",
104460
+ `model_providers.${VAPI_CODEX_PROVIDER}.env_key="${VAPI_ROUTER_KEY_ENV}"`,
104461
+ "-c",
104462
+ `model_providers.${VAPI_CODEX_PROVIDER}.wire_api="responses"`,
104463
+ "-c",
104464
+ `model_provider="${VAPI_CODEX_PROVIDER}"`
104465
+ ];
104466
+ if (hasVapiCodexProfile(contents))
104467
+ return [
104468
+ "--profile",
104469
+ VAPI_CODEX_PROFILE,
104470
+ ...providerArgs,
104471
+ ...model === void 0 ? [] : ["-m", model]
104472
+ ];
104473
+ return [...providerArgs, "-m", model ?? VAPI_CODEX_DEFAULT_MODEL];
104474
+ }
104475
+ async function runChild(binary, args, env, io, dependencies) {
104476
+ const signals = dependencies.code?.processSignals ?? process;
104477
+ let child;
104478
+ const ignore = () => {
104479
+ };
104480
+ const forward = (signal) => () => {
104481
+ try {
104482
+ child?.kill(signal);
104483
+ } catch (error61) {
104484
+ io.stderr(shortReason(error61, env));
104485
+ }
104486
+ };
104487
+ const listeners = [
104488
+ ["SIGINT", ignore],
104489
+ ["SIGQUIT", ignore],
104490
+ ["SIGTERM", forward("SIGTERM")],
104491
+ ["SIGHUP", forward("SIGHUP")]
104492
+ ];
104493
+ try {
104494
+ for (const [signal, listener] of listeners) signals.on(signal, listener);
104495
+ return await new Promise((resolve3) => {
104496
+ let settled = false;
104497
+ const finish = (code) => {
104498
+ if (!settled) {
104499
+ settled = true;
104500
+ resolve3(code);
104501
+ }
104502
+ };
104503
+ try {
104504
+ child = (dependencies.code?.spawn ?? spawn4)(binary, args, { env, stdio: "inherit" });
104505
+ child.once("error", (error61) => {
104506
+ if (!settled) io.stderr(shortReason(error61, env));
104507
+ finish(127);
104508
+ });
104509
+ child.once(
104510
+ "exit",
104511
+ (code, signal) => finish(code ?? (signal === null ? 1 : 128 + (constants3.signals[signal] ?? 0)))
104512
+ );
104513
+ } catch (error61) {
104514
+ io.stderr(shortReason(error61, env));
104515
+ finish(127);
104516
+ }
104517
+ });
104518
+ } finally {
104519
+ for (const [signal, listener] of listeners) signals.removeListener(signal, listener);
104520
+ }
104521
+ }
104522
+
103899
104523
  // src/send.ts
103900
104524
  var SEND_USAGE = "Usage: vapi send <amount> --from <account> --to <account|owner|0x\u2026> [--network base|arc] [--resume <nonce>] [--json]";
103901
104525
  async function sendCommand(argv, json2, io, dependencies) {
@@ -103995,7 +104619,7 @@ async function sendConfig(dependencies) {
103995
104619
 
103996
104620
  // src/setup.ts
103997
104621
  import { rm as rm5 } from "node:fs/promises";
103998
- import { join as join26 } from "node:path";
104622
+ import { join as join27 } from "node:path";
103999
104623
  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.`;
104000
104624
  var VAULT_CHOICE = "Create a new vault, or restore one from a recovery phrase? [new/restore] ";
104001
104625
  async function setupCommand(argv, json2, io, dependencies) {
@@ -104025,7 +104649,7 @@ async function setupCommand(argv, json2, io, dependencies) {
104025
104649
  let changedAccount = false;
104026
104650
  let changedLink = false;
104027
104651
  let scannedAddresses;
104028
- if (!await fileExists2(join26(paths.directory, "vault.json"))) {
104652
+ if (!await fileExists2(join27(paths.directory, "vault.json"))) {
104029
104653
  const choice = await vaultChoice(dependencies);
104030
104654
  if (choice === "restore") {
104031
104655
  if (!isInteractive(dependencies)) {
@@ -104113,7 +104737,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
104113
104737
  let scannedAddresses = 0;
104114
104738
  try {
104115
104739
  const restored = await restoreVault({
104116
- path: join26(paths.directory, "vault.json"),
104740
+ path: join27(paths.directory, "vault.json"),
104117
104741
  key: key2,
104118
104742
  phrase: validatedPhrase,
104119
104743
  probe: async (address4) => await readBalance3(address4) > 0n,
@@ -104124,7 +104748,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
104124
104748
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
104125
104749
  });
104126
104750
  names = restored.accounts().map((account) => account.name);
104127
- await rm5(join26(paths.directory, "wallets.json"), { force: true });
104751
+ await rm5(join27(paths.directory, "wallets.json"), { force: true });
104128
104752
  } finally {
104129
104753
  key2.fill(0);
104130
104754
  }
@@ -104242,7 +104866,7 @@ async function withRouterError2(operation) {
104242
104866
 
104243
104867
  // src/task.ts
104244
104868
  import { randomUUID as randomUUID6 } from "node:crypto";
104245
- import { readFile as readFile28 } from "node:fs/promises";
104869
+ import { readFile as readFile30 } from "node:fs/promises";
104246
104870
  var TASK_HELP = `Usage:
104247
104871
  vapi task search [--open] [--min <usd>] [--tab trending|new|closing|paid] [--limit <n>] [--json]
104248
104872
  vapi task show <id> [--account <name>] [--json]
@@ -104578,7 +105202,7 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104578
105202
  if (maxAwards !== void 0 && maxAwards > TASK_LIMITS.maxAwardsMax)
104579
105203
  throw new UsageError("--max-awards must be between 1 and 50.");
104580
105204
  if (parsed.one("--webhook") !== void 0) httpsUrl2(parsed.one("--webhook"), "--webhook");
104581
- const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile28(briefPath, "utf8");
105205
+ const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile30(briefPath, "utf8");
104582
105206
  const input2 = {
104583
105207
  title: title.trim(),
104584
105208
  description: brief.trim(),
@@ -105164,13 +105788,13 @@ async function watchTask(id2, parsed, json2, io, dependencies, now) {
105164
105788
  }
105165
105789
  }
105166
105790
  cursor2 = Math.max(cursor2, page.nextAfter, ...events.map((event) => event.sequence));
105167
- const remaining = deadline - clock().getTime();
105168
- if (remaining <= 0)
105791
+ const remaining2 = deadline - clock().getTime();
105792
+ if (remaining2 <= 0)
105169
105793
  throw new TaskCommandError(
105170
105794
  "timeout",
105171
105795
  `Task watch timed out after ${parsed.one("--timeout") ?? "7d"}.`
105172
105796
  );
105173
- await context.sleep(Math.min(interval, remaining));
105797
+ await context.sleep(Math.min(interval, remaining2));
105174
105798
  }
105175
105799
  }
105176
105800
  function expandDeliveryFiles(argv) {
@@ -106256,7 +106880,7 @@ async function referencedSleep(milliseconds, signal) {
106256
106880
  }
106257
106881
 
106258
106882
  // src/vault.ts
106259
- import { join as join27 } from "node:path";
106883
+ import { join as join28 } from "node:path";
106260
106884
  var VAULT_USAGE = "Usage: vapi vault protect|unprotect|lock|unlock|status [--json]";
106261
106885
  var RESTORE_USAGE = "Usage: vapi restore [--accounts <n> | --from-owner [--owner <0x\u2026>]] [--json]";
106262
106886
  var LEGACY_PASSWORD_NOTICE = "VAPI_KEYSTORE_PASSWORD is deprecated for vault passwords; use VAPI_VAULT_PASSWORD instead.";
@@ -106300,7 +106924,7 @@ async function restoreCommand(argv, json2, io, dependencies) {
106300
106924
  }
106301
106925
  const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
106302
106926
  const paths = getVapiPaths();
106303
- const path = join27(paths.directory, "vault.json");
106927
+ const path = join28(paths.directory, "vault.json");
106304
106928
  if (await fileExists2(path)) {
106305
106929
  throw new Error(
106306
106930
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
@@ -106457,7 +107081,7 @@ function requireNoArguments(argv) {
106457
107081
  parseArguments(argv, { valueOptions: /* @__PURE__ */ new Set(), maximumPositionals: 0 });
106458
107082
  }
106459
107083
  function vaultPath() {
106460
- return join27(getVapiPaths().directory, "vault.json");
107084
+ return join28(getVapiPaths().directory, "vault.json");
106461
107085
  }
106462
107086
  function quietIo(io) {
106463
107087
  return { stdout: () => void 0, stderr: io.stderr };
@@ -106525,6 +107149,10 @@ Usage:
106525
107149
  vapi login [--account <name>] [--label <name>] [--publish] [--no-browser] [--json]
106526
107150
  vapi logout [--account <name>] [--json]
106527
107151
  vapi whoami [--account <name>] [--json]
107152
+ vapi claude [--vapi|--own] [--model <m>] [--use-balance] [--account <name>] [<claude args>...]
107153
+ vapi codex [--vapi|--own] [--model <id>] [--use-balance] [--account <name>] [<codex args>...]
107154
+ vapi code install [--yes] [--no-alias] [--account <name>] [--json]
107155
+ vapi code uninstall [--json]
106528
107156
  vapi router models [--account <name>] [--json]
106529
107157
  vapi router usage [--account <name>] [--json]
106530
107158
  vapi router chat --model <id> [--system <text>] [--max-tokens <n>] "<prompt>" [--account <name>] [--json]
@@ -106744,6 +107372,8 @@ async function confirmWalletName(name, prompt, refusal, dependencies) {
106744
107372
  if (typed.trim() !== name) throw new KeystoreError(refusal);
106745
107373
  }
106746
107374
  async function runCli(argv = process.argv.slice(2), io = processIo, dependencies = {}) {
107375
+ const firstArgument = argv.find((argument) => argument !== "--json");
107376
+ const codeLaunch = firstArgument === "claude" || firstArgument === "codex";
106747
107377
  let json2 = argv.includes("--json");
106748
107378
  const taskInvocation = argv.find((argument) => argument !== "--json") === "task";
106749
107379
  const resultFile = runResultFile(argv);
@@ -106752,15 +107382,15 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106752
107382
  stderr: (message) => io.stderr(redactDetachedRunText(message, getEnvironment(dependencies)))
106753
107383
  };
106754
107384
  try {
106755
- const parsedInvocation = removeJsonFlag(argv);
107385
+ const parsedInvocation = removeJsonFlag(argv, codeLaunch);
106756
107386
  json2 = parsedInvocation.json;
106757
- const hasWalletOption = parsedInvocation.args.includes(WALLET_OPTION5);
107387
+ const hasWalletOption = !codeLaunch && parsedInvocation.args.includes(WALLET_OPTION5);
106758
107388
  const hasAccountOption = parsedInvocation.args.includes(ACCOUNT_OPTION2);
106759
107389
  if (hasWalletOption && hasAccountOption) {
106760
107390
  throw new UsageError("--wallet and --account cannot be used together.");
106761
107391
  }
106762
107392
  if (hasWalletOption) io.stderr(WALLET_OPTION_DEPRECATION);
106763
- const args = parsedInvocation.args.map(
107393
+ const args = codeLaunch ? parsedInvocation.args : parsedInvocation.args.map(
106764
107394
  (argument) => argument === WALLET_OPTION5 ? ACCOUNT_OPTION2 : argument
106765
107395
  );
106766
107396
  const command = args[0];
@@ -106856,6 +107486,15 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106856
107486
  await whoamiCommand(args.slice(1), json2, io, dependencies);
106857
107487
  exitCode = 0;
106858
107488
  break;
107489
+ case "claude":
107490
+ exitCode = await claudeCommand(args.slice(1), json2, io, dependencies);
107491
+ break;
107492
+ case "codex":
107493
+ exitCode = await codexCommand(args.slice(1), json2, io, dependencies);
107494
+ break;
107495
+ case "code":
107496
+ exitCode = await codeCommand(args.slice(1), json2, io, dependencies);
107497
+ break;
106859
107498
  case "router":
106860
107499
  await routerCommand(args.slice(1), json2, io, dependencies);
106861
107500
  exitCode = 0;
@@ -106893,7 +107532,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106893
107532
  break;
106894
107533
  case "unlock":
106895
107534
  io.stderr("vapi unlock is now vapi vault unlock; the old name works for one release.");
106896
- if (await fileExists2(join28(getVapiPaths().directory, "vault.json"))) {
107535
+ if (await fileExists2(join29(getVapiPaths().directory, "vault.json"))) {
106897
107536
  parseArguments(args.slice(1), {
106898
107537
  valueOptions: /* @__PURE__ */ new Set([WALLET_OPTION5]),
106899
107538
  maximumPositionals: 0
@@ -107099,7 +107738,7 @@ async function initCommand(argv, json2, io, dependencies) {
107099
107738
  address: account.address,
107100
107739
  accounts,
107101
107740
  config: paths.config,
107102
- vault: join28(paths.directory, "vault.json"),
107741
+ vault: join29(paths.directory, "vault.json"),
107103
107742
  ...configRewrites.length > 0 ? { configRewrites } : {},
107104
107743
  custody: "self",
107105
107744
  warning: CUSTODY_NOTICE,
@@ -107238,7 +107877,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
107238
107877
  const result = {
107239
107878
  address: account.address,
107240
107879
  ...account.solana ? { solanaAddress: account.solana.address } : {},
107241
- vault: join28(paths.directory, "vault.json"),
107880
+ vault: join29(paths.directory, "vault.json"),
107242
107881
  ...label === void 0 ? {} : { label },
107243
107882
  spendCaps: created.entry.spendCaps,
107244
107883
  isDefault,
@@ -107278,7 +107917,7 @@ function formatCaps2(caps) {
107278
107917
  function walletListResult(store, wallets, unlocked) {
107279
107918
  return {
107280
107919
  default: store.defaultName ?? null,
107281
- vault: join28(store.home, "vault.json"),
107920
+ vault: join29(store.home, "vault.json"),
107282
107921
  wallets: wallets.map((wallet) => ({
107283
107922
  name: wallet.name,
107284
107923
  ...wallet.address === void 0 ? {} : { address: wallet.address },
@@ -108294,7 +108933,7 @@ function sameOrigin2(left, right) {
108294
108933
  function noApiKeyMessage(baseUrl) {
108295
108934
  return [
108296
108935
  "No vAPI API key on this machine.",
108297
- `Create one in the console at ${listingsUrl(baseUrl, API_KEY_CONSOLE_PATH).href}, then store it with vapi auth set-key.`,
108936
+ `Create one in the console at ${apiKeyConsoleUrl(baseUrl).href}, then store it with vapi auth set-key.`,
108298
108937
  `In CI, set ${API_KEY_ENV} instead.`
108299
108938
  ].join("\n");
108300
108939
  }
@@ -108551,7 +109190,7 @@ function formatClaimed(origin, claimed) {
108551
109190
  }
108552
109191
  var EXPORT_KEY_WARNING = "Anyone with this key can spend the wallet. Never paste it into a website or chat.";
108553
109192
  async function deviceVaultKey2(store, dependencies) {
108554
- const path = join28(store.home, "vault.json");
109193
+ const path = join29(store.home, "vault.json");
108555
109194
  const metadata = await readVaultFileUnlocked(path);
108556
109195
  const secrets = getSecretStore(dependencies);
108557
109196
  const key2 = metadata.protected ? await unlockProtectedVault({
@@ -108644,7 +109283,7 @@ async function backupCommand(argv, json2, io, dependencies) {
108644
109283
  const target = await targetWallet(parsed, dependencies);
108645
109284
  const vaultAccount = await target.store.hasVaultAccount(target.name);
108646
109285
  if (vaultAccount) {
108647
- const vault = await readVaultFileUnlocked(join28(target.store.home, "vault.json"));
109286
+ const vault = await readVaultFileUnlocked(join29(target.store.home, "vault.json"));
108648
109287
  if (vault.accounts.some((account) => account.name === target.name && account.kind === "imported")) {
108649
109288
  throw new KeystoreError(
108650
109289
  `Account ${target.name} was imported and is not recoverable from the vault phrase. Back it up with vapi export-key --account ${target.name}.`
@@ -108721,7 +109360,7 @@ async function importCommand(argv, json2, io, dependencies) {
108721
109360
  const existed = store.has(name);
108722
109361
  if (existed && !parsed.has("--replace")) {
108723
109362
  const address4 = await store.readAddress(name);
108724
- const location = await store.hasVaultAccount(name) ? join28(store.home, "vault.json") : store.pathFor(name);
109363
+ const location = await store.hasVaultAccount(name) ? join29(store.home, "vault.json") : store.pathFor(name);
108725
109364
  throw new Error(
108726
109365
  [
108727
109366
  `Wallet ${name} already exists at ${location}.`,
@@ -108757,7 +109396,7 @@ async function importCommand(argv, json2, io, dependencies) {
108757
109396
  const result = {
108758
109397
  address: account.address,
108759
109398
  ...account.solana ? { solanaAddress: account.solana.address } : {},
108760
- vault: join28(paths.directory, "vault.json"),
109399
+ vault: join29(paths.directory, "vault.json"),
108761
109400
  ...previousKeystore ? { previousKeystore } : {},
108762
109401
  message: "Wallet imported. Its encrypted key stays on this machine."
108763
109402
  };
@@ -109090,7 +109729,7 @@ function formatFund(address4, url2, opened) {
109090
109729
  function openInBrowser(url2) {
109091
109730
  const opener = process.platform === "darwin" ? { command: "open", args: [url2] } : process.platform === "win32" ? { command: "cmd", args: ["/c", "start", "", url2] } : { command: "xdg-open", args: [url2] };
109092
109731
  try {
109093
- const child = spawn4(opener.command, opener.args, { stdio: "ignore", detached: true });
109732
+ const child = spawn5(opener.command, opener.args, { stdio: "ignore", detached: true });
109094
109733
  child.on("error", () => void 0);
109095
109734
  child.unref();
109096
109735
  return true;
@@ -109282,11 +109921,13 @@ function parseArguments(argv, spec) {
109282
109921
  has: (name) => flags.has(name)
109283
109922
  };
109284
109923
  }
109285
- function removeJsonFlag(argv) {
109924
+ function removeJsonFlag(argv, preserveForwarded = false) {
109286
109925
  let json2 = false;
109287
109926
  const args = [];
109927
+ let forwarding = false;
109288
109928
  for (const argument of argv) {
109289
- if (argument !== "--json") {
109929
+ if (preserveForwarded && argument === "--") forwarding = true;
109930
+ if (argument !== "--json" || forwarding) {
109290
109931
  args.push(argument);
109291
109932
  continue;
109292
109933
  }
@@ -109387,7 +110028,7 @@ function parseInitNetworks(value) {
109387
110028
 
109388
110029
  // src/update-check.ts
109389
110030
  import { lookup } from "node:dns/promises";
109390
- import { mkdir as mkdir21, readFile as readFile29, writeFile as writeFile12 } from "node:fs/promises";
110031
+ import { mkdir as mkdir22, readFile as readFile31, writeFile as writeFile13 } from "node:fs/promises";
109391
110032
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
109392
110033
  var CHECK_TIMEOUT_MS = 1500;
109393
110034
  var LATEST_URL = "https://registry.npmjs.org/vapi-network/latest";
@@ -109404,7 +110045,7 @@ async function runCliWithUpdateCheck(argv = process.argv.slice(2), io = {
109404
110045
  async function checkForUpdate(options = {}) {
109405
110046
  const env = options.env ?? process.env;
109406
110047
  const argv = options.argv ?? process.argv.slice(2);
109407
- 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) {
110048
+ 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) {
109408
110049
  return void 0;
109409
110050
  }
109410
110051
  const controller = new AbortController();
@@ -109431,7 +110072,7 @@ async function latestNotice(options, env, signal) {
109431
110072
  const now = (options.nowMs ?? Date.now)();
109432
110073
  let cached2;
109433
110074
  try {
109434
- const value = JSON.parse(await readFile29(paths.updateCheck, "utf8"));
110075
+ const value = JSON.parse(await readFile31(paths.updateCheck, "utf8"));
109435
110076
  if (isRecord13(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
109436
110077
  cached2 = { checkedAt: value.checkedAt, latest: value.latest };
109437
110078
  }
@@ -109440,9 +110081,9 @@ async function latestNotice(options, env, signal) {
109440
110081
  signal.throwIfAborted();
109441
110082
  let latest = cached2?.latest ?? CLI_VERSION;
109442
110083
  if (cached2 === void 0 || now - cached2.checkedAt >= CHECK_INTERVAL_MS || now < cached2.checkedAt) {
109443
- await mkdir21(paths.directory, { recursive: true });
110084
+ await mkdir22(paths.directory, { recursive: true });
109444
110085
  signal.throwIfAborted();
109445
- await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
110086
+ await writeFile13(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
109446
110087
  signal.throwIfAborted();
109447
110088
  const fetchImpl = options.fetchImpl ?? createPublicFetch({
109448
110089
  allowPrivateNetwork: false,
@@ -109469,7 +110110,7 @@ async function latestNotice(options, env, signal) {
109469
110110
  return void 0;
109470
110111
  }
109471
110112
  latest = body.version;
109472
- await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
110113
+ await writeFile13(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
109473
110114
  }
109474
110115
  signal.throwIfAborted();
109475
110116
  return isNewerVersion(latest, CLI_VERSION) ? `vapi-network ${latest} is available (you have ${CLI_VERSION}). Update: npm i -g vapi-network@latest` : void 0;