vapi-network 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -10117,9 +10117,9 @@ var init_call = __esm({
10117
10117
  });
10118
10118
 
10119
10119
  // ../cli/src/cli.ts
10120
- import { spawn as spawn3 } from "node:child_process";
10120
+ import { spawn as spawn5 } from "node:child_process";
10121
10121
  import { stat as stat16 } from "node:fs/promises";
10122
- import { join as join28 } from "node:path";
10122
+ import { join as join29 } from "node:path";
10123
10123
  import { createInterface as createInterface3 } from "node:readline/promises";
10124
10124
 
10125
10125
  // ../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/external.js
@@ -39310,7 +39310,6 @@ var BROWSER_ENABLED_X402_NETWORK_CONFIG = Object.freeze({
39310
39310
 
39311
39311
  // ../core/src/marketplace-contracts.ts
39312
39312
  var MARKETPLACE_DISCOVERY_PROTOCOL = "vapi.marketplace.discovery/1";
39313
- var MARKETPLACE_RANKING_VERSION = "marketplace-ranking-v1";
39314
39313
  var MARKETPLACE_KINDS = ["api", "service_offer", "open_request"];
39315
39314
  var MARKETPLACE_EXECUTION_METHODS = [
39316
39315
  "GET",
@@ -39343,6 +39342,32 @@ var listingLivenessSchema = external_exports.looseObject({
39343
39342
  latencyP95Ms: external_exports.number().nonnegative().nullable(),
39344
39343
  checks7d: external_exports.number().int().nonnegative()
39345
39344
  });
39345
+ var LISTING_HEALTH_STATES = ["healthy", "degraded", "outage", "unknown"];
39346
+ var listingHealthStateSchema = external_exports.enum(LISTING_HEALTH_STATES).catch("unknown");
39347
+ var listingHealthSchema = external_exports.looseObject({
39348
+ state: listingHealthStateSchema,
39349
+ uptime7d: external_exports.number().min(0).max(1).nullable().catch(null),
39350
+ latencyP50Ms: external_exports.number().nonnegative().nullable().catch(null),
39351
+ latencyP95Ms: external_exports.number().nonnegative().nullable().catch(null),
39352
+ checks7d: external_exports.number().int().nonnegative().catch(0)
39353
+ });
39354
+ var marketplaceAlternativeSchema = external_exports.looseObject({
39355
+ ref: external_exports.string().trim().min(1),
39356
+ reason: external_exports.enum(["cheaper", "healthier"])
39357
+ });
39358
+ var marketplaceAlternativesSchema = external_exports.preprocess((value) => {
39359
+ if (!Array.isArray(value)) return void 0;
39360
+ const alternatives = [];
39361
+ const refs = /* @__PURE__ */ new Set();
39362
+ for (const entry of value) {
39363
+ const parsed = marketplaceAlternativeSchema.safeParse(entry);
39364
+ if (!parsed.success || refs.has(parsed.data.ref)) continue;
39365
+ refs.add(parsed.data.ref);
39366
+ alternatives.push(parsed.data);
39367
+ if (alternatives.length === 2) break;
39368
+ }
39369
+ return alternatives.length > 0 ? alternatives : void 0;
39370
+ }, external_exports.array(marketplaceAlternativeSchema).optional());
39346
39371
  var listingConformanceSchema = external_exports.looseObject({
39347
39372
  declaredVersion: external_exports.union([external_exports.literal(1), external_exports.literal(2)]).nullable(),
39348
39373
  versionConformant: external_exports.boolean(),
@@ -39374,7 +39399,8 @@ var marketplaceBadgeCodeSchema = external_exports.enum([
39374
39399
  "vapi_verified",
39375
39400
  "external_catalog",
39376
39401
  "approved_vendor",
39377
- "unverified"
39402
+ "unverified",
39403
+ "failed_calls_free"
39378
39404
  ]);
39379
39405
  var marketplaceBadgeSchema = external_exports.looseObject({
39380
39406
  code: marketplaceBadgeCodeSchema,
@@ -39415,6 +39441,8 @@ var firstPartyApiMarketplaceHitSchema = external_exports.looseObject({
39415
39441
  ...marketplaceHitBase,
39416
39442
  kind: external_exports.literal("api"),
39417
39443
  provenance: firstPartyProvenanceSchema,
39444
+ health: listingHealthSchema.optional().catch(void 0),
39445
+ alternatives: marketplaceAlternativesSchema.optional().catch(void 0),
39418
39446
  execution: external_exports.looseObject({
39419
39447
  mode: executionModeSchema
39420
39448
  }),
@@ -39424,6 +39452,8 @@ var mirroredApiMarketplaceHitSchema = external_exports.looseObject({
39424
39452
  ...marketplaceHitBase,
39425
39453
  kind: external_exports.literal("api"),
39426
39454
  provenance: external_exports.literal("indexed"),
39455
+ health: listingHealthSchema.optional().catch(void 0),
39456
+ alternatives: marketplaceAlternativesSchema.optional().catch(void 0),
39427
39457
  execution: external_exports.looseObject({
39428
39458
  mode: external_exports.literal("direct"),
39429
39459
  url: external_exports.url().max(2048).regex(/^https:\/\/(?![^/?#]*@)/),
@@ -39473,7 +39503,8 @@ var marketplaceDiscoveryInputSchema = external_exports.strictObject({
39473
39503
  network: external_exports.string().trim().min(1).max(160).optional(),
39474
39504
  cursor: external_exports.string().trim().min(1).max(4096).optional(),
39475
39505
  limit: external_exports.number().int().min(1).max(50).optional(),
39476
- includeUnverified: external_exports.boolean().optional()
39506
+ includeUnverified: external_exports.boolean().optional(),
39507
+ includeOutage: external_exports.boolean().optional()
39477
39508
  }).superRefine((input2, context) => {
39478
39509
  if (input2.kinds && new Set(input2.kinds).size !== input2.kinds.length) {
39479
39510
  context.addIssue({
@@ -39491,7 +39522,14 @@ var marketplaceDiscoveryEnvelopeSchema = external_exports.looseObject({
39491
39522
  items: external_exports.array(external_exports.unknown()),
39492
39523
  nextCursor: external_exports.string().min(1).max(4096).nullable(),
39493
39524
  unavailableKinds: external_exports.array(marketplaceKindSchema).max(MARKETPLACE_KINDS.length),
39494
- rankingVersion: external_exports.literal(MARKETPLACE_RANKING_VERSION)
39525
+ // The ranking label is informational: pinning it made every installed client
39526
+ // reject the page the day the registry re-ranked, so any label is accepted.
39527
+ rankingVersion: external_exports.string().trim().min(1).max(80),
39528
+ // `hiddenOutage` counts listings in outage the registry left out because
39529
+ // `includeOutage` was not set. Older registries send no totals at all.
39530
+ totals: external_exports.looseObject({
39531
+ hiddenOutage: external_exports.number().int().nonnegative().optional().catch(void 0)
39532
+ }).optional().catch(void 0)
39495
39533
  });
39496
39534
  var marketplaceDiscoveryPageSchema = marketplaceDiscoveryEnvelopeSchema.extend({
39497
39535
  items: external_exports.array(marketplaceHitSchema)
@@ -46032,6 +46070,11 @@ var discoveryEndpointSchema = external_exports.looseObject({
46032
46070
  operationId: external_exports.string().trim().min(1).optional(),
46033
46071
  requestContentType: external_exports.string().trim().min(1).optional(),
46034
46072
  requestSchema: external_exports.json().optional(),
46073
+ responseSchema: external_exports.json().optional().catch(void 0),
46074
+ exampleRequest: external_exports.looseObject({
46075
+ query: external_exports.record(external_exports.string(), external_exports.string()).optional().catch(void 0),
46076
+ body: external_exports.json().optional()
46077
+ }).optional().catch(void 0),
46035
46078
  responseContentType: external_exports.string().trim().min(1).optional(),
46036
46079
  pathTemplate: external_exports.string().trim().min(1).optional(),
46037
46080
  pathParameters: external_exports.array(external_exports.string().trim().min(1)).optional(),
@@ -70061,13 +70104,13 @@ async function withAccountMovementLocks(home, accounts, timeoutMs, operation) {
70061
70104
  );
70062
70105
  }
70063
70106
  async function acquireAccountMovementLocks(home, accounts, timeoutMs, operation) {
70064
- const [account, ...remaining] = accounts;
70107
+ const [account, ...remaining2] = accounts;
70065
70108
  if (account === void 0) return await operation();
70066
70109
  return await withAccountMovementLock(
70067
70110
  home,
70068
70111
  account,
70069
70112
  timeoutMs,
70070
- async () => acquireAccountMovementLocks(home, remaining, timeoutMs, operation)
70113
+ async () => acquireAccountMovementLocks(home, remaining2, timeoutMs, operation)
70071
70114
  );
70072
70115
  }
70073
70116
  async function removeStaleLock2(path) {
@@ -70140,7 +70183,7 @@ var POWERSHELL_MISSING = [
70140
70183
  ].join(" ");
70141
70184
  function secretStore(options = {}) {
70142
70185
  const platform2 = options.platform ?? process.platform;
70143
- const run = options.run ?? spawnRunner;
70186
+ const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
70144
70187
  const env = options.env ?? process.env;
70145
70188
  const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
70146
70189
  if (platform2 === "darwin") return keychainStore(platform2, run);
@@ -70334,6 +70377,7 @@ function windowsDataProtectionStore(platform2, run, env, installed) {
70334
70377
  ].join("\n");
70335
70378
  const execute = async (script2) => {
70336
70379
  const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
70380
+
70337
70381
  `);
70338
70382
  requirePowerShell(result);
70339
70383
  return result;
@@ -70506,7 +70550,7 @@ function requireSuccess(result, what) {
70506
70550
  function withoutTrailingNewline(value) {
70507
70551
  return value.replace(/\r?\n$/u, "");
70508
70552
  }
70509
- var spawnRunner = async (file2, args, input2) => await new Promise((resolve3) => {
70553
+ var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve3) => {
70510
70554
  let stdout = "";
70511
70555
  let stderr2 = "";
70512
70556
  let settled = false;
@@ -70516,7 +70560,7 @@ var spawnRunner = async (file2, args, input2) => await new Promise((resolve3) =>
70516
70560
  resolve3(outcome);
70517
70561
  };
70518
70562
  const child = spawn(file2, [...args], {
70519
- detached: true,
70563
+ detached: platform2 !== "win32",
70520
70564
  stdio: ["pipe", "pipe", "pipe"],
70521
70565
  windowsHide: true
70522
70566
  });
@@ -72132,6 +72176,17 @@ var WalletStore = class _WalletStore {
72132
72176
  );
72133
72177
  return account?.address ?? (await readKeystoreSummary(this.pathFor(target))).address;
72134
72178
  }
72179
+ /**
72180
+ * Creates the vault without deriving an account, for apps that create every
72181
+ * account by name. Refuses when a vault already exists in this home.
72182
+ */
72183
+ async createEmptyVault() {
72184
+ if (await this.readVaultUnlocked() !== void 0) {
72185
+ throw new KeystoreError("A vault already exists in this home.");
72186
+ }
72187
+ await this.openVault({ create: true });
72188
+ this.dropVaultCache();
72189
+ }
72135
72190
  async create(name, passphrase, options = {}) {
72136
72191
  void passphrase;
72137
72192
  void options.enableSolana;
@@ -73012,11 +73067,11 @@ function accountChangeBusyError(account, command) {
73012
73067
  );
73013
73068
  }
73014
73069
  async function withAccountMutationLocks(home, accounts, command, operation) {
73015
- const [account, ...remaining] = [...new Set(accounts)].sort();
73070
+ const [account, ...remaining2] = [...new Set(accounts)].sort();
73016
73071
  if (account === void 0) return await operation();
73017
73072
  return await withFileLock(
73018
73073
  join8(home, `.account-${account}.lock`),
73019
- async () => await withAccountMutationLocks(home, remaining, command, operation),
73074
+ async () => await withAccountMutationLocks(home, remaining2, command, operation),
73020
73075
  {
73021
73076
  lockedMessage: `Account ${account} is busy with another account change. Wait for it to finish, then retry ${command}.`
73022
73077
  }
@@ -73802,12 +73857,14 @@ var ledgerFileSchema = external_exports.union([
73802
73857
  ledgerRowSchema
73803
73858
  ]);
73804
73859
  var SpendCapError = class extends Error {
73805
- constructor(code, message) {
73860
+ constructor(code, message, details) {
73806
73861
  super(message);
73807
73862
  this.code = code;
73863
+ this.details = details;
73808
73864
  this.name = "SpendCapError";
73809
73865
  }
73810
73866
  code;
73867
+ details;
73811
73868
  };
73812
73869
  function utcDateKey(now = /* @__PURE__ */ new Date()) {
73813
73870
  return now.toISOString().slice(0, 10);
@@ -73822,8 +73879,8 @@ async function escrowFundingDayRemainingAtomic(input2) {
73822
73879
  const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now);
73823
73880
  const row = rows.find((candidate) => candidate.wallet === input2.wallet);
73824
73881
  const reserved = input2.reservationId ? row?.reservations?.find((candidate) => candidate.id === input2.reservationId) : void 0;
73825
- const remaining = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
73826
- return remaining > 0n ? remaining : 0n;
73882
+ const remaining2 = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
73883
+ return remaining2 > 0n ? remaining2 : 0n;
73827
73884
  }
73828
73885
  async function taskReservedAtomic(input2) {
73829
73886
  const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now, true);
@@ -73889,7 +73946,8 @@ async function reserveSpend(amountAtomic2, caps, options) {
73889
73946
  if (amountAtomic2 > perCallAtomic) {
73890
73947
  throw new SpendCapError(
73891
73948
  "per_call_cap_exceeded",
73892
- `Payment quote ${amountAtomic2} atomic USDC exceeds the per-call cap ${perCallAtomic}. Refusing to sign.`
73949
+ `Payment quote ${amountAtomic2} atomic USDC exceeds the per-call cap ${perCallAtomic}. Refusing to sign.`,
73950
+ { amountAtomic: amountAtomic2, limitAtomic: perCallAtomic, wallet: options?.wallet }
73893
73951
  );
73894
73952
  }
73895
73953
  }
@@ -73978,7 +74036,8 @@ async function reserveSpend(amountAtomic2, caps, options) {
73978
74036
  if (nextSpent > perDayAtomic) {
73979
74037
  throw new SpendCapError(
73980
74038
  "per_day_cap_exceeded",
73981
- `${kind === "escrow-funding" ? "Escrow funding" : "Payment quote"} ${amountAtomic2} atomic USDC would raise today's spend to ${nextSpent} for wallet ${wallet}, above the per-day cap ${perDayAtomic}. Refusing to sign.`
74039
+ `${kind === "escrow-funding" ? "Escrow funding" : "Payment quote"} ${amountAtomic2} atomic USDC would raise today's spend to ${nextSpent} for wallet ${wallet}, above the per-day cap ${perDayAtomic}. Refusing to sign.`,
74040
+ { amountAtomic: amountAtomic2, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
73982
74041
  );
73983
74042
  }
73984
74043
  const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes10(16).toString("hex"));
@@ -75161,13 +75220,13 @@ function splitMovementPlanAtRelayLimit(plan) {
75161
75220
  const legs = plan.legs.flatMap((leg) => {
75162
75221
  const purpose = leg.purpose ?? "send";
75163
75222
  const split2 = purpose === "sweep" || plan.reason === "send" && plan.treasury !== void 0 && leg.to === plan.treasury;
75164
- let remaining = parseUsdCents(leg.amountUsd);
75165
- if (!split2 || remaining <= maximumCents) return [leg];
75223
+ let remaining2 = parseUsdCents(leg.amountUsd);
75224
+ if (!split2 || remaining2 <= maximumCents) return [leg];
75166
75225
  const parts = [];
75167
- while (remaining > 0n) {
75168
- const cents = remaining > maximumCents ? maximumCents : remaining;
75226
+ while (remaining2 > 0n) {
75227
+ const cents = remaining2 > maximumCents ? maximumCents : remaining2;
75169
75228
  parts.push({ ...leg, amountUsd: formatUsdCents(cents) });
75170
- remaining -= cents;
75229
+ remaining2 -= cents;
75171
75230
  }
75172
75231
  return parts;
75173
75232
  });
@@ -76043,13 +76102,13 @@ async function withMovementLock(home, from16, timeoutMs, operation) {
76043
76102
  }
76044
76103
  }
76045
76104
  async function withMovementLocks(home, senders, timeoutMs, operation) {
76046
- const [sender, ...remaining] = senders;
76105
+ const [sender, ...remaining2] = senders;
76047
76106
  if (sender === void 0) return await operation();
76048
76107
  return await withMovementLock(
76049
76108
  home,
76050
76109
  sender,
76051
76110
  timeoutMs,
76052
- async () => withMovementLocks(home, remaining, timeoutMs, operation)
76111
+ async () => withMovementLocks(home, remaining2, timeoutMs, operation)
76053
76112
  );
76054
76113
  }
76055
76114
  async function assertNoPendingCeilingSweep(deps, senders) {
@@ -76856,11 +76915,11 @@ function planTargets(input2) {
76856
76915
  function splitCandidateAtRelayMaximum(candidate, relayMaxAtomic) {
76857
76916
  const maximumCents = relayMaxAtomic / 10000n;
76858
76917
  const legs = [];
76859
- let remaining = candidate.cents;
76860
- while (remaining > 0n) {
76861
- const cents = remaining > maximumCents ? maximumCents : remaining;
76918
+ let remaining2 = candidate.cents;
76919
+ while (remaining2 > 0n) {
76920
+ const cents = remaining2 > maximumCents ? maximumCents : remaining2;
76862
76921
  legs.push(allocationLeg(candidate.from, candidate.to, cents, candidate.purpose));
76863
- remaining -= cents;
76922
+ remaining2 -= cents;
76864
76923
  }
76865
76924
  return legs;
76866
76925
  }
@@ -76934,6 +76993,96 @@ function parseAtomic(value, label) {
76934
76993
  throw new Error(`Invalid ${label} atomic amount.`);
76935
76994
  }
76936
76995
 
76996
+ // ../core/src/spend-cap-exceeded.ts
76997
+ var SpendCapExceededError = class extends Error {
76998
+ name = "SpendCapExceededError";
76999
+ code = "spend_cap_exceeded";
77000
+ retryable = false;
77001
+ cap;
77002
+ amountUsd;
77003
+ limitUsd;
77004
+ spentUsd;
77005
+ wallet;
77006
+ command;
77007
+ constructor(input2) {
77008
+ const amountUsd = normalizeUsd(input2.amountUsd);
77009
+ const limitUsd = normalizeUsd(input2.limitUsd);
77010
+ const spentUsd = input2.spentUsd === void 0 ? void 0 : normalizeUsd(input2.spentUsd);
77011
+ const wallet = input2.wallet?.trim() || void 0;
77012
+ const command = input2.command === void 0 ? spendCapCommand(input2.cap, amountUsd, spentUsd, wallet, input2.perDayLimitUsd) : input2.command;
77013
+ super(
77014
+ input2.message ?? spendCapMessage(input2.cap, amountUsd, limitUsd, spentUsd, wallet, command),
77015
+ input2.cause === void 0 ? void 0 : { cause: input2.cause }
77016
+ );
77017
+ this.cap = input2.cap;
77018
+ this.amountUsd = amountUsd;
77019
+ this.limitUsd = limitUsd;
77020
+ this.spentUsd = spentUsd;
77021
+ this.wallet = wallet;
77022
+ this.command = command;
77023
+ }
77024
+ toJSON() {
77025
+ return {
77026
+ code: this.code,
77027
+ cap: this.cap,
77028
+ amountUsd: this.amountUsd,
77029
+ limitUsd: this.limitUsd,
77030
+ ...this.spentUsd === void 0 ? {} : { spentUsd: this.spentUsd },
77031
+ ...this.wallet === void 0 ? {} : { wallet: this.wallet },
77032
+ command: this.command,
77033
+ message: this.message
77034
+ };
77035
+ }
77036
+ };
77037
+ function spendCapCommand(cap, amountUsd, spentUsd, wallet, perDayLimitUsd) {
77038
+ const account = wallet ?? "<account>";
77039
+ if (cap === "per_call") {
77040
+ const scale = Math.max(fractionLength(amountUsd), fractionLength(perDayLimitUsd ?? "0"));
77041
+ const raiseDay = perDayLimitUsd !== void 0 && parseDecimal(amountUsd, scale) > parseDecimal(perDayLimitUsd, scale);
77042
+ return `vapi accounts caps ${account} --per-call ${amountUsd}${raiseDay ? ` --per-day ${amountUsd}` : ""}`;
77043
+ }
77044
+ if (cap === "per_day") {
77045
+ return `vapi accounts caps ${account} --per-day ${addUsd(spentUsd ?? "0", amountUsd)}`;
77046
+ }
77047
+ if (cap === "max_price") {
77048
+ return `--max ${amountUsd}`;
77049
+ }
77050
+ if (cap === "run_budget") {
77051
+ const budget = addUsd(spentUsd ?? "0", amountUsd);
77052
+ return `--budget ${budget}`;
77053
+ }
77054
+ return null;
77055
+ }
77056
+ function spendCapMessage(cap, amountUsd, limitUsd, spentUsd, wallet, command) {
77057
+ const capName = cap === "per_call" ? "per-call spend cap" : cap === "per_day" ? "per-day spend cap" : cap === "max_price" ? "maximum price" : cap === "max_amount" ? "maximum amount" : "run budget";
77058
+ const account = cap === "per_call" || cap === "per_day" ? ` of account ${wallet ?? "<account>"}` : "";
77059
+ const payment = cap === "per_day" || cap === "run_budget" ? `this payment of $${amountUsd} would raise ${cap === "per_day" ? "today's spend" : "run spend"} from $${spentUsd ?? "0"} to $${addUsd(spentUsd ?? "0", amountUsd)}, above $${limitUsd}` : `this payment of $${amountUsd} exceeds the limit of $${limitUsd}`;
77060
+ const guidance = cap === "max_price" ? ` MCP call.pay takes maxPriceUsd. Raise the CLI maximum with:` : cap === "run_budget" ? " Raise it on vapi agent run or vapi swarm run with:" : " Raise it with:";
77061
+ const action = command === null ? "" : `${guidance} ${command}`;
77062
+ return `Blocked by the ${capName}${account}: ${payment}. Nothing was signed.${action}`;
77063
+ }
77064
+ function normalizeUsd(value) {
77065
+ const trimmed = value.trim();
77066
+ if (!trimmed.includes(".")) return trimmed;
77067
+ const normalized = trimmed.replace(/0+$/u, "").replace(/\.$/u, "");
77068
+ return normalized || "0";
77069
+ }
77070
+ function addUsd(left, right) {
77071
+ const scale = Math.max(fractionLength(left), fractionLength(right));
77072
+ const factor = 10n ** BigInt(scale);
77073
+ const total = parseDecimal(left, scale) + parseDecimal(right, scale);
77074
+ const whole = total / factor;
77075
+ const fraction = (total % factor).toString().padStart(scale, "0").replace(/0+$/u, "");
77076
+ return fraction ? `${whole}.${fraction}` : whole.toString();
77077
+ }
77078
+ function fractionLength(value) {
77079
+ return value.split(".")[1]?.length ?? 0;
77080
+ }
77081
+ function parseDecimal(value, scale) {
77082
+ const [whole = "0", fraction = ""] = value.split(".");
77083
+ return BigInt(whole) * 10n ** BigInt(scale) + BigInt(fraction.padEnd(scale, "0") || "0");
77084
+ }
77085
+
76937
77086
  // ../core/src/swarm.ts
76938
77087
  import { readdir as readdir6, readFile as readFile15, stat as stat11, unlink as unlink11 } from "node:fs/promises";
76939
77088
  import { join as join12 } from "node:path";
@@ -77605,7 +77754,7 @@ function createRunBudget(args) {
77605
77754
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
77606
77755
  import { arch, platform, release } from "node:os";
77607
77756
  import { join as join13 } from "node:path";
77608
- var VAPI_CLIENT_VERSION = "0.10.0";
77757
+ var VAPI_CLIENT_VERSION = "0.12.0";
77609
77758
  async function createSupportReport(options) {
77610
77759
  const message = options.message.trim();
77611
77760
  if (!message) throw new Error("Support report message must not be empty.");
@@ -77800,8 +77949,28 @@ async function completeX402Payment(args) {
77800
77949
  }
77801
77950
  args.challenge.request.signal.throwIfAborted();
77802
77951
  if (trace) trace.capsApplied = true;
77803
- assertMaximumAtomic(quote.amountAtomic, args.maxAtomic);
77804
- assertMaxPrice(quote.amountAtomic, args.maxPriceUsd);
77952
+ try {
77953
+ assertMaximumAtomic(quote.amountAtomic, args.maxAtomic);
77954
+ } catch (error61) {
77955
+ if (args.maxAtomic !== void 0 && isErrorCode(error61, "max_price_exceeded")) {
77956
+ throw paymentCapError("max_amount", quote.amountAtomic, args.maxAtomic, args, error61);
77957
+ }
77958
+ throw error61;
77959
+ }
77960
+ try {
77961
+ assertMaxPrice(quote.amountAtomic, args.maxPriceUsd);
77962
+ } catch (error61) {
77963
+ if (args.maxPriceUsd !== void 0 && isErrorCode(error61, "max_price_exceeded")) {
77964
+ throw paymentCapError(
77965
+ "max_price",
77966
+ quote.amountAtomic,
77967
+ usdToAtomic(args.maxPriceUsd),
77968
+ args,
77969
+ error61
77970
+ );
77971
+ }
77972
+ throw error61;
77973
+ }
77805
77974
  const spendReservation = {
77806
77975
  ledgerPath: args.ledgerPath ?? getVapiPaths().ledger,
77807
77976
  now: args.now,
@@ -77810,18 +77979,42 @@ async function completeX402Payment(args) {
77810
77979
  let reservationId;
77811
77980
  let reservedOn;
77812
77981
  if (args.runBudget === void 0) {
77813
- await reserveSpend(quote.amountAtomic, args.caps, spendReservation);
77982
+ try {
77983
+ await reserveSpend(quote.amountAtomic, args.caps, spendReservation);
77984
+ } catch (error61) {
77985
+ throw walletCapError(error61, quote.amountAtomic, args);
77986
+ }
77814
77987
  } else {
77815
77988
  reservationId = args.paymentId ?? `x402_${randomBytes14(12).toString("hex")}`;
77816
- const reservation = await reserveSpend(quote.amountAtomic, args.caps, {
77817
- ...spendReservation,
77818
- reservationId
77819
- });
77989
+ let reservation;
77990
+ try {
77991
+ reservation = await reserveSpend(quote.amountAtomic, args.caps, {
77992
+ ...spendReservation,
77993
+ reservationId
77994
+ });
77995
+ } catch (error61) {
77996
+ throw walletCapError(error61, quote.amountAtomic, args);
77997
+ }
77820
77998
  reservedOn = reservation.date;
77821
77999
  try {
77822
78000
  args.runBudget.reserve(quote.amountAtomic, reservationId);
77823
78001
  } catch (error61) {
77824
- await releaseUnsentReservation(args, quote.amountAtomic, reservationId, reservedOn);
78002
+ let runSpentAtomic;
78003
+ try {
78004
+ runSpentAtomic = args.runBudget.spentAtomic();
78005
+ } finally {
78006
+ await releaseUnsentReservation(args, quote.amountAtomic, reservationId, reservedOn);
78007
+ }
78008
+ if (error61 instanceof RunBudgetError || isErrorCode(error61, "run_budget_exceeded")) {
78009
+ throw new SpendCapExceededError({
78010
+ cap: "run_budget",
78011
+ amountUsd: formatUsdc(quote.amountAtomic),
78012
+ limitUsd: formatUsdc(args.runBudget.limitAtomic),
78013
+ spentUsd: formatUsdc(runSpentAtomic),
78014
+ ...args.wallet === void 0 ? {} : { wallet: args.wallet },
78015
+ cause: error61
78016
+ });
78017
+ }
77825
78018
  throw error61;
77826
78019
  }
77827
78020
  }
@@ -78104,6 +78297,18 @@ function sanitizeThrownError(error61, secrets) {
78104
78297
  if (!(error61 instanceof Error)) return error61;
78105
78298
  const message = redactKnownSecrets(error61.message, secrets);
78106
78299
  const cause = error61.cause === void 0 ? void 0 : sanitizeThrownError(error61.cause, secrets);
78300
+ if (error61 instanceof SpendCapExceededError) {
78301
+ return new SpendCapExceededError({
78302
+ cap: error61.cap,
78303
+ amountUsd: error61.amountUsd,
78304
+ limitUsd: error61.limitUsd,
78305
+ ...error61.spentUsd === void 0 ? {} : { spentUsd: error61.spentUsd },
78306
+ ...error61.wallet === void 0 ? {} : { wallet: error61.wallet },
78307
+ command: error61.command,
78308
+ message,
78309
+ ...cause === void 0 ? {} : { cause }
78310
+ });
78311
+ }
78107
78312
  if (message === error61.message && cause === error61.cause) return error61;
78108
78313
  if (error61 instanceof X402Error) {
78109
78314
  return new X402Error(error61.code, message, cause === void 0 ? void 0 : { cause });
@@ -78205,6 +78410,43 @@ function assertMaximumAtomic(amountAtomic2, maxAtomic) {
78205
78410
  );
78206
78411
  }
78207
78412
  }
78413
+ function walletCapError(error61, amountAtomic2, args) {
78414
+ if (!(error61 instanceof SpendCapError)) return error61;
78415
+ if (error61.code === "per_call_cap_exceeded") {
78416
+ return paymentCapError(
78417
+ "per_call",
78418
+ amountAtomic2,
78419
+ error61.details?.limitAtomic ?? BigInt(args.caps.perCallAtomic),
78420
+ args,
78421
+ error61
78422
+ );
78423
+ }
78424
+ if (error61.code === "per_day_cap_exceeded") {
78425
+ return paymentCapError(
78426
+ "per_day",
78427
+ amountAtomic2,
78428
+ error61.details?.limitAtomic ?? BigInt(args.caps.perDayAtomic),
78429
+ args,
78430
+ error61,
78431
+ error61.details?.spentAtomic
78432
+ );
78433
+ }
78434
+ return error61;
78435
+ }
78436
+ function paymentCapError(cap, amountAtomic2, limitAtomic, args, cause, spentAtomic) {
78437
+ return new SpendCapExceededError({
78438
+ cap,
78439
+ amountUsd: formatUsdc(amountAtomic2),
78440
+ limitUsd: formatUsdc(limitAtomic),
78441
+ ...cap === "per_call" ? { perDayLimitUsd: formatUsdc(BigInt(args.caps.perDayAtomic)) } : {},
78442
+ ...spentAtomic === void 0 ? {} : { spentUsd: formatUsdc(spentAtomic) },
78443
+ ...args.wallet === void 0 ? {} : { wallet: args.wallet },
78444
+ cause
78445
+ });
78446
+ }
78447
+ function isErrorCode(error61, code) {
78448
+ return typeof error61 === "object" && error61 !== null && Reflect.get(error61, "code") === code;
78449
+ }
78208
78450
  function settlementUnknown(message, quote, payment, payer, receipt, cause) {
78209
78451
  return new X402PaymentError(
78210
78452
  "settlement_unknown",
@@ -78280,7 +78522,7 @@ function receiptQuote(quote) {
78280
78522
  };
78281
78523
  }
78282
78524
  function paymentErrorOutcome(error61) {
78283
- if (error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error && error61.code === "max_price_exceeded") {
78525
+ if (error61 instanceof SpendCapExceededError || error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error && error61.code === "max_price_exceeded") {
78284
78526
  return "declined_policy";
78285
78527
  }
78286
78528
  if (error61 instanceof X402PaymentError) {
@@ -78297,7 +78539,7 @@ function errorCode(error61) {
78297
78539
  return "request_failed";
78298
78540
  }
78299
78541
  function receiptSafeErrorMessage(error61) {
78300
- if (error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error || error61 instanceof X402PaymentError) {
78542
+ if (error61 instanceof SpendCapExceededError || error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error || error61 instanceof X402PaymentError) {
78301
78543
  return error61.message;
78302
78544
  }
78303
78545
  return "The x402 request failed before it completed.";
@@ -78803,15 +79045,18 @@ function budgetExhaustedError(resetsAt, status) {
78803
79045
  );
78804
79046
  }
78805
79047
  function refillDeclinedDetail(error61) {
79048
+ if (error61 instanceof SpendCapExceededError) return `${error61.name}: ${error61.cap}`;
78806
79049
  if (error61 instanceof SpendCapError) return `${error61.name}: ${error61.code}`;
78807
- if (isRunBudgetError(error61)) return `RunBudgetError: ${error61.code}`;
79050
+ if (isRunBudgetError(error61)) {
79051
+ return error61.code === "spend_cap_exceeded" ? "SpendCapExceededError: run_budget" : `RunBudgetError: ${error61.code}`;
79052
+ }
78808
79053
  if (error61 instanceof RouterClientError) {
78809
79054
  return `${error61.name}: ${error61.code}${error61.status === void 0 ? "" : ` (${error61.status})`}`;
78810
79055
  }
78811
79056
  return "Error: Router balance refill failed.";
78812
79057
  }
78813
79058
  function isRunBudgetError(error61) {
78814
- return typeof error61 === "object" && error61 !== null && Reflect.get(error61, "code") === "run_budget_exceeded";
79059
+ return typeof error61 === "object" && error61 !== null && (Reflect.get(error61, "code") === "run_budget_exceeded" || Reflect.get(error61, "code") === "spend_cap_exceeded" && Reflect.get(error61, "cap") === "run_budget");
78815
79060
  }
78816
79061
  function isRouterTopupTier(value) {
78817
79062
  return ROUTER_TOPUP_TIERS.some((tier) => tier === value);
@@ -78901,8 +79146,15 @@ async function ownerStake(deps) {
78901
79146
  stakeUrl: parsed.data.stakeUrl
78902
79147
  };
78903
79148
  }
78904
- async function routerCredentials(deps) {
78905
- const { routerBaseUrl, routerKey } = await routerCredentialSnapshot(deps);
79149
+ async function routerCredentials(deps, options = {}) {
79150
+ const credentials = options.funding === "balance" ? await routerBalanceCredentialSnapshot(deps) : await routerCredentialSnapshot(deps);
79151
+ if (credentials === void 0) {
79152
+ throw new RouterClientError(
79153
+ "no_router_key",
79154
+ "No Router balance key is stored for this wallet."
79155
+ );
79156
+ }
79157
+ const { routerBaseUrl, routerKey } = credentials;
78906
79158
  return { baseURL: `${routerBaseUrl}/v1`, apiKey: routerKey };
78907
79159
  }
78908
79160
  async function routerCredentialSnapshot(deps) {
@@ -82126,10 +82378,10 @@ async function waitForMilestone(client, input2) {
82126
82378
  return { reached, milestone, polls, elapsedMs: now().getTime() - started };
82127
82379
  }
82128
82380
  for (; ; ) {
82129
- const remaining = deadline - now().getTime();
82130
- if (remaining <= 0) return result(false);
82381
+ const remaining2 = deadline - now().getTime();
82382
+ if (remaining2 <= 0) return result(false);
82131
82383
  const controller = new AbortController();
82132
- const timer = setTimeout(() => controller.abort(), remaining);
82384
+ const timer = setTimeout(() => controller.abort(), remaining2);
82133
82385
  let response;
82134
82386
  polls++;
82135
82387
  try {
@@ -82793,7 +83045,7 @@ async function feeTask(input2, action) {
82793
83045
  );
82794
83046
  let approvalGranted = input2.approval !== void 0 && "granted" in input2.approval && input2.approval.granted;
82795
83047
  const checkPolicy = async (reservationId) => {
82796
- const remaining = await escrowFundingDayRemainingAtomic({
83048
+ const remaining2 = await escrowFundingDayRemainingAtomic({
82797
83049
  caps: input2.caps,
82798
83050
  ledgerPath: input2.ledgerPath,
82799
83051
  wallet: input2.wallet,
@@ -82810,13 +83062,13 @@ async function feeTask(input2, action) {
82810
83062
  const maxPerTaskAtomic = policyAtomic(input2.policy.maxPerTaskUsd);
82811
83063
  if (feeAtomic > maxPerTaskAtomic || taskReserved + feeAtomic > maxPerTaskAtomic)
82812
83064
  return { outcome: "refused", reason: "policy.perTask", money: money2, disputeFee: fee };
82813
- if (feeAtomic > remaining)
83065
+ if (feeAtomic > remaining2)
82814
83066
  return { outcome: "refused", reason: "policy.perDay", money: money2, disputeFee: fee };
82815
83067
  if (feeAtomic > policyAtomic(input2.policy.approveAboveUsd) && !approvalGranted) {
82816
83068
  if (input2.approval && "ask" in input2.approval) {
82817
83069
  approvalGranted = await input2.approval.ask({
82818
83070
  money: money2,
82819
- dayRemainingUsd: Number(formatBaseUnitsUsd(remaining))
83071
+ dayRemainingUsd: Number(formatBaseUnitsUsd(remaining2))
82820
83072
  });
82821
83073
  if (!approvalGranted) return { outcome: "declined", money: money2, disputeFee: fee };
82822
83074
  } else return { outcome: "approval_needed", money: money2, disputeFee: fee };
@@ -84853,6 +85105,11 @@ function safeOrigin2(value) {
84853
85105
  }
84854
85106
  }
84855
85107
 
85108
+ // ../core/src/listing-fee.ts
85109
+ function formatListingFee(fee) {
85110
+ return fee.bps === 0 ? "No network fee" : `${fee.label} (${fee.bps / 100}%)`;
85111
+ }
85112
+
84856
85113
  // ../core/src/onramp.ts
84857
85114
  var ONRAMP_NETWORK = "base";
84858
85115
  var ONRAMP_FALLBACK_INSTRUCTIONS = "Send USDC on Base (eip155:8453) to this address; add a little ETH for gas if you plan to sweep.";
@@ -87683,7 +87940,8 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
87683
87940
  network: input2.network,
87684
87941
  limit: input2.limit,
87685
87942
  cursor: input2.cursor,
87686
- includeUnverified: input2.includeUnverified
87943
+ includeUnverified: input2.includeUnverified,
87944
+ includeOutage: input2.includeOutage
87687
87945
  });
87688
87946
  const startedAt = options.now ?? /* @__PURE__ */ new Date();
87689
87947
  const attempts = [];
@@ -87705,6 +87963,9 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
87705
87963
  if (normalized.includeUnverified === true) {
87706
87964
  url2.searchParams.set("includeUnverified", "true");
87707
87965
  }
87966
+ if (normalized.includeOutage === true) {
87967
+ url2.searchParams.set("includeOutage", "true");
87968
+ }
87708
87969
  }
87709
87970
  });
87710
87971
  const envelope = marketplaceDiscoveryEnvelopeSchema.parse(await response.json());
@@ -87749,7 +88010,7 @@ async function resolveServiceListing(id2, config2, fetchImpl, endpointName) {
87749
88010
  }
87750
88011
  async function findMarketplaceApiByRef(ref, config2, fetchImpl) {
87751
88012
  const page = await searchMarketplace(
87752
- { query: ref, kinds: ["api"], limit: 50, includeUnverified: true },
88013
+ { query: ref, kinds: ["api"], limit: 50, includeUnverified: true, includeOutage: true },
87753
88014
  config2,
87754
88015
  fetchImpl
87755
88016
  );
@@ -87767,6 +88028,7 @@ async function fetchCallsDiscovery(query, config2, fetchImpl) {
87767
88028
  configureUrl(url2) {
87768
88029
  url2.searchParams.set("q", query);
87769
88030
  url2.searchParams.set("includeUnverified", "true");
88031
+ url2.searchParams.set("includeOutage", "true");
87770
88032
  }
87771
88033
  });
87772
88034
  return parseDiscovery(await response.json());
@@ -87839,6 +88101,18 @@ function isEnotfound(error61) {
87839
88101
  return false;
87840
88102
  }
87841
88103
 
88104
+ // ../mcp/src/tools/search.ts
88105
+ async function searchMarketplace2(...args) {
88106
+ const page = await searchMarketplace(...args);
88107
+ return {
88108
+ ...page,
88109
+ items: page.items.map((item) => ({
88110
+ ...item,
88111
+ ...item.fee === void 0 ? {} : { feeDisplay: formatListingFee(item.fee) }
88112
+ }))
88113
+ };
88114
+ }
88115
+
87842
88116
  // ../mcp/src/tools/call.ts
87843
88117
  var VapiCallError = class extends Error {
87844
88118
  constructor(code, message, possibleSettlement2, options) {
@@ -88349,7 +88623,7 @@ function receiptContext(args, trace, resourceUrl) {
88349
88623
  };
88350
88624
  }
88351
88625
  function errorOutcome(error61, code) {
88352
- if (code === "max_price_exceeded" || code.includes("cap_exceeded")) {
88626
+ if (error61 instanceof SpendCapExceededError || code === "max_price_exceeded" || code.includes("cap_exceeded")) {
88353
88627
  return "declined_policy";
88354
88628
  }
88355
88629
  if (error61 instanceof VapiCallError) {
@@ -88691,6 +88965,7 @@ function paidRequestTimeoutMs(timeoutSeconds, internalTimeoutMs, offerTimeoutSec
88691
88965
  return usableOfferTimeout === void 0 ? 12e4 : Math.min(12e4, Math.max(3e4, usableOfferTimeout * 1e3));
88692
88966
  }
88693
88967
  function mapX402PaymentError(error61, resumeId) {
88968
+ if (error61 instanceof SpendCapExceededError) return error61;
88694
88969
  if (!(error61 instanceof X402PaymentError)) return error61;
88695
88970
  if (error61.code === "payment_rejected") {
88696
88971
  return new VapiCallError("payment_rejected", error61.message, void 0, {
@@ -88750,9 +89025,11 @@ async function inspectService(input2, config2, fetchImpl) {
88750
89025
  ...endpoint.operationId === void 0 ? {} : { operationId: endpoint.operationId },
88751
89026
  ...endpoint.requestContentType === void 0 ? {} : { requestContentType: endpoint.requestContentType },
88752
89027
  ...endpoint.requestSchema === void 0 ? {} : { requestSchema: endpoint.requestSchema },
89028
+ ...endpoint.responseSchema === void 0 ? {} : { responseSchema: endpoint.responseSchema },
89029
+ ...endpoint.exampleRequest === void 0 ? {} : { exampleRequest: endpoint.exampleRequest },
88753
89030
  ...endpoint.responseContentType === void 0 ? {} : { responseContentType: endpoint.responseContentType },
88754
89031
  ...service.group === void 0 ? {} : { group: service.group },
88755
- ...service.fee === void 0 ? {} : { fee: service.fee },
89032
+ ...service.fee === void 0 ? {} : { fee: service.fee, feeDisplay: formatListingFee(service.fee) },
88756
89033
  verification: service.verification,
88757
89034
  ...healthOf(service),
88758
89035
  payment: endpoint.payment ?? null
@@ -88767,14 +89044,16 @@ function inspectIndexedHit(hit) {
88767
89044
  description: hit.card.summary,
88768
89045
  network: hit.execution.network,
88769
89046
  ...hit.group === void 0 ? {} : { group: hit.group },
88770
- ...hit.fee === void 0 ? {} : { fee: hit.fee },
89047
+ ...hit.fee === void 0 ? {} : { fee: hit.fee, feeDisplay: formatListingFee(hit.fee) },
88771
89048
  verification: hit.verification,
88772
89049
  ...healthOf(hit),
88773
89050
  payment: null
88774
89051
  };
88775
89052
  }
88776
89053
  function healthOf(listing) {
89054
+ const health = listingHealthSchema.optional().catch(void 0).parse(listing.health);
88777
89055
  return {
89056
+ ...health === void 0 ? {} : { health },
88778
89057
  ...listing.liveness === void 0 ? {} : { liveness: listing.liveness },
88779
89058
  ...listing.conformance === void 0 ? {} : { conformance: listing.conformance },
88780
89059
  ...listing.identity === void 0 ? {} : { identity: listing.identity }
@@ -88793,6 +89072,160 @@ function inspectionCacheKey(input2) {
88793
89072
  return JSON.stringify([input2.id, input2.endpoint ?? null]);
88794
89073
  }
88795
89074
 
89075
+ // ../mcp/src/actions/hints.ts
89076
+ function searchHints(page, options) {
89077
+ const hints = [];
89078
+ const apis = page.items.filter((hit) => hit.kind === "api");
89079
+ const payable = apis.find(
89080
+ (hit) => hit.action.type === "invoke_api" && hit.execution.payable !== false
89081
+ );
89082
+ if (payable) {
89083
+ hints.push(
89084
+ `Inspect before paying: ${renderAction(options.surface, "inspect", { id: payable.ref })}`
89085
+ );
89086
+ }
89087
+ hints.push(
89088
+ ...apis.flatMap(
89089
+ (hit) => (hit.alternatives ?? []).map((alternative) => {
89090
+ const reason = alternative.reason === "cheaper" ? "cheaper healthy" : "healthier";
89091
+ return `${hit.ref} has a ${reason} alternative: ${alternative.ref}`;
89092
+ })
89093
+ ).slice(0, 2)
89094
+ );
89095
+ const hiddenOutage = page.totals?.hiddenOutage ?? 0;
89096
+ if (options.includeOutage !== true && hiddenOutage > 0) {
89097
+ const count = hiddenOutage === 1 ? "1 listing in outage is" : `${hiddenOutage} listings in outage are`;
89098
+ hints.push(
89099
+ options.surface === "cli" ? `${count} hidden; add --include-outage to show them.` : `${count} hidden; call with includeOutage: true to show them.`
89100
+ );
89101
+ }
89102
+ if (page.items.length === 0) {
89103
+ hints.push(
89104
+ `Broaden your search with: ${renderAction(options.surface, "search", { includeUnverified: true })}`
89105
+ );
89106
+ }
89107
+ return hints.slice(0, 4);
89108
+ }
89109
+ function inspectHints(result, options) {
89110
+ const hints = [];
89111
+ if (result.health?.state === "degraded" || result.health?.state === "outage") {
89112
+ hints.push(
89113
+ options.surface === "agent" ? `Recent checks show ${result.health.state}; find another API with: ${renderAction(options.surface, "search", {})}` : `Recent checks show ${result.health.state}; retry inspection later with: ${renderAction(options.surface, "inspect", { id: options.ref })}`
89114
+ );
89115
+ }
89116
+ if (typeof result.payment?.protocol === "string") {
89117
+ hints.push(
89118
+ `This payment protocol is not supported; find another API with: ${renderAction(options.surface, "search", {})}`
89119
+ );
89120
+ return hints;
89121
+ }
89122
+ const query = result.exampleRequest?.query;
89123
+ const hasQuery = query !== void 0 && Object.keys(query).length > 0;
89124
+ const queryInBody = result.method === "GET" || result.method === "HEAD";
89125
+ let body = result.exampleRequest?.body;
89126
+ if (queryInBody && hasQuery) {
89127
+ body = { ...isRecord6(body) ? body : {}, ...query };
89128
+ }
89129
+ if (body === void 0) body = requiredBody(result.requestSchema);
89130
+ if (options.surface === "agent" && !queryInBody && hasQuery) {
89131
+ hints.push(
89132
+ `This example needs URL query parameters; find another API with: ${renderAction(options.surface, "search", {})}`
89133
+ );
89134
+ } else if (options.surface === "agent" && (exactPrice(result.price) === void 0 || result.method === null)) {
89135
+ hints.push(
89136
+ `Find an API with a published price and method: ${renderAction(options.surface, "search", {})}`
89137
+ );
89138
+ } else {
89139
+ const queryUrl = !queryInBody && hasQuery ? new URL(result.url) : void 0;
89140
+ if (queryUrl) {
89141
+ for (const [key2, value] of Object.entries(query)) queryUrl.searchParams.set(key2, value);
89142
+ }
89143
+ const direct = queryUrl !== void 0 || result.network !== void 0 || /^https?:\/\//u.test(options.ref);
89144
+ hints.push(
89145
+ `Pay with: ${renderAction(
89146
+ options.surface,
89147
+ "pay",
89148
+ {
89149
+ ...queryUrl === void 0 ? { id: options.ref } : { url: queryUrl.href },
89150
+ ...!direct && result.name ? { endpoint: result.name } : {},
89151
+ ...direct ? { method: result.method ?? "<method>" } : {},
89152
+ body,
89153
+ ...queryUrl !== void 0 && result.requestContentType !== void 0 ? { contentType: result.requestContentType } : {},
89154
+ ...queryUrl !== void 0 && result.payment?.network !== void 0 ? { network: result.payment.network } : {},
89155
+ ...queryUrl !== void 0 && result.payment?.payTo !== void 0 ? { expectedPayTo: result.payment.payTo } : {}
89156
+ },
89157
+ result.price
89158
+ )}`
89159
+ );
89160
+ }
89161
+ return hints;
89162
+ }
89163
+ function payHints(result, options) {
89164
+ const hints = [];
89165
+ const settlementUnknown2 = result.outcome === "settlement_unknown";
89166
+ if (result.status >= 200 && result.status < 300 && !settlementUnknown2) {
89167
+ if (options.surface === "cli") {
89168
+ hints.push(
89169
+ `Receipt saved; review it with: vapi receipts --limit 1${result.wallet ? ` --account ${shellWord(result.wallet)}` : ""}`
89170
+ );
89171
+ } else if (options.surface === "mcp") {
89172
+ hints.push(
89173
+ `Receipt saved; review it with: receipts.list ${JSON.stringify({ limit: 1, ...result.wallet ? { wallet: result.wallet } : {} })}`
89174
+ );
89175
+ } else if (options.ref) {
89176
+ hints.push(
89177
+ `Review the request contract with: ${renderAction(options.surface, "inspect", { id: options.ref })}`
89178
+ );
89179
+ }
89180
+ return hints;
89181
+ }
89182
+ if (options.ref) {
89183
+ hints.push(
89184
+ `The provider answered ${result.status}; check the request contract with: ${renderAction(options.surface, "inspect", { id: options.ref })}`
89185
+ );
89186
+ }
89187
+ const receiptId = options.receiptId ?? result.receiptId;
89188
+ if ((result.status === 402 || settlementUnknown2) && receiptId && options.surface === "cli") {
89189
+ hints.push(`Check settlement with: vapi pay --resume ${shellWord(receiptId)}`);
89190
+ }
89191
+ return hints;
89192
+ }
89193
+ function renderAction(surface, action, args, price) {
89194
+ if (surface === "agent") {
89195
+ const loopArgs = action === "search" ? { query: "api", network: null, includeOutage: false } : action === "inspect" ? { ref: args.id } : { ref: args.id, body: JSON.stringify(args.body), max_usd: exactPrice(price ?? "") };
89196
+ return `call_${action} ${JSON.stringify(loopArgs)}`;
89197
+ }
89198
+ if (surface === "mcp") return `call.${action} ${JSON.stringify(args)}`;
89199
+ if (action === "search") return "vapi search --include-unverified";
89200
+ const command = `vapi ${action} ${shellWord(args.url ?? args.id ?? "")}`;
89201
+ if (action === "inspect") return command;
89202
+ const endpoint = args.endpoint ? ` --endpoint ${shellWord(args.endpoint)}` : "";
89203
+ const method = args.method ? ` --method ${shellWord(args.method)}` : "";
89204
+ const headers = args.contentType ? ` --content-type ${shellWord(args.contentType)}` : "";
89205
+ const network = args.network ? ` --network ${shellWord(args.network)}` : "";
89206
+ const payee = args.expectedPayTo ? ` --expected-pay-to ${shellWord(args.expectedPayTo)}` : "";
89207
+ return `${command}${endpoint}${method} --body ${shellQuote(args.body === "<json>" ? "<json>" : JSON.stringify(args.body) ?? "<json>")}${headers}${network}${payee}`;
89208
+ }
89209
+ function exactPrice(price) {
89210
+ if (!/^\$(0|[1-9]\d*)(?:\.\d{1,6})?$/u.test(price.trim())) return void 0;
89211
+ const value = Number(price.trim().slice(1));
89212
+ return Number.isFinite(value) ? value : void 0;
89213
+ }
89214
+ function requiredBody(schema) {
89215
+ if (!isRecord6(schema) || !Array.isArray(schema.required)) return "<json>";
89216
+ const names = schema.required.filter((name) => typeof name === "string");
89217
+ return names.length > 0 ? Object.fromEntries(names.map((name) => [name, "<value>"])) : "<json>";
89218
+ }
89219
+ function isRecord6(value) {
89220
+ return typeof value === "object" && value !== null && !Array.isArray(value);
89221
+ }
89222
+ function shellWord(value) {
89223
+ return /^[a-zA-Z0-9_./:@%-]+$/u.test(value) ? value : shellQuote(value);
89224
+ }
89225
+ function shellQuote(value) {
89226
+ return `'${value.replaceAll("'", "'\\''")}'`;
89227
+ }
89228
+
88796
89229
  // ../mcp/src/actions/call.ts
88797
89230
  var MAX_CACHED_MARKETPLACE_REFS = 200;
88798
89231
  var walletArgument = {
@@ -88801,6 +89234,7 @@ var walletArgument = {
88801
89234
  )
88802
89235
  };
88803
89236
  var callToolResultSchema = external_exports.object({
89237
+ hints: external_exports.array(external_exports.string()).max(4),
88804
89238
  wallet: external_exports.string(),
88805
89239
  status: external_exports.number().int(),
88806
89240
  body: external_exports.unknown(),
@@ -88823,6 +89257,7 @@ var callToolResultSchema = external_exports.object({
88823
89257
  }).optional()
88824
89258
  });
88825
89259
  var inspectToolResultSchema = external_exports.object({
89260
+ hints: external_exports.array(external_exports.string()).max(4),
88826
89261
  name: external_exports.string(),
88827
89262
  method: external_exports.string().nullable(),
88828
89263
  url: external_exports.url(),
@@ -88831,13 +89266,17 @@ var inspectToolResultSchema = external_exports.object({
88831
89266
  operationId: external_exports.string().optional(),
88832
89267
  requestContentType: external_exports.string().optional(),
88833
89268
  requestSchema: external_exports.unknown().optional(),
89269
+ responseSchema: discoveryEndpointSchema.shape.responseSchema,
89270
+ exampleRequest: discoveryEndpointSchema.shape.exampleRequest,
88834
89271
  responseContentType: external_exports.string().optional(),
88835
89272
  network: external_exports.string().optional(),
88836
89273
  // Registry-owned listing disclosures, mirrored from call.search.
88837
89274
  group: listingGroupSchema.optional(),
88838
89275
  fee: listingFeeSchema.optional(),
89276
+ feeDisplay: external_exports.string().optional(),
88839
89277
  verification: listingVerificationSchema,
88840
89278
  liveness: listingLivenessSchema.optional(),
89279
+ health: listingHealthSchema.optional().catch(void 0),
88841
89280
  conformance: listingConformanceSchema.optional(),
88842
89281
  identity: listingIdentitySchema.optional(),
88843
89282
  payment: discoveryEndpointSchema.shape.payment.unwrap().nullable()
@@ -88850,6 +89289,9 @@ var callSearchInputSchema = external_exports.object({
88850
89289
  cursor: external_exports.string().trim().min(1).max(4096).optional(),
88851
89290
  includeUnverified: external_exports.boolean().optional().describe(
88852
89291
  "Default results are vAPI-verified listings plus mirrored external catalogs; includeUnverified: true adds unverified self-listed APIs, which passed vAPI's automated x402 probe but were not reviewed."
89292
+ ),
89293
+ includeOutage: external_exports.boolean().optional().describe(
89294
+ "Default results hide listings whose recent health checks show an outage; includeOutage: true shows them."
88853
89295
  )
88854
89296
  });
88855
89297
  var callInspectInputSchema = external_exports.object({
@@ -88874,11 +89316,14 @@ var callPayInputSchema = external_exports.object({
88874
89316
  "Seconds to wait for the paid response. Default: the provider's maxTimeoutSeconds, at most 120."
88875
89317
  )
88876
89318
  });
89319
+ var callSearchOutputSchema = marketplaceDiscoveryPageSchema.extend({
89320
+ hints: external_exports.array(external_exports.string()).max(4)
89321
+ });
88877
89322
  var callSearch = defineAction({
88878
89323
  name: "call.search",
88879
89324
  description: "Search the public vAPI Marketplace for APIs, services, and open requests. API results can be paid locally; other results continue at their web action. Search returns public cards, not request bodies \u2014 use call.inspect before call.pay whenever the request contract is not already known.",
88880
89325
  input: callSearchInputSchema,
88881
- output: marketplaceDiscoveryPageSchema,
89326
+ output: callSearchOutputSchema,
88882
89327
  money: "none",
88883
89328
  grant: "call",
88884
89329
  async run(input2, ctx) {
@@ -88886,7 +89331,13 @@ var callSearch = defineAction({
88886
89331
  if (ctx.caller.run) {
88887
89332
  for (const item of page.items) ctx.caller.run.searchedRefs.add(item.ref);
88888
89333
  }
88889
- return page;
89334
+ return {
89335
+ ...page,
89336
+ hints: searchHints(page, {
89337
+ surface: ctx.caller.surface,
89338
+ ...input2.includeOutage === void 0 ? {} : { includeOutage: input2.includeOutage }
89339
+ })
89340
+ };
88890
89341
  }
88891
89342
  });
88892
89343
  var callInspect = defineAction({
@@ -88899,10 +89350,13 @@ var callInspect = defineAction({
88899
89350
  async run(input2, ctx) {
88900
89351
  const cacheKey2 = inspectionCacheKey(input2);
88901
89352
  const cached2 = ctx.caller.run?.inspected.get(cacheKey2);
88902
- if (cached2) return cached2;
88903
- const result = await ctx.call.inspect(input2);
88904
- ctx.caller.run?.inspected.set(cacheKey2, result);
88905
- return result;
89353
+ const result = cached2 ?? await ctx.call.inspect(input2);
89354
+ if (!cached2) ctx.caller.run?.inspected.set(cacheKey2, result);
89355
+ return {
89356
+ ...result,
89357
+ payment: result.payment ?? null,
89358
+ hints: inspectHints(result, { ref: input2.id, surface: ctx.caller.surface })
89359
+ };
88906
89360
  }
88907
89361
  });
88908
89362
  var callPay = defineAction({
@@ -88913,14 +89367,22 @@ var callPay = defineAction({
88913
89367
  money: "spends",
88914
89368
  grant: "call",
88915
89369
  async run(input2, ctx) {
88916
- return await ctx.call.pay(input2);
89370
+ const result = await ctx.call.pay(input2);
89371
+ return {
89372
+ ...result,
89373
+ hints: payHints(result, {
89374
+ surface: ctx.caller.surface,
89375
+ ...input2.id === void 0 ? {} : { ref: input2.id },
89376
+ ...input2.url === void 0 ? {} : { url: input2.url }
89377
+ })
89378
+ };
88917
89379
  }
88918
89380
  });
88919
89381
  function createCallPort(options) {
88920
89382
  const searchedMarketplaceHits = options.cacheMarketplaceHits ? /* @__PURE__ */ new Map() : void 0;
88921
89383
  return {
88922
89384
  async search(input2) {
88923
- const page = await searchMarketplace(input2, options.config, options.fetchImpl, {
89385
+ const page = await searchMarketplace2(input2, options.config, options.fetchImpl, {
88924
89386
  ...options.searchesPath === void 0 ? {} : { searchesPath: options.searchesPath },
88925
89387
  ...options.notice === void 0 ? {} : { notice: options.notice }
88926
89388
  });
@@ -89377,6 +89839,15 @@ async function checkAction(action, input2, ctx, options = {}) {
89377
89839
  }
89378
89840
  const priceUsd = exactUsdcPrice(listing.price);
89379
89841
  const profile = ctx.caller.profile;
89842
+ if (priceUsd !== null && ctx.caps !== void 0 && priceUsd > ctx.caps.perCallUsd) {
89843
+ throw new SpendCapExceededError({
89844
+ cap: "per_call",
89845
+ amountUsd: listing.price.trim().slice(1),
89846
+ limitUsd: String(ctx.caps.perCallUsd),
89847
+ ...ctx.caps.perDayUsd === void 0 ? {} : { perDayLimitUsd: ctx.caps.perDayUsd },
89848
+ wallet: profile.wallet
89849
+ });
89850
+ }
89380
89851
  const decision = decidePayment({
89381
89852
  ref,
89382
89853
  priceUsd,
@@ -89397,10 +89868,12 @@ async function checkAction(action, input2, ctx, options = {}) {
89397
89868
  }
89398
89869
  const maxUsd = Number(input2.maxPriceUsd);
89399
89870
  if (priceUsd !== null && maxUsd < priceUsd) {
89400
- return {
89401
- kind: "deny",
89402
- reason: `Requested maximum $${maxUsd} is below the listing price $${priceUsd}.`
89403
- };
89871
+ throw new SpendCapExceededError({
89872
+ cap: "max_price",
89873
+ amountUsd: listing.price.trim().slice(1),
89874
+ limitUsd: String(maxUsd),
89875
+ wallet: profile.wallet
89876
+ });
89404
89877
  }
89405
89878
  return { kind: "allow" };
89406
89879
  }
@@ -89943,6 +90416,7 @@ function createAgentRunDeps(input2) {
89943
90416
  config: input2.config,
89944
90417
  home: input2.home,
89945
90418
  chat: input2.chat,
90419
+ searchPage: call2.search,
89946
90420
  async search(query) {
89947
90421
  const page = await call2.search(query);
89948
90422
  const rows = page.items.map((hit) => ({
@@ -89991,7 +90465,10 @@ function createAgentRunDeps(input2) {
89991
90465
  network: result.payment?.network ?? listing?.payment?.network ?? listing?.network ?? ""
89992
90466
  };
89993
90467
  },
89994
- caps: { perCallUsd: Number(input2.spendCaps.perCallAtomic) / 1e6 },
90468
+ caps: {
90469
+ perCallUsd: Number(input2.spendCaps.perCallAtomic) / 1e6,
90470
+ perDayUsd: formatUsdc(BigInt(input2.spendCaps.perDayAtomic))
90471
+ },
89995
90472
  approve: input2.approve,
89996
90473
  ...input2.budget === void 0 ? {} : { budget: input2.budget },
89997
90474
  ...input2.runId === void 0 ? {} : { runId: input2.runId },
@@ -90001,6 +90478,7 @@ function createAgentRunDeps(input2) {
90001
90478
  return {
90002
90479
  ...this,
90003
90480
  search: this.search === dependencies.search ? next.search : this.search,
90481
+ searchPage: this.searchPage !== dependencies.searchPage ? this.searchPage : this.search === dependencies.search ? next.searchPage : void 0,
90004
90482
  inspect: this.inspect === dependencies.inspect ? next.inspect : this.inspect,
90005
90483
  read: this.read === dependencies.read ? next.read : this.read,
90006
90484
  pay: this.pay === dependencies.pay ? next.pay : this.pay,
@@ -90032,7 +90510,11 @@ var loopSearchResultSchema = external_exports.array(
90032
90510
  description: external_exports.string().optional()
90033
90511
  })
90034
90512
  );
90035
- var loopPayResultSchema = external_exports.object({ status: external_exports.number(), body: external_exports.unknown() });
90513
+ var loopPayResultSchema = external_exports.object({
90514
+ status: external_exports.number(),
90515
+ body: external_exports.unknown(),
90516
+ hints: external_exports.array(external_exports.string()).max(4)
90517
+ });
90036
90518
  var LOOP_BINDINGS = {
90037
90519
  "call.search": {
90038
90520
  description: "Search vAPI Call listings available to this agent. Set network to null to search every network, or to a CAIP-2 id such as eip155:8453 (Base) or eip155:5042 (Arc).",
@@ -90040,25 +90522,32 @@ var LOOP_BINDINGS = {
90040
90522
  type: "object",
90041
90523
  properties: {
90042
90524
  query: { type: "string" },
90043
- network: { type: ["string", "null"] }
90525
+ network: { type: ["string", "null"] },
90526
+ includeOutage: { type: ["boolean", "null"] }
90044
90527
  },
90045
- required: ["query", "network"],
90528
+ required: ["query", "network", "includeOutage"],
90046
90529
  additionalProperties: false
90047
90530
  },
90048
- output: loopSearchResultSchema,
90531
+ output: external_exports.union([callSearchOutputSchema, loopSearchResultSchema]),
90049
90532
  summary: "Search completed.",
90050
90533
  parseArguments(value, deps) {
90051
90534
  const args = parseObjectArgs(value);
90052
90535
  const query = requiredString2(args, "query");
90053
90536
  const network = searchNetwork(nullableString(args, "network"));
90537
+ const includeOutage = args.includeOutage;
90538
+ if (includeOutage !== void 0 && includeOutage !== null && typeof includeOutage !== "boolean") {
90539
+ throw new ToolInputError("includeOutage must be a boolean or null.");
90540
+ }
90054
90541
  return {
90055
90542
  query,
90056
90543
  ...network === null ? {} : { network },
90057
- includeUnverified: !deps.profile.verifiedOnly
90544
+ includeUnverified: !deps.profile.verifiedOnly,
90545
+ ...includeOutage == null ? {} : { includeOutage }
90058
90546
  };
90059
90547
  },
90060
90548
  async run(input2, ctx, execution) {
90061
90549
  const search2 = input2;
90550
+ if (execution.deps.searchPage) return await callSearch.run(search2, ctx);
90062
90551
  const rows = await execution.deps.search(search2);
90063
90552
  for (const row of rows) ctx.caller.run?.searchedRefs.add(row.ref);
90064
90553
  return rows;
@@ -90078,14 +90567,8 @@ var LOOP_BINDINGS = {
90078
90567
  const args = parseObjectArgs(value);
90079
90568
  return { id: requiredString2(args, "ref") };
90080
90569
  },
90081
- async run(input2, ctx, execution) {
90082
- const { id: id2 } = input2;
90083
- const cacheKey2 = inspectionCacheKey({ id: id2 });
90084
- const cached2 = ctx.caller.run?.inspected.get(cacheKey2);
90085
- if (cached2) return cached2;
90086
- const result = await execution.deps.inspect(id2);
90087
- ctx.caller.run?.inspected.set(cacheKey2, result);
90088
- return result;
90570
+ async run(input2, ctx) {
90571
+ return await callInspect.run(input2, ctx);
90089
90572
  }
90090
90573
  },
90091
90574
  "call.pay": {
@@ -90130,7 +90613,8 @@ var LOOP_BINDINGS = {
90130
90613
  }
90131
90614
  return {
90132
90615
  status: execution.payment.status,
90133
- body: execution.payment.body
90616
+ body: execution.payment.body,
90617
+ hints: payHints(execution.payment, { ref: id2, surface: ctx.caller.surface })
90134
90618
  };
90135
90619
  }
90136
90620
  },
@@ -90280,7 +90764,8 @@ async function runAgent(task, deps) {
90280
90764
  config: deps.config,
90281
90765
  clock: deps.now ?? (() => /* @__PURE__ */ new Date()),
90282
90766
  call: {
90283
- async search() {
90767
+ async search(input2) {
90768
+ if (runDeps.searchPage) return await runDeps.searchPage(input2);
90284
90769
  throw new Error("The agent loop uses its reduced search binding.");
90285
90770
  },
90286
90771
  async inspect({ id: id2 }) {
@@ -90425,6 +90910,18 @@ ${UNTRUSTED_NOTICE}` },
90425
90910
  fatalDetail: "The local audit log could not be written."
90426
90911
  };
90427
90912
  }
90913
+ if (error61 instanceof SpendCapExceededError) {
90914
+ const ref2 = paymentRef(input2);
90915
+ const reason = callRunBudgetReason(error61, runDeps.budget) ?? callBudgetReason(error61);
90916
+ if (ref2 !== void 0 && reason !== void 0) {
90917
+ const outcome = await declineSafely(ref2, reason);
90918
+ return outcome.fatalDetail === void 0 ? {
90919
+ ...outcome,
90920
+ fatalDetail: reason,
90921
+ ...error61.cap === "run_budget" ? { fatalReason: "run_budget" } : {}
90922
+ } : outcome;
90923
+ }
90924
+ }
90428
90925
  if (error61 instanceof ActionDeclinedError) {
90429
90926
  const declinedRef = actionDeclineRef(action, input2);
90430
90927
  if (declinedRef !== void 0) {
@@ -90442,7 +90939,8 @@ ${UNTRUSTED_NOTICE}` },
90442
90939
  }
90443
90940
  const runBudgetReason = callRunBudgetReason(error61.paymentError, runDeps.budget);
90444
90941
  if (runBudgetReason !== void 0) {
90445
- return await declineSafely(ref, runBudgetReason);
90942
+ const outcome = await declineSafely(ref, runBudgetReason);
90943
+ return spendCap(error61.paymentError) === "run_budget" ? { ...outcome, fatalDetail: runBudgetReason, fatalReason: "run_budget" } : outcome;
90446
90944
  }
90447
90945
  const spendBudgetReason = callBudgetReason(error61.paymentError);
90448
90946
  if (spendBudgetReason !== void 0) {
@@ -90464,7 +90962,7 @@ ${UNTRUSTED_NOTICE}` },
90464
90962
  try {
90465
90963
  reply = await deps.chat({ model: profile.model, messages, tools, tool_choice: "auto" });
90466
90964
  } catch (error61) {
90467
- if (error61 instanceof RunBudgetError || hasErrorCode(error61, "run_budget_exceeded")) {
90965
+ if (error61 instanceof RunBudgetError || hasErrorCode(error61, "run_budget_exceeded") || spendCap(error61) === "run_budget") {
90468
90966
  return await stop("run_budget", runBudgetDetail(runDeps.budget));
90469
90967
  }
90470
90968
  if (hasErrorCode(error61, "budget_exhausted")) {
@@ -90511,7 +91009,9 @@ ${UNTRUSTED_NOTICE}` },
90511
91009
  name: call2.name,
90512
91010
  summary: toolSummary(call2.name, loopActions)
90513
91011
  });
90514
- if (outcome.fatalDetail) return await stop("error", outcome.fatalDetail);
91012
+ if (outcome.fatalDetail) {
91013
+ return await stop(outcome.fatalReason ?? "error", outcome.fatalDetail);
91014
+ }
90515
91015
  }
90516
91016
  }
90517
91017
  return await stop("max_steps");
@@ -90604,6 +91104,14 @@ function hasErrorCode(error61, code) {
90604
91104
  return typeof error61 === "object" && error61 !== null && typeof Reflect.get(error61, "code") === "string" && Reflect.get(error61, "code") === code;
90605
91105
  }
90606
91106
  function callBudgetReason(error61) {
91107
+ const cap = spendCap(error61);
91108
+ if (cap !== void 0) {
91109
+ if (cap === "per_call") return "This wallet's per-call Call budget is exhausted.";
91110
+ if (cap === "per_day") return "This wallet's daily Call budget is exhausted.";
91111
+ if (cap === "max_price") return "This call exceeds its maximum price.";
91112
+ if (cap === "max_amount") return "This payment exceeds its maximum amount.";
91113
+ return void 0;
91114
+ }
90607
91115
  if (hasErrorCode(error61, "per_call_cap_exceeded")) {
90608
91116
  return "This wallet's per-call Call budget is exhausted.";
90609
91117
  }
@@ -90613,11 +91121,17 @@ function callBudgetReason(error61) {
90613
91121
  return void 0;
90614
91122
  }
90615
91123
  function callRunBudgetReason(error61, budget) {
90616
- if (!(error61 instanceof RunBudgetError) && !hasErrorCode(error61, "run_budget_exceeded")) {
91124
+ if (!(error61 instanceof RunBudgetError) && spendCap(error61) !== "run_budget" && !hasErrorCode(error61, "run_budget_exceeded")) {
90617
91125
  return void 0;
90618
91126
  }
90619
91127
  return budget === void 0 ? "The run budget is spent; this call was not paid." : `The run budget of $${formatUsdc(budget.limitAtomic)} is spent; this call was not paid.`;
90620
91128
  }
91129
+ function spendCap(error61) {
91130
+ if (error61 instanceof SpendCapExceededError) return error61.cap;
91131
+ if (!hasErrorCode(error61, "spend_cap_exceeded")) return void 0;
91132
+ const cap = Reflect.get(error61, "cap");
91133
+ return cap === "per_call" || cap === "per_day" || cap === "max_price" || cap === "max_amount" || cap === "run_budget" ? cap : void 0;
91134
+ }
90621
91135
  function runBudgetDetail(budget) {
90622
91136
  return budget === void 0 ? "The run budget is spent." : `The run budget of $${formatUsdc(budget.limitAtomic)} is spent.`;
90623
91137
  }
@@ -91070,8 +91584,8 @@ async function memberBudgetAtomic(account, configured, deps) {
91070
91584
  deps.now?.() ?? /* @__PURE__ */ new Date(),
91071
91585
  account
91072
91586
  );
91073
- const remaining = BigInt(caps.perDayAtomic) - BigInt(ledger.spentAtomic);
91074
- return remaining < 0n ? 0n : remaining;
91587
+ const remaining2 = BigInt(caps.perDayAtomic) - BigInt(ledger.spentAtomic);
91588
+ return remaining2 < 0n ? 0n : remaining2;
91075
91589
  }
91076
91590
  function withoutTreasuryGrants(profile) {
91077
91591
  return {
@@ -93066,9 +93580,9 @@ async function watchEvents(ctx, input2, now, sleep, deadline, signal, progress)
93066
93580
  const reached = input2.until !== void 0 && next.events.some((event) => taskStateMatches(input2.until, taskEventState(event)));
93067
93581
  if (next.events.length || reached)
93068
93582
  return { ...next, ...reached ? { reached: input2.until } : {}, timedOut: false };
93069
- const remaining = deadline - now().getTime();
93070
- if (remaining <= 0) return { ...next, timedOut: true };
93071
- await sleep(Math.min(TASK_LIMITS.watchIntervalMinMs, remaining), signal);
93583
+ const remaining2 = deadline - now().getTime();
93584
+ if (remaining2 <= 0) return { ...next, timedOut: true };
93585
+ await sleep(Math.min(TASK_LIMITS.watchIntervalMinMs, remaining2), signal);
93072
93586
  if (now().getTime() >= deadline)
93073
93587
  return { events: [], nextCursor: progress.cursor, timedOut: true };
93074
93588
  }
@@ -94111,9 +94625,15 @@ var VapiMcpServer = class {
94111
94625
  return tool.deprecatedReplacement ? withDeprecation(result, tool.deprecatedReplacement) : result;
94112
94626
  }
94113
94627
  }
94114
- connectStdio() {
94628
+ #output = process.stdout;
94629
+ /**
94630
+ * Serves JSON-RPC lines from `input` and answers on `output`. The desktop
94631
+ * app hands in a socket; the CLI hands in stdio through connectStdio().
94632
+ */
94633
+ connect(input2, output4) {
94115
94634
  if (this.#stdio) return;
94116
- this.#stdio = createInterface({ input: process.stdin, crlfDelay: Infinity });
94635
+ this.#output = output4;
94636
+ this.#stdio = createInterface({ input: input2, crlfDelay: Infinity });
94117
94637
  this.#stdio.on("line", (line) => {
94118
94638
  void this.#handleLine(line);
94119
94639
  });
@@ -94122,6 +94642,9 @@ var VapiMcpServer = class {
94122
94642
  this.#onClose?.();
94123
94643
  });
94124
94644
  }
94645
+ connectStdio() {
94646
+ this.connect(process.stdin, process.stdout);
94647
+ }
94125
94648
  async close() {
94126
94649
  this.#stdio?.close();
94127
94650
  this.#stdio = void 0;
@@ -94202,7 +94725,7 @@ var VapiMcpServer = class {
94202
94725
  }
94203
94726
  }
94204
94727
  #write(message) {
94205
- process.stdout.write(`${JSON.stringify(message)}
94728
+ this.#output.write(`${JSON.stringify(message)}
94206
94729
  `);
94207
94730
  }
94208
94731
  };
@@ -94987,7 +95510,8 @@ async function startStdioServer(options) {
94987
95510
  return server;
94988
95511
  }
94989
95512
  function toolError(error61) {
94990
- const text = error61 instanceof VapiCallError ? JSON.stringify(
95513
+ const spendCapError = serializeSpendCapError(error61);
95514
+ const text = spendCapError !== void 0 ? JSON.stringify(spendCapError, null, 2) : error61 instanceof VapiCallError ? JSON.stringify(
94991
95515
  {
94992
95516
  error: error61.message,
94993
95517
  code: error61.code,
@@ -95009,6 +95533,29 @@ function toolError(error61) {
95009
95533
  content: [{ type: "text", text }]
95010
95534
  };
95011
95535
  }
95536
+ function serializeSpendCapError(error61) {
95537
+ const record2 = asRecord2(error61);
95538
+ if (!(error61 instanceof SpendCapExceededError) && (record2 === void 0 || record2.code !== "spend_cap_exceeded")) {
95539
+ return void 0;
95540
+ }
95541
+ const value = error61;
95542
+ if (typeof value.amountUsd !== "string" || typeof value.limitUsd !== "string") return void 0;
95543
+ if (value.cap !== "per_call" && value.cap !== "per_day" && value.cap !== "max_price" && value.cap !== "max_amount" && value.cap !== "run_budget") {
95544
+ return void 0;
95545
+ }
95546
+ const message = typeof value.message === "string" ? value.message : "A spend cap was exceeded.";
95547
+ return {
95548
+ error: message,
95549
+ code: "spend_cap_exceeded",
95550
+ cap: value.cap,
95551
+ amountUsd: value.amountUsd,
95552
+ limitUsd: value.limitUsd,
95553
+ ...typeof value.spentUsd === "string" ? { spentUsd: value.spentUsd } : {},
95554
+ ...typeof value.wallet === "string" ? { wallet: value.wallet } : {},
95555
+ command: typeof value.command === "string" ? value.command : null,
95556
+ retryable: false
95557
+ };
95558
+ }
95012
95559
  function asRecord2(value) {
95013
95560
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
95014
95561
  }
@@ -95247,12 +95794,6 @@ function createListingsClient(options) {
95247
95794
  query: { wallet }
95248
95795
  });
95249
95796
  },
95250
- async splitters(wallet) {
95251
- return await call2("/api/call/listings/splitters", {
95252
- method: "GET",
95253
- query: { wallet }
95254
- });
95255
- },
95256
95797
  async create(input2) {
95257
95798
  return await call2("/api/call/listings", { method: "POST", body: input2 });
95258
95799
  },
@@ -95326,11 +95867,11 @@ function readProbeOperations(probe) {
95326
95867
  return isOperation(probe.endpoint) ? [probe.endpoint] : [];
95327
95868
  }
95328
95869
  function isOperation(operation) {
95329
- return isRecord6(operation) && typeof operation.name === "string" && operation.name.length > 0;
95870
+ return isRecord7(operation) && typeof operation.name === "string" && operation.name.length > 0;
95330
95871
  }
95331
95872
  function readProbeRejection(probe) {
95332
95873
  const rejection = probe.diagnostics?.rejection;
95333
- return isRecord6(rejection) ? rejection : void 0;
95874
+ return isRecord7(rejection) ? rejection : void 0;
95334
95875
  }
95335
95876
  function formatProbeSteps(probe) {
95336
95877
  const steps = probe.diagnostics?.steps;
@@ -95339,7 +95880,7 @@ function formatProbeSteps(probe) {
95339
95880
  }
95340
95881
  function formatProbeStep(step2) {
95341
95882
  if (typeof step2 === "string") return step2;
95342
- if (!isRecord6(step2)) return JSON.stringify(step2);
95883
+ if (!isRecord7(step2)) return JSON.stringify(step2);
95343
95884
  const label = asString(step2.name) ?? asString(step2.step) ?? asString(step2.label) ?? "step";
95344
95885
  const outcome = asString(step2.status) ?? asString(step2.outcome) ?? asString(step2.result) ?? (typeof step2.ok === "boolean" ? step2.ok ? "ok" : "failed" : void 0);
95345
95886
  const detail = asString(step2.detail) ?? asString(step2.message) ?? asString(step2.description);
@@ -95405,19 +95946,19 @@ async function readJson(response) {
95405
95946
  }
95406
95947
  function readErrorMessage(body) {
95407
95948
  if (typeof body === "string") return body.trim() || void 0;
95408
- if (!isRecord6(body)) return void 0;
95949
+ if (!isRecord7(body)) return void 0;
95409
95950
  const error61 = body.error;
95410
- if (isRecord6(error61)) return asString(error61.message) ?? asString(error61.code);
95951
+ if (isRecord7(error61)) return asString(error61.message) ?? asString(error61.code);
95411
95952
  return asString(body.message) ?? asString(body.error) ?? asString(body.detail);
95412
95953
  }
95413
95954
  function readErrorIssues(body) {
95414
- if (!isRecord6(body)) return [];
95955
+ if (!isRecord7(body)) return [];
95415
95956
  const candidates = [body.issues, body.errors, body.details];
95416
95957
  for (const candidate of candidates) {
95417
95958
  if (!Array.isArray(candidate)) continue;
95418
95959
  const issues = candidate.map((issue2) => {
95419
95960
  if (typeof issue2 === "string") return issue2;
95420
- if (!isRecord6(issue2)) return JSON.stringify(issue2);
95961
+ if (!isRecord7(issue2)) return JSON.stringify(issue2);
95421
95962
  const path = Array.isArray(issue2.path) ? issue2.path.join(".") : asString(issue2.path);
95422
95963
  const message = asString(issue2.message) ?? asString(issue2.code) ?? JSON.stringify(issue2);
95423
95964
  return path ? `${path}: ${message}` : message;
@@ -95429,7 +95970,7 @@ function readErrorIssues(body) {
95429
95970
  function asString(value) {
95430
95971
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
95431
95972
  }
95432
- function isRecord6(value) {
95973
+ function isRecord7(value) {
95433
95974
  return typeof value === "object" && value !== null && !Array.isArray(value);
95434
95975
  }
95435
95976
 
@@ -95464,11 +96005,11 @@ function formatIdentityLines(identity) {
95464
96005
  ];
95465
96006
  }
95466
96007
  function parseIdentityResponse(value) {
95467
- if (!isRecord7(value) || typeof value.wallet !== "string" || value.chain !== "eip155:8453") {
96008
+ if (!isRecord8(value) || typeof value.wallet !== "string" || value.chain !== "eip155:8453") {
95468
96009
  return void 0;
95469
96010
  }
95470
96011
  if (value.identity === null) return null;
95471
- if (!isRecord7(value.identity)) return void 0;
96012
+ if (!isRecord8(value.identity)) return void 0;
95472
96013
  const { identity } = value;
95473
96014
  if (typeof identity.erc8004Id !== "string" || identity.erc8004Id.length === 0 || typeof identity.agentCount !== "number" || !Number.isFinite(identity.agentCount) || typeof identity.registry !== "string") {
95474
96015
  return void 0;
@@ -95482,13 +96023,13 @@ function parseIdentityResponse(value) {
95482
96023
  };
95483
96024
  }
95484
96025
  function parseReputation(value) {
95485
- if (!isRecord7(value)) return void 0;
96026
+ if (!isRecord8(value)) return void 0;
95486
96027
  if (typeof value.score !== "number" || !Number.isFinite(value.score) || typeof value.count !== "number" || !Number.isInteger(value.count) || value.count < 0) {
95487
96028
  return void 0;
95488
96029
  }
95489
96030
  return { score: value.score, count: value.count };
95490
96031
  }
95491
- function isRecord7(value) {
96032
+ function isRecord8(value) {
95492
96033
  return typeof value === "object" && value !== null && !Array.isArray(value);
95493
96034
  }
95494
96035
 
@@ -95787,7 +96328,7 @@ async function offerDashboardLink({
95787
96328
  apiBase
95788
96329
  }) {
95789
96330
  const otherHome = resolve2(home) !== resolve2(getVapiPaths().directory);
95790
- const command = `${otherHome ? `VAPI_HOME=${shellQuote(home)} ` : ""}${apiBase === void 0 ? "" : `VAPI_REGISTRY_URL=${shellQuote(apiBase)} `}vapi login --account ${name}`;
96331
+ const command = `${otherHome ? `VAPI_HOME=${shellQuote2(home)} ` : ""}${apiBase === void 0 ? "" : `VAPI_REGISTRY_URL=${shellQuote2(apiBase)} `}vapi login --account ${name}`;
95791
96332
  const unlinked = {
95792
96333
  linked: false,
95793
96334
  next: [{ kind: "link", account: name, command }]
@@ -95850,7 +96391,7 @@ async function dashboardCommand(argv, json2, io, dependencies) {
95850
96391
  }
95851
96392
  io.stdout(json2 ? JSON.stringify({ account: target.name, url: url2, ...status, opened }) : url2);
95852
96393
  }
95853
- function shellQuote(value) {
96394
+ function shellQuote2(value) {
95854
96395
  return /^[a-zA-Z0-9_./-]+$/u.test(value) ? value : `'${value.replace(/'/gu, "'\\''")}'`;
95855
96396
  }
95856
96397
 
@@ -96323,7 +96864,7 @@ function buildRelayRestorePayload(options) {
96323
96864
  const owner = normalizedOwner(options.owner);
96324
96865
  assertDevice(options.device);
96325
96866
  assertBytes(options.key, 32);
96326
- if (!isRecord8(options.kdf)) throw new Error();
96867
+ if (!isRecord9(options.kdf)) throw new Error();
96327
96868
  const kdf = parseKdf(options.kdf);
96328
96869
  const parsed = backupPlaintextSchema.safeParse(options.vault);
96329
96870
  if (!parsed.success) throw new Error();
@@ -96345,7 +96886,7 @@ function buildRelayRestorePayload(options) {
96345
96886
  async function exportBackupSource(options) {
96346
96887
  try {
96347
96888
  assertBytes(options.vaultKey, 32);
96348
- if (!isRecord8(options.store) || typeof options.store.home !== "string" || typeof options.store.snapshot !== "function" || typeof options.store.reload !== "function") {
96889
+ if (!isRecord9(options.store) || typeof options.store.home !== "string" || typeof options.store.snapshot !== "function" || typeof options.store.reload !== "function") {
96349
96890
  throw new BackupError("backup_invalid_input");
96350
96891
  }
96351
96892
  const networks = normalizeNetworks(options.networks ?? []);
@@ -97078,7 +97619,7 @@ function prettyJson(value) {
97078
97619
  }
97079
97620
  function parseSealed(sealed) {
97080
97621
  const value = JSON.parse(sealed);
97081
- if (!isRecord8(value) || !hasExactKeys(value, RELAY_KEYS) || value.format !== RELAY_FORMAT || value.v !== RELAY_VERSION || typeof value.epk !== "string" || typeof value.nonce !== "string" || typeof value.ciphertext !== "string" || decodeBase64Url(value.epk)?.byteLength !== 32 || decodeBase64Url(value.nonce)?.byteLength !== 12 || (decodeBase64Url(value.ciphertext)?.byteLength ?? 0) < 16) {
97622
+ if (!isRecord9(value) || !hasExactKeys(value, RELAY_KEYS) || value.format !== RELAY_FORMAT || value.v !== RELAY_VERSION || typeof value.epk !== "string" || typeof value.nonce !== "string" || typeof value.ciphertext !== "string" || decodeBase64Url(value.epk)?.byteLength !== 32 || decodeBase64Url(value.nonce)?.byteLength !== 12 || (decodeBase64Url(value.ciphertext)?.byteLength ?? 0) < 16) {
97082
97623
  throw new Error();
97083
97624
  }
97084
97625
  return { epk: value.epk, nonce: value.nonce, ciphertext: value.ciphertext };
@@ -97245,13 +97786,13 @@ async function pathExists4(path) {
97245
97786
  }
97246
97787
  }
97247
97788
  function isMissingFile4(error61) {
97248
- return isErrorCode(error61, "ENOENT");
97789
+ return isErrorCode2(error61, "ENOENT");
97249
97790
  }
97250
97791
  function isExistingFile2(error61) {
97251
- return isErrorCode(error61, "EEXIST");
97792
+ return isErrorCode2(error61, "EEXIST");
97252
97793
  }
97253
- function isErrorCode(error61, code) {
97254
- return isRecord8(error61) && Reflect.get(error61, "code") === code;
97794
+ function isErrorCode2(error61, code) {
97795
+ return isRecord9(error61) && Reflect.get(error61, "code") === code;
97255
97796
  }
97256
97797
  function validateBackupSourceRelationships(source, context) {
97257
97798
  const names = /* @__PURE__ */ new Set();
@@ -97650,7 +98191,7 @@ function assertBytes(value, length) {
97650
98191
  }
97651
98192
  }
97652
98193
  function assertOwnerKey(ownerKey) {
97653
- if (!isRecord8(ownerKey) || ownerKey.kdf !== "hkdf-sha256" && ownerKey.kdf !== "scrypt") {
98194
+ if (!isRecord9(ownerKey) || ownerKey.kdf !== "hkdf-sha256" && ownerKey.kdf !== "scrypt") {
97654
98195
  throw new BackupError("backup_invalid_input");
97655
98196
  }
97656
98197
  assertBytes(ownerKey.key, 32);
@@ -97680,7 +98221,7 @@ function isIsoUtcMilliseconds(value) {
97680
98221
  return false;
97681
98222
  }
97682
98223
  }
97683
- function isRecord8(value) {
98224
+ function isRecord9(value) {
97684
98225
  return typeof value === "object" && value !== null && !Array.isArray(value);
97685
98226
  }
97686
98227
  function hasExactKeys(value, expected) {
@@ -97748,7 +98289,7 @@ async function startRelay(options) {
97748
98289
  );
97749
98290
  if (response.status !== 201) throw new Error();
97750
98291
  const value = await response.json();
97751
- if (!isRecord9(value) || !hasExactKeys2(value, RELAY_START_KEYS) || value.code !== code || typeof value.expiresAt !== "string" || !isIsoUtc(value.expiresAt) || new Date(value.expiresAt).getTime() <= readNow(options.now).getTime()) {
98292
+ if (!isRecord10(value) || !hasExactKeys2(value, RELAY_START_KEYS) || value.code !== code || typeof value.expiresAt !== "string" || !isIsoUtc(value.expiresAt) || new Date(value.expiresAt).getTime() <= readNow(options.now).getTime()) {
97752
98293
  throw new Error();
97753
98294
  }
97754
98295
  return { code, expiresAt: value.expiresAt, keyPair };
@@ -97766,10 +98307,10 @@ async function awaitRelay(options) {
97766
98307
  if (!Number.isFinite(deadline)) throw new CloudBackupError("relay_expired");
97767
98308
  while (true) {
97768
98309
  if (isAborted(options.signal)) throw new CloudBackupError("relay_aborted");
97769
- const remaining = deadline - readNow(now).getTime();
97770
- if (remaining <= 0) throw new CloudBackupError("relay_expired");
98310
+ const remaining2 = deadline - readNow(now).getTime();
98311
+ if (remaining2 <= 0) throw new CloudBackupError("relay_expired");
97771
98312
  let response;
97772
- const requestDeadline = AbortSignal.timeout(Math.max(1, remaining));
98313
+ const requestDeadline = AbortSignal.timeout(Math.max(1, remaining2));
97773
98314
  const requestSignal = options.signal === void 0 ? requestDeadline : AbortSignal.any([options.signal, requestDeadline]);
97774
98315
  try {
97775
98316
  response = await (options.fetchImpl ?? publicFetch5)(
@@ -97788,7 +98329,7 @@ async function awaitRelay(options) {
97788
98329
  return await readRelayResult(response, options);
97789
98330
  }
97790
98331
  try {
97791
- await sleep(Math.min(Math.max(0, pollMs), remaining), options.signal);
98332
+ await sleep(Math.min(Math.max(0, pollMs), remaining2), options.signal);
97792
98333
  } catch {
97793
98334
  if (isAborted(options.signal)) throw new CloudBackupError("relay_aborted");
97794
98335
  }
@@ -98045,7 +98586,7 @@ async function readRelayResult(response, options) {
98045
98586
  let plaintext;
98046
98587
  try {
98047
98588
  const result = await response.json();
98048
- if (!isRecord9(result) || !hasExactKeys2(result, RELAY_RESULT_KEYS) || typeof result.sealed !== "string") {
98589
+ if (!isRecord10(result) || !hasExactKeys2(result, RELAY_RESULT_KEYS) || typeof result.sealed !== "string") {
98049
98590
  throw new Error();
98050
98591
  }
98051
98592
  plaintext = openSealed({
@@ -98075,11 +98616,11 @@ async function readRelayResult(response, options) {
98075
98616
  }
98076
98617
  }
98077
98618
  function parseRelayPayload(value) {
98078
- if (!isRecord9(value) || !isRelayPurpose(value.purpose)) {
98619
+ if (!isRecord10(value) || !isRelayPurpose(value.purpose)) {
98079
98620
  throw new CloudBackupError("payload_invalid");
98080
98621
  }
98081
98622
  const expectedKeys = value.purpose === "restore" ? RESTORE_PAYLOAD_KEYS : ENROLL_PAYLOAD_KEYS;
98082
- if (!hasExactKeys2(value, expectedKeys) || value.format !== RELAY_PAYLOAD_FORMAT || value.v !== 1 || typeof value.owner !== "string" || !OWNER_PATTERN.test(value.owner) || typeof value.device !== "string" || !DEVICE_NAME_PATTERN.test(value.device) || !isRecord9(value.kdf) || typeof value.key !== "string") {
98623
+ if (!hasExactKeys2(value, expectedKeys) || value.format !== RELAY_PAYLOAD_FORMAT || value.v !== 1 || typeof value.owner !== "string" || !OWNER_PATTERN.test(value.owner) || typeof value.device !== "string" || !DEVICE_NAME_PATTERN.test(value.device) || !isRecord10(value.kdf) || typeof value.key !== "string") {
98083
98624
  throw new CloudBackupError("payload_invalid");
98084
98625
  }
98085
98626
  const kdf = parseKdf2(value.kdf);
@@ -98109,7 +98650,7 @@ function parseRelayPayload(value) {
98109
98650
  };
98110
98651
  }
98111
98652
  function parseStoredBackupKey(value) {
98112
- if (!isRecord9(value) || !hasExactKeys2(value, STORED_KEY_KEYS) || typeof value.owner !== "string" || !OWNER_PATTERN.test(value.owner) || typeof value.device !== "string" || !DEVICE_NAME_PATTERN.test(value.device) || !isRecord9(value.kdf) || typeof value.key !== "string") {
98653
+ if (!isRecord10(value) || !hasExactKeys2(value, STORED_KEY_KEYS) || typeof value.owner !== "string" || !OWNER_PATTERN.test(value.owner) || typeof value.device !== "string" || !DEVICE_NAME_PATTERN.test(value.device) || !isRecord10(value.kdf) || typeof value.key !== "string") {
98113
98654
  return void 0;
98114
98655
  }
98115
98656
  const kdf = parseKdf2(value.kdf);
@@ -98135,7 +98676,7 @@ function parseStoredState(value) {
98135
98676
  if (value === void 0) return void 0;
98136
98677
  try {
98137
98678
  const parsed = JSON.parse(value);
98138
- if (!isRecord9(parsed) || !hasExactKeys2(parsed, STATE_KEYS) || typeof parsed.lastUploadAt !== "string" || !isIsoUtc(parsed.lastUploadAt) || typeof parsed.sizeBytes !== "number" || !Number.isSafeInteger(parsed.sizeBytes) || parsed.sizeBytes < 0) {
98679
+ if (!isRecord10(parsed) || !hasExactKeys2(parsed, STATE_KEYS) || typeof parsed.lastUploadAt !== "string" || !isIsoUtc(parsed.lastUploadAt) || typeof parsed.sizeBytes !== "number" || !Number.isSafeInteger(parsed.sizeBytes) || parsed.sizeBytes < 0) {
98139
98680
  return void 0;
98140
98681
  }
98141
98682
  return { lastUploadAt: parsed.lastUploadAt, sizeBytes: parsed.sizeBytes };
@@ -98227,7 +98768,7 @@ function isRelayPurpose(value) {
98227
98768
  function isAborted(signal) {
98228
98769
  return signal?.aborted === true;
98229
98770
  }
98230
- function isRecord9(value) {
98771
+ function isRecord10(value) {
98231
98772
  return typeof value === "object" && value !== null && !Array.isArray(value);
98232
98773
  }
98233
98774
  function hasExactKeys2(value, expected) {
@@ -98425,6 +98966,7 @@ async function buyCommand(argv, json2, io, dependencies) {
98425
98966
  )
98426
98967
  );
98427
98968
  } catch (error61) {
98969
+ if (error61 instanceof SpendCapExceededError) throw error61;
98428
98970
  if (error61 instanceof SpendCapError) {
98429
98971
  throw new Error(
98430
98972
  `Router balance purchase refused by the wallet spend policy: ${error61.message} Review or change it with vapi accounts caps ${target.name}.`
@@ -98577,7 +99119,7 @@ async function readProcessStdin() {
98577
99119
  }
98578
99120
 
98579
99121
  // ../cli/src/version.ts
98580
- var CLI_VERSION = "0.10.0";
99122
+ var CLI_VERSION = "0.12.0";
98581
99123
 
98582
99124
  // ../cli/src/status.ts
98583
99125
  async function statusCommand(argv, json2, io, dependencies) {
@@ -100157,7 +100699,7 @@ async function readOffer(response) {
100157
100699
  if (raw !== null) {
100158
100700
  try {
100159
100701
  const decoded = decodePaymentRequiredHeader(raw);
100160
- if (isRecord10(decoded)) header = decoded;
100702
+ if (isRecord11(decoded)) header = decoded;
100161
100703
  else headerMalformed = true;
100162
100704
  } catch {
100163
100705
  headerMalformed = true;
@@ -100166,7 +100708,7 @@ async function readOffer(response) {
100166
100708
  let body;
100167
100709
  try {
100168
100710
  const parsed = JSON.parse(await readBoundedText(response) ?? "");
100169
- if (isRecord10(parsed) && ("accepts" in parsed || "x402Version" in parsed)) body = parsed;
100711
+ if (isRecord11(parsed) && ("accepts" in parsed || "x402Version" in parsed)) body = parsed;
100170
100712
  } catch {
100171
100713
  }
100172
100714
  const mpp = parseMppChallenge(response.headers.get("www-authenticate"));
@@ -100244,7 +100786,7 @@ function gradeOffer(offer) {
100244
100786
  };
100245
100787
  }
100246
100788
  const version5 = declared.x402Version === 1 || declared.x402Version === 2 ? declared.x402Version : null;
100247
- const accepts = (Array.isArray(declared.accepts) ? declared.accepts : []).filter(isRecord10);
100789
+ const accepts = (Array.isArray(declared.accepts) ? declared.accepts : []).filter(isRecord11);
100248
100790
  const exact = accepts.filter((accept) => accept.scheme === "exact");
100249
100791
  const fields = version5 === null ? void 0 : fieldsRule(declared, version5);
100250
100792
  const offerRules = [
@@ -100269,7 +100811,7 @@ function gradeOffer(offer) {
100269
100811
  }
100270
100812
  function advertisedExtensions(declared) {
100271
100813
  const extensions = declared.extensions;
100272
- if (!isRecord10(extensions)) return [];
100814
+ if (!isRecord11(extensions)) return [];
100273
100815
  return KNOWN_EXTENSIONS.filter((name) => Object.prototype.hasOwnProperty.call(extensions, name));
100274
100816
  }
100275
100817
  function extensionsRule(advertised) {
@@ -100392,14 +100934,14 @@ function fieldsRule(declared, version5) {
100392
100934
  if (version5 === 2) {
100393
100935
  const resource = declared.resource;
100394
100936
  if (resource === void 0) issues.push("v2_missing_resource");
100395
- else if (!isRecord10(resource) || !nonEmptyString(resource.url)) {
100937
+ else if (!isRecord11(resource) || !nonEmptyString(resource.url)) {
100396
100938
  issues.push("v2_invalid_resource");
100397
100939
  }
100398
100940
  }
100399
100941
  const accepts = declared.accepts;
100400
100942
  if (!Array.isArray(accepts) || accepts.length === 0) issues.push(`${prefix}_missing_accepts`);
100401
100943
  for (const accept of Array.isArray(accepts) ? accepts : []) {
100402
- if (!isRecord10(accept)) {
100944
+ if (!isRecord11(accept)) {
100403
100945
  issues.push(`${prefix}_invalid_accepts`);
100404
100946
  continue;
100405
100947
  }
@@ -100457,7 +100999,7 @@ function usdcIssue(accept, network) {
100457
100999
  if (typeof accept.asset !== "string" || accept.asset.toLowerCase() !== canonical.usdc.toLowerCase()) {
100458
101000
  return "asset_not_usdc";
100459
101001
  }
100460
- const extra = isRecord10(accept.extra) ? accept.extra : {};
101002
+ const extra = isRecord11(accept.extra) ? accept.extra : {};
100461
101003
  return extra.name === canonical.eip712Domain.name && extra.version === canonical.eip712Domain.version ? void 0 : "usdc_domain_mismatch";
100462
101004
  }
100463
101005
  function payToRule(exact, version5) {
@@ -100509,7 +101051,7 @@ async function discoveryRule(target, fetchImpl) {
100509
101051
  "discovery_missing"
100510
101052
  ]);
100511
101053
  }
100512
- if (!isRecord10(document)) {
101054
+ if (!isRecord11(document)) {
100513
101055
  return rule("discovery", "warn", `${url2.href} is not a JSON object.`, ["discovery_malformed"]);
100514
101056
  }
100515
101057
  const resources = Array.isArray(document.resources) ? document.resources.length : void 0;
@@ -100580,12 +101122,12 @@ function pathAdjacentOpenApiUrls(target) {
100580
101122
  }
100581
101123
  }
100582
101124
  function apiCatalogOpenApiUrls(document, catalogUrl, origin, seen) {
100583
- if (!isRecord10(document) || !Array.isArray(document.linkset)) return [];
101125
+ if (!isRecord11(document) || !Array.isArray(document.linkset)) return [];
100584
101126
  const candidates = [];
100585
101127
  for (const link3 of document.linkset) {
100586
- if (!isRecord10(link3) || !Array.isArray(link3["service-desc"])) continue;
101128
+ if (!isRecord11(link3) || !Array.isArray(link3["service-desc"])) continue;
100587
101129
  for (const description of link3["service-desc"]) {
100588
- if (!isRecord10(description) || typeof description.href !== "string") continue;
101130
+ if (!isRecord11(description) || typeof description.href !== "string") continue;
100589
101131
  let candidate;
100590
101132
  try {
100591
101133
  candidate = new URL(description.href, catalogUrl);
@@ -100604,7 +101146,7 @@ async function findOpenApiOperation(fetchImpl, candidates, pathname, method, via
100604
101146
  let firstDocument;
100605
101147
  for (const url2 of candidates) {
100606
101148
  const document = await fetchJson(fetchImpl, url2);
100607
- if (isRecord10(document) && isRecord10(document.paths)) {
101149
+ if (isRecord11(document) && isRecord11(document.paths)) {
100608
101150
  const located = {
100609
101151
  url: url2,
100610
101152
  paths: document.paths,
@@ -100625,9 +101167,9 @@ function openApiSource(document, catalogUrl) {
100625
101167
  function findOperation(paths, pathname, method) {
100626
101168
  const path = trimSlash(pathname);
100627
101169
  for (const [template, item] of Object.entries(paths)) {
100628
- if (!isRecord10(item)) continue;
101170
+ if (!isRecord11(item)) continue;
100629
101171
  const operation = item[method.toLowerCase()];
100630
- if (!isRecord10(operation)) continue;
101172
+ if (!isRecord11(operation)) continue;
100631
101173
  const pattern = trimSlash(template).split(/(\{[^/}]+\})/).map((part) => part.startsWith("{") ? "[^/]+" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("");
100632
101174
  if (new RegExp(`${pattern}$`).test(path)) return { item, operation };
100633
101175
  }
@@ -100696,7 +101238,7 @@ function trimSlash(path) {
100696
101238
  function nonEmptyString(value) {
100697
101239
  return typeof value === "string" && value.length > 0;
100698
101240
  }
100699
- function isRecord10(value) {
101241
+ function isRecord11(value) {
100700
101242
  return typeof value === "object" && value !== null && !Array.isArray(value);
100701
101243
  }
100702
101244
 
@@ -101802,9 +102344,9 @@ async function reserveRemoteAllowance(args) {
101802
102344
  const perDayAtomic = BigInt(args.caps.perDayAtomic);
101803
102345
  const ledgerPath = getVapiPaths(args.home).ledger;
101804
102346
  const spent = BigInt((await readSpendLedger(ledgerPath, args.now, args.account)).spentAtomic);
101805
- const remaining = spent >= perDayAtomic ? 0n : perDayAtomic - spent;
101806
- const requested = args.run.budgetUsd === void 0 ? remaining : usdToAtomic(args.run.budgetUsd);
101807
- const reserved = requested < remaining ? requested : remaining;
102347
+ const remaining2 = spent >= perDayAtomic ? 0n : perDayAtomic - spent;
102348
+ const requested = args.run.budgetUsd === void 0 ? remaining2 : usdToAtomic(args.run.budgetUsd);
102349
+ const reserved = requested < remaining2 ? requested : remaining2;
101808
102350
  if (reserved === 0n) {
101809
102351
  throw new RemoteKeyRefusedError(
101810
102352
  "no_daily_allowance",
@@ -101824,7 +102366,7 @@ async function reserveRemoteAllowance(args) {
101824
102366
  );
101825
102367
  return { atomic: reserved, expiresAt: nextUtcMidnight(reservation.date) };
101826
102368
  } catch (error61) {
101827
- if (error61 instanceof Error && "code" in error61 && error61.code === "per_day_cap_exceeded") {
102369
+ if (error61 instanceof SpendCapExceededError && error61.cap === "per_day" || error61 instanceof Error && "code" in error61 && error61.code === "per_day_cap_exceeded") {
101828
102370
  throw new RemoteKeyRefusedError(
101829
102371
  "no_daily_allowance",
101830
102372
  `${args.account}'s remaining daily allowance changed while Railway was starting. Run the command again.`
@@ -102086,12 +102628,12 @@ function createLocalRuntime(options) {
102086
102628
  const { home } = options;
102087
102629
  const entry = options.entry ?? realpathSync(process.argv[1]);
102088
102630
  const execPath = options.execPath ?? process.execPath;
102089
- const spawn4 = options.spawn ?? nodeSpawn;
102631
+ const spawn6 = options.spawn ?? nodeSpawn;
102090
102632
  const kill = options.kill ?? ((pid, signal) => process.kill(pid, signal));
102091
102633
  const processCommand = options.processCommand ?? defaultProcessCommand;
102092
102634
  const ownsProcess = (handle, pid) => processCommand(pid)?.includes(runResultPath(home, handle.runId)) === true;
102093
102635
  const closeFd = options.closeFd ?? closeSync2;
102094
- const readFile30 = options.readFile ?? nodeReadFile;
102636
+ const readFile32 = options.readFile ?? nodeReadFile;
102095
102637
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
102096
102638
  const openLog = options.openLog ?? ((path) => {
102097
102639
  mkdirSync2(runsDirectory(home), { recursive: true, mode: 448 });
@@ -102109,7 +102651,7 @@ function createLocalRuntime(options) {
102109
102651
  const logFd = openLog(logPath);
102110
102652
  let child;
102111
102653
  try {
102112
- child = spawn4(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
102654
+ child = spawn6(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
102113
102655
  detached: true,
102114
102656
  stdio: ["ignore", logFd, logFd],
102115
102657
  env: {
@@ -102146,7 +102688,7 @@ function createLocalRuntime(options) {
102146
102688
  return handle;
102147
102689
  },
102148
102690
  async status(handle) {
102149
- const result = await readResultFile(readFile30, runResultPath(home, handle.runId));
102691
+ const result = await readResultFile(readFile32, runResultPath(home, handle.runId));
102150
102692
  if (result !== void 0) return result;
102151
102693
  const pid = localPid(handle);
102152
102694
  if (pid === void 0 || handle.kind !== "local") {
@@ -102249,10 +102791,10 @@ function childArguments(member, run) {
102249
102791
  ...run.drawUsd ? ["--draw", run.drawUsd] : []
102250
102792
  ];
102251
102793
  }
102252
- async function readResultFile(readFile30, path) {
102794
+ async function readResultFile(readFile32, path) {
102253
102795
  let text;
102254
102796
  try {
102255
- text = await readFile30(path, "utf8");
102797
+ text = await readFile32(path, "utf8");
102256
102798
  } catch (error61) {
102257
102799
  if (hasCode3(error61, "ENOENT")) return void 0;
102258
102800
  return { state: "failed", detail: "unreadable result file" };
@@ -103023,13 +103565,91 @@ function usd(value, minimumDecimals = 0) {
103023
103565
  }
103024
103566
 
103025
103567
  // ../cli/src/mcp-install.ts
103568
+ import { spawn as spawn3 } from "node:child_process";
103026
103569
  import { mkdir as mkdir20, readFile as readFile27, writeFile as writeFile11 } from "node:fs/promises";
103027
103570
  import { homedir as systemHomedir } from "node:os";
103028
103571
  import { dirname as dirname14, posix, win32 as win322 } from "node:path";
103029
- var MCP_INSTALL_USAGE = "Usage: vapi mcp install <claude|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]";
103030
- var APPS = /* @__PURE__ */ new Set(["claude", "cursor", "codex"]);
103572
+
103573
+ // ../cli/src/toml-config.ts
103574
+ function removeTomlTables(contents, isTarget) {
103575
+ let removing = false;
103576
+ let retained = "";
103577
+ for (const { line, table } of tomlLines(contents)) {
103578
+ if (table !== void 0) removing = isTarget(tomlKeyPath(table));
103579
+ if (!removing) retained += line;
103580
+ }
103581
+ return retained;
103582
+ }
103583
+ function* tomlLines(contents) {
103584
+ let multiline;
103585
+ for (const line of contents.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
103586
+ yield { line, table: multiline === void 0 ? tomlTableName(line) : void 0 };
103587
+ for (let index2 = 0; index2 < line.length; index2 += 1) {
103588
+ const char = line[index2];
103589
+ if (multiline !== void 0) {
103590
+ if (multiline === '"""' && char === "\\") {
103591
+ index2 += 1;
103592
+ continue;
103593
+ }
103594
+ if (line.startsWith(multiline, index2)) {
103595
+ index2 += 2;
103596
+ multiline = void 0;
103597
+ }
103598
+ } else {
103599
+ if (char === "#") break;
103600
+ if (char !== "'" && char !== '"') continue;
103601
+ const delimiter2 = char.repeat(3);
103602
+ if (line.startsWith(delimiter2, index2)) {
103603
+ multiline = delimiter2;
103604
+ index2 += 2;
103605
+ } else {
103606
+ for (index2 += 1; index2 < line.length; index2 += 1) {
103607
+ if (char === '"' && line[index2] === "\\") index2 += 1;
103608
+ else if (line[index2] === char) break;
103609
+ }
103610
+ }
103611
+ }
103612
+ }
103613
+ }
103614
+ }
103615
+ function tomlKeyPath(table) {
103616
+ const key2 = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
103617
+ const pattern = new RegExp(`^\\s*(${key2})(?:\\s*\\.\\s*(${key2}))*\\s*$`);
103618
+ if (!pattern.test(table)) return [];
103619
+ return [...table.matchAll(new RegExp(key2, "g"))].map(([part]) => unquoteTomlKey(part));
103620
+ }
103621
+ function tomlTableName(line) {
103622
+ const header = line.replace(/\r?\n$/, "");
103623
+ const match = /^\s*(?:\[\[\s*(.*?)\s*\]\]|\[\s*(.*?)\s*\])\s*(?:#.*)?$/.exec(header);
103624
+ return match?.[1] ?? match?.[2];
103625
+ }
103626
+ function unquoteTomlKey(key2) {
103627
+ if (key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
103628
+ if (key2.startsWith('"') && key2.endsWith('"')) {
103629
+ try {
103630
+ return JSON.parse(key2);
103631
+ } catch {
103632
+ return key2;
103633
+ }
103634
+ }
103635
+ return key2;
103636
+ }
103637
+ function tomlSeparator(contents) {
103638
+ if (contents.length === 0 || /(?:\r?\n)[ \t]*(?:\r?\n)$/.test(contents)) return "";
103639
+ return /\r?\n$/.test(contents) ? "\n" : "\n\n";
103640
+ }
103641
+ function escapeToml(value) {
103642
+ return JSON.stringify(value).slice(1, -1);
103643
+ }
103644
+
103645
+ // ../cli/src/mcp-install.ts
103646
+ var MCP_INSTALL_USAGE = "Usage: vapi mcp install <claude-code|claude-desktop|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]";
103647
+ var APPS = /* @__PURE__ */ new Set(["claude-code", "claude-desktop", "cursor", "codex"]);
103648
+ var CLAUDE_ALIAS_NOTICE = "vapi mcp install claude installs into Claude Desktop; for the Claude Code CLI use: vapi mcp install claude-code";
103649
+ var CLAUDE_NOT_FOUND = "Claude Code's claude command was not found on PATH. Install Claude Code, or run this yourself:";
103031
103650
  var NEXT_STEP = {
103032
- claude: 'Restart Claude Desktop, then ask it: "Search vAPI for a weather API."',
103651
+ "claude-code": 'Start a new Claude Code session, then ask: "Search vAPI for a weather API."',
103652
+ "claude-desktop": 'Restart Claude Desktop, then ask it: "Search vAPI for a weather API."',
103033
103653
  cursor: 'Reload Cursor, then ask its agent: "Search vAPI for a weather API."',
103034
103654
  codex: 'Start codex in a new terminal, then ask: "Search vAPI for a weather API."'
103035
103655
  };
@@ -103070,36 +103690,44 @@ async function mcpInstallCommand(argv, json2, io, dependencies) {
103070
103690
  booleanOptions: /* @__PURE__ */ new Set(["--no-link"]),
103071
103691
  maximumPositionals: 1
103072
103692
  });
103073
- const appValue = parsed.positionals[0];
103074
- if (appValue === void 0) throw new UsageError(MCP_INSTALL_USAGE);
103693
+ const requestedApp = parsed.positionals[0];
103694
+ if (requestedApp === void 0) throw new UsageError(MCP_INSTALL_USAGE);
103695
+ const appValue = requestedApp === "claude" ? "claude-desktop" : requestedApp;
103075
103696
  if (!isMcpInstallApp(appValue)) {
103076
103697
  throw new UsageError(
103077
- `Unknown app ${JSON.stringify(appValue)}. Choose claude, cursor or codex.
103698
+ `Unknown app ${JSON.stringify(requestedApp)}. Choose claude-code, claude-desktop, cursor or codex.
103078
103699
  ${MCP_INSTALL_USAGE}`
103079
103700
  );
103080
103701
  }
103702
+ if (requestedApp === "claude") io.stderr(CLAUDE_ALIAS_NOTICE);
103081
103703
  const home = parsed.one("--home") ?? getVapiPaths().directory;
103082
103704
  const paths = getVapiPaths(home);
103083
103705
  const registry2 = parsed.one("--registry") ?? (await pathExists5(paths.config) ? registryBaseUrl(await readConfig(paths.config, io)) : resolveRegistryUrl());
103706
+ const offerLink = async () => {
103707
+ const name = await unlinkedDefaultAccount(home, dependencies);
103708
+ return name === void 0 ? {} : await offerDashboardLink({
103709
+ name,
103710
+ json: json2,
103711
+ noLink: parsed.has("--no-link"),
103712
+ io,
103713
+ dependencies,
103714
+ home,
103715
+ apiBase: parsed.one("--registry")
103716
+ });
103717
+ };
103718
+ const platform2 = dependencies.mcpInstall?.platform ?? process.platform;
103719
+ const entry = serverEntry(home, registry2);
103720
+ if (appValue === "claude-code") {
103721
+ return await installClaudeCode(entry, platform2, json2, io, dependencies, offerLink);
103722
+ }
103084
103723
  const target = mcpInstallTarget(appValue, {
103085
- platform: dependencies.mcpInstall?.platform ?? process.platform,
103724
+ platform: platform2,
103086
103725
  homedir: dependencies.mcpInstall?.homedir ?? systemHomedir(),
103087
103726
  cwd: dependencies.mcpInstall?.cwd ?? process.cwd(),
103088
103727
  appData: dependencies.mcpInstall?.appData ?? process.env.APPDATA
103089
103728
  });
103090
- const entry = serverEntry(home, registry2);
103091
103729
  const created = await writeMcpConfig(target, entry);
103092
- const name = await unlinkedDefaultAccount(home, dependencies);
103093
- const offerLink = (name2) => offerDashboardLink({
103094
- name: name2,
103095
- json: json2,
103096
- noLink: parsed.has("--no-link"),
103097
- io,
103098
- dependencies,
103099
- home,
103100
- apiBase: parsed.one("--registry")
103101
- });
103102
- const link3 = json2 && name !== void 0 ? await offerLink(name) : {};
103730
+ const link3 = json2 ? await offerLink() : {};
103103
103731
  output3(
103104
103732
  io,
103105
103733
  json2,
@@ -103108,8 +103736,9 @@ ${MCP_INSTALL_USAGE}`
103108
103736
  );
103109
103737
  if (!json2) {
103110
103738
  io.stdout(NEXT_STEP[appValue]);
103111
- if (name !== void 0) await offerLink(name);
103739
+ await offerLink();
103112
103740
  }
103741
+ return 0;
103113
103742
  }
103114
103743
  async function unlinkedDefaultAccount(home, dependencies) {
103115
103744
  try {
@@ -103123,6 +103752,131 @@ async function unlinkedDefaultAccount(home, dependencies) {
103123
103752
  }
103124
103753
  return void 0;
103125
103754
  }
103755
+ async function installClaudeCode(entry, platform2, json2, io, dependencies, offerLink) {
103756
+ const processCommand = platform2 === "win32" ? "claude.cmd" : "claude";
103757
+ const processArgs = claudeCodeArgs(entry);
103758
+ const command = platform2 === "win32" ? [escapeCmd(processCommand), ...processArgs.map(escapeCmdArgument)].join(" ") : displayCommand(processCommand, processArgs);
103759
+ let result;
103760
+ try {
103761
+ result = await (dependencies.mcpInstall?.runProcess ?? defaultMcpInstallProcess)(
103762
+ processCommand,
103763
+ processArgs
103764
+ );
103765
+ } catch (error61) {
103766
+ if (isErrorCode3(error61, "ENOENT")) {
103767
+ return claudeCodeFailure(json2, io, command, "claude_not_found", CLAUDE_NOT_FOUND);
103768
+ }
103769
+ const message = `Claude Code MCP installation failed: ${errorMessage2(error61)}`;
103770
+ return claudeCodeFailure(json2, io, command, "claude_mcp_add_failed", message);
103771
+ }
103772
+ if (result.exitCode !== 0) {
103773
+ const status = result.exitCode === null ? "Claude Code's claude command ended without an exit code." : `Claude Code's claude command exited with code ${result.exitCode}.`;
103774
+ const stderr2 = result.stderr.trim();
103775
+ const message = stderr2.length === 0 ? status : `${status} ${stderr2}`;
103776
+ return claudeCodeFailure(json2, io, command, "claude_mcp_add_failed", message, result.exitCode);
103777
+ }
103778
+ const nextStep = NEXT_STEP["claude-code"];
103779
+ const link3 = json2 ? await offerLink() : {};
103780
+ if (json2)
103781
+ io.stdout(JSON.stringify({ ...link3, app: "claude-code", installed: true, command, nextStep }));
103782
+ else {
103783
+ io.stdout(command);
103784
+ io.stdout(nextStep);
103785
+ await offerLink();
103786
+ }
103787
+ return 0;
103788
+ }
103789
+ function claudeCodeArgs(entry) {
103790
+ return [
103791
+ "mcp",
103792
+ "add",
103793
+ "--scope",
103794
+ "user",
103795
+ "vapi",
103796
+ "-e",
103797
+ `VAPI_HOME=${entry.env.VAPI_HOME}`,
103798
+ "-e",
103799
+ `VAPI_REGISTRY_URL=${entry.env.VAPI_REGISTRY_URL}`,
103800
+ "--",
103801
+ entry.command,
103802
+ ...entry.args
103803
+ ];
103804
+ }
103805
+ function claudeCodeFailure(json2, io, command, code, message, exitCode) {
103806
+ if (json2) {
103807
+ io.stdout(
103808
+ JSON.stringify({
103809
+ app: "claude-code",
103810
+ installed: false,
103811
+ command,
103812
+ error: { code, message, ...exitCode === void 0 ? {} : { exitCode } }
103813
+ })
103814
+ );
103815
+ } else if (code === "claude_not_found") {
103816
+ io.stderr(`${message}
103817
+ ${command}`);
103818
+ } else {
103819
+ io.stderr(`${command}
103820
+ ${message}`);
103821
+ }
103822
+ return 1;
103823
+ }
103824
+ function displayCommand(command, args) {
103825
+ return [command, ...args].map(shellQuote3).join(" ");
103826
+ }
103827
+ function shellQuote3(value) {
103828
+ return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
103829
+ }
103830
+ function isErrorCode3(error61, code) {
103831
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && error61.code === code;
103832
+ }
103833
+ function errorMessage2(error61) {
103834
+ return error61 instanceof Error ? error61.message : String(error61);
103835
+ }
103836
+ var defaultMcpInstallProcess = async (command, args) => {
103837
+ const batch = /\.(?:cmd|bat)$/iu.test(command);
103838
+ const executable = batch ? await windowsBatchPath(command) : command;
103839
+ const commandLine = batch ? [escapeCmd(executable), ...args.map((arg) => escapeCmdArgument(arg))].join(" ") : void 0;
103840
+ return await new Promise((resolve3, reject) => {
103841
+ const child = spawn3(
103842
+ batch ? "cmd.exe" : command,
103843
+ batch ? ["/d", "/v:off", "/s", "/c", `"${commandLine}"`] : [...args],
103844
+ {
103845
+ shell: false,
103846
+ ...batch ? { windowsVerbatimArguments: true } : {},
103847
+ stdio: ["ignore", "pipe", "pipe"],
103848
+ timeout: 6e4,
103849
+ killSignal: "SIGKILL",
103850
+ windowsHide: true
103851
+ }
103852
+ );
103853
+ let stdout = "";
103854
+ let stderr2 = "";
103855
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
103856
+ stdout += chunk;
103857
+ });
103858
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
103859
+ stderr2 += chunk;
103860
+ });
103861
+ child.once("error", reject);
103862
+ child.once("close", (exitCode) => resolve3({ exitCode, stdout, stderr: stderr2 }));
103863
+ });
103864
+ };
103865
+ async function windowsBatchPath(command) {
103866
+ const path = Object.entries(process.env).find(([key2]) => key2.toLowerCase() === "path")?.[1];
103867
+ for (const directory of ["", ...(path ?? "").split(";")]) {
103868
+ const candidate = win322.join(directory.replace(/^"|"$/gu, ""), command);
103869
+ if (await pathExists5(candidate)) return candidate;
103870
+ }
103871
+ throw Object.assign(new Error(`${command} was not found on PATH.`), { code: "ENOENT" });
103872
+ }
103873
+ function escapeCmd(value) {
103874
+ return value.replace(/[()[\]%!^"`<>&|;, *?]/gu, "^$&");
103875
+ }
103876
+ function escapeCmdArgument(value) {
103877
+ const quoted = `"${value.replace(/(\\*)"/gu, '$1$1\\"').replace(/(\\*)$/u, "$1$1")}"`;
103878
+ return escapeCmd(escapeCmd(quoted));
103879
+ }
103126
103880
  function isMcpInstallApp(value) {
103127
103881
  return APPS.has(value);
103128
103882
  }
@@ -103156,13 +103910,13 @@ function jsonConfig(path, existing, entry) {
103156
103910
  } catch {
103157
103911
  throw new Error(`${path} is not valid JSON. Fix it by hand; nothing was written.`);
103158
103912
  }
103159
- if (!isRecord11(parsed)) {
103913
+ if (!isRecord12(parsed)) {
103160
103914
  throw new Error(`${path} must contain a JSON object. Fix it by hand; nothing was written.`);
103161
103915
  }
103162
103916
  config2 = parsed;
103163
103917
  }
103164
103918
  const existingServers = config2.mcpServers;
103165
- if (existingServers !== void 0 && !isRecord11(existingServers)) {
103919
+ if (existingServers !== void 0 && !isRecord12(existingServers)) {
103166
103920
  throw new Error(
103167
103921
  `${path} has an invalid mcpServers value. Fix it by hand; nothing was written.`
103168
103922
  );
@@ -103174,7 +103928,10 @@ function jsonConfig(path, existing, entry) {
103174
103928
  `;
103175
103929
  }
103176
103930
  function tomlConfig(existing, entry) {
103177
- const retained = removeVapiTomlTables(existing);
103931
+ const retained = removeTomlTables(
103932
+ existing,
103933
+ ([root, name]) => root === "mcp_servers" && name === "vapi"
103934
+ );
103178
103935
  const block = [
103179
103936
  "[mcp_servers.vapi]",
103180
103937
  'command = "npx"',
@@ -103184,64 +103941,564 @@ function tomlConfig(existing, entry) {
103184
103941
  ].join("\n");
103185
103942
  return `${retained}${tomlSeparator(retained)}${block}`;
103186
103943
  }
103187
- function removeVapiTomlTables(contents) {
103188
- const lines = contents.match(/[^\n]*\n|[^\n]+$/g) ?? [];
103189
- let removing = false;
103190
- let retained = "";
103191
- for (const line of lines) {
103192
- const table = tomlTableName(line);
103193
- if (table !== void 0) removing = isVapiTomlTable(table);
103194
- if (!removing) retained += line;
103195
- }
103196
- return retained;
103944
+ function isRecord12(value) {
103945
+ return typeof value === "object" && value !== null && !Array.isArray(value);
103197
103946
  }
103198
- function tomlTableName(line) {
103199
- const header = line.replace(/\r?\n$/, "");
103200
- const match = /^\s*(?:\[\[\s*(.*?)\s*\]\]|\[\s*(.*?)\s*\])\s*(?:#.*)?$/.exec(header);
103201
- return match?.[1] ?? match?.[2];
103947
+ async function readExistingFile(path) {
103948
+ try {
103949
+ return await readFile27(path, "utf8");
103950
+ } catch (error61) {
103951
+ if (isMissingFile(error61)) return void 0;
103952
+ throw error61;
103953
+ }
103202
103954
  }
103203
- function isVapiTomlTable(table) {
103204
- const key2 = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
103205
- const match = new RegExp(`^\\s*(${key2})\\s*\\.\\s*(${key2})(?:\\s*\\.|\\s*$)`).exec(table);
103206
- if (match === null) return false;
103207
- return unquoteTomlKey(match[1]) === "mcp_servers" && unquoteTomlKey(match[2]) === "vapi";
103955
+ async function pathExists5(path) {
103956
+ try {
103957
+ await readFile27(path);
103958
+ return true;
103959
+ } catch (error61) {
103960
+ if (isMissingFile(error61)) return false;
103961
+ throw error61;
103962
+ }
103208
103963
  }
103209
- function unquoteTomlKey(key2) {
103210
- if (key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
103211
- if (key2.startsWith('"') && key2.endsWith('"')) {
103964
+
103965
+ // ../cli/src/code.ts
103966
+ import { constants as constants2 } from "node:fs";
103967
+ import { access, mkdir as mkdir21, readFile as readFile28, realpath, unlink as unlink13, writeFile as writeFile12 } from "node:fs/promises";
103968
+ import { homedir as homedir3 } from "node:os";
103969
+ import { basename as basename5, dirname as dirname15, join as join26, posix as posix2, win32 as win323 } from "node:path";
103970
+ var VAPI_CODEX_PROVIDER = "vapi";
103971
+ var VAPI_CODEX_PROFILE = "vapi";
103972
+ var VAPI_CODEX_DEFAULT_MODEL = "venice/openai-gpt-61-sol";
103973
+ var VAPI_ROUTER_KEY_ENV = "VAPI_ROUTER_KEY";
103974
+ function codexConfigPath(env, home) {
103975
+ return join26(env.CODEX_HOME || join26(home, ".codex"), "config.toml");
103976
+ }
103977
+ function hasVapiCodexProfile(contents) {
103978
+ const roots = new Set(
103979
+ [...tomlLines(contents)].flatMap(({ table }) => {
103980
+ const path = table === void 0 ? [] : tomlKeyPath(table);
103981
+ return path.length === 2 && path[1] === "vapi" ? [path[0]] : [];
103982
+ })
103983
+ );
103984
+ return roots.has("model_providers") && roots.has("profiles");
103985
+ }
103986
+ async function resolveBinary(name, options) {
103987
+ const windows = (options.platform ?? process.platform) === "win32";
103988
+ const path = options.env.PATH ?? (windows ? Object.entries(options.env).find(([key2]) => key2.toLowerCase() === "path")?.[1] : void 0);
103989
+ if (path === void 0) return void 0;
103990
+ const paths = windows ? win323 : posix2;
103991
+ const canonical = options.realpath ?? realpath;
103992
+ const executable = options.isExecutable ?? (async (candidate) => {
103212
103993
  try {
103213
- return JSON.parse(key2);
103214
- } catch {
103215
- return key2;
103994
+ await access(candidate, constants2.X_OK);
103995
+ return true;
103996
+ } catch (error61) {
103997
+ if (isMissingFile(error61) || error61.code === "EACCES")
103998
+ return false;
103999
+ throw error61;
104000
+ }
104001
+ });
104002
+ const self = options.selfPath ?? process.argv[1];
104003
+ const selfReal = self === void 0 ? void 0 : await canonical(self);
104004
+ const extensions = windows ? ["", ...(options.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";")] : [""];
104005
+ for (const directory of path.split(windows ? ";" : ":")) {
104006
+ for (const extension of extensions) {
104007
+ const candidate = paths.resolve(directory.replace(/^"|"$/gu, ""), `${name}${extension}`);
104008
+ if (!await executable(candidate)) continue;
104009
+ const resolved = await canonical(candidate);
104010
+ if (selfReal !== void 0 && (windows ? resolved.toLowerCase() === selfReal.toLowerCase() : resolved === selfReal))
104011
+ continue;
104012
+ return candidate;
103216
104013
  }
103217
104014
  }
103218
- return key2;
104015
+ return void 0;
103219
104016
  }
103220
- function tomlSeparator(contents) {
103221
- if (contents.length === 0 || /(?:\r?\n)[ \t]*(?:\r?\n)$/.test(contents)) return "";
103222
- return /\r?\n$/.test(contents) ? "\n" : "\n\n";
104017
+ var RC_START = "# >>> vapi code >>>";
104018
+ var RC_END = "# <<< vapi code <<<";
104019
+ var CONFIG_END = "# <<< vapi code config <<<\n";
104020
+ var isCodeTable = ([root, name]) => name === "vapi" && (root === "model_providers" || root === "profiles");
104021
+ function cleanConfig(contents) {
104022
+ let created = false;
104023
+ const cleaned = contents.replace(
104024
+ /(\n?)\[model_providers\.vapi\]\n# >>> vapi code config (created|existing) (0|1) >>>\n([\s\S]*?)# <<< vapi code config <<<\n/gu,
104025
+ (_, prefix, kind, separator, body) => {
104026
+ created ||= kind === "created";
104027
+ return (separator === "1" ? "" : prefix) + removeTomlTables(`[model_providers.vapi]
104028
+ ${body}`, isCodeTable);
104029
+ }
104030
+ );
104031
+ return { contents: removeTomlTables(cleaned, isCodeTable), created };
104032
+ }
104033
+ function configContents(existing, baseURL) {
104034
+ const clean2 = cleanConfig(existing ?? "");
104035
+ const retained = clean2.contents;
104036
+ const separator = retained.length > 0 && !retained.endsWith("\n") ? "\n" : "";
104037
+ return `${retained}${separator}[model_providers.vapi]
104038
+ # >>> vapi code config ${existing === void 0 || clean2.created ? "created" : "existing"} ${separator.length} >>>
104039
+ ` + [
104040
+ 'name = "vAPI Router"',
104041
+ `base_url = "${escapeToml(baseURL)}"`,
104042
+ `env_key = "${VAPI_ROUTER_KEY_ENV}"`,
104043
+ 'wire_api = "responses"',
104044
+ "",
104045
+ "[profiles.vapi]",
104046
+ `model_provider = "${VAPI_CODEX_PROVIDER}"`,
104047
+ `model = "${VAPI_CODEX_DEFAULT_MODEL}"`,
104048
+ ""
104049
+ ].join("\n") + CONFIG_END;
103223
104050
  }
103224
- function escapeToml(value) {
103225
- return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
104051
+ function removeAliases(contents) {
104052
+ return contents.replace(
104053
+ /(^|\n)# >>> vapi code >>>\r?\n[\s\S]*?^# <<< vapi code <<<(\r?\n|$)/gmu,
104054
+ (_, prefix, suffix) => suffix === "" ? "" : prefix
104055
+ );
103226
104056
  }
103227
- function isRecord11(value) {
103228
- return typeof value === "object" && value !== null && !Array.isArray(value);
104057
+ function aliasContents(original, tools) {
104058
+ const existing = original ?? "";
104059
+ const block = [RC_START, ...tools.map((tool) => `alias ${tool}="vapi ${tool}"`), RC_END].join(
104060
+ "\n"
104061
+ );
104062
+ const match = /^# >>> vapi code >>>\r?\n[\s\S]*?^# <<< vapi code <<</gmu;
104063
+ if (match.test(existing)) return existing.replace(match, block);
104064
+ const separator = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
104065
+ return `${existing}${separator}${block}${original === "" || existing.endsWith("\n") ? "\n" : ""}`;
103229
104066
  }
103230
- async function readExistingFile(path) {
104067
+ async function readOptional(path) {
103231
104068
  try {
103232
- return await readFile27(path, "utf8");
104069
+ return await readFile28(path, "utf8");
103233
104070
  } catch (error61) {
103234
104071
  if (isMissingFile(error61)) return void 0;
103235
104072
  throw error61;
103236
104073
  }
103237
104074
  }
103238
- async function pathExists5(path) {
104075
+ async function writeConfig(path, contents) {
104076
+ await mkdir21(dirname15(path), { recursive: true });
104077
+ await writeFile12(path, contents);
104078
+ }
104079
+ async function codeCommand(argv, json2, io, dependencies) {
104080
+ const command = argv[0];
104081
+ if (command !== "install" && command !== "uninstall")
104082
+ throw new UsageError("Usage: vapi code <install|uninstall>.");
104083
+ const parsed = parseArguments(argv.slice(1), {
104084
+ valueOptions: new Set(command === "install" ? ["--wallet"] : []),
104085
+ booleanOptions: new Set(command === "install" ? ["--yes", "--no-alias"] : []),
104086
+ maximumPositionals: 0
104087
+ });
104088
+ const env = getEnvironment(dependencies);
104089
+ const home = dependencies.code?.homedir ?? homedir3();
104090
+ const config2 = codexConfigPath(env, home);
104091
+ const rcPaths = [join26(home, ".zshrc"), join26(home, ".bashrc")];
104092
+ if (command === "uninstall") {
104093
+ const removed = [];
104094
+ const previous = await readOptional(config2);
104095
+ if (previous !== void 0) {
104096
+ const clean2 = cleanConfig(previous);
104097
+ if (clean2.contents !== previous) {
104098
+ if (clean2.contents === "" && clean2.created) await unlink13(config2);
104099
+ else await writeFile12(config2, clean2.contents);
104100
+ removed.push(config2);
104101
+ }
104102
+ }
104103
+ for (const path of rcPaths) {
104104
+ const previous2 = await readOptional(path);
104105
+ if (previous2 === void 0) continue;
104106
+ const clean2 = removeAliases(previous2);
104107
+ if (clean2 !== previous2) {
104108
+ if (clean2 === "" && previous2.startsWith(RC_START) && !previous2.endsWith("\n"))
104109
+ await unlink13(path);
104110
+ else await writeFile12(path, clean2);
104111
+ removed.push(path);
104112
+ }
104113
+ }
104114
+ io.stdout(
104115
+ json2 ? JSON.stringify({ command: "code uninstall", removed }) : removed.length === 0 ? "Nothing to remove." : `Removed vAPI code settings from: ${removed.join(", ")}`
104116
+ );
104117
+ return 0;
104118
+ }
104119
+ const tools = [];
104120
+ const skipped2 = [];
104121
+ for (const name of ["claude", "codex"]) {
104122
+ const binary = await resolveBinary(name, { ...dependencies.code, env });
104123
+ if (binary === void 0)
104124
+ skipped2.push(
104125
+ `Skipped ${name === "claude" ? "Claude Code" : "Codex"}: \`${name}\` is not on PATH.`
104126
+ );
104127
+ else tools.push(name);
104128
+ }
104129
+ if (tools.length === 0) {
104130
+ const message = "Neither claude nor codex is on PATH; nothing was installed.";
104131
+ if (json2) io.stdout(JSON.stringify({ installed: [], skipped: skipped2, error: message }));
104132
+ else {
104133
+ skipped2.forEach(io.stderr);
104134
+ io.stderr(message);
104135
+ }
104136
+ return 1;
104137
+ }
104138
+ let target = await targetWallet(parsed, dependencies);
104139
+ const credentials = dependencies.router?.routerCredentials ?? routerCredentials;
104140
+ let linked = false;
104141
+ let rotated = false;
104142
+ let result;
104143
+ for (; ; ) {
104144
+ try {
104145
+ result = await credentials(routerDeps2(target, dependencies));
104146
+ break;
104147
+ } catch (error61) {
104148
+ if (error61 instanceof RouterClientError && error61.code === "not_linked" && !linked) {
104149
+ linked = true;
104150
+ const account = parsed.one("--wallet");
104151
+ await (dependencies.code?.login ?? runLoginFlow)(
104152
+ account === void 0 ? [] : ["--account", account],
104153
+ json2,
104154
+ { ...io, stdout: io.stderr },
104155
+ json2 ? { ...dependencies, interactive: false, stdinIsTTY: false } : dependencies
104156
+ );
104157
+ target = await targetWallet(parsed, dependencies);
104158
+ } else if (error61 instanceof RouterClientError && error61.code === "no_router_key" && !rotated) {
104159
+ rotated = true;
104160
+ await (dependencies.router?.rotateRouterKey ?? rotateRouterKey)(
104161
+ routerDeps2(target, dependencies)
104162
+ );
104163
+ } else throw error61;
104164
+ }
104165
+ }
104166
+ const installed = [];
104167
+ if (tools.includes("claude")) installed.push("Claude Code: ready, launch with `vapi claude`");
104168
+ if (tools.includes("codex")) {
104169
+ await writeConfig(config2, configContents(await readOptional(config2), result.baseURL));
104170
+ installed.push(`Codex: installed ${config2}`);
104171
+ }
104172
+ let alias = "Aliases: skipped.";
104173
+ if (!parsed.has("--no-alias")) {
104174
+ if ((dependencies.code?.platform ?? process.platform) === "win32")
104175
+ alias = "Aliases: skipped on Windows.";
104176
+ else {
104177
+ const yes = parsed.has("--yes") || !json2 && isInteractive(dependencies) && isStdinInteractive(dependencies) && /^y(?:es)?$/iu.test(
104178
+ (await getLinePrompt(dependencies)(
104179
+ "Make `claude` and `codex` use your vAPI Compute first from now on? [y/N] "
104180
+ )).trim()
104181
+ );
104182
+ if (yes) {
104183
+ const shell = basename5(env.SHELL ?? "");
104184
+ const rc = shell === "zsh" ? rcPaths[0] : shell === "bash" ? rcPaths[1] : await readOptional(rcPaths[0]) !== void 0 ? rcPaths[0] : rcPaths[1];
104185
+ await writeConfig(rc, aliasContents(await readOptional(rc), tools));
104186
+ alias = `Aliases: installed in ${rc}. Open a new terminal or run: source ${rc}`;
104187
+ }
104188
+ }
104189
+ }
104190
+ let compute;
103239
104191
  try {
103240
- await readFile27(path);
103241
- return true;
104192
+ const usage = await (dependencies.router?.routerUsage ?? routerUsage)(
104193
+ routerDeps2(target, dependencies)
104194
+ );
104195
+ const reset = new Date(usage.compute.resetsAt);
104196
+ if (!Number.isFinite(reset.getTime())) throw new Error("invalid reset time");
104197
+ compute = `$${usage.compute.remainingTodayUsd.toFixed(2)} left today (resets ${reset.toISOString().slice(11, 16)} UTC)`;
103242
104198
  } catch (error61) {
103243
- if (isMissingFile(error61)) return false;
103244
- throw error61;
104199
+ compute = `Compute today: unavailable (${error61 instanceof RouterClientError ? error61.code : "request failed"})`;
104200
+ }
104201
+ const start = `Start with \`vapi ${tools.includes("claude") ? "claude" : "codex"}\``;
104202
+ if (json2)
104203
+ io.stdout(
104204
+ JSON.stringify({ command: "code install", installed, skipped: skipped2, alias, compute, start })
104205
+ );
104206
+ else {
104207
+ skipped2.forEach(io.stderr);
104208
+ [...installed, alias, compute, start].forEach(io.stdout);
104209
+ }
104210
+ return 0;
104211
+ }
104212
+
104213
+ // ../cli/src/code-launch.ts
104214
+ import { spawn as spawn4 } from "node:child_process";
104215
+ import { readFile as readFile29 } from "node:fs/promises";
104216
+ import { constants as constants3, homedir as homedir4 } from "node:os";
104217
+ var CLAUDE_MODELS = {
104218
+ sonnet: "venice/claude-sonnet-5-5",
104219
+ opus: "venice/claude-opus-5-5",
104220
+ haiku: "venice/claude-haiku-5-5"
104221
+ };
104222
+ async function claudeCommand(argv, json2, io, dependencies) {
104223
+ return await launch("claude", argv, json2, io, dependencies);
104224
+ }
104225
+ async function codexCommand(argv, json2, io, dependencies) {
104226
+ return await launch("codex", argv, json2, io, dependencies);
104227
+ }
104228
+ function parseLaunch(argv) {
104229
+ const result = { own: false, vapi: false, balance: false, forwarded: [] };
104230
+ for (let index2 = 0; index2 < argv.length; index2 += 1) {
104231
+ const arg = argv[index2];
104232
+ if (arg === "--") {
104233
+ result.forwarded.push(...argv.slice(index2 + 1));
104234
+ break;
104235
+ }
104236
+ if (arg === "--own") result.own = true;
104237
+ else if (arg === "--vapi") result.vapi = true;
104238
+ else if (arg === "--use-balance") result.balance = true;
104239
+ else if (arg === "--model" || arg === "--account") {
104240
+ const value = argv[++index2];
104241
+ if (!value || value.startsWith("--")) throw new UsageError(`Expected ${arg} <value>.`);
104242
+ if (arg === "--model") result.model = value;
104243
+ else result.account = value;
104244
+ } else result.forwarded.push(arg);
104245
+ }
104246
+ if (result.own && result.vapi) throw new UsageError("--vapi and --own cannot be used together.");
104247
+ return result;
104248
+ }
104249
+ var LaunchTimeout = class extends Error {
104250
+ constructor() {
104251
+ super("timed out");
104252
+ }
104253
+ };
104254
+ async function bounded(operation, milliseconds) {
104255
+ const controller = new AbortController();
104256
+ let timer;
104257
+ try {
104258
+ return await Promise.race([
104259
+ new Promise((_resolve, reject) => {
104260
+ timer = setTimeout(() => {
104261
+ const error61 = new LaunchTimeout();
104262
+ controller.abort(error61);
104263
+ reject(error61);
104264
+ }, milliseconds);
104265
+ }),
104266
+ operation(controller.signal)
104267
+ ]);
104268
+ } finally {
104269
+ clearTimeout(timer);
104270
+ controller.abort();
104271
+ }
104272
+ }
104273
+ function abortableDeps(deps, signal) {
104274
+ const fetchImpl = deps.fetchImpl ?? createPublicFetch({ allowPrivateNetwork: false });
104275
+ return {
104276
+ ...deps,
104277
+ fetchImpl: (input2, init) => fetchImpl(input2, {
104278
+ ...init,
104279
+ signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal
104280
+ })
104281
+ };
104282
+ }
104283
+ function shortReason(error61, env, credentials) {
104284
+ if (error61 instanceof RouterClientError) {
104285
+ if (error61.code === "not_linked") return "not linked, run vapi code install";
104286
+ if (error61.code === "no_router_key") return "no Router key, run vapi code install";
104287
+ }
104288
+ let message = error61 instanceof Error ? error61.message : String(error61);
104289
+ for (const secret of [
104290
+ credentials?.apiKey,
104291
+ env.ANTHROPIC_API_KEY,
104292
+ env.ANTHROPIC_AUTH_TOKEN,
104293
+ env[VAPI_ROUTER_KEY_ENV]
104294
+ ]) {
104295
+ if (secret) message = message.replaceAll(secret, "[redacted]");
104296
+ }
104297
+ return message.replace(/\s+/gu, " ").trim().slice(0, 160) || "request failed";
104298
+ }
104299
+ async function chooseRoute(options, env, dependencies) {
104300
+ if (options.own) return { kind: "own" };
104301
+ const timeout = dependencies.code?.usageTimeoutMs ?? 4e3;
104302
+ let credentials;
104303
+ let deps;
104304
+ let balanceKeyRequired = false;
104305
+ try {
104306
+ credentials = await bounded(async (signal) => {
104307
+ const target = await targetWallet(
104308
+ { one: (name) => name === "--wallet" ? options.account : void 0 },
104309
+ dependencies,
104310
+ env.VAPI_HOME
104311
+ );
104312
+ signal.throwIfAborted();
104313
+ deps = routerDeps2(target, dependencies);
104314
+ return await (dependencies.router?.routerCredentials ?? routerCredentials)(
104315
+ abortableDeps(deps, signal)
104316
+ );
104317
+ }, timeout);
104318
+ let usage;
104319
+ try {
104320
+ usage = await bounded(
104321
+ (signal) => (dependencies.router?.routerUsage ?? routerUsage)(abortableDeps(deps, signal)),
104322
+ timeout
104323
+ );
104324
+ if (!Number.isFinite(new Date(usage.compute.resetsAt).getTime()))
104325
+ throw new Error("invalid Compute reset time");
104326
+ } catch (error61) {
104327
+ if (options.vapi) return { kind: "vapi", credentials };
104328
+ throw error61;
104329
+ }
104330
+ if (options.vapi || remaining(usage, options.balance) >= 0.5) {
104331
+ if (options.balance && usage.compute.remainingTodayUsd < 0.5 && (usage.balance?.remainingUsd ?? 0) > 0) {
104332
+ balanceKeyRequired = true;
104333
+ credentials = await bounded(
104334
+ (signal) => (dependencies.router?.routerCredentials ?? routerCredentials)(
104335
+ abortableDeps(deps, signal),
104336
+ { funding: "balance" }
104337
+ ),
104338
+ timeout
104339
+ );
104340
+ }
104341
+ return { kind: "vapi", credentials, usage };
104342
+ }
104343
+ return { kind: "own", exhausted: true };
104344
+ } catch (error61) {
104345
+ const reason = balanceKeyRequired && error61 instanceof RouterClientError && error61.code === "no_router_key" ? "no Router balance key is stored" : shortReason(error61, env, credentials);
104346
+ if (options.vapi) return { kind: "unavailable", reason };
104347
+ return { kind: "own", reason };
104348
+ }
104349
+ }
104350
+ function remaining(usage, useBalance) {
104351
+ return usage.compute.remainingTodayUsd + (useBalance ? usage.balance?.remainingUsd ?? 0 : 0);
104352
+ }
104353
+ async function launch(tool, argv, json2, io, dependencies) {
104354
+ if (json2) throw new UsageError(`vapi ${tool} is interactive and does not support --json.`);
104355
+ const options = parseLaunch(argv);
104356
+ const env = getEnvironment(dependencies);
104357
+ let binary;
104358
+ try {
104359
+ binary = await resolveBinary(tool, { ...dependencies.code, env });
104360
+ } catch (error61) {
104361
+ io.stderr(shortReason(error61, env));
104362
+ return 127;
104363
+ }
104364
+ if (binary === void 0) {
104365
+ io.stderr(
104366
+ `\`${tool}\` is not on PATH. Install ${tool === "claude" ? "Claude Code" : "Codex"} first.`
104367
+ );
104368
+ return 127;
104369
+ }
104370
+ const route = await chooseRoute(options, env, dependencies);
104371
+ if (route.kind === "unavailable") {
104372
+ io.stderr(route.reason);
104373
+ return 1;
104374
+ }
104375
+ let args = options.forwarded;
104376
+ let childEnv = env;
104377
+ const own2 = tool === "claude" ? "your own Claude subscription" : "your own Codex/ChatGPT login";
104378
+ if (route.kind === "own") {
104379
+ if (route.exhausted) io.stderr(`\u25CF Compute used up today \u2192 ${own2}`);
104380
+ else if (route.reason !== void 0) io.stderr(`\u25CF vAPI unreachable (${route.reason}) \u2192 ${own2}`);
104381
+ if (options.model !== void 0)
104382
+ args = [tool === "claude" ? "--model" : "-m", options.model, ...args];
104383
+ } else {
104384
+ const { credentials, usage } = route;
104385
+ const model = tool === "claude" ? claudeModel(options.model) : options.model ?? VAPI_CODEX_DEFAULT_MODEL;
104386
+ let status = "\u25CF vAPI Compute";
104387
+ if (usage !== void 0)
104388
+ status += ` \u2014 $${remaining(usage, options.balance).toFixed(2)} left today (resets ${new Date(usage.compute.resetsAt).toISOString().slice(11, 16)} UTC)`;
104389
+ io.stderr(`${status} \xB7 model ${model.slice(model.lastIndexOf("/") + 1)}`);
104390
+ io.stderr(
104391
+ tool === "claude" ? " Compute runs out mid-session? /exit, then: vapi claude --continue" : " Compute runs out mid-session? /quit, then: vapi codex resume --last"
104392
+ );
104393
+ if (tool === "claude") {
104394
+ childEnv = {
104395
+ ...env,
104396
+ ANTHROPIC_BASE_URL: credentials.baseURL.replace(/\/v1\/?$/u, ""),
104397
+ ANTHROPIC_AUTH_TOKEN: credentials.apiKey
104398
+ };
104399
+ delete childEnv.ANTHROPIC_API_KEY;
104400
+ if (args.some((arg) => arg === "--settings" || arg.startsWith("--settings=")))
104401
+ io.stderr("\u25CF Your --settings is passed as is; vAPI model settings were not added.");
104402
+ else
104403
+ args = [
104404
+ "--settings",
104405
+ JSON.stringify({
104406
+ env: {
104407
+ ANTHROPIC_MODEL: model,
104408
+ ANTHROPIC_DEFAULT_SONNET_MODEL: CLAUDE_MODELS.sonnet,
104409
+ ANTHROPIC_DEFAULT_OPUS_MODEL: CLAUDE_MODELS.opus,
104410
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: CLAUDE_MODELS.haiku,
104411
+ CLAUDE_CODE_MAX_RETRIES: "2"
104412
+ }
104413
+ }),
104414
+ ...args
104415
+ ];
104416
+ } else {
104417
+ childEnv = { ...env, [VAPI_ROUTER_KEY_ENV]: credentials.apiKey };
104418
+ args = [...await codexArgs(env, credentials.baseURL, options.model, dependencies), ...args];
104419
+ }
104420
+ }
104421
+ return await runChild(binary, args, childEnv, io, dependencies);
104422
+ }
104423
+ function claudeModel(model) {
104424
+ return model === void 0 ? CLAUDE_MODELS.sonnet : Object.hasOwn(CLAUDE_MODELS, model) ? CLAUDE_MODELS[model] : model;
104425
+ }
104426
+ async function codexArgs(env, baseURL, model, dependencies) {
104427
+ let contents = "";
104428
+ try {
104429
+ contents = await readFile29(
104430
+ codexConfigPath(env, dependencies.code?.homedir ?? homedir4()),
104431
+ "utf8"
104432
+ );
104433
+ } catch (error61) {
104434
+ if (!isMissingFile(error61)) throw error61;
104435
+ }
104436
+ const providerArgs = [
104437
+ "-c",
104438
+ `model_providers.${VAPI_CODEX_PROVIDER}.name="vAPI Router"`,
104439
+ "-c",
104440
+ `model_providers.${VAPI_CODEX_PROVIDER}.base_url=${JSON.stringify(baseURL)}`,
104441
+ "-c",
104442
+ `model_providers.${VAPI_CODEX_PROVIDER}.env_key="${VAPI_ROUTER_KEY_ENV}"`,
104443
+ "-c",
104444
+ `model_providers.${VAPI_CODEX_PROVIDER}.wire_api="responses"`,
104445
+ "-c",
104446
+ `model_provider="${VAPI_CODEX_PROVIDER}"`
104447
+ ];
104448
+ if (hasVapiCodexProfile(contents))
104449
+ return [
104450
+ "--profile",
104451
+ VAPI_CODEX_PROFILE,
104452
+ ...providerArgs,
104453
+ ...model === void 0 ? [] : ["-m", model]
104454
+ ];
104455
+ return [...providerArgs, "-m", model ?? VAPI_CODEX_DEFAULT_MODEL];
104456
+ }
104457
+ async function runChild(binary, args, env, io, dependencies) {
104458
+ const signals = dependencies.code?.processSignals ?? process;
104459
+ let child;
104460
+ const ignore = () => {
104461
+ };
104462
+ const forward = (signal) => () => {
104463
+ try {
104464
+ child?.kill(signal);
104465
+ } catch (error61) {
104466
+ io.stderr(shortReason(error61, env));
104467
+ }
104468
+ };
104469
+ const listeners = [
104470
+ ["SIGINT", ignore],
104471
+ ["SIGQUIT", ignore],
104472
+ ["SIGTERM", forward("SIGTERM")],
104473
+ ["SIGHUP", forward("SIGHUP")]
104474
+ ];
104475
+ try {
104476
+ for (const [signal, listener] of listeners) signals.on(signal, listener);
104477
+ return await new Promise((resolve3) => {
104478
+ let settled = false;
104479
+ const finish = (code) => {
104480
+ if (!settled) {
104481
+ settled = true;
104482
+ resolve3(code);
104483
+ }
104484
+ };
104485
+ try {
104486
+ child = (dependencies.code?.spawn ?? spawn4)(binary, args, { env, stdio: "inherit" });
104487
+ child.once("error", (error61) => {
104488
+ if (!settled) io.stderr(shortReason(error61, env));
104489
+ finish(127);
104490
+ });
104491
+ child.once(
104492
+ "exit",
104493
+ (code, signal) => finish(code ?? (signal === null ? 1 : 128 + (constants3.signals[signal] ?? 0)))
104494
+ );
104495
+ } catch (error61) {
104496
+ io.stderr(shortReason(error61, env));
104497
+ finish(127);
104498
+ }
104499
+ });
104500
+ } finally {
104501
+ for (const [signal, listener] of listeners) signals.removeListener(signal, listener);
103245
104502
  }
103246
104503
  }
103247
104504
 
@@ -103344,7 +104601,7 @@ async function sendConfig(dependencies) {
103344
104601
 
103345
104602
  // ../cli/src/setup.ts
103346
104603
  import { rm as rm5 } from "node:fs/promises";
103347
- import { join as join26 } from "node:path";
104604
+ import { join as join27 } from "node:path";
103348
104605
  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.`;
103349
104606
  var VAULT_CHOICE = "Create a new vault, or restore one from a recovery phrase? [new/restore] ";
103350
104607
  async function setupCommand(argv, json2, io, dependencies) {
@@ -103374,7 +104631,7 @@ async function setupCommand(argv, json2, io, dependencies) {
103374
104631
  let changedAccount = false;
103375
104632
  let changedLink = false;
103376
104633
  let scannedAddresses;
103377
- if (!await fileExists2(join26(paths.directory, "vault.json"))) {
104634
+ if (!await fileExists2(join27(paths.directory, "vault.json"))) {
103378
104635
  const choice = await vaultChoice(dependencies);
103379
104636
  if (choice === "restore") {
103380
104637
  if (!isInteractive(dependencies)) {
@@ -103462,7 +104719,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
103462
104719
  let scannedAddresses = 0;
103463
104720
  try {
103464
104721
  const restored = await restoreVault({
103465
- path: join26(paths.directory, "vault.json"),
104722
+ path: join27(paths.directory, "vault.json"),
103466
104723
  key: key2,
103467
104724
  phrase: validatedPhrase,
103468
104725
  probe: async (address4) => await readBalance3(address4) > 0n,
@@ -103473,7 +104730,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
103473
104730
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
103474
104731
  });
103475
104732
  names = restored.accounts().map((account) => account.name);
103476
- await rm5(join26(paths.directory, "wallets.json"), { force: true });
104733
+ await rm5(join27(paths.directory, "wallets.json"), { force: true });
103477
104734
  } finally {
103478
104735
  key2.fill(0);
103479
104736
  }
@@ -103591,7 +104848,7 @@ async function withRouterError2(operation) {
103591
104848
 
103592
104849
  // ../cli/src/task.ts
103593
104850
  import { randomUUID as randomUUID6 } from "node:crypto";
103594
- import { readFile as readFile28 } from "node:fs/promises";
104851
+ import { readFile as readFile30 } from "node:fs/promises";
103595
104852
  var TASK_HELP = `Usage:
103596
104853
  vapi task search [--open] [--min <usd>] [--tab trending|new|closing|paid] [--limit <n>] [--json]
103597
104854
  vapi task show <id> [--account <name>] [--json]
@@ -103927,7 +105184,7 @@ async function taskCommandInner(argv, json2, io, dependencies) {
103927
105184
  if (maxAwards !== void 0 && maxAwards > TASK_LIMITS.maxAwardsMax)
103928
105185
  throw new UsageError("--max-awards must be between 1 and 50.");
103929
105186
  if (parsed.one("--webhook") !== void 0) httpsUrl2(parsed.one("--webhook"), "--webhook");
103930
- const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile28(briefPath, "utf8");
105187
+ const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile30(briefPath, "utf8");
103931
105188
  const input2 = {
103932
105189
  title: title.trim(),
103933
105190
  description: brief.trim(),
@@ -104513,13 +105770,13 @@ async function watchTask(id2, parsed, json2, io, dependencies, now) {
104513
105770
  }
104514
105771
  }
104515
105772
  cursor2 = Math.max(cursor2, page.nextAfter, ...events.map((event) => event.sequence));
104516
- const remaining = deadline - clock().getTime();
104517
- if (remaining <= 0)
105773
+ const remaining2 = deadline - clock().getTime();
105774
+ if (remaining2 <= 0)
104518
105775
  throw new TaskCommandError(
104519
105776
  "timeout",
104520
105777
  `Task watch timed out after ${parsed.one("--timeout") ?? "7d"}.`
104521
105778
  );
104522
- await context.sleep(Math.min(interval, remaining));
105779
+ await context.sleep(Math.min(interval, remaining2));
104523
105780
  }
104524
105781
  }
104525
105782
  function expandDeliveryFiles(argv) {
@@ -105605,7 +106862,7 @@ async function referencedSleep(milliseconds, signal) {
105605
106862
  }
105606
106863
 
105607
106864
  // ../cli/src/vault.ts
105608
- import { join as join27 } from "node:path";
106865
+ import { join as join28 } from "node:path";
105609
106866
  var VAULT_USAGE = "Usage: vapi vault protect|unprotect|lock|unlock|status [--json]";
105610
106867
  var RESTORE_USAGE = "Usage: vapi restore [--accounts <n> | --from-owner [--owner <0x\u2026>]] [--json]";
105611
106868
  var LEGACY_PASSWORD_NOTICE = "VAPI_KEYSTORE_PASSWORD is deprecated for vault passwords; use VAPI_VAULT_PASSWORD instead.";
@@ -105649,7 +106906,7 @@ async function restoreCommand(argv, json2, io, dependencies) {
105649
106906
  }
105650
106907
  const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
105651
106908
  const paths = getVapiPaths();
105652
- const path = join27(paths.directory, "vault.json");
106909
+ const path = join28(paths.directory, "vault.json");
105653
106910
  if (await fileExists2(path)) {
105654
106911
  throw new Error(
105655
106912
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
@@ -105806,7 +107063,7 @@ function requireNoArguments(argv) {
105806
107063
  parseArguments(argv, { valueOptions: /* @__PURE__ */ new Set(), maximumPositionals: 0 });
105807
107064
  }
105808
107065
  function vaultPath() {
105809
- return join27(getVapiPaths().directory, "vault.json");
107066
+ return join28(getVapiPaths().directory, "vault.json");
105810
107067
  }
105811
107068
  function quietIo(io) {
105812
107069
  return { stdout: () => void 0, stderr: io.stderr };
@@ -105852,7 +107109,7 @@ Usage:
105852
107109
  vapi docs "<question>" [--json]
105853
107110
  vapi docs search "<query>" [--json]
105854
107111
  vapi docs read <url-or-path> [--json]
105855
- vapi search [query] [--kind <kind>] [--network <caip2>] [--limit <n>] [--cursor <cursor>] [--include-unverified] [--json]
107112
+ vapi search [query] [--kind <kind>] [--network <caip2>] [--limit <n>] [--cursor <cursor>] [--include-unverified] [--include-outage] [--json]
105856
107113
  vapi inspect <id> [--endpoint <name>] [--json]
105857
107114
  vapi pay <id-or-url> [--method <method>] [--endpoint <name>] [--body <json>] [--content-type <type>] [--network <caip2>] [--expected-pay-to <address>] [--max <amount>] [--timeout <seconds>] [--account <name>] [--json]
105858
107115
  vapi pay --resume <receipt-id> [--json]
@@ -105874,6 +107131,10 @@ Usage:
105874
107131
  vapi login [--account <name>] [--label <name>] [--publish] [--no-browser] [--json]
105875
107132
  vapi logout [--account <name>] [--json]
105876
107133
  vapi whoami [--account <name>] [--json]
107134
+ vapi claude [--vapi|--own] [--model <m>] [--use-balance] [--account <name>] [<claude args>...]
107135
+ vapi codex [--vapi|--own] [--model <id>] [--use-balance] [--account <name>] [<codex args>...]
107136
+ vapi code install [--yes] [--no-alias] [--account <name>] [--json]
107137
+ vapi code uninstall [--json]
105877
107138
  vapi router models [--account <name>] [--json]
105878
107139
  vapi router usage [--account <name>] [--json]
105879
107140
  vapi router chat --model <id> [--system <text>] [--max-tokens <n>] "<prompt>" [--account <name>] [--json]
@@ -105921,7 +107182,7 @@ Usage:
105921
107182
  vapi publish list [--json]
105922
107183
  vapi claim <origin> [--account <name>] [--json]
105923
107184
  vapi mcp [--account <name>] [--json]
105924
- vapi mcp install <claude|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]
107185
+ vapi mcp install <claude-code|claude-desktop|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]
105925
107186
  vapi serve [--json]
105926
107187
  vapi version [--json]
105927
107188
  vapi help [--json]
@@ -105948,13 +107209,13 @@ Solana listings remain searchable; inspect and pay return \`unsupported_network\
105948
107209
 
105949
107210
  \`vapi backup\` and \`vapi export-key\` print a secret, so they run only on a real terminal, never for an agent, and ask you to type the wallet name first. \`vapi backup --cloud\` keeps an encrypted vault copy that only the owner can approve for recovery. \`vapi restore\` rebuilds the vault from the phrase and re-derives accounts until five consecutive addresses have no Base USDC, and reports the number scanned. Use \`--accounts <n>\` with restore or setup to recover a fixed count without querying balances. Set \`VAPI_NO_SECRETS=1\` to switch exports off entirely. Every export and every wallet change is logged to ~/.vapi/audit.log.
105950
107211
 
105951
- \`vapi publish <url>\` lists an API you own. vAPI probes the URL \u2014 an origin, one endpoint, or an OpenAPI document \u2014 you choose which endpoints to list, and your wallet signs one line naming where the payouts go. Listing is permissionless: a listing that passed the probe goes live with \`vapi publish activate <slug>\`, and \`vapi publish verify-request <slug>\` asks for the review that puts it in the default search. Deploying the FeeSplitter that receives the payouts is a wallet transaction and stays in the console. A catalog of more than 20 endpoints is listed as several listings of up to 20, with one result line per endpoint; \`--resume\` skips every endpoint this key already lists.
107212
+ \`vapi publish <url>\` lists an API you own. vAPI probes the URL \u2014 an origin, one endpoint, or an OpenAPI document \u2014 you choose which endpoints to list, and your wallet signs one line naming where the payouts go. Listing is permissionless: a listing that passed the probe goes live with \`vapi publish activate <slug>\`, and \`vapi publish verify-request <slug>\` asks for the review that puts it in the default search. Set each endpoint's x402 payTo to the payout wallet you signed with before activation. vAPI Call takes no fee. Providers are paid directly. A catalog of more than 20 endpoints is listed as several listings of up to 20, with one result line per endpoint; \`--resume\` skips every endpoint this key already lists.
105952
107213
 
105953
107214
  \`vapi claim <origin>\` takes ownership of the listings vAPI indexed from your API. The wallet their payments go to signs one line, \`Claim the vAPI Call listings served from <origin>\`; the listings stay paid directly to that wallet, and \`vapi publish list\` shows them.
105954
107215
 
105955
107216
  \`vapi auth set-key\` types the registry API key once, on a terminal, into the same OS secret store as the passphrase. A key is a secret: it is never an argument, \`VAPI_API_KEY\` is the route for CI, and no agent or MCP tool can reach it.
105956
107217
 
105957
- With no command, vapi shows the status screen; vapi help prints this text. The MCP server starts only with \`vapi mcp\`; \`vapi mcp install <app>\` writes that app's MCP config and prints the file it touched.`;
107218
+ With no command, vapi shows the status screen; vapi help prints this text. The MCP server starts only with \`vapi mcp\`; \`vapi mcp install claude-code\` runs Claude Code's installer, while the other install targets write the client's MCP config.`;
105958
107219
  var processIo = {
105959
107220
  stdout: (message) => process.stdout.write(`${message}
105960
107221
  `),
@@ -105992,6 +107253,7 @@ var ACCOUNT_OPTION2 = "--account";
105992
107253
  var WALLET_OPTION_DEPRECATION = "--wallet is now --account; --wallet keeps working for one release.";
105993
107254
  var SOLANA_VAULT_UNAVAILABLE2 = "Solana keys are not part of the device vault yet.";
105994
107255
  var INCLUDE_UNVERIFIED_OPTION = "--include-unverified";
107256
+ var INCLUDE_OUTAGE_OPTION = "--include-outage";
105995
107257
  async function openWalletStore(dependencies, home = getVapiPaths().directory) {
105996
107258
  return await WalletStore.open(home, {
105997
107259
  secrets: getSecretStore(dependencies),
@@ -106092,6 +107354,8 @@ async function confirmWalletName(name, prompt, refusal, dependencies) {
106092
107354
  if (typed.trim() !== name) throw new KeystoreError(refusal);
106093
107355
  }
106094
107356
  async function runCli(argv = process.argv.slice(2), io = processIo, dependencies = {}) {
107357
+ const firstArgument = argv.find((argument) => argument !== "--json");
107358
+ const codeLaunch = firstArgument === "claude" || firstArgument === "codex";
106095
107359
  let json2 = argv.includes("--json");
106096
107360
  const taskInvocation = argv.find((argument) => argument !== "--json") === "task";
106097
107361
  const resultFile = runResultFile(argv);
@@ -106100,15 +107364,15 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106100
107364
  stderr: (message) => io.stderr(redactDetachedRunText(message, getEnvironment(dependencies)))
106101
107365
  };
106102
107366
  try {
106103
- const parsedInvocation = removeJsonFlag(argv);
107367
+ const parsedInvocation = removeJsonFlag(argv, codeLaunch);
106104
107368
  json2 = parsedInvocation.json;
106105
- const hasWalletOption = parsedInvocation.args.includes(WALLET_OPTION5);
107369
+ const hasWalletOption = !codeLaunch && parsedInvocation.args.includes(WALLET_OPTION5);
106106
107370
  const hasAccountOption = parsedInvocation.args.includes(ACCOUNT_OPTION2);
106107
107371
  if (hasWalletOption && hasAccountOption) {
106108
107372
  throw new UsageError("--wallet and --account cannot be used together.");
106109
107373
  }
106110
107374
  if (hasWalletOption) io.stderr(WALLET_OPTION_DEPRECATION);
106111
- const args = parsedInvocation.args.map(
107375
+ const args = codeLaunch ? parsedInvocation.args : parsedInvocation.args.map(
106112
107376
  (argument) => argument === WALLET_OPTION5 ? ACCOUNT_OPTION2 : argument
106113
107377
  );
106114
107378
  const command = args[0];
@@ -106204,6 +107468,15 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106204
107468
  await whoamiCommand(args.slice(1), json2, io, dependencies);
106205
107469
  exitCode = 0;
106206
107470
  break;
107471
+ case "claude":
107472
+ exitCode = await claudeCommand(args.slice(1), json2, io, dependencies);
107473
+ break;
107474
+ case "codex":
107475
+ exitCode = await codexCommand(args.slice(1), json2, io, dependencies);
107476
+ break;
107477
+ case "code":
107478
+ exitCode = await codeCommand(args.slice(1), json2, io, dependencies);
107479
+ break;
106207
107480
  case "router":
106208
107481
  await routerCommand(args.slice(1), json2, io, dependencies);
106209
107482
  exitCode = 0;
@@ -106241,7 +107514,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106241
107514
  break;
106242
107515
  case "unlock":
106243
107516
  io.stderr("vapi unlock is now vapi vault unlock; the old name works for one release.");
106244
- if (await fileExists2(join28(getVapiPaths().directory, "vault.json"))) {
107517
+ if (await fileExists2(join29(getVapiPaths().directory, "vault.json"))) {
106245
107518
  parseArguments(args.slice(1), {
106246
107519
  valueOptions: /* @__PURE__ */ new Set([WALLET_OPTION5]),
106247
107520
  maximumPositionals: 0
@@ -106277,11 +107550,11 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106277
107550
  break;
106278
107551
  case "mcp":
106279
107552
  if (args[1] === "install") {
106280
- await mcpInstallCommand(args.slice(2), json2, io, dependencies);
107553
+ exitCode = await mcpInstallCommand(args.slice(2), json2, io, dependencies);
106281
107554
  } else {
106282
107555
  await mcpCommand(args.slice(1), dependencies);
107556
+ exitCode = 0;
106283
107557
  }
106284
- exitCode = 0;
106285
107558
  break;
106286
107559
  case "serve":
106287
107560
  outputStub(io, json2);
@@ -106311,7 +107584,9 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106311
107584
  ).catch(() => void 0);
106312
107585
  }
106313
107586
  if (json2) {
106314
- if (taskInvocation) {
107587
+ if (error61 instanceof SpendCapExceededError) {
107588
+ runIo.stdout(JSON.stringify({ error: error61.toJSON(), exitCode: 1 }));
107589
+ } else if (taskInvocation) {
106315
107590
  runIo.stdout(
106316
107591
  JSON.stringify({
106317
107592
  ok: false,
@@ -106445,7 +107720,7 @@ async function initCommand(argv, json2, io, dependencies) {
106445
107720
  address: account.address,
106446
107721
  accounts,
106447
107722
  config: paths.config,
106448
- vault: join28(paths.directory, "vault.json"),
107723
+ vault: join29(paths.directory, "vault.json"),
106449
107724
  ...configRewrites.length > 0 ? { configRewrites } : {},
106450
107725
  custody: "self",
106451
107726
  warning: CUSTODY_NOTICE,
@@ -106584,7 +107859,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
106584
107859
  const result = {
106585
107860
  address: account.address,
106586
107861
  ...account.solana ? { solanaAddress: account.solana.address } : {},
106587
- vault: join28(paths.directory, "vault.json"),
107862
+ vault: join29(paths.directory, "vault.json"),
106588
107863
  ...label === void 0 ? {} : { label },
106589
107864
  spendCaps: created.entry.spendCaps,
106590
107865
  isDefault,
@@ -106624,7 +107899,7 @@ function formatCaps2(caps) {
106624
107899
  function walletListResult(store, wallets, unlocked) {
106625
107900
  return {
106626
107901
  default: store.defaultName ?? null,
106627
- vault: join28(store.home, "vault.json"),
107902
+ vault: join29(store.home, "vault.json"),
106628
107903
  wallets: wallets.map((wallet) => ({
106629
107904
  name: wallet.name,
106630
107905
  ...wallet.address === void 0 ? {} : { address: wallet.address },
@@ -106697,7 +107972,7 @@ async function fundCommand2(argv, json2, io, dependencies) {
106697
107972
  async function searchCommand(argv, json2, io, dependencies) {
106698
107973
  const parsed = parseArguments(argv, {
106699
107974
  valueOptions: /* @__PURE__ */ new Set(["--kind", "--network", "--limit", "--cursor"]),
106700
- booleanOptions: /* @__PURE__ */ new Set([INCLUDE_UNVERIFIED_OPTION]),
107975
+ booleanOptions: /* @__PURE__ */ new Set([INCLUDE_UNVERIFIED_OPTION, INCLUDE_OUTAGE_OPTION]),
106701
107976
  repeatableOptions: /* @__PURE__ */ new Set(["--kind"]),
106702
107977
  maximumPositionals: 1
106703
107978
  });
@@ -106710,7 +107985,8 @@ async function searchCommand(argv, json2, io, dependencies) {
106710
107985
  ...limit === void 0 ? {} : { limit },
106711
107986
  ...parsed.one("--cursor") ? { cursor: parsed.one("--cursor") } : {},
106712
107987
  // Only the opt-in travels: `false` is the registry default.
106713
- ...parsed.has(INCLUDE_UNVERIFIED_OPTION) ? { includeUnverified: true } : {}
107988
+ ...parsed.has(INCLUDE_UNVERIFIED_OPTION) ? { includeUnverified: true } : {},
107989
+ ...parsed.has(INCLUDE_OUTAGE_OPTION) ? { includeOutage: true } : {}
106714
107990
  };
106715
107991
  const call2 = createCallPort({
106716
107992
  config: config2,
@@ -106836,12 +108112,14 @@ async function payCommand(argv, json2, io, dependencies) {
106836
108112
  cliActionContext(config2, pinPayInput(call2, input2), dependencies)
106837
108113
  );
106838
108114
  void _resolvedWallet;
108115
+ const { hints: _hints, ...humanResult } = result;
108116
+ void _hints;
106839
108117
  outputForWallet2(
106840
108118
  io,
106841
108119
  json2,
106842
108120
  wallet,
106843
108121
  result,
106844
- [...verificationNotice(result.verification), JSON.stringify(result, null, 2)].join("\n")
108122
+ [...verificationNotice(result.verification), JSON.stringify(humanResult, null, 2)].join("\n")
106845
108123
  );
106846
108124
  await (dependencies.ceiling?.drainCeilingSweeps ?? drainCeilingSweeps)(1e4).catch(
106847
108125
  () => void 0
@@ -107482,15 +108760,6 @@ async function publishListingCommand(argv, json2, io, dependencies) {
107482
108760
  }
107483
108761
  say(formatCreatedListing(listing, batch.name, payoutWallet, batch.endpoints.length));
107484
108762
  }
107485
- let splitters;
107486
- let splittersError;
107487
- if (created.length > 0) {
107488
- try {
107489
- splitters = await client.splitters(payoutWallet);
107490
- } catch (error61) {
107491
- splittersError = error61 instanceof Error ? error61.message : String(error61);
107492
- }
107493
- }
107494
108763
  const failed2 = failures.length > 0;
107495
108764
  const resumeHint = `Run the same vapi publish command with ${RESUME_OPTION} to list the rest; it skips what is already listed.`;
107496
108765
  if (json2) {
@@ -107500,8 +108769,6 @@ async function publishListingCommand(argv, json2, io, dependencies) {
107500
108769
  probe,
107501
108770
  listings: created,
107502
108771
  results,
107503
- ...splitters === void 0 ? {} : { splitters },
107504
- ...splittersError === void 0 ? {} : { splittersError },
107505
108772
  ...failed2 ? {
107506
108773
  error: [...new Set(failures.map((failure) => failure.message))].join("\n"),
107507
108774
  exitCode: 1
@@ -107511,8 +108778,12 @@ async function publishListingCommand(argv, json2, io, dependencies) {
107511
108778
  return failed2 ? 1 : 0;
107512
108779
  }
107513
108780
  if (created.length > 0) {
107514
- const slug = created.length === 1 ? listingSlug(created[0]) : void 0;
107515
- for (const line of formatSplitters(splitters, splittersError, slug, baseUrl)) io.stdout(line);
108781
+ for (const line of formatDescriptionWarnings(created[0])) io.stdout(line);
108782
+ io.stdout("vAPI Call takes no fee. Providers are paid directly.");
108783
+ io.stdout(`Set each endpoint's payTo to your payout wallet ${payoutWallet}, then run:`);
108784
+ for (const listing of created) {
108785
+ io.stdout(` vapi publish activate ${listingSlug(listing) ?? "<slug>"}`);
108786
+ }
107516
108787
  }
107517
108788
  if (!failed2) return 0;
107518
108789
  for (const message of new Set(failures.map((failure) => failure.message))) io.stderr(message);
@@ -107804,22 +109075,15 @@ function formatCreatedListing(created, name, payoutWallet, endpoints) {
107804
109075
  `Payout wallet: ${payoutWallet}`
107805
109076
  ].join("\n");
107806
109077
  }
107807
- function formatSplitters(splitters, splittersError, slug, baseUrl) {
107808
- const nextStep = `Deploy the FeeSplitter from your wallet in the console at ${listingsUrl(baseUrl, "/providers").href}, then run \`vapi publish activate ${slug ?? "<slug>"}\`.`;
107809
- if (splittersError !== void 0) {
107810
- return [`Could not read your splitters: ${splittersError}`, nextStep];
107811
- }
107812
- const states = Array.isArray(splitters?.networkStates) ? splitters.networkStates : [];
107813
- const fee = typeof splitters?.feeBp === "number" ? ` (vAPI fee ${splitters.feeBp / 100}%)` : "";
107814
- return [
107815
- `Splitters${fee}:`,
107816
- ...states.map((state) => {
107817
- const label = [state.name, state.network].filter(Boolean).join(" ");
107818
- const address4 = typeof state.splitterAddress === "string" ? state.splitterAddress : "unknown";
107819
- return ` ${label || "network"} ${address4} ${state.deployed === true ? "deployed" : "not deployed"}`;
107820
- }),
107821
- nextStep
107822
- ];
109078
+ function formatDescriptionWarnings(created) {
109079
+ const warnings = Array.isArray(created.descriptionWarnings) ? created.descriptionWarnings : [];
109080
+ const lines = warnings.flatMap((warning) => {
109081
+ if (typeof warning !== "object" || warning === null) return [];
109082
+ const { message, hint } = warning;
109083
+ if (typeof message !== "string") return [];
109084
+ return [`- ${message}${typeof hint === "string" ? ` ${hint}` : ""}`];
109085
+ });
109086
+ return lines.length === 0 ? [] : ["Description check (the listing is published either way):", ...lines];
107823
109087
  }
107824
109088
  function formatListingStatus(slug, action, result) {
107825
109089
  const status = typeof result.status === "string" ? result.status : "unknown";
@@ -107908,7 +109172,7 @@ function formatClaimed(origin, claimed) {
107908
109172
  }
107909
109173
  var EXPORT_KEY_WARNING = "Anyone with this key can spend the wallet. Never paste it into a website or chat.";
107910
109174
  async function deviceVaultKey2(store, dependencies) {
107911
- const path = join28(store.home, "vault.json");
109175
+ const path = join29(store.home, "vault.json");
107912
109176
  const metadata = await readVaultFileUnlocked(path);
107913
109177
  const secrets = getSecretStore(dependencies);
107914
109178
  const key2 = metadata.protected ? await unlockProtectedVault({
@@ -108001,7 +109265,7 @@ async function backupCommand(argv, json2, io, dependencies) {
108001
109265
  const target = await targetWallet(parsed, dependencies);
108002
109266
  const vaultAccount = await target.store.hasVaultAccount(target.name);
108003
109267
  if (vaultAccount) {
108004
- const vault = await readVaultFileUnlocked(join28(target.store.home, "vault.json"));
109268
+ const vault = await readVaultFileUnlocked(join29(target.store.home, "vault.json"));
108005
109269
  if (vault.accounts.some((account) => account.name === target.name && account.kind === "imported")) {
108006
109270
  throw new KeystoreError(
108007
109271
  `Account ${target.name} was imported and is not recoverable from the vault phrase. Back it up with vapi export-key --account ${target.name}.`
@@ -108078,7 +109342,7 @@ async function importCommand(argv, json2, io, dependencies) {
108078
109342
  const existed = store.has(name);
108079
109343
  if (existed && !parsed.has("--replace")) {
108080
109344
  const address4 = await store.readAddress(name);
108081
- const location = await store.hasVaultAccount(name) ? join28(store.home, "vault.json") : store.pathFor(name);
109345
+ const location = await store.hasVaultAccount(name) ? join29(store.home, "vault.json") : store.pathFor(name);
108082
109346
  throw new Error(
108083
109347
  [
108084
109348
  `Wallet ${name} already exists at ${location}.`,
@@ -108114,7 +109378,7 @@ async function importCommand(argv, json2, io, dependencies) {
108114
109378
  const result = {
108115
109379
  address: account.address,
108116
109380
  ...account.solana ? { solanaAddress: account.solana.address } : {},
108117
- vault: join28(paths.directory, "vault.json"),
109381
+ vault: join29(paths.directory, "vault.json"),
108118
109382
  ...previousKeystore ? { previousKeystore } : {},
108119
109383
  message: "Wallet imported. Its encrypted key stays on this machine."
108120
109384
  };
@@ -108367,26 +109631,42 @@ function formatSearch(page) {
108367
109631
  verificationTag({ verification: item.verification, external: isMirroredHit(item) })
108368
109632
  ];
108369
109633
  const prefix = [...new Set(tags)].map((tag) => `[${tag}] `).join("");
109634
+ const health = item.kind === "api" && item.health ? `${item.health.state}${item.health.latencyP50Ms === null ? "" : ` ${Math.round(item.health.latencyP50Ms)}ms`}` : "-";
108370
109635
  return [
108371
- `${item.ref} ${item.kind} ${prefix}${item.card.title}`,
109636
+ `${item.ref} ${item.kind} ${health} ${prefix}${item.card.title}`,
108372
109637
  ` ${item.card.summary}`,
108373
- ...item.fee ? [` Fee: ${item.fee.label}`] : []
109638
+ ...item.fee ? [` Fee: ${formatListingFee(item.fee)}`] : [],
109639
+ ...item.kind === "api" && item.alternatives ? [
109640
+ ` Alternatives: ${item.alternatives.map((alternative) => `${alternative.ref} (${alternative.reason})`).join(", ")}`
109641
+ ] : []
108374
109642
  ].join("\n");
108375
109643
  }).join("\n");
108376
109644
  }
108377
109645
  function formatInspect(result) {
109646
+ const { hints: _hints, ...humanResult } = result;
109647
+ void _hints;
108378
109648
  return [
108379
109649
  `Verification: ${verificationTag({
108380
109650
  verification: result.verification,
108381
109651
  external: result.group === "external"
108382
109652
  })}`,
108383
- ...result.fee ? [`Fee: ${result.fee.label}`] : [],
109653
+ ...result.fee ? [`Fee: ${formatListingFee(result.fee)}`] : [],
109654
+ ...result.health ? [formatHealth(result.health)] : [],
109655
+ ...result.exampleRequest ? [`Example request: ${JSON.stringify(result.exampleRequest)}`] : [],
108384
109656
  ...result.liveness ? [formatLiveness(result.liveness)] : [],
108385
109657
  ...result.conformance ? [formatConformance(result.conformance)] : [],
108386
109658
  ...result.identity ? formatIdentityLines(result.identity) : [],
108387
- JSON.stringify(result, null, 2)
109659
+ JSON.stringify(humanResult, null, 2)
108388
109660
  ].join("\n");
108389
109661
  }
109662
+ function formatHealth(health) {
109663
+ return [
109664
+ `Health: ${health.state}`,
109665
+ ...health.uptime7d === null ? [`(${health.checks7d} checks)`] : [`${(health.uptime7d * 100).toFixed(1)}% up over 7 days (${health.checks7d} checks)`],
109666
+ ...health.latencyP50Ms === null ? [] : [`p50 ${Math.round(health.latencyP50Ms)} ms`],
109667
+ ...health.latencyP95Ms === null ? [] : [`p95 ${Math.round(health.latencyP95Ms)} ms`]
109668
+ ].join(" \xB7 ");
109669
+ }
108390
109670
  function formatLiveness(liveness) {
108391
109671
  const checks = `${liveness.checks7d} check${liveness.checks7d === 1 ? "" : "s"}`;
108392
109672
  return [
@@ -108431,7 +109711,7 @@ function formatFund(address4, url2, opened) {
108431
109711
  function openInBrowser(url2) {
108432
109712
  const opener = process.platform === "darwin" ? { command: "open", args: [url2] } : process.platform === "win32" ? { command: "cmd", args: ["/c", "start", "", url2] } : { command: "xdg-open", args: [url2] };
108433
109713
  try {
108434
- const child = spawn3(opener.command, opener.args, { stdio: "ignore", detached: true });
109714
+ const child = spawn5(opener.command, opener.args, { stdio: "ignore", detached: true });
108435
109715
  child.on("error", () => void 0);
108436
109716
  child.unref();
108437
109717
  return true;
@@ -108623,11 +109903,13 @@ function parseArguments(argv, spec) {
108623
109903
  has: (name) => flags.has(name)
108624
109904
  };
108625
109905
  }
108626
- function removeJsonFlag(argv) {
109906
+ function removeJsonFlag(argv, preserveForwarded = false) {
108627
109907
  let json2 = false;
108628
109908
  const args = [];
109909
+ let forwarding = false;
108629
109910
  for (const argument of argv) {
108630
- if (argument !== "--json") {
109911
+ if (preserveForwarded && argument === "--") forwarding = true;
109912
+ if (argument !== "--json" || forwarding) {
108631
109913
  args.push(argument);
108632
109914
  continue;
108633
109915
  }
@@ -108728,7 +110010,7 @@ function parseInitNetworks(value) {
108728
110010
 
108729
110011
  // ../cli/src/update-check.ts
108730
110012
  import { lookup } from "node:dns/promises";
108731
- import { mkdir as mkdir21, readFile as readFile29, writeFile as writeFile12 } from "node:fs/promises";
110013
+ import { mkdir as mkdir22, readFile as readFile31, writeFile as writeFile13 } from "node:fs/promises";
108732
110014
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
108733
110015
  var CHECK_TIMEOUT_MS = 1500;
108734
110016
  var LATEST_URL = "https://registry.npmjs.org/vapi-network/latest";
@@ -108745,7 +110027,7 @@ async function runCliWithUpdateCheck(argv = process.argv.slice(2), io = {
108745
110027
  async function checkForUpdate(options = {}) {
108746
110028
  const env = options.env ?? process.env;
108747
110029
  const argv = options.argv ?? process.argv.slice(2);
108748
- 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) {
110030
+ 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) {
108749
110031
  return void 0;
108750
110032
  }
108751
110033
  const controller = new AbortController();
@@ -108772,8 +110054,8 @@ async function latestNotice(options, env, signal) {
108772
110054
  const now = (options.nowMs ?? Date.now)();
108773
110055
  let cached2;
108774
110056
  try {
108775
- const value = JSON.parse(await readFile29(paths.updateCheck, "utf8"));
108776
- if (isRecord12(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
110057
+ const value = JSON.parse(await readFile31(paths.updateCheck, "utf8"));
110058
+ if (isRecord13(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
108777
110059
  cached2 = { checkedAt: value.checkedAt, latest: value.latest };
108778
110060
  }
108779
110061
  } catch {
@@ -108781,9 +110063,9 @@ async function latestNotice(options, env, signal) {
108781
110063
  signal.throwIfAborted();
108782
110064
  let latest = cached2?.latest ?? CLI_VERSION;
108783
110065
  if (cached2 === void 0 || now - cached2.checkedAt >= CHECK_INTERVAL_MS || now < cached2.checkedAt) {
108784
- await mkdir21(paths.directory, { recursive: true });
110066
+ await mkdir22(paths.directory, { recursive: true });
108785
110067
  signal.throwIfAborted();
108786
- await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
110068
+ await writeFile13(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
108787
110069
  signal.throwIfAborted();
108788
110070
  const fetchImpl = options.fetchImpl ?? createPublicFetch({
108789
110071
  allowPrivateNetwork: false,
@@ -108806,16 +110088,16 @@ async function latestNotice(options, env, signal) {
108806
110088
  if (!response.ok) return void 0;
108807
110089
  const body = await response.json();
108808
110090
  signal.throwIfAborted();
108809
- if (!isRecord12(body) || typeof body.version !== "string" || !parseVersion(body.version)) {
110091
+ if (!isRecord13(body) || typeof body.version !== "string" || !parseVersion(body.version)) {
108810
110092
  return void 0;
108811
110093
  }
108812
110094
  latest = body.version;
108813
- await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
110095
+ await writeFile13(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
108814
110096
  }
108815
110097
  signal.throwIfAborted();
108816
110098
  return isNewerVersion(latest, CLI_VERSION) ? `vapi-network ${latest} is available (you have ${CLI_VERSION}). Update: npm i -g vapi-network@latest` : void 0;
108817
110099
  }
108818
- function isRecord12(value) {
110100
+ function isRecord13(value) {
108819
110101
  return typeof value === "object" && value !== null && !Array.isArray(value);
108820
110102
  }
108821
110103
  function parseVersion(version5) {