vapi-network 0.9.7 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10128,7 +10128,7 @@ __export(src_exports4, {
10128
10128
  });
10129
10129
 
10130
10130
  // ../cli/src/cli.ts
10131
- import { spawn as spawn3 } from "node:child_process";
10131
+ import { spawn as spawn4 } from "node:child_process";
10132
10132
  import { stat as stat16 } from "node:fs/promises";
10133
10133
  import { join as join28 } from "node:path";
10134
10134
  import { createInterface as createInterface3 } from "node:readline/promises";
@@ -10180,6 +10180,7 @@ __export(src_exports, {
10180
10180
  FileLockedError: () => FileLockedError,
10181
10181
  KeystoreError: () => KeystoreError,
10182
10182
  LISTING_GROUPS: () => LISTING_GROUPS,
10183
+ LISTING_HEALTH_STATES: () => LISTING_HEALTH_STATES,
10183
10184
  LISTING_VERIFICATIONS: () => LISTING_VERIFICATIONS,
10184
10185
  LocalWallet: () => LocalWallet,
10185
10186
  MARKETPLACE_DISCOVERY_PROTOCOL: () => MARKETPLACE_DISCOVERY_PROTOCOL,
@@ -10214,6 +10215,7 @@ __export(src_exports, {
10214
10215
  SWARM_TREASURY_CAPS: () => SWARM_TREASURY_CAPS,
10215
10216
  SiblingsError: () => SiblingsError,
10216
10217
  SpendCapError: () => SpendCapError,
10218
+ SpendCapExceededError: () => SpendCapExceededError,
10217
10219
  SpendPolicy: () => SpendPolicy,
10218
10220
  SwarmError: () => SwarmError,
10219
10221
  SweepGasError: () => SweepGasError,
@@ -10315,6 +10317,7 @@ __export(src_exports, {
10315
10317
  firstPartyProvenanceSchema: () => firstPartyProvenanceSchema,
10316
10318
  formatCeilingUsd: () => formatCeilingUsd,
10317
10319
  formatLegacyRegistryRewrites: () => formatLegacyRegistryRewrites,
10320
+ formatListingFee: () => formatListingFee,
10318
10321
  formatUsdAmount: () => formatUsdAmount,
10319
10322
  formatUsdc: () => formatUsdc,
10320
10323
  fundSwarm: () => fundSwarm,
@@ -10351,6 +10354,8 @@ __export(src_exports, {
10351
10354
  listingDisclosureShape: () => listingDisclosureShape,
10352
10355
  listingFeeSchema: () => listingFeeSchema,
10353
10356
  listingGroupSchema: () => listingGroupSchema,
10357
+ listingHealthSchema: () => listingHealthSchema,
10358
+ listingHealthStateSchema: () => listingHealthStateSchema,
10354
10359
  listingIdentitySchema: () => listingIdentitySchema,
10355
10360
  listingLivenessSchema: () => listingLivenessSchema,
10356
10361
  listingVerificationFieldSchema: () => listingVerificationFieldSchema,
@@ -10359,6 +10364,7 @@ __export(src_exports, {
10359
10364
  loadOrCreateDeviceKey: () => loadOrCreateDeviceKey,
10360
10365
  lockVault: () => lockVault,
10361
10366
  lowerAccountCaps: () => lowerAccountCaps,
10367
+ marketplaceAlternativeSchema: () => marketplaceAlternativeSchema,
10362
10368
  marketplaceBadgeCodeSchema: () => marketplaceBadgeCodeSchema,
10363
10369
  marketplaceBadgeSchema: () => marketplaceBadgeSchema,
10364
10370
  marketplaceDiscoveryEnvelopeSchema: () => marketplaceDiscoveryEnvelopeSchema,
@@ -39703,6 +39709,32 @@ var listingLivenessSchema = external_exports.looseObject({
39703
39709
  latencyP95Ms: external_exports.number().nonnegative().nullable(),
39704
39710
  checks7d: external_exports.number().int().nonnegative()
39705
39711
  });
39712
+ var LISTING_HEALTH_STATES = ["healthy", "degraded", "outage", "unknown"];
39713
+ var listingHealthStateSchema = external_exports.enum(LISTING_HEALTH_STATES).catch("unknown");
39714
+ var listingHealthSchema = external_exports.looseObject({
39715
+ state: listingHealthStateSchema,
39716
+ uptime7d: external_exports.number().min(0).max(1).nullable().catch(null),
39717
+ latencyP50Ms: external_exports.number().nonnegative().nullable().catch(null),
39718
+ latencyP95Ms: external_exports.number().nonnegative().nullable().catch(null),
39719
+ checks7d: external_exports.number().int().nonnegative().catch(0)
39720
+ });
39721
+ var marketplaceAlternativeSchema = external_exports.looseObject({
39722
+ ref: external_exports.string().trim().min(1),
39723
+ reason: external_exports.enum(["cheaper", "healthier"])
39724
+ });
39725
+ var marketplaceAlternativesSchema = external_exports.preprocess((value) => {
39726
+ if (!Array.isArray(value)) return void 0;
39727
+ const alternatives = [];
39728
+ const refs = /* @__PURE__ */ new Set();
39729
+ for (const entry of value) {
39730
+ const parsed = marketplaceAlternativeSchema.safeParse(entry);
39731
+ if (!parsed.success || refs.has(parsed.data.ref)) continue;
39732
+ refs.add(parsed.data.ref);
39733
+ alternatives.push(parsed.data);
39734
+ if (alternatives.length === 2) break;
39735
+ }
39736
+ return alternatives.length > 0 ? alternatives : void 0;
39737
+ }, external_exports.array(marketplaceAlternativeSchema).optional());
39706
39738
  var listingConformanceSchema = external_exports.looseObject({
39707
39739
  declaredVersion: external_exports.union([external_exports.literal(1), external_exports.literal(2)]).nullable(),
39708
39740
  versionConformant: external_exports.boolean(),
@@ -39734,7 +39766,8 @@ var marketplaceBadgeCodeSchema = external_exports.enum([
39734
39766
  "vapi_verified",
39735
39767
  "external_catalog",
39736
39768
  "approved_vendor",
39737
- "unverified"
39769
+ "unverified",
39770
+ "failed_calls_free"
39738
39771
  ]);
39739
39772
  var marketplaceBadgeSchema = external_exports.looseObject({
39740
39773
  code: marketplaceBadgeCodeSchema,
@@ -39775,6 +39808,8 @@ var firstPartyApiMarketplaceHitSchema = external_exports.looseObject({
39775
39808
  ...marketplaceHitBase,
39776
39809
  kind: external_exports.literal("api"),
39777
39810
  provenance: firstPartyProvenanceSchema,
39811
+ health: listingHealthSchema.optional().catch(void 0),
39812
+ alternatives: marketplaceAlternativesSchema.optional().catch(void 0),
39778
39813
  execution: external_exports.looseObject({
39779
39814
  mode: executionModeSchema
39780
39815
  }),
@@ -39784,6 +39819,8 @@ var mirroredApiMarketplaceHitSchema = external_exports.looseObject({
39784
39819
  ...marketplaceHitBase,
39785
39820
  kind: external_exports.literal("api"),
39786
39821
  provenance: external_exports.literal("indexed"),
39822
+ health: listingHealthSchema.optional().catch(void 0),
39823
+ alternatives: marketplaceAlternativesSchema.optional().catch(void 0),
39787
39824
  execution: external_exports.looseObject({
39788
39825
  mode: external_exports.literal("direct"),
39789
39826
  url: external_exports.url().max(2048).regex(/^https:\/\/(?![^/?#]*@)/),
@@ -39833,7 +39870,8 @@ var marketplaceDiscoveryInputSchema = external_exports.strictObject({
39833
39870
  network: external_exports.string().trim().min(1).max(160).optional(),
39834
39871
  cursor: external_exports.string().trim().min(1).max(4096).optional(),
39835
39872
  limit: external_exports.number().int().min(1).max(50).optional(),
39836
- includeUnverified: external_exports.boolean().optional()
39873
+ includeUnverified: external_exports.boolean().optional(),
39874
+ includeOutage: external_exports.boolean().optional()
39837
39875
  }).superRefine((input2, context) => {
39838
39876
  if (input2.kinds && new Set(input2.kinds).size !== input2.kinds.length) {
39839
39877
  context.addIssue({
@@ -39851,7 +39889,14 @@ var marketplaceDiscoveryEnvelopeSchema = external_exports.looseObject({
39851
39889
  items: external_exports.array(external_exports.unknown()),
39852
39890
  nextCursor: external_exports.string().min(1).max(4096).nullable(),
39853
39891
  unavailableKinds: external_exports.array(marketplaceKindSchema).max(MARKETPLACE_KINDS.length),
39854
- rankingVersion: external_exports.literal(MARKETPLACE_RANKING_VERSION)
39892
+ // The ranking label is informational: pinning it made every installed client
39893
+ // reject the page the day the registry re-ranked, so any label is accepted.
39894
+ rankingVersion: external_exports.string().trim().min(1).max(80),
39895
+ // `hiddenOutage` counts listings in outage the registry left out because
39896
+ // `includeOutage` was not set. Older registries send no totals at all.
39897
+ totals: external_exports.looseObject({
39898
+ hiddenOutage: external_exports.number().int().nonnegative().optional().catch(void 0)
39899
+ }).optional().catch(void 0)
39855
39900
  });
39856
39901
  var marketplaceDiscoveryPageSchema = marketplaceDiscoveryEnvelopeSchema.extend({
39857
39902
  items: external_exports.array(marketplaceHitSchema)
@@ -40887,14 +40932,14 @@ function assertByteArrayOffsetIsNotOutOfRange(codecDescription, offset, bytesLen
40887
40932
  }
40888
40933
  }
40889
40934
  function addEncoderSizePrefix(encoder5, prefix) {
40890
- const write = ((value, bytes, offset) => {
40935
+ const write2 = ((value, bytes, offset) => {
40891
40936
  const encoderBytes = encoder5.encode(value);
40892
40937
  offset = prefix.write(encoderBytes.length, bytes, offset);
40893
40938
  bytes.set(encoderBytes, offset);
40894
40939
  return offset + encoderBytes.length;
40895
40940
  });
40896
40941
  if (isFixedSize(prefix) && isFixedSize(encoder5)) {
40897
- return createEncoder({ ...encoder5, fixedSize: prefix.fixedSize + encoder5.fixedSize, write });
40942
+ return createEncoder({ ...encoder5, fixedSize: prefix.fixedSize + encoder5.fixedSize, write: write2 });
40898
40943
  }
40899
40944
  const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
40900
40945
  const encoderMaxSize = isFixedSize(encoder5) ? encoder5.fixedSize : encoder5.maxSize ?? null;
@@ -40906,7 +40951,7 @@ function addEncoderSizePrefix(encoder5, prefix) {
40906
40951
  const encoderSize = getEncodedSize(value, encoder5);
40907
40952
  return getEncodedSize(encoderSize, prefix) + encoderSize;
40908
40953
  },
40909
- write
40954
+ write: write2
40910
40955
  });
40911
40956
  }
40912
40957
  function addDecoderSizePrefix(decoder2, prefix) {
@@ -41742,13 +41787,13 @@ function getTupleDecoder(items) {
41742
41787
  }
41743
41788
  function getUnionEncoder(variants, getIndexFromValue) {
41744
41789
  const fixedSize = getUnionFixedSize(variants);
41745
- const write = (variant, bytes, offset) => {
41790
+ const write2 = (variant, bytes, offset) => {
41746
41791
  const index2 = getIndexFromValue(variant);
41747
41792
  assertValidVariantIndex(variants, index2);
41748
41793
  return variants[index2].write(variant, bytes, offset);
41749
41794
  };
41750
41795
  if (fixedSize !== null) {
41751
- return createEncoder({ fixedSize, write });
41796
+ return createEncoder({ fixedSize, write: write2 });
41752
41797
  }
41753
41798
  const maxSize = getUnionMaxSize(variants);
41754
41799
  return createEncoder({
@@ -41758,7 +41803,7 @@ function getUnionEncoder(variants, getIndexFromValue) {
41758
41803
  assertValidVariantIndex(variants, index2);
41759
41804
  return getEncodedSize(variant, variants[index2]);
41760
41805
  },
41761
- write
41806
+ write: write2
41762
41807
  });
41763
41808
  }
41764
41809
  function getUnionDecoder(variants, getIndexFromBytes) {
@@ -46403,6 +46448,11 @@ var discoveryEndpointSchema = external_exports.looseObject({
46403
46448
  operationId: external_exports.string().trim().min(1).optional(),
46404
46449
  requestContentType: external_exports.string().trim().min(1).optional(),
46405
46450
  requestSchema: external_exports.json().optional(),
46451
+ responseSchema: external_exports.json().optional().catch(void 0),
46452
+ exampleRequest: external_exports.looseObject({
46453
+ query: external_exports.record(external_exports.string(), external_exports.string()).optional().catch(void 0),
46454
+ body: external_exports.json().optional()
46455
+ }).optional().catch(void 0),
46406
46456
  responseContentType: external_exports.string().trim().min(1).optional(),
46407
46457
  pathTemplate: external_exports.string().trim().min(1).optional(),
46408
46458
  pathParameters: external_exports.array(external_exports.string().trim().min(1)).optional(),
@@ -70729,7 +70779,7 @@ function keychainStore(platform2, run) {
70729
70779
  const value = withoutTrailingNewline(result.stdout);
70730
70780
  return value.length === 0 ? void 0 : value;
70731
70781
  };
70732
- const write = async (account, value, what) => {
70782
+ const write2 = async (account, value, what) => {
70733
70783
  const result = await run(
70734
70784
  SECURITY_BINARY,
70735
70785
  [
@@ -70800,7 +70850,7 @@ ${value}
70800
70850
  const account = accountFor(name);
70801
70851
  const what = `store the passphrase of ${name} in the macOS Keychain`;
70802
70852
  if (passphrase.length <= KEYCHAIN_PROMPT_LIMIT) {
70803
- await write(account, passphrase, what);
70853
+ await write2(account, passphrase, what);
70804
70854
  return;
70805
70855
  }
70806
70856
  const chunks = [];
@@ -70811,10 +70861,10 @@ ${value}
70811
70861
  throw new KeystoreError(`The secret ${name} is too long for the macOS Keychain.`);
70812
70862
  }
70813
70863
  for (const [index2, chunk] of chunks.entries()) {
70814
- await write(keychainPart(account, index2 + 1), chunk, what);
70864
+ await write2(keychainPart(account, index2 + 1), chunk, what);
70815
70865
  }
70816
70866
  await erasePartsAfter(account, chunks.length, what);
70817
- await write(account, `${CHUNKED_MARKER}${chunks.length}`, what);
70867
+ await write2(account, `${CHUNKED_MARKER}${chunks.length}`, what);
70818
70868
  },
70819
70869
  async remove(name) {
70820
70870
  const account = accountFor(name);
@@ -74347,12 +74397,14 @@ var ledgerFileSchema = external_exports.union([
74347
74397
  ledgerRowSchema
74348
74398
  ]);
74349
74399
  var SpendCapError = class extends Error {
74350
- constructor(code, message) {
74400
+ constructor(code, message, details) {
74351
74401
  super(message);
74352
74402
  this.code = code;
74403
+ this.details = details;
74353
74404
  this.name = "SpendCapError";
74354
74405
  }
74355
74406
  code;
74407
+ details;
74356
74408
  };
74357
74409
  function utcDateKey(now = /* @__PURE__ */ new Date()) {
74358
74410
  return now.toISOString().slice(0, 10);
@@ -74434,7 +74486,8 @@ async function reserveSpend(amountAtomic2, caps, options) {
74434
74486
  if (amountAtomic2 > perCallAtomic) {
74435
74487
  throw new SpendCapError(
74436
74488
  "per_call_cap_exceeded",
74437
- `Payment quote ${amountAtomic2} atomic USDC exceeds the per-call cap ${perCallAtomic}. Refusing to sign.`
74489
+ `Payment quote ${amountAtomic2} atomic USDC exceeds the per-call cap ${perCallAtomic}. Refusing to sign.`,
74490
+ { amountAtomic: amountAtomic2, limitAtomic: perCallAtomic, wallet: options?.wallet }
74438
74491
  );
74439
74492
  }
74440
74493
  }
@@ -74523,7 +74576,8 @@ async function reserveSpend(amountAtomic2, caps, options) {
74523
74576
  if (nextSpent > perDayAtomic) {
74524
74577
  throw new SpendCapError(
74525
74578
  "per_day_cap_exceeded",
74526
- `${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.`
74579
+ `${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.`,
74580
+ { amountAtomic: amountAtomic2, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
74527
74581
  );
74528
74582
  }
74529
74583
  const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes10(16).toString("hex"));
@@ -77479,6 +77533,96 @@ function parseAtomic(value, label) {
77479
77533
  throw new Error(`Invalid ${label} atomic amount.`);
77480
77534
  }
77481
77535
 
77536
+ // ../core/src/spend-cap-exceeded.ts
77537
+ var SpendCapExceededError = class extends Error {
77538
+ name = "SpendCapExceededError";
77539
+ code = "spend_cap_exceeded";
77540
+ retryable = false;
77541
+ cap;
77542
+ amountUsd;
77543
+ limitUsd;
77544
+ spentUsd;
77545
+ wallet;
77546
+ command;
77547
+ constructor(input2) {
77548
+ const amountUsd = normalizeUsd(input2.amountUsd);
77549
+ const limitUsd = normalizeUsd(input2.limitUsd);
77550
+ const spentUsd = input2.spentUsd === void 0 ? void 0 : normalizeUsd(input2.spentUsd);
77551
+ const wallet = input2.wallet?.trim() || void 0;
77552
+ const command = input2.command === void 0 ? spendCapCommand(input2.cap, amountUsd, spentUsd, wallet, input2.perDayLimitUsd) : input2.command;
77553
+ super(
77554
+ input2.message ?? spendCapMessage(input2.cap, amountUsd, limitUsd, spentUsd, wallet, command),
77555
+ input2.cause === void 0 ? void 0 : { cause: input2.cause }
77556
+ );
77557
+ this.cap = input2.cap;
77558
+ this.amountUsd = amountUsd;
77559
+ this.limitUsd = limitUsd;
77560
+ this.spentUsd = spentUsd;
77561
+ this.wallet = wallet;
77562
+ this.command = command;
77563
+ }
77564
+ toJSON() {
77565
+ return {
77566
+ code: this.code,
77567
+ cap: this.cap,
77568
+ amountUsd: this.amountUsd,
77569
+ limitUsd: this.limitUsd,
77570
+ ...this.spentUsd === void 0 ? {} : { spentUsd: this.spentUsd },
77571
+ ...this.wallet === void 0 ? {} : { wallet: this.wallet },
77572
+ command: this.command,
77573
+ message: this.message
77574
+ };
77575
+ }
77576
+ };
77577
+ function spendCapCommand(cap, amountUsd, spentUsd, wallet, perDayLimitUsd) {
77578
+ const account = wallet ?? "<account>";
77579
+ if (cap === "per_call") {
77580
+ const scale = Math.max(fractionLength(amountUsd), fractionLength(perDayLimitUsd ?? "0"));
77581
+ const raiseDay = perDayLimitUsd !== void 0 && parseDecimal(amountUsd, scale) > parseDecimal(perDayLimitUsd, scale);
77582
+ return `vapi accounts caps ${account} --per-call ${amountUsd}${raiseDay ? ` --per-day ${amountUsd}` : ""}`;
77583
+ }
77584
+ if (cap === "per_day") {
77585
+ return `vapi accounts caps ${account} --per-day ${addUsd(spentUsd ?? "0", amountUsd)}`;
77586
+ }
77587
+ if (cap === "max_price") {
77588
+ return `--max ${amountUsd}`;
77589
+ }
77590
+ if (cap === "run_budget") {
77591
+ const budget = addUsd(spentUsd ?? "0", amountUsd);
77592
+ return `--budget ${budget}`;
77593
+ }
77594
+ return null;
77595
+ }
77596
+ function spendCapMessage(cap, amountUsd, limitUsd, spentUsd, wallet, command) {
77597
+ 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";
77598
+ const account = cap === "per_call" || cap === "per_day" ? ` of account ${wallet ?? "<account>"}` : "";
77599
+ 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}`;
77600
+ 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:";
77601
+ const action = command === null ? "" : `${guidance} ${command}`;
77602
+ return `Blocked by the ${capName}${account}: ${payment}. Nothing was signed.${action}`;
77603
+ }
77604
+ function normalizeUsd(value) {
77605
+ const trimmed = value.trim();
77606
+ if (!trimmed.includes(".")) return trimmed;
77607
+ const normalized = trimmed.replace(/0+$/u, "").replace(/\.$/u, "");
77608
+ return normalized || "0";
77609
+ }
77610
+ function addUsd(left, right) {
77611
+ const scale = Math.max(fractionLength(left), fractionLength(right));
77612
+ const factor = 10n ** BigInt(scale);
77613
+ const total = parseDecimal(left, scale) + parseDecimal(right, scale);
77614
+ const whole = total / factor;
77615
+ const fraction = (total % factor).toString().padStart(scale, "0").replace(/0+$/u, "");
77616
+ return fraction ? `${whole}.${fraction}` : whole.toString();
77617
+ }
77618
+ function fractionLength(value) {
77619
+ return value.split(".")[1]?.length ?? 0;
77620
+ }
77621
+ function parseDecimal(value, scale) {
77622
+ const [whole = "0", fraction = ""] = value.split(".");
77623
+ return BigInt(whole) * 10n ** BigInt(scale) + BigInt(fraction.padEnd(scale, "0") || "0");
77624
+ }
77625
+
77482
77626
  // ../core/src/swarm.ts
77483
77627
  import { readdir as readdir6, readFile as readFile15, stat as stat11, unlink as unlink11 } from "node:fs/promises";
77484
77628
  import { join as join12 } from "node:path";
@@ -78150,7 +78294,7 @@ function createRunBudget(args) {
78150
78294
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
78151
78295
  import { arch, platform, release } from "node:os";
78152
78296
  import { join as join13 } from "node:path";
78153
- var VAPI_CLIENT_VERSION = "0.9.7";
78297
+ var VAPI_CLIENT_VERSION = "0.11.0";
78154
78298
  async function createSupportReport(options) {
78155
78299
  const message = options.message.trim();
78156
78300
  if (!message) throw new Error("Support report message must not be empty.");
@@ -78345,8 +78489,28 @@ async function completeX402Payment(args) {
78345
78489
  }
78346
78490
  args.challenge.request.signal.throwIfAborted();
78347
78491
  if (trace) trace.capsApplied = true;
78348
- assertMaximumAtomic(quote.amountAtomic, args.maxAtomic);
78349
- assertMaxPrice(quote.amountAtomic, args.maxPriceUsd);
78492
+ try {
78493
+ assertMaximumAtomic(quote.amountAtomic, args.maxAtomic);
78494
+ } catch (error61) {
78495
+ if (args.maxAtomic !== void 0 && isErrorCode(error61, "max_price_exceeded")) {
78496
+ throw paymentCapError("max_amount", quote.amountAtomic, args.maxAtomic, args, error61);
78497
+ }
78498
+ throw error61;
78499
+ }
78500
+ try {
78501
+ assertMaxPrice(quote.amountAtomic, args.maxPriceUsd);
78502
+ } catch (error61) {
78503
+ if (args.maxPriceUsd !== void 0 && isErrorCode(error61, "max_price_exceeded")) {
78504
+ throw paymentCapError(
78505
+ "max_price",
78506
+ quote.amountAtomic,
78507
+ usdToAtomic(args.maxPriceUsd),
78508
+ args,
78509
+ error61
78510
+ );
78511
+ }
78512
+ throw error61;
78513
+ }
78350
78514
  const spendReservation = {
78351
78515
  ledgerPath: args.ledgerPath ?? getVapiPaths().ledger,
78352
78516
  now: args.now,
@@ -78355,18 +78519,42 @@ async function completeX402Payment(args) {
78355
78519
  let reservationId;
78356
78520
  let reservedOn;
78357
78521
  if (args.runBudget === void 0) {
78358
- await reserveSpend(quote.amountAtomic, args.caps, spendReservation);
78522
+ try {
78523
+ await reserveSpend(quote.amountAtomic, args.caps, spendReservation);
78524
+ } catch (error61) {
78525
+ throw walletCapError(error61, quote.amountAtomic, args);
78526
+ }
78359
78527
  } else {
78360
78528
  reservationId = args.paymentId ?? `x402_${randomBytes14(12).toString("hex")}`;
78361
- const reservation = await reserveSpend(quote.amountAtomic, args.caps, {
78362
- ...spendReservation,
78363
- reservationId
78364
- });
78529
+ let reservation;
78530
+ try {
78531
+ reservation = await reserveSpend(quote.amountAtomic, args.caps, {
78532
+ ...spendReservation,
78533
+ reservationId
78534
+ });
78535
+ } catch (error61) {
78536
+ throw walletCapError(error61, quote.amountAtomic, args);
78537
+ }
78365
78538
  reservedOn = reservation.date;
78366
78539
  try {
78367
78540
  args.runBudget.reserve(quote.amountAtomic, reservationId);
78368
78541
  } catch (error61) {
78369
- await releaseUnsentReservation(args, quote.amountAtomic, reservationId, reservedOn);
78542
+ let runSpentAtomic;
78543
+ try {
78544
+ runSpentAtomic = args.runBudget.spentAtomic();
78545
+ } finally {
78546
+ await releaseUnsentReservation(args, quote.amountAtomic, reservationId, reservedOn);
78547
+ }
78548
+ if (error61 instanceof RunBudgetError || isErrorCode(error61, "run_budget_exceeded")) {
78549
+ throw new SpendCapExceededError({
78550
+ cap: "run_budget",
78551
+ amountUsd: formatUsdc(quote.amountAtomic),
78552
+ limitUsd: formatUsdc(args.runBudget.limitAtomic),
78553
+ spentUsd: formatUsdc(runSpentAtomic),
78554
+ ...args.wallet === void 0 ? {} : { wallet: args.wallet },
78555
+ cause: error61
78556
+ });
78557
+ }
78370
78558
  throw error61;
78371
78559
  }
78372
78560
  }
@@ -78649,6 +78837,18 @@ function sanitizeThrownError(error61, secrets) {
78649
78837
  if (!(error61 instanceof Error)) return error61;
78650
78838
  const message = redactKnownSecrets(error61.message, secrets);
78651
78839
  const cause = error61.cause === void 0 ? void 0 : sanitizeThrownError(error61.cause, secrets);
78840
+ if (error61 instanceof SpendCapExceededError) {
78841
+ return new SpendCapExceededError({
78842
+ cap: error61.cap,
78843
+ amountUsd: error61.amountUsd,
78844
+ limitUsd: error61.limitUsd,
78845
+ ...error61.spentUsd === void 0 ? {} : { spentUsd: error61.spentUsd },
78846
+ ...error61.wallet === void 0 ? {} : { wallet: error61.wallet },
78847
+ command: error61.command,
78848
+ message,
78849
+ ...cause === void 0 ? {} : { cause }
78850
+ });
78851
+ }
78652
78852
  if (message === error61.message && cause === error61.cause) return error61;
78653
78853
  if (error61 instanceof X402Error) {
78654
78854
  return new X402Error(error61.code, message, cause === void 0 ? void 0 : { cause });
@@ -78750,6 +78950,43 @@ function assertMaximumAtomic(amountAtomic2, maxAtomic) {
78750
78950
  );
78751
78951
  }
78752
78952
  }
78953
+ function walletCapError(error61, amountAtomic2, args) {
78954
+ if (!(error61 instanceof SpendCapError)) return error61;
78955
+ if (error61.code === "per_call_cap_exceeded") {
78956
+ return paymentCapError(
78957
+ "per_call",
78958
+ amountAtomic2,
78959
+ error61.details?.limitAtomic ?? BigInt(args.caps.perCallAtomic),
78960
+ args,
78961
+ error61
78962
+ );
78963
+ }
78964
+ if (error61.code === "per_day_cap_exceeded") {
78965
+ return paymentCapError(
78966
+ "per_day",
78967
+ amountAtomic2,
78968
+ error61.details?.limitAtomic ?? BigInt(args.caps.perDayAtomic),
78969
+ args,
78970
+ error61,
78971
+ error61.details?.spentAtomic
78972
+ );
78973
+ }
78974
+ return error61;
78975
+ }
78976
+ function paymentCapError(cap, amountAtomic2, limitAtomic, args, cause, spentAtomic) {
78977
+ return new SpendCapExceededError({
78978
+ cap,
78979
+ amountUsd: formatUsdc(amountAtomic2),
78980
+ limitUsd: formatUsdc(limitAtomic),
78981
+ ...cap === "per_call" ? { perDayLimitUsd: formatUsdc(BigInt(args.caps.perDayAtomic)) } : {},
78982
+ ...spentAtomic === void 0 ? {} : { spentUsd: formatUsdc(spentAtomic) },
78983
+ ...args.wallet === void 0 ? {} : { wallet: args.wallet },
78984
+ cause
78985
+ });
78986
+ }
78987
+ function isErrorCode(error61, code) {
78988
+ return typeof error61 === "object" && error61 !== null && Reflect.get(error61, "code") === code;
78989
+ }
78753
78990
  function settlementUnknown(message, quote, payment, payer, receipt, cause) {
78754
78991
  return new X402PaymentError(
78755
78992
  "settlement_unknown",
@@ -78825,7 +79062,7 @@ function receiptQuote(quote) {
78825
79062
  };
78826
79063
  }
78827
79064
  function paymentErrorOutcome(error61) {
78828
- if (error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error && error61.code === "max_price_exceeded") {
79065
+ if (error61 instanceof SpendCapExceededError || error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error && error61.code === "max_price_exceeded") {
78829
79066
  return "declined_policy";
78830
79067
  }
78831
79068
  if (error61 instanceof X402PaymentError) {
@@ -78842,7 +79079,7 @@ function errorCode(error61) {
78842
79079
  return "request_failed";
78843
79080
  }
78844
79081
  function receiptSafeErrorMessage(error61) {
78845
- if (error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error || error61 instanceof X402PaymentError) {
79082
+ if (error61 instanceof SpendCapExceededError || error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error || error61 instanceof X402PaymentError) {
78846
79083
  return error61.message;
78847
79084
  }
78848
79085
  return "The x402 request failed before it completed.";
@@ -79348,15 +79585,18 @@ function budgetExhaustedError(resetsAt, status) {
79348
79585
  );
79349
79586
  }
79350
79587
  function refillDeclinedDetail(error61) {
79588
+ if (error61 instanceof SpendCapExceededError) return `${error61.name}: ${error61.cap}`;
79351
79589
  if (error61 instanceof SpendCapError) return `${error61.name}: ${error61.code}`;
79352
- if (isRunBudgetError(error61)) return `RunBudgetError: ${error61.code}`;
79590
+ if (isRunBudgetError(error61)) {
79591
+ return error61.code === "spend_cap_exceeded" ? "SpendCapExceededError: run_budget" : `RunBudgetError: ${error61.code}`;
79592
+ }
79353
79593
  if (error61 instanceof RouterClientError) {
79354
79594
  return `${error61.name}: ${error61.code}${error61.status === void 0 ? "" : ` (${error61.status})`}`;
79355
79595
  }
79356
79596
  return "Error: Router balance refill failed.";
79357
79597
  }
79358
79598
  function isRunBudgetError(error61) {
79359
- return typeof error61 === "object" && error61 !== null && Reflect.get(error61, "code") === "run_budget_exceeded";
79599
+ 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");
79360
79600
  }
79361
79601
  function isRouterTopupTier(value) {
79362
79602
  return ROUTER_TOPUP_TIERS.some((tier) => tier === value);
@@ -84805,7 +85045,10 @@ function normalizeResourceUrl(value) {
84805
85045
  async function discover(sources, query, options = {}) {
84806
85046
  const nowMs = options.nowMs ?? (() => performance.now());
84807
85047
  const startedAt = options.now ?? /* @__PURE__ */ new Date();
84808
- const searchOptions = options.includeUnverified === void 0 ? {} : { includeUnverified: options.includeUnverified };
85048
+ const searchOptions = {
85049
+ ...options.includeUnverified === void 0 ? {} : { includeUnverified: options.includeUnverified },
85050
+ ...options.includeOutage === void 0 ? {} : { includeOutage: options.includeOutage }
85051
+ };
84809
85052
  const settled = await Promise.all(
84810
85053
  sources.map(async (source) => {
84811
85054
  const started = nowMs();
@@ -85530,6 +85773,11 @@ function safeOrigin2(value) {
85530
85773
  }
85531
85774
  }
85532
85775
 
85776
+ // ../core/src/listing-fee.ts
85777
+ function formatListingFee(fee) {
85778
+ return fee.bps === 0 ? "No network fee" : `${fee.label} (${fee.bps / 100}%)`;
85779
+ }
85780
+
85533
85781
  // ../core/src/onramp.ts
85534
85782
  var ONRAMP_NETWORK = "base";
85535
85783
  var ONRAMP_FALLBACK_INSTRUCTIONS = "Send USDC on Base (eip155:8453) to this address; add a little ETH for gas if you plan to sweep.";
@@ -88395,7 +88643,7 @@ __export(src_exports3, {
88395
88643
  runResultPath: () => runResultPath,
88396
88644
  runSwarm: () => runSwarm,
88397
88645
  runsDirectory: () => runsDirectory,
88398
- searchMarketplace: () => searchMarketplace,
88646
+ searchMarketplace: () => searchMarketplace2,
88399
88647
  selectLead: () => selectLead,
88400
88648
  startDetachedRun: () => startDetachedRun,
88401
88649
  startDetachedSwarmRun: () => startDetachedSwarmRun,
@@ -88766,7 +89014,8 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
88766
89014
  network: input2.network,
88767
89015
  limit: input2.limit,
88768
89016
  cursor: input2.cursor,
88769
- includeUnverified: input2.includeUnverified
89017
+ includeUnverified: input2.includeUnverified,
89018
+ includeOutage: input2.includeOutage
88770
89019
  });
88771
89020
  const startedAt = options.now ?? /* @__PURE__ */ new Date();
88772
89021
  const attempts = [];
@@ -88788,6 +89037,9 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
88788
89037
  if (normalized.includeUnverified === true) {
88789
89038
  url2.searchParams.set("includeUnverified", "true");
88790
89039
  }
89040
+ if (normalized.includeOutage === true) {
89041
+ url2.searchParams.set("includeOutage", "true");
89042
+ }
88791
89043
  }
88792
89044
  });
88793
89045
  const envelope = marketplaceDiscoveryEnvelopeSchema.parse(await response.json());
@@ -88835,7 +89087,7 @@ async function resolveServiceListing(id2, config2, fetchImpl, endpointName) {
88835
89087
  }
88836
89088
  async function findMarketplaceApiByRef(ref, config2, fetchImpl) {
88837
89089
  const page = await searchMarketplace(
88838
- { query: ref, kinds: ["api"], limit: 50, includeUnverified: true },
89090
+ { query: ref, kinds: ["api"], limit: 50, includeUnverified: true, includeOutage: true },
88839
89091
  config2,
88840
89092
  fetchImpl
88841
89093
  );
@@ -88855,7 +89107,8 @@ function vapiRegistrySource(baseUrl, options = {}) {
88855
89107
  {
88856
89108
  query,
88857
89109
  kinds: ["api"],
88858
- ...searchOptions?.includeUnverified === void 0 ? {} : { includeUnverified: searchOptions.includeUnverified }
89110
+ ...searchOptions?.includeUnverified === void 0 ? {} : { includeUnverified: searchOptions.includeUnverified },
89111
+ ...searchOptions?.includeOutage === void 0 ? {} : { includeOutage: searchOptions.includeOutage }
88859
89112
  },
88860
89113
  config2,
88861
89114
  fetchImpl
@@ -88897,7 +89150,7 @@ function vapiRegistrySource(baseUrl, options = {}) {
88897
89150
  throw resolutionError;
88898
89151
  }
88899
89152
  const page = await searchMarketplace(
88900
- { query: ref, kinds: ["api"], includeUnverified: true },
89153
+ { query: ref, kinds: ["api"], includeUnverified: true, includeOutage: true },
88901
89154
  config2,
88902
89155
  fetchImpl
88903
89156
  );
@@ -88921,6 +89174,7 @@ async function fetchCallsDiscovery(query, config2, fetchImpl) {
88921
89174
  configureUrl(url2) {
88922
89175
  url2.searchParams.set("q", query);
88923
89176
  url2.searchParams.set("includeUnverified", "true");
89177
+ url2.searchParams.set("includeOutage", "true");
88924
89178
  }
88925
89179
  });
88926
89180
  return parseDiscovery(await response.json());
@@ -89080,6 +89334,18 @@ function x402scanSource() {
89080
89334
  };
89081
89335
  }
89082
89336
 
89337
+ // ../mcp/src/tools/search.ts
89338
+ async function searchMarketplace2(...args) {
89339
+ const page = await searchMarketplace(...args);
89340
+ return {
89341
+ ...page,
89342
+ items: page.items.map((item) => ({
89343
+ ...item,
89344
+ ...item.fee === void 0 ? {} : { feeDisplay: formatListingFee(item.fee) }
89345
+ }))
89346
+ };
89347
+ }
89348
+
89083
89349
  // ../mcp/src/tools/call.ts
89084
89350
  var VapiCallError = class extends Error {
89085
89351
  constructor(code, message, possibleSettlement2, options) {
@@ -89590,7 +89856,7 @@ function receiptContext(args, trace, resourceUrl) {
89590
89856
  };
89591
89857
  }
89592
89858
  function errorOutcome(error61, code) {
89593
- if (code === "max_price_exceeded" || code.includes("cap_exceeded")) {
89859
+ if (error61 instanceof SpendCapExceededError || code === "max_price_exceeded" || code.includes("cap_exceeded")) {
89594
89860
  return "declined_policy";
89595
89861
  }
89596
89862
  if (error61 instanceof VapiCallError) {
@@ -89932,6 +90198,7 @@ function paidRequestTimeoutMs(timeoutSeconds, internalTimeoutMs, offerTimeoutSec
89932
90198
  return usableOfferTimeout === void 0 ? 12e4 : Math.min(12e4, Math.max(3e4, usableOfferTimeout * 1e3));
89933
90199
  }
89934
90200
  function mapX402PaymentError(error61, resumeId) {
90201
+ if (error61 instanceof SpendCapExceededError) return error61;
89935
90202
  if (!(error61 instanceof X402PaymentError)) return error61;
89936
90203
  if (error61.code === "payment_rejected") {
89937
90204
  return new VapiCallError("payment_rejected", error61.message, void 0, {
@@ -89991,9 +90258,11 @@ async function inspectService(input2, config2, fetchImpl) {
89991
90258
  ...endpoint.operationId === void 0 ? {} : { operationId: endpoint.operationId },
89992
90259
  ...endpoint.requestContentType === void 0 ? {} : { requestContentType: endpoint.requestContentType },
89993
90260
  ...endpoint.requestSchema === void 0 ? {} : { requestSchema: endpoint.requestSchema },
90261
+ ...endpoint.responseSchema === void 0 ? {} : { responseSchema: endpoint.responseSchema },
90262
+ ...endpoint.exampleRequest === void 0 ? {} : { exampleRequest: endpoint.exampleRequest },
89994
90263
  ...endpoint.responseContentType === void 0 ? {} : { responseContentType: endpoint.responseContentType },
89995
90264
  ...service.group === void 0 ? {} : { group: service.group },
89996
- ...service.fee === void 0 ? {} : { fee: service.fee },
90265
+ ...service.fee === void 0 ? {} : { fee: service.fee, feeDisplay: formatListingFee(service.fee) },
89997
90266
  verification: service.verification,
89998
90267
  ...healthOf(service),
89999
90268
  payment: endpoint.payment ?? null
@@ -90008,14 +90277,16 @@ function inspectIndexedHit(hit) {
90008
90277
  description: hit.card.summary,
90009
90278
  network: hit.execution.network,
90010
90279
  ...hit.group === void 0 ? {} : { group: hit.group },
90011
- ...hit.fee === void 0 ? {} : { fee: hit.fee },
90280
+ ...hit.fee === void 0 ? {} : { fee: hit.fee, feeDisplay: formatListingFee(hit.fee) },
90012
90281
  verification: hit.verification,
90013
90282
  ...healthOf(hit),
90014
90283
  payment: null
90015
90284
  };
90016
90285
  }
90017
90286
  function healthOf(listing) {
90287
+ const health = listingHealthSchema.optional().catch(void 0).parse(listing.health);
90018
90288
  return {
90289
+ ...health === void 0 ? {} : { health },
90019
90290
  ...listing.liveness === void 0 ? {} : { liveness: listing.liveness },
90020
90291
  ...listing.conformance === void 0 ? {} : { conformance: listing.conformance },
90021
90292
  ...listing.identity === void 0 ? {} : { identity: listing.identity }
@@ -90034,6 +90305,160 @@ function inspectionCacheKey(input2) {
90034
90305
  return JSON.stringify([input2.id, input2.endpoint ?? null]);
90035
90306
  }
90036
90307
 
90308
+ // ../mcp/src/actions/hints.ts
90309
+ function searchHints(page, options) {
90310
+ const hints = [];
90311
+ const apis = page.items.filter((hit) => hit.kind === "api");
90312
+ const payable = apis.find(
90313
+ (hit) => hit.action.type === "invoke_api" && hit.execution.payable !== false
90314
+ );
90315
+ if (payable) {
90316
+ hints.push(
90317
+ `Inspect before paying: ${renderAction(options.surface, "inspect", { id: payable.ref })}`
90318
+ );
90319
+ }
90320
+ hints.push(
90321
+ ...apis.flatMap(
90322
+ (hit) => (hit.alternatives ?? []).map((alternative) => {
90323
+ const reason = alternative.reason === "cheaper" ? "cheaper healthy" : "healthier";
90324
+ return `${hit.ref} has a ${reason} alternative: ${alternative.ref}`;
90325
+ })
90326
+ ).slice(0, 2)
90327
+ );
90328
+ const hiddenOutage = page.totals?.hiddenOutage ?? 0;
90329
+ if (options.includeOutage !== true && hiddenOutage > 0) {
90330
+ const count = hiddenOutage === 1 ? "1 listing in outage is" : `${hiddenOutage} listings in outage are`;
90331
+ hints.push(
90332
+ options.surface === "cli" ? `${count} hidden; add --include-outage to show them.` : `${count} hidden; call with includeOutage: true to show them.`
90333
+ );
90334
+ }
90335
+ if (page.items.length === 0) {
90336
+ hints.push(
90337
+ `Broaden your search with: ${renderAction(options.surface, "search", { includeUnverified: true })}`
90338
+ );
90339
+ }
90340
+ return hints.slice(0, 4);
90341
+ }
90342
+ function inspectHints(result, options) {
90343
+ const hints = [];
90344
+ if (result.health?.state === "degraded" || result.health?.state === "outage") {
90345
+ hints.push(
90346
+ 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 })}`
90347
+ );
90348
+ }
90349
+ if (typeof result.payment?.protocol === "string") {
90350
+ hints.push(
90351
+ `This payment protocol is not supported; find another API with: ${renderAction(options.surface, "search", {})}`
90352
+ );
90353
+ return hints;
90354
+ }
90355
+ const query = result.exampleRequest?.query;
90356
+ const hasQuery = query !== void 0 && Object.keys(query).length > 0;
90357
+ const queryInBody = result.method === "GET" || result.method === "HEAD";
90358
+ let body = result.exampleRequest?.body;
90359
+ if (queryInBody && hasQuery) {
90360
+ body = { ...isRecord6(body) ? body : {}, ...query };
90361
+ }
90362
+ if (body === void 0) body = requiredBody(result.requestSchema);
90363
+ if (options.surface === "agent" && !queryInBody && hasQuery) {
90364
+ hints.push(
90365
+ `This example needs URL query parameters; find another API with: ${renderAction(options.surface, "search", {})}`
90366
+ );
90367
+ } else if (options.surface === "agent" && (exactPrice(result.price) === void 0 || result.method === null)) {
90368
+ hints.push(
90369
+ `Find an API with a published price and method: ${renderAction(options.surface, "search", {})}`
90370
+ );
90371
+ } else {
90372
+ const queryUrl = !queryInBody && hasQuery ? new URL(result.url) : void 0;
90373
+ if (queryUrl) {
90374
+ for (const [key2, value] of Object.entries(query)) queryUrl.searchParams.set(key2, value);
90375
+ }
90376
+ const direct = queryUrl !== void 0 || result.network !== void 0 || /^https?:\/\//u.test(options.ref);
90377
+ hints.push(
90378
+ `Pay with: ${renderAction(
90379
+ options.surface,
90380
+ "pay",
90381
+ {
90382
+ ...queryUrl === void 0 ? { id: options.ref } : { url: queryUrl.href },
90383
+ ...!direct && result.name ? { endpoint: result.name } : {},
90384
+ ...direct ? { method: result.method ?? "<method>" } : {},
90385
+ body,
90386
+ ...queryUrl !== void 0 && result.requestContentType !== void 0 ? { contentType: result.requestContentType } : {},
90387
+ ...queryUrl !== void 0 && result.payment?.network !== void 0 ? { network: result.payment.network } : {},
90388
+ ...queryUrl !== void 0 && result.payment?.payTo !== void 0 ? { expectedPayTo: result.payment.payTo } : {}
90389
+ },
90390
+ result.price
90391
+ )}`
90392
+ );
90393
+ }
90394
+ return hints;
90395
+ }
90396
+ function payHints(result, options) {
90397
+ const hints = [];
90398
+ const settlementUnknown2 = result.outcome === "settlement_unknown";
90399
+ if (result.status >= 200 && result.status < 300 && !settlementUnknown2) {
90400
+ if (options.surface === "cli") {
90401
+ hints.push(
90402
+ `Receipt saved; review it with: vapi receipts --limit 1${result.wallet ? ` --account ${shellWord(result.wallet)}` : ""}`
90403
+ );
90404
+ } else if (options.surface === "mcp") {
90405
+ hints.push(
90406
+ `Receipt saved; review it with: receipts.list ${JSON.stringify({ limit: 1, ...result.wallet ? { wallet: result.wallet } : {} })}`
90407
+ );
90408
+ } else if (options.ref) {
90409
+ hints.push(
90410
+ `Review the request contract with: ${renderAction(options.surface, "inspect", { id: options.ref })}`
90411
+ );
90412
+ }
90413
+ return hints;
90414
+ }
90415
+ if (options.ref) {
90416
+ hints.push(
90417
+ `The provider answered ${result.status}; check the request contract with: ${renderAction(options.surface, "inspect", { id: options.ref })}`
90418
+ );
90419
+ }
90420
+ const receiptId = options.receiptId ?? result.receiptId;
90421
+ if ((result.status === 402 || settlementUnknown2) && receiptId && options.surface === "cli") {
90422
+ hints.push(`Check settlement with: vapi pay --resume ${shellWord(receiptId)}`);
90423
+ }
90424
+ return hints;
90425
+ }
90426
+ function renderAction(surface, action, args, price) {
90427
+ if (surface === "agent") {
90428
+ 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 ?? "") };
90429
+ return `call_${action} ${JSON.stringify(loopArgs)}`;
90430
+ }
90431
+ if (surface === "mcp") return `call.${action} ${JSON.stringify(args)}`;
90432
+ if (action === "search") return "vapi search --include-unverified";
90433
+ const command = `vapi ${action} ${shellWord(args.url ?? args.id ?? "")}`;
90434
+ if (action === "inspect") return command;
90435
+ const endpoint = args.endpoint ? ` --endpoint ${shellWord(args.endpoint)}` : "";
90436
+ const method = args.method ? ` --method ${shellWord(args.method)}` : "";
90437
+ const headers = args.contentType ? ` --content-type ${shellWord(args.contentType)}` : "";
90438
+ const network = args.network ? ` --network ${shellWord(args.network)}` : "";
90439
+ const payee = args.expectedPayTo ? ` --expected-pay-to ${shellWord(args.expectedPayTo)}` : "";
90440
+ return `${command}${endpoint}${method} --body ${shellQuote(args.body === "<json>" ? "<json>" : JSON.stringify(args.body) ?? "<json>")}${headers}${network}${payee}`;
90441
+ }
90442
+ function exactPrice(price) {
90443
+ if (!/^\$(0|[1-9]\d*)(?:\.\d{1,6})?$/u.test(price.trim())) return void 0;
90444
+ const value = Number(price.trim().slice(1));
90445
+ return Number.isFinite(value) ? value : void 0;
90446
+ }
90447
+ function requiredBody(schema) {
90448
+ if (!isRecord6(schema) || !Array.isArray(schema.required)) return "<json>";
90449
+ const names = schema.required.filter((name) => typeof name === "string");
90450
+ return names.length > 0 ? Object.fromEntries(names.map((name) => [name, "<value>"])) : "<json>";
90451
+ }
90452
+ function isRecord6(value) {
90453
+ return typeof value === "object" && value !== null && !Array.isArray(value);
90454
+ }
90455
+ function shellWord(value) {
90456
+ return /^[a-zA-Z0-9_./:@%-]+$/u.test(value) ? value : shellQuote(value);
90457
+ }
90458
+ function shellQuote(value) {
90459
+ return `'${value.replaceAll("'", "'\\''")}'`;
90460
+ }
90461
+
90037
90462
  // ../mcp/src/actions/call.ts
90038
90463
  var MAX_CACHED_MARKETPLACE_REFS = 200;
90039
90464
  var walletArgument = {
@@ -90042,6 +90467,7 @@ var walletArgument = {
90042
90467
  )
90043
90468
  };
90044
90469
  var callToolResultSchema = external_exports.object({
90470
+ hints: external_exports.array(external_exports.string()).max(4),
90045
90471
  wallet: external_exports.string(),
90046
90472
  status: external_exports.number().int(),
90047
90473
  body: external_exports.unknown(),
@@ -90064,6 +90490,7 @@ var callToolResultSchema = external_exports.object({
90064
90490
  }).optional()
90065
90491
  });
90066
90492
  var inspectToolResultSchema = external_exports.object({
90493
+ hints: external_exports.array(external_exports.string()).max(4),
90067
90494
  name: external_exports.string(),
90068
90495
  method: external_exports.string().nullable(),
90069
90496
  url: external_exports.url(),
@@ -90072,13 +90499,17 @@ var inspectToolResultSchema = external_exports.object({
90072
90499
  operationId: external_exports.string().optional(),
90073
90500
  requestContentType: external_exports.string().optional(),
90074
90501
  requestSchema: external_exports.unknown().optional(),
90502
+ responseSchema: discoveryEndpointSchema.shape.responseSchema,
90503
+ exampleRequest: discoveryEndpointSchema.shape.exampleRequest,
90075
90504
  responseContentType: external_exports.string().optional(),
90076
90505
  network: external_exports.string().optional(),
90077
90506
  // Registry-owned listing disclosures, mirrored from call.search.
90078
90507
  group: listingGroupSchema.optional(),
90079
90508
  fee: listingFeeSchema.optional(),
90509
+ feeDisplay: external_exports.string().optional(),
90080
90510
  verification: listingVerificationSchema,
90081
90511
  liveness: listingLivenessSchema.optional(),
90512
+ health: listingHealthSchema.optional().catch(void 0),
90082
90513
  conformance: listingConformanceSchema.optional(),
90083
90514
  identity: listingIdentitySchema.optional(),
90084
90515
  payment: discoveryEndpointSchema.shape.payment.unwrap().nullable()
@@ -90091,6 +90522,9 @@ var callSearchInputSchema = external_exports.object({
90091
90522
  cursor: external_exports.string().trim().min(1).max(4096).optional(),
90092
90523
  includeUnverified: external_exports.boolean().optional().describe(
90093
90524
  "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."
90525
+ ),
90526
+ includeOutage: external_exports.boolean().optional().describe(
90527
+ "Default results hide listings whose recent health checks show an outage; includeOutage: true shows them."
90094
90528
  )
90095
90529
  });
90096
90530
  var callInspectInputSchema = external_exports.object({
@@ -90115,11 +90549,14 @@ var callPayInputSchema = external_exports.object({
90115
90549
  "Seconds to wait for the paid response. Default: the provider's maxTimeoutSeconds, at most 120."
90116
90550
  )
90117
90551
  });
90552
+ var callSearchOutputSchema = marketplaceDiscoveryPageSchema.extend({
90553
+ hints: external_exports.array(external_exports.string()).max(4)
90554
+ });
90118
90555
  var callSearch = defineAction({
90119
90556
  name: "call.search",
90120
90557
  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.",
90121
90558
  input: callSearchInputSchema,
90122
- output: marketplaceDiscoveryPageSchema,
90559
+ output: callSearchOutputSchema,
90123
90560
  money: "none",
90124
90561
  grant: "call",
90125
90562
  async run(input2, ctx) {
@@ -90127,7 +90564,13 @@ var callSearch = defineAction({
90127
90564
  if (ctx.caller.run) {
90128
90565
  for (const item of page.items) ctx.caller.run.searchedRefs.add(item.ref);
90129
90566
  }
90130
- return page;
90567
+ return {
90568
+ ...page,
90569
+ hints: searchHints(page, {
90570
+ surface: ctx.caller.surface,
90571
+ ...input2.includeOutage === void 0 ? {} : { includeOutage: input2.includeOutage }
90572
+ })
90573
+ };
90131
90574
  }
90132
90575
  });
90133
90576
  var callInspect = defineAction({
@@ -90140,10 +90583,13 @@ var callInspect = defineAction({
90140
90583
  async run(input2, ctx) {
90141
90584
  const cacheKey2 = inspectionCacheKey(input2);
90142
90585
  const cached2 = ctx.caller.run?.inspected.get(cacheKey2);
90143
- if (cached2) return cached2;
90144
- const result = await ctx.call.inspect(input2);
90145
- ctx.caller.run?.inspected.set(cacheKey2, result);
90146
- return result;
90586
+ const result = cached2 ?? await ctx.call.inspect(input2);
90587
+ if (!cached2) ctx.caller.run?.inspected.set(cacheKey2, result);
90588
+ return {
90589
+ ...result,
90590
+ payment: result.payment ?? null,
90591
+ hints: inspectHints(result, { ref: input2.id, surface: ctx.caller.surface })
90592
+ };
90147
90593
  }
90148
90594
  });
90149
90595
  var callPay = defineAction({
@@ -90154,14 +90600,22 @@ var callPay = defineAction({
90154
90600
  money: "spends",
90155
90601
  grant: "call",
90156
90602
  async run(input2, ctx) {
90157
- return await ctx.call.pay(input2);
90603
+ const result = await ctx.call.pay(input2);
90604
+ return {
90605
+ ...result,
90606
+ hints: payHints(result, {
90607
+ surface: ctx.caller.surface,
90608
+ ...input2.id === void 0 ? {} : { ref: input2.id },
90609
+ ...input2.url === void 0 ? {} : { url: input2.url }
90610
+ })
90611
+ };
90158
90612
  }
90159
90613
  });
90160
90614
  function createCallPort(options) {
90161
90615
  const searchedMarketplaceHits = options.cacheMarketplaceHits ? /* @__PURE__ */ new Map() : void 0;
90162
90616
  return {
90163
90617
  async search(input2) {
90164
- const page = await searchMarketplace(input2, options.config, options.fetchImpl, {
90618
+ const page = await searchMarketplace2(input2, options.config, options.fetchImpl, {
90165
90619
  ...options.searchesPath === void 0 ? {} : { searchesPath: options.searchesPath },
90166
90620
  ...options.notice === void 0 ? {} : { notice: options.notice }
90167
90621
  });
@@ -90618,6 +91072,15 @@ async function checkAction(action, input2, ctx, options = {}) {
90618
91072
  }
90619
91073
  const priceUsd = exactUsdcPrice(listing.price);
90620
91074
  const profile = ctx.caller.profile;
91075
+ if (priceUsd !== null && ctx.caps !== void 0 && priceUsd > ctx.caps.perCallUsd) {
91076
+ throw new SpendCapExceededError({
91077
+ cap: "per_call",
91078
+ amountUsd: listing.price.trim().slice(1),
91079
+ limitUsd: String(ctx.caps.perCallUsd),
91080
+ ...ctx.caps.perDayUsd === void 0 ? {} : { perDayLimitUsd: ctx.caps.perDayUsd },
91081
+ wallet: profile.wallet
91082
+ });
91083
+ }
90621
91084
  const decision = decidePayment({
90622
91085
  ref,
90623
91086
  priceUsd,
@@ -90638,10 +91101,12 @@ async function checkAction(action, input2, ctx, options = {}) {
90638
91101
  }
90639
91102
  const maxUsd = Number(input2.maxPriceUsd);
90640
91103
  if (priceUsd !== null && maxUsd < priceUsd) {
90641
- return {
90642
- kind: "deny",
90643
- reason: `Requested maximum $${maxUsd} is below the listing price $${priceUsd}.`
90644
- };
91104
+ throw new SpendCapExceededError({
91105
+ cap: "max_price",
91106
+ amountUsd: listing.price.trim().slice(1),
91107
+ limitUsd: String(maxUsd),
91108
+ wallet: profile.wallet
91109
+ });
90645
91110
  }
90646
91111
  return { kind: "allow" };
90647
91112
  }
@@ -91187,6 +91652,7 @@ function createAgentRunDeps(input2) {
91187
91652
  config: input2.config,
91188
91653
  home: input2.home,
91189
91654
  chat: input2.chat,
91655
+ searchPage: call2.search,
91190
91656
  async search(query) {
91191
91657
  const page = await call2.search(query);
91192
91658
  const rows = page.items.map((hit) => ({
@@ -91235,7 +91701,10 @@ function createAgentRunDeps(input2) {
91235
91701
  network: result.payment?.network ?? listing?.payment?.network ?? listing?.network ?? ""
91236
91702
  };
91237
91703
  },
91238
- caps: { perCallUsd: Number(input2.spendCaps.perCallAtomic) / 1e6 },
91704
+ caps: {
91705
+ perCallUsd: Number(input2.spendCaps.perCallAtomic) / 1e6,
91706
+ perDayUsd: formatUsdc(BigInt(input2.spendCaps.perDayAtomic))
91707
+ },
91239
91708
  approve: input2.approve,
91240
91709
  ...input2.budget === void 0 ? {} : { budget: input2.budget },
91241
91710
  ...input2.runId === void 0 ? {} : { runId: input2.runId },
@@ -91245,6 +91714,7 @@ function createAgentRunDeps(input2) {
91245
91714
  return {
91246
91715
  ...this,
91247
91716
  search: this.search === dependencies.search ? next.search : this.search,
91717
+ searchPage: this.searchPage !== dependencies.searchPage ? this.searchPage : this.search === dependencies.search ? next.searchPage : void 0,
91248
91718
  inspect: this.inspect === dependencies.inspect ? next.inspect : this.inspect,
91249
91719
  read: this.read === dependencies.read ? next.read : this.read,
91250
91720
  pay: this.pay === dependencies.pay ? next.pay : this.pay,
@@ -91276,7 +91746,11 @@ var loopSearchResultSchema = external_exports.array(
91276
91746
  description: external_exports.string().optional()
91277
91747
  })
91278
91748
  );
91279
- var loopPayResultSchema = external_exports.object({ status: external_exports.number(), body: external_exports.unknown() });
91749
+ var loopPayResultSchema = external_exports.object({
91750
+ status: external_exports.number(),
91751
+ body: external_exports.unknown(),
91752
+ hints: external_exports.array(external_exports.string()).max(4)
91753
+ });
91280
91754
  var LOOP_BINDINGS = {
91281
91755
  "call.search": {
91282
91756
  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).",
@@ -91284,26 +91758,33 @@ var LOOP_BINDINGS = {
91284
91758
  type: "object",
91285
91759
  properties: {
91286
91760
  query: { type: "string" },
91287
- network: { type: ["string", "null"] }
91761
+ network: { type: ["string", "null"] },
91762
+ includeOutage: { type: ["boolean", "null"] }
91288
91763
  },
91289
- required: ["query", "network"],
91764
+ required: ["query", "network", "includeOutage"],
91290
91765
  additionalProperties: false
91291
91766
  },
91292
- output: loopSearchResultSchema,
91767
+ output: external_exports.union([callSearchOutputSchema, loopSearchResultSchema]),
91293
91768
  summary: "Search completed.",
91294
91769
  parseArguments(value, deps) {
91295
91770
  const args = parseObjectArgs(value);
91296
91771
  const query = requiredString2(args, "query");
91297
91772
  const network = searchNetwork(nullableString(args, "network"));
91773
+ const includeOutage = args.includeOutage;
91774
+ if (includeOutage !== void 0 && includeOutage !== null && typeof includeOutage !== "boolean") {
91775
+ throw new ToolInputError("includeOutage must be a boolean or null.");
91776
+ }
91298
91777
  return {
91299
91778
  query,
91300
91779
  ...network === null ? {} : { network },
91301
- includeUnverified: !deps.profile.verifiedOnly
91780
+ includeUnverified: !deps.profile.verifiedOnly,
91781
+ ...includeOutage == null ? {} : { includeOutage }
91302
91782
  };
91303
91783
  },
91304
91784
  async run(input2, ctx, execution) {
91305
- const search = input2;
91306
- const rows = await execution.deps.search(search);
91785
+ const search2 = input2;
91786
+ if (execution.deps.searchPage) return await callSearch.run(search2, ctx);
91787
+ const rows = await execution.deps.search(search2);
91307
91788
  for (const row of rows) ctx.caller.run?.searchedRefs.add(row.ref);
91308
91789
  return rows;
91309
91790
  }
@@ -91322,14 +91803,8 @@ var LOOP_BINDINGS = {
91322
91803
  const args = parseObjectArgs(value);
91323
91804
  return { id: requiredString2(args, "ref") };
91324
91805
  },
91325
- async run(input2, ctx, execution) {
91326
- const { id: id2 } = input2;
91327
- const cacheKey2 = inspectionCacheKey({ id: id2 });
91328
- const cached2 = ctx.caller.run?.inspected.get(cacheKey2);
91329
- if (cached2) return cached2;
91330
- const result = await execution.deps.inspect(id2);
91331
- ctx.caller.run?.inspected.set(cacheKey2, result);
91332
- return result;
91806
+ async run(input2, ctx) {
91807
+ return await callInspect.run(input2, ctx);
91333
91808
  }
91334
91809
  },
91335
91810
  "call.pay": {
@@ -91374,7 +91849,8 @@ var LOOP_BINDINGS = {
91374
91849
  }
91375
91850
  return {
91376
91851
  status: execution.payment.status,
91377
- body: execution.payment.body
91852
+ body: execution.payment.body,
91853
+ hints: payHints(execution.payment, { ref: id2, surface: ctx.caller.surface })
91378
91854
  };
91379
91855
  }
91380
91856
  },
@@ -91524,7 +92000,8 @@ async function runAgent(task, deps) {
91524
92000
  config: deps.config,
91525
92001
  clock: deps.now ?? (() => /* @__PURE__ */ new Date()),
91526
92002
  call: {
91527
- async search() {
92003
+ async search(input2) {
92004
+ if (runDeps.searchPage) return await runDeps.searchPage(input2);
91528
92005
  throw new Error("The agent loop uses its reduced search binding.");
91529
92006
  },
91530
92007
  async inspect({ id: id2 }) {
@@ -91669,6 +92146,18 @@ ${UNTRUSTED_NOTICE}` },
91669
92146
  fatalDetail: "The local audit log could not be written."
91670
92147
  };
91671
92148
  }
92149
+ if (error61 instanceof SpendCapExceededError) {
92150
+ const ref2 = paymentRef(input2);
92151
+ const reason = callRunBudgetReason(error61, runDeps.budget) ?? callBudgetReason(error61);
92152
+ if (ref2 !== void 0 && reason !== void 0) {
92153
+ const outcome = await declineSafely(ref2, reason);
92154
+ return outcome.fatalDetail === void 0 ? {
92155
+ ...outcome,
92156
+ fatalDetail: reason,
92157
+ ...error61.cap === "run_budget" ? { fatalReason: "run_budget" } : {}
92158
+ } : outcome;
92159
+ }
92160
+ }
91672
92161
  if (error61 instanceof ActionDeclinedError) {
91673
92162
  const declinedRef = actionDeclineRef(action, input2);
91674
92163
  if (declinedRef !== void 0) {
@@ -91686,7 +92175,8 @@ ${UNTRUSTED_NOTICE}` },
91686
92175
  }
91687
92176
  const runBudgetReason = callRunBudgetReason(error61.paymentError, runDeps.budget);
91688
92177
  if (runBudgetReason !== void 0) {
91689
- return await declineSafely(ref, runBudgetReason);
92178
+ const outcome = await declineSafely(ref, runBudgetReason);
92179
+ return spendCap(error61.paymentError) === "run_budget" ? { ...outcome, fatalDetail: runBudgetReason, fatalReason: "run_budget" } : outcome;
91690
92180
  }
91691
92181
  const spendBudgetReason = callBudgetReason(error61.paymentError);
91692
92182
  if (spendBudgetReason !== void 0) {
@@ -91708,7 +92198,7 @@ ${UNTRUSTED_NOTICE}` },
91708
92198
  try {
91709
92199
  reply = await deps.chat({ model: profile.model, messages, tools, tool_choice: "auto" });
91710
92200
  } catch (error61) {
91711
- if (error61 instanceof RunBudgetError || hasErrorCode(error61, "run_budget_exceeded")) {
92201
+ if (error61 instanceof RunBudgetError || hasErrorCode(error61, "run_budget_exceeded") || spendCap(error61) === "run_budget") {
91712
92202
  return await stop("run_budget", runBudgetDetail(runDeps.budget));
91713
92203
  }
91714
92204
  if (hasErrorCode(error61, "budget_exhausted")) {
@@ -91755,7 +92245,9 @@ ${UNTRUSTED_NOTICE}` },
91755
92245
  name: call2.name,
91756
92246
  summary: toolSummary(call2.name, loopActions)
91757
92247
  });
91758
- if (outcome.fatalDetail) return await stop("error", outcome.fatalDetail);
92248
+ if (outcome.fatalDetail) {
92249
+ return await stop(outcome.fatalReason ?? "error", outcome.fatalDetail);
92250
+ }
91759
92251
  }
91760
92252
  }
91761
92253
  return await stop("max_steps");
@@ -91848,6 +92340,14 @@ function hasErrorCode(error61, code) {
91848
92340
  return typeof error61 === "object" && error61 !== null && typeof Reflect.get(error61, "code") === "string" && Reflect.get(error61, "code") === code;
91849
92341
  }
91850
92342
  function callBudgetReason(error61) {
92343
+ const cap = spendCap(error61);
92344
+ if (cap !== void 0) {
92345
+ if (cap === "per_call") return "This wallet's per-call Call budget is exhausted.";
92346
+ if (cap === "per_day") return "This wallet's daily Call budget is exhausted.";
92347
+ if (cap === "max_price") return "This call exceeds its maximum price.";
92348
+ if (cap === "max_amount") return "This payment exceeds its maximum amount.";
92349
+ return void 0;
92350
+ }
91851
92351
  if (hasErrorCode(error61, "per_call_cap_exceeded")) {
91852
92352
  return "This wallet's per-call Call budget is exhausted.";
91853
92353
  }
@@ -91857,11 +92357,17 @@ function callBudgetReason(error61) {
91857
92357
  return void 0;
91858
92358
  }
91859
92359
  function callRunBudgetReason(error61, budget) {
91860
- if (!(error61 instanceof RunBudgetError) && !hasErrorCode(error61, "run_budget_exceeded")) {
92360
+ if (!(error61 instanceof RunBudgetError) && spendCap(error61) !== "run_budget" && !hasErrorCode(error61, "run_budget_exceeded")) {
91861
92361
  return void 0;
91862
92362
  }
91863
92363
  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.`;
91864
92364
  }
92365
+ function spendCap(error61) {
92366
+ if (error61 instanceof SpendCapExceededError) return error61.cap;
92367
+ if (!hasErrorCode(error61, "spend_cap_exceeded")) return void 0;
92368
+ const cap = Reflect.get(error61, "cap");
92369
+ return cap === "per_call" || cap === "per_day" || cap === "max_price" || cap === "max_amount" || cap === "run_budget" ? cap : void 0;
92370
+ }
91865
92371
  function runBudgetDetail(budget) {
91866
92372
  return budget === void 0 ? "The run budget is spent." : `The run budget of $${formatUsdc(budget.limitAtomic)} is spent.`;
91867
92373
  }
@@ -94701,6 +95207,106 @@ function createDocsTools(options) {
94701
95207
  };
94702
95208
  }
94703
95209
 
95210
+ // ../mcp/src/tool-presentation.ts
95211
+ var SERVER_ICONS = [
95212
+ {
95213
+ src: "https://vapinetwork.ai/branding/kit/logos/vapi-app-icon-light.png",
95214
+ mimeType: "image/png",
95215
+ sizes: ["1024x1024"],
95216
+ theme: "light"
95217
+ },
95218
+ {
95219
+ src: "https://vapinetwork.ai/branding/kit/logos/vapi-app-icon-dark.png",
95220
+ mimeType: "image/png",
95221
+ sizes: ["1024x1024"],
95222
+ theme: "dark"
95223
+ }
95224
+ ];
95225
+ var readOnly = {
95226
+ readOnlyHint: true,
95227
+ destructiveHint: false,
95228
+ idempotentHint: true,
95229
+ openWorldHint: false
95230
+ };
95231
+ var write = {
95232
+ readOnlyHint: false,
95233
+ destructiveHint: false,
95234
+ idempotentHint: false,
95235
+ openWorldHint: false
95236
+ };
95237
+ var destructive = { ...write, destructiveHint: true };
95238
+ var search = { ...readOnly, openWorldHint: true };
95239
+ var TOOL_PRESENTATION = {
95240
+ "docs.search": { title: "Search the vAPI docs", annotations: readOnly },
95241
+ "docs.read": { title: "Read a vAPI docs page", annotations: readOnly },
95242
+ "auth.link": {
95243
+ title: "Link this account to the vAPI dashboard",
95244
+ annotations: { ...write, idempotentHint: true }
95245
+ },
95246
+ "auth.status": { title: "Check the dashboard link", annotations: readOnly },
95247
+ "router.models": { title: "List Router models", annotations: readOnly },
95248
+ "router.usage": { title: "Show Router usage", annotations: readOnly },
95249
+ "router.chat": { title: "Chat through the vAPI Router", annotations: destructive },
95250
+ "router.buy": { title: "Buy Router balance", annotations: destructive },
95251
+ "tasks.search": { title: "Browse tasks", annotations: readOnly },
95252
+ "tasks.show": { title: "Show a task", annotations: readOnly },
95253
+ "tasks.post": { title: "Post a task", annotations: write },
95254
+ "tasks.propose": { title: "Propose on a task", annotations: write },
95255
+ "tasks.submit": { title: "Submit a proposal", annotations: write },
95256
+ "tasks.award": { title: "Award a task", annotations: write },
95257
+ "tasks.sign": { title: "Sign a task step", annotations: destructive },
95258
+ "tasks.fund": { title: "Fund escrow", annotations: destructive },
95259
+ "tasks.deliver": { title: "Deliver work", annotations: write },
95260
+ "tasks.release": { title: "Release escrow", annotations: destructive },
95261
+ "tasks.refund": { title: "Refund escrow", annotations: destructive },
95262
+ "tasks.dispute": { title: "Open a dispute", annotations: destructive },
95263
+ "tasks.counter-evidence": { title: "Add counter-evidence", annotations: write },
95264
+ "tasks.resolve-unmatched": { title: "Resolve an unmatched escrow", annotations: destructive },
95265
+ "tasks.message": { title: "Message a task thread", annotations: write },
95266
+ "tasks.thread": { title: "Read a task thread", annotations: readOnly },
95267
+ "tasks.watch": { title: "Watch a task", annotations: readOnly },
95268
+ "tasks.status": { title: "Check a task's chain status", annotations: readOnly },
95269
+ "vapi.status": { title: "Show the vAPI status screen", annotations: readOnly },
95270
+ "vapi.accounts": { title: "List vAPI accounts", annotations: readOnly },
95271
+ "vapi.siblings": { title: "List sibling agents", annotations: readOnly },
95272
+ "accounts.add": { title: "Add a local account", annotations: write },
95273
+ "accounts.caps": { title: "Lower an account's spend caps", annotations: write },
95274
+ "accounts.send": { title: "Send USDC from an account", annotations: destructive },
95275
+ "call.search": { title: "Search the vAPI marketplace", annotations: search },
95276
+ search: { title: "Search the vAPI marketplace (deprecated)", annotations: search },
95277
+ "call.inspect": { title: "Inspect a Call listing", annotations: readOnly },
95278
+ inspect: { title: "Inspect a Call listing (deprecated)", annotations: readOnly },
95279
+ "call.pay": { title: "Pay an x402 API", annotations: destructive },
95280
+ call: { title: "Pay an x402 API (deprecated)", annotations: destructive },
95281
+ "call.read": { title: "Read a paid origin", annotations: readOnly },
95282
+ "wallet.address": { title: "Show the account address", annotations: readOnly },
95283
+ "wallet.balance": { title: "Show the account balance", annotations: readOnly },
95284
+ "wallet.accounts": { title: "Show the account's addresses", annotations: readOnly },
95285
+ "wallet.list": { title: "List local accounts", annotations: readOnly },
95286
+ "wallet.use": { title: "Switch the active account", annotations: write },
95287
+ "wallet.fund": { title: "Fund the account", annotations: destructive },
95288
+ wallet: { title: "Show the account balance (deprecated)", annotations: readOnly },
95289
+ "receipts.list": { title: "List payment receipts", annotations: readOnly },
95290
+ "receipts.stats": { title: "Show receipt statistics", annotations: readOnly },
95291
+ "support.report": { title: "Create a local support report", annotations: write },
95292
+ "swarm.setup": { title: "Set up a swarm", annotations: write },
95293
+ "swarm.add": { title: "Add a swarm member", annotations: write },
95294
+ "swarm.leave": { title: "Leave a swarm", annotations: write },
95295
+ "swarm.fund": { title: "Fund a swarm", annotations: destructive },
95296
+ "swarm.rebalance": { title: "Rebalance a swarm", annotations: destructive },
95297
+ "swarm.status": { title: "Show swarm status", annotations: readOnly },
95298
+ "swarm.dissolve": { title: "Dissolve a swarm", annotations: destructive },
95299
+ "swarm.run": { title: "Run a swarm", annotations: destructive },
95300
+ "swarm.allocate": { title: "Allocate swarm budget", annotations: destructive },
95301
+ "swarm.delegate": { title: "Delegate a swarm task", annotations: destructive },
95302
+ "swarm.runs": { title: "List swarm runs", annotations: readOnly }
95303
+ };
95304
+ function withPresentation(tool) {
95305
+ const presentation = Object.hasOwn(TOOL_PRESENTATION, tool.name) ? TOOL_PRESENTATION[tool.name] : void 0;
95306
+ if (!presentation) throw new Error(`no presentation for tool ${tool.name}`);
95307
+ return { ...tool, ...presentation };
95308
+ }
95309
+
94704
95310
  // ../mcp/src/wallet-session.ts
94705
95311
  var WalletSession = class {
94706
95312
  constructor(options) {
@@ -94929,6 +95535,99 @@ var WalletSession = class {
94929
95535
  }
94930
95536
  };
94931
95537
 
95538
+ // ../mcp/src/views.ts
95539
+ var searchView = { view: "call-search", uri: "ui://vapi/call-search.html" };
95540
+ var inspectView = { view: "call-inspect", uri: "ui://vapi/call-inspect.html" };
95541
+ var MCP_APP_VIEWS = {
95542
+ "call.search": searchView,
95543
+ "call.inspect": inspectView,
95544
+ search: searchView,
95545
+ inspect: inspectView
95546
+ };
95547
+ var VIEW_RESOURCE_META = {
95548
+ "call-search": {
95549
+ title: "vAPI marketplace results",
95550
+ description: "Interactive list of Call listings returned by call.search."
95551
+ },
95552
+ "call-inspect": {
95553
+ title: "vAPI listing inspector",
95554
+ description: "Interactive request contract and price for one Call listing."
95555
+ }
95556
+ };
95557
+ function createViewLoader(options) {
95558
+ const origin = new URL(options.registryUrl).origin;
95559
+ const timeoutMs = options.timeoutMs ?? 2e3;
95560
+ const log = options.log ?? ((line) => process.stderr.write(`${line}
95561
+ `));
95562
+ const cache = /* @__PURE__ */ new Map();
95563
+ const inFlight = /* @__PURE__ */ new Map();
95564
+ const logged = /* @__PURE__ */ new Set();
95565
+ async function fetchHtml(view) {
95566
+ const url2 = `${origin}/mcp/apps/${view}.html`;
95567
+ const controller = new AbortController();
95568
+ let timer;
95569
+ const timedOut = new Promise((_resolve, reject) => {
95570
+ timer = setTimeout(() => {
95571
+ const error61 = new Error(`timed out after ${timeoutMs} ms`);
95572
+ reject(error61);
95573
+ controller.abort(error61);
95574
+ }, timeoutMs);
95575
+ });
95576
+ try {
95577
+ return await Promise.race([
95578
+ (async () => {
95579
+ const response = await options.fetchImpl(url2, {
95580
+ signal: controller.signal,
95581
+ redirect: "manual"
95582
+ });
95583
+ if (response.status !== 200) {
95584
+ void response.body?.cancel().catch(() => {
95585
+ });
95586
+ throw new Error(`HTTP ${response.status}`);
95587
+ }
95588
+ return await response.text();
95589
+ })(),
95590
+ timedOut
95591
+ ]);
95592
+ } catch (error61) {
95593
+ if (!logged.has(view)) {
95594
+ logged.add(view);
95595
+ const reason = (error61 instanceof Error ? error61.message : String(error61)).replace(
95596
+ /[\r\n\u2028\u2029]+/gu,
95597
+ " "
95598
+ );
95599
+ try {
95600
+ log(`vapi mcp: could not load view ${view} from ${url2}: ${reason}`);
95601
+ } catch {
95602
+ }
95603
+ }
95604
+ return void 0;
95605
+ } finally {
95606
+ if (timer !== void 0) clearTimeout(timer);
95607
+ }
95608
+ }
95609
+ function load(view) {
95610
+ const html = cache.get(view);
95611
+ if (html !== void 0) return Promise.resolve(html);
95612
+ const pending = inFlight.get(view);
95613
+ if (pending) return pending;
95614
+ const request = fetchHtml(view).then((html2) => {
95615
+ if (html2 !== void 0) cache.set(view, html2);
95616
+ return html2;
95617
+ }).finally(() => inFlight.delete(view));
95618
+ inFlight.set(view, request);
95619
+ return request;
95620
+ }
95621
+ return {
95622
+ origin,
95623
+ load,
95624
+ get: (view) => cache.get(view),
95625
+ async warm() {
95626
+ await Promise.allSettled([load("call-search"), load("call-inspect")]);
95627
+ }
95628
+ };
95629
+ }
95630
+
94932
95631
  // ../mcp/src/server.ts
94933
95632
  var allWalletsArgument = {
94934
95633
  allWallets: external_exports.boolean().optional().describe("Read every account's rows instead of one account's.")
@@ -95069,16 +95768,50 @@ function objectOutputSchema(schema) {
95069
95768
  const json2 = external_exports.toJSONSchema(schema);
95070
95769
  return json2.type === "object" ? { outputSchema: json2 } : {};
95071
95770
  }
95771
+ function appViewForTool(name) {
95772
+ return Object.hasOwn(MCP_APP_VIEWS, name) ? MCP_APP_VIEWS[name] : void 0;
95773
+ }
95774
+ function appViewResource({ view, uri }, origin) {
95775
+ return {
95776
+ uri,
95777
+ name: `vapi-${view}`,
95778
+ ...VIEW_RESOURCE_META[view],
95779
+ mimeType: "text/html;profile=mcp-app",
95780
+ _meta: {
95781
+ ui: {
95782
+ csp: {
95783
+ connectDomains: [origin],
95784
+ resourceDomains: ["https://assets.claude.ai", origin]
95785
+ },
95786
+ prefersBorder: view === "call-inspect"
95787
+ }
95788
+ }
95789
+ };
95790
+ }
95072
95791
  var VapiMcpServer = class {
95073
95792
  #tools = /* @__PURE__ */ new Map();
95074
95793
  #onClose;
95075
95794
  #stdio;
95795
+ #views;
95796
+ #viewSequence = 0;
95076
95797
  constructor(onClose) {
95077
95798
  this.#onClose = onClose;
95078
95799
  }
95800
+ useViews(loader) {
95801
+ this.#views = loader;
95802
+ }
95803
+ #resources() {
95804
+ const loader = this.#views;
95805
+ return loader ? [MCP_APP_VIEWS["call.search"], MCP_APP_VIEWS["call.inspect"]].map(
95806
+ (view) => appViewResource(view, loader.origin)
95807
+ ) : [];
95808
+ }
95079
95809
  registerTool(name, definition, handler) {
95810
+ const presentation = definition.title !== void 0 && definition.annotations !== void 0 ? { title: definition.title, annotations: definition.annotations } : withPresentation({ name, ...definition });
95080
95811
  const inputSchema = definition.strictInput ? external_exports.strictObject(definition.inputSchema) : external_exports.object(definition.inputSchema);
95081
95812
  this.#tools.set(name, {
95813
+ title: presentation.title,
95814
+ annotations: presentation.annotations,
95082
95815
  ...definition.description ? { description: definition.description } : {},
95083
95816
  ...definition.deprecatedReplacement ? { deprecatedReplacement: definition.deprecatedReplacement } : {},
95084
95817
  inputSchema,
@@ -95088,12 +95821,19 @@ var VapiMcpServer = class {
95088
95821
  }
95089
95822
  async listTools() {
95090
95823
  return {
95091
- tools: [...this.#tools].map(([name, tool]) => ({
95092
- name,
95093
- ...tool.description ? { description: tool.description } : {},
95094
- inputSchema: external_exports.toJSONSchema(tool.inputSchema),
95095
- ...objectOutputSchema(tool.outputSchema)
95096
- }))
95824
+ tools: [...this.#tools].map(([name, tool]) => {
95825
+ const view = appViewForTool(name);
95826
+ const uri = view && this.#views?.get(view.view) !== void 0 ? view.uri : void 0;
95827
+ return {
95828
+ name,
95829
+ title: tool.title,
95830
+ annotations: tool.annotations,
95831
+ ...tool.description ? { description: tool.description } : {},
95832
+ inputSchema: external_exports.toJSONSchema(tool.inputSchema),
95833
+ ...objectOutputSchema(tool.outputSchema),
95834
+ ...uri === void 0 ? {} : { _meta: { ui: { resourceUri: uri }, "ui/resourceUri": uri } }
95835
+ };
95836
+ })
95097
95837
  };
95098
95838
  }
95099
95839
  async callTool(request) {
@@ -95105,7 +95845,16 @@ var VapiMcpServer = class {
95105
95845
  };
95106
95846
  }
95107
95847
  try {
95108
- const result = await tool.handler(request.arguments ?? {});
95848
+ let result = await tool.handler(request.arguments ?? {});
95849
+ if (!result.isError && appViewForTool(request.name)) {
95850
+ result = {
95851
+ ...result,
95852
+ structuredContent: {
95853
+ ...result.structuredContent,
95854
+ _view: { createdAt: Date.now(), seq: ++this.#viewSequence }
95855
+ }
95856
+ };
95857
+ }
95109
95858
  return tool.deprecatedReplacement ? withDeprecation(result, tool.deprecatedReplacement) : result;
95110
95859
  } catch (error61) {
95111
95860
  const result = request.name.startsWith("tasks.") ? tasksErrorResult(error61) : toolError(error61);
@@ -95137,17 +95886,44 @@ var VapiMcpServer = class {
95137
95886
  this.#write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
95138
95887
  return;
95139
95888
  }
95889
+ const response = await this.handleRequest(request);
95890
+ if (response !== void 0) this.#write(response);
95891
+ }
95892
+ async handleRequest(request) {
95140
95893
  const id2 = request.id;
95141
95894
  const method = request.method;
95142
95895
  if (typeof method !== "string" || id2 === void 0) return;
95143
95896
  try {
95144
95897
  let result;
95145
95898
  if (method === "initialize") {
95899
+ await this.#views?.warm();
95146
95900
  const params = asRecord3(request.params);
95147
95901
  result = {
95148
95902
  protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-11-25",
95149
- capabilities: { tools: {} },
95150
- serverInfo: { name: "@vapi-network/mcp", version: VAPI_CLIENT_VERSION }
95903
+ capabilities: { tools: {}, ...this.#views ? { resources: {} } : {} },
95904
+ serverInfo: {
95905
+ name: "@vapi-network/mcp",
95906
+ title: "vAPI Network",
95907
+ version: VAPI_CLIENT_VERSION,
95908
+ websiteUrl: "https://vapinetwork.ai",
95909
+ icons: SERVER_ICONS
95910
+ }
95911
+ };
95912
+ } else if (method === "resources/list") {
95913
+ result = { resources: this.#resources() };
95914
+ } else if (method === "resources/read") {
95915
+ const params = asRecord3(request.params);
95916
+ const view = Object.values(MCP_APP_VIEWS).find((view2) => view2.uri === params?.uri);
95917
+ if (!this.#views || !view) {
95918
+ return { jsonrpc: "2.0", id: id2, error: { code: -32002, message: "resource not found" } };
95919
+ }
95920
+ const html = await this.#views.load(view.view);
95921
+ if (html === void 0) throw new Error(`view ${view.view} is unavailable`);
95922
+ const resource = appViewResource(view, this.#views.origin);
95923
+ result = {
95924
+ contents: [
95925
+ { uri: resource.uri, mimeType: resource.mimeType, text: html, _meta: resource._meta }
95926
+ ]
95151
95927
  };
95152
95928
  } else if (method === "tools/list") {
95153
95929
  result = await this.listTools();
@@ -95160,20 +95936,19 @@ var VapiMcpServer = class {
95160
95936
  } else if (method === "ping") {
95161
95937
  result = {};
95162
95938
  } else {
95163
- this.#write({
95939
+ return {
95164
95940
  jsonrpc: "2.0",
95165
95941
  id: id2,
95166
95942
  error: { code: -32601, message: `Method not found: ${method}` }
95167
- });
95168
- return;
95943
+ };
95169
95944
  }
95170
- this.#write({ jsonrpc: "2.0", id: id2, result });
95945
+ return { jsonrpc: "2.0", id: id2, result };
95171
95946
  } catch (error61) {
95172
- this.#write({
95947
+ return {
95173
95948
  jsonrpc: "2.0",
95174
95949
  id: id2,
95175
95950
  error: { code: -32603, message: error61 instanceof Error ? error61.message : String(error61) }
95176
- });
95951
+ };
95177
95952
  }
95178
95953
  }
95179
95954
  #write(message) {
@@ -95212,6 +95987,7 @@ function createVapiServer(options = {}) {
95212
95987
  });
95213
95988
  const guardedFetch2 = options.fetchImpl ?? createPublicFetch({ allowPrivateNetwork: config2.allowPrivateNetwork ?? false });
95214
95989
  const apiBase = options.agentLink?.apiBase ?? agentApiBase(config2, options.env);
95990
+ server.useViews(createViewLoader({ registryUrl: apiBase, fetchImpl: guardedFetch2 }));
95215
95991
  const auth = createAuthTools({
95216
95992
  session,
95217
95993
  secrets,
@@ -95588,7 +96364,9 @@ function createVapiServer(options = {}) {
95588
96364
  const tool = {
95589
96365
  description: action.description,
95590
96366
  inputSchema: action.input.shape,
95591
- outputSchema: action.output
96367
+ outputSchema: appViewForTool(action.name) && action.output instanceof external_exports.ZodObject ? action.output.extend({
96368
+ _view: external_exports.object({ createdAt: external_exports.number(), seq: external_exports.number().int() }).optional()
96369
+ }) : action.output
95592
96370
  };
95593
96371
  const handler = async (input2) => asStructuredToolResult(() => runAction(registeredAction, input2, actionContext));
95594
96372
  server.registerTool(action.name, tool, handler);
@@ -95962,7 +96740,8 @@ async function loadServerConfig() {
95962
96740
  return await loadConfig();
95963
96741
  }
95964
96742
  function toolError(error61) {
95965
- const text = error61 instanceof VapiCallError ? JSON.stringify(
96743
+ const spendCapError = serializeSpendCapError(error61);
96744
+ const text = spendCapError !== void 0 ? JSON.stringify(spendCapError, null, 2) : error61 instanceof VapiCallError ? JSON.stringify(
95966
96745
  {
95967
96746
  error: error61.message,
95968
96747
  code: error61.code,
@@ -95984,6 +96763,29 @@ function toolError(error61) {
95984
96763
  content: [{ type: "text", text }]
95985
96764
  };
95986
96765
  }
96766
+ function serializeSpendCapError(error61) {
96767
+ const record2 = asRecord3(error61);
96768
+ if (!(error61 instanceof SpendCapExceededError) && (record2 === void 0 || record2.code !== "spend_cap_exceeded")) {
96769
+ return void 0;
96770
+ }
96771
+ const value = error61;
96772
+ if (typeof value.amountUsd !== "string" || typeof value.limitUsd !== "string") return void 0;
96773
+ if (value.cap !== "per_call" && value.cap !== "per_day" && value.cap !== "max_price" && value.cap !== "max_amount" && value.cap !== "run_budget") {
96774
+ return void 0;
96775
+ }
96776
+ const message = typeof value.message === "string" ? value.message : "A spend cap was exceeded.";
96777
+ return {
96778
+ error: message,
96779
+ code: "spend_cap_exceeded",
96780
+ cap: value.cap,
96781
+ amountUsd: value.amountUsd,
96782
+ limitUsd: value.limitUsd,
96783
+ ...typeof value.spentUsd === "string" ? { spentUsd: value.spentUsd } : {},
96784
+ ...typeof value.wallet === "string" ? { wallet: value.wallet } : {},
96785
+ command: typeof value.command === "string" ? value.command : null,
96786
+ retryable: false
96787
+ };
96788
+ }
95987
96789
  function asRecord3(value) {
95988
96790
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
95989
96791
  }
@@ -96222,12 +97024,6 @@ function createListingsClient(options) {
96222
97024
  query: { wallet }
96223
97025
  });
96224
97026
  },
96225
- async splitters(wallet) {
96226
- return await call2("/api/call/listings/splitters", {
96227
- method: "GET",
96228
- query: { wallet }
96229
- });
96230
- },
96231
97027
  async create(input2) {
96232
97028
  return await call2("/api/call/listings", { method: "POST", body: input2 });
96233
97029
  },
@@ -96301,11 +97097,11 @@ function readProbeOperations(probe) {
96301
97097
  return isOperation(probe.endpoint) ? [probe.endpoint] : [];
96302
97098
  }
96303
97099
  function isOperation(operation) {
96304
- return isRecord6(operation) && typeof operation.name === "string" && operation.name.length > 0;
97100
+ return isRecord7(operation) && typeof operation.name === "string" && operation.name.length > 0;
96305
97101
  }
96306
97102
  function readProbeRejection(probe) {
96307
97103
  const rejection = probe.diagnostics?.rejection;
96308
- return isRecord6(rejection) ? rejection : void 0;
97104
+ return isRecord7(rejection) ? rejection : void 0;
96309
97105
  }
96310
97106
  function formatProbeSteps(probe) {
96311
97107
  const steps = probe.diagnostics?.steps;
@@ -96314,7 +97110,7 @@ function formatProbeSteps(probe) {
96314
97110
  }
96315
97111
  function formatProbeStep(step2) {
96316
97112
  if (typeof step2 === "string") return step2;
96317
- if (!isRecord6(step2)) return JSON.stringify(step2);
97113
+ if (!isRecord7(step2)) return JSON.stringify(step2);
96318
97114
  const label = asString2(step2.name) ?? asString2(step2.step) ?? asString2(step2.label) ?? "step";
96319
97115
  const outcome = asString2(step2.status) ?? asString2(step2.outcome) ?? asString2(step2.result) ?? (typeof step2.ok === "boolean" ? step2.ok ? "ok" : "failed" : void 0);
96320
97116
  const detail = asString2(step2.detail) ?? asString2(step2.message) ?? asString2(step2.description);
@@ -96380,19 +97176,19 @@ async function readJson(response) {
96380
97176
  }
96381
97177
  function readErrorMessage(body) {
96382
97178
  if (typeof body === "string") return body.trim() || void 0;
96383
- if (!isRecord6(body)) return void 0;
97179
+ if (!isRecord7(body)) return void 0;
96384
97180
  const error61 = body.error;
96385
- if (isRecord6(error61)) return asString2(error61.message) ?? asString2(error61.code);
97181
+ if (isRecord7(error61)) return asString2(error61.message) ?? asString2(error61.code);
96386
97182
  return asString2(body.message) ?? asString2(body.error) ?? asString2(body.detail);
96387
97183
  }
96388
97184
  function readErrorIssues(body) {
96389
- if (!isRecord6(body)) return [];
97185
+ if (!isRecord7(body)) return [];
96390
97186
  const candidates = [body.issues, body.errors, body.details];
96391
97187
  for (const candidate of candidates) {
96392
97188
  if (!Array.isArray(candidate)) continue;
96393
97189
  const issues = candidate.map((issue2) => {
96394
97190
  if (typeof issue2 === "string") return issue2;
96395
- if (!isRecord6(issue2)) return JSON.stringify(issue2);
97191
+ if (!isRecord7(issue2)) return JSON.stringify(issue2);
96396
97192
  const path = Array.isArray(issue2.path) ? issue2.path.join(".") : asString2(issue2.path);
96397
97193
  const message = asString2(issue2.message) ?? asString2(issue2.code) ?? JSON.stringify(issue2);
96398
97194
  return path ? `${path}: ${message}` : message;
@@ -96404,7 +97200,7 @@ function readErrorIssues(body) {
96404
97200
  function asString2(value) {
96405
97201
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
96406
97202
  }
96407
- function isRecord6(value) {
97203
+ function isRecord7(value) {
96408
97204
  return typeof value === "object" && value !== null && !Array.isArray(value);
96409
97205
  }
96410
97206
 
@@ -96439,11 +97235,11 @@ function formatIdentityLines(identity) {
96439
97235
  ];
96440
97236
  }
96441
97237
  function parseIdentityResponse(value) {
96442
- if (!isRecord7(value) || typeof value.wallet !== "string" || value.chain !== "eip155:8453") {
97238
+ if (!isRecord8(value) || typeof value.wallet !== "string" || value.chain !== "eip155:8453") {
96443
97239
  return void 0;
96444
97240
  }
96445
97241
  if (value.identity === null) return null;
96446
- if (!isRecord7(value.identity)) return void 0;
97242
+ if (!isRecord8(value.identity)) return void 0;
96447
97243
  const { identity } = value;
96448
97244
  if (typeof identity.erc8004Id !== "string" || identity.erc8004Id.length === 0 || typeof identity.agentCount !== "number" || !Number.isFinite(identity.agentCount) || typeof identity.registry !== "string") {
96449
97245
  return void 0;
@@ -96457,13 +97253,13 @@ function parseIdentityResponse(value) {
96457
97253
  };
96458
97254
  }
96459
97255
  function parseReputation(value) {
96460
- if (!isRecord7(value)) return void 0;
97256
+ if (!isRecord8(value)) return void 0;
96461
97257
  if (typeof value.score !== "number" || !Number.isFinite(value.score) || typeof value.count !== "number" || !Number.isInteger(value.count) || value.count < 0) {
96462
97258
  return void 0;
96463
97259
  }
96464
97260
  return { score: value.score, count: value.count };
96465
97261
  }
96466
- function isRecord7(value) {
97262
+ function isRecord8(value) {
96467
97263
  return typeof value === "object" && value !== null && !Array.isArray(value);
96468
97264
  }
96469
97265
 
@@ -96762,7 +97558,7 @@ async function offerDashboardLink({
96762
97558
  apiBase
96763
97559
  }) {
96764
97560
  const otherHome = resolve3(home) !== resolve3(getVapiPaths().directory);
96765
- const command = `${otherHome ? `VAPI_HOME=${shellQuote(home)} ` : ""}${apiBase === void 0 ? "" : `VAPI_REGISTRY_URL=${shellQuote(apiBase)} `}vapi login --account ${name}`;
97561
+ const command = `${otherHome ? `VAPI_HOME=${shellQuote2(home)} ` : ""}${apiBase === void 0 ? "" : `VAPI_REGISTRY_URL=${shellQuote2(apiBase)} `}vapi login --account ${name}`;
96766
97562
  const unlinked = {
96767
97563
  linked: false,
96768
97564
  next: [{ kind: "link", account: name, command }]
@@ -96825,7 +97621,7 @@ async function dashboardCommand(argv, json2, io, dependencies) {
96825
97621
  }
96826
97622
  io.stdout(json2 ? JSON.stringify({ account: target.name, url: url2, ...status, opened }) : url2);
96827
97623
  }
96828
- function shellQuote(value) {
97624
+ function shellQuote2(value) {
96829
97625
  return /^[a-zA-Z0-9_./-]+$/u.test(value) ? value : `'${value.replace(/'/gu, "'\\''")}'`;
96830
97626
  }
96831
97627
 
@@ -97298,7 +98094,7 @@ function buildRelayRestorePayload(options) {
97298
98094
  const owner = normalizedOwner(options.owner);
97299
98095
  assertDevice(options.device);
97300
98096
  assertBytes(options.key, 32);
97301
- if (!isRecord8(options.kdf)) throw new Error();
98097
+ if (!isRecord9(options.kdf)) throw new Error();
97302
98098
  const kdf = parseKdf(options.kdf);
97303
98099
  const parsed = backupPlaintextSchema.safeParse(options.vault);
97304
98100
  if (!parsed.success) throw new Error();
@@ -97320,7 +98116,7 @@ function buildRelayRestorePayload(options) {
97320
98116
  async function exportBackupSource(options) {
97321
98117
  try {
97322
98118
  assertBytes(options.vaultKey, 32);
97323
- if (!isRecord8(options.store) || typeof options.store.home !== "string" || typeof options.store.snapshot !== "function" || typeof options.store.reload !== "function") {
98119
+ if (!isRecord9(options.store) || typeof options.store.home !== "string" || typeof options.store.snapshot !== "function" || typeof options.store.reload !== "function") {
97324
98120
  throw new BackupError("backup_invalid_input");
97325
98121
  }
97326
98122
  const networks = normalizeNetworks(options.networks ?? []);
@@ -98053,7 +98849,7 @@ function prettyJson(value) {
98053
98849
  }
98054
98850
  function parseSealed(sealed) {
98055
98851
  const value = JSON.parse(sealed);
98056
- 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) {
98852
+ 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) {
98057
98853
  throw new Error();
98058
98854
  }
98059
98855
  return { epk: value.epk, nonce: value.nonce, ciphertext: value.ciphertext };
@@ -98220,13 +99016,13 @@ async function pathExists4(path) {
98220
99016
  }
98221
99017
  }
98222
99018
  function isMissingFile4(error61) {
98223
- return isErrorCode(error61, "ENOENT");
99019
+ return isErrorCode2(error61, "ENOENT");
98224
99020
  }
98225
99021
  function isExistingFile2(error61) {
98226
- return isErrorCode(error61, "EEXIST");
99022
+ return isErrorCode2(error61, "EEXIST");
98227
99023
  }
98228
- function isErrorCode(error61, code) {
98229
- return isRecord8(error61) && Reflect.get(error61, "code") === code;
99024
+ function isErrorCode2(error61, code) {
99025
+ return isRecord9(error61) && Reflect.get(error61, "code") === code;
98230
99026
  }
98231
99027
  function validateBackupSourceRelationships(source, context) {
98232
99028
  const names = /* @__PURE__ */ new Set();
@@ -98625,7 +99421,7 @@ function assertBytes(value, length) {
98625
99421
  }
98626
99422
  }
98627
99423
  function assertOwnerKey(ownerKey) {
98628
- if (!isRecord8(ownerKey) || ownerKey.kdf !== "hkdf-sha256" && ownerKey.kdf !== "scrypt") {
99424
+ if (!isRecord9(ownerKey) || ownerKey.kdf !== "hkdf-sha256" && ownerKey.kdf !== "scrypt") {
98629
99425
  throw new BackupError("backup_invalid_input");
98630
99426
  }
98631
99427
  assertBytes(ownerKey.key, 32);
@@ -98655,7 +99451,7 @@ function isIsoUtcMilliseconds(value) {
98655
99451
  return false;
98656
99452
  }
98657
99453
  }
98658
- function isRecord8(value) {
99454
+ function isRecord9(value) {
98659
99455
  return typeof value === "object" && value !== null && !Array.isArray(value);
98660
99456
  }
98661
99457
  function hasExactKeys(value, expected) {
@@ -98723,7 +99519,7 @@ async function startRelay(options) {
98723
99519
  );
98724
99520
  if (response.status !== 201) throw new Error();
98725
99521
  const value = await response.json();
98726
- 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()) {
99522
+ 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()) {
98727
99523
  throw new Error();
98728
99524
  }
98729
99525
  return { code, expiresAt: value.expiresAt, keyPair };
@@ -99020,7 +99816,7 @@ async function readRelayResult(response, options) {
99020
99816
  let plaintext;
99021
99817
  try {
99022
99818
  const result = await response.json();
99023
- if (!isRecord9(result) || !hasExactKeys2(result, RELAY_RESULT_KEYS) || typeof result.sealed !== "string") {
99819
+ if (!isRecord10(result) || !hasExactKeys2(result, RELAY_RESULT_KEYS) || typeof result.sealed !== "string") {
99024
99820
  throw new Error();
99025
99821
  }
99026
99822
  plaintext = openSealed({
@@ -99050,11 +99846,11 @@ async function readRelayResult(response, options) {
99050
99846
  }
99051
99847
  }
99052
99848
  function parseRelayPayload(value) {
99053
- if (!isRecord9(value) || !isRelayPurpose(value.purpose)) {
99849
+ if (!isRecord10(value) || !isRelayPurpose(value.purpose)) {
99054
99850
  throw new CloudBackupError("payload_invalid");
99055
99851
  }
99056
99852
  const expectedKeys = value.purpose === "restore" ? RESTORE_PAYLOAD_KEYS : ENROLL_PAYLOAD_KEYS;
99057
- 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") {
99853
+ 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") {
99058
99854
  throw new CloudBackupError("payload_invalid");
99059
99855
  }
99060
99856
  const kdf = parseKdf2(value.kdf);
@@ -99084,7 +99880,7 @@ function parseRelayPayload(value) {
99084
99880
  };
99085
99881
  }
99086
99882
  function parseStoredBackupKey(value) {
99087
- 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") {
99883
+ 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") {
99088
99884
  return void 0;
99089
99885
  }
99090
99886
  const kdf = parseKdf2(value.kdf);
@@ -99110,7 +99906,7 @@ function parseStoredState(value) {
99110
99906
  if (value === void 0) return void 0;
99111
99907
  try {
99112
99908
  const parsed = JSON.parse(value);
99113
- 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) {
99909
+ 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) {
99114
99910
  return void 0;
99115
99911
  }
99116
99912
  return { lastUploadAt: parsed.lastUploadAt, sizeBytes: parsed.sizeBytes };
@@ -99202,7 +99998,7 @@ function isRelayPurpose(value) {
99202
99998
  function isAborted(signal) {
99203
99999
  return signal?.aborted === true;
99204
100000
  }
99205
- function isRecord9(value) {
100001
+ function isRecord10(value) {
99206
100002
  return typeof value === "object" && value !== null && !Array.isArray(value);
99207
100003
  }
99208
100004
  function hasExactKeys2(value, expected) {
@@ -99400,6 +100196,7 @@ async function buyCommand(argv, json2, io, dependencies) {
99400
100196
  )
99401
100197
  );
99402
100198
  } catch (error61) {
100199
+ if (error61 instanceof SpendCapExceededError) throw error61;
99403
100200
  if (error61 instanceof SpendCapError) {
99404
100201
  throw new Error(
99405
100202
  `Router balance purchase refused by the wallet spend policy: ${error61.message} Review or change it with vapi accounts caps ${target.name}.`
@@ -99552,7 +100349,7 @@ async function readProcessStdin() {
99552
100349
  }
99553
100350
 
99554
100351
  // ../cli/src/version.ts
99555
- var CLI_VERSION = "0.9.7";
100352
+ var CLI_VERSION = "0.11.0";
99556
100353
 
99557
100354
  // ../cli/src/status.ts
99558
100355
  async function statusCommand(argv, json2, io, dependencies) {
@@ -101132,7 +101929,7 @@ async function readOffer(response) {
101132
101929
  if (raw !== null) {
101133
101930
  try {
101134
101931
  const decoded = decodePaymentRequiredHeader(raw);
101135
- if (isRecord10(decoded)) header = decoded;
101932
+ if (isRecord11(decoded)) header = decoded;
101136
101933
  else headerMalformed = true;
101137
101934
  } catch {
101138
101935
  headerMalformed = true;
@@ -101141,7 +101938,7 @@ async function readOffer(response) {
101141
101938
  let body;
101142
101939
  try {
101143
101940
  const parsed = JSON.parse(await readBoundedText(response) ?? "");
101144
- if (isRecord10(parsed) && ("accepts" in parsed || "x402Version" in parsed)) body = parsed;
101941
+ if (isRecord11(parsed) && ("accepts" in parsed || "x402Version" in parsed)) body = parsed;
101145
101942
  } catch {
101146
101943
  }
101147
101944
  const mpp = parseMppChallenge(response.headers.get("www-authenticate"));
@@ -101219,7 +102016,7 @@ function gradeOffer(offer) {
101219
102016
  };
101220
102017
  }
101221
102018
  const version5 = declared.x402Version === 1 || declared.x402Version === 2 ? declared.x402Version : null;
101222
- const accepts = (Array.isArray(declared.accepts) ? declared.accepts : []).filter(isRecord10);
102019
+ const accepts = (Array.isArray(declared.accepts) ? declared.accepts : []).filter(isRecord11);
101223
102020
  const exact = accepts.filter((accept) => accept.scheme === "exact");
101224
102021
  const fields = version5 === null ? void 0 : fieldsRule(declared, version5);
101225
102022
  const offerRules = [
@@ -101244,7 +102041,7 @@ function gradeOffer(offer) {
101244
102041
  }
101245
102042
  function advertisedExtensions(declared) {
101246
102043
  const extensions = declared.extensions;
101247
- if (!isRecord10(extensions)) return [];
102044
+ if (!isRecord11(extensions)) return [];
101248
102045
  return KNOWN_EXTENSIONS.filter((name) => Object.prototype.hasOwnProperty.call(extensions, name));
101249
102046
  }
101250
102047
  function extensionsRule(advertised) {
@@ -101367,14 +102164,14 @@ function fieldsRule(declared, version5) {
101367
102164
  if (version5 === 2) {
101368
102165
  const resource = declared.resource;
101369
102166
  if (resource === void 0) issues.push("v2_missing_resource");
101370
- else if (!isRecord10(resource) || !nonEmptyString(resource.url)) {
102167
+ else if (!isRecord11(resource) || !nonEmptyString(resource.url)) {
101371
102168
  issues.push("v2_invalid_resource");
101372
102169
  }
101373
102170
  }
101374
102171
  const accepts = declared.accepts;
101375
102172
  if (!Array.isArray(accepts) || accepts.length === 0) issues.push(`${prefix}_missing_accepts`);
101376
102173
  for (const accept of Array.isArray(accepts) ? accepts : []) {
101377
- if (!isRecord10(accept)) {
102174
+ if (!isRecord11(accept)) {
101378
102175
  issues.push(`${prefix}_invalid_accepts`);
101379
102176
  continue;
101380
102177
  }
@@ -101432,7 +102229,7 @@ function usdcIssue(accept, network) {
101432
102229
  if (typeof accept.asset !== "string" || accept.asset.toLowerCase() !== canonical.usdc.toLowerCase()) {
101433
102230
  return "asset_not_usdc";
101434
102231
  }
101435
- const extra = isRecord10(accept.extra) ? accept.extra : {};
102232
+ const extra = isRecord11(accept.extra) ? accept.extra : {};
101436
102233
  return extra.name === canonical.eip712Domain.name && extra.version === canonical.eip712Domain.version ? void 0 : "usdc_domain_mismatch";
101437
102234
  }
101438
102235
  function payToRule(exact, version5) {
@@ -101484,7 +102281,7 @@ async function discoveryRule(target, fetchImpl) {
101484
102281
  "discovery_missing"
101485
102282
  ]);
101486
102283
  }
101487
- if (!isRecord10(document)) {
102284
+ if (!isRecord11(document)) {
101488
102285
  return rule("discovery", "warn", `${url2.href} is not a JSON object.`, ["discovery_malformed"]);
101489
102286
  }
101490
102287
  const resources = Array.isArray(document.resources) ? document.resources.length : void 0;
@@ -101555,12 +102352,12 @@ function pathAdjacentOpenApiUrls(target) {
101555
102352
  }
101556
102353
  }
101557
102354
  function apiCatalogOpenApiUrls(document, catalogUrl, origin, seen) {
101558
- if (!isRecord10(document) || !Array.isArray(document.linkset)) return [];
102355
+ if (!isRecord11(document) || !Array.isArray(document.linkset)) return [];
101559
102356
  const candidates = [];
101560
102357
  for (const link3 of document.linkset) {
101561
- if (!isRecord10(link3) || !Array.isArray(link3["service-desc"])) continue;
102358
+ if (!isRecord11(link3) || !Array.isArray(link3["service-desc"])) continue;
101562
102359
  for (const description of link3["service-desc"]) {
101563
- if (!isRecord10(description) || typeof description.href !== "string") continue;
102360
+ if (!isRecord11(description) || typeof description.href !== "string") continue;
101564
102361
  let candidate;
101565
102362
  try {
101566
102363
  candidate = new URL(description.href, catalogUrl);
@@ -101579,7 +102376,7 @@ async function findOpenApiOperation(fetchImpl, candidates, pathname, method, via
101579
102376
  let firstDocument;
101580
102377
  for (const url2 of candidates) {
101581
102378
  const document = await fetchJson(fetchImpl, url2);
101582
- if (isRecord10(document) && isRecord10(document.paths)) {
102379
+ if (isRecord11(document) && isRecord11(document.paths)) {
101583
102380
  const located = {
101584
102381
  url: url2,
101585
102382
  paths: document.paths,
@@ -101600,9 +102397,9 @@ function openApiSource(document, catalogUrl) {
101600
102397
  function findOperation(paths, pathname, method) {
101601
102398
  const path = trimSlash(pathname);
101602
102399
  for (const [template, item] of Object.entries(paths)) {
101603
- if (!isRecord10(item)) continue;
102400
+ if (!isRecord11(item)) continue;
101604
102401
  const operation = item[method.toLowerCase()];
101605
- if (!isRecord10(operation)) continue;
102402
+ if (!isRecord11(operation)) continue;
101606
102403
  const pattern = trimSlash(template).split(/(\{[^/}]+\})/).map((part) => part.startsWith("{") ? "[^/]+" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("");
101607
102404
  if (new RegExp(`${pattern}$`).test(path)) return { item, operation };
101608
102405
  }
@@ -101671,7 +102468,7 @@ function trimSlash(path) {
101671
102468
  function nonEmptyString(value) {
101672
102469
  return typeof value === "string" && value.length > 0;
101673
102470
  }
101674
- function isRecord10(value) {
102471
+ function isRecord11(value) {
101675
102472
  return typeof value === "object" && value !== null && !Array.isArray(value);
101676
102473
  }
101677
102474
 
@@ -102799,7 +103596,7 @@ async function reserveRemoteAllowance(args) {
102799
103596
  );
102800
103597
  return { atomic: reserved, expiresAt: nextUtcMidnight(reservation.date) };
102801
103598
  } catch (error61) {
102802
- if (error61 instanceof Error && "code" in error61 && error61.code === "per_day_cap_exceeded") {
103599
+ if (error61 instanceof SpendCapExceededError && error61.cap === "per_day" || error61 instanceof Error && "code" in error61 && error61.code === "per_day_cap_exceeded") {
102803
103600
  throw new RemoteKeyRefusedError(
102804
103601
  "no_daily_allowance",
102805
103602
  `${args.account}'s remaining daily allowance changed while Railway was starting. Run the command again.`
@@ -103061,7 +103858,7 @@ function createLocalRuntime(options) {
103061
103858
  const { home } = options;
103062
103859
  const entry = options.entry ?? realpathSync(process.argv[1]);
103063
103860
  const execPath = options.execPath ?? process.execPath;
103064
- const spawn4 = options.spawn ?? nodeSpawn;
103861
+ const spawn5 = options.spawn ?? nodeSpawn;
103065
103862
  const kill = options.kill ?? ((pid, signal) => process.kill(pid, signal));
103066
103863
  const processCommand = options.processCommand ?? defaultProcessCommand;
103067
103864
  const ownsProcess = (handle, pid) => processCommand(pid)?.includes(runResultPath(home, handle.runId)) === true;
@@ -103084,7 +103881,7 @@ function createLocalRuntime(options) {
103084
103881
  const logFd = openLog(logPath);
103085
103882
  let child;
103086
103883
  try {
103087
- child = spawn4(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
103884
+ child = spawn5(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
103088
103885
  detached: true,
103089
103886
  stdio: ["ignore", logFd, logFd],
103090
103887
  env: {
@@ -103705,9 +104502,9 @@ async function buildAgentRunDeps(input2) {
103705
104502
  })
103706
104503
  }
103707
104504
  });
103708
- const search = runDependencies.search;
104505
+ const search2 = runDependencies.search;
103709
104506
  runDependencies.search = async (query) => {
103710
- const rows = await search(query);
104507
+ const rows = await search2(query);
103711
104508
  for (const row of rows) listingNames.set(row.ref, row.name);
103712
104509
  return rows;
103713
104510
  };
@@ -103998,13 +104795,17 @@ function usd(value, minimumDecimals = 0) {
103998
104795
  }
103999
104796
 
104000
104797
  // ../cli/src/mcp-install.ts
104798
+ import { spawn as spawn3 } from "node:child_process";
104001
104799
  import { mkdir as mkdir20, readFile as readFile28, writeFile as writeFile11 } from "node:fs/promises";
104002
104800
  import { homedir as systemHomedir } from "node:os";
104003
104801
  import { dirname as dirname14, posix, win32 as win322 } from "node:path";
104004
- var MCP_INSTALL_USAGE = "Usage: vapi mcp install <claude|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]";
104005
- var APPS = /* @__PURE__ */ new Set(["claude", "cursor", "codex"]);
104802
+ var MCP_INSTALL_USAGE = "Usage: vapi mcp install <claude-code|claude-desktop|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]";
104803
+ var APPS = /* @__PURE__ */ new Set(["claude-code", "claude-desktop", "cursor", "codex"]);
104804
+ var CLAUDE_ALIAS_NOTICE = "vapi mcp install claude installs into Claude Desktop; for the Claude Code CLI use: vapi mcp install claude-code";
104805
+ var CLAUDE_NOT_FOUND = "Claude Code's claude command was not found on PATH. Install Claude Code, or run this yourself:";
104006
104806
  var NEXT_STEP = {
104007
- claude: 'Restart Claude Desktop, then ask it: "Search vAPI for a weather API."',
104807
+ "claude-code": 'Start a new Claude Code session, then ask: "Search vAPI for a weather API."',
104808
+ "claude-desktop": 'Restart Claude Desktop, then ask it: "Search vAPI for a weather API."',
104008
104809
  cursor: 'Reload Cursor, then ask its agent: "Search vAPI for a weather API."',
104009
104810
  codex: 'Start codex in a new terminal, then ask: "Search vAPI for a weather API."'
104010
104811
  };
@@ -104045,36 +104846,44 @@ async function mcpInstallCommand(argv, json2, io, dependencies) {
104045
104846
  booleanOptions: /* @__PURE__ */ new Set(["--no-link"]),
104046
104847
  maximumPositionals: 1
104047
104848
  });
104048
- const appValue = parsed.positionals[0];
104049
- if (appValue === void 0) throw new UsageError(MCP_INSTALL_USAGE);
104849
+ const requestedApp = parsed.positionals[0];
104850
+ if (requestedApp === void 0) throw new UsageError(MCP_INSTALL_USAGE);
104851
+ const appValue = requestedApp === "claude" ? "claude-desktop" : requestedApp;
104050
104852
  if (!isMcpInstallApp(appValue)) {
104051
104853
  throw new UsageError(
104052
- `Unknown app ${JSON.stringify(appValue)}. Choose claude, cursor or codex.
104854
+ `Unknown app ${JSON.stringify(requestedApp)}. Choose claude-code, claude-desktop, cursor or codex.
104053
104855
  ${MCP_INSTALL_USAGE}`
104054
104856
  );
104055
104857
  }
104858
+ if (requestedApp === "claude") io.stderr(CLAUDE_ALIAS_NOTICE);
104056
104859
  const home = parsed.one("--home") ?? getVapiPaths().directory;
104057
104860
  const paths = getVapiPaths(home);
104058
104861
  const registry2 = parsed.one("--registry") ?? (await pathExists5(paths.config) ? registryBaseUrl(await readConfig(paths.config, io)) : resolveRegistryUrl());
104862
+ const offerLink = async () => {
104863
+ const name = await unlinkedDefaultAccount(home, dependencies);
104864
+ return name === void 0 ? {} : await offerDashboardLink({
104865
+ name,
104866
+ json: json2,
104867
+ noLink: parsed.has("--no-link"),
104868
+ io,
104869
+ dependencies,
104870
+ home,
104871
+ apiBase: parsed.one("--registry")
104872
+ });
104873
+ };
104874
+ const platform2 = dependencies.mcpInstall?.platform ?? process.platform;
104875
+ const entry = serverEntry(home, registry2);
104876
+ if (appValue === "claude-code") {
104877
+ return await installClaudeCode(entry, platform2, json2, io, dependencies, offerLink);
104878
+ }
104059
104879
  const target = mcpInstallTarget(appValue, {
104060
- platform: dependencies.mcpInstall?.platform ?? process.platform,
104880
+ platform: platform2,
104061
104881
  homedir: dependencies.mcpInstall?.homedir ?? systemHomedir(),
104062
104882
  cwd: dependencies.mcpInstall?.cwd ?? process.cwd(),
104063
104883
  appData: dependencies.mcpInstall?.appData ?? process.env.APPDATA
104064
104884
  });
104065
- const entry = serverEntry(home, registry2);
104066
104885
  const created = await writeMcpConfig(target, entry);
104067
- const name = await unlinkedDefaultAccount(home, dependencies);
104068
- const offerLink = (name2) => offerDashboardLink({
104069
- name: name2,
104070
- json: json2,
104071
- noLink: parsed.has("--no-link"),
104072
- io,
104073
- dependencies,
104074
- home,
104075
- apiBase: parsed.one("--registry")
104076
- });
104077
- const link3 = json2 && name !== void 0 ? await offerLink(name) : {};
104886
+ const link3 = json2 ? await offerLink() : {};
104078
104887
  output3(
104079
104888
  io,
104080
104889
  json2,
@@ -104083,8 +104892,9 @@ ${MCP_INSTALL_USAGE}`
104083
104892
  );
104084
104893
  if (!json2) {
104085
104894
  io.stdout(NEXT_STEP[appValue]);
104086
- if (name !== void 0) await offerLink(name);
104895
+ await offerLink();
104087
104896
  }
104897
+ return 0;
104088
104898
  }
104089
104899
  async function unlinkedDefaultAccount(home, dependencies) {
104090
104900
  try {
@@ -104098,6 +104908,131 @@ async function unlinkedDefaultAccount(home, dependencies) {
104098
104908
  }
104099
104909
  return void 0;
104100
104910
  }
104911
+ async function installClaudeCode(entry, platform2, json2, io, dependencies, offerLink) {
104912
+ const processCommand = platform2 === "win32" ? "claude.cmd" : "claude";
104913
+ const processArgs = claudeCodeArgs(entry);
104914
+ const command = platform2 === "win32" ? [escapeCmd(processCommand), ...processArgs.map(escapeCmdArgument)].join(" ") : displayCommand(processCommand, processArgs);
104915
+ let result;
104916
+ try {
104917
+ result = await (dependencies.mcpInstall?.runProcess ?? defaultMcpInstallProcess)(
104918
+ processCommand,
104919
+ processArgs
104920
+ );
104921
+ } catch (error61) {
104922
+ if (isErrorCode3(error61, "ENOENT")) {
104923
+ return claudeCodeFailure(json2, io, command, "claude_not_found", CLAUDE_NOT_FOUND);
104924
+ }
104925
+ const message = `Claude Code MCP installation failed: ${errorMessage2(error61)}`;
104926
+ return claudeCodeFailure(json2, io, command, "claude_mcp_add_failed", message);
104927
+ }
104928
+ if (result.exitCode !== 0) {
104929
+ 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}.`;
104930
+ const stderr2 = result.stderr.trim();
104931
+ const message = stderr2.length === 0 ? status : `${status} ${stderr2}`;
104932
+ return claudeCodeFailure(json2, io, command, "claude_mcp_add_failed", message, result.exitCode);
104933
+ }
104934
+ const nextStep = NEXT_STEP["claude-code"];
104935
+ const link3 = json2 ? await offerLink() : {};
104936
+ if (json2)
104937
+ io.stdout(JSON.stringify({ ...link3, app: "claude-code", installed: true, command, nextStep }));
104938
+ else {
104939
+ io.stdout(command);
104940
+ io.stdout(nextStep);
104941
+ await offerLink();
104942
+ }
104943
+ return 0;
104944
+ }
104945
+ function claudeCodeArgs(entry) {
104946
+ return [
104947
+ "mcp",
104948
+ "add",
104949
+ "--scope",
104950
+ "user",
104951
+ "vapi",
104952
+ "-e",
104953
+ `VAPI_HOME=${entry.env.VAPI_HOME}`,
104954
+ "-e",
104955
+ `VAPI_REGISTRY_URL=${entry.env.VAPI_REGISTRY_URL}`,
104956
+ "--",
104957
+ entry.command,
104958
+ ...entry.args
104959
+ ];
104960
+ }
104961
+ function claudeCodeFailure(json2, io, command, code, message, exitCode) {
104962
+ if (json2) {
104963
+ io.stdout(
104964
+ JSON.stringify({
104965
+ app: "claude-code",
104966
+ installed: false,
104967
+ command,
104968
+ error: { code, message, ...exitCode === void 0 ? {} : { exitCode } }
104969
+ })
104970
+ );
104971
+ } else if (code === "claude_not_found") {
104972
+ io.stderr(`${message}
104973
+ ${command}`);
104974
+ } else {
104975
+ io.stderr(`${command}
104976
+ ${message}`);
104977
+ }
104978
+ return 1;
104979
+ }
104980
+ function displayCommand(command, args) {
104981
+ return [command, ...args].map(shellQuote3).join(" ");
104982
+ }
104983
+ function shellQuote3(value) {
104984
+ return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
104985
+ }
104986
+ function isErrorCode3(error61, code) {
104987
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && error61.code === code;
104988
+ }
104989
+ function errorMessage2(error61) {
104990
+ return error61 instanceof Error ? error61.message : String(error61);
104991
+ }
104992
+ var defaultMcpInstallProcess = async (command, args) => {
104993
+ const batch = /\.(?:cmd|bat)$/iu.test(command);
104994
+ const executable = batch ? await windowsBatchPath(command) : command;
104995
+ const commandLine = batch ? [escapeCmd(executable), ...args.map((arg) => escapeCmdArgument(arg))].join(" ") : void 0;
104996
+ return await new Promise((resolve4, reject) => {
104997
+ const child = spawn3(
104998
+ batch ? "cmd.exe" : command,
104999
+ batch ? ["/d", "/v:off", "/s", "/c", `"${commandLine}"`] : [...args],
105000
+ {
105001
+ shell: false,
105002
+ ...batch ? { windowsVerbatimArguments: true } : {},
105003
+ stdio: ["ignore", "pipe", "pipe"],
105004
+ timeout: 6e4,
105005
+ killSignal: "SIGKILL",
105006
+ windowsHide: true
105007
+ }
105008
+ );
105009
+ let stdout = "";
105010
+ let stderr2 = "";
105011
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
105012
+ stdout += chunk;
105013
+ });
105014
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
105015
+ stderr2 += chunk;
105016
+ });
105017
+ child.once("error", reject);
105018
+ child.once("close", (exitCode) => resolve4({ exitCode, stdout, stderr: stderr2 }));
105019
+ });
105020
+ };
105021
+ async function windowsBatchPath(command) {
105022
+ const path = Object.entries(process.env).find(([key2]) => key2.toLowerCase() === "path")?.[1];
105023
+ for (const directory of ["", ...(path ?? "").split(";")]) {
105024
+ const candidate = win322.join(directory.replace(/^"|"$/gu, ""), command);
105025
+ if (await pathExists5(candidate)) return candidate;
105026
+ }
105027
+ throw Object.assign(new Error(`${command} was not found on PATH.`), { code: "ENOENT" });
105028
+ }
105029
+ function escapeCmd(value) {
105030
+ return value.replace(/[()[\]%!^"`<>&|;, *?]/gu, "^$&");
105031
+ }
105032
+ function escapeCmdArgument(value) {
105033
+ const quoted = `"${value.replace(/(\\*)"/gu, '$1$1\\"').replace(/(\\*)$/u, "$1$1")}"`;
105034
+ return escapeCmd(escapeCmd(quoted));
105035
+ }
104101
105036
  function isMcpInstallApp(value) {
104102
105037
  return APPS.has(value);
104103
105038
  }
@@ -104131,13 +105066,13 @@ function jsonConfig(path, existing, entry) {
104131
105066
  } catch {
104132
105067
  throw new Error(`${path} is not valid JSON. Fix it by hand; nothing was written.`);
104133
105068
  }
104134
- if (!isRecord11(parsed)) {
105069
+ if (!isRecord12(parsed)) {
104135
105070
  throw new Error(`${path} must contain a JSON object. Fix it by hand; nothing was written.`);
104136
105071
  }
104137
105072
  config2 = parsed;
104138
105073
  }
104139
105074
  const existingServers = config2.mcpServers;
104140
- if (existingServers !== void 0 && !isRecord11(existingServers)) {
105075
+ if (existingServers !== void 0 && !isRecord12(existingServers)) {
104141
105076
  throw new Error(
104142
105077
  `${path} has an invalid mcpServers value. Fix it by hand; nothing was written.`
104143
105078
  );
@@ -104199,7 +105134,7 @@ function tomlSeparator(contents) {
104199
105134
  function escapeToml(value) {
104200
105135
  return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
104201
105136
  }
104202
- function isRecord11(value) {
105137
+ function isRecord12(value) {
104203
105138
  return typeof value === "object" && value !== null && !Array.isArray(value);
104204
105139
  }
104205
105140
  async function readExistingFile(path) {
@@ -106827,7 +107762,7 @@ Usage:
106827
107762
  vapi docs "<question>" [--json]
106828
107763
  vapi docs search "<query>" [--json]
106829
107764
  vapi docs read <url-or-path> [--json]
106830
- vapi search [query] [--kind <kind>] [--network <caip2>] [--limit <n>] [--cursor <cursor>] [--include-unverified] [--json]
107765
+ vapi search [query] [--kind <kind>] [--network <caip2>] [--limit <n>] [--cursor <cursor>] [--include-unverified] [--include-outage] [--json]
106831
107766
  vapi inspect <id> [--endpoint <name>] [--json]
106832
107767
  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]
106833
107768
  vapi pay --resume <receipt-id> [--json]
@@ -106896,7 +107831,7 @@ Usage:
106896
107831
  vapi publish list [--json]
106897
107832
  vapi claim <origin> [--account <name>] [--json]
106898
107833
  vapi mcp [--account <name>] [--json]
106899
- vapi mcp install <claude|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]
107834
+ vapi mcp install <claude-code|claude-desktop|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]
106900
107835
  vapi serve [--json]
106901
107836
  vapi version [--json]
106902
107837
  vapi help [--json]
@@ -106923,13 +107858,13 @@ Solana listings remain searchable; inspect and pay return \`unsupported_network\
106923
107858
 
106924
107859
  \`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.
106925
107860
 
106926
- \`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.
107861
+ \`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.
106927
107862
 
106928
107863
  \`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.
106929
107864
 
106930
107865
  \`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.
106931
107866
 
106932
- 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.`;
107867
+ 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.`;
106933
107868
  var processIo = {
106934
107869
  stdout: (message) => process.stdout.write(`${message}
106935
107870
  `),
@@ -106967,6 +107902,7 @@ var ACCOUNT_OPTION2 = "--account";
106967
107902
  var WALLET_OPTION_DEPRECATION = "--wallet is now --account; --wallet keeps working for one release.";
106968
107903
  var SOLANA_VAULT_UNAVAILABLE2 = "Solana keys are not part of the device vault yet.";
106969
107904
  var INCLUDE_UNVERIFIED_OPTION = "--include-unverified";
107905
+ var INCLUDE_OUTAGE_OPTION = "--include-outage";
106970
107906
  async function openWalletStore(dependencies, home = getVapiPaths().directory) {
106971
107907
  return await WalletStore.open(home, {
106972
107908
  secrets: getSecretStore(dependencies),
@@ -107252,11 +108188,11 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
107252
108188
  break;
107253
108189
  case "mcp":
107254
108190
  if (args[1] === "install") {
107255
- await mcpInstallCommand(args.slice(2), json2, io, dependencies);
108191
+ exitCode = await mcpInstallCommand(args.slice(2), json2, io, dependencies);
107256
108192
  } else {
107257
108193
  await mcpCommand(args.slice(1), dependencies);
108194
+ exitCode = 0;
107258
108195
  }
107259
- exitCode = 0;
107260
108196
  break;
107261
108197
  case "serve":
107262
108198
  outputStub(io, json2);
@@ -107286,7 +108222,9 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
107286
108222
  ).catch(() => void 0);
107287
108223
  }
107288
108224
  if (json2) {
107289
- if (taskInvocation) {
108225
+ if (error61 instanceof SpendCapExceededError) {
108226
+ runIo.stdout(JSON.stringify({ error: error61.toJSON(), exitCode: 1 }));
108227
+ } else if (taskInvocation) {
107290
108228
  runIo.stdout(
107291
108229
  JSON.stringify({
107292
108230
  ok: false,
@@ -107672,7 +108610,7 @@ async function fundCommand2(argv, json2, io, dependencies) {
107672
108610
  async function searchCommand(argv, json2, io, dependencies) {
107673
108611
  const parsed = parseArguments(argv, {
107674
108612
  valueOptions: /* @__PURE__ */ new Set(["--kind", "--network", "--limit", "--cursor"]),
107675
- booleanOptions: /* @__PURE__ */ new Set([INCLUDE_UNVERIFIED_OPTION]),
108613
+ booleanOptions: /* @__PURE__ */ new Set([INCLUDE_UNVERIFIED_OPTION, INCLUDE_OUTAGE_OPTION]),
107676
108614
  repeatableOptions: /* @__PURE__ */ new Set(["--kind"]),
107677
108615
  maximumPositionals: 1
107678
108616
  });
@@ -107685,7 +108623,8 @@ async function searchCommand(argv, json2, io, dependencies) {
107685
108623
  ...limit === void 0 ? {} : { limit },
107686
108624
  ...parsed.one("--cursor") ? { cursor: parsed.one("--cursor") } : {},
107687
108625
  // Only the opt-in travels: `false` is the registry default.
107688
- ...parsed.has(INCLUDE_UNVERIFIED_OPTION) ? { includeUnverified: true } : {}
108626
+ ...parsed.has(INCLUDE_UNVERIFIED_OPTION) ? { includeUnverified: true } : {},
108627
+ ...parsed.has(INCLUDE_OUTAGE_OPTION) ? { includeOutage: true } : {}
107689
108628
  };
107690
108629
  const call2 = createCallPort({
107691
108630
  config: config2,
@@ -107811,12 +108750,14 @@ async function payCommand(argv, json2, io, dependencies) {
107811
108750
  cliActionContext(config2, pinPayInput(call2, input2), dependencies)
107812
108751
  );
107813
108752
  void _resolvedWallet;
108753
+ const { hints: _hints, ...humanResult } = result;
108754
+ void _hints;
107814
108755
  outputForWallet2(
107815
108756
  io,
107816
108757
  json2,
107817
108758
  wallet,
107818
108759
  result,
107819
- [...verificationNotice(result.verification), JSON.stringify(result, null, 2)].join("\n")
108760
+ [...verificationNotice(result.verification), JSON.stringify(humanResult, null, 2)].join("\n")
107820
108761
  );
107821
108762
  await (dependencies.ceiling?.drainCeilingSweeps ?? drainCeilingSweeps)(1e4).catch(
107822
108763
  () => void 0
@@ -108457,15 +109398,6 @@ async function publishListingCommand(argv, json2, io, dependencies) {
108457
109398
  }
108458
109399
  say(formatCreatedListing(listing, batch.name, payoutWallet, batch.endpoints.length));
108459
109400
  }
108460
- let splitters;
108461
- let splittersError;
108462
- if (created.length > 0) {
108463
- try {
108464
- splitters = await client.splitters(payoutWallet);
108465
- } catch (error61) {
108466
- splittersError = error61 instanceof Error ? error61.message : String(error61);
108467
- }
108468
- }
108469
109401
  const failed2 = failures.length > 0;
108470
109402
  const resumeHint = `Run the same vapi publish command with ${RESUME_OPTION} to list the rest; it skips what is already listed.`;
108471
109403
  if (json2) {
@@ -108475,8 +109407,6 @@ async function publishListingCommand(argv, json2, io, dependencies) {
108475
109407
  probe,
108476
109408
  listings: created,
108477
109409
  results,
108478
- ...splitters === void 0 ? {} : { splitters },
108479
- ...splittersError === void 0 ? {} : { splittersError },
108480
109410
  ...failed2 ? {
108481
109411
  error: [...new Set(failures.map((failure) => failure.message))].join("\n"),
108482
109412
  exitCode: 1
@@ -108486,8 +109416,12 @@ async function publishListingCommand(argv, json2, io, dependencies) {
108486
109416
  return failed2 ? 1 : 0;
108487
109417
  }
108488
109418
  if (created.length > 0) {
108489
- const slug = created.length === 1 ? listingSlug(created[0]) : void 0;
108490
- for (const line of formatSplitters(splitters, splittersError, slug, baseUrl)) io.stdout(line);
109419
+ for (const line of formatDescriptionWarnings(created[0])) io.stdout(line);
109420
+ io.stdout("vAPI Call takes no fee. Providers are paid directly.");
109421
+ io.stdout(`Set each endpoint's payTo to your payout wallet ${payoutWallet}, then run:`);
109422
+ for (const listing of created) {
109423
+ io.stdout(` vapi publish activate ${listingSlug(listing) ?? "<slug>"}`);
109424
+ }
108491
109425
  }
108492
109426
  if (!failed2) return 0;
108493
109427
  for (const message of new Set(failures.map((failure) => failure.message))) io.stderr(message);
@@ -108779,22 +109713,15 @@ function formatCreatedListing(created, name, payoutWallet, endpoints) {
108779
109713
  `Payout wallet: ${payoutWallet}`
108780
109714
  ].join("\n");
108781
109715
  }
108782
- function formatSplitters(splitters, splittersError, slug, baseUrl) {
108783
- const nextStep = `Deploy the FeeSplitter from your wallet in the console at ${listingsUrl(baseUrl, "/providers").href}, then run \`vapi publish activate ${slug ?? "<slug>"}\`.`;
108784
- if (splittersError !== void 0) {
108785
- return [`Could not read your splitters: ${splittersError}`, nextStep];
108786
- }
108787
- const states = Array.isArray(splitters?.networkStates) ? splitters.networkStates : [];
108788
- const fee = typeof splitters?.feeBp === "number" ? ` (vAPI fee ${splitters.feeBp / 100}%)` : "";
108789
- return [
108790
- `Splitters${fee}:`,
108791
- ...states.map((state) => {
108792
- const label = [state.name, state.network].filter(Boolean).join(" ");
108793
- const address4 = typeof state.splitterAddress === "string" ? state.splitterAddress : "unknown";
108794
- return ` ${label || "network"} ${address4} ${state.deployed === true ? "deployed" : "not deployed"}`;
108795
- }),
108796
- nextStep
108797
- ];
109716
+ function formatDescriptionWarnings(created) {
109717
+ const warnings = Array.isArray(created.descriptionWarnings) ? created.descriptionWarnings : [];
109718
+ const lines = warnings.flatMap((warning) => {
109719
+ if (typeof warning !== "object" || warning === null) return [];
109720
+ const { message, hint } = warning;
109721
+ if (typeof message !== "string") return [];
109722
+ return [`- ${message}${typeof hint === "string" ? ` ${hint}` : ""}`];
109723
+ });
109724
+ return lines.length === 0 ? [] : ["Description check (the listing is published either way):", ...lines];
108798
109725
  }
108799
109726
  function formatListingStatus(slug, action, result) {
108800
109727
  const status = typeof result.status === "string" ? result.status : "unknown";
@@ -109342,26 +110269,42 @@ function formatSearch(page) {
109342
110269
  verificationTag({ verification: item.verification, external: isMirroredHit(item) })
109343
110270
  ];
109344
110271
  const prefix = [...new Set(tags)].map((tag) => `[${tag}] `).join("");
110272
+ const health = item.kind === "api" && item.health ? `${item.health.state}${item.health.latencyP50Ms === null ? "" : ` ${Math.round(item.health.latencyP50Ms)}ms`}` : "-";
109345
110273
  return [
109346
- `${item.ref} ${item.kind} ${prefix}${item.card.title}`,
110274
+ `${item.ref} ${item.kind} ${health} ${prefix}${item.card.title}`,
109347
110275
  ` ${item.card.summary}`,
109348
- ...item.fee ? [` Fee: ${item.fee.label}`] : []
110276
+ ...item.fee ? [` Fee: ${formatListingFee(item.fee)}`] : [],
110277
+ ...item.kind === "api" && item.alternatives ? [
110278
+ ` Alternatives: ${item.alternatives.map((alternative) => `${alternative.ref} (${alternative.reason})`).join(", ")}`
110279
+ ] : []
109349
110280
  ].join("\n");
109350
110281
  }).join("\n");
109351
110282
  }
109352
110283
  function formatInspect(result) {
110284
+ const { hints: _hints, ...humanResult } = result;
110285
+ void _hints;
109353
110286
  return [
109354
110287
  `Verification: ${verificationTag({
109355
110288
  verification: result.verification,
109356
110289
  external: result.group === "external"
109357
110290
  })}`,
109358
- ...result.fee ? [`Fee: ${result.fee.label}`] : [],
110291
+ ...result.fee ? [`Fee: ${formatListingFee(result.fee)}`] : [],
110292
+ ...result.health ? [formatHealth(result.health)] : [],
110293
+ ...result.exampleRequest ? [`Example request: ${JSON.stringify(result.exampleRequest)}`] : [],
109359
110294
  ...result.liveness ? [formatLiveness(result.liveness)] : [],
109360
110295
  ...result.conformance ? [formatConformance(result.conformance)] : [],
109361
110296
  ...result.identity ? formatIdentityLines(result.identity) : [],
109362
- JSON.stringify(result, null, 2)
110297
+ JSON.stringify(humanResult, null, 2)
109363
110298
  ].join("\n");
109364
110299
  }
110300
+ function formatHealth(health) {
110301
+ return [
110302
+ `Health: ${health.state}`,
110303
+ ...health.uptime7d === null ? [`(${health.checks7d} checks)`] : [`${(health.uptime7d * 100).toFixed(1)}% up over 7 days (${health.checks7d} checks)`],
110304
+ ...health.latencyP50Ms === null ? [] : [`p50 ${Math.round(health.latencyP50Ms)} ms`],
110305
+ ...health.latencyP95Ms === null ? [] : [`p95 ${Math.round(health.latencyP95Ms)} ms`]
110306
+ ].join(" \xB7 ");
110307
+ }
109365
110308
  function formatLiveness(liveness) {
109366
110309
  const checks = `${liveness.checks7d} check${liveness.checks7d === 1 ? "" : "s"}`;
109367
110310
  return [
@@ -109406,7 +110349,7 @@ function formatFund(address4, url2, opened) {
109406
110349
  function openInBrowser(url2) {
109407
110350
  const opener = process.platform === "darwin" ? { command: "open", args: [url2] } : process.platform === "win32" ? { command: "cmd", args: ["/c", "start", "", url2] } : { command: "xdg-open", args: [url2] };
109408
110351
  try {
109409
- const child = spawn3(opener.command, opener.args, { stdio: "ignore", detached: true });
110352
+ const child = spawn4(opener.command, opener.args, { stdio: "ignore", detached: true });
109410
110353
  child.on("error", () => void 0);
109411
110354
  child.unref();
109412
110355
  return true;
@@ -109748,7 +110691,7 @@ async function latestNotice(options, env, signal) {
109748
110691
  let cached2;
109749
110692
  try {
109750
110693
  const value = JSON.parse(await readFile30(paths.updateCheck, "utf8"));
109751
- if (isRecord12(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
110694
+ if (isRecord13(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
109752
110695
  cached2 = { checkedAt: value.checkedAt, latest: value.latest };
109753
110696
  }
109754
110697
  } catch {
@@ -109781,7 +110724,7 @@ async function latestNotice(options, env, signal) {
109781
110724
  if (!response.ok) return void 0;
109782
110725
  const body = await response.json();
109783
110726
  signal.throwIfAborted();
109784
- if (!isRecord12(body) || typeof body.version !== "string" || !parseVersion(body.version)) {
110727
+ if (!isRecord13(body) || typeof body.version !== "string" || !parseVersion(body.version)) {
109785
110728
  return void 0;
109786
110729
  }
109787
110730
  latest = body.version;
@@ -109790,7 +110733,7 @@ async function latestNotice(options, env, signal) {
109790
110733
  signal.throwIfAborted();
109791
110734
  return isNewerVersion(latest, CLI_VERSION) ? `vapi-network ${latest} is available (you have ${CLI_VERSION}). Update: npm i -g vapi-network@latest` : void 0;
109792
110735
  }
109793
- function isRecord12(value) {
110736
+ function isRecord13(value) {
109794
110737
  return typeof value === "object" && value !== null && !Array.isArray(value);
109795
110738
  }
109796
110739
  function parseVersion(version5) {
@@ -109937,7 +110880,7 @@ async function createVapiClient(options = {}) {
109937
110880
  },
109938
110881
  call: {
109939
110882
  async search(query, searchOptions = {}) {
109940
- const page = await searchMarketplace(
110883
+ const page = await searchMarketplace2(
109941
110884
  {
109942
110885
  query,
109943
110886
  ...searchOptions.network === void 0 ? {} : { network: searchOptions.network },