vapi-network 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10128,9 +10128,9 @@ __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 spawn5 } from "node:child_process";
10132
10132
  import { stat as stat16 } from "node:fs/promises";
10133
- import { join as join28 } from "node:path";
10133
+ import { join as join30 } from "node:path";
10134
10134
  import { createInterface as createInterface3 } from "node:readline/promises";
10135
10135
 
10136
10136
  // ../core/src/index.ts
@@ -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,
@@ -10197,6 +10198,7 @@ __export(src_exports, {
10197
10198
  RESTORE_GAP_LIMIT: () => RESTORE_GAP_LIMIT,
10198
10199
  ROUTER_TOPUP_TIERS: () => ROUTER_TOPUP_TIERS,
10199
10200
  RUN_ID_PATTERN: () => RUN_ID_PATTERN,
10201
+ RemoteAccountError: () => RemoteAccountError,
10200
10202
  RunBudgetError: () => RunBudgetError,
10201
10203
  SECRET_STORE_SERVICE: () => SECRET_STORE_SERVICE,
10202
10204
  SIBLINGS_DEFAULT_TIMEOUT_MS: () => SIBLINGS_DEFAULT_TIMEOUT_MS,
@@ -10214,6 +10216,7 @@ __export(src_exports, {
10214
10216
  SWARM_TREASURY_CAPS: () => SWARM_TREASURY_CAPS,
10215
10217
  SiblingsError: () => SiblingsError,
10216
10218
  SpendCapError: () => SpendCapError,
10219
+ SpendCapExceededError: () => SpendCapExceededError,
10217
10220
  SpendPolicy: () => SpendPolicy,
10218
10221
  SwarmError: () => SwarmError,
10219
10222
  SweepGasError: () => SweepGasError,
@@ -10282,6 +10285,7 @@ __export(src_exports, {
10282
10285
  createRunId: () => createRunId,
10283
10286
  createSIWxMessage: () => createSIWxMessage,
10284
10287
  createSupportReport: () => createSupportReport,
10288
+ createVault: () => createVault2,
10285
10289
  decideFunding: () => decideFunding,
10286
10290
  decideRelease: () => decideRelease,
10287
10291
  decodePaymentRequiredHeader: () => decodePaymentRequiredHeader,
@@ -10315,6 +10319,7 @@ __export(src_exports, {
10315
10319
  firstPartyProvenanceSchema: () => firstPartyProvenanceSchema,
10316
10320
  formatCeilingUsd: () => formatCeilingUsd,
10317
10321
  formatLegacyRegistryRewrites: () => formatLegacyRegistryRewrites,
10322
+ formatListingFee: () => formatListingFee,
10318
10323
  formatUsdAmount: () => formatUsdAmount,
10319
10324
  formatUsdc: () => formatUsdc,
10320
10325
  fundSwarm: () => fundSwarm,
@@ -10342,6 +10347,7 @@ __export(src_exports, {
10342
10347
  isWalletName: () => isWalletName,
10343
10348
  leaveSwarm: () => leaveSwarm,
10344
10349
  linkRouterAllowanceUsd: () => linkRouterAllowanceUsd,
10350
+ linkStates: () => linkStates,
10345
10351
  listAccounts: () => listAccounts,
10346
10352
  listAgentProfiles: () => listAgentProfiles,
10347
10353
  listServicesResponseSchema: () => listServicesResponseSchema,
@@ -10351,6 +10357,8 @@ __export(src_exports, {
10351
10357
  listingDisclosureShape: () => listingDisclosureShape,
10352
10358
  listingFeeSchema: () => listingFeeSchema,
10353
10359
  listingGroupSchema: () => listingGroupSchema,
10360
+ listingHealthSchema: () => listingHealthSchema,
10361
+ listingHealthStateSchema: () => listingHealthStateSchema,
10354
10362
  listingIdentitySchema: () => listingIdentitySchema,
10355
10363
  listingLivenessSchema: () => listingLivenessSchema,
10356
10364
  listingVerificationFieldSchema: () => listingVerificationFieldSchema,
@@ -10359,6 +10367,7 @@ __export(src_exports, {
10359
10367
  loadOrCreateDeviceKey: () => loadOrCreateDeviceKey,
10360
10368
  lockVault: () => lockVault,
10361
10369
  lowerAccountCaps: () => lowerAccountCaps,
10370
+ marketplaceAlternativeSchema: () => marketplaceAlternativeSchema,
10362
10371
  marketplaceBadgeCodeSchema: () => marketplaceBadgeCodeSchema,
10363
10372
  marketplaceBadgeSchema: () => marketplaceBadgeSchema,
10364
10373
  marketplaceDiscoveryEnvelopeSchema: () => marketplaceDiscoveryEnvelopeSchema,
@@ -10415,6 +10424,7 @@ __export(src_exports, {
10415
10424
  receiptWallet: () => receiptWallet,
10416
10425
  receiptsToCsv: () => receiptsToCsv,
10417
10426
  releaseSpend: () => releaseSpend,
10427
+ remotePaymentAccount: () => remotePaymentAccount,
10418
10428
  removeAgentProfile: () => removeAgentProfile,
10419
10429
  renameReceiptWallet: () => renameReceiptWallet,
10420
10430
  requireRpcUrl: () => requireRpcUrl,
@@ -39703,6 +39713,32 @@ var listingLivenessSchema = external_exports.looseObject({
39703
39713
  latencyP95Ms: external_exports.number().nonnegative().nullable(),
39704
39714
  checks7d: external_exports.number().int().nonnegative()
39705
39715
  });
39716
+ var LISTING_HEALTH_STATES = ["healthy", "degraded", "outage", "unknown"];
39717
+ var listingHealthStateSchema = external_exports.enum(LISTING_HEALTH_STATES).catch("unknown");
39718
+ var listingHealthSchema = external_exports.looseObject({
39719
+ state: listingHealthStateSchema,
39720
+ uptime7d: external_exports.number().min(0).max(1).nullable().catch(null),
39721
+ latencyP50Ms: external_exports.number().nonnegative().nullable().catch(null),
39722
+ latencyP95Ms: external_exports.number().nonnegative().nullable().catch(null),
39723
+ checks7d: external_exports.number().int().nonnegative().catch(0)
39724
+ });
39725
+ var marketplaceAlternativeSchema = external_exports.looseObject({
39726
+ ref: external_exports.string().trim().min(1),
39727
+ reason: external_exports.enum(["cheaper", "healthier"])
39728
+ });
39729
+ var marketplaceAlternativesSchema = external_exports.preprocess((value) => {
39730
+ if (!Array.isArray(value)) return void 0;
39731
+ const alternatives = [];
39732
+ const refs = /* @__PURE__ */ new Set();
39733
+ for (const entry of value) {
39734
+ const parsed = marketplaceAlternativeSchema.safeParse(entry);
39735
+ if (!parsed.success || refs.has(parsed.data.ref)) continue;
39736
+ refs.add(parsed.data.ref);
39737
+ alternatives.push(parsed.data);
39738
+ if (alternatives.length === 2) break;
39739
+ }
39740
+ return alternatives.length > 0 ? alternatives : void 0;
39741
+ }, external_exports.array(marketplaceAlternativeSchema).optional());
39706
39742
  var listingConformanceSchema = external_exports.looseObject({
39707
39743
  declaredVersion: external_exports.union([external_exports.literal(1), external_exports.literal(2)]).nullable(),
39708
39744
  versionConformant: external_exports.boolean(),
@@ -39734,7 +39770,8 @@ var marketplaceBadgeCodeSchema = external_exports.enum([
39734
39770
  "vapi_verified",
39735
39771
  "external_catalog",
39736
39772
  "approved_vendor",
39737
- "unverified"
39773
+ "unverified",
39774
+ "failed_calls_free"
39738
39775
  ]);
39739
39776
  var marketplaceBadgeSchema = external_exports.looseObject({
39740
39777
  code: marketplaceBadgeCodeSchema,
@@ -39775,6 +39812,8 @@ var firstPartyApiMarketplaceHitSchema = external_exports.looseObject({
39775
39812
  ...marketplaceHitBase,
39776
39813
  kind: external_exports.literal("api"),
39777
39814
  provenance: firstPartyProvenanceSchema,
39815
+ health: listingHealthSchema.optional().catch(void 0),
39816
+ alternatives: marketplaceAlternativesSchema.optional().catch(void 0),
39778
39817
  execution: external_exports.looseObject({
39779
39818
  mode: executionModeSchema
39780
39819
  }),
@@ -39784,6 +39823,8 @@ var mirroredApiMarketplaceHitSchema = external_exports.looseObject({
39784
39823
  ...marketplaceHitBase,
39785
39824
  kind: external_exports.literal("api"),
39786
39825
  provenance: external_exports.literal("indexed"),
39826
+ health: listingHealthSchema.optional().catch(void 0),
39827
+ alternatives: marketplaceAlternativesSchema.optional().catch(void 0),
39787
39828
  execution: external_exports.looseObject({
39788
39829
  mode: external_exports.literal("direct"),
39789
39830
  url: external_exports.url().max(2048).regex(/^https:\/\/(?![^/?#]*@)/),
@@ -39833,7 +39874,8 @@ var marketplaceDiscoveryInputSchema = external_exports.strictObject({
39833
39874
  network: external_exports.string().trim().min(1).max(160).optional(),
39834
39875
  cursor: external_exports.string().trim().min(1).max(4096).optional(),
39835
39876
  limit: external_exports.number().int().min(1).max(50).optional(),
39836
- includeUnverified: external_exports.boolean().optional()
39877
+ includeUnverified: external_exports.boolean().optional(),
39878
+ includeOutage: external_exports.boolean().optional()
39837
39879
  }).superRefine((input2, context) => {
39838
39880
  if (input2.kinds && new Set(input2.kinds).size !== input2.kinds.length) {
39839
39881
  context.addIssue({
@@ -39851,7 +39893,14 @@ var marketplaceDiscoveryEnvelopeSchema = external_exports.looseObject({
39851
39893
  items: external_exports.array(external_exports.unknown()),
39852
39894
  nextCursor: external_exports.string().min(1).max(4096).nullable(),
39853
39895
  unavailableKinds: external_exports.array(marketplaceKindSchema).max(MARKETPLACE_KINDS.length),
39854
- rankingVersion: external_exports.literal(MARKETPLACE_RANKING_VERSION)
39896
+ // The ranking label is informational: pinning it made every installed client
39897
+ // reject the page the day the registry re-ranked, so any label is accepted.
39898
+ rankingVersion: external_exports.string().trim().min(1).max(80),
39899
+ // `hiddenOutage` counts listings in outage the registry left out because
39900
+ // `includeOutage` was not set. Older registries send no totals at all.
39901
+ totals: external_exports.looseObject({
39902
+ hiddenOutage: external_exports.number().int().nonnegative().optional().catch(void 0)
39903
+ }).optional().catch(void 0)
39855
39904
  });
39856
39905
  var marketplaceDiscoveryPageSchema = marketplaceDiscoveryEnvelopeSchema.extend({
39857
39906
  items: external_exports.array(marketplaceHitSchema)
@@ -46403,6 +46452,11 @@ var discoveryEndpointSchema = external_exports.looseObject({
46403
46452
  operationId: external_exports.string().trim().min(1).optional(),
46404
46453
  requestContentType: external_exports.string().trim().min(1).optional(),
46405
46454
  requestSchema: external_exports.json().optional(),
46455
+ responseSchema: external_exports.json().optional().catch(void 0),
46456
+ exampleRequest: external_exports.looseObject({
46457
+ query: external_exports.record(external_exports.string(), external_exports.string()).optional().catch(void 0),
46458
+ body: external_exports.json().optional()
46459
+ }).optional().catch(void 0),
46406
46460
  responseContentType: external_exports.string().trim().min(1).optional(),
46407
46461
  pathTemplate: external_exports.string().trim().min(1).optional(),
46408
46462
  pathParameters: external_exports.array(external_exports.string().trim().min(1)).optional(),
@@ -70603,13 +70657,13 @@ async function withAccountMovementLocks(home, accounts, timeoutMs, operation) {
70603
70657
  );
70604
70658
  }
70605
70659
  async function acquireAccountMovementLocks(home, accounts, timeoutMs, operation) {
70606
- const [account, ...remaining] = accounts;
70660
+ const [account, ...remaining2] = accounts;
70607
70661
  if (account === void 0) return await operation();
70608
70662
  return await withAccountMovementLock(
70609
70663
  home,
70610
70664
  account,
70611
70665
  timeoutMs,
70612
- async () => acquireAccountMovementLocks(home, remaining, timeoutMs, operation)
70666
+ async () => acquireAccountMovementLocks(home, remaining2, timeoutMs, operation)
70613
70667
  );
70614
70668
  }
70615
70669
  async function removeStaleLock2(path) {
@@ -70682,7 +70736,7 @@ var POWERSHELL_MISSING = [
70682
70736
  ].join(" ");
70683
70737
  function secretStore(options = {}) {
70684
70738
  const platform2 = options.platform ?? process.platform;
70685
- const run = options.run ?? spawnRunner;
70739
+ const run = options.run ?? (async (file2, args, input2) => await spawnRunner(platform2, file2, args, input2));
70686
70740
  const env = options.env ?? process.env;
70687
70741
  const installed = options.installed ?? ((file2) => binaryInstalled(file2, env));
70688
70742
  if (platform2 === "darwin") return keychainStore(platform2, run);
@@ -70876,6 +70930,7 @@ function windowsDataProtectionStore(platform2, run, env, installed) {
70876
70930
  ].join("\n");
70877
70931
  const execute = async (script2) => {
70878
70932
  const result = await run(powershell, WINDOWS_POWERSHELL_ARGS, `${script2}
70933
+
70879
70934
  `);
70880
70935
  requirePowerShell(result);
70881
70936
  return result;
@@ -71048,7 +71103,7 @@ function requireSuccess(result, what) {
71048
71103
  function withoutTrailingNewline(value) {
71049
71104
  return value.replace(/\r?\n$/u, "");
71050
71105
  }
71051
- var spawnRunner = async (file2, args, input2) => await new Promise((resolve4) => {
71106
+ var spawnRunner = async (platform2, file2, args, input2) => await new Promise((resolve4) => {
71052
71107
  let stdout = "";
71053
71108
  let stderr2 = "";
71054
71109
  let settled = false;
@@ -71058,7 +71113,7 @@ var spawnRunner = async (file2, args, input2) => await new Promise((resolve4) =>
71058
71113
  resolve4(outcome);
71059
71114
  };
71060
71115
  const child = spawn(file2, [...args], {
71061
- detached: true,
71116
+ detached: platform2 !== "win32",
71062
71117
  stdio: ["pipe", "pipe", "pipe"],
71063
71118
  windowsHide: true
71064
71119
  });
@@ -72677,6 +72732,17 @@ var WalletStore = class _WalletStore {
72677
72732
  );
72678
72733
  return account?.address ?? (await readKeystoreSummary(this.pathFor(target))).address;
72679
72734
  }
72735
+ /**
72736
+ * Creates the vault without deriving an account, for apps that create every
72737
+ * account by name. Refuses when a vault already exists in this home.
72738
+ */
72739
+ async createEmptyVault() {
72740
+ if (await this.readVaultUnlocked() !== void 0) {
72741
+ throw new KeystoreError("A vault already exists in this home.");
72742
+ }
72743
+ await this.openVault({ create: true });
72744
+ this.dropVaultCache();
72745
+ }
72680
72746
  async create(name, passphrase, options = {}) {
72681
72747
  void passphrase;
72682
72748
  void options.enableSolana;
@@ -73557,11 +73623,11 @@ function accountChangeBusyError(account, command) {
73557
73623
  );
73558
73624
  }
73559
73625
  async function withAccountMutationLocks(home, accounts, command, operation) {
73560
- const [account, ...remaining] = [...new Set(accounts)].sort();
73626
+ const [account, ...remaining2] = [...new Set(accounts)].sort();
73561
73627
  if (account === void 0) return await operation();
73562
73628
  return await withFileLock(
73563
73629
  join8(home, `.account-${account}.lock`),
73564
- async () => await withAccountMutationLocks(home, remaining, command, operation),
73630
+ async () => await withAccountMutationLocks(home, remaining2, command, operation),
73565
73631
  {
73566
73632
  lockedMessage: `Account ${account} is busy with another account change. Wait for it to finish, then retry ${command}.`
73567
73633
  }
@@ -74347,12 +74413,14 @@ var ledgerFileSchema = external_exports.union([
74347
74413
  ledgerRowSchema
74348
74414
  ]);
74349
74415
  var SpendCapError = class extends Error {
74350
- constructor(code, message) {
74416
+ constructor(code, message, details) {
74351
74417
  super(message);
74352
74418
  this.code = code;
74419
+ this.details = details;
74353
74420
  this.name = "SpendCapError";
74354
74421
  }
74355
74422
  code;
74423
+ details;
74356
74424
  };
74357
74425
  function utcDateKey(now = /* @__PURE__ */ new Date()) {
74358
74426
  return now.toISOString().slice(0, 10);
@@ -74367,8 +74435,8 @@ async function escrowFundingDayRemainingAtomic(input2) {
74367
74435
  const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now);
74368
74436
  const row = rows.find((candidate) => candidate.wallet === input2.wallet);
74369
74437
  const reserved = input2.reservationId ? row?.reservations?.find((candidate) => candidate.id === input2.reservationId) : void 0;
74370
- const remaining = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
74371
- return remaining > 0n ? remaining : 0n;
74438
+ const remaining2 = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
74439
+ return remaining2 > 0n ? remaining2 : 0n;
74372
74440
  }
74373
74441
  async function taskReservedAtomic(input2) {
74374
74442
  const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now, true);
@@ -74434,7 +74502,8 @@ async function reserveSpend(amountAtomic2, caps, options) {
74434
74502
  if (amountAtomic2 > perCallAtomic) {
74435
74503
  throw new SpendCapError(
74436
74504
  "per_call_cap_exceeded",
74437
- `Payment quote ${amountAtomic2} atomic USDC exceeds the per-call cap ${perCallAtomic}. Refusing to sign.`
74505
+ `Payment quote ${amountAtomic2} atomic USDC exceeds the per-call cap ${perCallAtomic}. Refusing to sign.`,
74506
+ { amountAtomic: amountAtomic2, limitAtomic: perCallAtomic, wallet: options?.wallet }
74438
74507
  );
74439
74508
  }
74440
74509
  }
@@ -74523,7 +74592,8 @@ async function reserveSpend(amountAtomic2, caps, options) {
74523
74592
  if (nextSpent > perDayAtomic) {
74524
74593
  throw new SpendCapError(
74525
74594
  "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.`
74595
+ `${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.`,
74596
+ { amountAtomic: amountAtomic2, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
74527
74597
  );
74528
74598
  }
74529
74599
  const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes10(16).toString("hex"));
@@ -75706,13 +75776,13 @@ function splitMovementPlanAtRelayLimit(plan) {
75706
75776
  const legs = plan.legs.flatMap((leg) => {
75707
75777
  const purpose = leg.purpose ?? "send";
75708
75778
  const split2 = purpose === "sweep" || plan.reason === "send" && plan.treasury !== void 0 && leg.to === plan.treasury;
75709
- let remaining = parseUsdCents(leg.amountUsd);
75710
- if (!split2 || remaining <= maximumCents) return [leg];
75779
+ let remaining2 = parseUsdCents(leg.amountUsd);
75780
+ if (!split2 || remaining2 <= maximumCents) return [leg];
75711
75781
  const parts = [];
75712
- while (remaining > 0n) {
75713
- const cents = remaining > maximumCents ? maximumCents : remaining;
75782
+ while (remaining2 > 0n) {
75783
+ const cents = remaining2 > maximumCents ? maximumCents : remaining2;
75714
75784
  parts.push({ ...leg, amountUsd: formatUsdCents(cents) });
75715
- remaining -= cents;
75785
+ remaining2 -= cents;
75716
75786
  }
75717
75787
  return parts;
75718
75788
  });
@@ -76588,13 +76658,13 @@ async function withMovementLock(home, from16, timeoutMs, operation) {
76588
76658
  }
76589
76659
  }
76590
76660
  async function withMovementLocks(home, senders, timeoutMs, operation) {
76591
- const [sender, ...remaining] = senders;
76661
+ const [sender, ...remaining2] = senders;
76592
76662
  if (sender === void 0) return await operation();
76593
76663
  return await withMovementLock(
76594
76664
  home,
76595
76665
  sender,
76596
76666
  timeoutMs,
76597
- async () => withMovementLocks(home, remaining, timeoutMs, operation)
76667
+ async () => withMovementLocks(home, remaining2, timeoutMs, operation)
76598
76668
  );
76599
76669
  }
76600
76670
  async function assertNoPendingCeilingSweep(deps, senders) {
@@ -77401,11 +77471,11 @@ function planTargets(input2) {
77401
77471
  function splitCandidateAtRelayMaximum(candidate, relayMaxAtomic) {
77402
77472
  const maximumCents = relayMaxAtomic / 10000n;
77403
77473
  const legs = [];
77404
- let remaining = candidate.cents;
77405
- while (remaining > 0n) {
77406
- const cents = remaining > maximumCents ? maximumCents : remaining;
77474
+ let remaining2 = candidate.cents;
77475
+ while (remaining2 > 0n) {
77476
+ const cents = remaining2 > maximumCents ? maximumCents : remaining2;
77407
77477
  legs.push(allocationLeg(candidate.from, candidate.to, cents, candidate.purpose));
77408
- remaining -= cents;
77478
+ remaining2 -= cents;
77409
77479
  }
77410
77480
  return legs;
77411
77481
  }
@@ -77479,6 +77549,96 @@ function parseAtomic(value, label) {
77479
77549
  throw new Error(`Invalid ${label} atomic amount.`);
77480
77550
  }
77481
77551
 
77552
+ // ../core/src/spend-cap-exceeded.ts
77553
+ var SpendCapExceededError = class extends Error {
77554
+ name = "SpendCapExceededError";
77555
+ code = "spend_cap_exceeded";
77556
+ retryable = false;
77557
+ cap;
77558
+ amountUsd;
77559
+ limitUsd;
77560
+ spentUsd;
77561
+ wallet;
77562
+ command;
77563
+ constructor(input2) {
77564
+ const amountUsd = normalizeUsd(input2.amountUsd);
77565
+ const limitUsd = normalizeUsd(input2.limitUsd);
77566
+ const spentUsd = input2.spentUsd === void 0 ? void 0 : normalizeUsd(input2.spentUsd);
77567
+ const wallet = input2.wallet?.trim() || void 0;
77568
+ const command = input2.command === void 0 ? spendCapCommand(input2.cap, amountUsd, spentUsd, wallet, input2.perDayLimitUsd) : input2.command;
77569
+ super(
77570
+ input2.message ?? spendCapMessage(input2.cap, amountUsd, limitUsd, spentUsd, wallet, command),
77571
+ input2.cause === void 0 ? void 0 : { cause: input2.cause }
77572
+ );
77573
+ this.cap = input2.cap;
77574
+ this.amountUsd = amountUsd;
77575
+ this.limitUsd = limitUsd;
77576
+ this.spentUsd = spentUsd;
77577
+ this.wallet = wallet;
77578
+ this.command = command;
77579
+ }
77580
+ toJSON() {
77581
+ return {
77582
+ code: this.code,
77583
+ cap: this.cap,
77584
+ amountUsd: this.amountUsd,
77585
+ limitUsd: this.limitUsd,
77586
+ ...this.spentUsd === void 0 ? {} : { spentUsd: this.spentUsd },
77587
+ ...this.wallet === void 0 ? {} : { wallet: this.wallet },
77588
+ command: this.command,
77589
+ message: this.message
77590
+ };
77591
+ }
77592
+ };
77593
+ function spendCapCommand(cap, amountUsd, spentUsd, wallet, perDayLimitUsd) {
77594
+ const account = wallet ?? "<account>";
77595
+ if (cap === "per_call") {
77596
+ const scale = Math.max(fractionLength(amountUsd), fractionLength(perDayLimitUsd ?? "0"));
77597
+ const raiseDay = perDayLimitUsd !== void 0 && parseDecimal(amountUsd, scale) > parseDecimal(perDayLimitUsd, scale);
77598
+ return `vapi accounts caps ${account} --per-call ${amountUsd}${raiseDay ? ` --per-day ${amountUsd}` : ""}`;
77599
+ }
77600
+ if (cap === "per_day") {
77601
+ return `vapi accounts caps ${account} --per-day ${addUsd(spentUsd ?? "0", amountUsd)}`;
77602
+ }
77603
+ if (cap === "max_price") {
77604
+ return `--max ${amountUsd}`;
77605
+ }
77606
+ if (cap === "run_budget") {
77607
+ const budget = addUsd(spentUsd ?? "0", amountUsd);
77608
+ return `--budget ${budget}`;
77609
+ }
77610
+ return null;
77611
+ }
77612
+ function spendCapMessage(cap, amountUsd, limitUsd, spentUsd, wallet, command) {
77613
+ 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";
77614
+ const account = cap === "per_call" || cap === "per_day" ? ` of account ${wallet ?? "<account>"}` : "";
77615
+ 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}`;
77616
+ 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:";
77617
+ const action = command === null ? "" : `${guidance} ${command}`;
77618
+ return `Blocked by the ${capName}${account}: ${payment}. Nothing was signed.${action}`;
77619
+ }
77620
+ function normalizeUsd(value) {
77621
+ const trimmed = value.trim();
77622
+ if (!trimmed.includes(".")) return trimmed;
77623
+ const normalized = trimmed.replace(/0+$/u, "").replace(/\.$/u, "");
77624
+ return normalized || "0";
77625
+ }
77626
+ function addUsd(left, right) {
77627
+ const scale = Math.max(fractionLength(left), fractionLength(right));
77628
+ const factor = 10n ** BigInt(scale);
77629
+ const total = parseDecimal(left, scale) + parseDecimal(right, scale);
77630
+ const whole = total / factor;
77631
+ const fraction = (total % factor).toString().padStart(scale, "0").replace(/0+$/u, "");
77632
+ return fraction ? `${whole}.${fraction}` : whole.toString();
77633
+ }
77634
+ function fractionLength(value) {
77635
+ return value.split(".")[1]?.length ?? 0;
77636
+ }
77637
+ function parseDecimal(value, scale) {
77638
+ const [whole = "0", fraction = ""] = value.split(".");
77639
+ return BigInt(whole) * 10n ** BigInt(scale) + BigInt(fraction.padEnd(scale, "0") || "0");
77640
+ }
77641
+
77482
77642
  // ../core/src/swarm.ts
77483
77643
  import { readdir as readdir6, readFile as readFile15, stat as stat11, unlink as unlink11 } from "node:fs/promises";
77484
77644
  import { join as join12 } from "node:path";
@@ -78150,7 +78310,7 @@ function createRunBudget(args) {
78150
78310
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
78151
78311
  import { arch, platform, release } from "node:os";
78152
78312
  import { join as join13 } from "node:path";
78153
- var VAPI_CLIENT_VERSION = "0.10.0";
78313
+ var VAPI_CLIENT_VERSION = "0.12.0";
78154
78314
  async function createSupportReport(options) {
78155
78315
  const message = options.message.trim();
78156
78316
  if (!message) throw new Error("Support report message must not be empty.");
@@ -78345,8 +78505,28 @@ async function completeX402Payment(args) {
78345
78505
  }
78346
78506
  args.challenge.request.signal.throwIfAborted();
78347
78507
  if (trace) trace.capsApplied = true;
78348
- assertMaximumAtomic(quote.amountAtomic, args.maxAtomic);
78349
- assertMaxPrice(quote.amountAtomic, args.maxPriceUsd);
78508
+ try {
78509
+ assertMaximumAtomic(quote.amountAtomic, args.maxAtomic);
78510
+ } catch (error61) {
78511
+ if (args.maxAtomic !== void 0 && isErrorCode(error61, "max_price_exceeded")) {
78512
+ throw paymentCapError("max_amount", quote.amountAtomic, args.maxAtomic, args, error61);
78513
+ }
78514
+ throw error61;
78515
+ }
78516
+ try {
78517
+ assertMaxPrice(quote.amountAtomic, args.maxPriceUsd);
78518
+ } catch (error61) {
78519
+ if (args.maxPriceUsd !== void 0 && isErrorCode(error61, "max_price_exceeded")) {
78520
+ throw paymentCapError(
78521
+ "max_price",
78522
+ quote.amountAtomic,
78523
+ usdToAtomic(args.maxPriceUsd),
78524
+ args,
78525
+ error61
78526
+ );
78527
+ }
78528
+ throw error61;
78529
+ }
78350
78530
  const spendReservation = {
78351
78531
  ledgerPath: args.ledgerPath ?? getVapiPaths().ledger,
78352
78532
  now: args.now,
@@ -78355,18 +78535,42 @@ async function completeX402Payment(args) {
78355
78535
  let reservationId;
78356
78536
  let reservedOn;
78357
78537
  if (args.runBudget === void 0) {
78358
- await reserveSpend(quote.amountAtomic, args.caps, spendReservation);
78538
+ try {
78539
+ await reserveSpend(quote.amountAtomic, args.caps, spendReservation);
78540
+ } catch (error61) {
78541
+ throw walletCapError(error61, quote.amountAtomic, args);
78542
+ }
78359
78543
  } else {
78360
78544
  reservationId = args.paymentId ?? `x402_${randomBytes14(12).toString("hex")}`;
78361
- const reservation = await reserveSpend(quote.amountAtomic, args.caps, {
78362
- ...spendReservation,
78363
- reservationId
78364
- });
78545
+ let reservation;
78546
+ try {
78547
+ reservation = await reserveSpend(quote.amountAtomic, args.caps, {
78548
+ ...spendReservation,
78549
+ reservationId
78550
+ });
78551
+ } catch (error61) {
78552
+ throw walletCapError(error61, quote.amountAtomic, args);
78553
+ }
78365
78554
  reservedOn = reservation.date;
78366
78555
  try {
78367
78556
  args.runBudget.reserve(quote.amountAtomic, reservationId);
78368
78557
  } catch (error61) {
78369
- await releaseUnsentReservation(args, quote.amountAtomic, reservationId, reservedOn);
78558
+ let runSpentAtomic;
78559
+ try {
78560
+ runSpentAtomic = args.runBudget.spentAtomic();
78561
+ } finally {
78562
+ await releaseUnsentReservation(args, quote.amountAtomic, reservationId, reservedOn);
78563
+ }
78564
+ if (error61 instanceof RunBudgetError || isErrorCode(error61, "run_budget_exceeded")) {
78565
+ throw new SpendCapExceededError({
78566
+ cap: "run_budget",
78567
+ amountUsd: formatUsdc(quote.amountAtomic),
78568
+ limitUsd: formatUsdc(args.runBudget.limitAtomic),
78569
+ spentUsd: formatUsdc(runSpentAtomic),
78570
+ ...args.wallet === void 0 ? {} : { wallet: args.wallet },
78571
+ cause: error61
78572
+ });
78573
+ }
78370
78574
  throw error61;
78371
78575
  }
78372
78576
  }
@@ -78649,6 +78853,18 @@ function sanitizeThrownError(error61, secrets) {
78649
78853
  if (!(error61 instanceof Error)) return error61;
78650
78854
  const message = redactKnownSecrets(error61.message, secrets);
78651
78855
  const cause = error61.cause === void 0 ? void 0 : sanitizeThrownError(error61.cause, secrets);
78856
+ if (error61 instanceof SpendCapExceededError) {
78857
+ return new SpendCapExceededError({
78858
+ cap: error61.cap,
78859
+ amountUsd: error61.amountUsd,
78860
+ limitUsd: error61.limitUsd,
78861
+ ...error61.spentUsd === void 0 ? {} : { spentUsd: error61.spentUsd },
78862
+ ...error61.wallet === void 0 ? {} : { wallet: error61.wallet },
78863
+ command: error61.command,
78864
+ message,
78865
+ ...cause === void 0 ? {} : { cause }
78866
+ });
78867
+ }
78652
78868
  if (message === error61.message && cause === error61.cause) return error61;
78653
78869
  if (error61 instanceof X402Error) {
78654
78870
  return new X402Error(error61.code, message, cause === void 0 ? void 0 : { cause });
@@ -78750,6 +78966,43 @@ function assertMaximumAtomic(amountAtomic2, maxAtomic) {
78750
78966
  );
78751
78967
  }
78752
78968
  }
78969
+ function walletCapError(error61, amountAtomic2, args) {
78970
+ if (!(error61 instanceof SpendCapError)) return error61;
78971
+ if (error61.code === "per_call_cap_exceeded") {
78972
+ return paymentCapError(
78973
+ "per_call",
78974
+ amountAtomic2,
78975
+ error61.details?.limitAtomic ?? BigInt(args.caps.perCallAtomic),
78976
+ args,
78977
+ error61
78978
+ );
78979
+ }
78980
+ if (error61.code === "per_day_cap_exceeded") {
78981
+ return paymentCapError(
78982
+ "per_day",
78983
+ amountAtomic2,
78984
+ error61.details?.limitAtomic ?? BigInt(args.caps.perDayAtomic),
78985
+ args,
78986
+ error61,
78987
+ error61.details?.spentAtomic
78988
+ );
78989
+ }
78990
+ return error61;
78991
+ }
78992
+ function paymentCapError(cap, amountAtomic2, limitAtomic, args, cause, spentAtomic) {
78993
+ return new SpendCapExceededError({
78994
+ cap,
78995
+ amountUsd: formatUsdc(amountAtomic2),
78996
+ limitUsd: formatUsdc(limitAtomic),
78997
+ ...cap === "per_call" ? { perDayLimitUsd: formatUsdc(BigInt(args.caps.perDayAtomic)) } : {},
78998
+ ...spentAtomic === void 0 ? {} : { spentUsd: formatUsdc(spentAtomic) },
78999
+ ...args.wallet === void 0 ? {} : { wallet: args.wallet },
79000
+ cause
79001
+ });
79002
+ }
79003
+ function isErrorCode(error61, code) {
79004
+ return typeof error61 === "object" && error61 !== null && Reflect.get(error61, "code") === code;
79005
+ }
78753
79006
  function settlementUnknown(message, quote, payment, payer, receipt, cause) {
78754
79007
  return new X402PaymentError(
78755
79008
  "settlement_unknown",
@@ -78825,7 +79078,7 @@ function receiptQuote(quote) {
78825
79078
  };
78826
79079
  }
78827
79080
  function paymentErrorOutcome(error61) {
78828
- if (error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error && error61.code === "max_price_exceeded") {
79081
+ if (error61 instanceof SpendCapExceededError || error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error && error61.code === "max_price_exceeded") {
78829
79082
  return "declined_policy";
78830
79083
  }
78831
79084
  if (error61 instanceof X402PaymentError) {
@@ -78842,7 +79095,7 @@ function errorCode(error61) {
78842
79095
  return "request_failed";
78843
79096
  }
78844
79097
  function receiptSafeErrorMessage(error61) {
78845
- if (error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error || error61 instanceof X402PaymentError) {
79098
+ if (error61 instanceof SpendCapExceededError || error61 instanceof SpendCapError || error61 instanceof RunBudgetError || error61 instanceof X402Error || error61 instanceof X402PaymentError) {
78846
79099
  return error61.message;
78847
79100
  }
78848
79101
  return "The x402 request failed before it completed.";
@@ -79348,15 +79601,18 @@ function budgetExhaustedError(resetsAt, status) {
79348
79601
  );
79349
79602
  }
79350
79603
  function refillDeclinedDetail(error61) {
79604
+ if (error61 instanceof SpendCapExceededError) return `${error61.name}: ${error61.cap}`;
79351
79605
  if (error61 instanceof SpendCapError) return `${error61.name}: ${error61.code}`;
79352
- if (isRunBudgetError(error61)) return `RunBudgetError: ${error61.code}`;
79606
+ if (isRunBudgetError(error61)) {
79607
+ return error61.code === "spend_cap_exceeded" ? "SpendCapExceededError: run_budget" : `RunBudgetError: ${error61.code}`;
79608
+ }
79353
79609
  if (error61 instanceof RouterClientError) {
79354
79610
  return `${error61.name}: ${error61.code}${error61.status === void 0 ? "" : ` (${error61.status})`}`;
79355
79611
  }
79356
79612
  return "Error: Router balance refill failed.";
79357
79613
  }
79358
79614
  function isRunBudgetError(error61) {
79359
- return typeof error61 === "object" && error61 !== null && Reflect.get(error61, "code") === "run_budget_exceeded";
79615
+ 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
79616
  }
79361
79617
  function isRouterTopupTier(value) {
79362
79618
  return ROUTER_TOPUP_TIERS.some((tier) => tier === value);
@@ -79446,8 +79702,15 @@ async function ownerStake(deps) {
79446
79702
  stakeUrl: parsed.data.stakeUrl
79447
79703
  };
79448
79704
  }
79449
- async function routerCredentials(deps) {
79450
- const { routerBaseUrl, routerKey } = await routerCredentialSnapshot(deps);
79705
+ async function routerCredentials(deps, options = {}) {
79706
+ const credentials = options.funding === "balance" ? await routerBalanceCredentialSnapshot(deps) : await routerCredentialSnapshot(deps);
79707
+ if (credentials === void 0) {
79708
+ throw new RouterClientError(
79709
+ "no_router_key",
79710
+ "No Router balance key is stored for this wallet."
79711
+ );
79712
+ }
79713
+ const { routerBaseUrl, routerKey } = credentials;
79451
79714
  return { baseURL: `${routerBaseUrl}/v1`, apiKey: routerKey };
79452
79715
  }
79453
79716
  async function routerCredentialSnapshot(deps) {
@@ -82671,10 +82934,10 @@ async function waitForMilestone(client, input2) {
82671
82934
  return { reached, milestone, polls, elapsedMs: now().getTime() - started };
82672
82935
  }
82673
82936
  for (; ; ) {
82674
- const remaining = deadline - now().getTime();
82675
- if (remaining <= 0) return result(false);
82937
+ const remaining2 = deadline - now().getTime();
82938
+ if (remaining2 <= 0) return result(false);
82676
82939
  const controller = new AbortController();
82677
- const timer = setTimeout(() => controller.abort(), remaining);
82940
+ const timer = setTimeout(() => controller.abort(), remaining2);
82678
82941
  let response;
82679
82942
  polls++;
82680
82943
  try {
@@ -83338,7 +83601,7 @@ async function feeTask(input2, action) {
83338
83601
  );
83339
83602
  let approvalGranted = input2.approval !== void 0 && "granted" in input2.approval && input2.approval.granted;
83340
83603
  const checkPolicy = async (reservationId) => {
83341
- const remaining = await escrowFundingDayRemainingAtomic({
83604
+ const remaining2 = await escrowFundingDayRemainingAtomic({
83342
83605
  caps: input2.caps,
83343
83606
  ledgerPath: input2.ledgerPath,
83344
83607
  wallet: input2.wallet,
@@ -83355,13 +83618,13 @@ async function feeTask(input2, action) {
83355
83618
  const maxPerTaskAtomic = policyAtomic(input2.policy.maxPerTaskUsd);
83356
83619
  if (feeAtomic > maxPerTaskAtomic || taskReserved + feeAtomic > maxPerTaskAtomic)
83357
83620
  return { outcome: "refused", reason: "policy.perTask", money: money2, disputeFee: fee };
83358
- if (feeAtomic > remaining)
83621
+ if (feeAtomic > remaining2)
83359
83622
  return { outcome: "refused", reason: "policy.perDay", money: money2, disputeFee: fee };
83360
83623
  if (feeAtomic > policyAtomic(input2.policy.approveAboveUsd) && !approvalGranted) {
83361
83624
  if (input2.approval && "ask" in input2.approval) {
83362
83625
  approvalGranted = await input2.approval.ask({
83363
83626
  money: money2,
83364
- dayRemainingUsd: Number(formatBaseUnitsUsd(remaining))
83627
+ dayRemainingUsd: Number(formatBaseUnitsUsd(remaining2))
83365
83628
  });
83366
83629
  if (!approvalGranted) return { outcome: "declined", money: money2, disputeFee: fee };
83367
83630
  } else return { outcome: "approval_needed", money: money2, disputeFee: fee };
@@ -84805,7 +85068,10 @@ function normalizeResourceUrl(value) {
84805
85068
  async function discover(sources, query, options = {}) {
84806
85069
  const nowMs = options.nowMs ?? (() => performance.now());
84807
85070
  const startedAt = options.now ?? /* @__PURE__ */ new Date();
84808
- const searchOptions = options.includeUnverified === void 0 ? {} : { includeUnverified: options.includeUnverified };
85071
+ const searchOptions = {
85072
+ ...options.includeUnverified === void 0 ? {} : { includeUnverified: options.includeUnverified },
85073
+ ...options.includeOutage === void 0 ? {} : { includeOutage: options.includeOutage }
85074
+ };
84809
85075
  const settled = await Promise.all(
84810
85076
  sources.map(async (source) => {
84811
85077
  const started = nowMs();
@@ -85530,6 +85796,11 @@ function safeOrigin2(value) {
85530
85796
  }
85531
85797
  }
85532
85798
 
85799
+ // ../core/src/listing-fee.ts
85800
+ function formatListingFee(fee) {
85801
+ return fee.bps === 0 ? "No network fee" : `${fee.label} (${fee.bps / 100}%)`;
85802
+ }
85803
+
85533
85804
  // ../core/src/onramp.ts
85534
85805
  var ONRAMP_NETWORK = "base";
85535
85806
  var ONRAMP_FALLBACK_INSTRUCTIONS = "Send USDC on Base (eip155:8453) to this address; add a little ETH for gas if you plan to sweep.";
@@ -85578,6 +85849,54 @@ var SpendPolicy = class {
85578
85849
  }
85579
85850
  };
85580
85851
 
85852
+ // ../core/src/link-state.ts
85853
+ async function linkStates(args) {
85854
+ const origin = new URL(args.apiBase).origin;
85855
+ await args.store.reload();
85856
+ const states = /* @__PURE__ */ new Map();
85857
+ const candidates = [];
85858
+ for (const name of args.store.names()) {
85859
+ const link3 = args.store.entry(name)?.link;
85860
+ const address4 = await args.store.readAddress(name);
85861
+ const hasTokens = args.secrets.available && await args.secrets.has(agentSecretAccounts(name).tokens).catch(() => false);
85862
+ if (link3 === void 0 || new URL(link3.apiBase).origin !== origin || address4 === void 0 || !hasTokens) {
85863
+ states.set(name, "not_linked");
85864
+ continue;
85865
+ }
85866
+ states.set(name, "linked");
85867
+ candidates.push({ name, owner: getAddress(link3.owner), address: getAddress(address4) });
85868
+ }
85869
+ for (const source of candidates) {
85870
+ let result;
85871
+ try {
85872
+ result = await fetchSiblings({
85873
+ apiBase: args.apiBase,
85874
+ account: source.name,
85875
+ secrets: args.secrets,
85876
+ wallets: args.store,
85877
+ ...args.fetchImpl === void 0 ? {} : { fetchImpl: args.fetchImpl },
85878
+ ...args.now === void 0 ? {} : { now: args.now }
85879
+ });
85880
+ } catch (error61) {
85881
+ if (error61 instanceof SiblingsError && error61.code === "not_linked") {
85882
+ states.set(source.name, "revoked");
85883
+ continue;
85884
+ }
85885
+ return states;
85886
+ }
85887
+ const owner = result.owner === null ? source.owner : getAddress(result.owner);
85888
+ for (const candidate of candidates) {
85889
+ if (candidate.owner !== owner) continue;
85890
+ const sibling = result.siblings.find(
85891
+ (entry) => getAddress(entry.address) === candidate.address
85892
+ );
85893
+ states.set(candidate.name, sibling?.status === "active" ? "linked" : "revoked");
85894
+ }
85895
+ return states;
85896
+ }
85897
+ return states;
85898
+ }
85899
+
85581
85900
  // ../core/src/stats.ts
85582
85901
  var STATS_RANGES = ["24h", "7d", "30d"];
85583
85902
  var OUTCOMES = [
@@ -87897,6 +88216,37 @@ function isRecord4(value) {
87897
88216
  return typeof value === "object" && value !== null && !Array.isArray(value);
87898
88217
  }
87899
88218
 
88219
+ // ../core/src/vault-setup.ts
88220
+ import { rm as rm2 } from "node:fs/promises";
88221
+ import { join as join18 } from "node:path";
88222
+ async function createVault2(home, options) {
88223
+ if (options.password === "") {
88224
+ throw new KeystoreError("A password cannot be empty.");
88225
+ }
88226
+ const store = await WalletStore.open(home, {
88227
+ secrets: options.secrets,
88228
+ ...options.now === void 0 ? {} : { now: options.now }
88229
+ });
88230
+ const hadDeviceKey = options.password !== void 0 && await options.secrets.has(VAULT_KEY_ACCOUNT);
88231
+ await store.createEmptyVault();
88232
+ if (options.password !== void 0) {
88233
+ const path = join18(home, "vault.json");
88234
+ try {
88235
+ await protectVault({
88236
+ path,
88237
+ secrets: options.secrets,
88238
+ password: options.password
88239
+ });
88240
+ } catch (error61) {
88241
+ await Promise.allSettled([
88242
+ rm2(path, { force: true }),
88243
+ ...hadDeviceKey ? [] : [options.secrets.remove(VAULT_KEY_ACCOUNT)]
88244
+ ]);
88245
+ throw error61;
88246
+ }
88247
+ }
88248
+ }
88249
+
87900
88250
  // ../core/src/wallet.ts
87901
88251
  var LocalWallet = class {
87902
88252
  constructor(account, policy) {
@@ -87924,6 +88274,44 @@ var LocalWallet = class {
87924
88274
  }
87925
88275
  };
87926
88276
 
88277
+ // ../core/src/remote-account.ts
88278
+ var RemoteAccountError = class extends Error {
88279
+ constructor(code, message) {
88280
+ super(message);
88281
+ this.code = code;
88282
+ this.name = "RemoteAccountError";
88283
+ }
88284
+ code;
88285
+ };
88286
+ var notPermitted = (what) => new RemoteAccountError("not_permitted", `${what} is not permitted through vAPI Desktop.`);
88287
+ function remotePaymentAccount(args) {
88288
+ const base = toAccount({
88289
+ address: args.address,
88290
+ async signMessage({ message }) {
88291
+ const text = typeof message === "string" ? message : JSON.stringify(message);
88292
+ return await args.request({ kind: "message", wallet: args.wallet, message: text });
88293
+ },
88294
+ async signTransaction() {
88295
+ throw notPermitted("Raw transaction signing");
88296
+ },
88297
+ async signTypedData(typedData) {
88298
+ return await args.request({ kind: "typedData", wallet: args.wallet, typedData });
88299
+ }
88300
+ });
88301
+ const account = {
88302
+ ...base,
88303
+ publicKey: args.publicKey,
88304
+ source: "privateKey",
88305
+ async sign() {
88306
+ throw notPermitted("Hash signing");
88307
+ },
88308
+ async signAuthorization() {
88309
+ throw notPermitted("EIP-7702 authorization");
88310
+ }
88311
+ };
88312
+ return account;
88313
+ }
88314
+
87927
88315
  // ../core/src/member-bundle.ts
87928
88316
  var MEMBER_BUNDLE_MAX_BYTES = 32 * 1024;
87929
88317
  var REMOTE_BLOCKED_GRANTS = /* @__PURE__ */ new Set([
@@ -88395,7 +88783,7 @@ __export(src_exports3, {
88395
88783
  runResultPath: () => runResultPath,
88396
88784
  runSwarm: () => runSwarm,
88397
88785
  runsDirectory: () => runsDirectory,
88398
- searchMarketplace: () => searchMarketplace,
88786
+ searchMarketplace: () => searchMarketplace2,
88399
88787
  selectLead: () => selectLead,
88400
88788
  startDetachedRun: () => startDetachedRun,
88401
88789
  startDetachedSwarmRun: () => startDetachedSwarmRun,
@@ -88766,7 +89154,8 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
88766
89154
  network: input2.network,
88767
89155
  limit: input2.limit,
88768
89156
  cursor: input2.cursor,
88769
- includeUnverified: input2.includeUnverified
89157
+ includeUnverified: input2.includeUnverified,
89158
+ includeOutage: input2.includeOutage
88770
89159
  });
88771
89160
  const startedAt = options.now ?? /* @__PURE__ */ new Date();
88772
89161
  const attempts = [];
@@ -88788,6 +89177,9 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
88788
89177
  if (normalized.includeUnverified === true) {
88789
89178
  url2.searchParams.set("includeUnverified", "true");
88790
89179
  }
89180
+ if (normalized.includeOutage === true) {
89181
+ url2.searchParams.set("includeOutage", "true");
89182
+ }
88791
89183
  }
88792
89184
  });
88793
89185
  const envelope = marketplaceDiscoveryEnvelopeSchema.parse(await response.json());
@@ -88835,7 +89227,7 @@ async function resolveServiceListing(id2, config2, fetchImpl, endpointName) {
88835
89227
  }
88836
89228
  async function findMarketplaceApiByRef(ref, config2, fetchImpl) {
88837
89229
  const page = await searchMarketplace(
88838
- { query: ref, kinds: ["api"], limit: 50, includeUnverified: true },
89230
+ { query: ref, kinds: ["api"], limit: 50, includeUnverified: true, includeOutage: true },
88839
89231
  config2,
88840
89232
  fetchImpl
88841
89233
  );
@@ -88855,7 +89247,8 @@ function vapiRegistrySource(baseUrl, options = {}) {
88855
89247
  {
88856
89248
  query,
88857
89249
  kinds: ["api"],
88858
- ...searchOptions?.includeUnverified === void 0 ? {} : { includeUnverified: searchOptions.includeUnverified }
89250
+ ...searchOptions?.includeUnverified === void 0 ? {} : { includeUnverified: searchOptions.includeUnverified },
89251
+ ...searchOptions?.includeOutage === void 0 ? {} : { includeOutage: searchOptions.includeOutage }
88859
89252
  },
88860
89253
  config2,
88861
89254
  fetchImpl
@@ -88897,7 +89290,7 @@ function vapiRegistrySource(baseUrl, options = {}) {
88897
89290
  throw resolutionError;
88898
89291
  }
88899
89292
  const page = await searchMarketplace(
88900
- { query: ref, kinds: ["api"], includeUnverified: true },
89293
+ { query: ref, kinds: ["api"], includeUnverified: true, includeOutage: true },
88901
89294
  config2,
88902
89295
  fetchImpl
88903
89296
  );
@@ -88921,6 +89314,7 @@ async function fetchCallsDiscovery(query, config2, fetchImpl) {
88921
89314
  configureUrl(url2) {
88922
89315
  url2.searchParams.set("q", query);
88923
89316
  url2.searchParams.set("includeUnverified", "true");
89317
+ url2.searchParams.set("includeOutage", "true");
88924
89318
  }
88925
89319
  });
88926
89320
  return parseDiscovery(await response.json());
@@ -89080,6 +89474,18 @@ function x402scanSource() {
89080
89474
  };
89081
89475
  }
89082
89476
 
89477
+ // ../mcp/src/tools/search.ts
89478
+ async function searchMarketplace2(...args) {
89479
+ const page = await searchMarketplace(...args);
89480
+ return {
89481
+ ...page,
89482
+ items: page.items.map((item) => ({
89483
+ ...item,
89484
+ ...item.fee === void 0 ? {} : { feeDisplay: formatListingFee(item.fee) }
89485
+ }))
89486
+ };
89487
+ }
89488
+
89083
89489
  // ../mcp/src/tools/call.ts
89084
89490
  var VapiCallError = class extends Error {
89085
89491
  constructor(code, message, possibleSettlement2, options) {
@@ -89590,7 +89996,7 @@ function receiptContext(args, trace, resourceUrl) {
89590
89996
  };
89591
89997
  }
89592
89998
  function errorOutcome(error61, code) {
89593
- if (code === "max_price_exceeded" || code.includes("cap_exceeded")) {
89999
+ if (error61 instanceof SpendCapExceededError || code === "max_price_exceeded" || code.includes("cap_exceeded")) {
89594
90000
  return "declined_policy";
89595
90001
  }
89596
90002
  if (error61 instanceof VapiCallError) {
@@ -89932,6 +90338,7 @@ function paidRequestTimeoutMs(timeoutSeconds, internalTimeoutMs, offerTimeoutSec
89932
90338
  return usableOfferTimeout === void 0 ? 12e4 : Math.min(12e4, Math.max(3e4, usableOfferTimeout * 1e3));
89933
90339
  }
89934
90340
  function mapX402PaymentError(error61, resumeId) {
90341
+ if (error61 instanceof SpendCapExceededError) return error61;
89935
90342
  if (!(error61 instanceof X402PaymentError)) return error61;
89936
90343
  if (error61.code === "payment_rejected") {
89937
90344
  return new VapiCallError("payment_rejected", error61.message, void 0, {
@@ -89991,9 +90398,11 @@ async function inspectService(input2, config2, fetchImpl) {
89991
90398
  ...endpoint.operationId === void 0 ? {} : { operationId: endpoint.operationId },
89992
90399
  ...endpoint.requestContentType === void 0 ? {} : { requestContentType: endpoint.requestContentType },
89993
90400
  ...endpoint.requestSchema === void 0 ? {} : { requestSchema: endpoint.requestSchema },
90401
+ ...endpoint.responseSchema === void 0 ? {} : { responseSchema: endpoint.responseSchema },
90402
+ ...endpoint.exampleRequest === void 0 ? {} : { exampleRequest: endpoint.exampleRequest },
89994
90403
  ...endpoint.responseContentType === void 0 ? {} : { responseContentType: endpoint.responseContentType },
89995
90404
  ...service.group === void 0 ? {} : { group: service.group },
89996
- ...service.fee === void 0 ? {} : { fee: service.fee },
90405
+ ...service.fee === void 0 ? {} : { fee: service.fee, feeDisplay: formatListingFee(service.fee) },
89997
90406
  verification: service.verification,
89998
90407
  ...healthOf(service),
89999
90408
  payment: endpoint.payment ?? null
@@ -90008,14 +90417,16 @@ function inspectIndexedHit(hit) {
90008
90417
  description: hit.card.summary,
90009
90418
  network: hit.execution.network,
90010
90419
  ...hit.group === void 0 ? {} : { group: hit.group },
90011
- ...hit.fee === void 0 ? {} : { fee: hit.fee },
90420
+ ...hit.fee === void 0 ? {} : { fee: hit.fee, feeDisplay: formatListingFee(hit.fee) },
90012
90421
  verification: hit.verification,
90013
90422
  ...healthOf(hit),
90014
90423
  payment: null
90015
90424
  };
90016
90425
  }
90017
90426
  function healthOf(listing) {
90427
+ const health = listingHealthSchema.optional().catch(void 0).parse(listing.health);
90018
90428
  return {
90429
+ ...health === void 0 ? {} : { health },
90019
90430
  ...listing.liveness === void 0 ? {} : { liveness: listing.liveness },
90020
90431
  ...listing.conformance === void 0 ? {} : { conformance: listing.conformance },
90021
90432
  ...listing.identity === void 0 ? {} : { identity: listing.identity }
@@ -90034,6 +90445,160 @@ function inspectionCacheKey(input2) {
90034
90445
  return JSON.stringify([input2.id, input2.endpoint ?? null]);
90035
90446
  }
90036
90447
 
90448
+ // ../mcp/src/actions/hints.ts
90449
+ function searchHints(page, options) {
90450
+ const hints = [];
90451
+ const apis = page.items.filter((hit) => hit.kind === "api");
90452
+ const payable = apis.find(
90453
+ (hit) => hit.action.type === "invoke_api" && hit.execution.payable !== false
90454
+ );
90455
+ if (payable) {
90456
+ hints.push(
90457
+ `Inspect before paying: ${renderAction(options.surface, "inspect", { id: payable.ref })}`
90458
+ );
90459
+ }
90460
+ hints.push(
90461
+ ...apis.flatMap(
90462
+ (hit) => (hit.alternatives ?? []).map((alternative) => {
90463
+ const reason = alternative.reason === "cheaper" ? "cheaper healthy" : "healthier";
90464
+ return `${hit.ref} has a ${reason} alternative: ${alternative.ref}`;
90465
+ })
90466
+ ).slice(0, 2)
90467
+ );
90468
+ const hiddenOutage = page.totals?.hiddenOutage ?? 0;
90469
+ if (options.includeOutage !== true && hiddenOutage > 0) {
90470
+ const count = hiddenOutage === 1 ? "1 listing in outage is" : `${hiddenOutage} listings in outage are`;
90471
+ hints.push(
90472
+ options.surface === "cli" ? `${count} hidden; add --include-outage to show them.` : `${count} hidden; call with includeOutage: true to show them.`
90473
+ );
90474
+ }
90475
+ if (page.items.length === 0) {
90476
+ hints.push(
90477
+ `Broaden your search with: ${renderAction(options.surface, "search", { includeUnverified: true })}`
90478
+ );
90479
+ }
90480
+ return hints.slice(0, 4);
90481
+ }
90482
+ function inspectHints(result, options) {
90483
+ const hints = [];
90484
+ if (result.health?.state === "degraded" || result.health?.state === "outage") {
90485
+ hints.push(
90486
+ 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 })}`
90487
+ );
90488
+ }
90489
+ if (typeof result.payment?.protocol === "string") {
90490
+ hints.push(
90491
+ `This payment protocol is not supported; find another API with: ${renderAction(options.surface, "search", {})}`
90492
+ );
90493
+ return hints;
90494
+ }
90495
+ const query = result.exampleRequest?.query;
90496
+ const hasQuery = query !== void 0 && Object.keys(query).length > 0;
90497
+ const queryInBody = result.method === "GET" || result.method === "HEAD";
90498
+ let body = result.exampleRequest?.body;
90499
+ if (queryInBody && hasQuery) {
90500
+ body = { ...isRecord6(body) ? body : {}, ...query };
90501
+ }
90502
+ if (body === void 0) body = requiredBody(result.requestSchema);
90503
+ if (options.surface === "agent" && !queryInBody && hasQuery) {
90504
+ hints.push(
90505
+ `This example needs URL query parameters; find another API with: ${renderAction(options.surface, "search", {})}`
90506
+ );
90507
+ } else if (options.surface === "agent" && (exactPrice(result.price) === void 0 || result.method === null)) {
90508
+ hints.push(
90509
+ `Find an API with a published price and method: ${renderAction(options.surface, "search", {})}`
90510
+ );
90511
+ } else {
90512
+ const queryUrl = !queryInBody && hasQuery ? new URL(result.url) : void 0;
90513
+ if (queryUrl) {
90514
+ for (const [key2, value] of Object.entries(query)) queryUrl.searchParams.set(key2, value);
90515
+ }
90516
+ const direct = queryUrl !== void 0 || result.network !== void 0 || /^https?:\/\//u.test(options.ref);
90517
+ hints.push(
90518
+ `Pay with: ${renderAction(
90519
+ options.surface,
90520
+ "pay",
90521
+ {
90522
+ ...queryUrl === void 0 ? { id: options.ref } : { url: queryUrl.href },
90523
+ ...!direct && result.name ? { endpoint: result.name } : {},
90524
+ ...direct ? { method: result.method ?? "<method>" } : {},
90525
+ body,
90526
+ ...queryUrl !== void 0 && result.requestContentType !== void 0 ? { contentType: result.requestContentType } : {},
90527
+ ...queryUrl !== void 0 && result.payment?.network !== void 0 ? { network: result.payment.network } : {},
90528
+ ...queryUrl !== void 0 && result.payment?.payTo !== void 0 ? { expectedPayTo: result.payment.payTo } : {}
90529
+ },
90530
+ result.price
90531
+ )}`
90532
+ );
90533
+ }
90534
+ return hints;
90535
+ }
90536
+ function payHints(result, options) {
90537
+ const hints = [];
90538
+ const settlementUnknown2 = result.outcome === "settlement_unknown";
90539
+ if (result.status >= 200 && result.status < 300 && !settlementUnknown2) {
90540
+ if (options.surface === "cli") {
90541
+ hints.push(
90542
+ `Receipt saved; review it with: vapi receipts --limit 1${result.wallet ? ` --account ${shellWord(result.wallet)}` : ""}`
90543
+ );
90544
+ } else if (options.surface === "mcp") {
90545
+ hints.push(
90546
+ `Receipt saved; review it with: receipts.list ${JSON.stringify({ limit: 1, ...result.wallet ? { wallet: result.wallet } : {} })}`
90547
+ );
90548
+ } else if (options.ref) {
90549
+ hints.push(
90550
+ `Review the request contract with: ${renderAction(options.surface, "inspect", { id: options.ref })}`
90551
+ );
90552
+ }
90553
+ return hints;
90554
+ }
90555
+ if (options.ref) {
90556
+ hints.push(
90557
+ `The provider answered ${result.status}; check the request contract with: ${renderAction(options.surface, "inspect", { id: options.ref })}`
90558
+ );
90559
+ }
90560
+ const receiptId = options.receiptId ?? result.receiptId;
90561
+ if ((result.status === 402 || settlementUnknown2) && receiptId && options.surface === "cli") {
90562
+ hints.push(`Check settlement with: vapi pay --resume ${shellWord(receiptId)}`);
90563
+ }
90564
+ return hints;
90565
+ }
90566
+ function renderAction(surface, action, args, price) {
90567
+ if (surface === "agent") {
90568
+ 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 ?? "") };
90569
+ return `call_${action} ${JSON.stringify(loopArgs)}`;
90570
+ }
90571
+ if (surface === "mcp") return `call.${action} ${JSON.stringify(args)}`;
90572
+ if (action === "search") return "vapi search --include-unverified";
90573
+ const command = `vapi ${action} ${shellWord(args.url ?? args.id ?? "")}`;
90574
+ if (action === "inspect") return command;
90575
+ const endpoint = args.endpoint ? ` --endpoint ${shellWord(args.endpoint)}` : "";
90576
+ const method = args.method ? ` --method ${shellWord(args.method)}` : "";
90577
+ const headers = args.contentType ? ` --content-type ${shellWord(args.contentType)}` : "";
90578
+ const network = args.network ? ` --network ${shellWord(args.network)}` : "";
90579
+ const payee = args.expectedPayTo ? ` --expected-pay-to ${shellWord(args.expectedPayTo)}` : "";
90580
+ return `${command}${endpoint}${method} --body ${shellQuote(args.body === "<json>" ? "<json>" : JSON.stringify(args.body) ?? "<json>")}${headers}${network}${payee}`;
90581
+ }
90582
+ function exactPrice(price) {
90583
+ if (!/^\$(0|[1-9]\d*)(?:\.\d{1,6})?$/u.test(price.trim())) return void 0;
90584
+ const value = Number(price.trim().slice(1));
90585
+ return Number.isFinite(value) ? value : void 0;
90586
+ }
90587
+ function requiredBody(schema) {
90588
+ if (!isRecord6(schema) || !Array.isArray(schema.required)) return "<json>";
90589
+ const names = schema.required.filter((name) => typeof name === "string");
90590
+ return names.length > 0 ? Object.fromEntries(names.map((name) => [name, "<value>"])) : "<json>";
90591
+ }
90592
+ function isRecord6(value) {
90593
+ return typeof value === "object" && value !== null && !Array.isArray(value);
90594
+ }
90595
+ function shellWord(value) {
90596
+ return /^[a-zA-Z0-9_./:@%-]+$/u.test(value) ? value : shellQuote(value);
90597
+ }
90598
+ function shellQuote(value) {
90599
+ return `'${value.replaceAll("'", "'\\''")}'`;
90600
+ }
90601
+
90037
90602
  // ../mcp/src/actions/call.ts
90038
90603
  var MAX_CACHED_MARKETPLACE_REFS = 200;
90039
90604
  var walletArgument = {
@@ -90042,6 +90607,7 @@ var walletArgument = {
90042
90607
  )
90043
90608
  };
90044
90609
  var callToolResultSchema = external_exports.object({
90610
+ hints: external_exports.array(external_exports.string()).max(4),
90045
90611
  wallet: external_exports.string(),
90046
90612
  status: external_exports.number().int(),
90047
90613
  body: external_exports.unknown(),
@@ -90064,6 +90630,7 @@ var callToolResultSchema = external_exports.object({
90064
90630
  }).optional()
90065
90631
  });
90066
90632
  var inspectToolResultSchema = external_exports.object({
90633
+ hints: external_exports.array(external_exports.string()).max(4),
90067
90634
  name: external_exports.string(),
90068
90635
  method: external_exports.string().nullable(),
90069
90636
  url: external_exports.url(),
@@ -90072,13 +90639,17 @@ var inspectToolResultSchema = external_exports.object({
90072
90639
  operationId: external_exports.string().optional(),
90073
90640
  requestContentType: external_exports.string().optional(),
90074
90641
  requestSchema: external_exports.unknown().optional(),
90642
+ responseSchema: discoveryEndpointSchema.shape.responseSchema,
90643
+ exampleRequest: discoveryEndpointSchema.shape.exampleRequest,
90075
90644
  responseContentType: external_exports.string().optional(),
90076
90645
  network: external_exports.string().optional(),
90077
90646
  // Registry-owned listing disclosures, mirrored from call.search.
90078
90647
  group: listingGroupSchema.optional(),
90079
90648
  fee: listingFeeSchema.optional(),
90649
+ feeDisplay: external_exports.string().optional(),
90080
90650
  verification: listingVerificationSchema,
90081
90651
  liveness: listingLivenessSchema.optional(),
90652
+ health: listingHealthSchema.optional().catch(void 0),
90082
90653
  conformance: listingConformanceSchema.optional(),
90083
90654
  identity: listingIdentitySchema.optional(),
90084
90655
  payment: discoveryEndpointSchema.shape.payment.unwrap().nullable()
@@ -90091,6 +90662,9 @@ var callSearchInputSchema = external_exports.object({
90091
90662
  cursor: external_exports.string().trim().min(1).max(4096).optional(),
90092
90663
  includeUnverified: external_exports.boolean().optional().describe(
90093
90664
  "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."
90665
+ ),
90666
+ includeOutage: external_exports.boolean().optional().describe(
90667
+ "Default results hide listings whose recent health checks show an outage; includeOutage: true shows them."
90094
90668
  )
90095
90669
  });
90096
90670
  var callInspectInputSchema = external_exports.object({
@@ -90115,11 +90689,14 @@ var callPayInputSchema = external_exports.object({
90115
90689
  "Seconds to wait for the paid response. Default: the provider's maxTimeoutSeconds, at most 120."
90116
90690
  )
90117
90691
  });
90692
+ var callSearchOutputSchema = marketplaceDiscoveryPageSchema.extend({
90693
+ hints: external_exports.array(external_exports.string()).max(4)
90694
+ });
90118
90695
  var callSearch = defineAction({
90119
90696
  name: "call.search",
90120
90697
  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
90698
  input: callSearchInputSchema,
90122
- output: marketplaceDiscoveryPageSchema,
90699
+ output: callSearchOutputSchema,
90123
90700
  money: "none",
90124
90701
  grant: "call",
90125
90702
  async run(input2, ctx) {
@@ -90127,7 +90704,13 @@ var callSearch = defineAction({
90127
90704
  if (ctx.caller.run) {
90128
90705
  for (const item of page.items) ctx.caller.run.searchedRefs.add(item.ref);
90129
90706
  }
90130
- return page;
90707
+ return {
90708
+ ...page,
90709
+ hints: searchHints(page, {
90710
+ surface: ctx.caller.surface,
90711
+ ...input2.includeOutage === void 0 ? {} : { includeOutage: input2.includeOutage }
90712
+ })
90713
+ };
90131
90714
  }
90132
90715
  });
90133
90716
  var callInspect = defineAction({
@@ -90140,10 +90723,13 @@ var callInspect = defineAction({
90140
90723
  async run(input2, ctx) {
90141
90724
  const cacheKey2 = inspectionCacheKey(input2);
90142
90725
  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;
90726
+ const result = cached2 ?? await ctx.call.inspect(input2);
90727
+ if (!cached2) ctx.caller.run?.inspected.set(cacheKey2, result);
90728
+ return {
90729
+ ...result,
90730
+ payment: result.payment ?? null,
90731
+ hints: inspectHints(result, { ref: input2.id, surface: ctx.caller.surface })
90732
+ };
90147
90733
  }
90148
90734
  });
90149
90735
  var callPay = defineAction({
@@ -90154,14 +90740,22 @@ var callPay = defineAction({
90154
90740
  money: "spends",
90155
90741
  grant: "call",
90156
90742
  async run(input2, ctx) {
90157
- return await ctx.call.pay(input2);
90743
+ const result = await ctx.call.pay(input2);
90744
+ return {
90745
+ ...result,
90746
+ hints: payHints(result, {
90747
+ surface: ctx.caller.surface,
90748
+ ...input2.id === void 0 ? {} : { ref: input2.id },
90749
+ ...input2.url === void 0 ? {} : { url: input2.url }
90750
+ })
90751
+ };
90158
90752
  }
90159
90753
  });
90160
90754
  function createCallPort(options) {
90161
90755
  const searchedMarketplaceHits = options.cacheMarketplaceHits ? /* @__PURE__ */ new Map() : void 0;
90162
90756
  return {
90163
90757
  async search(input2) {
90164
- const page = await searchMarketplace(input2, options.config, options.fetchImpl, {
90758
+ const page = await searchMarketplace2(input2, options.config, options.fetchImpl, {
90165
90759
  ...options.searchesPath === void 0 ? {} : { searchesPath: options.searchesPath },
90166
90760
  ...options.notice === void 0 ? {} : { notice: options.notice }
90167
90761
  });
@@ -90618,6 +91212,15 @@ async function checkAction(action, input2, ctx, options = {}) {
90618
91212
  }
90619
91213
  const priceUsd = exactUsdcPrice(listing.price);
90620
91214
  const profile = ctx.caller.profile;
91215
+ if (priceUsd !== null && ctx.caps !== void 0 && priceUsd > ctx.caps.perCallUsd) {
91216
+ throw new SpendCapExceededError({
91217
+ cap: "per_call",
91218
+ amountUsd: listing.price.trim().slice(1),
91219
+ limitUsd: String(ctx.caps.perCallUsd),
91220
+ ...ctx.caps.perDayUsd === void 0 ? {} : { perDayLimitUsd: ctx.caps.perDayUsd },
91221
+ wallet: profile.wallet
91222
+ });
91223
+ }
90621
91224
  const decision = decidePayment({
90622
91225
  ref,
90623
91226
  priceUsd,
@@ -90638,10 +91241,12 @@ async function checkAction(action, input2, ctx, options = {}) {
90638
91241
  }
90639
91242
  const maxUsd = Number(input2.maxPriceUsd);
90640
91243
  if (priceUsd !== null && maxUsd < priceUsd) {
90641
- return {
90642
- kind: "deny",
90643
- reason: `Requested maximum $${maxUsd} is below the listing price $${priceUsd}.`
90644
- };
91244
+ throw new SpendCapExceededError({
91245
+ cap: "max_price",
91246
+ amountUsd: listing.price.trim().slice(1),
91247
+ limitUsd: String(maxUsd),
91248
+ wallet: profile.wallet
91249
+ });
90645
91250
  }
90646
91251
  return { kind: "allow" };
90647
91252
  }
@@ -91187,6 +91792,7 @@ function createAgentRunDeps(input2) {
91187
91792
  config: input2.config,
91188
91793
  home: input2.home,
91189
91794
  chat: input2.chat,
91795
+ searchPage: call2.search,
91190
91796
  async search(query) {
91191
91797
  const page = await call2.search(query);
91192
91798
  const rows = page.items.map((hit) => ({
@@ -91235,7 +91841,10 @@ function createAgentRunDeps(input2) {
91235
91841
  network: result.payment?.network ?? listing?.payment?.network ?? listing?.network ?? ""
91236
91842
  };
91237
91843
  },
91238
- caps: { perCallUsd: Number(input2.spendCaps.perCallAtomic) / 1e6 },
91844
+ caps: {
91845
+ perCallUsd: Number(input2.spendCaps.perCallAtomic) / 1e6,
91846
+ perDayUsd: formatUsdc(BigInt(input2.spendCaps.perDayAtomic))
91847
+ },
91239
91848
  approve: input2.approve,
91240
91849
  ...input2.budget === void 0 ? {} : { budget: input2.budget },
91241
91850
  ...input2.runId === void 0 ? {} : { runId: input2.runId },
@@ -91245,6 +91854,7 @@ function createAgentRunDeps(input2) {
91245
91854
  return {
91246
91855
  ...this,
91247
91856
  search: this.search === dependencies.search ? next.search : this.search,
91857
+ searchPage: this.searchPage !== dependencies.searchPage ? this.searchPage : this.search === dependencies.search ? next.searchPage : void 0,
91248
91858
  inspect: this.inspect === dependencies.inspect ? next.inspect : this.inspect,
91249
91859
  read: this.read === dependencies.read ? next.read : this.read,
91250
91860
  pay: this.pay === dependencies.pay ? next.pay : this.pay,
@@ -91263,8 +91873,8 @@ function exactPriceFact(value) {
91263
91873
  }
91264
91874
 
91265
91875
  // ../mcp/src/agent/runtime.ts
91266
- import { mkdir as mkdir18, readFile as readFile23, readdir as readdir7, rm as rm2 } from "node:fs/promises";
91267
- import { join as join18 } from "node:path";
91876
+ import { mkdir as mkdir18, readFile as readFile23, readdir as readdir7, rm as rm3 } from "node:fs/promises";
91877
+ import { join as join19 } from "node:path";
91268
91878
 
91269
91879
  // ../mcp/src/agent/run.ts
91270
91880
  var loopSearchResultSchema = external_exports.array(
@@ -91276,7 +91886,11 @@ var loopSearchResultSchema = external_exports.array(
91276
91886
  description: external_exports.string().optional()
91277
91887
  })
91278
91888
  );
91279
- var loopPayResultSchema = external_exports.object({ status: external_exports.number(), body: external_exports.unknown() });
91889
+ var loopPayResultSchema = external_exports.object({
91890
+ status: external_exports.number(),
91891
+ body: external_exports.unknown(),
91892
+ hints: external_exports.array(external_exports.string()).max(4)
91893
+ });
91280
91894
  var LOOP_BINDINGS = {
91281
91895
  "call.search": {
91282
91896
  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,25 +91898,32 @@ var LOOP_BINDINGS = {
91284
91898
  type: "object",
91285
91899
  properties: {
91286
91900
  query: { type: "string" },
91287
- network: { type: ["string", "null"] }
91901
+ network: { type: ["string", "null"] },
91902
+ includeOutage: { type: ["boolean", "null"] }
91288
91903
  },
91289
- required: ["query", "network"],
91904
+ required: ["query", "network", "includeOutage"],
91290
91905
  additionalProperties: false
91291
91906
  },
91292
- output: loopSearchResultSchema,
91907
+ output: external_exports.union([callSearchOutputSchema, loopSearchResultSchema]),
91293
91908
  summary: "Search completed.",
91294
91909
  parseArguments(value, deps) {
91295
91910
  const args = parseObjectArgs(value);
91296
91911
  const query = requiredString2(args, "query");
91297
91912
  const network = searchNetwork(nullableString(args, "network"));
91913
+ const includeOutage = args.includeOutage;
91914
+ if (includeOutage !== void 0 && includeOutage !== null && typeof includeOutage !== "boolean") {
91915
+ throw new ToolInputError("includeOutage must be a boolean or null.");
91916
+ }
91298
91917
  return {
91299
91918
  query,
91300
91919
  ...network === null ? {} : { network },
91301
- includeUnverified: !deps.profile.verifiedOnly
91920
+ includeUnverified: !deps.profile.verifiedOnly,
91921
+ ...includeOutage == null ? {} : { includeOutage }
91302
91922
  };
91303
91923
  },
91304
91924
  async run(input2, ctx, execution) {
91305
91925
  const search2 = input2;
91926
+ if (execution.deps.searchPage) return await callSearch.run(search2, ctx);
91306
91927
  const rows = await execution.deps.search(search2);
91307
91928
  for (const row of rows) ctx.caller.run?.searchedRefs.add(row.ref);
91308
91929
  return rows;
@@ -91322,14 +91943,8 @@ var LOOP_BINDINGS = {
91322
91943
  const args = parseObjectArgs(value);
91323
91944
  return { id: requiredString2(args, "ref") };
91324
91945
  },
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;
91946
+ async run(input2, ctx) {
91947
+ return await callInspect.run(input2, ctx);
91333
91948
  }
91334
91949
  },
91335
91950
  "call.pay": {
@@ -91374,7 +91989,8 @@ var LOOP_BINDINGS = {
91374
91989
  }
91375
91990
  return {
91376
91991
  status: execution.payment.status,
91377
- body: execution.payment.body
91992
+ body: execution.payment.body,
91993
+ hints: payHints(execution.payment, { ref: id2, surface: ctx.caller.surface })
91378
91994
  };
91379
91995
  }
91380
91996
  },
@@ -91524,7 +92140,8 @@ async function runAgent(task, deps) {
91524
92140
  config: deps.config,
91525
92141
  clock: deps.now ?? (() => /* @__PURE__ */ new Date()),
91526
92142
  call: {
91527
- async search() {
92143
+ async search(input2) {
92144
+ if (runDeps.searchPage) return await runDeps.searchPage(input2);
91528
92145
  throw new Error("The agent loop uses its reduced search binding.");
91529
92146
  },
91530
92147
  async inspect({ id: id2 }) {
@@ -91669,6 +92286,18 @@ ${UNTRUSTED_NOTICE}` },
91669
92286
  fatalDetail: "The local audit log could not be written."
91670
92287
  };
91671
92288
  }
92289
+ if (error61 instanceof SpendCapExceededError) {
92290
+ const ref2 = paymentRef(input2);
92291
+ const reason = callRunBudgetReason(error61, runDeps.budget) ?? callBudgetReason(error61);
92292
+ if (ref2 !== void 0 && reason !== void 0) {
92293
+ const outcome = await declineSafely(ref2, reason);
92294
+ return outcome.fatalDetail === void 0 ? {
92295
+ ...outcome,
92296
+ fatalDetail: reason,
92297
+ ...error61.cap === "run_budget" ? { fatalReason: "run_budget" } : {}
92298
+ } : outcome;
92299
+ }
92300
+ }
91672
92301
  if (error61 instanceof ActionDeclinedError) {
91673
92302
  const declinedRef = actionDeclineRef(action, input2);
91674
92303
  if (declinedRef !== void 0) {
@@ -91686,7 +92315,8 @@ ${UNTRUSTED_NOTICE}` },
91686
92315
  }
91687
92316
  const runBudgetReason = callRunBudgetReason(error61.paymentError, runDeps.budget);
91688
92317
  if (runBudgetReason !== void 0) {
91689
- return await declineSafely(ref, runBudgetReason);
92318
+ const outcome = await declineSafely(ref, runBudgetReason);
92319
+ return spendCap(error61.paymentError) === "run_budget" ? { ...outcome, fatalDetail: runBudgetReason, fatalReason: "run_budget" } : outcome;
91690
92320
  }
91691
92321
  const spendBudgetReason = callBudgetReason(error61.paymentError);
91692
92322
  if (spendBudgetReason !== void 0) {
@@ -91708,7 +92338,7 @@ ${UNTRUSTED_NOTICE}` },
91708
92338
  try {
91709
92339
  reply = await deps.chat({ model: profile.model, messages, tools, tool_choice: "auto" });
91710
92340
  } catch (error61) {
91711
- if (error61 instanceof RunBudgetError || hasErrorCode(error61, "run_budget_exceeded")) {
92341
+ if (error61 instanceof RunBudgetError || hasErrorCode(error61, "run_budget_exceeded") || spendCap(error61) === "run_budget") {
91712
92342
  return await stop("run_budget", runBudgetDetail(runDeps.budget));
91713
92343
  }
91714
92344
  if (hasErrorCode(error61, "budget_exhausted")) {
@@ -91755,7 +92385,9 @@ ${UNTRUSTED_NOTICE}` },
91755
92385
  name: call2.name,
91756
92386
  summary: toolSummary(call2.name, loopActions)
91757
92387
  });
91758
- if (outcome.fatalDetail) return await stop("error", outcome.fatalDetail);
92388
+ if (outcome.fatalDetail) {
92389
+ return await stop(outcome.fatalReason ?? "error", outcome.fatalDetail);
92390
+ }
91759
92391
  }
91760
92392
  }
91761
92393
  return await stop("max_steps");
@@ -91848,6 +92480,14 @@ function hasErrorCode(error61, code) {
91848
92480
  return typeof error61 === "object" && error61 !== null && typeof Reflect.get(error61, "code") === "string" && Reflect.get(error61, "code") === code;
91849
92481
  }
91850
92482
  function callBudgetReason(error61) {
92483
+ const cap = spendCap(error61);
92484
+ if (cap !== void 0) {
92485
+ if (cap === "per_call") return "This wallet's per-call Call budget is exhausted.";
92486
+ if (cap === "per_day") return "This wallet's daily Call budget is exhausted.";
92487
+ if (cap === "max_price") return "This call exceeds its maximum price.";
92488
+ if (cap === "max_amount") return "This payment exceeds its maximum amount.";
92489
+ return void 0;
92490
+ }
91851
92491
  if (hasErrorCode(error61, "per_call_cap_exceeded")) {
91852
92492
  return "This wallet's per-call Call budget is exhausted.";
91853
92493
  }
@@ -91857,11 +92497,17 @@ function callBudgetReason(error61) {
91857
92497
  return void 0;
91858
92498
  }
91859
92499
  function callRunBudgetReason(error61, budget) {
91860
- if (!(error61 instanceof RunBudgetError) && !hasErrorCode(error61, "run_budget_exceeded")) {
92500
+ if (!(error61 instanceof RunBudgetError) && spendCap(error61) !== "run_budget" && !hasErrorCode(error61, "run_budget_exceeded")) {
91861
92501
  return void 0;
91862
92502
  }
91863
92503
  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
92504
  }
92505
+ function spendCap(error61) {
92506
+ if (error61 instanceof SpendCapExceededError) return error61.cap;
92507
+ if (!hasErrorCode(error61, "spend_cap_exceeded")) return void 0;
92508
+ const cap = Reflect.get(error61, "cap");
92509
+ return cap === "per_call" || cap === "per_day" || cap === "max_price" || cap === "max_amount" || cap === "run_budget" ? cap : void 0;
92510
+ }
91865
92511
  function runBudgetDetail(budget) {
91866
92512
  return budget === void 0 ? "The run budget is spent." : `The run budget of $${formatUsdc(budget.limitAtomic)} is spent.`;
91867
92513
  }
@@ -92314,8 +92960,8 @@ async function memberBudgetAtomic(account, configured, deps) {
92314
92960
  deps.now?.() ?? /* @__PURE__ */ new Date(),
92315
92961
  account
92316
92962
  );
92317
- const remaining = BigInt(caps.perDayAtomic) - BigInt(ledger.spentAtomic);
92318
- return remaining < 0n ? 0n : remaining;
92963
+ const remaining2 = BigInt(caps.perDayAtomic) - BigInt(ledger.spentAtomic);
92964
+ return remaining2 < 0n ? 0n : remaining2;
92319
92965
  }
92320
92966
  function withoutTreasuryGrants(profile) {
92321
92967
  return {
@@ -92529,19 +93175,19 @@ var runRecordSchema = external_exports.strictObject({
92529
93175
  detail: external_exports.string().optional()
92530
93176
  });
92531
93177
  function runsDirectory(home) {
92532
- return join18(home, "runs");
93178
+ return join19(home, "runs");
92533
93179
  }
92534
93180
  function runRecordPath(home, runId) {
92535
93181
  assertRunId(runId);
92536
- return join18(runsDirectory(home), `${runId}.json`);
93182
+ return join19(runsDirectory(home), `${runId}.json`);
92537
93183
  }
92538
93184
  function runLogPath(home, runId) {
92539
93185
  assertRunId(runId);
92540
- return join18(runsDirectory(home), `${runId}.log`);
93186
+ return join19(runsDirectory(home), `${runId}.log`);
92541
93187
  }
92542
93188
  function runResultPath(home, runId) {
92543
93189
  assertRunId(runId);
92544
- return join18(runsDirectory(home), `${runId}.result.json`);
93190
+ return join19(runsDirectory(home), `${runId}.result.json`);
92545
93191
  }
92546
93192
  async function writeRunRecord(home, record2) {
92547
93193
  const path = runRecordPath(home, record2.runId);
@@ -92572,7 +93218,7 @@ async function listRunRecords(home, filter = {}) {
92572
93218
  if (match === null) continue;
92573
93219
  try {
92574
93220
  const record2 = runRecordSchema.parse(
92575
- JSON.parse(await readFile23(join18(runsDirectory(home), file2), "utf8"))
93221
+ JSON.parse(await readFile23(join19(runsDirectory(home), file2), "utf8"))
92576
93222
  );
92577
93223
  if (record2.runId !== match[1]) continue;
92578
93224
  if (filter.swarm !== void 0 && record2.member.swarm !== filter.swarm) continue;
@@ -92709,7 +93355,7 @@ async function startDetachedRun(args) {
92709
93355
  await writeRunRecord(args.home, reservation);
92710
93356
  });
92711
93357
  } catch (error61) {
92712
- await rm2(runRecordPath(args.home, args.run.runId), { force: true }).catch(
93358
+ await rm3(runRecordPath(args.home, args.run.runId), { force: true }).catch(
92713
93359
  () => void 0
92714
93360
  );
92715
93361
  throw error61;
@@ -92728,7 +93374,7 @@ async function startDetachedRun(args) {
92728
93374
  () => false
92729
93375
  );
92730
93376
  if (stopped) {
92731
- await rm2(runRecordPath(args.home, args.run.runId), { force: true }).catch(
93377
+ await rm3(runRecordPath(args.home, args.run.runId), { force: true }).catch(
92732
93378
  () => void 0
92733
93379
  );
92734
93380
  }
@@ -92849,7 +93495,7 @@ async function stopRun(args) {
92849
93495
  }
92850
93496
  }
92851
93497
  function memberRunLockPath(home, account) {
92852
- return join18(runsDirectory(home), `.member-${account}.lock`);
93498
+ return join19(runsDirectory(home), `.member-${account}.lock`);
92853
93499
  }
92854
93500
  function summarizeRunRecord(record2) {
92855
93501
  return {
@@ -94310,9 +94956,9 @@ async function watchEvents(ctx, input2, now, sleep, deadline, signal, progress)
94310
94956
  const reached = input2.until !== void 0 && next.events.some((event) => taskStateMatches(input2.until, taskEventState(event)));
94311
94957
  if (next.events.length || reached)
94312
94958
  return { ...next, ...reached ? { reached: input2.until } : {}, timedOut: false };
94313
- const remaining = deadline - now().getTime();
94314
- if (remaining <= 0) return { ...next, timedOut: true };
94315
- await sleep(Math.min(TASK_LIMITS.watchIntervalMinMs, remaining), signal);
94959
+ const remaining2 = deadline - now().getTime();
94960
+ if (remaining2 <= 0) return { ...next, timedOut: true };
94961
+ await sleep(Math.min(TASK_LIMITS.watchIntervalMinMs, remaining2), signal);
94316
94962
  if (now().getTime() >= deadline)
94317
94963
  return { events: [], nextCursor: progress.cursor, timedOut: true };
94318
94964
  }
@@ -95355,9 +96001,15 @@ var VapiMcpServer = class {
95355
96001
  return tool.deprecatedReplacement ? withDeprecation(result, tool.deprecatedReplacement) : result;
95356
96002
  }
95357
96003
  }
95358
- connectStdio() {
96004
+ #output = process.stdout;
96005
+ /**
96006
+ * Serves JSON-RPC lines from `input` and answers on `output`. The desktop
96007
+ * app hands in a socket; the CLI hands in stdio through connectStdio().
96008
+ */
96009
+ connect(input2, output4) {
95359
96010
  if (this.#stdio) return;
95360
- this.#stdio = createInterface({ input: process.stdin, crlfDelay: Infinity });
96011
+ this.#output = output4;
96012
+ this.#stdio = createInterface({ input: input2, crlfDelay: Infinity });
95361
96013
  this.#stdio.on("line", (line) => {
95362
96014
  void this.#handleLine(line);
95363
96015
  });
@@ -95366,6 +96018,9 @@ var VapiMcpServer = class {
95366
96018
  this.#onClose?.();
95367
96019
  });
95368
96020
  }
96021
+ connectStdio() {
96022
+ this.connect(process.stdin, process.stdout);
96023
+ }
95369
96024
  async close() {
95370
96025
  this.#stdio?.close();
95371
96026
  this.#stdio = void 0;
@@ -95446,7 +96101,7 @@ var VapiMcpServer = class {
95446
96101
  }
95447
96102
  }
95448
96103
  #write(message) {
95449
- process.stdout.write(`${JSON.stringify(message)}
96104
+ this.#output.write(`${JSON.stringify(message)}
95450
96105
  `);
95451
96106
  }
95452
96107
  };
@@ -96234,7 +96889,8 @@ async function loadServerConfig() {
96234
96889
  return await loadConfig();
96235
96890
  }
96236
96891
  function toolError(error61) {
96237
- const text = error61 instanceof VapiCallError ? JSON.stringify(
96892
+ const spendCapError = serializeSpendCapError(error61);
96893
+ const text = spendCapError !== void 0 ? JSON.stringify(spendCapError, null, 2) : error61 instanceof VapiCallError ? JSON.stringify(
96238
96894
  {
96239
96895
  error: error61.message,
96240
96896
  code: error61.code,
@@ -96256,6 +96912,29 @@ function toolError(error61) {
96256
96912
  content: [{ type: "text", text }]
96257
96913
  };
96258
96914
  }
96915
+ function serializeSpendCapError(error61) {
96916
+ const record2 = asRecord3(error61);
96917
+ if (!(error61 instanceof SpendCapExceededError) && (record2 === void 0 || record2.code !== "spend_cap_exceeded")) {
96918
+ return void 0;
96919
+ }
96920
+ const value = error61;
96921
+ if (typeof value.amountUsd !== "string" || typeof value.limitUsd !== "string") return void 0;
96922
+ if (value.cap !== "per_call" && value.cap !== "per_day" && value.cap !== "max_price" && value.cap !== "max_amount" && value.cap !== "run_budget") {
96923
+ return void 0;
96924
+ }
96925
+ const message = typeof value.message === "string" ? value.message : "A spend cap was exceeded.";
96926
+ return {
96927
+ error: message,
96928
+ code: "spend_cap_exceeded",
96929
+ cap: value.cap,
96930
+ amountUsd: value.amountUsd,
96931
+ limitUsd: value.limitUsd,
96932
+ ...typeof value.spentUsd === "string" ? { spentUsd: value.spentUsd } : {},
96933
+ ...typeof value.wallet === "string" ? { wallet: value.wallet } : {},
96934
+ command: typeof value.command === "string" ? value.command : null,
96935
+ retryable: false
96936
+ };
96937
+ }
96259
96938
  function asRecord3(value) {
96260
96939
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
96261
96940
  }
@@ -96424,7 +97103,7 @@ function rgbToAnsi256(red, green, blue) {
96424
97103
 
96425
97104
  // ../cli/src/accounts.ts
96426
97105
  import { readFile as readFile25, stat as stat14 } from "node:fs/promises";
96427
- import { join as join21 } from "node:path";
97106
+ import { join as join22 } from "node:path";
96428
97107
 
96429
97108
  // ../cli/src/dashboard.ts
96430
97109
  import { resolve as resolve3 } from "node:path";
@@ -96494,12 +97173,6 @@ function createListingsClient(options) {
96494
97173
  query: { wallet }
96495
97174
  });
96496
97175
  },
96497
- async splitters(wallet) {
96498
- return await call2("/api/call/listings/splitters", {
96499
- method: "GET",
96500
- query: { wallet }
96501
- });
96502
- },
96503
97176
  async create(input2) {
96504
97177
  return await call2("/api/call/listings", { method: "POST", body: input2 });
96505
97178
  },
@@ -96573,11 +97246,11 @@ function readProbeOperations(probe) {
96573
97246
  return isOperation(probe.endpoint) ? [probe.endpoint] : [];
96574
97247
  }
96575
97248
  function isOperation(operation) {
96576
- return isRecord6(operation) && typeof operation.name === "string" && operation.name.length > 0;
97249
+ return isRecord7(operation) && typeof operation.name === "string" && operation.name.length > 0;
96577
97250
  }
96578
97251
  function readProbeRejection(probe) {
96579
97252
  const rejection = probe.diagnostics?.rejection;
96580
- return isRecord6(rejection) ? rejection : void 0;
97253
+ return isRecord7(rejection) ? rejection : void 0;
96581
97254
  }
96582
97255
  function formatProbeSteps(probe) {
96583
97256
  const steps = probe.diagnostics?.steps;
@@ -96586,7 +97259,7 @@ function formatProbeSteps(probe) {
96586
97259
  }
96587
97260
  function formatProbeStep(step2) {
96588
97261
  if (typeof step2 === "string") return step2;
96589
- if (!isRecord6(step2)) return JSON.stringify(step2);
97262
+ if (!isRecord7(step2)) return JSON.stringify(step2);
96590
97263
  const label = asString2(step2.name) ?? asString2(step2.step) ?? asString2(step2.label) ?? "step";
96591
97264
  const outcome = asString2(step2.status) ?? asString2(step2.outcome) ?? asString2(step2.result) ?? (typeof step2.ok === "boolean" ? step2.ok ? "ok" : "failed" : void 0);
96592
97265
  const detail = asString2(step2.detail) ?? asString2(step2.message) ?? asString2(step2.description);
@@ -96652,19 +97325,19 @@ async function readJson(response) {
96652
97325
  }
96653
97326
  function readErrorMessage(body) {
96654
97327
  if (typeof body === "string") return body.trim() || void 0;
96655
- if (!isRecord6(body)) return void 0;
97328
+ if (!isRecord7(body)) return void 0;
96656
97329
  const error61 = body.error;
96657
- if (isRecord6(error61)) return asString2(error61.message) ?? asString2(error61.code);
97330
+ if (isRecord7(error61)) return asString2(error61.message) ?? asString2(error61.code);
96658
97331
  return asString2(body.message) ?? asString2(body.error) ?? asString2(body.detail);
96659
97332
  }
96660
97333
  function readErrorIssues(body) {
96661
- if (!isRecord6(body)) return [];
97334
+ if (!isRecord7(body)) return [];
96662
97335
  const candidates = [body.issues, body.errors, body.details];
96663
97336
  for (const candidate of candidates) {
96664
97337
  if (!Array.isArray(candidate)) continue;
96665
97338
  const issues = candidate.map((issue2) => {
96666
97339
  if (typeof issue2 === "string") return issue2;
96667
- if (!isRecord6(issue2)) return JSON.stringify(issue2);
97340
+ if (!isRecord7(issue2)) return JSON.stringify(issue2);
96668
97341
  const path = Array.isArray(issue2.path) ? issue2.path.join(".") : asString2(issue2.path);
96669
97342
  const message = asString2(issue2.message) ?? asString2(issue2.code) ?? JSON.stringify(issue2);
96670
97343
  return path ? `${path}: ${message}` : message;
@@ -96676,7 +97349,7 @@ function readErrorIssues(body) {
96676
97349
  function asString2(value) {
96677
97350
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
96678
97351
  }
96679
- function isRecord6(value) {
97352
+ function isRecord7(value) {
96680
97353
  return typeof value === "object" && value !== null && !Array.isArray(value);
96681
97354
  }
96682
97355
 
@@ -96711,11 +97384,11 @@ function formatIdentityLines(identity) {
96711
97384
  ];
96712
97385
  }
96713
97386
  function parseIdentityResponse(value) {
96714
- if (!isRecord7(value) || typeof value.wallet !== "string" || value.chain !== "eip155:8453") {
97387
+ if (!isRecord8(value) || typeof value.wallet !== "string" || value.chain !== "eip155:8453") {
96715
97388
  return void 0;
96716
97389
  }
96717
97390
  if (value.identity === null) return null;
96718
- if (!isRecord7(value.identity)) return void 0;
97391
+ if (!isRecord8(value.identity)) return void 0;
96719
97392
  const { identity } = value;
96720
97393
  if (typeof identity.erc8004Id !== "string" || identity.erc8004Id.length === 0 || typeof identity.agentCount !== "number" || !Number.isFinite(identity.agentCount) || typeof identity.registry !== "string") {
96721
97394
  return void 0;
@@ -96729,13 +97402,13 @@ function parseIdentityResponse(value) {
96729
97402
  };
96730
97403
  }
96731
97404
  function parseReputation(value) {
96732
- if (!isRecord7(value)) return void 0;
97405
+ if (!isRecord8(value)) return void 0;
96733
97406
  if (typeof value.score !== "number" || !Number.isFinite(value.score) || typeof value.count !== "number" || !Number.isInteger(value.count) || value.count < 0) {
96734
97407
  return void 0;
96735
97408
  }
96736
97409
  return { score: value.score, count: value.count };
96737
97410
  }
96738
- function isRecord7(value) {
97411
+ function isRecord8(value) {
96739
97412
  return typeof value === "object" && value !== null && !Array.isArray(value);
96740
97413
  }
96741
97414
 
@@ -97034,7 +97707,7 @@ async function offerDashboardLink({
97034
97707
  apiBase
97035
97708
  }) {
97036
97709
  const otherHome = resolve3(home) !== resolve3(getVapiPaths().directory);
97037
- const command = `${otherHome ? `VAPI_HOME=${shellQuote(home)} ` : ""}${apiBase === void 0 ? "" : `VAPI_REGISTRY_URL=${shellQuote(apiBase)} `}vapi login --account ${name}`;
97710
+ const command = `${otherHome ? `VAPI_HOME=${shellQuote2(home)} ` : ""}${apiBase === void 0 ? "" : `VAPI_REGISTRY_URL=${shellQuote2(apiBase)} `}vapi login --account ${name}`;
97038
97711
  const unlinked = {
97039
97712
  linked: false,
97040
97713
  next: [{ kind: "link", account: name, command }]
@@ -97097,7 +97770,7 @@ async function dashboardCommand(argv, json2, io, dependencies) {
97097
97770
  }
97098
97771
  io.stdout(json2 ? JSON.stringify({ account: target.name, url: url2, ...status, opened }) : url2);
97099
97772
  }
97100
- function shellQuote(value) {
97773
+ function shellQuote2(value) {
97101
97774
  return /^[a-zA-Z0-9_./-]+$/u.test(value) ? value : `'${value.replace(/'/gu, "'\\''")}'`;
97102
97775
  }
97103
97776
 
@@ -97107,7 +97780,7 @@ import { homedir as homedir2 } from "node:os";
97107
97780
  import { sep } from "node:path";
97108
97781
 
97109
97782
  // ../core/src/cloud-backup.ts
97110
- import { join as join20 } from "node:path";
97783
+ import { join as join21 } from "node:path";
97111
97784
 
97112
97785
  // ../core/src/backup.ts
97113
97786
  import {
@@ -97132,9 +97805,9 @@ import {
97132
97805
  open as openFile,
97133
97806
  readFile as readFile24,
97134
97807
  readdir as readdir8,
97135
- rm as rm3
97808
+ rm as rm4
97136
97809
  } from "node:fs/promises";
97137
- import { dirname as dirname12, join as join19 } from "node:path";
97810
+ import { dirname as dirname12, join as join20 } from "node:path";
97138
97811
  var ERROR_MESSAGES = {
97139
97812
  backup_too_large: "Backup envelope exceeds 65,536 bytes.",
97140
97813
  backup_open_failed: "Unable to open backup.",
@@ -97570,7 +98243,7 @@ function buildRelayRestorePayload(options) {
97570
98243
  const owner = normalizedOwner(options.owner);
97571
98244
  assertDevice(options.device);
97572
98245
  assertBytes(options.key, 32);
97573
- if (!isRecord8(options.kdf)) throw new Error();
98246
+ if (!isRecord9(options.kdf)) throw new Error();
97574
98247
  const kdf = parseKdf(options.kdf);
97575
98248
  const parsed = backupPlaintextSchema.safeParse(options.vault);
97576
98249
  if (!parsed.success) throw new Error();
@@ -97592,7 +98265,7 @@ function buildRelayRestorePayload(options) {
97592
98265
  async function exportBackupSource(options) {
97593
98266
  try {
97594
98267
  assertBytes(options.vaultKey, 32);
97595
- if (!isRecord8(options.store) || typeof options.store.home !== "string" || typeof options.store.snapshot !== "function" || typeof options.store.reload !== "function") {
98268
+ if (!isRecord9(options.store) || typeof options.store.home !== "string" || typeof options.store.snapshot !== "function" || typeof options.store.reload !== "function") {
97596
98269
  throw new BackupError("backup_invalid_input");
97597
98270
  }
97598
98271
  const networks = normalizeNetworks(options.networks ?? []);
@@ -97612,7 +98285,7 @@ async function exportBackupSource(options) {
97612
98285
  var BackupSnapshotChangedError = class extends Error {
97613
98286
  };
97614
98287
  async function exportBackupSourceAttempt(options, networks) {
97615
- const path = join19(options.store.home, "vault.json");
98288
+ const path = join20(options.store.home, "vault.json");
97616
98289
  const { phrase, file: file2, accounts } = await withVaultLock(path, async () => {
97617
98290
  const [phrase2, vault, file3] = await Promise.all([
97618
98291
  exportVaultPhrase({ path, key: options.vaultKey }),
@@ -97748,16 +98421,16 @@ async function restoreBackupPlaintext(options) {
97748
98421
  } catch {
97749
98422
  throw new BackupError("backup_invalid_input");
97750
98423
  }
97751
- const vaultPath2 = join19(options.home, "vault.json");
97752
- const registryPath = join19(options.home, "wallets.json");
98424
+ const vaultPath2 = join20(options.home, "vault.json");
98425
+ const registryPath = join20(options.home, "wallets.json");
97753
98426
  let stagingHome;
97754
98427
  let beforePublishError;
97755
98428
  let afterPublishError;
97756
98429
  try {
97757
98430
  await mkdir19(options.home, { recursive: true, mode: 448 });
97758
- stagingHome = await mkdtemp(join19(options.home, ".backup-restore-"));
97759
- const stagedVaultPath = join19(stagingHome, "vault.json");
97760
- const stagedRegistryPath = join19(stagingHome, "wallets.json");
98431
+ stagingHome = await mkdtemp(join20(options.home, ".backup-restore-"));
98432
+ const stagedVaultPath = join20(stagingHome, "vault.json");
98433
+ const stagedRegistryPath = join20(stagingHome, "wallets.json");
97761
98434
  await createVault({
97762
98435
  path: stagedVaultPath,
97763
98436
  key: options.vaultKey,
@@ -97816,7 +98489,7 @@ async function restoreBackupPlaintext(options) {
97816
98489
  protected: plaintext.protected,
97817
98490
  networks: [...plaintext.registry.networks]
97818
98491
  };
97819
- const markerPath = join19(options.home, RESTORE_MARKER_FILE);
98492
+ const markerPath = join20(options.home, RESTORE_MARKER_FILE);
97820
98493
  const fingerprint = restoreFingerprint(
97821
98494
  plaintext,
97822
98495
  stagedV2?.restoreDevice ?? options.device,
@@ -97881,7 +98554,7 @@ async function restoreBackupPlaintext(options) {
97881
98554
  await link2(stagedVaultPath, vaultPath2);
97882
98555
  publishedVault = true;
97883
98556
  } catch (error61) {
97884
- await rm3(markerPath, { force: true }).catch(() => void 0);
98557
+ await rm4(markerPath, { force: true }).catch(() => void 0);
97885
98558
  throw error61;
97886
98559
  }
97887
98560
  await notifyRestorePublish(options.afterPublish, { kind: "vault" }, (error61) => {
@@ -97892,8 +98565,8 @@ async function restoreBackupPlaintext(options) {
97892
98565
  try {
97893
98566
  await link2(stagedRegistryPath, registryPath);
97894
98567
  } catch (error61) {
97895
- if (publishedVault) await rm3(vaultPath2, { force: true }).catch(() => void 0);
97896
- await rm3(markerPath, { force: true }).catch(() => void 0);
98568
+ if (publishedVault) await rm4(vaultPath2, { force: true }).catch(() => void 0);
98569
+ await rm4(markerPath, { force: true }).catch(() => void 0);
97897
98570
  throw error61;
97898
98571
  }
97899
98572
  await notifyRestorePublish(options.afterPublish, { kind: "registry" }, (error61) => {
@@ -97907,7 +98580,7 @@ async function restoreBackupPlaintext(options) {
97907
98580
  });
97908
98581
  });
97909
98582
  }
97910
- await rm3(markerPath, { force: true });
98583
+ await rm4(markerPath, { force: true });
97911
98584
  });
97912
98585
  if (stagedV2 === void 0) return baseResult;
97913
98586
  return {
@@ -97928,7 +98601,7 @@ async function restoreBackupPlaintext(options) {
97928
98601
  throw new BackupError("backup_invalid_input");
97929
98602
  } finally {
97930
98603
  if (stagingHome !== void 0) {
97931
- await rm3(stagingHome, { recursive: true, force: true }).catch(() => void 0);
98604
+ await rm4(stagingHome, { recursive: true, force: true }).catch(() => void 0);
97932
98605
  }
97933
98606
  }
97934
98607
  }
@@ -98027,13 +98700,13 @@ async function stageV2Restore(options) {
98027
98700
  }
98028
98701
  const agents = [];
98029
98702
  for (const profile of validAgents) {
98030
- const stagedPath = join19(options.stagingHome, "agents", `${profile.name}.json`);
98703
+ const stagedPath = join20(options.stagingHome, "agents", `${profile.name}.json`);
98031
98704
  if (await stageRestoreBytes(stagedPath, prettyJson(profile))) {
98032
98705
  agents.push({
98033
98706
  kind: "agent",
98034
98707
  name: profile.name,
98035
98708
  stagedPath,
98036
- targetPath: join19(options.home, "agents", `${profile.name}.json`)
98709
+ targetPath: join20(options.home, "agents", `${profile.name}.json`)
98037
98710
  });
98038
98711
  } else {
98039
98712
  skipped2.push({ kind: "agent", name: profile.name, reason: "write_failed" });
@@ -98053,13 +98726,13 @@ async function stageV2Restore(options) {
98053
98726
  if (restoreDevice !== void 0) {
98054
98727
  for (const value of validSwarms) {
98055
98728
  const swarm = swarmFileSchema.parse({ ...value, device: restoreDevice });
98056
- const stagedPath = join19(options.stagingHome, "swarms", `${swarm.name}.json`);
98729
+ const stagedPath = join20(options.stagingHome, "swarms", `${swarm.name}.json`);
98057
98730
  if (await stageRestoreBytes(stagedPath, prettyJson(swarm))) {
98058
98731
  swarms.push({
98059
98732
  kind: "swarm",
98060
98733
  name: swarm.name,
98061
98734
  stagedPath,
98062
- targetPath: join19(options.home, "swarms", `${swarm.name}.json`)
98735
+ targetPath: join20(options.home, "swarms", `${swarm.name}.json`)
98063
98736
  });
98064
98737
  } else {
98065
98738
  skipped2.push({ kind: "swarm", name: swarm.name, reason: "write_failed" });
@@ -98069,13 +98742,13 @@ async function stageV2Restore(options) {
98069
98742
  const movements = [];
98070
98743
  for (const movement of validMovements) {
98071
98744
  const restored = reconcileRestoredMovement(movement, assumedReceiptKeys);
98072
- const stagedPath = join19(options.stagingHome, "movements", `${restored.id}.json`);
98745
+ const stagedPath = join20(options.stagingHome, "movements", `${restored.id}.json`);
98073
98746
  if (await stageRestoreBytes(stagedPath, serializeMovement(restored))) {
98074
98747
  movements.push({
98075
98748
  kind: "movement",
98076
98749
  name: restored.id,
98077
98750
  stagedPath,
98078
- targetPath: join19(options.home, "movements", `${restored.id}.json`),
98751
+ targetPath: join20(options.home, "movements", `${restored.id}.json`),
98079
98752
  movement: restored
98080
98753
  });
98081
98754
  } else {
@@ -98234,7 +98907,7 @@ async function reconcilePublishedMovements(staged, home, requireDurableSafety =
98234
98907
  const unjournaledKeys = new Set([...signedKeys].filter((key2) => !journaledKeys.has(key2)));
98235
98908
  let files;
98236
98909
  try {
98237
- files = await readdir8(join19(home, "movements"));
98910
+ files = await readdir8(join20(home, "movements"));
98238
98911
  } catch (error61) {
98239
98912
  if (isMissingFile4(error61)) return;
98240
98913
  if (requireDurableSafety && unjournaledKeys.size > 0) throw error61;
@@ -98325,7 +98998,7 @@ function prettyJson(value) {
98325
98998
  }
98326
98999
  function parseSealed(sealed) {
98327
99000
  const value = JSON.parse(sealed);
98328
- 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) {
99001
+ 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) {
98329
99002
  throw new Error();
98330
99003
  }
98331
99004
  return { epk: value.epk, nonce: value.nonce, ciphertext: value.ciphertext };
@@ -98492,13 +99165,13 @@ async function pathExists4(path) {
98492
99165
  }
98493
99166
  }
98494
99167
  function isMissingFile4(error61) {
98495
- return isErrorCode(error61, "ENOENT");
99168
+ return isErrorCode2(error61, "ENOENT");
98496
99169
  }
98497
99170
  function isExistingFile2(error61) {
98498
- return isErrorCode(error61, "EEXIST");
99171
+ return isErrorCode2(error61, "EEXIST");
98499
99172
  }
98500
- function isErrorCode(error61, code) {
98501
- return isRecord8(error61) && Reflect.get(error61, "code") === code;
99173
+ function isErrorCode2(error61, code) {
99174
+ return isRecord9(error61) && Reflect.get(error61, "code") === code;
98502
99175
  }
98503
99176
  function validateBackupSourceRelationships(source, context) {
98504
99177
  const names = /* @__PURE__ */ new Set();
@@ -98897,7 +99570,7 @@ function assertBytes(value, length) {
98897
99570
  }
98898
99571
  }
98899
99572
  function assertOwnerKey(ownerKey) {
98900
- if (!isRecord8(ownerKey) || ownerKey.kdf !== "hkdf-sha256" && ownerKey.kdf !== "scrypt") {
99573
+ if (!isRecord9(ownerKey) || ownerKey.kdf !== "hkdf-sha256" && ownerKey.kdf !== "scrypt") {
98901
99574
  throw new BackupError("backup_invalid_input");
98902
99575
  }
98903
99576
  assertBytes(ownerKey.key, 32);
@@ -98927,7 +99600,7 @@ function isIsoUtcMilliseconds(value) {
98927
99600
  return false;
98928
99601
  }
98929
99602
  }
98930
- function isRecord8(value) {
99603
+ function isRecord9(value) {
98931
99604
  return typeof value === "object" && value !== null && !Array.isArray(value);
98932
99605
  }
98933
99606
  function hasExactKeys(value, expected) {
@@ -98995,7 +99668,7 @@ async function startRelay(options) {
98995
99668
  );
98996
99669
  if (response.status !== 201) throw new Error();
98997
99670
  const value = await response.json();
98998
- 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()) {
99671
+ 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()) {
98999
99672
  throw new Error();
99000
99673
  }
99001
99674
  return { code, expiresAt: value.expiresAt, keyPair };
@@ -99013,10 +99686,10 @@ async function awaitRelay(options) {
99013
99686
  if (!Number.isFinite(deadline)) throw new CloudBackupError("relay_expired");
99014
99687
  while (true) {
99015
99688
  if (isAborted(options.signal)) throw new CloudBackupError("relay_aborted");
99016
- const remaining = deadline - readNow(now).getTime();
99017
- if (remaining <= 0) throw new CloudBackupError("relay_expired");
99689
+ const remaining2 = deadline - readNow(now).getTime();
99690
+ if (remaining2 <= 0) throw new CloudBackupError("relay_expired");
99018
99691
  let response;
99019
- const requestDeadline = AbortSignal.timeout(Math.max(1, remaining));
99692
+ const requestDeadline = AbortSignal.timeout(Math.max(1, remaining2));
99020
99693
  const requestSignal = options.signal === void 0 ? requestDeadline : AbortSignal.any([options.signal, requestDeadline]);
99021
99694
  try {
99022
99695
  response = await (options.fetchImpl ?? publicFetch5)(
@@ -99035,7 +99708,7 @@ async function awaitRelay(options) {
99035
99708
  return await readRelayResult(response, options);
99036
99709
  }
99037
99710
  try {
99038
- await sleep(Math.min(Math.max(0, pollMs), remaining), options.signal);
99711
+ await sleep(Math.min(Math.max(0, pollMs), remaining2), options.signal);
99039
99712
  } catch {
99040
99713
  if (isAborted(options.signal)) throw new CloudBackupError("relay_aborted");
99041
99714
  }
@@ -99143,7 +99816,7 @@ async function uploadBackupLocked(options, signal) {
99143
99816
  try {
99144
99817
  let vaultFile;
99145
99818
  try {
99146
- vaultFile = await readVaultFileUnlocked(join20(options.store.home, "vault.json"));
99819
+ vaultFile = await readVaultFileUnlocked(join21(options.store.home, "vault.json"));
99147
99820
  } catch (error61) {
99148
99821
  if (error61 instanceof VaultError && error61.code === "not_found") {
99149
99822
  return { status: "skipped", reason: "no_vault" };
@@ -99152,7 +99825,7 @@ async function uploadBackupLocked(options, signal) {
99152
99825
  }
99153
99826
  try {
99154
99827
  vaultKey = vaultFile.protected ? await unlockProtectedVault({
99155
- path: join20(options.store.home, "vault.json"),
99828
+ path: join21(options.store.home, "vault.json"),
99156
99829
  secrets: options.secrets,
99157
99830
  env: options.env,
99158
99831
  ...options.now === void 0 ? {} : { now: options.now }
@@ -99292,7 +99965,7 @@ async function readRelayResult(response, options) {
99292
99965
  let plaintext;
99293
99966
  try {
99294
99967
  const result = await response.json();
99295
- if (!isRecord9(result) || !hasExactKeys2(result, RELAY_RESULT_KEYS) || typeof result.sealed !== "string") {
99968
+ if (!isRecord10(result) || !hasExactKeys2(result, RELAY_RESULT_KEYS) || typeof result.sealed !== "string") {
99296
99969
  throw new Error();
99297
99970
  }
99298
99971
  plaintext = openSealed({
@@ -99322,11 +99995,11 @@ async function readRelayResult(response, options) {
99322
99995
  }
99323
99996
  }
99324
99997
  function parseRelayPayload(value) {
99325
- if (!isRecord9(value) || !isRelayPurpose(value.purpose)) {
99998
+ if (!isRecord10(value) || !isRelayPurpose(value.purpose)) {
99326
99999
  throw new CloudBackupError("payload_invalid");
99327
100000
  }
99328
100001
  const expectedKeys = value.purpose === "restore" ? RESTORE_PAYLOAD_KEYS : ENROLL_PAYLOAD_KEYS;
99329
- 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") {
100002
+ 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") {
99330
100003
  throw new CloudBackupError("payload_invalid");
99331
100004
  }
99332
100005
  const kdf = parseKdf2(value.kdf);
@@ -99356,7 +100029,7 @@ function parseRelayPayload(value) {
99356
100029
  };
99357
100030
  }
99358
100031
  function parseStoredBackupKey(value) {
99359
- 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") {
100032
+ 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") {
99360
100033
  return void 0;
99361
100034
  }
99362
100035
  const kdf = parseKdf2(value.kdf);
@@ -99382,7 +100055,7 @@ function parseStoredState(value) {
99382
100055
  if (value === void 0) return void 0;
99383
100056
  try {
99384
100057
  const parsed = JSON.parse(value);
99385
- 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) {
100058
+ 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) {
99386
100059
  return void 0;
99387
100060
  }
99388
100061
  return { lastUploadAt: parsed.lastUploadAt, sizeBytes: parsed.sizeBytes };
@@ -99474,7 +100147,7 @@ function isRelayPurpose(value) {
99474
100147
  function isAborted(signal) {
99475
100148
  return signal?.aborted === true;
99476
100149
  }
99477
- function isRecord9(value) {
100150
+ function isRecord10(value) {
99478
100151
  return typeof value === "object" && value !== null && !Array.isArray(value);
99479
100152
  }
99480
100153
  function hasExactKeys2(value, expected) {
@@ -99672,6 +100345,7 @@ async function buyCommand(argv, json2, io, dependencies) {
99672
100345
  )
99673
100346
  );
99674
100347
  } catch (error61) {
100348
+ if (error61 instanceof SpendCapExceededError) throw error61;
99675
100349
  if (error61 instanceof SpendCapError) {
99676
100350
  throw new Error(
99677
100351
  `Router balance purchase refused by the wallet spend policy: ${error61.message} Review or change it with vapi accounts caps ${target.name}.`
@@ -99824,7 +100498,7 @@ async function readProcessStdin() {
99824
100498
  }
99825
100499
 
99826
100500
  // ../cli/src/version.ts
99827
- var CLI_VERSION = "0.10.0";
100501
+ var CLI_VERSION = "0.12.0";
99828
100502
 
99829
100503
  // ../cli/src/status.ts
99830
100504
  async function statusCommand(argv, json2, io, dependencies) {
@@ -100326,10 +101000,10 @@ async function accountsRenameCommand(argv, json2, io, dependencies) {
100326
101000
  {
100327
101001
  previous: from16,
100328
101002
  ...address4 === void 0 ? {} : { address: address4 },
100329
- vault: join21(store.home, "vault.json"),
101003
+ vault: join22(store.home, "vault.json"),
100330
101004
  message: `Wallet ${from16} is now ${renamed.name}.`
100331
101005
  },
100332
- [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join21(store.home, "vault.json")}`].join(
101006
+ [`Wallet ${from16} is now ${renamed.name}.`, `Vault: ${join22(store.home, "vault.json")}`].join(
100333
101007
  "\n"
100334
101008
  )
100335
101009
  );
@@ -100438,13 +101112,13 @@ async function accountsRestoreCommand(argv, json2, io, dependencies) {
100438
101112
  { name: restored.name, ...address4 === void 0 ? {} : { address: address4 } },
100439
101113
  {
100440
101114
  ...address4 === void 0 ? {} : { address: address4 },
100441
- vault: join21(store.home, "vault.json"),
101115
+ vault: join22(store.home, "vault.json"),
100442
101116
  spendCaps: restored.entry.spendCaps,
100443
101117
  message: `Wallet ${restored.name} restored to the device vault.`
100444
101118
  },
100445
101119
  [
100446
101120
  `Wallet ${restored.name} restored to the device vault.`,
100447
- `Vault: ${join21(store.home, "vault.json")}`
101121
+ `Vault: ${join22(store.home, "vault.json")}`
100448
101122
  ].join("\n")
100449
101123
  );
100450
101124
  }
@@ -100774,7 +101448,7 @@ function formatNetworkAccounts(accounts) {
100774
101448
  }
100775
101449
 
100776
101450
  // ../cli/src/cloud-backup.ts
100777
- import { join as join22 } from "node:path";
101451
+ import { join as join23 } from "node:path";
100778
101452
  var CLOUD_BACKUP_USAGE = "Usage: vapi backup --cloud [off] [--json]";
100779
101453
  var OWNER_RESTORE_USAGE = "Usage: vapi restore --from-owner [--owner <0x\u2026>] [--json]";
100780
101454
  var OWNER_PATTERN2 = /^0x[0-9a-fA-F]{40}$/u;
@@ -100797,7 +101471,7 @@ async function cloudBackupCommand(argv, json2, io, dependencies) {
100797
101471
  }
100798
101472
  async function enrollCloudBackup(json2, io, dependencies) {
100799
101473
  const paths = getVapiPaths();
100800
- if (!await fileExists2(join22(paths.directory, "vault.json"))) {
101474
+ if (!await fileExists2(join23(paths.directory, "vault.json"))) {
100801
101475
  throw new Error("No vault on this device. Run vapi setup first.");
100802
101476
  }
100803
101477
  const context = await cloudContext(io, dependencies);
@@ -100909,7 +101583,7 @@ async function restoreFromOwnerCommand(argv, json2, io, dependencies) {
100909
101583
  }
100910
101584
  const expectedOwner = ownerValue?.toLowerCase();
100911
101585
  const paths = getVapiPaths();
100912
- if (await fileExists2(join22(paths.directory, "vault.json")) && !await fileExists2(join22(paths.directory, ".backup-restore.json"))) {
101586
+ if (await fileExists2(join23(paths.directory, "vault.json")) && !await fileExists2(join23(paths.directory, ".backup-restore.json"))) {
100913
101587
  throw new Error(
100914
101588
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
100915
101589
  );
@@ -101404,7 +102078,7 @@ async function readOffer(response) {
101404
102078
  if (raw !== null) {
101405
102079
  try {
101406
102080
  const decoded = decodePaymentRequiredHeader(raw);
101407
- if (isRecord10(decoded)) header = decoded;
102081
+ if (isRecord11(decoded)) header = decoded;
101408
102082
  else headerMalformed = true;
101409
102083
  } catch {
101410
102084
  headerMalformed = true;
@@ -101413,7 +102087,7 @@ async function readOffer(response) {
101413
102087
  let body;
101414
102088
  try {
101415
102089
  const parsed = JSON.parse(await readBoundedText(response) ?? "");
101416
- if (isRecord10(parsed) && ("accepts" in parsed || "x402Version" in parsed)) body = parsed;
102090
+ if (isRecord11(parsed) && ("accepts" in parsed || "x402Version" in parsed)) body = parsed;
101417
102091
  } catch {
101418
102092
  }
101419
102093
  const mpp = parseMppChallenge(response.headers.get("www-authenticate"));
@@ -101491,7 +102165,7 @@ function gradeOffer(offer) {
101491
102165
  };
101492
102166
  }
101493
102167
  const version5 = declared.x402Version === 1 || declared.x402Version === 2 ? declared.x402Version : null;
101494
- const accepts = (Array.isArray(declared.accepts) ? declared.accepts : []).filter(isRecord10);
102168
+ const accepts = (Array.isArray(declared.accepts) ? declared.accepts : []).filter(isRecord11);
101495
102169
  const exact = accepts.filter((accept) => accept.scheme === "exact");
101496
102170
  const fields = version5 === null ? void 0 : fieldsRule(declared, version5);
101497
102171
  const offerRules = [
@@ -101516,7 +102190,7 @@ function gradeOffer(offer) {
101516
102190
  }
101517
102191
  function advertisedExtensions(declared) {
101518
102192
  const extensions = declared.extensions;
101519
- if (!isRecord10(extensions)) return [];
102193
+ if (!isRecord11(extensions)) return [];
101520
102194
  return KNOWN_EXTENSIONS.filter((name) => Object.prototype.hasOwnProperty.call(extensions, name));
101521
102195
  }
101522
102196
  function extensionsRule(advertised) {
@@ -101639,14 +102313,14 @@ function fieldsRule(declared, version5) {
101639
102313
  if (version5 === 2) {
101640
102314
  const resource = declared.resource;
101641
102315
  if (resource === void 0) issues.push("v2_missing_resource");
101642
- else if (!isRecord10(resource) || !nonEmptyString(resource.url)) {
102316
+ else if (!isRecord11(resource) || !nonEmptyString(resource.url)) {
101643
102317
  issues.push("v2_invalid_resource");
101644
102318
  }
101645
102319
  }
101646
102320
  const accepts = declared.accepts;
101647
102321
  if (!Array.isArray(accepts) || accepts.length === 0) issues.push(`${prefix}_missing_accepts`);
101648
102322
  for (const accept of Array.isArray(accepts) ? accepts : []) {
101649
- if (!isRecord10(accept)) {
102323
+ if (!isRecord11(accept)) {
101650
102324
  issues.push(`${prefix}_invalid_accepts`);
101651
102325
  continue;
101652
102326
  }
@@ -101704,7 +102378,7 @@ function usdcIssue(accept, network) {
101704
102378
  if (typeof accept.asset !== "string" || accept.asset.toLowerCase() !== canonical.usdc.toLowerCase()) {
101705
102379
  return "asset_not_usdc";
101706
102380
  }
101707
- const extra = isRecord10(accept.extra) ? accept.extra : {};
102381
+ const extra = isRecord11(accept.extra) ? accept.extra : {};
101708
102382
  return extra.name === canonical.eip712Domain.name && extra.version === canonical.eip712Domain.version ? void 0 : "usdc_domain_mismatch";
101709
102383
  }
101710
102384
  function payToRule(exact, version5) {
@@ -101756,7 +102430,7 @@ async function discoveryRule(target, fetchImpl) {
101756
102430
  "discovery_missing"
101757
102431
  ]);
101758
102432
  }
101759
- if (!isRecord10(document)) {
102433
+ if (!isRecord11(document)) {
101760
102434
  return rule("discovery", "warn", `${url2.href} is not a JSON object.`, ["discovery_malformed"]);
101761
102435
  }
101762
102436
  const resources = Array.isArray(document.resources) ? document.resources.length : void 0;
@@ -101827,12 +102501,12 @@ function pathAdjacentOpenApiUrls(target) {
101827
102501
  }
101828
102502
  }
101829
102503
  function apiCatalogOpenApiUrls(document, catalogUrl, origin, seen) {
101830
- if (!isRecord10(document) || !Array.isArray(document.linkset)) return [];
102504
+ if (!isRecord11(document) || !Array.isArray(document.linkset)) return [];
101831
102505
  const candidates = [];
101832
102506
  for (const link3 of document.linkset) {
101833
- if (!isRecord10(link3) || !Array.isArray(link3["service-desc"])) continue;
102507
+ if (!isRecord11(link3) || !Array.isArray(link3["service-desc"])) continue;
101834
102508
  for (const description of link3["service-desc"]) {
101835
- if (!isRecord10(description) || typeof description.href !== "string") continue;
102509
+ if (!isRecord11(description) || typeof description.href !== "string") continue;
101836
102510
  let candidate;
101837
102511
  try {
101838
102512
  candidate = new URL(description.href, catalogUrl);
@@ -101851,7 +102525,7 @@ async function findOpenApiOperation(fetchImpl, candidates, pathname, method, via
101851
102525
  let firstDocument;
101852
102526
  for (const url2 of candidates) {
101853
102527
  const document = await fetchJson(fetchImpl, url2);
101854
- if (isRecord10(document) && isRecord10(document.paths)) {
102528
+ if (isRecord11(document) && isRecord11(document.paths)) {
101855
102529
  const located = {
101856
102530
  url: url2,
101857
102531
  paths: document.paths,
@@ -101872,9 +102546,9 @@ function openApiSource(document, catalogUrl) {
101872
102546
  function findOperation(paths, pathname, method) {
101873
102547
  const path = trimSlash(pathname);
101874
102548
  for (const [template, item] of Object.entries(paths)) {
101875
- if (!isRecord10(item)) continue;
102549
+ if (!isRecord11(item)) continue;
101876
102550
  const operation = item[method.toLowerCase()];
101877
- if (!isRecord10(operation)) continue;
102551
+ if (!isRecord11(operation)) continue;
101878
102552
  const pattern = trimSlash(template).split(/(\{[^/}]+\})/).map((part) => part.startsWith("{") ? "[^/]+" : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("");
101879
102553
  if (new RegExp(`${pattern}$`).test(path)) return { item, operation };
101880
102554
  }
@@ -101943,7 +102617,7 @@ function trimSlash(path) {
101943
102617
  function nonEmptyString(value) {
101944
102618
  return typeof value === "string" && value.length > 0;
101945
102619
  }
101946
- function isRecord10(value) {
102620
+ function isRecord11(value) {
101947
102621
  return typeof value === "object" && value !== null && !Array.isArray(value);
101948
102622
  }
101949
102623
 
@@ -102007,21 +102681,21 @@ function shortExcerpt(value) {
102007
102681
 
102008
102682
  // ../cli/src/agent.ts
102009
102683
  import { readFile as readFile27, stat as stat15 } from "node:fs/promises";
102010
- import { join as join25 } from "node:path";
102684
+ import { join as join26 } from "node:path";
102011
102685
  import { createInterface as createInterface2 } from "node:readline/promises";
102012
102686
 
102013
102687
  // ../cli/src/headless.ts
102014
- import { chmod as chmod7, mkdtemp as mkdtemp2, rm as rm4, writeFile as writeFile10 } from "node:fs/promises";
102688
+ import { chmod as chmod7, mkdtemp as mkdtemp2, rm as rm5, writeFile as writeFile10 } from "node:fs/promises";
102015
102689
  import { rmSync } from "node:fs";
102016
102690
  import { tmpdir as osTmpdir } from "node:os";
102017
- import { join as join23 } from "node:path";
102691
+ import { join as join24 } from "node:path";
102018
102692
  var BUNDLE_VARIABLE_PATTERN = /^[A-Z_][A-Z0-9_]*$/u;
102019
102693
  var REMOTE_BLOCKED_GRANTS2 = /* @__PURE__ */ new Set(["delegate", "allocate"]);
102020
102694
  var agentProfileOptions = { schema: registeredAgentProfileSchema };
102021
102695
  async function createHeadlessHome(bundle, options = {}) {
102022
- const home = await mkdtemp2(join23(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
102696
+ const home = await mkdtemp2(join24(options.tmpdir ?? osTmpdir(), "vapi-headless-"));
102023
102697
  const cleanup = async () => {
102024
- await rm4(home, { recursive: true, force: true });
102698
+ await rm5(home, { recursive: true, force: true });
102025
102699
  };
102026
102700
  try {
102027
102701
  await chmod7(home, 448);
@@ -102168,7 +102842,7 @@ async function runHeadlessAgent(input2) {
102168
102842
  } finally {
102169
102843
  if (previousHome === void 0) delete process.env.VAPI_HOME;
102170
102844
  else process.env.VAPI_HOME = previousHome;
102171
- if (home !== void 0) await rm4(home, { recursive: true, force: true });
102845
+ if (home !== void 0) await rm5(home, { recursive: true, force: true });
102172
102846
  removeSignalHandlers();
102173
102847
  }
102174
102848
  }
@@ -102230,7 +102904,7 @@ import {
102230
102904
  writeFile as nodeWriteFile
102231
102905
  } from "node:fs/promises";
102232
102906
  import { tmpdir as osTmpdir2 } from "node:os";
102233
- import { basename as basename4, dirname as dirname13, join as join24 } from "node:path";
102907
+ import { basename as basename4, dirname as dirname13, join as join25 } from "node:path";
102234
102908
  var RAILWAY_CLI = {
102235
102909
  binary: "railway",
102236
102910
  create: (options) => [
@@ -102402,7 +103076,7 @@ async function assertRemoteSafeMember(args) {
102402
103076
  }
102403
103077
  function railwaySidecarPath(home, runId) {
102404
103078
  if (!isRunId(runId)) throw new RuntimeError("invalid_run_id", `Invalid run id: ${runId}.`);
102405
- return join24(runsDirectory(home), `${runId}.railway.json`);
103079
+ return join25(runsDirectory(home), `${runId}.railway.json`);
102406
103080
  }
102407
103081
  function createRailwayRuntime(options) {
102408
103082
  const { home } = options;
@@ -102727,10 +103401,10 @@ function createRailwayRuntime(options) {
102727
103401
  let createError;
102728
103402
  let cleanupError;
102729
103403
  try {
102730
- directory = await fs.mkdtemp(join24(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
103404
+ directory = await fs.mkdtemp(join25(options.tmpdir ?? osTmpdir2(), "vapi-railway-"));
102731
103405
  assertNotInterrupted();
102732
103406
  await assertMode(fs, directory, 448, "env-file directory");
102733
- envFile = join24(directory, "member.env");
103407
+ envFile = join25(directory, "member.env");
102734
103408
  await fs.writeFile(envFile, `${RAILWAY_CLI.bundleVariable}=${bundle}
102735
103409
  `, {
102736
103410
  encoding: "utf8",
@@ -103049,9 +103723,9 @@ async function reserveRemoteAllowance(args) {
103049
103723
  const perDayAtomic = BigInt(args.caps.perDayAtomic);
103050
103724
  const ledgerPath = getVapiPaths(args.home).ledger;
103051
103725
  const spent = BigInt((await readSpendLedger(ledgerPath, args.now, args.account)).spentAtomic);
103052
- const remaining = spent >= perDayAtomic ? 0n : perDayAtomic - spent;
103053
- const requested = args.run.budgetUsd === void 0 ? remaining : usdToAtomic(args.run.budgetUsd);
103054
- const reserved = requested < remaining ? requested : remaining;
103726
+ const remaining2 = spent >= perDayAtomic ? 0n : perDayAtomic - spent;
103727
+ const requested = args.run.budgetUsd === void 0 ? remaining2 : usdToAtomic(args.run.budgetUsd);
103728
+ const reserved = requested < remaining2 ? requested : remaining2;
103055
103729
  if (reserved === 0n) {
103056
103730
  throw new RemoteKeyRefusedError(
103057
103731
  "no_daily_allowance",
@@ -103071,7 +103745,7 @@ async function reserveRemoteAllowance(args) {
103071
103745
  );
103072
103746
  return { atomic: reserved, expiresAt: nextUtcMidnight(reservation.date) };
103073
103747
  } catch (error61) {
103074
- if (error61 instanceof Error && "code" in error61 && error61.code === "per_day_cap_exceeded") {
103748
+ if (error61 instanceof SpendCapExceededError && error61.cap === "per_day" || error61 instanceof Error && "code" in error61 && error61.code === "per_day_cap_exceeded") {
103075
103749
  throw new RemoteKeyRefusedError(
103076
103750
  "no_daily_allowance",
103077
103751
  `${args.account}'s remaining daily allowance changed while Railway was starting. Run the command again.`
@@ -103185,7 +103859,7 @@ async function writeSidecar(home, runId, sidecar) {
103185
103859
  function writeSidecarSync(path, sidecar) {
103186
103860
  const directory = dirname13(path);
103187
103861
  mkdirSync(directory, { recursive: true, mode: 448 });
103188
- const temporary = join24(
103862
+ const temporary = join25(
103189
103863
  directory,
103190
103864
  `.${basename4(path)}.${process.pid}.${randomBytes16(6).toString("hex")}.tmp`
103191
103865
  );
@@ -103283,7 +103957,7 @@ async function assertMode(fs, path, mode, what) {
103283
103957
  }
103284
103958
  }
103285
103959
  async function deviceVaultKey(home, secrets, now) {
103286
- const path = join24(home, "vault.json");
103960
+ const path = join25(home, "vault.json");
103287
103961
  const metadata = await readVaultFileUnlocked(path);
103288
103962
  const key2 = metadata.protected ? await unlockProtectedVault({
103289
103963
  path,
@@ -103333,12 +104007,12 @@ function createLocalRuntime(options) {
103333
104007
  const { home } = options;
103334
104008
  const entry = options.entry ?? realpathSync(process.argv[1]);
103335
104009
  const execPath = options.execPath ?? process.execPath;
103336
- const spawn4 = options.spawn ?? nodeSpawn;
104010
+ const spawn6 = options.spawn ?? nodeSpawn;
103337
104011
  const kill = options.kill ?? ((pid, signal) => process.kill(pid, signal));
103338
104012
  const processCommand = options.processCommand ?? defaultProcessCommand;
103339
104013
  const ownsProcess = (handle, pid) => processCommand(pid)?.includes(runResultPath(home, handle.runId)) === true;
103340
104014
  const closeFd = options.closeFd ?? closeSync2;
103341
- const readFile31 = options.readFile ?? nodeReadFile;
104015
+ const readFile33 = options.readFile ?? nodeReadFile;
103342
104016
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
103343
104017
  const openLog = options.openLog ?? ((path) => {
103344
104018
  mkdirSync2(runsDirectory(home), { recursive: true, mode: 448 });
@@ -103356,7 +104030,7 @@ function createLocalRuntime(options) {
103356
104030
  const logFd = openLog(logPath);
103357
104031
  let child;
103358
104032
  try {
103359
- child = spawn4(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
104033
+ child = spawn6(execPath, [entry, ...args, "--json", "--result-file", resultPath], {
103360
104034
  detached: true,
103361
104035
  stdio: ["ignore", logFd, logFd],
103362
104036
  env: {
@@ -103393,7 +104067,7 @@ function createLocalRuntime(options) {
103393
104067
  return handle;
103394
104068
  },
103395
104069
  async status(handle) {
103396
- const result = await readResultFile(readFile31, runResultPath(home, handle.runId));
104070
+ const result = await readResultFile(readFile33, runResultPath(home, handle.runId));
103397
104071
  if (result !== void 0) return result;
103398
104072
  const pid = localPid(handle);
103399
104073
  if (pid === void 0 || handle.kind !== "local") {
@@ -103496,10 +104170,10 @@ function childArguments(member, run) {
103496
104170
  ...run.drawUsd ? ["--draw", run.drawUsd] : []
103497
104171
  ];
103498
104172
  }
103499
- async function readResultFile(readFile31, path) {
104173
+ async function readResultFile(readFile33, path) {
103500
104174
  let text;
103501
104175
  try {
103502
- text = await readFile31(path, "utf8");
104176
+ text = await readFile33(path, "utf8");
103503
104177
  } catch (error61) {
103504
104178
  if (hasCode3(error61, "ENOENT")) return void 0;
103505
104179
  return { state: "failed", detail: "unreadable result file" };
@@ -104210,7 +104884,7 @@ function explicitWallet(name) {
104210
104884
  }
104211
104885
  async function profileFileExists(directory, name) {
104212
104886
  try {
104213
- await stat15(join25(directory, `${name}.json`));
104887
+ await stat15(join26(directory, `${name}.json`));
104214
104888
  return true;
104215
104889
  } catch (error61) {
104216
104890
  if (isMissingFile(error61)) return false;
@@ -104270,13 +104944,91 @@ function usd(value, minimumDecimals = 0) {
104270
104944
  }
104271
104945
 
104272
104946
  // ../cli/src/mcp-install.ts
104947
+ import { spawn as spawn3 } from "node:child_process";
104273
104948
  import { mkdir as mkdir20, readFile as readFile28, writeFile as writeFile11 } from "node:fs/promises";
104274
104949
  import { homedir as systemHomedir } from "node:os";
104275
104950
  import { dirname as dirname14, posix, win32 as win322 } from "node:path";
104276
- var MCP_INSTALL_USAGE = "Usage: vapi mcp install <claude|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]";
104277
- var APPS = /* @__PURE__ */ new Set(["claude", "cursor", "codex"]);
104951
+
104952
+ // ../cli/src/toml-config.ts
104953
+ function removeTomlTables(contents, isTarget) {
104954
+ let removing = false;
104955
+ let retained = "";
104956
+ for (const { line, table } of tomlLines(contents)) {
104957
+ if (table !== void 0) removing = isTarget(tomlKeyPath(table));
104958
+ if (!removing) retained += line;
104959
+ }
104960
+ return retained;
104961
+ }
104962
+ function* tomlLines(contents) {
104963
+ let multiline;
104964
+ for (const line of contents.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
104965
+ yield { line, table: multiline === void 0 ? tomlTableName(line) : void 0 };
104966
+ for (let index2 = 0; index2 < line.length; index2 += 1) {
104967
+ const char = line[index2];
104968
+ if (multiline !== void 0) {
104969
+ if (multiline === '"""' && char === "\\") {
104970
+ index2 += 1;
104971
+ continue;
104972
+ }
104973
+ if (line.startsWith(multiline, index2)) {
104974
+ index2 += 2;
104975
+ multiline = void 0;
104976
+ }
104977
+ } else {
104978
+ if (char === "#") break;
104979
+ if (char !== "'" && char !== '"') continue;
104980
+ const delimiter2 = char.repeat(3);
104981
+ if (line.startsWith(delimiter2, index2)) {
104982
+ multiline = delimiter2;
104983
+ index2 += 2;
104984
+ } else {
104985
+ for (index2 += 1; index2 < line.length; index2 += 1) {
104986
+ if (char === '"' && line[index2] === "\\") index2 += 1;
104987
+ else if (line[index2] === char) break;
104988
+ }
104989
+ }
104990
+ }
104991
+ }
104992
+ }
104993
+ }
104994
+ function tomlKeyPath(table) {
104995
+ const key2 = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
104996
+ const pattern = new RegExp(`^\\s*(${key2})(?:\\s*\\.\\s*(${key2}))*\\s*$`);
104997
+ if (!pattern.test(table)) return [];
104998
+ return [...table.matchAll(new RegExp(key2, "g"))].map(([part]) => unquoteTomlKey(part));
104999
+ }
105000
+ function tomlTableName(line) {
105001
+ const header = line.replace(/\r?\n$/, "");
105002
+ const match = /^\s*(?:\[\[\s*(.*?)\s*\]\]|\[\s*(.*?)\s*\])\s*(?:#.*)?$/.exec(header);
105003
+ return match?.[1] ?? match?.[2];
105004
+ }
105005
+ function unquoteTomlKey(key2) {
105006
+ if (key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
105007
+ if (key2.startsWith('"') && key2.endsWith('"')) {
105008
+ try {
105009
+ return JSON.parse(key2);
105010
+ } catch {
105011
+ return key2;
105012
+ }
105013
+ }
105014
+ return key2;
105015
+ }
105016
+ function tomlSeparator(contents) {
105017
+ if (contents.length === 0 || /(?:\r?\n)[ \t]*(?:\r?\n)$/.test(contents)) return "";
105018
+ return /\r?\n$/.test(contents) ? "\n" : "\n\n";
105019
+ }
105020
+ function escapeToml(value) {
105021
+ return JSON.stringify(value).slice(1, -1);
105022
+ }
105023
+
105024
+ // ../cli/src/mcp-install.ts
105025
+ var MCP_INSTALL_USAGE = "Usage: vapi mcp install <claude-code|claude-desktop|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]";
105026
+ var APPS = /* @__PURE__ */ new Set(["claude-code", "claude-desktop", "cursor", "codex"]);
105027
+ var CLAUDE_ALIAS_NOTICE = "vapi mcp install claude installs into Claude Desktop; for the Claude Code CLI use: vapi mcp install claude-code";
105028
+ var CLAUDE_NOT_FOUND = "Claude Code's claude command was not found on PATH. Install Claude Code, or run this yourself:";
104278
105029
  var NEXT_STEP = {
104279
- claude: 'Restart Claude Desktop, then ask it: "Search vAPI for a weather API."',
105030
+ "claude-code": 'Start a new Claude Code session, then ask: "Search vAPI for a weather API."',
105031
+ "claude-desktop": 'Restart Claude Desktop, then ask it: "Search vAPI for a weather API."',
104280
105032
  cursor: 'Reload Cursor, then ask its agent: "Search vAPI for a weather API."',
104281
105033
  codex: 'Start codex in a new terminal, then ask: "Search vAPI for a weather API."'
104282
105034
  };
@@ -104317,36 +105069,44 @@ async function mcpInstallCommand(argv, json2, io, dependencies) {
104317
105069
  booleanOptions: /* @__PURE__ */ new Set(["--no-link"]),
104318
105070
  maximumPositionals: 1
104319
105071
  });
104320
- const appValue = parsed.positionals[0];
104321
- if (appValue === void 0) throw new UsageError(MCP_INSTALL_USAGE);
105072
+ const requestedApp = parsed.positionals[0];
105073
+ if (requestedApp === void 0) throw new UsageError(MCP_INSTALL_USAGE);
105074
+ const appValue = requestedApp === "claude" ? "claude-desktop" : requestedApp;
104322
105075
  if (!isMcpInstallApp(appValue)) {
104323
105076
  throw new UsageError(
104324
- `Unknown app ${JSON.stringify(appValue)}. Choose claude, cursor or codex.
105077
+ `Unknown app ${JSON.stringify(requestedApp)}. Choose claude-code, claude-desktop, cursor or codex.
104325
105078
  ${MCP_INSTALL_USAGE}`
104326
105079
  );
104327
105080
  }
105081
+ if (requestedApp === "claude") io.stderr(CLAUDE_ALIAS_NOTICE);
104328
105082
  const home = parsed.one("--home") ?? getVapiPaths().directory;
104329
105083
  const paths = getVapiPaths(home);
104330
105084
  const registry2 = parsed.one("--registry") ?? (await pathExists5(paths.config) ? registryBaseUrl(await readConfig(paths.config, io)) : resolveRegistryUrl());
105085
+ const offerLink = async () => {
105086
+ const name = await unlinkedDefaultAccount(home, dependencies);
105087
+ return name === void 0 ? {} : await offerDashboardLink({
105088
+ name,
105089
+ json: json2,
105090
+ noLink: parsed.has("--no-link"),
105091
+ io,
105092
+ dependencies,
105093
+ home,
105094
+ apiBase: parsed.one("--registry")
105095
+ });
105096
+ };
105097
+ const platform2 = dependencies.mcpInstall?.platform ?? process.platform;
105098
+ const entry = serverEntry(home, registry2);
105099
+ if (appValue === "claude-code") {
105100
+ return await installClaudeCode(entry, platform2, json2, io, dependencies, offerLink);
105101
+ }
104331
105102
  const target = mcpInstallTarget(appValue, {
104332
- platform: dependencies.mcpInstall?.platform ?? process.platform,
105103
+ platform: platform2,
104333
105104
  homedir: dependencies.mcpInstall?.homedir ?? systemHomedir(),
104334
105105
  cwd: dependencies.mcpInstall?.cwd ?? process.cwd(),
104335
105106
  appData: dependencies.mcpInstall?.appData ?? process.env.APPDATA
104336
105107
  });
104337
- const entry = serverEntry(home, registry2);
104338
105108
  const created = await writeMcpConfig(target, entry);
104339
- const name = await unlinkedDefaultAccount(home, dependencies);
104340
- const offerLink = (name2) => offerDashboardLink({
104341
- name: name2,
104342
- json: json2,
104343
- noLink: parsed.has("--no-link"),
104344
- io,
104345
- dependencies,
104346
- home,
104347
- apiBase: parsed.one("--registry")
104348
- });
104349
- const link3 = json2 && name !== void 0 ? await offerLink(name) : {};
105109
+ const link3 = json2 ? await offerLink() : {};
104350
105110
  output3(
104351
105111
  io,
104352
105112
  json2,
@@ -104355,8 +105115,9 @@ ${MCP_INSTALL_USAGE}`
104355
105115
  );
104356
105116
  if (!json2) {
104357
105117
  io.stdout(NEXT_STEP[appValue]);
104358
- if (name !== void 0) await offerLink(name);
105118
+ await offerLink();
104359
105119
  }
105120
+ return 0;
104360
105121
  }
104361
105122
  async function unlinkedDefaultAccount(home, dependencies) {
104362
105123
  try {
@@ -104370,6 +105131,131 @@ async function unlinkedDefaultAccount(home, dependencies) {
104370
105131
  }
104371
105132
  return void 0;
104372
105133
  }
105134
+ async function installClaudeCode(entry, platform2, json2, io, dependencies, offerLink) {
105135
+ const processCommand = platform2 === "win32" ? "claude.cmd" : "claude";
105136
+ const processArgs = claudeCodeArgs(entry);
105137
+ const command = platform2 === "win32" ? [escapeCmd(processCommand), ...processArgs.map(escapeCmdArgument)].join(" ") : displayCommand(processCommand, processArgs);
105138
+ let result;
105139
+ try {
105140
+ result = await (dependencies.mcpInstall?.runProcess ?? defaultMcpInstallProcess)(
105141
+ processCommand,
105142
+ processArgs
105143
+ );
105144
+ } catch (error61) {
105145
+ if (isErrorCode3(error61, "ENOENT")) {
105146
+ return claudeCodeFailure(json2, io, command, "claude_not_found", CLAUDE_NOT_FOUND);
105147
+ }
105148
+ const message = `Claude Code MCP installation failed: ${errorMessage2(error61)}`;
105149
+ return claudeCodeFailure(json2, io, command, "claude_mcp_add_failed", message);
105150
+ }
105151
+ if (result.exitCode !== 0) {
105152
+ 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}.`;
105153
+ const stderr2 = result.stderr.trim();
105154
+ const message = stderr2.length === 0 ? status : `${status} ${stderr2}`;
105155
+ return claudeCodeFailure(json2, io, command, "claude_mcp_add_failed", message, result.exitCode);
105156
+ }
105157
+ const nextStep = NEXT_STEP["claude-code"];
105158
+ const link3 = json2 ? await offerLink() : {};
105159
+ if (json2)
105160
+ io.stdout(JSON.stringify({ ...link3, app: "claude-code", installed: true, command, nextStep }));
105161
+ else {
105162
+ io.stdout(command);
105163
+ io.stdout(nextStep);
105164
+ await offerLink();
105165
+ }
105166
+ return 0;
105167
+ }
105168
+ function claudeCodeArgs(entry) {
105169
+ return [
105170
+ "mcp",
105171
+ "add",
105172
+ "--scope",
105173
+ "user",
105174
+ "vapi",
105175
+ "-e",
105176
+ `VAPI_HOME=${entry.env.VAPI_HOME}`,
105177
+ "-e",
105178
+ `VAPI_REGISTRY_URL=${entry.env.VAPI_REGISTRY_URL}`,
105179
+ "--",
105180
+ entry.command,
105181
+ ...entry.args
105182
+ ];
105183
+ }
105184
+ function claudeCodeFailure(json2, io, command, code, message, exitCode) {
105185
+ if (json2) {
105186
+ io.stdout(
105187
+ JSON.stringify({
105188
+ app: "claude-code",
105189
+ installed: false,
105190
+ command,
105191
+ error: { code, message, ...exitCode === void 0 ? {} : { exitCode } }
105192
+ })
105193
+ );
105194
+ } else if (code === "claude_not_found") {
105195
+ io.stderr(`${message}
105196
+ ${command}`);
105197
+ } else {
105198
+ io.stderr(`${command}
105199
+ ${message}`);
105200
+ }
105201
+ return 1;
105202
+ }
105203
+ function displayCommand(command, args) {
105204
+ return [command, ...args].map(shellQuote3).join(" ");
105205
+ }
105206
+ function shellQuote3(value) {
105207
+ return /^[A-Za-z0-9_@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
105208
+ }
105209
+ function isErrorCode3(error61, code) {
105210
+ return typeof error61 === "object" && error61 !== null && "code" in error61 && error61.code === code;
105211
+ }
105212
+ function errorMessage2(error61) {
105213
+ return error61 instanceof Error ? error61.message : String(error61);
105214
+ }
105215
+ var defaultMcpInstallProcess = async (command, args) => {
105216
+ const batch = /\.(?:cmd|bat)$/iu.test(command);
105217
+ const executable = batch ? await windowsBatchPath(command) : command;
105218
+ const commandLine = batch ? [escapeCmd(executable), ...args.map((arg) => escapeCmdArgument(arg))].join(" ") : void 0;
105219
+ return await new Promise((resolve4, reject) => {
105220
+ const child = spawn3(
105221
+ batch ? "cmd.exe" : command,
105222
+ batch ? ["/d", "/v:off", "/s", "/c", `"${commandLine}"`] : [...args],
105223
+ {
105224
+ shell: false,
105225
+ ...batch ? { windowsVerbatimArguments: true } : {},
105226
+ stdio: ["ignore", "pipe", "pipe"],
105227
+ timeout: 6e4,
105228
+ killSignal: "SIGKILL",
105229
+ windowsHide: true
105230
+ }
105231
+ );
105232
+ let stdout = "";
105233
+ let stderr2 = "";
105234
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
105235
+ stdout += chunk;
105236
+ });
105237
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
105238
+ stderr2 += chunk;
105239
+ });
105240
+ child.once("error", reject);
105241
+ child.once("close", (exitCode) => resolve4({ exitCode, stdout, stderr: stderr2 }));
105242
+ });
105243
+ };
105244
+ async function windowsBatchPath(command) {
105245
+ const path = Object.entries(process.env).find(([key2]) => key2.toLowerCase() === "path")?.[1];
105246
+ for (const directory of ["", ...(path ?? "").split(";")]) {
105247
+ const candidate = win322.join(directory.replace(/^"|"$/gu, ""), command);
105248
+ if (await pathExists5(candidate)) return candidate;
105249
+ }
105250
+ throw Object.assign(new Error(`${command} was not found on PATH.`), { code: "ENOENT" });
105251
+ }
105252
+ function escapeCmd(value) {
105253
+ return value.replace(/[()[\]%!^"`<>&|;, *?]/gu, "^$&");
105254
+ }
105255
+ function escapeCmdArgument(value) {
105256
+ const quoted = `"${value.replace(/(\\*)"/gu, '$1$1\\"').replace(/(\\*)$/u, "$1$1")}"`;
105257
+ return escapeCmd(escapeCmd(quoted));
105258
+ }
104373
105259
  function isMcpInstallApp(value) {
104374
105260
  return APPS.has(value);
104375
105261
  }
@@ -104403,13 +105289,13 @@ function jsonConfig(path, existing, entry) {
104403
105289
  } catch {
104404
105290
  throw new Error(`${path} is not valid JSON. Fix it by hand; nothing was written.`);
104405
105291
  }
104406
- if (!isRecord11(parsed)) {
105292
+ if (!isRecord12(parsed)) {
104407
105293
  throw new Error(`${path} must contain a JSON object. Fix it by hand; nothing was written.`);
104408
105294
  }
104409
105295
  config2 = parsed;
104410
105296
  }
104411
105297
  const existingServers = config2.mcpServers;
104412
- if (existingServers !== void 0 && !isRecord11(existingServers)) {
105298
+ if (existingServers !== void 0 && !isRecord12(existingServers)) {
104413
105299
  throw new Error(
104414
105300
  `${path} has an invalid mcpServers value. Fix it by hand; nothing was written.`
104415
105301
  );
@@ -104421,7 +105307,10 @@ function jsonConfig(path, existing, entry) {
104421
105307
  `;
104422
105308
  }
104423
105309
  function tomlConfig(existing, entry) {
104424
- const retained = removeVapiTomlTables(existing);
105310
+ const retained = removeTomlTables(
105311
+ existing,
105312
+ ([root, name]) => root === "mcp_servers" && name === "vapi"
105313
+ );
104425
105314
  const block = [
104426
105315
  "[mcp_servers.vapi]",
104427
105316
  'command = "npx"',
@@ -104431,64 +105320,564 @@ function tomlConfig(existing, entry) {
104431
105320
  ].join("\n");
104432
105321
  return `${retained}${tomlSeparator(retained)}${block}`;
104433
105322
  }
104434
- function removeVapiTomlTables(contents) {
104435
- const lines = contents.match(/[^\n]*\n|[^\n]+$/g) ?? [];
104436
- let removing = false;
104437
- let retained = "";
104438
- for (const line of lines) {
104439
- const table = tomlTableName(line);
104440
- if (table !== void 0) removing = isVapiTomlTable(table);
104441
- if (!removing) retained += line;
104442
- }
104443
- return retained;
105323
+ function isRecord12(value) {
105324
+ return typeof value === "object" && value !== null && !Array.isArray(value);
104444
105325
  }
104445
- function tomlTableName(line) {
104446
- const header = line.replace(/\r?\n$/, "");
104447
- const match = /^\s*(?:\[\[\s*(.*?)\s*\]\]|\[\s*(.*?)\s*\])\s*(?:#.*)?$/.exec(header);
104448
- return match?.[1] ?? match?.[2];
105326
+ async function readExistingFile(path) {
105327
+ try {
105328
+ return await readFile28(path, "utf8");
105329
+ } catch (error61) {
105330
+ if (isMissingFile(error61)) return void 0;
105331
+ throw error61;
105332
+ }
104449
105333
  }
104450
- function isVapiTomlTable(table) {
104451
- const key2 = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
104452
- const match = new RegExp(`^\\s*(${key2})\\s*\\.\\s*(${key2})(?:\\s*\\.|\\s*$)`).exec(table);
104453
- if (match === null) return false;
104454
- return unquoteTomlKey(match[1]) === "mcp_servers" && unquoteTomlKey(match[2]) === "vapi";
105334
+ async function pathExists5(path) {
105335
+ try {
105336
+ await readFile28(path);
105337
+ return true;
105338
+ } catch (error61) {
105339
+ if (isMissingFile(error61)) return false;
105340
+ throw error61;
105341
+ }
104455
105342
  }
104456
- function unquoteTomlKey(key2) {
104457
- if (key2.startsWith("'") && key2.endsWith("'")) return key2.slice(1, -1);
104458
- if (key2.startsWith('"') && key2.endsWith('"')) {
105343
+
105344
+ // ../cli/src/code.ts
105345
+ import { constants as constants2 } from "node:fs";
105346
+ import { access, mkdir as mkdir21, readFile as readFile29, realpath, unlink as unlink13, writeFile as writeFile12 } from "node:fs/promises";
105347
+ import { homedir as homedir3 } from "node:os";
105348
+ import { basename as basename5, dirname as dirname15, join as join27, posix as posix2, win32 as win323 } from "node:path";
105349
+ var VAPI_CODEX_PROVIDER = "vapi";
105350
+ var VAPI_CODEX_PROFILE = "vapi";
105351
+ var VAPI_CODEX_DEFAULT_MODEL = "venice/openai-gpt-61-sol";
105352
+ var VAPI_ROUTER_KEY_ENV = "VAPI_ROUTER_KEY";
105353
+ function codexConfigPath(env, home) {
105354
+ return join27(env.CODEX_HOME || join27(home, ".codex"), "config.toml");
105355
+ }
105356
+ function hasVapiCodexProfile(contents) {
105357
+ const roots = new Set(
105358
+ [...tomlLines(contents)].flatMap(({ table }) => {
105359
+ const path = table === void 0 ? [] : tomlKeyPath(table);
105360
+ return path.length === 2 && path[1] === "vapi" ? [path[0]] : [];
105361
+ })
105362
+ );
105363
+ return roots.has("model_providers") && roots.has("profiles");
105364
+ }
105365
+ async function resolveBinary(name, options) {
105366
+ const windows = (options.platform ?? process.platform) === "win32";
105367
+ const path = options.env.PATH ?? (windows ? Object.entries(options.env).find(([key2]) => key2.toLowerCase() === "path")?.[1] : void 0);
105368
+ if (path === void 0) return void 0;
105369
+ const paths = windows ? win323 : posix2;
105370
+ const canonical = options.realpath ?? realpath;
105371
+ const executable = options.isExecutable ?? (async (candidate) => {
104459
105372
  try {
104460
- return JSON.parse(key2);
104461
- } catch {
104462
- return key2;
105373
+ await access(candidate, constants2.X_OK);
105374
+ return true;
105375
+ } catch (error61) {
105376
+ if (isMissingFile(error61) || error61.code === "EACCES")
105377
+ return false;
105378
+ throw error61;
105379
+ }
105380
+ });
105381
+ const self = options.selfPath ?? process.argv[1];
105382
+ const selfReal = self === void 0 ? void 0 : await canonical(self);
105383
+ const extensions = windows ? ["", ...(options.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";")] : [""];
105384
+ for (const directory of path.split(windows ? ";" : ":")) {
105385
+ for (const extension of extensions) {
105386
+ const candidate = paths.resolve(directory.replace(/^"|"$/gu, ""), `${name}${extension}`);
105387
+ if (!await executable(candidate)) continue;
105388
+ const resolved = await canonical(candidate);
105389
+ if (selfReal !== void 0 && (windows ? resolved.toLowerCase() === selfReal.toLowerCase() : resolved === selfReal))
105390
+ continue;
105391
+ return candidate;
104463
105392
  }
104464
105393
  }
104465
- return key2;
105394
+ return void 0;
104466
105395
  }
104467
- function tomlSeparator(contents) {
104468
- if (contents.length === 0 || /(?:\r?\n)[ \t]*(?:\r?\n)$/.test(contents)) return "";
104469
- return /\r?\n$/.test(contents) ? "\n" : "\n\n";
105396
+ var RC_START = "# >>> vapi code >>>";
105397
+ var RC_END = "# <<< vapi code <<<";
105398
+ var CONFIG_END = "# <<< vapi code config <<<\n";
105399
+ var isCodeTable = ([root, name]) => name === "vapi" && (root === "model_providers" || root === "profiles");
105400
+ function cleanConfig(contents) {
105401
+ let created = false;
105402
+ const cleaned = contents.replace(
105403
+ /(\n?)\[model_providers\.vapi\]\n# >>> vapi code config (created|existing) (0|1) >>>\n([\s\S]*?)# <<< vapi code config <<<\n/gu,
105404
+ (_, prefix, kind, separator, body) => {
105405
+ created ||= kind === "created";
105406
+ return (separator === "1" ? "" : prefix) + removeTomlTables(`[model_providers.vapi]
105407
+ ${body}`, isCodeTable);
105408
+ }
105409
+ );
105410
+ return { contents: removeTomlTables(cleaned, isCodeTable), created };
105411
+ }
105412
+ function configContents(existing, baseURL) {
105413
+ const clean2 = cleanConfig(existing ?? "");
105414
+ const retained = clean2.contents;
105415
+ const separator = retained.length > 0 && !retained.endsWith("\n") ? "\n" : "";
105416
+ return `${retained}${separator}[model_providers.vapi]
105417
+ # >>> vapi code config ${existing === void 0 || clean2.created ? "created" : "existing"} ${separator.length} >>>
105418
+ ` + [
105419
+ 'name = "vAPI Router"',
105420
+ `base_url = "${escapeToml(baseURL)}"`,
105421
+ `env_key = "${VAPI_ROUTER_KEY_ENV}"`,
105422
+ 'wire_api = "responses"',
105423
+ "",
105424
+ "[profiles.vapi]",
105425
+ `model_provider = "${VAPI_CODEX_PROVIDER}"`,
105426
+ `model = "${VAPI_CODEX_DEFAULT_MODEL}"`,
105427
+ ""
105428
+ ].join("\n") + CONFIG_END;
104470
105429
  }
104471
- function escapeToml(value) {
104472
- return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
105430
+ function removeAliases(contents) {
105431
+ return contents.replace(
105432
+ /(^|\n)# >>> vapi code >>>\r?\n[\s\S]*?^# <<< vapi code <<<(\r?\n|$)/gmu,
105433
+ (_, prefix, suffix) => suffix === "" ? "" : prefix
105434
+ );
104473
105435
  }
104474
- function isRecord11(value) {
104475
- return typeof value === "object" && value !== null && !Array.isArray(value);
105436
+ function aliasContents(original, tools) {
105437
+ const existing = original ?? "";
105438
+ const block = [RC_START, ...tools.map((tool) => `alias ${tool}="vapi ${tool}"`), RC_END].join(
105439
+ "\n"
105440
+ );
105441
+ const match = /^# >>> vapi code >>>\r?\n[\s\S]*?^# <<< vapi code <<</gmu;
105442
+ if (match.test(existing)) return existing.replace(match, block);
105443
+ const separator = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
105444
+ return `${existing}${separator}${block}${original === "" || existing.endsWith("\n") ? "\n" : ""}`;
104476
105445
  }
104477
- async function readExistingFile(path) {
105446
+ async function readOptional(path) {
104478
105447
  try {
104479
- return await readFile28(path, "utf8");
105448
+ return await readFile29(path, "utf8");
104480
105449
  } catch (error61) {
104481
105450
  if (isMissingFile(error61)) return void 0;
104482
105451
  throw error61;
104483
105452
  }
104484
105453
  }
104485
- async function pathExists5(path) {
105454
+ async function writeConfig(path, contents) {
105455
+ await mkdir21(dirname15(path), { recursive: true });
105456
+ await writeFile12(path, contents);
105457
+ }
105458
+ async function codeCommand(argv, json2, io, dependencies) {
105459
+ const command = argv[0];
105460
+ if (command !== "install" && command !== "uninstall")
105461
+ throw new UsageError("Usage: vapi code <install|uninstall>.");
105462
+ const parsed = parseArguments(argv.slice(1), {
105463
+ valueOptions: new Set(command === "install" ? ["--wallet"] : []),
105464
+ booleanOptions: new Set(command === "install" ? ["--yes", "--no-alias"] : []),
105465
+ maximumPositionals: 0
105466
+ });
105467
+ const env = getEnvironment(dependencies);
105468
+ const home = dependencies.code?.homedir ?? homedir3();
105469
+ const config2 = codexConfigPath(env, home);
105470
+ const rcPaths = [join27(home, ".zshrc"), join27(home, ".bashrc")];
105471
+ if (command === "uninstall") {
105472
+ const removed = [];
105473
+ const previous = await readOptional(config2);
105474
+ if (previous !== void 0) {
105475
+ const clean2 = cleanConfig(previous);
105476
+ if (clean2.contents !== previous) {
105477
+ if (clean2.contents === "" && clean2.created) await unlink13(config2);
105478
+ else await writeFile12(config2, clean2.contents);
105479
+ removed.push(config2);
105480
+ }
105481
+ }
105482
+ for (const path of rcPaths) {
105483
+ const previous2 = await readOptional(path);
105484
+ if (previous2 === void 0) continue;
105485
+ const clean2 = removeAliases(previous2);
105486
+ if (clean2 !== previous2) {
105487
+ if (clean2 === "" && previous2.startsWith(RC_START) && !previous2.endsWith("\n"))
105488
+ await unlink13(path);
105489
+ else await writeFile12(path, clean2);
105490
+ removed.push(path);
105491
+ }
105492
+ }
105493
+ io.stdout(
105494
+ json2 ? JSON.stringify({ command: "code uninstall", removed }) : removed.length === 0 ? "Nothing to remove." : `Removed vAPI code settings from: ${removed.join(", ")}`
105495
+ );
105496
+ return 0;
105497
+ }
105498
+ const tools = [];
105499
+ const skipped2 = [];
105500
+ for (const name of ["claude", "codex"]) {
105501
+ const binary = await resolveBinary(name, { ...dependencies.code, env });
105502
+ if (binary === void 0)
105503
+ skipped2.push(
105504
+ `Skipped ${name === "claude" ? "Claude Code" : "Codex"}: \`${name}\` is not on PATH.`
105505
+ );
105506
+ else tools.push(name);
105507
+ }
105508
+ if (tools.length === 0) {
105509
+ const message = "Neither claude nor codex is on PATH; nothing was installed.";
105510
+ if (json2) io.stdout(JSON.stringify({ installed: [], skipped: skipped2, error: message }));
105511
+ else {
105512
+ skipped2.forEach(io.stderr);
105513
+ io.stderr(message);
105514
+ }
105515
+ return 1;
105516
+ }
105517
+ let target = await targetWallet(parsed, dependencies);
105518
+ const credentials = dependencies.router?.routerCredentials ?? routerCredentials;
105519
+ let linked = false;
105520
+ let rotated = false;
105521
+ let result;
105522
+ for (; ; ) {
105523
+ try {
105524
+ result = await credentials(routerDeps2(target, dependencies));
105525
+ break;
105526
+ } catch (error61) {
105527
+ if (error61 instanceof RouterClientError && error61.code === "not_linked" && !linked) {
105528
+ linked = true;
105529
+ const account = parsed.one("--wallet");
105530
+ await (dependencies.code?.login ?? runLoginFlow)(
105531
+ account === void 0 ? [] : ["--account", account],
105532
+ json2,
105533
+ { ...io, stdout: io.stderr },
105534
+ json2 ? { ...dependencies, interactive: false, stdinIsTTY: false } : dependencies
105535
+ );
105536
+ target = await targetWallet(parsed, dependencies);
105537
+ } else if (error61 instanceof RouterClientError && error61.code === "no_router_key" && !rotated) {
105538
+ rotated = true;
105539
+ await (dependencies.router?.rotateRouterKey ?? rotateRouterKey)(
105540
+ routerDeps2(target, dependencies)
105541
+ );
105542
+ } else throw error61;
105543
+ }
105544
+ }
105545
+ const installed = [];
105546
+ if (tools.includes("claude")) installed.push("Claude Code: ready, launch with `vapi claude`");
105547
+ if (tools.includes("codex")) {
105548
+ await writeConfig(config2, configContents(await readOptional(config2), result.baseURL));
105549
+ installed.push(`Codex: installed ${config2}`);
105550
+ }
105551
+ let alias = "Aliases: skipped.";
105552
+ if (!parsed.has("--no-alias")) {
105553
+ if ((dependencies.code?.platform ?? process.platform) === "win32")
105554
+ alias = "Aliases: skipped on Windows.";
105555
+ else {
105556
+ const yes = parsed.has("--yes") || !json2 && isInteractive(dependencies) && isStdinInteractive(dependencies) && /^y(?:es)?$/iu.test(
105557
+ (await getLinePrompt(dependencies)(
105558
+ "Make `claude` and `codex` use your vAPI Compute first from now on? [y/N] "
105559
+ )).trim()
105560
+ );
105561
+ if (yes) {
105562
+ const shell = basename5(env.SHELL ?? "");
105563
+ const rc = shell === "zsh" ? rcPaths[0] : shell === "bash" ? rcPaths[1] : await readOptional(rcPaths[0]) !== void 0 ? rcPaths[0] : rcPaths[1];
105564
+ await writeConfig(rc, aliasContents(await readOptional(rc), tools));
105565
+ alias = `Aliases: installed in ${rc}. Open a new terminal or run: source ${rc}`;
105566
+ }
105567
+ }
105568
+ }
105569
+ let compute;
104486
105570
  try {
104487
- await readFile28(path);
104488
- return true;
105571
+ const usage = await (dependencies.router?.routerUsage ?? routerUsage)(
105572
+ routerDeps2(target, dependencies)
105573
+ );
105574
+ const reset = new Date(usage.compute.resetsAt);
105575
+ if (!Number.isFinite(reset.getTime())) throw new Error("invalid reset time");
105576
+ compute = `$${usage.compute.remainingTodayUsd.toFixed(2)} left today (resets ${reset.toISOString().slice(11, 16)} UTC)`;
104489
105577
  } catch (error61) {
104490
- if (isMissingFile(error61)) return false;
104491
- throw error61;
105578
+ compute = `Compute today: unavailable (${error61 instanceof RouterClientError ? error61.code : "request failed"})`;
105579
+ }
105580
+ const start = `Start with \`vapi ${tools.includes("claude") ? "claude" : "codex"}\``;
105581
+ if (json2)
105582
+ io.stdout(
105583
+ JSON.stringify({ command: "code install", installed, skipped: skipped2, alias, compute, start })
105584
+ );
105585
+ else {
105586
+ skipped2.forEach(io.stderr);
105587
+ [...installed, alias, compute, start].forEach(io.stdout);
105588
+ }
105589
+ return 0;
105590
+ }
105591
+
105592
+ // ../cli/src/code-launch.ts
105593
+ import { spawn as spawn4 } from "node:child_process";
105594
+ import { readFile as readFile30 } from "node:fs/promises";
105595
+ import { constants as constants3, homedir as homedir4 } from "node:os";
105596
+ var CLAUDE_MODELS = {
105597
+ sonnet: "venice/claude-sonnet-5-5",
105598
+ opus: "venice/claude-opus-5-5",
105599
+ haiku: "venice/claude-haiku-5-5"
105600
+ };
105601
+ async function claudeCommand(argv, json2, io, dependencies) {
105602
+ return await launch("claude", argv, json2, io, dependencies);
105603
+ }
105604
+ async function codexCommand(argv, json2, io, dependencies) {
105605
+ return await launch("codex", argv, json2, io, dependencies);
105606
+ }
105607
+ function parseLaunch(argv) {
105608
+ const result = { own: false, vapi: false, balance: false, forwarded: [] };
105609
+ for (let index2 = 0; index2 < argv.length; index2 += 1) {
105610
+ const arg = argv[index2];
105611
+ if (arg === "--") {
105612
+ result.forwarded.push(...argv.slice(index2 + 1));
105613
+ break;
105614
+ }
105615
+ if (arg === "--own") result.own = true;
105616
+ else if (arg === "--vapi") result.vapi = true;
105617
+ else if (arg === "--use-balance") result.balance = true;
105618
+ else if (arg === "--model" || arg === "--account") {
105619
+ const value = argv[++index2];
105620
+ if (!value || value.startsWith("--")) throw new UsageError(`Expected ${arg} <value>.`);
105621
+ if (arg === "--model") result.model = value;
105622
+ else result.account = value;
105623
+ } else result.forwarded.push(arg);
105624
+ }
105625
+ if (result.own && result.vapi) throw new UsageError("--vapi and --own cannot be used together.");
105626
+ return result;
105627
+ }
105628
+ var LaunchTimeout = class extends Error {
105629
+ constructor() {
105630
+ super("timed out");
105631
+ }
105632
+ };
105633
+ async function bounded(operation, milliseconds) {
105634
+ const controller = new AbortController();
105635
+ let timer;
105636
+ try {
105637
+ return await Promise.race([
105638
+ new Promise((_resolve, reject) => {
105639
+ timer = setTimeout(() => {
105640
+ const error61 = new LaunchTimeout();
105641
+ controller.abort(error61);
105642
+ reject(error61);
105643
+ }, milliseconds);
105644
+ }),
105645
+ operation(controller.signal)
105646
+ ]);
105647
+ } finally {
105648
+ clearTimeout(timer);
105649
+ controller.abort();
105650
+ }
105651
+ }
105652
+ function abortableDeps(deps, signal) {
105653
+ const fetchImpl = deps.fetchImpl ?? createPublicFetch({ allowPrivateNetwork: false });
105654
+ return {
105655
+ ...deps,
105656
+ fetchImpl: (input2, init) => fetchImpl(input2, {
105657
+ ...init,
105658
+ signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal
105659
+ })
105660
+ };
105661
+ }
105662
+ function shortReason(error61, env, credentials) {
105663
+ if (error61 instanceof RouterClientError) {
105664
+ if (error61.code === "not_linked") return "not linked, run vapi code install";
105665
+ if (error61.code === "no_router_key") return "no Router key, run vapi code install";
105666
+ }
105667
+ let message = error61 instanceof Error ? error61.message : String(error61);
105668
+ for (const secret of [
105669
+ credentials?.apiKey,
105670
+ env.ANTHROPIC_API_KEY,
105671
+ env.ANTHROPIC_AUTH_TOKEN,
105672
+ env[VAPI_ROUTER_KEY_ENV]
105673
+ ]) {
105674
+ if (secret) message = message.replaceAll(secret, "[redacted]");
105675
+ }
105676
+ return message.replace(/\s+/gu, " ").trim().slice(0, 160) || "request failed";
105677
+ }
105678
+ async function chooseRoute(options, env, dependencies) {
105679
+ if (options.own) return { kind: "own" };
105680
+ const timeout = dependencies.code?.usageTimeoutMs ?? 4e3;
105681
+ let credentials;
105682
+ let deps;
105683
+ let balanceKeyRequired = false;
105684
+ try {
105685
+ credentials = await bounded(async (signal) => {
105686
+ const target = await targetWallet(
105687
+ { one: (name) => name === "--wallet" ? options.account : void 0 },
105688
+ dependencies,
105689
+ env.VAPI_HOME
105690
+ );
105691
+ signal.throwIfAborted();
105692
+ deps = routerDeps2(target, dependencies);
105693
+ return await (dependencies.router?.routerCredentials ?? routerCredentials)(
105694
+ abortableDeps(deps, signal)
105695
+ );
105696
+ }, timeout);
105697
+ let usage;
105698
+ try {
105699
+ usage = await bounded(
105700
+ (signal) => (dependencies.router?.routerUsage ?? routerUsage)(abortableDeps(deps, signal)),
105701
+ timeout
105702
+ );
105703
+ if (!Number.isFinite(new Date(usage.compute.resetsAt).getTime()))
105704
+ throw new Error("invalid Compute reset time");
105705
+ } catch (error61) {
105706
+ if (options.vapi) return { kind: "vapi", credentials };
105707
+ throw error61;
105708
+ }
105709
+ if (options.vapi || remaining(usage, options.balance) >= 0.5) {
105710
+ if (options.balance && usage.compute.remainingTodayUsd < 0.5 && (usage.balance?.remainingUsd ?? 0) > 0) {
105711
+ balanceKeyRequired = true;
105712
+ credentials = await bounded(
105713
+ (signal) => (dependencies.router?.routerCredentials ?? routerCredentials)(
105714
+ abortableDeps(deps, signal),
105715
+ { funding: "balance" }
105716
+ ),
105717
+ timeout
105718
+ );
105719
+ }
105720
+ return { kind: "vapi", credentials, usage };
105721
+ }
105722
+ return { kind: "own", exhausted: true };
105723
+ } catch (error61) {
105724
+ const reason = balanceKeyRequired && error61 instanceof RouterClientError && error61.code === "no_router_key" ? "no Router balance key is stored" : shortReason(error61, env, credentials);
105725
+ if (options.vapi) return { kind: "unavailable", reason };
105726
+ return { kind: "own", reason };
105727
+ }
105728
+ }
105729
+ function remaining(usage, useBalance) {
105730
+ return usage.compute.remainingTodayUsd + (useBalance ? usage.balance?.remainingUsd ?? 0 : 0);
105731
+ }
105732
+ async function launch(tool, argv, json2, io, dependencies) {
105733
+ if (json2) throw new UsageError(`vapi ${tool} is interactive and does not support --json.`);
105734
+ const options = parseLaunch(argv);
105735
+ const env = getEnvironment(dependencies);
105736
+ let binary;
105737
+ try {
105738
+ binary = await resolveBinary(tool, { ...dependencies.code, env });
105739
+ } catch (error61) {
105740
+ io.stderr(shortReason(error61, env));
105741
+ return 127;
105742
+ }
105743
+ if (binary === void 0) {
105744
+ io.stderr(
105745
+ `\`${tool}\` is not on PATH. Install ${tool === "claude" ? "Claude Code" : "Codex"} first.`
105746
+ );
105747
+ return 127;
105748
+ }
105749
+ const route = await chooseRoute(options, env, dependencies);
105750
+ if (route.kind === "unavailable") {
105751
+ io.stderr(route.reason);
105752
+ return 1;
105753
+ }
105754
+ let args = options.forwarded;
105755
+ let childEnv = env;
105756
+ const own2 = tool === "claude" ? "your own Claude subscription" : "your own Codex/ChatGPT login";
105757
+ if (route.kind === "own") {
105758
+ if (route.exhausted) io.stderr(`\u25CF Compute used up today \u2192 ${own2}`);
105759
+ else if (route.reason !== void 0) io.stderr(`\u25CF vAPI unreachable (${route.reason}) \u2192 ${own2}`);
105760
+ if (options.model !== void 0)
105761
+ args = [tool === "claude" ? "--model" : "-m", options.model, ...args];
105762
+ } else {
105763
+ const { credentials, usage } = route;
105764
+ const model = tool === "claude" ? claudeModel(options.model) : options.model ?? VAPI_CODEX_DEFAULT_MODEL;
105765
+ let status = "\u25CF vAPI Compute";
105766
+ if (usage !== void 0)
105767
+ status += ` \u2014 $${remaining(usage, options.balance).toFixed(2)} left today (resets ${new Date(usage.compute.resetsAt).toISOString().slice(11, 16)} UTC)`;
105768
+ io.stderr(`${status} \xB7 model ${model.slice(model.lastIndexOf("/") + 1)}`);
105769
+ io.stderr(
105770
+ tool === "claude" ? " Compute runs out mid-session? /exit, then: vapi claude --continue" : " Compute runs out mid-session? /quit, then: vapi codex resume --last"
105771
+ );
105772
+ if (tool === "claude") {
105773
+ childEnv = {
105774
+ ...env,
105775
+ ANTHROPIC_BASE_URL: credentials.baseURL.replace(/\/v1\/?$/u, ""),
105776
+ ANTHROPIC_AUTH_TOKEN: credentials.apiKey
105777
+ };
105778
+ delete childEnv.ANTHROPIC_API_KEY;
105779
+ if (args.some((arg) => arg === "--settings" || arg.startsWith("--settings=")))
105780
+ io.stderr("\u25CF Your --settings is passed as is; vAPI model settings were not added.");
105781
+ else
105782
+ args = [
105783
+ "--settings",
105784
+ JSON.stringify({
105785
+ env: {
105786
+ ANTHROPIC_MODEL: model,
105787
+ ANTHROPIC_DEFAULT_SONNET_MODEL: CLAUDE_MODELS.sonnet,
105788
+ ANTHROPIC_DEFAULT_OPUS_MODEL: CLAUDE_MODELS.opus,
105789
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: CLAUDE_MODELS.haiku,
105790
+ CLAUDE_CODE_MAX_RETRIES: "2"
105791
+ }
105792
+ }),
105793
+ ...args
105794
+ ];
105795
+ } else {
105796
+ childEnv = { ...env, [VAPI_ROUTER_KEY_ENV]: credentials.apiKey };
105797
+ args = [...await codexArgs(env, credentials.baseURL, options.model, dependencies), ...args];
105798
+ }
105799
+ }
105800
+ return await runChild(binary, args, childEnv, io, dependencies);
105801
+ }
105802
+ function claudeModel(model) {
105803
+ return model === void 0 ? CLAUDE_MODELS.sonnet : Object.hasOwn(CLAUDE_MODELS, model) ? CLAUDE_MODELS[model] : model;
105804
+ }
105805
+ async function codexArgs(env, baseURL, model, dependencies) {
105806
+ let contents = "";
105807
+ try {
105808
+ contents = await readFile30(
105809
+ codexConfigPath(env, dependencies.code?.homedir ?? homedir4()),
105810
+ "utf8"
105811
+ );
105812
+ } catch (error61) {
105813
+ if (!isMissingFile(error61)) throw error61;
105814
+ }
105815
+ const providerArgs = [
105816
+ "-c",
105817
+ `model_providers.${VAPI_CODEX_PROVIDER}.name="vAPI Router"`,
105818
+ "-c",
105819
+ `model_providers.${VAPI_CODEX_PROVIDER}.base_url=${JSON.stringify(baseURL)}`,
105820
+ "-c",
105821
+ `model_providers.${VAPI_CODEX_PROVIDER}.env_key="${VAPI_ROUTER_KEY_ENV}"`,
105822
+ "-c",
105823
+ `model_providers.${VAPI_CODEX_PROVIDER}.wire_api="responses"`,
105824
+ "-c",
105825
+ `model_provider="${VAPI_CODEX_PROVIDER}"`
105826
+ ];
105827
+ if (hasVapiCodexProfile(contents))
105828
+ return [
105829
+ "--profile",
105830
+ VAPI_CODEX_PROFILE,
105831
+ ...providerArgs,
105832
+ ...model === void 0 ? [] : ["-m", model]
105833
+ ];
105834
+ return [...providerArgs, "-m", model ?? VAPI_CODEX_DEFAULT_MODEL];
105835
+ }
105836
+ async function runChild(binary, args, env, io, dependencies) {
105837
+ const signals = dependencies.code?.processSignals ?? process;
105838
+ let child;
105839
+ const ignore = () => {
105840
+ };
105841
+ const forward = (signal) => () => {
105842
+ try {
105843
+ child?.kill(signal);
105844
+ } catch (error61) {
105845
+ io.stderr(shortReason(error61, env));
105846
+ }
105847
+ };
105848
+ const listeners = [
105849
+ ["SIGINT", ignore],
105850
+ ["SIGQUIT", ignore],
105851
+ ["SIGTERM", forward("SIGTERM")],
105852
+ ["SIGHUP", forward("SIGHUP")]
105853
+ ];
105854
+ try {
105855
+ for (const [signal, listener] of listeners) signals.on(signal, listener);
105856
+ return await new Promise((resolve4) => {
105857
+ let settled = false;
105858
+ const finish = (code) => {
105859
+ if (!settled) {
105860
+ settled = true;
105861
+ resolve4(code);
105862
+ }
105863
+ };
105864
+ try {
105865
+ child = (dependencies.code?.spawn ?? spawn4)(binary, args, { env, stdio: "inherit" });
105866
+ child.once("error", (error61) => {
105867
+ if (!settled) io.stderr(shortReason(error61, env));
105868
+ finish(127);
105869
+ });
105870
+ child.once(
105871
+ "exit",
105872
+ (code, signal) => finish(code ?? (signal === null ? 1 : 128 + (constants3.signals[signal] ?? 0)))
105873
+ );
105874
+ } catch (error61) {
105875
+ io.stderr(shortReason(error61, env));
105876
+ finish(127);
105877
+ }
105878
+ });
105879
+ } finally {
105880
+ for (const [signal, listener] of listeners) signals.removeListener(signal, listener);
104492
105881
  }
104493
105882
  }
104494
105883
 
@@ -104590,8 +105979,8 @@ async function sendConfig(dependencies) {
104590
105979
  }
104591
105980
 
104592
105981
  // ../cli/src/setup.ts
104593
- import { rm as rm5 } from "node:fs/promises";
104594
- import { join as join26 } from "node:path";
105982
+ import { rm as rm6 } from "node:fs/promises";
105983
+ import { join as join28 } from "node:path";
104595
105984
  var SETUP_ARGUMENT_ERROR = `vapi setup accepts only --no-cloud-backup and --accounts <n> (1-${MAX_RESTORE_ACCOUNTS}); a recovery phrase is typed at the prompt, never passed on the command line.`;
104596
105985
  var VAULT_CHOICE = "Create a new vault, or restore one from a recovery phrase? [new/restore] ";
104597
105986
  async function setupCommand(argv, json2, io, dependencies) {
@@ -104621,7 +106010,7 @@ async function setupCommand(argv, json2, io, dependencies) {
104621
106010
  let changedAccount = false;
104622
106011
  let changedLink = false;
104623
106012
  let scannedAddresses;
104624
- if (!await fileExists2(join26(paths.directory, "vault.json"))) {
106013
+ if (!await fileExists2(join28(paths.directory, "vault.json"))) {
104625
106014
  const choice = await vaultChoice(dependencies);
104626
106015
  if (choice === "restore") {
104627
106016
  if (!isInteractive(dependencies)) {
@@ -104709,7 +106098,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
104709
106098
  let scannedAddresses = 0;
104710
106099
  try {
104711
106100
  const restored = await restoreVault({
104712
- path: join26(paths.directory, "vault.json"),
106101
+ path: join28(paths.directory, "vault.json"),
104713
106102
  key: key2,
104714
106103
  phrase: validatedPhrase,
104715
106104
  probe: async (address4) => await readBalance3(address4) > 0n,
@@ -104720,7 +106109,7 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, account
104720
106109
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
104721
106110
  });
104722
106111
  names = restored.accounts().map((account) => account.name);
104723
- await rm5(join26(paths.directory, "wallets.json"), { force: true });
106112
+ await rm6(join28(paths.directory, "wallets.json"), { force: true });
104724
106113
  } finally {
104725
106114
  key2.fill(0);
104726
106115
  }
@@ -104838,7 +106227,7 @@ async function withRouterError2(operation) {
104838
106227
 
104839
106228
  // ../cli/src/task.ts
104840
106229
  import { randomUUID as randomUUID6 } from "node:crypto";
104841
- import { readFile as readFile29 } from "node:fs/promises";
106230
+ import { readFile as readFile31 } from "node:fs/promises";
104842
106231
  var TASK_HELP = `Usage:
104843
106232
  vapi task search [--open] [--min <usd>] [--tab trending|new|closing|paid] [--limit <n>] [--json]
104844
106233
  vapi task show <id> [--account <name>] [--json]
@@ -105174,7 +106563,7 @@ async function taskCommandInner(argv, json2, io, dependencies) {
105174
106563
  if (maxAwards !== void 0 && maxAwards > TASK_LIMITS.maxAwardsMax)
105175
106564
  throw new UsageError("--max-awards must be between 1 and 50.");
105176
106565
  if (parsed.one("--webhook") !== void 0) httpsUrl2(parsed.one("--webhook"), "--webhook");
105177
- const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile29(briefPath, "utf8");
106566
+ const brief = briefPath === "-" ? await (dependencies.readStdin ?? readProcessStdin2)() : await readFile31(briefPath, "utf8");
105178
106567
  const input2 = {
105179
106568
  title: title.trim(),
105180
106569
  description: brief.trim(),
@@ -105760,13 +107149,13 @@ async function watchTask(id2, parsed, json2, io, dependencies, now) {
105760
107149
  }
105761
107150
  }
105762
107151
  cursor2 = Math.max(cursor2, page.nextAfter, ...events.map((event) => event.sequence));
105763
- const remaining = deadline - clock().getTime();
105764
- if (remaining <= 0)
107152
+ const remaining2 = deadline - clock().getTime();
107153
+ if (remaining2 <= 0)
105765
107154
  throw new TaskCommandError(
105766
107155
  "timeout",
105767
107156
  `Task watch timed out after ${parsed.one("--timeout") ?? "7d"}.`
105768
107157
  );
105769
- await context.sleep(Math.min(interval, remaining));
107158
+ await context.sleep(Math.min(interval, remaining2));
105770
107159
  }
105771
107160
  }
105772
107161
  function expandDeliveryFiles(argv) {
@@ -106852,7 +108241,7 @@ async function referencedSleep(milliseconds, signal) {
106852
108241
  }
106853
108242
 
106854
108243
  // ../cli/src/vault.ts
106855
- import { join as join27 } from "node:path";
108244
+ import { join as join29 } from "node:path";
106856
108245
  var VAULT_USAGE = "Usage: vapi vault protect|unprotect|lock|unlock|status [--json]";
106857
108246
  var RESTORE_USAGE = "Usage: vapi restore [--accounts <n> | --from-owner [--owner <0x\u2026>]] [--json]";
106858
108247
  var LEGACY_PASSWORD_NOTICE = "VAPI_KEYSTORE_PASSWORD is deprecated for vault passwords; use VAPI_VAULT_PASSWORD instead.";
@@ -106896,7 +108285,7 @@ async function restoreCommand(argv, json2, io, dependencies) {
106896
108285
  }
106897
108286
  const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
106898
108287
  const paths = getVapiPaths();
106899
- const path = join27(paths.directory, "vault.json");
108288
+ const path = join29(paths.directory, "vault.json");
106900
108289
  if (await fileExists2(path)) {
106901
108290
  throw new Error(
106902
108291
  `A vault already exists in ${paths.directory}. Move it aside before restoring.`
@@ -107053,7 +108442,7 @@ function requireNoArguments(argv) {
107053
108442
  parseArguments(argv, { valueOptions: /* @__PURE__ */ new Set(), maximumPositionals: 0 });
107054
108443
  }
107055
108444
  function vaultPath() {
107056
- return join27(getVapiPaths().directory, "vault.json");
108445
+ return join29(getVapiPaths().directory, "vault.json");
107057
108446
  }
107058
108447
  function quietIo(io) {
107059
108448
  return { stdout: () => void 0, stderr: io.stderr };
@@ -107099,7 +108488,7 @@ Usage:
107099
108488
  vapi docs "<question>" [--json]
107100
108489
  vapi docs search "<query>" [--json]
107101
108490
  vapi docs read <url-or-path> [--json]
107102
- vapi search [query] [--kind <kind>] [--network <caip2>] [--limit <n>] [--cursor <cursor>] [--include-unverified] [--json]
108491
+ vapi search [query] [--kind <kind>] [--network <caip2>] [--limit <n>] [--cursor <cursor>] [--include-unverified] [--include-outage] [--json]
107103
108492
  vapi inspect <id> [--endpoint <name>] [--json]
107104
108493
  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]
107105
108494
  vapi pay --resume <receipt-id> [--json]
@@ -107121,6 +108510,10 @@ Usage:
107121
108510
  vapi login [--account <name>] [--label <name>] [--publish] [--no-browser] [--json]
107122
108511
  vapi logout [--account <name>] [--json]
107123
108512
  vapi whoami [--account <name>] [--json]
108513
+ vapi claude [--vapi|--own] [--model <m>] [--use-balance] [--account <name>] [<claude args>...]
108514
+ vapi codex [--vapi|--own] [--model <id>] [--use-balance] [--account <name>] [<codex args>...]
108515
+ vapi code install [--yes] [--no-alias] [--account <name>] [--json]
108516
+ vapi code uninstall [--json]
107124
108517
  vapi router models [--account <name>] [--json]
107125
108518
  vapi router usage [--account <name>] [--json]
107126
108519
  vapi router chat --model <id> [--system <text>] [--max-tokens <n>] "<prompt>" [--account <name>] [--json]
@@ -107168,7 +108561,7 @@ Usage:
107168
108561
  vapi publish list [--json]
107169
108562
  vapi claim <origin> [--account <name>] [--json]
107170
108563
  vapi mcp [--account <name>] [--json]
107171
- vapi mcp install <claude|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]
108564
+ vapi mcp install <claude-code|claude-desktop|cursor|codex> [--home <dir>] [--registry <url>] [--no-link] [--json]
107172
108565
  vapi serve [--json]
107173
108566
  vapi version [--json]
107174
108567
  vapi help [--json]
@@ -107195,13 +108588,13 @@ Solana listings remain searchable; inspect and pay return \`unsupported_network\
107195
108588
 
107196
108589
  \`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.
107197
108590
 
107198
- \`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.
108591
+ \`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.
107199
108592
 
107200
108593
  \`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.
107201
108594
 
107202
108595
  \`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.
107203
108596
 
107204
- 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.`;
108597
+ 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.`;
107205
108598
  var processIo = {
107206
108599
  stdout: (message) => process.stdout.write(`${message}
107207
108600
  `),
@@ -107239,6 +108632,7 @@ var ACCOUNT_OPTION2 = "--account";
107239
108632
  var WALLET_OPTION_DEPRECATION = "--wallet is now --account; --wallet keeps working for one release.";
107240
108633
  var SOLANA_VAULT_UNAVAILABLE2 = "Solana keys are not part of the device vault yet.";
107241
108634
  var INCLUDE_UNVERIFIED_OPTION = "--include-unverified";
108635
+ var INCLUDE_OUTAGE_OPTION = "--include-outage";
107242
108636
  async function openWalletStore(dependencies, home = getVapiPaths().directory) {
107243
108637
  return await WalletStore.open(home, {
107244
108638
  secrets: getSecretStore(dependencies),
@@ -107339,6 +108733,8 @@ async function confirmWalletName(name, prompt, refusal, dependencies) {
107339
108733
  if (typed.trim() !== name) throw new KeystoreError(refusal);
107340
108734
  }
107341
108735
  async function runCli(argv = process.argv.slice(2), io = processIo, dependencies = {}) {
108736
+ const firstArgument = argv.find((argument) => argument !== "--json");
108737
+ const codeLaunch = firstArgument === "claude" || firstArgument === "codex";
107342
108738
  let json2 = argv.includes("--json");
107343
108739
  const taskInvocation = argv.find((argument) => argument !== "--json") === "task";
107344
108740
  const resultFile = runResultFile(argv);
@@ -107347,15 +108743,15 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
107347
108743
  stderr: (message) => io.stderr(redactDetachedRunText(message, getEnvironment(dependencies)))
107348
108744
  };
107349
108745
  try {
107350
- const parsedInvocation = removeJsonFlag(argv);
108746
+ const parsedInvocation = removeJsonFlag(argv, codeLaunch);
107351
108747
  json2 = parsedInvocation.json;
107352
- const hasWalletOption = parsedInvocation.args.includes(WALLET_OPTION5);
108748
+ const hasWalletOption = !codeLaunch && parsedInvocation.args.includes(WALLET_OPTION5);
107353
108749
  const hasAccountOption = parsedInvocation.args.includes(ACCOUNT_OPTION2);
107354
108750
  if (hasWalletOption && hasAccountOption) {
107355
108751
  throw new UsageError("--wallet and --account cannot be used together.");
107356
108752
  }
107357
108753
  if (hasWalletOption) io.stderr(WALLET_OPTION_DEPRECATION);
107358
- const args = parsedInvocation.args.map(
108754
+ const args = codeLaunch ? parsedInvocation.args : parsedInvocation.args.map(
107359
108755
  (argument) => argument === WALLET_OPTION5 ? ACCOUNT_OPTION2 : argument
107360
108756
  );
107361
108757
  const command = args[0];
@@ -107451,6 +108847,15 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
107451
108847
  await whoamiCommand(args.slice(1), json2, io, dependencies);
107452
108848
  exitCode = 0;
107453
108849
  break;
108850
+ case "claude":
108851
+ exitCode = await claudeCommand(args.slice(1), json2, io, dependencies);
108852
+ break;
108853
+ case "codex":
108854
+ exitCode = await codexCommand(args.slice(1), json2, io, dependencies);
108855
+ break;
108856
+ case "code":
108857
+ exitCode = await codeCommand(args.slice(1), json2, io, dependencies);
108858
+ break;
107454
108859
  case "router":
107455
108860
  await routerCommand(args.slice(1), json2, io, dependencies);
107456
108861
  exitCode = 0;
@@ -107488,7 +108893,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
107488
108893
  break;
107489
108894
  case "unlock":
107490
108895
  io.stderr("vapi unlock is now vapi vault unlock; the old name works for one release.");
107491
- if (await fileExists2(join28(getVapiPaths().directory, "vault.json"))) {
108896
+ if (await fileExists2(join30(getVapiPaths().directory, "vault.json"))) {
107492
108897
  parseArguments(args.slice(1), {
107493
108898
  valueOptions: /* @__PURE__ */ new Set([WALLET_OPTION5]),
107494
108899
  maximumPositionals: 0
@@ -107524,11 +108929,11 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
107524
108929
  break;
107525
108930
  case "mcp":
107526
108931
  if (args[1] === "install") {
107527
- await mcpInstallCommand(args.slice(2), json2, io, dependencies);
108932
+ exitCode = await mcpInstallCommand(args.slice(2), json2, io, dependencies);
107528
108933
  } else {
107529
108934
  await mcpCommand(args.slice(1), dependencies);
108935
+ exitCode = 0;
107530
108936
  }
107531
- exitCode = 0;
107532
108937
  break;
107533
108938
  case "serve":
107534
108939
  outputStub(io, json2);
@@ -107558,7 +108963,9 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
107558
108963
  ).catch(() => void 0);
107559
108964
  }
107560
108965
  if (json2) {
107561
- if (taskInvocation) {
108966
+ if (error61 instanceof SpendCapExceededError) {
108967
+ runIo.stdout(JSON.stringify({ error: error61.toJSON(), exitCode: 1 }));
108968
+ } else if (taskInvocation) {
107562
108969
  runIo.stdout(
107563
108970
  JSON.stringify({
107564
108971
  ok: false,
@@ -107692,7 +109099,7 @@ async function initCommand(argv, json2, io, dependencies) {
107692
109099
  address: account.address,
107693
109100
  accounts,
107694
109101
  config: paths.config,
107695
- vault: join28(paths.directory, "vault.json"),
109102
+ vault: join30(paths.directory, "vault.json"),
107696
109103
  ...configRewrites.length > 0 ? { configRewrites } : {},
107697
109104
  custody: "self",
107698
109105
  warning: CUSTODY_NOTICE,
@@ -107831,7 +109238,7 @@ async function walletCreateCommand(argv, json2, io, dependencies) {
107831
109238
  const result = {
107832
109239
  address: account.address,
107833
109240
  ...account.solana ? { solanaAddress: account.solana.address } : {},
107834
- vault: join28(paths.directory, "vault.json"),
109241
+ vault: join30(paths.directory, "vault.json"),
107835
109242
  ...label === void 0 ? {} : { label },
107836
109243
  spendCaps: created.entry.spendCaps,
107837
109244
  isDefault,
@@ -107871,7 +109278,7 @@ function formatCaps2(caps) {
107871
109278
  function walletListResult(store, wallets, unlocked) {
107872
109279
  return {
107873
109280
  default: store.defaultName ?? null,
107874
- vault: join28(store.home, "vault.json"),
109281
+ vault: join30(store.home, "vault.json"),
107875
109282
  wallets: wallets.map((wallet) => ({
107876
109283
  name: wallet.name,
107877
109284
  ...wallet.address === void 0 ? {} : { address: wallet.address },
@@ -107944,7 +109351,7 @@ async function fundCommand2(argv, json2, io, dependencies) {
107944
109351
  async function searchCommand(argv, json2, io, dependencies) {
107945
109352
  const parsed = parseArguments(argv, {
107946
109353
  valueOptions: /* @__PURE__ */ new Set(["--kind", "--network", "--limit", "--cursor"]),
107947
- booleanOptions: /* @__PURE__ */ new Set([INCLUDE_UNVERIFIED_OPTION]),
109354
+ booleanOptions: /* @__PURE__ */ new Set([INCLUDE_UNVERIFIED_OPTION, INCLUDE_OUTAGE_OPTION]),
107948
109355
  repeatableOptions: /* @__PURE__ */ new Set(["--kind"]),
107949
109356
  maximumPositionals: 1
107950
109357
  });
@@ -107957,7 +109364,8 @@ async function searchCommand(argv, json2, io, dependencies) {
107957
109364
  ...limit === void 0 ? {} : { limit },
107958
109365
  ...parsed.one("--cursor") ? { cursor: parsed.one("--cursor") } : {},
107959
109366
  // Only the opt-in travels: `false` is the registry default.
107960
- ...parsed.has(INCLUDE_UNVERIFIED_OPTION) ? { includeUnverified: true } : {}
109367
+ ...parsed.has(INCLUDE_UNVERIFIED_OPTION) ? { includeUnverified: true } : {},
109368
+ ...parsed.has(INCLUDE_OUTAGE_OPTION) ? { includeOutage: true } : {}
107961
109369
  };
107962
109370
  const call2 = createCallPort({
107963
109371
  config: config2,
@@ -108083,12 +109491,14 @@ async function payCommand(argv, json2, io, dependencies) {
108083
109491
  cliActionContext(config2, pinPayInput(call2, input2), dependencies)
108084
109492
  );
108085
109493
  void _resolvedWallet;
109494
+ const { hints: _hints, ...humanResult } = result;
109495
+ void _hints;
108086
109496
  outputForWallet2(
108087
109497
  io,
108088
109498
  json2,
108089
109499
  wallet,
108090
109500
  result,
108091
- [...verificationNotice(result.verification), JSON.stringify(result, null, 2)].join("\n")
109501
+ [...verificationNotice(result.verification), JSON.stringify(humanResult, null, 2)].join("\n")
108092
109502
  );
108093
109503
  await (dependencies.ceiling?.drainCeilingSweeps ?? drainCeilingSweeps)(1e4).catch(
108094
109504
  () => void 0
@@ -108729,15 +110139,6 @@ async function publishListingCommand(argv, json2, io, dependencies) {
108729
110139
  }
108730
110140
  say(formatCreatedListing(listing, batch.name, payoutWallet, batch.endpoints.length));
108731
110141
  }
108732
- let splitters;
108733
- let splittersError;
108734
- if (created.length > 0) {
108735
- try {
108736
- splitters = await client.splitters(payoutWallet);
108737
- } catch (error61) {
108738
- splittersError = error61 instanceof Error ? error61.message : String(error61);
108739
- }
108740
- }
108741
110142
  const failed2 = failures.length > 0;
108742
110143
  const resumeHint = `Run the same vapi publish command with ${RESUME_OPTION} to list the rest; it skips what is already listed.`;
108743
110144
  if (json2) {
@@ -108747,8 +110148,6 @@ async function publishListingCommand(argv, json2, io, dependencies) {
108747
110148
  probe,
108748
110149
  listings: created,
108749
110150
  results,
108750
- ...splitters === void 0 ? {} : { splitters },
108751
- ...splittersError === void 0 ? {} : { splittersError },
108752
110151
  ...failed2 ? {
108753
110152
  error: [...new Set(failures.map((failure) => failure.message))].join("\n"),
108754
110153
  exitCode: 1
@@ -108758,8 +110157,12 @@ async function publishListingCommand(argv, json2, io, dependencies) {
108758
110157
  return failed2 ? 1 : 0;
108759
110158
  }
108760
110159
  if (created.length > 0) {
108761
- const slug = created.length === 1 ? listingSlug(created[0]) : void 0;
108762
- for (const line of formatSplitters(splitters, splittersError, slug, baseUrl)) io.stdout(line);
110160
+ for (const line of formatDescriptionWarnings(created[0])) io.stdout(line);
110161
+ io.stdout("vAPI Call takes no fee. Providers are paid directly.");
110162
+ io.stdout(`Set each endpoint's payTo to your payout wallet ${payoutWallet}, then run:`);
110163
+ for (const listing of created) {
110164
+ io.stdout(` vapi publish activate ${listingSlug(listing) ?? "<slug>"}`);
110165
+ }
108763
110166
  }
108764
110167
  if (!failed2) return 0;
108765
110168
  for (const message of new Set(failures.map((failure) => failure.message))) io.stderr(message);
@@ -109051,22 +110454,15 @@ function formatCreatedListing(created, name, payoutWallet, endpoints) {
109051
110454
  `Payout wallet: ${payoutWallet}`
109052
110455
  ].join("\n");
109053
110456
  }
109054
- function formatSplitters(splitters, splittersError, slug, baseUrl) {
109055
- const nextStep = `Deploy the FeeSplitter from your wallet in the console at ${listingsUrl(baseUrl, "/providers").href}, then run \`vapi publish activate ${slug ?? "<slug>"}\`.`;
109056
- if (splittersError !== void 0) {
109057
- return [`Could not read your splitters: ${splittersError}`, nextStep];
109058
- }
109059
- const states = Array.isArray(splitters?.networkStates) ? splitters.networkStates : [];
109060
- const fee = typeof splitters?.feeBp === "number" ? ` (vAPI fee ${splitters.feeBp / 100}%)` : "";
109061
- return [
109062
- `Splitters${fee}:`,
109063
- ...states.map((state) => {
109064
- const label = [state.name, state.network].filter(Boolean).join(" ");
109065
- const address4 = typeof state.splitterAddress === "string" ? state.splitterAddress : "unknown";
109066
- return ` ${label || "network"} ${address4} ${state.deployed === true ? "deployed" : "not deployed"}`;
109067
- }),
109068
- nextStep
109069
- ];
110457
+ function formatDescriptionWarnings(created) {
110458
+ const warnings = Array.isArray(created.descriptionWarnings) ? created.descriptionWarnings : [];
110459
+ const lines = warnings.flatMap((warning) => {
110460
+ if (typeof warning !== "object" || warning === null) return [];
110461
+ const { message, hint } = warning;
110462
+ if (typeof message !== "string") return [];
110463
+ return [`- ${message}${typeof hint === "string" ? ` ${hint}` : ""}`];
110464
+ });
110465
+ return lines.length === 0 ? [] : ["Description check (the listing is published either way):", ...lines];
109070
110466
  }
109071
110467
  function formatListingStatus(slug, action, result) {
109072
110468
  const status = typeof result.status === "string" ? result.status : "unknown";
@@ -109155,7 +110551,7 @@ function formatClaimed(origin, claimed) {
109155
110551
  }
109156
110552
  var EXPORT_KEY_WARNING = "Anyone with this key can spend the wallet. Never paste it into a website or chat.";
109157
110553
  async function deviceVaultKey2(store, dependencies) {
109158
- const path = join28(store.home, "vault.json");
110554
+ const path = join30(store.home, "vault.json");
109159
110555
  const metadata = await readVaultFileUnlocked(path);
109160
110556
  const secrets = getSecretStore(dependencies);
109161
110557
  const key2 = metadata.protected ? await unlockProtectedVault({
@@ -109248,7 +110644,7 @@ async function backupCommand(argv, json2, io, dependencies) {
109248
110644
  const target = await targetWallet(parsed, dependencies);
109249
110645
  const vaultAccount = await target.store.hasVaultAccount(target.name);
109250
110646
  if (vaultAccount) {
109251
- const vault = await readVaultFileUnlocked(join28(target.store.home, "vault.json"));
110647
+ const vault = await readVaultFileUnlocked(join30(target.store.home, "vault.json"));
109252
110648
  if (vault.accounts.some((account) => account.name === target.name && account.kind === "imported")) {
109253
110649
  throw new KeystoreError(
109254
110650
  `Account ${target.name} was imported and is not recoverable from the vault phrase. Back it up with vapi export-key --account ${target.name}.`
@@ -109325,7 +110721,7 @@ async function importCommand(argv, json2, io, dependencies) {
109325
110721
  const existed = store.has(name);
109326
110722
  if (existed && !parsed.has("--replace")) {
109327
110723
  const address4 = await store.readAddress(name);
109328
- const location = await store.hasVaultAccount(name) ? join28(store.home, "vault.json") : store.pathFor(name);
110724
+ const location = await store.hasVaultAccount(name) ? join30(store.home, "vault.json") : store.pathFor(name);
109329
110725
  throw new Error(
109330
110726
  [
109331
110727
  `Wallet ${name} already exists at ${location}.`,
@@ -109361,7 +110757,7 @@ async function importCommand(argv, json2, io, dependencies) {
109361
110757
  const result = {
109362
110758
  address: account.address,
109363
110759
  ...account.solana ? { solanaAddress: account.solana.address } : {},
109364
- vault: join28(paths.directory, "vault.json"),
110760
+ vault: join30(paths.directory, "vault.json"),
109365
110761
  ...previousKeystore ? { previousKeystore } : {},
109366
110762
  message: "Wallet imported. Its encrypted key stays on this machine."
109367
110763
  };
@@ -109614,26 +111010,42 @@ function formatSearch(page) {
109614
111010
  verificationTag({ verification: item.verification, external: isMirroredHit(item) })
109615
111011
  ];
109616
111012
  const prefix = [...new Set(tags)].map((tag) => `[${tag}] `).join("");
111013
+ const health = item.kind === "api" && item.health ? `${item.health.state}${item.health.latencyP50Ms === null ? "" : ` ${Math.round(item.health.latencyP50Ms)}ms`}` : "-";
109617
111014
  return [
109618
- `${item.ref} ${item.kind} ${prefix}${item.card.title}`,
111015
+ `${item.ref} ${item.kind} ${health} ${prefix}${item.card.title}`,
109619
111016
  ` ${item.card.summary}`,
109620
- ...item.fee ? [` Fee: ${item.fee.label}`] : []
111017
+ ...item.fee ? [` Fee: ${formatListingFee(item.fee)}`] : [],
111018
+ ...item.kind === "api" && item.alternatives ? [
111019
+ ` Alternatives: ${item.alternatives.map((alternative) => `${alternative.ref} (${alternative.reason})`).join(", ")}`
111020
+ ] : []
109621
111021
  ].join("\n");
109622
111022
  }).join("\n");
109623
111023
  }
109624
111024
  function formatInspect(result) {
111025
+ const { hints: _hints, ...humanResult } = result;
111026
+ void _hints;
109625
111027
  return [
109626
111028
  `Verification: ${verificationTag({
109627
111029
  verification: result.verification,
109628
111030
  external: result.group === "external"
109629
111031
  })}`,
109630
- ...result.fee ? [`Fee: ${result.fee.label}`] : [],
111032
+ ...result.fee ? [`Fee: ${formatListingFee(result.fee)}`] : [],
111033
+ ...result.health ? [formatHealth(result.health)] : [],
111034
+ ...result.exampleRequest ? [`Example request: ${JSON.stringify(result.exampleRequest)}`] : [],
109631
111035
  ...result.liveness ? [formatLiveness(result.liveness)] : [],
109632
111036
  ...result.conformance ? [formatConformance(result.conformance)] : [],
109633
111037
  ...result.identity ? formatIdentityLines(result.identity) : [],
109634
- JSON.stringify(result, null, 2)
111038
+ JSON.stringify(humanResult, null, 2)
109635
111039
  ].join("\n");
109636
111040
  }
111041
+ function formatHealth(health) {
111042
+ return [
111043
+ `Health: ${health.state}`,
111044
+ ...health.uptime7d === null ? [`(${health.checks7d} checks)`] : [`${(health.uptime7d * 100).toFixed(1)}% up over 7 days (${health.checks7d} checks)`],
111045
+ ...health.latencyP50Ms === null ? [] : [`p50 ${Math.round(health.latencyP50Ms)} ms`],
111046
+ ...health.latencyP95Ms === null ? [] : [`p95 ${Math.round(health.latencyP95Ms)} ms`]
111047
+ ].join(" \xB7 ");
111048
+ }
109637
111049
  function formatLiveness(liveness) {
109638
111050
  const checks = `${liveness.checks7d} check${liveness.checks7d === 1 ? "" : "s"}`;
109639
111051
  return [
@@ -109678,7 +111090,7 @@ function formatFund(address4, url2, opened) {
109678
111090
  function openInBrowser(url2) {
109679
111091
  const opener = process.platform === "darwin" ? { command: "open", args: [url2] } : process.platform === "win32" ? { command: "cmd", args: ["/c", "start", "", url2] } : { command: "xdg-open", args: [url2] };
109680
111092
  try {
109681
- const child = spawn3(opener.command, opener.args, { stdio: "ignore", detached: true });
111093
+ const child = spawn5(opener.command, opener.args, { stdio: "ignore", detached: true });
109682
111094
  child.on("error", () => void 0);
109683
111095
  child.unref();
109684
111096
  return true;
@@ -109870,11 +111282,13 @@ function parseArguments(argv, spec) {
109870
111282
  has: (name) => flags.has(name)
109871
111283
  };
109872
111284
  }
109873
- function removeJsonFlag(argv) {
111285
+ function removeJsonFlag(argv, preserveForwarded = false) {
109874
111286
  let json2 = false;
109875
111287
  const args = [];
111288
+ let forwarding = false;
109876
111289
  for (const argument of argv) {
109877
- if (argument !== "--json") {
111290
+ if (preserveForwarded && argument === "--") forwarding = true;
111291
+ if (argument !== "--json" || forwarding) {
109878
111292
  args.push(argument);
109879
111293
  continue;
109880
111294
  }
@@ -109975,7 +111389,7 @@ function parseInitNetworks(value) {
109975
111389
 
109976
111390
  // ../cli/src/update-check.ts
109977
111391
  import { lookup } from "node:dns/promises";
109978
- import { mkdir as mkdir21, readFile as readFile30, writeFile as writeFile12 } from "node:fs/promises";
111392
+ import { mkdir as mkdir22, readFile as readFile32, writeFile as writeFile13 } from "node:fs/promises";
109979
111393
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
109980
111394
  var CHECK_TIMEOUT_MS = 1500;
109981
111395
  var LATEST_URL = "https://registry.npmjs.org/vapi-network/latest";
@@ -109992,7 +111406,7 @@ async function runCliWithUpdateCheck(argv = process.argv.slice(2), io = {
109992
111406
  async function checkForUpdate(options = {}) {
109993
111407
  const env = options.env ?? process.env;
109994
111408
  const argv = options.argv ?? process.argv.slice(2);
109995
- if (!(options.stderrIsTTY ?? process.stderr.isTTY) || argv.includes("--json") || argv[0] === "mcp" && argv[1] !== "install" || env.VAPI_NO_UPDATE_CHECK === "1" || env.CI !== void 0) {
111409
+ if (!(options.stderrIsTTY ?? process.stderr.isTTY) || argv.includes("--json") || argv[0] === "claude" || argv[0] === "codex" || argv[0] === "mcp" && argv[1] !== "install" || env.VAPI_NO_UPDATE_CHECK === "1" || env.CI !== void 0) {
109996
111410
  return void 0;
109997
111411
  }
109998
111412
  const controller = new AbortController();
@@ -110019,8 +111433,8 @@ async function latestNotice(options, env, signal) {
110019
111433
  const now = (options.nowMs ?? Date.now)();
110020
111434
  let cached2;
110021
111435
  try {
110022
- const value = JSON.parse(await readFile30(paths.updateCheck, "utf8"));
110023
- if (isRecord12(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
111436
+ const value = JSON.parse(await readFile32(paths.updateCheck, "utf8"));
111437
+ if (isRecord13(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
110024
111438
  cached2 = { checkedAt: value.checkedAt, latest: value.latest };
110025
111439
  }
110026
111440
  } catch {
@@ -110028,9 +111442,9 @@ async function latestNotice(options, env, signal) {
110028
111442
  signal.throwIfAborted();
110029
111443
  let latest = cached2?.latest ?? CLI_VERSION;
110030
111444
  if (cached2 === void 0 || now - cached2.checkedAt >= CHECK_INTERVAL_MS || now < cached2.checkedAt) {
110031
- await mkdir21(paths.directory, { recursive: true });
111445
+ await mkdir22(paths.directory, { recursive: true });
110032
111446
  signal.throwIfAborted();
110033
- await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
111447
+ await writeFile13(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
110034
111448
  signal.throwIfAborted();
110035
111449
  const fetchImpl = options.fetchImpl ?? createPublicFetch({
110036
111450
  allowPrivateNetwork: false,
@@ -110053,16 +111467,16 @@ async function latestNotice(options, env, signal) {
110053
111467
  if (!response.ok) return void 0;
110054
111468
  const body = await response.json();
110055
111469
  signal.throwIfAborted();
110056
- if (!isRecord12(body) || typeof body.version !== "string" || !parseVersion(body.version)) {
111470
+ if (!isRecord13(body) || typeof body.version !== "string" || !parseVersion(body.version)) {
110057
111471
  return void 0;
110058
111472
  }
110059
111473
  latest = body.version;
110060
- await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
111474
+ await writeFile13(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
110061
111475
  }
110062
111476
  signal.throwIfAborted();
110063
111477
  return isNewerVersion(latest, CLI_VERSION) ? `vapi-network ${latest} is available (you have ${CLI_VERSION}). Update: npm i -g vapi-network@latest` : void 0;
110064
111478
  }
110065
- function isRecord12(value) {
111479
+ function isRecord13(value) {
110066
111480
  return typeof value === "object" && value !== null && !Array.isArray(value);
110067
111481
  }
110068
111482
  function parseVersion(version5) {
@@ -110100,15 +111514,15 @@ function isNewerVersion(latest, current) {
110100
111514
  }
110101
111515
 
110102
111516
  // src/client.ts
110103
- import { homedir as homedir3 } from "node:os";
110104
- import { join as join29 } from "node:path";
111517
+ import { homedir as homedir5 } from "node:os";
111518
+ import { join as join31 } from "node:path";
110105
111519
  var ACCOUNT_NOT_LINKED = "Not linked. Run vapi login on this machine, or set VAPI_HOME to a linked home.";
110106
111520
  var DISCOVERY_PATH2 = "/api/call/discovery";
110107
111521
  var warnedWalletOption = false;
110108
111522
  async function createVapiClient(options = {}) {
110109
111523
  if (options.wallet !== void 0) warnWalletOption();
110110
111524
  const env = options.env ?? process.env;
110111
- const home = options.home ?? (env.VAPI_HOME?.trim() || join29(homedir3(), ".vapi"));
111525
+ const home = options.home ?? (env.VAPI_HOME?.trim() || join31(homedir5(), ".vapi"));
110112
111526
  const paths = getVapiPaths(home);
110113
111527
  const requestedName = typeof options.account === "string" ? options.account : options.wallet;
110114
111528
  const injected = typeof options.account === "object" ? options.account : void 0;
@@ -110209,7 +111623,7 @@ async function createVapiClient(options = {}) {
110209
111623
  },
110210
111624
  call: {
110211
111625
  async search(query, searchOptions = {}) {
110212
- const page = await searchMarketplace(
111626
+ const page = await searchMarketplace2(
110213
111627
  {
110214
111628
  query,
110215
111629
  ...searchOptions.network === void 0 ? {} : { network: searchOptions.network },