vapi-network 0.9.0 → 0.9.4

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
@@ -10123,6 +10123,7 @@ __export(src_exports4, {
10123
10123
  parseRuntimeKind: () => parseRuntimeKind,
10124
10124
  resolveRuntime: () => resolveRuntime,
10125
10125
  runCli: () => runCli,
10126
+ runCliWithUpdateCheck: () => runCliWithUpdateCheck,
10126
10127
  runtimeForKind: () => runtimeForKind
10127
10128
  });
10128
10129
 
@@ -10185,13 +10186,15 @@ __export(src_exports, {
10185
10186
  MARKETPLACE_EXECUTION_METHODS: () => MARKETPLACE_EXECUTION_METHODS,
10186
10187
  MARKETPLACE_KINDS: () => MARKETPLACE_KINDS,
10187
10188
  MARKETPLACE_RANKING_VERSION: () => MARKETPLACE_RANKING_VERSION,
10189
+ MAX_RESTORE_ACCOUNTS: () => MAX_RESTORE_ACCOUNTS,
10188
10190
  MovementError: () => MovementError,
10189
- NETWORKS: () => NETWORKS,
10191
+ NETWORKS: () => NETWORKS2,
10190
10192
  ONRAMP_FALLBACK_INSTRUCTIONS: () => ONRAMP_FALLBACK_INSTRUCTIONS,
10191
10193
  ONRAMP_NETWORK: () => ONRAMP_NETWORK,
10192
10194
  PASSPHRASE_ENVIRONMENT_VARIABLE: () => PASSPHRASE_ENVIRONMENT_VARIABLE,
10193
10195
  PROVENANCES: () => PROVENANCES,
10194
10196
  RELAY_MAX_PER_TRANSFER_ATOMIC: () => RELAY_MAX_PER_TRANSFER_ATOMIC,
10197
+ RESTORE_GAP_LIMIT: () => RESTORE_GAP_LIMIT,
10195
10198
  ROUTER_TOPUP_TIERS: () => ROUTER_TOPUP_TIERS,
10196
10199
  RUN_ID_PATTERN: () => RUN_ID_PATTERN,
10197
10200
  RunBudgetError: () => RunBudgetError,
@@ -10201,6 +10204,7 @@ __export(src_exports, {
10201
10204
  SIGN_IN_WITH_X: () => SIGN_IN_WITH_X,
10202
10205
  SIWxError: () => SIWxError,
10203
10206
  SOLANA_DERIVATION_PATH: () => SOLANA_DERIVATION_PATH,
10207
+ SOLANA_DEVNET_CAIP2: () => SOLANA_DEVNET_CAIP2,
10204
10208
  SOLANA_MAINNET_CAIP2: () => SOLANA_MAINNET_CAIP2,
10205
10209
  SOLANA_MAINNET_USDC: () => SOLANA_MAINNET_USDC,
10206
10210
  STATS_RANGES: () => STATS_RANGES,
@@ -10324,6 +10328,7 @@ __export(src_exports, {
10324
10328
  getNetworkDefinition: () => getNetworkDefinition,
10325
10329
  getVapiPaths: () => getVapiPaths,
10326
10330
  isCallableListing: () => isCallableListing,
10331
+ isDiscoveryCatalogError: () => isDiscoveryCatalogError,
10327
10332
  isEvmPaymentRequirements: () => isEvmPaymentRequirements,
10328
10333
  isMirroredHit: () => isMirroredHit,
10329
10334
  isMissingFile: () => isMissingFile,
@@ -10356,6 +10361,7 @@ __export(src_exports, {
10356
10361
  lowerAccountCaps: () => lowerAccountCaps,
10357
10362
  marketplaceBadgeCodeSchema: () => marketplaceBadgeCodeSchema,
10358
10363
  marketplaceBadgeSchema: () => marketplaceBadgeSchema,
10364
+ marketplaceDiscoveryEnvelopeSchema: () => marketplaceDiscoveryEnvelopeSchema,
10359
10365
  marketplaceDiscoveryInputSchema: () => marketplaceDiscoveryInputSchema,
10360
10366
  marketplaceDiscoveryPageSchema: () => marketplaceDiscoveryPageSchema,
10361
10367
  marketplaceExecutionMethodSchema: () => marketplaceExecutionMethodSchema,
@@ -29342,378 +29348,6 @@ function date4(params) {
29342
29348
  return _coercedDate(ZodDate, params);
29343
29349
  }
29344
29350
 
29345
- // ../core/src/marketplace-contracts.ts
29346
- var MARKETPLACE_DISCOVERY_PROTOCOL = "vapi.marketplace.discovery/1";
29347
- var MARKETPLACE_RANKING_VERSION = "marketplace-ranking-v1";
29348
- var MARKETPLACE_KINDS = ["api", "service_offer", "open_request"];
29349
- var MARKETPLACE_EXECUTION_METHODS = [
29350
- "GET",
29351
- "HEAD",
29352
- "POST",
29353
- "PUT",
29354
- "PATCH",
29355
- "DELETE"
29356
- ];
29357
- var marketplaceExecutionMethodSchema = external_exports.enum(MARKETPLACE_EXECUTION_METHODS);
29358
- var marketplaceKindSchema = external_exports.enum(MARKETPLACE_KINDS);
29359
- var EXECUTION_MODES = ["direct", "gateway"];
29360
- var executionModeSchema = external_exports.enum(EXECUTION_MODES);
29361
- var PROVENANCES = ["indexed", "self_listed", "partner"];
29362
- var provenanceSchema = external_exports.enum(PROVENANCES);
29363
- var FIRST_PARTY_PROVENANCES = ["self_listed", "partner"];
29364
- var firstPartyProvenanceSchema = external_exports.enum(FIRST_PARTY_PROVENANCES);
29365
- var LISTING_GROUPS = ["vapi", "added", "partner", "external"];
29366
- var listingGroupSchema = external_exports.enum(LISTING_GROUPS);
29367
- var listingFeeSchema = external_exports.looseObject({
29368
- bps: external_exports.number().int().min(0),
29369
- label: external_exports.string()
29370
- });
29371
- var LISTING_VERIFICATIONS = ["none", "requested", "verified"];
29372
- var listingVerificationSchema = external_exports.enum(LISTING_VERIFICATIONS);
29373
- var listingVerificationFieldSchema = listingVerificationSchema.default("none").catch("none");
29374
- var listingLivenessSchema = external_exports.looseObject({
29375
- uptime7d: external_exports.number().min(0).max(1),
29376
- latencyP50Ms: external_exports.number().nonnegative().nullable(),
29377
- latencyP95Ms: external_exports.number().nonnegative().nullable(),
29378
- checks7d: external_exports.number().int().nonnegative()
29379
- });
29380
- var listingConformanceSchema = external_exports.looseObject({
29381
- declaredVersion: external_exports.union([external_exports.literal(1), external_exports.literal(2)]).nullable(),
29382
- versionConformant: external_exports.boolean(),
29383
- offerTransport: external_exports.enum(["body", "header", "both"]),
29384
- issues: external_exports.array(external_exports.string())
29385
- });
29386
- var listingIdentitySchema = external_exports.looseObject({
29387
- erc8004Id: external_exports.string().trim().min(1),
29388
- reputation: external_exports.looseObject({
29389
- score: external_exports.number().finite(),
29390
- count: external_exports.number().int().nonnegative()
29391
- }).optional().catch(void 0)
29392
- });
29393
- var listingDisclosureShape = {
29394
- group: listingGroupSchema.optional(),
29395
- fee: listingFeeSchema.optional(),
29396
- verification: listingVerificationFieldSchema,
29397
- liveness: listingLivenessSchema.optional().catch(void 0),
29398
- conformance: listingConformanceSchema.optional().catch(void 0),
29399
- identity: listingIdentitySchema.optional().catch(void 0)
29400
- };
29401
- var marketplaceBadgeCodeSchema = external_exports.enum([
29402
- "live_x402",
29403
- "partner",
29404
- "payout_wallet_confirmed",
29405
- "vapi_verified",
29406
- "external_catalog",
29407
- "approved_vendor"
29408
- ]);
29409
- var marketplaceBadgeSchema = external_exports.looseObject({
29410
- code: marketplaceBadgeCodeSchema,
29411
- label: external_exports.string().trim().min(1).max(80)
29412
- });
29413
- var marketplacePublicFactSchema = external_exports.looseObject({
29414
- label: external_exports.string().trim().min(1).max(80),
29415
- value: external_exports.string().trim().min(1).max(160)
29416
- });
29417
- var marketplaceHrefSchema = external_exports.union([
29418
- external_exports.string().trim().min(1).max(2048).regex(/^\/(?!\/)/),
29419
- external_exports.url().max(2048).regex(/^https:\/\//)
29420
- ]);
29421
- var marketplaceCardSchema = external_exports.looseObject({
29422
- title: external_exports.string().trim().min(1).max(160),
29423
- summary: external_exports.string().trim().min(1).max(1e3),
29424
- byline: external_exports.string().trim().min(1).max(160).optional(),
29425
- bylineHref: marketplaceHrefSchema.optional(),
29426
- badges: external_exports.array(marketplaceBadgeSchema).max(8),
29427
- facts: external_exports.array(marketplacePublicFactSchema).max(12)
29428
- });
29429
- var marketplaceHitBase = {
29430
- ref: external_exports.string().trim().min(1).max(512),
29431
- card: marketplaceCardSchema,
29432
- ...listingDisclosureShape
29433
- };
29434
- var invokeApiActionSchema = external_exports.looseObject({
29435
- type: external_exports.literal("invoke_api"),
29436
- href: marketplaceHrefSchema
29437
- });
29438
- var firstPartyApiMarketplaceHitSchema = external_exports.looseObject({
29439
- ...marketplaceHitBase,
29440
- kind: external_exports.literal("api"),
29441
- provenance: firstPartyProvenanceSchema,
29442
- execution: external_exports.looseObject({
29443
- mode: executionModeSchema
29444
- }),
29445
- action: invokeApiActionSchema
29446
- });
29447
- var mirroredApiMarketplaceHitSchema = external_exports.looseObject({
29448
- ...marketplaceHitBase,
29449
- kind: external_exports.literal("api"),
29450
- provenance: external_exports.literal("indexed"),
29451
- execution: external_exports.looseObject({
29452
- mode: external_exports.literal("direct"),
29453
- url: external_exports.url().max(2048).regex(/^https:\/\/(?![^/?#]*@)/),
29454
- method: marketplaceExecutionMethodSchema.nullable(),
29455
- network: external_exports.string().trim().max(160).regex(/^eip155:[1-9]\d*$/)
29456
- }),
29457
- action: invokeApiActionSchema
29458
- });
29459
- var apiMarketplaceHitSchema = external_exports.discriminatedUnion("provenance", [
29460
- firstPartyApiMarketplaceHitSchema,
29461
- mirroredApiMarketplaceHitSchema
29462
- ]);
29463
- var serviceOfferMarketplaceHitSchema = external_exports.looseObject({
29464
- ...marketplaceHitBase,
29465
- kind: external_exports.literal("service_offer"),
29466
- action: external_exports.looseObject({
29467
- type: external_exports.literal("start_engagement"),
29468
- href: marketplaceHrefSchema
29469
- })
29470
- });
29471
- var openRequestMarketplaceHitSchema = external_exports.looseObject({
29472
- ...marketplaceHitBase,
29473
- kind: external_exports.literal("open_request"),
29474
- action: external_exports.looseObject({
29475
- type: external_exports.literal("propose_to_request"),
29476
- href: marketplaceHrefSchema
29477
- })
29478
- });
29479
- var marketplaceHitSchema = external_exports.union([
29480
- apiMarketplaceHitSchema,
29481
- serviceOfferMarketplaceHitSchema,
29482
- openRequestMarketplaceHitSchema
29483
- ]);
29484
- var marketplaceDiscoveryInputSchema = external_exports.strictObject({
29485
- q: external_exports.string().trim().max(200).optional(),
29486
- kinds: external_exports.array(marketplaceKindSchema).min(1).max(MARKETPLACE_KINDS.length).optional(),
29487
- network: external_exports.string().trim().min(1).max(160).optional(),
29488
- cursor: external_exports.string().trim().min(1).max(4096).optional(),
29489
- limit: external_exports.number().int().min(1).max(50).optional(),
29490
- includeUnverified: external_exports.boolean().optional()
29491
- }).superRefine((input2, context) => {
29492
- if (input2.kinds && new Set(input2.kinds).size !== input2.kinds.length) {
29493
- context.addIssue({
29494
- code: "custom",
29495
- path: ["kinds"],
29496
- message: "Marketplace kinds must be unique"
29497
- });
29498
- }
29499
- });
29500
- function isMirroredHit(hit) {
29501
- return hit.kind === "api" && hit.provenance === "indexed";
29502
- }
29503
- var marketplaceDiscoveryPageSchema = external_exports.looseObject({
29504
- protocol: external_exports.literal(MARKETPLACE_DISCOVERY_PROTOCOL),
29505
- items: external_exports.array(marketplaceHitSchema),
29506
- nextCursor: external_exports.string().min(1).max(4096).nullable(),
29507
- unavailableKinds: external_exports.array(marketplaceKindSchema).max(MARKETPLACE_KINDS.length),
29508
- rankingVersion: external_exports.literal(MARKETPLACE_RANKING_VERSION)
29509
- });
29510
-
29511
- // ../core/src/call-contracts-wire.ts
29512
- var CALLABLE_KIND = "agent";
29513
- var CALLABLE_CATEGORIES = ["ai", "data", "crypto", "compute", "search"];
29514
- var callableCategorySchema = external_exports.enum(CALLABLE_CATEGORIES);
29515
- var DISCOVERY_CATEGORIES = [...CALLABLE_CATEGORIES, "other"];
29516
- var discoveryCategorySchema = external_exports.enum(DISCOVERY_CATEGORIES);
29517
- var CALLABLE_CATEGORY_LABELS = {
29518
- ai: { catalog: "AI / LLM", publish: "AI and models" },
29519
- data: { catalog: "Data", publish: "Data" },
29520
- crypto: { catalog: "Crypto", publish: "Crypto" },
29521
- compute: { catalog: "Compute", publish: "Compute" },
29522
- search: { catalog: "Search", publish: "Search" }
29523
- };
29524
- var CALLABLE_CATEGORY_SET = new Set(CALLABLE_CATEGORIES);
29525
- function isCallableListing(kind, category) {
29526
- return kind === CALLABLE_KIND && CALLABLE_CATEGORY_SET.has(category);
29527
- }
29528
- var serviceTierSchema = external_exports.enum(["listed", "verified", "partner"]);
29529
- var discoveryEndpointSchema = external_exports.looseObject({
29530
- name: external_exports.string(),
29531
- method: external_exports.string(),
29532
- url: external_exports.url(),
29533
- price: external_exports.string(),
29534
- description: external_exports.string(),
29535
- operationId: external_exports.string().trim().min(1).optional(),
29536
- requestContentType: external_exports.string().trim().min(1).optional(),
29537
- requestSchema: external_exports.json().optional(),
29538
- responseContentType: external_exports.string().trim().min(1).optional(),
29539
- pathTemplate: external_exports.string().trim().min(1).optional(),
29540
- pathParameters: external_exports.array(external_exports.string().trim().min(1)).optional(),
29541
- payment: external_exports.looseObject({
29542
- scheme: external_exports.literal("exact"),
29543
- network: external_exports.string().regex(/^eip155:\d+$/),
29544
- asset: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
29545
- payTo: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
29546
- checkedAt: external_exports.iso.datetime()
29547
- }).optional()
29548
- });
29549
- var serviceSummarySchema = external_exports.looseObject({
29550
- id: external_exports.string(),
29551
- name: external_exports.string(),
29552
- description: external_exports.string(),
29553
- category: discoveryCategorySchema,
29554
- tier: serviceTierSchema,
29555
- ...listingDisclosureShape,
29556
- verified: external_exports.boolean(),
29557
- wrapped: external_exports.boolean(),
29558
- price: external_exports.string(),
29559
- networks: external_exports.array(external_exports.string()),
29560
- endpoints: external_exports.array(discoveryEndpointSchema)
29561
- });
29562
- var searchServicesResponseSchema = external_exports.looseObject({
29563
- services: external_exports.array(serviceSummarySchema)
29564
- });
29565
- var listServicesResponseSchema = searchServicesResponseSchema;
29566
- var discoveryServiceSchema = serviceSummarySchema;
29567
- var discoveryResponseSchema = searchServicesResponseSchema;
29568
-
29569
- // ../core/src/call-contracts.ts
29570
- var DiscoveryCatalogError = class extends Error {
29571
- name = "DiscoveryCatalogError";
29572
- code;
29573
- serviceId;
29574
- constructor(code, message, serviceId) {
29575
- super(message);
29576
- this.code = code;
29577
- this.serviceId = serviceId;
29578
- }
29579
- };
29580
- function parseDiscovery(raw) {
29581
- const parsed = discoveryResponseSchema.safeParse(raw);
29582
- if (!parsed.success) {
29583
- const malformedUrl = parsed.error.issues.find(
29584
- (issue2) => issue2.path.at(-1) === "url" && issue2.path.includes("endpoints")
29585
- );
29586
- if (malformedUrl) {
29587
- const serviceIndex = pathIndexAfter(malformedUrl.path, "services");
29588
- const serviceId = rawServiceId(raw, serviceIndex);
29589
- throw new DiscoveryCatalogError(
29590
- "malformed_url",
29591
- `Service ${JSON.stringify(serviceId ?? "unknown")} has a malformed endpoint URL.`,
29592
- serviceId
29593
- );
29594
- }
29595
- throw new DiscoveryCatalogError("invalid_discovery", "Discovery response is malformed.");
29596
- }
29597
- for (const service of parsed.data.services) {
29598
- buildTargets(service);
29599
- }
29600
- const resolveListing = (serviceId, endpointName) => {
29601
- const service = parsed.data.services.find((candidate) => candidate.id === serviceId);
29602
- if (!service) {
29603
- throw new DiscoveryCatalogError(
29604
- "service_not_found",
29605
- `No payable endpoint found for service ${JSON.stringify(serviceId)}.`,
29606
- serviceId
29607
- );
29608
- }
29609
- return { service, endpoint: resolveTarget(service, endpointName) };
29610
- };
29611
- return {
29612
- services: parsed.data.services,
29613
- resolve: (serviceId, endpointName) => resolveListing(serviceId, endpointName).endpoint,
29614
- resolveListing
29615
- };
29616
- }
29617
- function resolveTarget(service, endpointName) {
29618
- const { targets, targetsByName } = buildTargets(service);
29619
- if (endpointName !== void 0) {
29620
- const selected = targetsByName.get(endpointName.trim());
29621
- if (!selected) {
29622
- throw new DiscoveryCatalogError(
29623
- "endpoint_not_found",
29624
- `Service ${JSON.stringify(service.id)} has no endpoint ${JSON.stringify(endpointName)}. Available endpoints: ${[...targetsByName.keys()].join(", ")}.`,
29625
- service.id
29626
- );
29627
- }
29628
- return { ...selected };
29629
- }
29630
- if (targets.size !== 1) {
29631
- throw new DiscoveryCatalogError(
29632
- "ambiguous_default",
29633
- `Service ${JSON.stringify(service.id)} has ${targets.size} distinct payable endpoints. Choose one with endpoint: ${[...targetsByName.keys()].join(", ")}.`,
29634
- service.id
29635
- );
29636
- }
29637
- return targets.values().next().value;
29638
- }
29639
- function buildTargets(service) {
29640
- if (service.endpoints.length === 0) {
29641
- throw new DiscoveryCatalogError(
29642
- "no_endpoint",
29643
- `Service ${JSON.stringify(service.id)} has no payable endpoint.`,
29644
- service.id
29645
- );
29646
- }
29647
- const namedEndpoints = [...service.endpoints].sort(
29648
- (left, right) => compareNames(left.name.trim(), right.name.trim())
29649
- );
29650
- const names = /* @__PURE__ */ new Set();
29651
- const targets = /* @__PURE__ */ new Map();
29652
- const targetsByName = /* @__PURE__ */ new Map();
29653
- for (const endpoint of namedEndpoints) {
29654
- const name = endpoint.name.trim();
29655
- if (!name) {
29656
- throw new DiscoveryCatalogError(
29657
- "invalid_endpoint_name",
29658
- `Service ${JSON.stringify(service.id)} has a blank endpoint name.`,
29659
- service.id
29660
- );
29661
- }
29662
- if (names.has(name)) {
29663
- throw new DiscoveryCatalogError(
29664
- "duplicate_endpoint_name",
29665
- `Service ${JSON.stringify(service.id)} has duplicate endpoint name ${JSON.stringify(name)}.`,
29666
- service.id
29667
- );
29668
- }
29669
- names.add(name);
29670
- const method = endpoint.method.trim().toUpperCase();
29671
- if (!method) {
29672
- throw new DiscoveryCatalogError(
29673
- "blank_method",
29674
- `Service ${JSON.stringify(service.id)} has a blank endpoint method.`,
29675
- service.id
29676
- );
29677
- }
29678
- const url2 = new URL(endpoint.url);
29679
- if (url2.protocol !== "http:" && url2.protocol !== "https:") {
29680
- throw new DiscoveryCatalogError(
29681
- "malformed_url",
29682
- `Service ${JSON.stringify(service.id)} has a non-HTTP endpoint URL.`,
29683
- service.id
29684
- );
29685
- }
29686
- const transportKey = `${method}\0${endpoint.url}`;
29687
- const normalized = { ...endpoint, name, method };
29688
- targetsByName.set(name, normalized);
29689
- if (!targets.has(transportKey)) targets.set(transportKey, normalized);
29690
- }
29691
- return { targets, targetsByName };
29692
- }
29693
- function compareNames(left, right) {
29694
- return left < right ? -1 : left > right ? 1 : 0;
29695
- }
29696
- function pathIndexAfter(path, key2) {
29697
- const keyIndex = path.indexOf(key2);
29698
- const candidate = path[keyIndex + 1];
29699
- return typeof candidate === "number" ? candidate : void 0;
29700
- }
29701
- function rawServiceId(raw, serviceIndex) {
29702
- if (serviceIndex === void 0 || typeof raw !== "object" || raw === null) {
29703
- return void 0;
29704
- }
29705
- const services = Reflect.get(raw, "services");
29706
- if (!Array.isArray(services)) {
29707
- return void 0;
29708
- }
29709
- const service = services[serviceIndex];
29710
- if (typeof service !== "object" || service === null) {
29711
- return void 0;
29712
- }
29713
- const id2 = Reflect.get(service, "id");
29714
- return typeof id2 === "string" ? id2 : void 0;
29715
- }
29716
-
29717
29351
  // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/index.js
29718
29352
  init_exports();
29719
29353
 
@@ -39990,6 +39624,7 @@ var ARC_MAINNET_CAIP2 = "eip155:5042";
39990
39624
  var ARC_TESTNET_CAIP2 = "eip155:5042002";
39991
39625
  var SOLANA_MAINNET_CAIP2 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d";
39992
39626
  var X402_SOLANA_MAINNET_CAIP2 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
39627
+ var SOLANA_DEVNET_CAIP2 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
39993
39628
  var SOLANA_MAINNET_USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
39994
39629
  function canonicalIdentity(usdc, eip712Domain) {
39995
39630
  return Object.freeze({
@@ -40033,375 +39668,194 @@ var BROWSER_ENABLED_X402_NETWORK_CONFIG = Object.freeze({
40033
39668
  [ARC_TESTNET_CAIP2]: browserNetwork(arcTestnetUsdc)
40034
39669
  });
40035
39670
 
40036
- // ../core/src/net-guard.ts
40037
- import { lookup as dnsLookup } from "node:dns/promises";
40038
- import { request as httpRequest } from "node:http";
40039
- import { request as httpsRequest } from "node:https";
40040
- import { isIP } from "node:net";
40041
- import { Readable } from "node:stream";
40042
- var defaultLookup = async (hostname4) => {
40043
- const addresses = await dnsLookup(hostname4, { all: true });
40044
- return addresses.map(({ address: address4 }) => address4);
39671
+ // ../core/src/marketplace-contracts.ts
39672
+ var MARKETPLACE_DISCOVERY_PROTOCOL = "vapi.marketplace.discovery/1";
39673
+ var MARKETPLACE_RANKING_VERSION = "marketplace-ranking-v1";
39674
+ var MARKETPLACE_KINDS = ["api", "service_offer", "open_request"];
39675
+ var MARKETPLACE_EXECUTION_METHODS = [
39676
+ "GET",
39677
+ "HEAD",
39678
+ "POST",
39679
+ "PUT",
39680
+ "PATCH",
39681
+ "DELETE"
39682
+ ];
39683
+ var marketplaceExecutionMethodSchema = external_exports.enum(MARKETPLACE_EXECUTION_METHODS);
39684
+ var marketplaceKindSchema = external_exports.enum(MARKETPLACE_KINDS);
39685
+ var EXECUTION_MODES = ["direct", "gateway"];
39686
+ var executionModeSchema = external_exports.enum(EXECUTION_MODES);
39687
+ var PROVENANCES = ["indexed", "self_listed", "partner"];
39688
+ var provenanceSchema = external_exports.enum(PROVENANCES);
39689
+ var FIRST_PARTY_PROVENANCES = ["self_listed", "partner"];
39690
+ var firstPartyProvenanceSchema = external_exports.enum(FIRST_PARTY_PROVENANCES);
39691
+ var LISTING_GROUPS = ["vapi", "added", "partner", "external"];
39692
+ var listingGroupSchema = external_exports.enum(LISTING_GROUPS);
39693
+ var listingFeeSchema = external_exports.looseObject({
39694
+ bps: external_exports.number().int().min(0),
39695
+ label: external_exports.string()
39696
+ });
39697
+ var LISTING_VERIFICATIONS = ["none", "requested", "verified"];
39698
+ var listingVerificationSchema = external_exports.enum(LISTING_VERIFICATIONS);
39699
+ var listingVerificationFieldSchema = listingVerificationSchema.default("none").catch("none");
39700
+ var listingLivenessSchema = external_exports.looseObject({
39701
+ uptime7d: external_exports.number().min(0).max(1),
39702
+ latencyP50Ms: external_exports.number().nonnegative().nullable(),
39703
+ latencyP95Ms: external_exports.number().nonnegative().nullable(),
39704
+ checks7d: external_exports.number().int().nonnegative()
39705
+ });
39706
+ var listingConformanceSchema = external_exports.looseObject({
39707
+ declaredVersion: external_exports.union([external_exports.literal(1), external_exports.literal(2)]).nullable(),
39708
+ versionConformant: external_exports.boolean(),
39709
+ offerTransport: external_exports.enum(["body", "header", "both"]),
39710
+ issues: external_exports.array(external_exports.string())
39711
+ });
39712
+ var listingIdentitySchema = external_exports.looseObject({
39713
+ erc8004Id: external_exports.string().trim().min(1),
39714
+ reputation: external_exports.looseObject({
39715
+ score: external_exports.number().finite(),
39716
+ count: external_exports.number().int().nonnegative()
39717
+ }).optional().catch(void 0)
39718
+ });
39719
+ var listingDisclosureShape = {
39720
+ // Presentation metadata must not make an otherwise executable row vanish
39721
+ // when the registry adds a new group or changes the fee display shape.
39722
+ group: listingGroupSchema.optional().catch(void 0),
39723
+ fee: listingFeeSchema.optional().catch(void 0),
39724
+ verification: listingVerificationFieldSchema,
39725
+ liveness: listingLivenessSchema.optional().catch(void 0),
39726
+ conformance: listingConformanceSchema.optional().catch(void 0),
39727
+ identity: listingIdentitySchema.optional().catch(void 0)
40045
39728
  };
40046
- async function assertPublicUrl(url2, options) {
40047
- if (url2.username || url2.password) {
40048
- throw guardError(url2);
40049
- }
40050
- if (url2.protocol !== "http:" && url2.protocol !== "https:") {
40051
- throw guardError(url2);
40052
- }
40053
- if (options.allowPrivateNetwork) {
40054
- return;
40055
- }
40056
- const hostname4 = normalizeHostname(url2.hostname);
40057
- const lowercaseHostname = hostname4.toLowerCase();
40058
- if (!lowercaseHostname || lowercaseHostname === "localhost" || lowercaseHostname.endsWith(".localhost") || lowercaseHostname.endsWith(".local") || lowercaseHostname.endsWith(".internal")) {
40059
- throw guardError(url2);
40060
- }
40061
- if (isIP(hostname4)) {
40062
- if (isNonPublicAddress(hostname4)) {
40063
- throw guardError(url2);
40064
- }
40065
- return;
40066
- }
40067
- let addresses;
40068
- try {
40069
- addresses = await withTimeout2(
40070
- (options.lookup ?? defaultLookup)(hostname4),
40071
- options.timeoutMs ?? 5e3
40072
- );
40073
- } catch {
40074
- throw guardError(url2);
40075
- }
40076
- if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
40077
- throw guardError(url2);
40078
- }
40079
- }
40080
- function createPublicFetch(options) {
40081
- const lookupFn = options.lookup ?? defaultLookup;
40082
- return (async (input2, init) => {
40083
- const url2 = new URL(input2 instanceof Request ? input2.url : input2);
40084
- await assertPublicUrl(url2, {
40085
- allowPrivateNetwork: options.allowPrivateNetwork,
40086
- lookup: lookupFn,
40087
- timeoutMs: 5e3
40088
- });
40089
- const normalized = new Request(input2, init);
40090
- const bytes = normalized.body ? Buffer.from(await normalized.arrayBuffer()) : null;
40091
- return await new Promise((resolve3, reject) => {
40092
- const requestOptions2 = {
40093
- method: normalized.method,
40094
- headers: Object.fromEntries(normalized.headers),
40095
- signal: normalized.signal,
40096
- ...options.allowPrivateNetwork ? {} : { lookup: pinnedLookup(lookupFn) }
40097
- };
40098
- const onResponse = (incoming) => {
40099
- try {
40100
- const headers = new Headers();
40101
- for (const [name, value] of Object.entries(incoming.headers)) {
40102
- if (Array.isArray(value)) {
40103
- for (const item of value) headers.append(name, item);
40104
- } else if (value !== void 0) {
40105
- headers.set(name, value);
40106
- }
40107
- }
40108
- const status = incoming.statusCode ?? 500;
40109
- const bodyForbidden = normalized.method === "HEAD" || [204, 205, 304].includes(status);
40110
- if (bodyForbidden) incoming.resume();
40111
- const response = new Response(
40112
- bodyForbidden ? null : Readable.toWeb(incoming),
40113
- { status, statusText: incoming.statusMessage, headers }
40114
- );
40115
- Object.defineProperty(response, "url", { value: url2.toString() });
40116
- resolve3(response);
40117
- } catch (error61) {
40118
- incoming.destroy();
40119
- reject(error61);
40120
- }
40121
- };
40122
- const request = url2.protocol === "https:" ? httpsRequest(url2, requestOptions2, onResponse) : httpRequest(url2, requestOptions2, onResponse);
40123
- request.on("error", reject);
40124
- if (bytes) request.write(bytes);
40125
- request.end();
40126
- });
40127
- });
40128
- }
40129
- function pinnedLookup(lookup) {
40130
- return (hostname4, dnsOptions, callback) => {
40131
- void lookup(normalizeHostname(hostname4)).then((addresses) => {
40132
- if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
40133
- callback(guardError(new URL(`https://${hostname4}`)), "");
40134
- return;
40135
- }
40136
- const address4 = addresses[0];
40137
- const family = isIP(address4);
40138
- callback(
40139
- null,
40140
- dnsOptions.all ? [{ address: address4, family }] : address4,
40141
- dnsOptions.all ? void 0 : family
40142
- );
40143
- }).catch(
40144
- (error61) => callback(error61 instanceof Error ? error61 : new Error("DNS lookup failed."), "")
40145
- );
40146
- };
40147
- }
40148
- async function withTimeout2(operation, timeoutMs) {
40149
- let timeout;
40150
- try {
40151
- return await Promise.race([
40152
- operation,
40153
- new Promise((_resolve, reject) => {
40154
- timeout = setTimeout(() => reject(new Error("DNS lookup timed out.")), timeoutMs);
40155
- })
40156
- ]);
40157
- } finally {
40158
- if (timeout) clearTimeout(timeout);
40159
- }
40160
- }
40161
- function normalizeHostname(hostname4) {
40162
- const unbracketed = hostname4.startsWith("[") && hostname4.endsWith("]") ? hostname4.slice(1, -1) : hostname4;
40163
- return unbracketed.endsWith(".") ? unbracketed.slice(0, -1) : unbracketed;
40164
- }
40165
- function isNonPublicAddress(address4) {
40166
- const normalized = normalizeHostname(address4);
40167
- const version5 = isIP(normalized);
40168
- if (version5 === 4) {
40169
- return isNonPublicIpv4(parseIpv4(normalized));
40170
- }
40171
- if (version5 === 6) {
40172
- return isNonPublicIpv6(parseIpv6(normalized));
40173
- }
40174
- return true;
40175
- }
40176
- function parseIpv4(address4) {
40177
- const octets = address4.split(".").map(Number);
40178
- return [octets[0], octets[1], octets[2], octets[3]];
40179
- }
40180
- function isNonPublicIpv4([first, second, third]) {
40181
- return first === 0 || first === 10 || first === 100 && second >= 64 && second <= 127 || first === 127 || first === 169 && second === 254 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 0 && (third === 0 || third === 2) || first === 192 && second === 168 || first === 198 && second >= 18 && second <= 19 || first === 198 && second === 51 && third === 100 || first === 203 && second === 0 && third === 113 || first >= 224;
40182
- }
40183
- function parseIpv6(address4) {
40184
- let normalized = address4.toLowerCase();
40185
- const lastColon = normalized.lastIndexOf(":");
40186
- const dottedTail = normalized.slice(lastColon + 1);
40187
- if (dottedTail.includes(".")) {
40188
- const [first, second, third, fourth] = parseIpv4(dottedTail);
40189
- normalized = `${normalized.slice(0, lastColon + 1)}${(first << 8 | second).toString(16)}:${(third << 8 | fourth).toString(16)}`;
40190
- }
40191
- const halves = normalized.split("::");
40192
- const left = halves[0] ? halves[0].split(":").map(parseHex) : [];
40193
- const right = halves[1] ? halves[1].split(":").map(parseHex) : [];
40194
- const omittedCount = 8 - left.length - right.length;
40195
- return halves.length === 2 ? [...left, ...Array.from({ length: omittedCount }, () => 0), ...right] : left;
40196
- }
40197
- function parseHex(value) {
40198
- return Number.parseInt(value, 16);
40199
- }
40200
- function isNonPublicIpv6(hextets) {
40201
- if (hextets.slice(0, 5).every((hextet) => hextet === 0) && hextets[5] === 65535) {
40202
- const embeddedIpv4 = [
40203
- hextets[6] >> 8,
40204
- hextets[6] & 255,
40205
- hextets[7] >> 8,
40206
- hextets[7] & 255
40207
- ];
40208
- return isNonPublicIpv4(embeddedIpv4);
40209
- }
40210
- if (hextets.slice(0, 6).every((hextet) => hextet === 0)) {
40211
- const compatibleIpv4 = [
40212
- hextets[6] >> 8,
40213
- hextets[6] & 255,
40214
- hextets[7] >> 8,
40215
- hextets[7] & 255
40216
- ];
40217
- if (isNonPublicIpv4(compatibleIpv4)) return true;
40218
- }
40219
- const isUnspecified = hextets.every((hextet) => hextet === 0);
40220
- const isLoopback = hextets.slice(0, 7).every((hextet) => hextet === 0) && hextets[7] === 1;
40221
- const first = hextets[0];
40222
- const isUniqueLocal = first >= 64512 && first <= 65023;
40223
- const isLinkLocal = first >= 65152 && first <= 65215;
40224
- const isSiteLocal = first >= 65216 && first <= 65279;
40225
- const isMulticast = first >= 65280;
40226
- const isDocumentation = first === 8193 && hextets[1] === 3512;
40227
- return isUnspecified || isLoopback || isUniqueLocal || isLinkLocal || isSiteLocal || isMulticast || isDocumentation;
40228
- }
40229
- function guardError(url2) {
40230
- return new Error(
40231
- `URL hostname ${JSON.stringify(url2.hostname)} is not allowed; private or internal destinations require allowPrivateNetwork true in the vAPI config.`
40232
- );
40233
- }
40234
-
40235
- // ../core/src/networks.ts
40236
- var USDC_DECIMALS = 6;
40237
- var DEFAULT_ARC_GAS_HEADROOM_ATOMIC = 50000n;
40238
- var NETWORKS = {
40239
- [BASE_MAINNET_CAIP2]: {
40240
- family: "evm",
40241
- chainId: 8453,
40242
- name: "Base mainnet",
40243
- usdc: CANONICAL_X402_USDC_NETWORKS[BASE_MAINNET_CAIP2].usdc,
40244
- gasToken: "ETH",
40245
- rpcEnv: "BASE_RPC_URL",
40246
- publicRpcUrl: "https://mainnet.base.org",
40247
- explorerUrl: "https://basescan.org"
40248
- },
40249
- [ARC_MAINNET_CAIP2]: {
40250
- family: "evm",
40251
- chainId: 5042,
40252
- name: "Arc mainnet",
40253
- usdc: CANONICAL_X402_USDC_NETWORKS[ARC_MAINNET_CAIP2].usdc,
40254
- gasToken: "USDC",
40255
- rpcEnv: "ARC_RPC_URL",
40256
- publicRpcUrl: "https://rpc.mainnet.arc.io",
40257
- explorerUrl: "https://explorer.arc.io"
40258
- },
40259
- [ARC_TESTNET_CAIP2]: {
40260
- family: "evm",
40261
- chainId: 5042002,
40262
- name: "Arc testnet",
40263
- usdc: CANONICAL_X402_USDC_NETWORKS[ARC_TESTNET_CAIP2].usdc,
40264
- gasToken: "USDC",
40265
- rpcEnv: "ARC_TESTNET_RPC_URL"
40266
- },
40267
- [SOLANA_MAINNET_CAIP2]: {
40268
- family: "svm",
40269
- name: "Solana mainnet",
40270
- usdc: SOLANA_MAINNET_USDC,
40271
- gasToken: "SOL",
40272
- rpcEnv: "SOLANA_RPC_URL",
40273
- publicRpcUrl: "https://api.mainnet-beta.solana.com"
40274
- },
40275
- [X402_SOLANA_MAINNET_CAIP2]: {
40276
- family: "svm",
40277
- name: "Solana mainnet",
40278
- usdc: SOLANA_MAINNET_USDC,
40279
- gasToken: "SOL",
40280
- rpcEnv: "SOLANA_RPC_URL",
40281
- publicRpcUrl: "https://api.mainnet-beta.solana.com"
40282
- }
39729
+ var marketplaceBadgeCodeSchema = external_exports.enum([
39730
+ "live_x402",
39731
+ "mpp",
39732
+ "partner",
39733
+ "payout_wallet_confirmed",
39734
+ "vapi_verified",
39735
+ "external_catalog",
39736
+ "approved_vendor",
39737
+ "unverified"
39738
+ ]);
39739
+ var marketplaceBadgeSchema = external_exports.looseObject({
39740
+ code: marketplaceBadgeCodeSchema,
39741
+ label: external_exports.string().trim().min(1).max(80)
39742
+ });
39743
+ var marketplacePublicFactSchema = external_exports.looseObject({
39744
+ label: external_exports.string().trim().min(1).max(80),
39745
+ value: external_exports.string().trim().min(1).max(160)
39746
+ });
39747
+ var marketplaceHrefSchema = external_exports.union([
39748
+ external_exports.string().trim().min(1).max(2048).regex(/^\/(?!\/)/),
39749
+ external_exports.url().max(2048).regex(/^https:\/\//)
39750
+ ]);
39751
+ var marketplaceCardSchema = external_exports.looseObject({
39752
+ title: external_exports.string().trim().min(1).max(160),
39753
+ summary: external_exports.string().trim().min(1).max(1e3),
39754
+ byline: external_exports.string().trim().min(1).max(160).optional(),
39755
+ bylineHref: marketplaceHrefSchema.optional(),
39756
+ badges: external_exports.preprocess(
39757
+ (badges) => Array.isArray(badges) ? badges.flatMap((badge) => {
39758
+ const parsed = marketplaceBadgeSchema.safeParse(badge);
39759
+ return parsed.success ? [parsed.data] : [];
39760
+ }) : badges,
39761
+ external_exports.array(marketplaceBadgeSchema).max(8)
39762
+ ),
39763
+ facts: external_exports.array(marketplacePublicFactSchema).max(12)
39764
+ });
39765
+ var marketplaceHitBase = {
39766
+ ref: external_exports.string().trim().min(1).max(512),
39767
+ card: marketplaceCardSchema,
39768
+ ...listingDisclosureShape
40283
39769
  };
40284
- function parseEip155ChainId(network) {
40285
- const match = /^eip155:(\d+)$/.exec(network);
40286
- if (!match) {
40287
- throw new Error(`Unsupported network ${network}; expected eip155:<chainId>.`);
40288
- }
40289
- const chainId = Number(match[1]);
40290
- if (!Number.isSafeInteger(chainId) || chainId <= 0) {
40291
- throw new Error(`Invalid EVM chain ID in network ${network}.`);
40292
- }
40293
- return chainId;
40294
- }
40295
- function isSolanaNetwork(network) {
40296
- return network === SOLANA_MAINNET_CAIP2 || network === X402_SOLANA_MAINNET_CAIP2;
40297
- }
40298
- function usesUsdcGas(network) {
40299
- try {
40300
- return getNetworkDefinition(network).gasToken === "USDC";
40301
- } catch {
40302
- return false;
40303
- }
40304
- }
40305
- function explorerTransactionUrl(network, hash5) {
40306
- try {
40307
- const explorerUrl = getNetworkDefinition(network).explorerUrl;
40308
- return explorerUrl ? `${explorerUrl}/tx/${hash5}` : void 0;
40309
- } catch {
40310
- return void 0;
40311
- }
40312
- }
40313
- function explorerAddressUrl(network, address4) {
40314
- try {
40315
- const explorerUrl = getNetworkDefinition(network).explorerUrl;
40316
- return explorerUrl ? `${explorerUrl}/address/${address4}` : void 0;
40317
- } catch {
40318
- return void 0;
40319
- }
40320
- }
40321
- function areSamePaymentNetwork(left, right) {
40322
- return left === right || isSolanaNetwork(left) && isSolanaNetwork(right);
40323
- }
40324
- function isSupportedPaymentNetwork(network) {
40325
- if (isSolanaNetwork(network)) return true;
40326
- try {
40327
- parseEip155ChainId(network);
40328
- return true;
40329
- } catch {
40330
- return false;
40331
- }
40332
- }
40333
- function configuredNetworkFor(networks, network) {
40334
- const configured = networks[network];
40335
- if (configured) return configured;
40336
- if (network === X402_SOLANA_MAINNET_CAIP2) return networks[SOLANA_MAINNET_CAIP2];
40337
- if (network === SOLANA_MAINNET_CAIP2) return networks[X402_SOLANA_MAINNET_CAIP2];
40338
- return void 0;
40339
- }
40340
- function getNetworkDefinition(network) {
40341
- const known = NETWORKS[network];
40342
- if (known) {
40343
- return known;
40344
- }
40345
- const chainId = parseEip155ChainId(network);
40346
- return {
40347
- family: "evm",
40348
- chainId,
40349
- name: network,
40350
- usdc: getAddress("0x0000000000000000000000000000000000000000"),
40351
- gasToken: "ETH",
40352
- rpcEnv: ""
40353
- };
40354
- }
40355
- function requireRpcUrl(network, configured) {
40356
- const definition = getNetworkDefinition(network);
40357
- const envUrl = definition.rpcEnv ? process.env[definition.rpcEnv]?.trim() : void 0;
40358
- const rpcUrl = envUrl || configured.rpcUrl.trim();
40359
- if (rpcUrl) {
40360
- return rpcUrl;
40361
- }
40362
- if (network === ARC_TESTNET_CAIP2) {
40363
- throw new Error(
40364
- "Arc testnet RPC is required. Set ARC_TESTNET_RPC_URL or add rpcUrl for eip155:5042002 in config.json."
40365
- );
40366
- }
40367
- throw new Error(`RPC URL is required for ${network}.`);
40368
- }
40369
- function createChain(network, rpcUrl) {
40370
- const definition = getNetworkDefinition(network);
40371
- if (definition.family !== "evm" || definition.chainId === void 0) {
40372
- throw new Error(`Network ${network} is not an EVM chain.`);
39770
+ var invokeApiActionSchema = external_exports.looseObject({
39771
+ type: external_exports.literal("invoke_api"),
39772
+ href: marketplaceHrefSchema
39773
+ });
39774
+ var firstPartyApiMarketplaceHitSchema = external_exports.looseObject({
39775
+ ...marketplaceHitBase,
39776
+ kind: external_exports.literal("api"),
39777
+ provenance: firstPartyProvenanceSchema,
39778
+ execution: external_exports.looseObject({
39779
+ mode: executionModeSchema
39780
+ }),
39781
+ action: invokeApiActionSchema
39782
+ });
39783
+ var mirroredApiMarketplaceHitSchema = external_exports.looseObject({
39784
+ ...marketplaceHitBase,
39785
+ kind: external_exports.literal("api"),
39786
+ provenance: external_exports.literal("indexed"),
39787
+ execution: external_exports.looseObject({
39788
+ mode: external_exports.literal("direct"),
39789
+ url: external_exports.url().max(2048).regex(/^https:\/\/(?![^/?#]*@)/),
39790
+ method: marketplaceExecutionMethodSchema.nullable(),
39791
+ network: external_exports.string().trim().max(160).transform((network) => {
39792
+ if (network === "solana") return X402_SOLANA_MAINNET_CAIP2;
39793
+ if (network === "solana-devnet") return SOLANA_DEVNET_CAIP2;
39794
+ return network;
39795
+ }).pipe(
39796
+ external_exports.union([
39797
+ external_exports.string().regex(/^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/),
39798
+ // Persisted mainnet configs also use the full genesis hash.
39799
+ external_exports.literal(SOLANA_MAINNET_CAIP2)
39800
+ ])
39801
+ )
39802
+ }),
39803
+ action: invokeApiActionSchema
39804
+ });
39805
+ var apiMarketplaceHitSchema = external_exports.discriminatedUnion("provenance", [
39806
+ firstPartyApiMarketplaceHitSchema,
39807
+ mirroredApiMarketplaceHitSchema
39808
+ ]);
39809
+ var serviceOfferMarketplaceHitSchema = external_exports.looseObject({
39810
+ ...marketplaceHitBase,
39811
+ kind: external_exports.literal("service_offer"),
39812
+ action: external_exports.looseObject({
39813
+ type: external_exports.literal("start_engagement"),
39814
+ href: marketplaceHrefSchema
39815
+ })
39816
+ });
39817
+ var openRequestMarketplaceHitSchema = external_exports.looseObject({
39818
+ ...marketplaceHitBase,
39819
+ kind: external_exports.literal("open_request"),
39820
+ action: external_exports.looseObject({
39821
+ type: external_exports.literal("propose_to_request"),
39822
+ href: marketplaceHrefSchema
39823
+ })
39824
+ });
39825
+ var marketplaceHitSchema = external_exports.union([
39826
+ apiMarketplaceHitSchema,
39827
+ serviceOfferMarketplaceHitSchema,
39828
+ openRequestMarketplaceHitSchema
39829
+ ]);
39830
+ var marketplaceDiscoveryInputSchema = external_exports.strictObject({
39831
+ q: external_exports.string().trim().max(200).optional(),
39832
+ kinds: external_exports.array(marketplaceKindSchema).min(1).max(MARKETPLACE_KINDS.length).optional(),
39833
+ network: external_exports.string().trim().min(1).max(160).optional(),
39834
+ cursor: external_exports.string().trim().min(1).max(4096).optional(),
39835
+ limit: external_exports.number().int().min(1).max(50).optional(),
39836
+ includeUnverified: external_exports.boolean().optional()
39837
+ }).superRefine((input2, context) => {
39838
+ if (input2.kinds && new Set(input2.kinds).size !== input2.kinds.length) {
39839
+ context.addIssue({
39840
+ code: "custom",
39841
+ path: ["kinds"],
39842
+ message: "Marketplace kinds must be unique"
39843
+ });
40373
39844
  }
40374
- return defineChain({
40375
- id: definition.chainId,
40376
- name: definition.name,
40377
- nativeCurrency: definition.gasToken === "USDC" ? { name: "USDC", symbol: "USDC", decimals: USDC_DECIMALS } : { name: "Ether", symbol: "ETH", decimals: 18 },
40378
- rpcUrls: {
40379
- default: { http: [rpcUrl] }
40380
- },
40381
- ...definition.explorerUrl ? {
40382
- blockExplorers: {
40383
- default: { name: `${definition.name} explorer`, url: definition.explorerUrl }
40384
- }
40385
- } : {}
40386
- });
40387
- }
40388
- function createNetworkPublicClient(network, configured, options = {}) {
40389
- const rpcUrl = requireRpcUrl(network, configured);
40390
- return createPublicClient({
40391
- chain: createChain(network, rpcUrl),
40392
- transport: createNetworkHttpTransport(rpcUrl, options)
40393
- });
40394
- }
40395
- function createNetworkHttpTransport(rpcUrl, options = {}) {
40396
- const fetchFn = options.fetch ?? createPublicFetch({
40397
- allowPrivateNetwork: options.allowPrivateNetwork ?? false,
40398
- ...options.lookup ? { lookup: options.lookup } : {}
40399
- });
40400
- return http(rpcUrl, { fetchFn, fetchOptions: { redirect: "manual" } });
40401
- }
40402
- function formatUsdc(amountAtomic2) {
40403
- return formatUnits(amountAtomic2, USDC_DECIMALS);
39845
+ });
39846
+ function isMirroredHit(hit) {
39847
+ return hit.kind === "api" && hit.provenance === "indexed";
40404
39848
  }
39849
+ var marketplaceDiscoveryEnvelopeSchema = external_exports.looseObject({
39850
+ protocol: external_exports.literal(MARKETPLACE_DISCOVERY_PROTOCOL),
39851
+ items: external_exports.array(external_exports.unknown()),
39852
+ nextCursor: external_exports.string().min(1).max(4096).nullable(),
39853
+ unavailableKinds: external_exports.array(marketplaceKindSchema).max(MARKETPLACE_KINDS.length),
39854
+ rankingVersion: external_exports.literal(MARKETPLACE_RANKING_VERSION)
39855
+ });
39856
+ var marketplaceDiscoveryPageSchema = marketplaceDiscoveryEnvelopeSchema.extend({
39857
+ items: external_exports.array(marketplaceHitSchema)
39858
+ });
40405
39859
 
40406
39860
  // ../../node_modules/.pnpm/@solana+errors@5.5.1_typescript@6.0.3/node_modules/@solana/errors/dist/index.node.mjs
40407
39861
  var SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;
@@ -45383,16 +44837,16 @@ var DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;
45383
44837
  var DEFAULT_COMPUTE_UNIT_LIMIT = 2e4;
45384
44838
  var MAX_MEMO_BYTES = 256;
45385
44839
  var SOLANA_MAINNET_CAIP22 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
45386
- var SOLANA_DEVNET_CAIP2 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
44840
+ var SOLANA_DEVNET_CAIP22 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
45387
44841
  var SOLANA_TESTNET_CAIP2 = "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";
45388
44842
  var V1_TO_V2_NETWORK_MAP = {
45389
44843
  solana: SOLANA_MAINNET_CAIP22,
45390
- "solana-devnet": SOLANA_DEVNET_CAIP2,
44844
+ "solana-devnet": SOLANA_DEVNET_CAIP22,
45391
44845
  "solana-testnet": SOLANA_TESTNET_CAIP2
45392
44846
  };
45393
44847
  function normalizeNetwork(network) {
45394
44848
  if (network.includes(":")) {
45395
- const supported = [SOLANA_MAINNET_CAIP22, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];
44849
+ const supported = [SOLANA_MAINNET_CAIP22, SOLANA_DEVNET_CAIP22, SOLANA_TESTNET_CAIP2];
45396
44850
  if (!supported.includes(network)) {
45397
44851
  throw new Error(`Unsupported SVM network: ${network}`);
45398
44852
  }
@@ -45440,7 +44894,7 @@ var DEFAULT_ASSETS = {
45440
44894
  tokenProgram: TOKEN_2022_PROGRAM_ADDRESS2
45441
44895
  }
45442
44896
  ],
45443
- [SOLANA_DEVNET_CAIP2]: [
44897
+ [SOLANA_DEVNET_CAIP22]: [
45444
44898
  {
45445
44899
  asset: USDC_DEVNET_ADDRESS,
45446
44900
  decimals: 6,
@@ -45495,7 +44949,7 @@ var findDefaultAsset = (asset, network) => {
45495
44949
  function createRpcClient(network, customRpcUrl) {
45496
44950
  const caip2Network = normalizeNetwork(network);
45497
44951
  switch (caip2Network) {
45498
- case SOLANA_DEVNET_CAIP2: {
44952
+ case SOLANA_DEVNET_CAIP22: {
45499
44953
  const url2 = customRpcUrl || DEVNET_RPC_URL;
45500
44954
  return createSolanaRpc(devnet(url2));
45501
44955
  }
@@ -45693,6 +45147,376 @@ var ExactSvmScheme = class {
45693
45147
  var addressEncoder = getAddressEncoder();
45694
45148
  var compiledMessageDecoder = getCompiledTransactionMessageDecoder();
45695
45149
 
45150
+ // ../core/src/net-guard.ts
45151
+ import { lookup as dnsLookup } from "node:dns/promises";
45152
+ import { request as httpRequest } from "node:http";
45153
+ import { request as httpsRequest } from "node:https";
45154
+ import { isIP } from "node:net";
45155
+ import { Readable } from "node:stream";
45156
+ var defaultLookup = async (hostname4) => {
45157
+ const addresses = await dnsLookup(hostname4, { all: true });
45158
+ return addresses.map(({ address: address4 }) => address4);
45159
+ };
45160
+ async function assertPublicUrl(url2, options) {
45161
+ if (url2.username || url2.password) {
45162
+ throw guardError(url2);
45163
+ }
45164
+ if (url2.protocol !== "http:" && url2.protocol !== "https:") {
45165
+ throw guardError(url2);
45166
+ }
45167
+ if (options.allowPrivateNetwork) {
45168
+ return;
45169
+ }
45170
+ const hostname4 = normalizeHostname(url2.hostname);
45171
+ const lowercaseHostname = hostname4.toLowerCase();
45172
+ if (!lowercaseHostname || lowercaseHostname === "localhost" || lowercaseHostname.endsWith(".localhost") || lowercaseHostname.endsWith(".local") || lowercaseHostname.endsWith(".internal")) {
45173
+ throw guardError(url2);
45174
+ }
45175
+ if (isIP(hostname4)) {
45176
+ if (isNonPublicAddress(hostname4)) {
45177
+ throw guardError(url2);
45178
+ }
45179
+ return;
45180
+ }
45181
+ let addresses;
45182
+ try {
45183
+ addresses = await withTimeout2(
45184
+ (options.lookup ?? defaultLookup)(hostname4),
45185
+ options.timeoutMs ?? 5e3
45186
+ );
45187
+ } catch {
45188
+ throw guardError(url2);
45189
+ }
45190
+ if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
45191
+ throw guardError(url2);
45192
+ }
45193
+ }
45194
+ function createPublicFetch(options) {
45195
+ const lookupFn = options.lookup ?? defaultLookup;
45196
+ return (async (input2, init) => {
45197
+ const url2 = new URL(input2 instanceof Request ? input2.url : input2);
45198
+ await assertPublicUrl(url2, {
45199
+ allowPrivateNetwork: options.allowPrivateNetwork,
45200
+ lookup: lookupFn,
45201
+ timeoutMs: 5e3
45202
+ });
45203
+ const normalized = new Request(input2, init);
45204
+ const bytes = normalized.body ? Buffer.from(await normalized.arrayBuffer()) : null;
45205
+ return await new Promise((resolve3, reject) => {
45206
+ const requestOptions2 = {
45207
+ method: normalized.method,
45208
+ headers: Object.fromEntries(normalized.headers),
45209
+ signal: normalized.signal,
45210
+ ...options.allowPrivateNetwork ? {} : { lookup: pinnedLookup(lookupFn) }
45211
+ };
45212
+ const onResponse = (incoming) => {
45213
+ try {
45214
+ const headers = new Headers();
45215
+ for (const [name, value] of Object.entries(incoming.headers)) {
45216
+ if (Array.isArray(value)) {
45217
+ for (const item of value) headers.append(name, item);
45218
+ } else if (value !== void 0) {
45219
+ headers.set(name, value);
45220
+ }
45221
+ }
45222
+ const status = incoming.statusCode ?? 500;
45223
+ const bodyForbidden = normalized.method === "HEAD" || [204, 205, 304].includes(status);
45224
+ if (bodyForbidden) incoming.resume();
45225
+ const response = new Response(
45226
+ bodyForbidden ? null : Readable.toWeb(incoming),
45227
+ { status, statusText: incoming.statusMessage, headers }
45228
+ );
45229
+ Object.defineProperty(response, "url", { value: url2.toString() });
45230
+ resolve3(response);
45231
+ } catch (error61) {
45232
+ incoming.destroy();
45233
+ reject(error61);
45234
+ }
45235
+ };
45236
+ const request = url2.protocol === "https:" ? httpsRequest(url2, requestOptions2, onResponse) : httpRequest(url2, requestOptions2, onResponse);
45237
+ request.on("error", reject);
45238
+ if (bytes) request.write(bytes);
45239
+ request.end();
45240
+ });
45241
+ });
45242
+ }
45243
+ function pinnedLookup(lookup2) {
45244
+ return (hostname4, dnsOptions, callback) => {
45245
+ void lookup2(normalizeHostname(hostname4)).then((addresses) => {
45246
+ if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
45247
+ callback(guardError(new URL(`https://${hostname4}`)), "");
45248
+ return;
45249
+ }
45250
+ const address4 = addresses[0];
45251
+ const family = isIP(address4);
45252
+ callback(
45253
+ null,
45254
+ dnsOptions.all ? [{ address: address4, family }] : address4,
45255
+ dnsOptions.all ? void 0 : family
45256
+ );
45257
+ }).catch(
45258
+ (error61) => callback(error61 instanceof Error ? error61 : new Error("DNS lookup failed."), "")
45259
+ );
45260
+ };
45261
+ }
45262
+ async function withTimeout2(operation, timeoutMs) {
45263
+ let timeout;
45264
+ try {
45265
+ return await Promise.race([
45266
+ operation,
45267
+ new Promise((_resolve, reject) => {
45268
+ timeout = setTimeout(() => reject(new Error("DNS lookup timed out.")), timeoutMs);
45269
+ })
45270
+ ]);
45271
+ } finally {
45272
+ if (timeout) clearTimeout(timeout);
45273
+ }
45274
+ }
45275
+ function normalizeHostname(hostname4) {
45276
+ const unbracketed = hostname4.startsWith("[") && hostname4.endsWith("]") ? hostname4.slice(1, -1) : hostname4;
45277
+ return unbracketed.endsWith(".") ? unbracketed.slice(0, -1) : unbracketed;
45278
+ }
45279
+ function isNonPublicAddress(address4) {
45280
+ const normalized = normalizeHostname(address4);
45281
+ const version5 = isIP(normalized);
45282
+ if (version5 === 4) {
45283
+ return isNonPublicIpv4(parseIpv4(normalized));
45284
+ }
45285
+ if (version5 === 6) {
45286
+ return isNonPublicIpv6(parseIpv6(normalized));
45287
+ }
45288
+ return true;
45289
+ }
45290
+ function parseIpv4(address4) {
45291
+ const octets = address4.split(".").map(Number);
45292
+ return [octets[0], octets[1], octets[2], octets[3]];
45293
+ }
45294
+ function isNonPublicIpv4([first, second, third]) {
45295
+ return first === 0 || first === 10 || first === 100 && second >= 64 && second <= 127 || first === 127 || first === 169 && second === 254 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 0 && (third === 0 || third === 2) || first === 192 && second === 168 || first === 198 && second >= 18 && second <= 19 || first === 198 && second === 51 && third === 100 || first === 203 && second === 0 && third === 113 || first >= 224;
45296
+ }
45297
+ function parseIpv6(address4) {
45298
+ let normalized = address4.toLowerCase();
45299
+ const lastColon = normalized.lastIndexOf(":");
45300
+ const dottedTail = normalized.slice(lastColon + 1);
45301
+ if (dottedTail.includes(".")) {
45302
+ const [first, second, third, fourth] = parseIpv4(dottedTail);
45303
+ normalized = `${normalized.slice(0, lastColon + 1)}${(first << 8 | second).toString(16)}:${(third << 8 | fourth).toString(16)}`;
45304
+ }
45305
+ const halves = normalized.split("::");
45306
+ const left = halves[0] ? halves[0].split(":").map(parseHex) : [];
45307
+ const right = halves[1] ? halves[1].split(":").map(parseHex) : [];
45308
+ const omittedCount = 8 - left.length - right.length;
45309
+ return halves.length === 2 ? [...left, ...Array.from({ length: omittedCount }, () => 0), ...right] : left;
45310
+ }
45311
+ function parseHex(value) {
45312
+ return Number.parseInt(value, 16);
45313
+ }
45314
+ function isNonPublicIpv6(hextets) {
45315
+ if (hextets.slice(0, 5).every((hextet) => hextet === 0) && hextets[5] === 65535) {
45316
+ const embeddedIpv4 = [
45317
+ hextets[6] >> 8,
45318
+ hextets[6] & 255,
45319
+ hextets[7] >> 8,
45320
+ hextets[7] & 255
45321
+ ];
45322
+ return isNonPublicIpv4(embeddedIpv4);
45323
+ }
45324
+ if (hextets.slice(0, 6).every((hextet) => hextet === 0)) {
45325
+ const compatibleIpv4 = [
45326
+ hextets[6] >> 8,
45327
+ hextets[6] & 255,
45328
+ hextets[7] >> 8,
45329
+ hextets[7] & 255
45330
+ ];
45331
+ if (isNonPublicIpv4(compatibleIpv4)) return true;
45332
+ }
45333
+ const isUnspecified = hextets.every((hextet) => hextet === 0);
45334
+ const isLoopback = hextets.slice(0, 7).every((hextet) => hextet === 0) && hextets[7] === 1;
45335
+ const first = hextets[0];
45336
+ const isUniqueLocal = first >= 64512 && first <= 65023;
45337
+ const isLinkLocal = first >= 65152 && first <= 65215;
45338
+ const isSiteLocal = first >= 65216 && first <= 65279;
45339
+ const isMulticast = first >= 65280;
45340
+ const isDocumentation = first === 8193 && hextets[1] === 3512;
45341
+ return isUnspecified || isLoopback || isUniqueLocal || isLinkLocal || isSiteLocal || isMulticast || isDocumentation;
45342
+ }
45343
+ function guardError(url2) {
45344
+ return new Error(
45345
+ `URL hostname ${JSON.stringify(url2.hostname)} is not allowed; private or internal destinations require allowPrivateNetwork true in the vAPI config.`
45346
+ );
45347
+ }
45348
+
45349
+ // ../core/src/networks.ts
45350
+ var USDC_DECIMALS = 6;
45351
+ var DEFAULT_ARC_GAS_HEADROOM_ATOMIC = 50000n;
45352
+ var NETWORKS2 = {
45353
+ [BASE_MAINNET_CAIP2]: {
45354
+ family: "evm",
45355
+ chainId: 8453,
45356
+ name: "Base mainnet",
45357
+ usdc: CANONICAL_X402_USDC_NETWORKS[BASE_MAINNET_CAIP2].usdc,
45358
+ gasToken: "ETH",
45359
+ rpcEnv: "BASE_RPC_URL",
45360
+ publicRpcUrl: "https://mainnet.base.org",
45361
+ explorerUrl: "https://basescan.org"
45362
+ },
45363
+ [ARC_MAINNET_CAIP2]: {
45364
+ family: "evm",
45365
+ chainId: 5042,
45366
+ name: "Arc mainnet",
45367
+ usdc: CANONICAL_X402_USDC_NETWORKS[ARC_MAINNET_CAIP2].usdc,
45368
+ gasToken: "USDC",
45369
+ rpcEnv: "ARC_RPC_URL",
45370
+ publicRpcUrl: "https://rpc.mainnet.arc.io",
45371
+ explorerUrl: "https://explorer.arc.io"
45372
+ },
45373
+ [ARC_TESTNET_CAIP2]: {
45374
+ family: "evm",
45375
+ chainId: 5042002,
45376
+ name: "Arc testnet",
45377
+ usdc: CANONICAL_X402_USDC_NETWORKS[ARC_TESTNET_CAIP2].usdc,
45378
+ gasToken: "USDC",
45379
+ rpcEnv: "ARC_TESTNET_RPC_URL"
45380
+ },
45381
+ [SOLANA_MAINNET_CAIP2]: {
45382
+ family: "svm",
45383
+ name: "Solana mainnet",
45384
+ usdc: SOLANA_MAINNET_USDC,
45385
+ gasToken: "SOL",
45386
+ rpcEnv: "SOLANA_RPC_URL",
45387
+ publicRpcUrl: "https://api.mainnet-beta.solana.com"
45388
+ },
45389
+ [X402_SOLANA_MAINNET_CAIP2]: {
45390
+ family: "svm",
45391
+ name: "Solana mainnet",
45392
+ usdc: SOLANA_MAINNET_USDC,
45393
+ gasToken: "SOL",
45394
+ rpcEnv: "SOLANA_RPC_URL",
45395
+ publicRpcUrl: "https://api.mainnet-beta.solana.com"
45396
+ }
45397
+ };
45398
+ function parseEip155ChainId(network) {
45399
+ const match = /^eip155:(\d+)$/.exec(network);
45400
+ if (!match) {
45401
+ throw new Error(`Unsupported network ${network}; expected eip155:<chainId>.`);
45402
+ }
45403
+ const chainId = Number(match[1]);
45404
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) {
45405
+ throw new Error(`Invalid EVM chain ID in network ${network}.`);
45406
+ }
45407
+ return chainId;
45408
+ }
45409
+ function isSolanaNetwork(network) {
45410
+ return network === SOLANA_MAINNET_CAIP2 || network === X402_SOLANA_MAINNET_CAIP2;
45411
+ }
45412
+ function usesUsdcGas(network) {
45413
+ try {
45414
+ return getNetworkDefinition(network).gasToken === "USDC";
45415
+ } catch {
45416
+ return false;
45417
+ }
45418
+ }
45419
+ function explorerTransactionUrl(network, hash5) {
45420
+ try {
45421
+ const explorerUrl = getNetworkDefinition(network).explorerUrl;
45422
+ return explorerUrl ? `${explorerUrl}/tx/${hash5}` : void 0;
45423
+ } catch {
45424
+ return void 0;
45425
+ }
45426
+ }
45427
+ function explorerAddressUrl(network, address4) {
45428
+ try {
45429
+ const explorerUrl = getNetworkDefinition(network).explorerUrl;
45430
+ return explorerUrl ? `${explorerUrl}/address/${address4}` : void 0;
45431
+ } catch {
45432
+ return void 0;
45433
+ }
45434
+ }
45435
+ function areSamePaymentNetwork(left, right) {
45436
+ return left === right || isSolanaNetwork(left) && isSolanaNetwork(right);
45437
+ }
45438
+ function isSupportedPaymentNetwork(network) {
45439
+ if (isSolanaNetwork(network)) return true;
45440
+ try {
45441
+ parseEip155ChainId(network);
45442
+ return true;
45443
+ } catch {
45444
+ return false;
45445
+ }
45446
+ }
45447
+ function configuredNetworkFor(networks, network) {
45448
+ const configured = networks[network];
45449
+ if (configured) return configured;
45450
+ if (network === X402_SOLANA_MAINNET_CAIP2) return networks[SOLANA_MAINNET_CAIP2];
45451
+ if (network === SOLANA_MAINNET_CAIP2) return networks[X402_SOLANA_MAINNET_CAIP2];
45452
+ return void 0;
45453
+ }
45454
+ function getNetworkDefinition(network) {
45455
+ const known = NETWORKS2[network];
45456
+ if (known) {
45457
+ return known;
45458
+ }
45459
+ const chainId = parseEip155ChainId(network);
45460
+ return {
45461
+ family: "evm",
45462
+ chainId,
45463
+ name: network,
45464
+ usdc: getAddress("0x0000000000000000000000000000000000000000"),
45465
+ gasToken: "ETH",
45466
+ rpcEnv: ""
45467
+ };
45468
+ }
45469
+ function requireRpcUrl(network, configured) {
45470
+ const definition = getNetworkDefinition(network);
45471
+ const envUrl = definition.rpcEnv ? process.env[definition.rpcEnv]?.trim() : void 0;
45472
+ const rpcUrl = envUrl || configured.rpcUrl.trim();
45473
+ if (rpcUrl) {
45474
+ return rpcUrl;
45475
+ }
45476
+ if (network === ARC_TESTNET_CAIP2) {
45477
+ throw new Error(
45478
+ "Arc testnet RPC is required. Set ARC_TESTNET_RPC_URL or add rpcUrl for eip155:5042002 in config.json."
45479
+ );
45480
+ }
45481
+ throw new Error(`RPC URL is required for ${network}.`);
45482
+ }
45483
+ function createChain(network, rpcUrl) {
45484
+ const definition = getNetworkDefinition(network);
45485
+ if (definition.family !== "evm" || definition.chainId === void 0) {
45486
+ throw new Error(`Network ${network} is not an EVM chain.`);
45487
+ }
45488
+ return defineChain({
45489
+ id: definition.chainId,
45490
+ name: definition.name,
45491
+ nativeCurrency: definition.gasToken === "USDC" ? { name: "USDC", symbol: "USDC", decimals: USDC_DECIMALS } : { name: "Ether", symbol: "ETH", decimals: 18 },
45492
+ rpcUrls: {
45493
+ default: { http: [rpcUrl] }
45494
+ },
45495
+ ...definition.explorerUrl ? {
45496
+ blockExplorers: {
45497
+ default: { name: `${definition.name} explorer`, url: definition.explorerUrl }
45498
+ }
45499
+ } : {}
45500
+ });
45501
+ }
45502
+ function createNetworkPublicClient(network, configured, options = {}) {
45503
+ const rpcUrl = requireRpcUrl(network, configured);
45504
+ return createPublicClient({
45505
+ chain: createChain(network, rpcUrl),
45506
+ transport: createNetworkHttpTransport(rpcUrl, options)
45507
+ });
45508
+ }
45509
+ function createNetworkHttpTransport(rpcUrl, options = {}) {
45510
+ const fetchFn = options.fetch ?? createPublicFetch({
45511
+ allowPrivateNetwork: options.allowPrivateNetwork ?? false,
45512
+ ...options.lookup ? { lookup: options.lookup } : {}
45513
+ });
45514
+ return http(rpcUrl, { fetchFn, fetchOptions: { redirect: "manual" } });
45515
+ }
45516
+ function formatUsdc(amountAtomic2) {
45517
+ return formatUnits(amountAtomic2, USDC_DECIMALS);
45518
+ }
45519
+
45696
45520
  // ../core/src/x402.ts
45697
45521
  var MAX_CHALLENGE_BYTES = 1048576;
45698
45522
  var MAX_UINT256 = (1n << 256n) - 1n;
@@ -46552,6 +46376,255 @@ function isRecord2(value) {
46552
46376
  return typeof value === "object" && value !== null && !Array.isArray(value);
46553
46377
  }
46554
46378
 
46379
+ // ../core/src/call-contracts-wire.ts
46380
+ var CALLABLE_KIND = "agent";
46381
+ var CALLABLE_CATEGORIES = ["ai", "data", "crypto", "compute", "search"];
46382
+ var callableCategorySchema = external_exports.enum(CALLABLE_CATEGORIES);
46383
+ var DISCOVERY_CATEGORIES = [...CALLABLE_CATEGORIES, "other"];
46384
+ var discoveryCategorySchema = external_exports.string().trim().min(1);
46385
+ var CALLABLE_CATEGORY_LABELS = {
46386
+ ai: { catalog: "AI / LLM", publish: "AI and models" },
46387
+ data: { catalog: "Data", publish: "Data" },
46388
+ crypto: { catalog: "Crypto", publish: "Crypto" },
46389
+ compute: { catalog: "Compute", publish: "Compute" },
46390
+ search: { catalog: "Search", publish: "Search" }
46391
+ };
46392
+ var CALLABLE_CATEGORY_SET = new Set(CALLABLE_CATEGORIES);
46393
+ function isCallableListing(kind, category) {
46394
+ return kind === CALLABLE_KIND && CALLABLE_CATEGORY_SET.has(category);
46395
+ }
46396
+ var serviceTierSchema = external_exports.string().trim().min(1);
46397
+ var discoveryEndpointSchema = external_exports.looseObject({
46398
+ name: external_exports.string(),
46399
+ method: external_exports.string(),
46400
+ url: external_exports.url(),
46401
+ price: external_exports.string(),
46402
+ description: external_exports.string(),
46403
+ operationId: external_exports.string().trim().min(1).optional(),
46404
+ requestContentType: external_exports.string().trim().min(1).optional(),
46405
+ requestSchema: external_exports.json().optional(),
46406
+ responseContentType: external_exports.string().trim().min(1).optional(),
46407
+ pathTemplate: external_exports.string().trim().min(1).optional(),
46408
+ pathParameters: external_exports.array(external_exports.string().trim().min(1)).optional(),
46409
+ payment: external_exports.union([
46410
+ external_exports.looseObject({
46411
+ scheme: external_exports.literal("exact"),
46412
+ network: external_exports.string().regex(/^eip155:\d+$/),
46413
+ asset: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
46414
+ payTo: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
46415
+ checkedAt: external_exports.iso.datetime()
46416
+ }),
46417
+ external_exports.looseObject({
46418
+ scheme: external_exports.literal("exact"),
46419
+ network: external_exports.union([
46420
+ external_exports.string().regex(/^solana:[-_a-zA-Z0-9]{1,32}$/),
46421
+ external_exports.literal(SOLANA_MAINNET_CAIP2)
46422
+ ]),
46423
+ asset: external_exports.string().refine(isSolanaAddress, "Expected a Solana base58 address."),
46424
+ payTo: external_exports.string().refine(isSolanaAddress, "Expected a Solana base58 address."),
46425
+ checkedAt: external_exports.iso.datetime()
46426
+ }),
46427
+ external_exports.looseObject({
46428
+ protocol: external_exports.literal("mpp"),
46429
+ intent: external_exports.enum(["charge", "authorize", "subscription"]).nullable(),
46430
+ method: external_exports.string().trim().min(1).max(40).nullable(),
46431
+ checkedAt: external_exports.iso.datetime(),
46432
+ // Keep common x402 properties readable on the union while making it
46433
+ // impossible for MPP metadata to masquerade as executable x402 terms.
46434
+ network: external_exports.never().optional(),
46435
+ payTo: external_exports.never().optional()
46436
+ }),
46437
+ external_exports.looseObject({
46438
+ // Future payment protocols remain visible to callers so the payment
46439
+ // layer can refuse them explicitly instead of discovery losing the row.
46440
+ protocol: external_exports.string().trim().min(1).max(40),
46441
+ checkedAt: external_exports.iso.datetime(),
46442
+ network: external_exports.never().optional(),
46443
+ payTo: external_exports.never().optional()
46444
+ })
46445
+ ]).optional()
46446
+ });
46447
+ var serviceSummarySchema = external_exports.looseObject({
46448
+ id: external_exports.string(),
46449
+ name: external_exports.string(),
46450
+ description: external_exports.string(),
46451
+ category: discoveryCategorySchema,
46452
+ tier: serviceTierSchema,
46453
+ ...listingDisclosureShape,
46454
+ verified: external_exports.boolean(),
46455
+ wrapped: external_exports.boolean(),
46456
+ price: external_exports.string(),
46457
+ networks: external_exports.array(external_exports.string()),
46458
+ endpoints: external_exports.array(discoveryEndpointSchema)
46459
+ });
46460
+ var searchServicesResponseSchema = external_exports.looseObject({
46461
+ services: external_exports.array(serviceSummarySchema)
46462
+ });
46463
+ var listServicesResponseSchema = searchServicesResponseSchema;
46464
+ var discoveryServiceSchema = serviceSummarySchema;
46465
+ var discoveryResponseSchema = searchServicesResponseSchema;
46466
+
46467
+ // ../core/src/call-contracts.ts
46468
+ var DiscoveryCatalogError = class extends Error {
46469
+ constructor(code, message, serviceId, paymentNetworks) {
46470
+ super(message);
46471
+ this.paymentNetworks = paymentNetworks;
46472
+ this.code = code;
46473
+ this.serviceId = serviceId;
46474
+ }
46475
+ paymentNetworks;
46476
+ name = "DiscoveryCatalogError";
46477
+ code;
46478
+ serviceId;
46479
+ };
46480
+ function isDiscoveryCatalogError(error61) {
46481
+ if (!(error61 instanceof Error) || error61.name !== "DiscoveryCatalogError" || !("code" in error61) || typeof error61.code !== "string") {
46482
+ return false;
46483
+ }
46484
+ const networks = Reflect.get(error61, "paymentNetworks");
46485
+ return networks === void 0 || Array.isArray(networks) && networks.every((network) => typeof network === "string");
46486
+ }
46487
+ function parseDiscovery(raw) {
46488
+ const parsed = discoveryResponseSchema.safeParse(raw);
46489
+ if (!parsed.success) {
46490
+ const malformedUrl = parsed.error.issues.find(
46491
+ (issue2) => issue2.path.at(-1) === "url" && issue2.path.includes("endpoints")
46492
+ );
46493
+ if (malformedUrl) {
46494
+ const serviceIndex = pathIndexAfter(malformedUrl.path, "services");
46495
+ const serviceId = rawServiceId(raw, serviceIndex);
46496
+ throw new DiscoveryCatalogError(
46497
+ "malformed_url",
46498
+ `Service ${JSON.stringify(serviceId ?? "unknown")} has a malformed endpoint URL.`,
46499
+ serviceId
46500
+ );
46501
+ }
46502
+ throw new DiscoveryCatalogError("invalid_discovery", "Discovery response is malformed.");
46503
+ }
46504
+ for (const service of parsed.data.services) {
46505
+ buildTargets(service);
46506
+ }
46507
+ const resolveListing = (serviceId, endpointName) => {
46508
+ const service = parsed.data.services.find((candidate) => candidate.id === serviceId);
46509
+ if (!service) {
46510
+ throw new DiscoveryCatalogError(
46511
+ "service_not_found",
46512
+ `No payable endpoint found for service ${JSON.stringify(serviceId)}.`,
46513
+ serviceId
46514
+ );
46515
+ }
46516
+ return { service, endpoint: resolveTarget(service, endpointName) };
46517
+ };
46518
+ return {
46519
+ services: parsed.data.services,
46520
+ resolve: (serviceId, endpointName) => resolveListing(serviceId, endpointName).endpoint,
46521
+ resolveListing
46522
+ };
46523
+ }
46524
+ function resolveTarget(service, endpointName) {
46525
+ const { targets, targetsByName } = buildTargets(service);
46526
+ if (endpointName !== void 0) {
46527
+ const selected = targetsByName.get(endpointName.trim());
46528
+ if (!selected) {
46529
+ throw new DiscoveryCatalogError(
46530
+ "endpoint_not_found",
46531
+ `Service ${JSON.stringify(service.id)} has no endpoint ${JSON.stringify(endpointName)}. Available endpoints: ${[...targetsByName.keys()].join(", ")}.`,
46532
+ service.id
46533
+ );
46534
+ }
46535
+ return { ...selected };
46536
+ }
46537
+ if (targets.size !== 1) {
46538
+ const paymentNetworks = service.endpoints.flatMap(
46539
+ (endpoint) => typeof endpoint.payment?.network === "string" ? [endpoint.payment.network] : []
46540
+ );
46541
+ throw new DiscoveryCatalogError(
46542
+ "ambiguous_default",
46543
+ `Service ${JSON.stringify(service.id)} has ${targets.size} distinct payable endpoints. Choose one with endpoint: ${[...targetsByName.keys()].join(", ")}.`,
46544
+ service.id,
46545
+ paymentNetworks.length === service.endpoints.length ? paymentNetworks : void 0
46546
+ );
46547
+ }
46548
+ return targets.values().next().value;
46549
+ }
46550
+ function buildTargets(service) {
46551
+ if (service.endpoints.length === 0) {
46552
+ throw new DiscoveryCatalogError(
46553
+ "no_endpoint",
46554
+ `Service ${JSON.stringify(service.id)} has no payable endpoint.`,
46555
+ service.id
46556
+ );
46557
+ }
46558
+ const namedEndpoints = [...service.endpoints].sort(
46559
+ (left, right) => compareNames(left.name.trim(), right.name.trim())
46560
+ );
46561
+ const names = /* @__PURE__ */ new Set();
46562
+ const targets = /* @__PURE__ */ new Map();
46563
+ const targetsByName = /* @__PURE__ */ new Map();
46564
+ for (const endpoint of namedEndpoints) {
46565
+ const name = endpoint.name.trim();
46566
+ if (!name) {
46567
+ throw new DiscoveryCatalogError(
46568
+ "invalid_endpoint_name",
46569
+ `Service ${JSON.stringify(service.id)} has a blank endpoint name.`,
46570
+ service.id
46571
+ );
46572
+ }
46573
+ if (names.has(name)) {
46574
+ throw new DiscoveryCatalogError(
46575
+ "duplicate_endpoint_name",
46576
+ `Service ${JSON.stringify(service.id)} has duplicate endpoint name ${JSON.stringify(name)}.`,
46577
+ service.id
46578
+ );
46579
+ }
46580
+ names.add(name);
46581
+ const method = endpoint.method.trim().toUpperCase();
46582
+ if (!method) {
46583
+ throw new DiscoveryCatalogError(
46584
+ "blank_method",
46585
+ `Service ${JSON.stringify(service.id)} has a blank endpoint method.`,
46586
+ service.id
46587
+ );
46588
+ }
46589
+ const url2 = new URL(endpoint.url);
46590
+ if (url2.protocol !== "http:" && url2.protocol !== "https:") {
46591
+ throw new DiscoveryCatalogError(
46592
+ "malformed_url",
46593
+ `Service ${JSON.stringify(service.id)} has a non-HTTP endpoint URL.`,
46594
+ service.id
46595
+ );
46596
+ }
46597
+ const transportKey = `${method}\0${endpoint.url}`;
46598
+ const normalized = { ...endpoint, name, method };
46599
+ targetsByName.set(name, normalized);
46600
+ if (!targets.has(transportKey)) targets.set(transportKey, normalized);
46601
+ }
46602
+ return { targets, targetsByName };
46603
+ }
46604
+ function compareNames(left, right) {
46605
+ return left < right ? -1 : left > right ? 1 : 0;
46606
+ }
46607
+ function pathIndexAfter(path, key2) {
46608
+ const keyIndex = path.indexOf(key2);
46609
+ const candidate = path[keyIndex + 1];
46610
+ return typeof candidate === "number" ? candidate : void 0;
46611
+ }
46612
+ function rawServiceId(raw, serviceIndex) {
46613
+ if (serviceIndex === void 0 || typeof raw !== "object" || raw === null) {
46614
+ return void 0;
46615
+ }
46616
+ const services = Reflect.get(raw, "services");
46617
+ if (!Array.isArray(services)) {
46618
+ return void 0;
46619
+ }
46620
+ const service = services[serviceIndex];
46621
+ if (typeof service !== "object" || service === null) {
46622
+ return void 0;
46623
+ }
46624
+ const id2 = Reflect.get(service, "id");
46625
+ return typeof id2 === "string" ? id2 : void 0;
46626
+ }
46627
+
46555
46628
  // ../core/src/sweep.ts
46556
46629
  var ERC20_ABI = [
46557
46630
  {
@@ -47403,7 +47476,7 @@ var configSchema = external_exports.object({
47403
47476
  }
47404
47477
  for (const [network, configured] of Object.entries(config2.networks)) {
47405
47478
  if (isSolanaNetwork(network)) {
47406
- if (configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
47479
+ if (configured.usdc !== NETWORKS2[SOLANA_MAINNET_CAIP2].usdc) {
47407
47480
  context.addIssue({
47408
47481
  code: "custom",
47409
47482
  path: ["networks", network, "usdc"],
@@ -47414,7 +47487,7 @@ var configSchema = external_exports.object({
47414
47487
  }
47415
47488
  try {
47416
47489
  const usdc = getAddress(configured.usdc);
47417
- if ((network === ARC_MAINNET_CAIP2 || network === ARC_TESTNET_CAIP2) && usdc !== getAddress(NETWORKS[network].usdc)) {
47490
+ if ((network === ARC_MAINNET_CAIP2 || network === ARC_TESTNET_CAIP2) && usdc !== getAddress(NETWORKS2[network].usdc)) {
47418
47491
  context.addIssue({
47419
47492
  code: "custom",
47420
47493
  path: ["networks", network, "usdc"],
@@ -47441,7 +47514,8 @@ function getVapiPaths(directory = process.env.VAPI_HOME?.trim() || join2(homedir
47441
47514
  keystore: join2(directory, "keystore.json"),
47442
47515
  receipts: join2(directory, "receipts.jsonl"),
47443
47516
  searches: join2(directory, "searches.jsonl"),
47444
- ledger: join2(directory, "spend-ledger.json")
47517
+ ledger: join2(directory, "spend-ledger.json"),
47518
+ updateCheck: join2(directory, "update-check.json")
47445
47519
  };
47446
47520
  }
47447
47521
  var getAgentCashPaths = getVapiPaths;
@@ -47566,15 +47640,15 @@ function getDefaultConfig(source = process.env, options = {}) {
47566
47640
  const tasksEscrowFactoryOverrides = tasksFactoryOverridesFromEnv(source);
47567
47641
  if (requested.has("base") || requested.has(BASE_MAINNET_CAIP2)) {
47568
47642
  networks[BASE_MAINNET_CAIP2] = {
47569
- rpcUrl: source.BASE_RPC_URL?.trim() || NETWORKS[BASE_MAINNET_CAIP2].publicRpcUrl,
47570
- usdc: NETWORKS[BASE_MAINNET_CAIP2].usdc
47643
+ rpcUrl: source.BASE_RPC_URL?.trim() || NETWORKS2[BASE_MAINNET_CAIP2].publicRpcUrl,
47644
+ usdc: NETWORKS2[BASE_MAINNET_CAIP2].usdc
47571
47645
  };
47572
47646
  }
47573
47647
  const arcMainnetRpcUrl = source.ARC_RPC_URL?.trim();
47574
47648
  if (arcMainnetRpcUrl || requested.has("arc") || requested.has(ARC_MAINNET_CAIP2)) {
47575
47649
  networks[ARC_MAINNET_CAIP2] = {
47576
- rpcUrl: arcMainnetRpcUrl || NETWORKS[ARC_MAINNET_CAIP2].publicRpcUrl,
47577
- usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc
47650
+ rpcUrl: arcMainnetRpcUrl || NETWORKS2[ARC_MAINNET_CAIP2].publicRpcUrl,
47651
+ usdc: NETWORKS2[ARC_MAINNET_CAIP2].usdc
47578
47652
  };
47579
47653
  }
47580
47654
  const arcTestnetRpcUrl = source.ARC_TESTNET_RPC_URL?.trim();
@@ -47586,14 +47660,14 @@ function getDefaultConfig(source = process.env, options = {}) {
47586
47660
  }
47587
47661
  networks[ARC_TESTNET_CAIP2] = {
47588
47662
  rpcUrl: arcTestnetRpcUrl,
47589
- usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc
47663
+ usdc: NETWORKS2[ARC_TESTNET_CAIP2].usdc
47590
47664
  };
47591
47665
  }
47592
47666
  const solanaRpcUrl = source.SOLANA_RPC_URL?.trim();
47593
47667
  if (solanaRpcUrl || requested.has("solana") || requested.has(SOLANA_MAINNET_CAIP2)) {
47594
47668
  networks[SOLANA_MAINNET_CAIP2] = {
47595
- rpcUrl: solanaRpcUrl || NETWORKS[SOLANA_MAINNET_CAIP2].publicRpcUrl,
47596
- usdc: NETWORKS[SOLANA_MAINNET_CAIP2].usdc
47669
+ rpcUrl: solanaRpcUrl || NETWORKS2[SOLANA_MAINNET_CAIP2].publicRpcUrl,
47670
+ usdc: NETWORKS2[SOLANA_MAINNET_CAIP2].usdc
47597
47671
  };
47598
47672
  }
47599
47673
  return {
@@ -47651,21 +47725,21 @@ Run vapi init to write the new URLs to ${path}.`
47651
47725
  if (arcMainnetRpcUrl) {
47652
47726
  const existing = config2.networks[ARC_MAINNET_CAIP2];
47653
47727
  config2.networks[ARC_MAINNET_CAIP2] = {
47654
- ...existing ?? { usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc },
47728
+ ...existing ?? { usdc: NETWORKS2[ARC_MAINNET_CAIP2].usdc },
47655
47729
  rpcUrl: arcMainnetRpcUrl
47656
47730
  };
47657
47731
  }
47658
47732
  if (arcTestnetRpcUrl) {
47659
47733
  const existing = config2.networks[ARC_TESTNET_CAIP2];
47660
47734
  config2.networks[ARC_TESTNET_CAIP2] = {
47661
- ...existing ?? { usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc },
47735
+ ...existing ?? { usdc: NETWORKS2[ARC_TESTNET_CAIP2].usdc },
47662
47736
  rpcUrl: arcTestnetRpcUrl
47663
47737
  };
47664
47738
  }
47665
47739
  if (solanaRpcUrl) {
47666
47740
  config2.networks[SOLANA_MAINNET_CAIP2] = {
47667
47741
  rpcUrl: solanaRpcUrl,
47668
- usdc: config2.networks[SOLANA_MAINNET_CAIP2]?.usdc ?? NETWORKS[SOLANA_MAINNET_CAIP2].usdc
47742
+ usdc: config2.networks[SOLANA_MAINNET_CAIP2]?.usdc ?? NETWORKS2[SOLANA_MAINNET_CAIP2].usdc
47669
47743
  };
47670
47744
  }
47671
47745
  if (registryUrl) {
@@ -47678,7 +47752,7 @@ Run vapi init to write the new URLs to ${path}.`
47678
47752
  for (const [network, configured] of Object.entries(config2.networks)) {
47679
47753
  configured.rpcUrl = configured.rpcUrl.trim();
47680
47754
  configured.usdc = configured.usdc.trim();
47681
- if (isSolanaNetwork(network) && configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
47755
+ if (isSolanaNetwork(network) && configured.usdc !== NETWORKS2[SOLANA_MAINNET_CAIP2].usdc) {
47682
47756
  throw new Error(`Network ${network} must use canonical Solana mainnet USDC.`);
47683
47757
  }
47684
47758
  if (!configured.rpcUrl) delete config2.networks[network];
@@ -47734,14 +47808,14 @@ async function enableDefaultNetwork(network, path = getVapiPaths().config, sourc
47734
47808
  const config2 = await loadConfig(path, source);
47735
47809
  if (network === "solana") {
47736
47810
  config2.networks[SOLANA_MAINNET_CAIP2] = {
47737
- rpcUrl: source.SOLANA_RPC_URL?.trim() || NETWORKS[SOLANA_MAINNET_CAIP2].publicRpcUrl,
47738
- usdc: NETWORKS[SOLANA_MAINNET_CAIP2].usdc
47811
+ rpcUrl: source.SOLANA_RPC_URL?.trim() || NETWORKS2[SOLANA_MAINNET_CAIP2].publicRpcUrl,
47812
+ usdc: NETWORKS2[SOLANA_MAINNET_CAIP2].usdc
47739
47813
  };
47740
47814
  } else {
47741
47815
  const existing = config2.networks[ARC_MAINNET_CAIP2];
47742
47816
  config2.networks[ARC_MAINNET_CAIP2] = {
47743
- ...existing ?? { usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc },
47744
- rpcUrl: source.ARC_RPC_URL?.trim() || NETWORKS[ARC_MAINNET_CAIP2].publicRpcUrl
47817
+ ...existing ?? { usdc: NETWORKS2[ARC_MAINNET_CAIP2].usdc },
47818
+ rpcUrl: source.ARC_RPC_URL?.trim() || NETWORKS2[ARC_MAINNET_CAIP2].publicRpcUrl
47745
47819
  };
47746
47820
  }
47747
47821
  await writeConfigFile(path, config2);
@@ -70871,7 +70945,7 @@ function windowsDataProtectionStore(platform2, run, env, installed) {
70871
70945
  };
70872
70946
  }
70873
70947
  function libsecretStore(platform2, run, installed) {
70874
- const lookup = async (name) => {
70948
+ const lookup2 = async (name) => {
70875
70949
  const result = await run(SECRET_TOOL_BINARY, [
70876
70950
  "lookup",
70877
70951
  "service",
@@ -70890,9 +70964,9 @@ function libsecretStore(platform2, run, installed) {
70890
70964
  available: installed(SECRET_TOOL_BINARY),
70891
70965
  platform: platform2,
70892
70966
  description: "the libsecret keyring",
70893
- get: lookup,
70967
+ get: lookup2,
70894
70968
  async has(name) {
70895
- return await lookup(name) !== void 0;
70969
+ return await lookup2(name) !== void 0;
70896
70970
  },
70897
70971
  async set(name, passphrase) {
70898
70972
  requirePassphrase(passphrase);
@@ -70914,7 +70988,7 @@ function libsecretStore(platform2, run, installed) {
70914
70988
  requireSuccess(result, `store the passphrase of ${name} in the secret service`);
70915
70989
  },
70916
70990
  async remove(name) {
70917
- const existed = await lookup(name) !== void 0;
70991
+ const existed = await lookup2(name) !== void 0;
70918
70992
  const result = await run(SECRET_TOOL_BINARY, [
70919
70993
  "clear",
70920
70994
  "service",
@@ -71980,6 +72054,8 @@ var VAULT_KEY_ACCOUNT = "vault-key";
71980
72054
  var VAULT_SESSION_ACCOUNT = "vault-session";
71981
72055
  var DEVICE_KEY_LENGTH = 32;
71982
72056
  var DEFAULT_SESSION_HOURS = 8;
72057
+ var RESTORE_GAP_LIMIT = 5;
72058
+ var MAX_RESTORE_ACCOUNTS = 1e4;
71983
72059
  var BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
71984
72060
  var deviceKeyOperations = Promise.resolve();
71985
72061
  var sessionSchema = external_exports.object({
@@ -72129,26 +72205,41 @@ async function restoreVault(args) {
72129
72205
  throw new VaultError("corrupt", "That recovery phrase is not valid.", { cause: error61 });
72130
72206
  }
72131
72207
  let seed;
72132
- let discoveredAccounts = 0;
72208
+ if (args.accountCount !== void 0 && (!Number.isSafeInteger(args.accountCount) || args.accountCount < 1 || args.accountCount > MAX_RESTORE_ACCOUNTS)) {
72209
+ throw new VaultError(
72210
+ "corrupt",
72211
+ `Account count must be a positive integer no greater than ${MAX_RESTORE_ACCOUNTS}.`
72212
+ );
72213
+ }
72214
+ let discoveredAccounts = args.accountCount ?? 0;
72215
+ let scannedAddresses = 0;
72133
72216
  try {
72134
72217
  seed = phraseToSeed(phrase);
72135
72218
  } catch (error61) {
72136
72219
  throw asVaultError2(error61, "Unable to derive an account while restoring the vault.");
72137
72220
  }
72138
72221
  try {
72139
- for (let index2 = 0; ; index2 += 1) {
72222
+ for (let index2 = 0, emptyRun = 0; args.accountCount === void 0; index2 += 1) {
72140
72223
  let address4;
72141
72224
  try {
72142
72225
  address4 = privateKeyToAccount(deriveEvmPrivateKey(seed, `m/44'/60'/0'/0/${index2}`)).address;
72143
72226
  } catch (error61) {
72144
72227
  throw asVaultError2(error61, "Unable to derive an account while restoring the vault.");
72145
72228
  }
72146
- if (!await args.probe(address4)) break;
72147
- discoveredAccounts += 1;
72229
+ const funded = await args.probe(address4);
72230
+ scannedAddresses += 1;
72231
+ if (funded) {
72232
+ discoveredAccounts = index2 + 1;
72233
+ emptyRun = 0;
72234
+ } else {
72235
+ emptyRun += 1;
72236
+ if (emptyRun === RESTORE_GAP_LIMIT) break;
72237
+ }
72148
72238
  }
72149
72239
  } finally {
72150
72240
  seed.fill(0);
72151
72241
  }
72242
+ args.onScanComplete?.(scannedAddresses);
72152
72243
  let vault;
72153
72244
  try {
72154
72245
  vault = await createVault({ path: args.path, key: args.key, phrase, now: args.now });
@@ -72637,6 +72728,26 @@ var WalletStore = class _WalletStore {
72637
72728
  }
72638
72729
  );
72639
72730
  }
72731
+ /** Checks a cached signer's current vault session without decrypting its account again. */
72732
+ async assertSigningAuthority(name) {
72733
+ const stored = await this.readVaultUnlocked();
72734
+ if (!stored?.protected || !stored.accounts.some((account) => account.name === name)) return;
72735
+ try {
72736
+ const key2 = await unlockProtectedVault({
72737
+ path: this.vaultPath,
72738
+ secrets: this.secrets,
72739
+ env: this.environment,
72740
+ now: () => this.now()
72741
+ });
72742
+ key2.fill(0);
72743
+ } catch (error61) {
72744
+ this.dropVaultCache();
72745
+ if (error61 instanceof VaultError && error61.code === "password_required") {
72746
+ throw new KeystoreError(VAULT_LOCKED_MESSAGE, { cause: error61 });
72747
+ }
72748
+ throw error61;
72749
+ }
72750
+ }
72640
72751
  /** Returns one wallet's vault signer, migrating its legacy keystore if needed. */
72641
72752
  async unlock(name, passphrase) {
72642
72753
  const wallet = this.resolve({ name });
@@ -78023,7 +78134,7 @@ function createRunBudget(args) {
78023
78134
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
78024
78135
  import { arch, platform, release } from "node:os";
78025
78136
  import { join as join13 } from "node:path";
78026
- var VAPI_CLIENT_VERSION = "0.9.0";
78137
+ var VAPI_CLIENT_VERSION = "0.9.4";
78027
78138
  async function createSupportReport(options) {
78028
78139
  const message = options.message.trim();
78029
78140
  if (!message) throw new Error("Support report message must not be empty.");
@@ -78296,7 +78407,7 @@ async function completeX402Payment(args) {
78296
78407
  let paidAttempt;
78297
78408
  const requestStarted = nowMs();
78298
78409
  try {
78299
- paidAttempt = await args.send(paidRequest);
78410
+ paidAttempt = await args.send(paidRequest, quote);
78300
78411
  } catch (error61) {
78301
78412
  if (trace) trace.phases.requestMs = elapsed(nowMs, requestStarted);
78302
78413
  throw settlementUnknown(
@@ -78314,7 +78425,7 @@ async function completeX402Payment(args) {
78314
78425
  const settleStarted = nowMs();
78315
78426
  const settlement = parseSettlementResponse(paidResponse.headers);
78316
78427
  const settlementOutcome = classifySettlement(settlement);
78317
- const receiptSettlement = sanitizeReceiptValue(settlement, receiptSecrets);
78428
+ const receiptSettlement = sanitizeReturnedValue(settlement, receiptSecrets);
78318
78429
  if (trace) {
78319
78430
  const transaction2 = settlementTransaction(receiptSettlement);
78320
78431
  const explorerUrl = transaction2 ? explorerTransactionUrl(quote.accepted.network, transaction2) : void 0;
@@ -78391,6 +78502,7 @@ async function completeX402Payment(args) {
78391
78502
  trace.phases.requestMs = (trace.phases.requestMs ?? 0) + elapsed(nowMs, bodyStarted);
78392
78503
  }
78393
78504
  }
78505
+ body = sanitizeReturnedValue(body, receiptSecrets);
78394
78506
  }
78395
78507
  const result = {
78396
78508
  response: paidResponse,
@@ -78399,7 +78511,11 @@ async function completeX402Payment(args) {
78399
78511
  quote,
78400
78512
  payer,
78401
78513
  ...payment.paymentId ? { paymentId: payment.paymentId } : {},
78402
- settlement,
78514
+ paymentProof: sanitizeReturnedValue(
78515
+ paidResponse.headers.get("x-vapi-payment-proof"),
78516
+ receiptSecrets
78517
+ ),
78518
+ settlement: receiptSettlement,
78403
78519
  settlementOutcome
78404
78520
  };
78405
78521
  if (settlementOutcome === "succeeded" && args.ceilingSweep) {
@@ -78536,19 +78652,70 @@ function sanitizeThrownError(error61, secrets) {
78536
78652
  }
78537
78653
  return new Error(message, cause === void 0 ? void 0 : { cause });
78538
78654
  }
78539
- function sanitizeReceiptValue(value, secrets, depth = 0) {
78655
+ function sanitizeReturnedValue(value, secrets) {
78540
78656
  if (typeof value === "string") return redactKnownSecrets(value, secrets);
78541
- if (value === null || typeof value !== "object") return value;
78542
- if (depth >= 16) return "[redacted nested settlement value]";
78543
- if (Array.isArray(value)) {
78544
- return value.map((item) => sanitizeReceiptValue(item, secrets, depth + 1));
78657
+ if (!isPlainReturnedContainer(value)) return value;
78658
+ const nodes = /* @__PURE__ */ new WeakMap();
78659
+ const ordered = [];
78660
+ const nodeFor = (source) => {
78661
+ const existing = nodes.get(source);
78662
+ if (existing) return existing;
78663
+ const copy = Array.isArray(source) ? new Array(source.length) : Object.create(Object.getPrototypeOf(source));
78664
+ const node2 = { source, copy, parents: /* @__PURE__ */ new Set(), changed: false };
78665
+ nodes.set(source, node2);
78666
+ ordered.push(node2);
78667
+ return node2;
78668
+ };
78669
+ const root = nodeFor(value);
78670
+ for (let index2 = 0; index2 < ordered.length; index2 += 1) {
78671
+ const node2 = ordered[index2];
78672
+ for (const [key2, item] of Object.entries(node2.source)) {
78673
+ const safeKey = Array.isArray(node2.source) ? key2 : redactKnownSecrets(key2, secrets);
78674
+ if (safeKey !== key2) node2.changed = true;
78675
+ if (typeof item === "string") {
78676
+ const safeItem = redactKnownSecrets(item, secrets);
78677
+ defineReturnedProperty(node2.copy, safeKey, safeItem);
78678
+ if (safeItem !== item) node2.changed = true;
78679
+ } else if (isPlainReturnedContainer(item)) {
78680
+ const child = nodeFor(item);
78681
+ child.parents.add(node2);
78682
+ defineReturnedProperty(node2.copy, safeKey, child.copy);
78683
+ } else {
78684
+ defineReturnedProperty(node2.copy, safeKey, item);
78685
+ }
78686
+ }
78545
78687
  }
78546
- return Object.fromEntries(
78547
- Object.entries(value).map(([key2, item]) => [
78548
- redactKnownSecrets(key2, secrets),
78549
- sanitizeReceiptValue(item, secrets, depth + 1)
78550
- ])
78551
- );
78688
+ const changed = ordered.filter((node2) => node2.changed);
78689
+ for (let index2 = 0; index2 < changed.length; index2 += 1) {
78690
+ for (const parent of changed[index2].parents) {
78691
+ if (parent.changed) continue;
78692
+ parent.changed = true;
78693
+ changed.push(parent);
78694
+ }
78695
+ }
78696
+ for (const node2 of ordered) {
78697
+ for (const [key2, item] of Object.entries(node2.source)) {
78698
+ if (!isPlainReturnedContainer(item)) continue;
78699
+ const safeKey = Array.isArray(node2.source) ? key2 : redactKnownSecrets(key2, secrets);
78700
+ const child = nodes.get(item);
78701
+ defineReturnedProperty(node2.copy, safeKey, child.changed ? child.copy : item);
78702
+ }
78703
+ }
78704
+ return root.changed ? root.copy : value;
78705
+ }
78706
+ function defineReturnedProperty(target, key2, value) {
78707
+ Object.defineProperty(target, key2, {
78708
+ value,
78709
+ enumerable: true,
78710
+ configurable: true,
78711
+ writable: true
78712
+ });
78713
+ }
78714
+ function isPlainReturnedContainer(value) {
78715
+ if (Array.isArray(value)) return true;
78716
+ if (value === null || typeof value !== "object") return false;
78717
+ const prototype = Object.getPrototypeOf(value);
78718
+ return prototype === Object.prototype || prototype === null;
78552
78719
  }
78553
78720
  function redactKnownSecrets(value, secrets) {
78554
78721
  let redacted = value;
@@ -78583,9 +78750,7 @@ function possibleSettlement(quote, payment, payer, receipt) {
78583
78750
  payTo: quote.accepted.payTo,
78584
78751
  payer,
78585
78752
  ...payment.paymentId ? { paymentId: payment.paymentId } : {},
78586
- ...isSvmPaymentRequirements(quote.accepted) ? {
78587
- authorizationTransaction: "transaction" in payment.payload.payload ? payment.payload.payload.transaction : ""
78588
- } : "authorization" in payment.payload.payload ? {
78753
+ ...isSvmPaymentRequirements(quote.accepted) ? {} : "authorization" in payment.payload.payload ? {
78589
78754
  authorizationNonce: payment.payload.payload.authorization.nonce,
78590
78755
  authorizationExpiresAt: payment.payload.payload.authorization.validBefore
78591
78756
  } : {},
@@ -78963,13 +79128,22 @@ async function sendRouterChat(deps, routerBaseUrl, routerKey, request, keyUsed)
78963
79128
  }
78964
79129
  const body = await responseText(response);
78965
79130
  if (!response.ok) {
78966
- if (response.status === 429 || body.includes("Budget has been exceeded") || body.includes("ExceededBudget")) {
79131
+ if (/budget (?:has been )?exceeded|exceededbudget/iu.test(body)) {
78967
79132
  throw new RouterClientError(
78968
79133
  "budget_exhausted",
78969
79134
  "The Router key has no remaining budget.",
78970
79135
  response.status
78971
79136
  );
78972
79137
  }
79138
+ if (response.status === 429) {
79139
+ const retryAfter = response.headers.get("retry-after")?.trim();
79140
+ const retrySeconds = retryAfter !== void 0 && /^\d+$/u.test(retryAfter) ? Number(retryAfter) : void 0;
79141
+ throw new RouterClientError(
79142
+ "rate_limited",
79143
+ `The vAPI Router is rate limited. ${retrySeconds !== void 0 && Number.isFinite(retrySeconds) ? `Retry after ${retrySeconds} seconds.` : "Wait and retry shortly."}`,
79144
+ response.status
79145
+ );
79146
+ }
78973
79147
  if (response.status === 401) {
78974
79148
  throw new RouterClientError(
78975
79149
  "no_router_key",
@@ -79536,6 +79710,7 @@ var missingTasksChain = {
79536
79710
 
79537
79711
  // ../core/src/tasks/types.ts
79538
79712
  var uuidSchema = external_exports.uuid();
79713
+ var profileIdSchema = external_exports.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/);
79539
79714
  var isoDateTimeSchema = external_exports.iso.datetime();
79540
79715
  var addressSchema5 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/).transform((value) => value.toLowerCase());
79541
79716
  var bytes32Schema = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform((value) => value.toLowerCase());
@@ -79873,7 +80048,7 @@ var deliveryResponseSchema = external_exports.looseObject({
79873
80048
  version: external_exports.number().int().positive(),
79874
80049
  manifest: manifestResponseSchema,
79875
80050
  manifestHash: bytes32Schema,
79876
- submittedByProfileId: uuidSchema,
80051
+ submittedByProfileId: profileIdSchema,
79877
80052
  createdAt: isoDateTimeSchema
79878
80053
  });
79879
80054
  var orderDeliveryResponseSchema = external_exports.looseObject({
@@ -79979,7 +80154,7 @@ var reviewResponseSchema = external_exports.looseObject({
79979
80154
  id: uuidSchema,
79980
80155
  workOrderId: uuidSchema,
79981
80156
  clientAddress: addressSchema5,
79982
- vendorProfileId: uuidSchema,
80157
+ vendorProfileId: profileIdSchema,
79983
80158
  rating: external_exports.number().int().min(1).max(5),
79984
80159
  body: external_exports.string(),
79985
80160
  subRatings: external_exports.json().nullable(),
@@ -80522,12 +80697,15 @@ function createTasksClient(options) {
80522
80697
  const parsed2 = serverErrorSchema.safeParse(errorBody);
80523
80698
  const server = parsed2.success ? parsed2.data : void 0;
80524
80699
  const nested = typeof server?.error === "object" ? server.error : void 0;
80525
- const message = (typeof server?.error === "string" ? server.error : nested?.message) || server?.message || response.statusText || `HTTP ${response.status}`;
80700
+ const serverCode = nested?.code ?? server?.code;
80701
+ const serverMessage = (typeof server?.error === "string" ? server.error : nested?.message) || server?.message;
80702
+ const fallback = response.statusText || `HTTP ${response.status}`;
80703
+ const message = response.status === 401 || response.status === 403 ? serverCode ?? fallback : serverMessage || (errorBody === void 0 && raw.trim() ? raw.replace(/\s+/gu, " ").trim().slice(0, 300) : fallback);
80526
80704
  throw new TasksClientError(
80527
80705
  "http",
80528
80706
  message,
80529
80707
  response.status,
80530
- nested?.code ?? server?.code,
80708
+ serverCode,
80531
80709
  response.headers.get("Retry-After") ?? void 0
80532
80710
  );
80533
80711
  }
@@ -80930,9 +81108,10 @@ function safeTasksChainError(cause, broadcast, authorizationExposed, txHash) {
80930
81108
  let message = "Task chain operation failed.";
80931
81109
  if (cause instanceof TasksValidationError || cause instanceof TasksChainError)
80932
81110
  message = cause.message;
80933
- else if (cause instanceof TasksClientError)
80934
- message = `Tasks service request failed${cause.status === void 0 ? "" : ` (status ${cause.status})`}.`;
80935
- else if (cause instanceof Error) {
81111
+ else if (cause instanceof TasksClientError) {
81112
+ const code = cause.serverCode ?? (cause.status ? `http_${cause.status}` : cause.code);
81113
+ message = cause.status === 401 || cause.status === 403 ? `${code} (status ${cause.status})` : `${code}: ${cause.message}`;
81114
+ } else if (cause instanceof Error) {
80936
81115
  const short = "shortMessage" in cause && typeof cause.shortMessage === "string" ? cause.shortMessage : void 0;
80937
81116
  let statusCode;
80938
81117
  const seen = /* @__PURE__ */ new Set();
@@ -81740,6 +81919,44 @@ function createTasksChain(options) {
81740
81919
  return idempotencyKey;
81741
81920
  });
81742
81921
  }
81922
+ async function prepareOrResume(prepare, expected, idempotencyKey, kind, steps, authorizationExposed = false, beforeSign) {
81923
+ let prepared;
81924
+ let resumedFromServer = false;
81925
+ try {
81926
+ prepared = await prepare();
81927
+ } catch (error61) {
81928
+ if (!uncertainPreparation(error61)) throw error61;
81929
+ const fresh = await order(expected.milestone.workOrderId);
81930
+ const matches = fresh.milestones.filter((item) => item.id === expected.milestone.id);
81931
+ if (matches.length !== 1 || matches[0].workOrderId !== fresh.id)
81932
+ throw new TasksValidationError("The task milestone does not match its parent order.");
81933
+ const selected = matches[0];
81934
+ const operation = selected.chainOperation;
81935
+ if (expected.verb === "deliver" && selected.delivery && !operation)
81936
+ throw new TasksValidationError(
81937
+ "The server recorded this delivery but has no chain operation for it; open the task in the console to continue."
81938
+ );
81939
+ if (!operation || operation.kind !== kind || !(typeof steps === "string" ? [steps] : steps).includes(operation.step) || !["prepared", "submitted", "confirmed"].includes(operation.state))
81940
+ throw error61;
81941
+ if (expected.verb === "deliver" && selected.delivery && selected.delivery.manifestHash !== expected.manifestHash)
81942
+ throw new TasksValidationError(
81943
+ "The server recorded a different delivery manifest; refusing to continue."
81944
+ );
81945
+ prepared = {
81946
+ operation,
81947
+ milestone: { id: selected.id, workOrderId: selected.workOrderId }
81948
+ };
81949
+ resumedFromServer = true;
81950
+ }
81951
+ const result = await execute(
81952
+ prepared,
81953
+ expected,
81954
+ idempotencyKey,
81955
+ authorizationExposed,
81956
+ beforeSign
81957
+ );
81958
+ return resumedFromServer ? { ...result, resumedFromServer: true } : result;
81959
+ }
81743
81960
  async function verifyReceipt(operation, expected, hash5) {
81744
81961
  const rpc = rpcFor(expected.deployment.chainId);
81745
81962
  const receipt = await rpc.waitForTransactionReceipt({ hash: hash5, confirmations });
@@ -81781,6 +81998,7 @@ function createTasksChain(options) {
81781
81998
  throw new TasksValidationError(
81782
81999
  "The RPC transaction input does not match the verified task plan."
81783
82000
  );
82001
+ return receipt.blockNumber.toString();
81784
82002
  }
81785
82003
  async function retryConflict(call2) {
81786
82004
  let waited = 0;
@@ -81808,6 +82026,7 @@ function createTasksChain(options) {
81808
82026
  current = { ...initial, operation: live };
81809
82027
  let broadcast = current.operation.state === "submitted";
81810
82028
  let txHash = current.operation.transactionHash ?? void 0;
82029
+ let blockNumber;
81811
82030
  const operationId = initial.operation.id;
81812
82031
  function checkTransition(previous, next) {
81813
82032
  if (previous !== next && !(previous === "approve-usdc" && next === afterApproval))
@@ -81843,7 +82062,7 @@ function createTasksChain(options) {
81843
82062
  if (!operation.transactionHash)
81844
82063
  throw new TasksValidationError("The confirmed task operation has no transaction hash.");
81845
82064
  if (!checkpoint) {
81846
- await verifyReceipt(operation, expected, operation.transactionHash);
82065
+ blockNumber = await verifyReceipt(operation, expected, operation.transactionHash);
81847
82066
  await pending.complete(operation.id, operation.step, current);
81848
82067
  }
81849
82068
  const fresh = await order(expected.milestone.workOrderId);
@@ -81852,7 +82071,12 @@ function createTasksChain(options) {
81852
82071
  );
81853
82072
  if (!resultMilestone)
81854
82073
  throw new TasksValidationError("The reconciled task milestone is unavailable.");
81855
- return { txHash: operation.transactionHash, operation, milestone: resultMilestone };
82074
+ return {
82075
+ txHash: operation.transactionHash,
82076
+ operation,
82077
+ milestone: resultMilestone,
82078
+ blockNumber
82079
+ };
81856
82080
  }
81857
82081
  const rpc = rpcFor(expected.deployment.chainId);
81858
82082
  if (operation.state === "prepared") {
@@ -82048,7 +82272,7 @@ function createTasksChain(options) {
82048
82272
  }
82049
82273
  if (operation.state !== "submitted" || !operation.transactionHash)
82050
82274
  throw new TasksValidationError("The task operation has no submitted transaction.");
82051
- await verifyReceipt(operation, expected, operation.transactionHash);
82275
+ blockNumber = await verifyReceipt(operation, expected, operation.transactionHash);
82052
82276
  const reconciled = await retryConflict(
82053
82277
  () => client.reconcileOperation(
82054
82278
  operation.id,
@@ -82071,6 +82295,7 @@ function createTasksChain(options) {
82071
82295
  if (reconciled.operation.state !== "confirmed" && !(operation.step === "approve-usdc" && reconciled.operation.state === "prepared" && reconciled.operation.step === afterApproval))
82072
82296
  throw new TasksValidationError("The task transaction was not reconciled.");
82073
82297
  await pending.complete(operation.id, operation.step, reconciled);
82298
+ if (reconciled.operation.step !== operation.step) blockNumber = void 0;
82074
82299
  current = reconciled;
82075
82300
  }
82076
82301
  throw new TasksValidationError("The task operation exceeded its allowed step transitions.");
@@ -82105,14 +82330,16 @@ function createTasksChain(options) {
82105
82330
  );
82106
82331
  const prepareKey = await preparation(input2, verb, { evidenceHash: input2.evidenceHash });
82107
82332
  const call2 = verb === "dispute" ? client.disputeEscrow.bind(client) : client.counterEvidenceEscrow.bind(client);
82108
- return await execute(
82109
- await call2(
82333
+ return await prepareOrResume(
82334
+ () => call2(
82110
82335
  input2.escrowId,
82111
82336
  { evidenceHash: input2.evidenceHash },
82112
82337
  { idempotencyKey: prepareKey }
82113
82338
  ),
82114
82339
  { ...expected, evidenceHash: input2.evidenceHash },
82115
82340
  prepareKey,
82341
+ verb === "dispute" ? "escrow-dispute" : "escrow-counter-evidence",
82342
+ expected.steps,
82116
82343
  exposed,
82117
82344
  input2.beforeSign
82118
82345
  );
@@ -82132,11 +82359,34 @@ function createTasksChain(options) {
82132
82359
  await options.bindings.put(binding);
82133
82360
  },
82134
82361
  createEscrow: (input2) => safe(async () => {
82135
- const workOrder = await order(input2.orderId);
82362
+ let workOrder = await order(input2.orderId);
82136
82363
  const ready = await deployment();
82137
- const prepared = await client.createEscrow(input2.orderId, {
82138
- idempotencyKey: input2.idempotencyKey
82139
- });
82364
+ let prepared;
82365
+ let resumedFromServer = false;
82366
+ try {
82367
+ prepared = await client.createEscrow(input2.orderId, {
82368
+ idempotencyKey: input2.idempotencyKey
82369
+ });
82370
+ } catch (error61) {
82371
+ if (!uncertainPreparation(error61)) throw error61;
82372
+ const fresh = await order(input2.orderId);
82373
+ const candidates = fresh.milestones.filter((item) => {
82374
+ const previous = workOrder.milestones.find((prior) => prior.id === item.id);
82375
+ const operation = item.chainOperation;
82376
+ return item.workOrderId === input2.orderId && previous && operation && operation.kind === "escrow-create" && operation.step === "create-escrow" && (previous.escrowState === null || previous.chainOperation?.id === operation.id);
82377
+ });
82378
+ if (candidates.length !== 1) throw error61;
82379
+ const selected2 = candidates[0];
82380
+ prepared = {
82381
+ operation: selected2.chainOperation,
82382
+ milestone: {
82383
+ id: selected2.id,
82384
+ workOrderId: selected2.workOrderId
82385
+ }
82386
+ };
82387
+ workOrder = fresh;
82388
+ resumedFromServer = true;
82389
+ }
82140
82390
  const selected = workOrder.milestones.find((item) => item.id === prepared.milestone.id);
82141
82391
  if (!selected || selected.workOrderId !== input2.orderId)
82142
82392
  throw new TasksValidationError(
@@ -82146,11 +82396,12 @@ function createTasksChain(options) {
82146
82396
  { escrowId: selected.id, idempotencyKey: input2.idempotencyKey },
82147
82397
  "createEscrow"
82148
82398
  );
82149
- return await execute(
82399
+ const result = await execute(
82150
82400
  prepared,
82151
82401
  await expectation(selected, ready, "createEscrow", ["create-escrow"], input2.counterparty),
82152
82402
  prepareKey
82153
82403
  );
82404
+ return resumedFromServer ? { ...result, resumedFromServer: true } : result;
82154
82405
  }),
82155
82406
  async fund(input2) {
82156
82407
  let exposed = true;
@@ -82238,10 +82489,14 @@ function createTasksChain(options) {
82238
82489
  }
82239
82490
  exposed = true;
82240
82491
  await pending.markExposure(selected.id);
82241
- const prepared = await client.fundEscrow(input2.escrowId, body, {
82242
- idempotencyKey: prepareKey
82243
- });
82244
- return await execute(prepared, expected, prepareKey, exposed);
82492
+ return await prepareOrResume(
82493
+ () => client.fundEscrow(input2.escrowId, body, { idempotencyKey: prepareKey }),
82494
+ expected,
82495
+ prepareKey,
82496
+ "escrow-funding",
82497
+ expected.steps,
82498
+ exposed
82499
+ );
82245
82500
  } catch (cause) {
82246
82501
  throw chainError(cause, false, exposed);
82247
82502
  }
@@ -82266,22 +82521,26 @@ function createTasksChain(options) {
82266
82521
  manifest: frozen.manifest,
82267
82522
  note: input2.note
82268
82523
  });
82269
- const prepared = await client.deliverEscrow(
82270
- input2.escrowId,
82271
- { fileIds: frozen.manifest.files.map((file2) => file2.fileId), note: input2.note },
82272
- { idempotencyKey: prepareKey }
82273
- );
82274
- if (prepared.delivery.manifestHash !== frozen.manifestHash)
82275
- throw new TasksValidationError(
82276
- "The server task delivery manifest hash does not match the local manifest."
82277
- );
82278
- return await execute(
82279
- prepared,
82524
+ return await prepareOrResume(
82525
+ async () => {
82526
+ const prepared = await client.deliverEscrow(
82527
+ input2.escrowId,
82528
+ { fileIds: frozen.manifest.files.map((file2) => file2.fileId), note: input2.note },
82529
+ { idempotencyKey: prepareKey }
82530
+ );
82531
+ if (prepared.delivery.manifestHash !== frozen.manifestHash)
82532
+ throw new TasksValidationError(
82533
+ "The server task delivery manifest hash does not match the local manifest."
82534
+ );
82535
+ return prepared;
82536
+ },
82280
82537
  {
82281
82538
  ...expected,
82282
82539
  manifestHash: frozen.manifestHash
82283
82540
  },
82284
- prepareKey
82541
+ prepareKey,
82542
+ "escrow-delivery",
82543
+ "submit-delivery"
82285
82544
  );
82286
82545
  }),
82287
82546
  release: (input2) => safe(async () => {
@@ -82295,10 +82554,12 @@ function createTasksChain(options) {
82295
82554
  input2.counterparty
82296
82555
  );
82297
82556
  const prepareKey = await preparation(input2, "release");
82298
- return await execute(
82299
- await client.releaseEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82557
+ return await prepareOrResume(
82558
+ () => client.releaseEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82300
82559
  expected,
82301
- prepareKey
82560
+ prepareKey,
82561
+ "escrow-release",
82562
+ "release-funds"
82302
82563
  );
82303
82564
  }),
82304
82565
  refund: (input2) => safe(async () => {
@@ -82312,10 +82573,12 @@ function createTasksChain(options) {
82312
82573
  input2.counterparty
82313
82574
  );
82314
82575
  const prepareKey = await preparation(input2, "refund");
82315
- return await execute(
82316
- await client.refundEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82576
+ return await prepareOrResume(
82577
+ () => client.refundEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82317
82578
  expected,
82318
- prepareKey
82579
+ prepareKey,
82580
+ "escrow-release",
82581
+ "refund-buyer"
82319
82582
  );
82320
82583
  }),
82321
82584
  disputeFee: (input2) => safe(async () => {
@@ -82343,16 +82606,21 @@ function createTasksChain(options) {
82343
82606
  input2.counterparty
82344
82607
  );
82345
82608
  const prepareKey = await preparation(input2, "resolve-unmatched");
82346
- return execute(
82347
- await client.resolveUnmatchedEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82609
+ return prepareOrResume(
82610
+ () => client.resolveUnmatchedEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82348
82611
  expected,
82349
- prepareKey
82612
+ prepareKey,
82613
+ "escrow-unmatched-resolution",
82614
+ "resolve-unmatched-dispute"
82350
82615
  );
82351
82616
  }),
82352
82617
  signScopeMessage: (message) => safe(() => account.signMessage({ message }))
82353
82618
  };
82354
82619
  }
82355
82620
  var chainError = safeTasksChainError;
82621
+ function uncertainPreparation(error61) {
82622
+ return error61 instanceof TasksClientError && ((error61.status ?? 0) >= 400 || error61.code === "network" || error61.code === "timeout");
82623
+ }
82356
82624
  function retryDelay(header, now) {
82357
82625
  if (/^\d+(?:\.\d+)?$/u.test(header.trim())) return Math.max(1, Math.ceil(Number(header) * 1e3));
82358
82626
  const date5 = Date.parse(header);
@@ -82369,6 +82637,60 @@ function alreadySent(error61) {
82369
82637
  return error61 instanceof Error && /already known|known transaction|nonce (?:is )?too low/iu.test(error61.message);
82370
82638
  }
82371
82639
 
82640
+ // ../core/src/tasks/wait.ts
82641
+ async function waitForMilestone(client, input2) {
82642
+ const timeoutMs = input2.timeoutMs ?? 12e4;
82643
+ const intervalMs = input2.intervalMs ?? 3e3;
82644
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
82645
+ throw new RangeError("The milestone wait timeout must be non-negative and finite.");
82646
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0)
82647
+ throw new RangeError("The milestone wait interval must be positive and finite.");
82648
+ const sleep = input2.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
82649
+ const now = input2.now ?? (() => /* @__PURE__ */ new Date());
82650
+ const started = now().getTime();
82651
+ const deadline = started + timeoutMs;
82652
+ let polls = 0;
82653
+ let milestone;
82654
+ function result(reached) {
82655
+ return { reached, milestone, polls, elapsedMs: now().getTime() - started };
82656
+ }
82657
+ for (; ; ) {
82658
+ const remaining = deadline - now().getTime();
82659
+ if (remaining <= 0) return result(false);
82660
+ const controller = new AbortController();
82661
+ const timer = setTimeout(() => controller.abort(), remaining);
82662
+ let response;
82663
+ polls++;
82664
+ try {
82665
+ response = await client.getOrder(input2.orderId, { signal: controller.signal });
82666
+ } catch (error61) {
82667
+ if (controller.signal.aborted) return result(false);
82668
+ throw error61;
82669
+ } finally {
82670
+ clearTimeout(timer);
82671
+ }
82672
+ if (controller.signal.aborted || now().getTime() >= deadline) return result(false);
82673
+ const { workOrder } = response;
82674
+ milestone = workOrder.id === input2.orderId && workOrder.version === "work-order-view-v1" ? workOrder.milestones.find(
82675
+ (item) => item.id === input2.milestoneId && item.workOrderId === input2.orderId
82676
+ ) : void 0;
82677
+ if (milestone && reachedTarget(milestone, input2.target)) return result(true);
82678
+ await sleep(Math.min(intervalMs, deadline - now().getTime()));
82679
+ }
82680
+ }
82681
+ function reachedTarget(milestone, target) {
82682
+ switch (target) {
82683
+ case "created":
82684
+ return milestone.escrowState !== null;
82685
+ case "locked":
82686
+ return ["locked", "submitted", "disputed", "resolved"].includes(milestone.escrowState ?? "");
82687
+ case "delivered":
82688
+ return ["submitted", "disputed", "resolved"].includes(milestone.escrowState ?? "");
82689
+ case "released":
82690
+ return milestone.escrowState === "resolved";
82691
+ }
82692
+ }
82693
+
82372
82694
  // ../core/src/tasks/rpc.ts
82373
82695
  function createTasksRpcFor(config2, options = {}) {
82374
82696
  const clients = /* @__PURE__ */ new Map();
@@ -83485,7 +83807,10 @@ async function taskRequest(verb, route, operation, options) {
83485
83807
  "not_signed_in",
83486
83808
  `${verb} needs sign-in. ${options.signInHint}`
83487
83809
  );
83488
- throw new TaskOperationError(error61.serverCode ?? error61.code, error61.message);
83810
+ throw new TaskOperationError(
83811
+ error61.serverCode ?? (error61.status ? `http_${error61.status}` : error61.code),
83812
+ error61.message
83813
+ );
83489
83814
  }
83490
83815
  throw error61;
83491
83816
  }
@@ -83606,7 +83931,8 @@ function proposalTerms(id2, address4, deployment, terms) {
83606
83931
  return {
83607
83932
  version: "work-proposal-v1",
83608
83933
  workOrderId: id2,
83609
- providerAddress: address4,
83934
+ // The server lowercases addresses before canonicalizing the signed payload.
83935
+ providerAddress: address4.toLowerCase(),
83610
83936
  pricingModel: "fixed",
83611
83937
  milestones: [
83612
83938
  {
@@ -83993,6 +84319,55 @@ async function showTask(context, input2) {
83993
84319
  };
83994
84320
  }
83995
84321
  async function taskStatus(context, input2) {
84322
+ if (input2.signedIn) {
84323
+ const chainState = await taskRequest(
84324
+ "status",
84325
+ "chainState",
84326
+ async () => {
84327
+ try {
84328
+ return await context.client.chainState(input2.id);
84329
+ } catch (error61) {
84330
+ if (error61 instanceof TasksClientError && error61.status === 404) {
84331
+ if (isMissingTaskEntity(error61.serverCode, error61.message))
84332
+ throw new TaskOperationError("not_found", error61.message);
84333
+ throw new TaskOperationError(
84334
+ "not_available",
84335
+ "GET /v1/work-orders/:id/chain-state is not available on this server."
84336
+ );
84337
+ }
84338
+ throw error61;
84339
+ }
84340
+ },
84341
+ context
84342
+ );
84343
+ if (chainState.workOrderId !== input2.id)
84344
+ throw new TaskOperationError("invalid_response", "The response belongs to a different task.");
84345
+ const page = await taskRequest(
84346
+ "status",
84347
+ "events",
84348
+ async () => {
84349
+ try {
84350
+ return await context.client.events(input2.id, { wait: 0 });
84351
+ } catch (error61) {
84352
+ if (error61 instanceof TasksClientError && error61.status === 404) {
84353
+ if (isMissingTaskEntity(error61.serverCode, error61.message)) return null;
84354
+ throw new TaskOperationError(
84355
+ "not_available",
84356
+ "GET /v1/work-orders/:id/events is not available on this server."
84357
+ );
84358
+ }
84359
+ throw error61;
84360
+ }
84361
+ },
84362
+ context
84363
+ );
84364
+ return {
84365
+ task: { id: input2.id },
84366
+ chainState,
84367
+ events: page ? [...page.events].sort((a, b) => a.sequence - b.sequence) : null,
84368
+ nextAfter: page?.nextAfter ?? null
84369
+ };
84370
+ }
83996
84371
  const task = await taskRequest(
83997
84372
  "status",
83998
84373
  "publicTask",
@@ -84348,6 +84723,7 @@ var searchEventSchema = external_exports.strictObject({
84348
84723
  source: external_exports.string().min(1),
84349
84724
  latencyMs: external_exports.number().nonnegative().finite(),
84350
84725
  count: external_exports.number().int().nonnegative(),
84726
+ dropped: external_exports.number().int().nonnegative().optional(),
84351
84727
  error: external_exports.string().optional()
84352
84728
  })
84353
84729
  ),
@@ -87598,7 +87974,7 @@ var memberBundleConfigSchema = external_exports.unknown().refine((value) => !has
87598
87974
  external_exports.strictObject({ usdc: external_exports.string() })
87599
87975
  ).refine(
87600
87976
  (networks) => Object.entries(networks).every(
87601
- ([id2, network]) => isMemberBundleNetwork(id2) && network.usdc === NETWORKS[id2].usdc
87977
+ ([id2, network]) => isMemberBundleNetwork(id2) && network.usdc === NETWORKS2[id2].usdc
87602
87978
  ),
87603
87979
  { message: "Expected the canonical USDC token of each network." }
87604
87980
  ).refine((networks) => Object.keys(networks).length === 1, {
@@ -87637,14 +88013,14 @@ function memberBundleConfig(owner, network) {
87637
88013
  return {
87638
88014
  discoveryUrl,
87639
88015
  marketplaceDiscoveryUrl,
87640
- networks: { [network]: { usdc: NETWORKS[network].usdc } }
88016
+ networks: { [network]: { usdc: NETWORKS2[network].usdc } }
87641
88017
  };
87642
88018
  }
87643
88019
  function headlessConfigFromBundle(config2) {
87644
88020
  const networks = {};
87645
88021
  for (const [id2, network] of Object.entries(config2.networks)) {
87646
88022
  if (!isMemberBundleNetwork(id2) || network === void 0) continue;
87647
- networks[id2] = { rpcUrl: NETWORKS[id2].publicRpcUrl, usdc: network.usdc };
88023
+ networks[id2] = { rpcUrl: NETWORKS2[id2].publicRpcUrl, usdc: network.usdc };
87648
88024
  }
87649
88025
  return configSchema.parse({
87650
88026
  discoveryUrl: config2.discoveryUrl,
@@ -87737,7 +88113,7 @@ function parseStoredTokens(value) {
87737
88113
  }
87738
88114
  }
87739
88115
  function isMemberBundleNetwork(id2) {
87740
- return Object.hasOwn(NETWORKS, id2) && typeof NETWORKS[id2].publicRpcUrl === "string";
88116
+ return Object.hasOwn(NETWORKS2, id2) && typeof NETWORKS2[id2].publicRpcUrl === "string";
87741
88117
  }
87742
88118
  function hasForbiddenConfigKey(value) {
87743
88119
  if (Array.isArray(value)) return value.some(hasForbiddenConfigKey);
@@ -87942,6 +88318,7 @@ __export(src_exports3, {
87942
88318
  STARTING_RECONCILIATION_TIMEOUT_MS: () => STARTING_RECONCILIATION_TIMEOUT_MS,
87943
88319
  SwarmRunError: () => SwarmRunError,
87944
88320
  UNTRUSTED_NOTICE: () => UNTRUSTED_NOTICE,
88321
+ VapiCallError: () => VapiCallError,
87945
88322
  WalletSession: () => WalletSession,
87946
88323
  accountsSend: () => accountsSend,
87947
88324
  accountsSendInputSchema: () => accountsSendInputSchema,
@@ -88397,11 +88774,28 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
88397
88774
  }
88398
88775
  }
88399
88776
  });
88400
- const page = marketplaceDiscoveryPageSchema.parse(await response.json());
88401
- mergedCount = page.items.length;
88777
+ const envelope = marketplaceDiscoveryEnvelopeSchema.parse(await response.json());
88778
+ const items = [];
88779
+ let dropped = 0;
88780
+ for (const [index2, rawItem] of envelope.items.entries()) {
88781
+ const parsed = marketplaceHitSchema.safeParse(rawItem);
88782
+ if (parsed.success) {
88783
+ items.push(parsed.data);
88784
+ continue;
88785
+ }
88786
+ dropped += 1;
88787
+ try {
88788
+ options.debug?.(`vAPI marketplace discovery dropped invalid row at index ${index2}.`);
88789
+ } catch {
88790
+ }
88791
+ }
88792
+ mergedCount = items.length;
88402
88793
  const attempt = attempts.at(-1);
88403
- if (attempt) attempt.count = mergedCount;
88404
- return page;
88794
+ if (attempt) {
88795
+ attempt.count = mergedCount;
88796
+ if (dropped > 0) attempt.dropped = dropped;
88797
+ }
88798
+ return { ...envelope, items };
88405
88799
  } finally {
88406
88800
  if (options.searchesPath) {
88407
88801
  await appendSearchEvent(
@@ -88685,6 +89079,34 @@ var VapiCallError = class extends Error {
88685
89079
  paymentRejection;
88686
89080
  confirmedSettlement;
88687
89081
  };
89082
+ var SOLANA_PAYMENTS_UNSUPPORTED_MESSAGE = "Solana payments are not supported in this version of vAPI yet; they arrive in a later release.";
89083
+ function isSolanaCaip2(network) {
89084
+ return network.startsWith("solana:");
89085
+ }
89086
+ function listingPaymentNetwork(endpointNetwork, serviceNetworks) {
89087
+ if (endpointNetwork !== void 0) return endpointNetwork;
89088
+ return serviceNetworks?.length && serviceNetworks.every(isSolanaCaip2) ? serviceNetworks[0] : void 0;
89089
+ }
89090
+ function assertSupportedListingNetwork(network) {
89091
+ if (network !== void 0 && isSolanaCaip2(network)) {
89092
+ throw new VapiCallError(
89093
+ "unsupported_network",
89094
+ `${SOLANA_PAYMENTS_UNSUPPORTED_MESSAGE} This listing pays on ${network}.`
89095
+ );
89096
+ }
89097
+ }
89098
+ function assertSupportedListingResolution(error61) {
89099
+ if (isDiscoveryCatalogError(error61) && error61.code === "ambiguous_default" && error61.paymentNetworks?.length && error61.paymentNetworks.every(isSolanaCaip2)) {
89100
+ assertSupportedListingNetwork(error61.paymentNetworks[0]);
89101
+ }
89102
+ }
89103
+ function payableConfig(config2, account) {
89104
+ if (account.solana !== void 0) return config2;
89105
+ const networks = Object.fromEntries(
89106
+ Object.entries(config2.networks).filter(([network]) => !isSolanaCaip2(network))
89107
+ );
89108
+ return { ...config2, networks };
89109
+ }
88688
89110
  var MAX_RESPONSE_BYTES = 1048576;
88689
89111
  var BODY_HEADER_NAMES = [
88690
89112
  "content-encoding",
@@ -88694,12 +89116,15 @@ var BODY_HEADER_NAMES = [
88694
89116
  "content-type"
88695
89117
  ];
88696
89118
  async function callService(args) {
89119
+ validateTimeoutSeconds(args.input.timeoutSeconds);
88697
89120
  const trace = createCallTrace(args);
88698
89121
  let execution;
88699
89122
  try {
88700
89123
  execution = await executeCallService(args, trace);
88701
89124
  } catch (error61) {
88702
- await recordCallError(args, error61, trace).catch(() => void 0);
89125
+ if (!(error61 instanceof VapiCallError && (error61.code === "unsupported_network" || error61.code === "unsupported_payment"))) {
89126
+ await recordCallError(args, error61, trace).catch(() => void 0);
89127
+ }
88703
89128
  throw error61;
88704
89129
  }
88705
89130
  try {
@@ -88747,10 +89172,16 @@ async function executeCallService(args, trace) {
88747
89172
  config2,
88748
89173
  fetchImpl
88749
89174
  );
89175
+ } catch (error61) {
89176
+ assertSupportedListingResolution(error61);
89177
+ throw error61;
88750
89178
  } finally {
88751
89179
  trace.phases.discoverMs = elapsed2(trace, discoverStarted);
88752
89180
  }
88753
89181
  }
89182
+ assertSupportedListingNetwork(
89183
+ listingPaymentNetwork(endpoint?.payment?.network, endpoint?.serviceNetworks)
89184
+ );
88754
89185
  const requestedNetwork = normalizeRequiredNetwork(input2.network);
88755
89186
  const listingNetwork = endpoint?.payment?.network;
88756
89187
  if (requestedNetwork && listingNetwork && !areSamePaymentNetwork(requestedNetwork, listingNetwork)) {
@@ -88805,6 +89236,8 @@ async function executeCallService(args, trace) {
88805
89236
  body: method === "GET" || method === "HEAD" ? void 0 : requestBody
88806
89237
  });
88807
89238
  const request = createRequest(headers);
89239
+ const probeTimeoutMs = input2.timeoutSeconds === void 0 ? args.timeoutMs ?? 3e4 : Math.min(input2.timeoutSeconds, 30) * 1e3;
89240
+ let requestTimeoutMs = probeTimeoutMs;
88808
89241
  const fetchWithGuardedRedirects = async (candidateRequest, followRedirects = true) => {
88809
89242
  let currentRequest = candidateRequest;
88810
89243
  let followedRedirects = 0;
@@ -88812,7 +89245,7 @@ async function executeCallService(args, trace) {
88812
89245
  const attempt = await fetchAttempt(
88813
89246
  fetchImpl,
88814
89247
  new Request(currentRequest.clone(), { redirect: "manual" }),
88815
- args.timeoutMs ?? 3e4
89248
+ requestTimeoutMs
88816
89249
  );
88817
89250
  const response = attempt.response;
88818
89251
  if (!isRedirectStatus2(response.status)) {
@@ -88966,8 +89399,13 @@ async function executeCallService(args, trace) {
88966
89399
  challenge: challengeAttempt,
88967
89400
  account,
88968
89401
  caps: args.spendCaps ?? config2.spendCaps,
88969
- config: config2,
88970
- send: async (paidRequest) => {
89402
+ config: payableConfig(config2, account),
89403
+ send: async (paidRequest, quote) => {
89404
+ requestTimeoutMs = paidRequestTimeoutMs(
89405
+ input2.timeoutSeconds,
89406
+ args.timeoutMs,
89407
+ quote.accepted.maxTimeoutSeconds
89408
+ );
88971
89409
  paidAttempt = await fetchWithGuardedRedirects(paidRequest, false);
88972
89410
  return paidAttempt;
88973
89411
  },
@@ -89006,7 +89444,7 @@ async function executeCallService(args, trace) {
89006
89444
  asset: completed.quote.accepted.asset,
89007
89445
  payTo: completed.quote.accepted.payTo,
89008
89446
  settlement: settlementWithExplorer2(completed.settlement, completed.quote.accepted.network),
89009
- proof: completed.response.headers.get("x-vapi-payment-proof")
89447
+ proof: completed.paymentProof
89010
89448
  },
89011
89449
  ...verificationFor(endpoint),
89012
89450
  ...expectedRequestFor(endpoint, completed.response.status)
@@ -89216,7 +89654,7 @@ async function resolveCallEndpoint(id2, endpointName, marketplaceHit, config2, f
89216
89654
  try {
89217
89655
  return registeredEndpoint(await resolveServiceListing(id2, config2, fetchImpl, endpointName));
89218
89656
  } catch (error61) {
89219
- if (!(error61 instanceof DiscoveryCatalogError) || error61.code !== "service_not_found") {
89657
+ if (!isDiscoveryCatalogError(error61) || error61.code !== "service_not_found") {
89220
89658
  throw error61;
89221
89659
  }
89222
89660
  const discovered = await findMarketplaceApiByRef(id2, config2, fetchImpl);
@@ -89253,9 +89691,18 @@ async function resolveCallEndpoint(id2, endpointName, marketplaceHit, config2, f
89253
89691
  );
89254
89692
  }
89255
89693
  function registeredEndpoint(listing, verification) {
89694
+ const { payment, ...endpoint } = listing.endpoint;
89695
+ if (payment && (typeof payment.protocol === "string" || typeof payment.network !== "string")) {
89696
+ throw new VapiCallError(
89697
+ "unsupported_payment",
89698
+ `Payment protocol ${payment.protocol} is not supported. This client pays x402 exact USDC endpoints only.`
89699
+ );
89700
+ }
89256
89701
  return {
89257
- ...listing.endpoint,
89702
+ ...endpoint,
89703
+ ...payment ? { payment: { network: payment.network, payTo: payment.payTo } } : {},
89258
89704
  verification: verification ?? listing.service.verification,
89705
+ serviceNetworks: listing.service.networks,
89259
89706
  registered: true,
89260
89707
  resolvedListing: true
89261
89708
  };
@@ -89415,7 +89862,7 @@ async function readResponseBody2(response) {
89415
89862
  async function fetchAttempt(fetchImpl, request, timeoutMs) {
89416
89863
  const controller = new AbortController();
89417
89864
  let rejectTimeout = null;
89418
- const timeoutError = new Error(`API request timed out after ${timeoutMs}ms.`);
89865
+ const timeoutError = new Error(`API request timed out after ${timeoutMs / 1e3} seconds.`);
89419
89866
  const timedOut = new Promise((_resolve, reject) => {
89420
89867
  rejectTimeout = reject;
89421
89868
  });
@@ -89455,6 +89902,19 @@ async function fetchAttempt(fetchImpl, request, timeoutMs) {
89455
89902
  throw error61;
89456
89903
  }
89457
89904
  }
89905
+ function validateTimeoutSeconds(timeoutSeconds) {
89906
+ if (timeoutSeconds !== void 0 && (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 300)) {
89907
+ throw new Error("call timeoutSeconds must be an integer from 1 to 300 seconds.");
89908
+ }
89909
+ }
89910
+ function paidRequestTimeoutMs(timeoutSeconds, internalTimeoutMs, offerTimeoutSeconds) {
89911
+ const usableOfferTimeout = Number.isInteger(offerTimeoutSeconds) && offerTimeoutSeconds > 0 ? offerTimeoutSeconds : void 0;
89912
+ if (timeoutSeconds !== void 0) {
89913
+ return Math.min(timeoutSeconds, usableOfferTimeout ?? timeoutSeconds) * 1e3;
89914
+ }
89915
+ if (internalTimeoutMs !== void 0) return internalTimeoutMs;
89916
+ return usableOfferTimeout === void 0 ? 12e4 : Math.min(12e4, Math.max(3e4, usableOfferTimeout * 1e3));
89917
+ }
89458
89918
  function mapX402PaymentError(error61, resumeId) {
89459
89919
  if (!(error61 instanceof X402PaymentError)) return error61;
89460
89920
  if (error61.code === "payment_rejected") {
@@ -89470,9 +89930,10 @@ function mapX402PaymentError(error61, resumeId) {
89470
89930
  });
89471
89931
  }
89472
89932
  const resume = resumeId !== void 0 && error61.possibleSettlement?.authorizationNonce ? ` Check whether it settled with \`vapi pay --resume ${resumeId}\` before paying again.` : "";
89933
+ const timeoutDetail = error61.cause instanceof Error && error61.cause.message.startsWith("API request timed out after ") ? `${error61.cause.message} ` : "";
89473
89934
  return new VapiCallError(
89474
89935
  "settlement_unknown",
89475
- `${error61.message}${resume}`,
89936
+ `${timeoutDetail}${error61.message}${resume}`,
89476
89937
  error61.possibleSettlement,
89477
89938
  { cause: error61.cause }
89478
89939
  );
@@ -89494,14 +89955,17 @@ async function inspectService(input2, config2, fetchImpl) {
89494
89955
  try {
89495
89956
  listing = await resolveServiceListing(input2.id, config2, fetchImpl, input2.endpoint);
89496
89957
  } catch (error61) {
89497
- if (input2.endpoint || !(error61 instanceof DiscoveryCatalogError) || error61.code !== "service_not_found") {
89958
+ assertSupportedListingResolution(error61);
89959
+ if (input2.endpoint || !isDiscoveryCatalogError(error61) || error61.code !== "service_not_found") {
89498
89960
  throw error61;
89499
89961
  }
89500
89962
  const hit = await findMarketplaceApiByRef(input2.id, config2, fetchImpl);
89501
89963
  if (!hit || hit.kind !== "api" || hit.provenance !== "indexed") throw error61;
89964
+ assertSupportedListingNetwork(hit.execution.network);
89502
89965
  return inspectIndexedHit(hit);
89503
89966
  }
89504
89967
  const { endpoint, service } = listing;
89968
+ assertSupportedListingNetwork(listingPaymentNetwork(endpoint.payment?.network, service.networks));
89505
89969
  return {
89506
89970
  name: endpoint.name,
89507
89971
  method: endpoint.method,
@@ -89601,13 +90065,7 @@ var inspectToolResultSchema = external_exports.object({
89601
90065
  liveness: listingLivenessSchema.optional(),
89602
90066
  conformance: listingConformanceSchema.optional(),
89603
90067
  identity: listingIdentitySchema.optional(),
89604
- payment: external_exports.object({
89605
- scheme: external_exports.literal("exact"),
89606
- network: external_exports.string(),
89607
- asset: external_exports.string(),
89608
- payTo: external_exports.string(),
89609
- checkedAt: external_exports.string()
89610
- }).nullable()
90068
+ payment: discoveryEndpointSchema.shape.payment.unwrap().nullable()
89611
90069
  });
89612
90070
  var callSearchInputSchema = external_exports.object({
89613
90071
  query: external_exports.string().trim().max(200).optional().describe("Capability, API, service, or request."),
@@ -89636,7 +90094,10 @@ var callPayInputSchema = external_exports.object({
89636
90094
  (value) => /^0x[0-9a-fA-F]{40}$/.test(value) || isSolanaAddress(value),
89637
90095
  "Expected an EVM or Solana address."
89638
90096
  ).optional(),
89639
- maxPriceUsd: external_exports.union([external_exports.number().nonnegative(), external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/)]).optional()
90097
+ maxPriceUsd: external_exports.union([external_exports.number().nonnegative(), external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/)]).optional(),
90098
+ timeoutSeconds: external_exports.number().int().min(1).max(300).optional().describe(
90099
+ "Seconds to wait for the paid response. Default: the provider's maxTimeoutSeconds, at most 120."
90100
+ )
89640
90101
  });
89641
90102
  var callSearch = defineAction({
89642
90103
  name: "call.search",
@@ -89899,7 +90360,7 @@ async function readResult(response, signal, secrets = []) {
89899
90360
  return {
89900
90361
  status: response.status,
89901
90362
  contentType: contentType === null ? null : redactKnownSecrets2(contentType, secrets),
89902
- body: sanitizeReturnedValue(await readResponseBody3(response, contentType, signal), secrets)
90363
+ body: sanitizeReturnedValue2(await readResponseBody3(response, contentType, signal), secrets)
89903
90364
  };
89904
90365
  }
89905
90366
  async function readResponseBody3(response, contentType, signal) {
@@ -89944,17 +90405,17 @@ function isJsonContentType2(value) {
89944
90405
  const mediaType = value?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
89945
90406
  return mediaType === "application/json" || mediaType.endsWith("+json");
89946
90407
  }
89947
- function sanitizeReturnedValue(value, secrets, depth = 0) {
90408
+ function sanitizeReturnedValue2(value, secrets, depth = 0) {
89948
90409
  if (typeof value === "string") return redactKnownSecrets2(value, secrets);
89949
90410
  if (value === null || typeof value !== "object") return value;
89950
90411
  if (depth >= 16) return "[redacted nested response value]";
89951
90412
  if (Array.isArray(value)) {
89952
- return value.map((item) => sanitizeReturnedValue(item, secrets, depth + 1));
90413
+ return value.map((item) => sanitizeReturnedValue2(item, secrets, depth + 1));
89953
90414
  }
89954
90415
  return Object.fromEntries(
89955
90416
  Object.entries(value).map(([key2, item]) => [
89956
90417
  redactKnownSecrets2(key2, secrets),
89957
- sanitizeReturnedValue(item, secrets, depth + 1)
90418
+ sanitizeReturnedValue2(item, secrets, depth + 1)
89958
90419
  ])
89959
90420
  );
89960
90421
  }
@@ -93274,6 +93735,7 @@ var moneyParticipant = {
93274
93735
  "Checksummed 0x address of the other party, taken from tasks.show (the poster's clientAddress when you are the worker; the accepted proposal's providerAddress when you are the poster). The human must supply it; it is compared with the signed scope and stored as local consent. Without it tasks.sign refuses and no local party binding is created, so tasks.fund/deliver/release cannot run from this machine."
93275
93736
  ).optional()
93276
93737
  };
93738
+ var waitForIndexer = external_exports.boolean().default(true).describe("Wait up to 60 seconds for vAPI to index the chain result before returning.");
93277
93739
  var cursor = external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
93278
93740
  function usdWithinEscrow(value, positive = false) {
93279
93741
  try {
@@ -93320,7 +93782,10 @@ var tasksPostTool = descriptor(
93320
93782
  deadline: external_exports.string(),
93321
93783
  intake: external_exports.enum(["proposals", "submissions"]).optional(),
93322
93784
  maxAwards: external_exports.number().int().min(TASK_LIMITS.maxAwardsMin).max(TASK_LIMITS.maxAwardsMax).optional(),
93323
- webhookUrl: httpsUrl.optional()
93785
+ webhookUrl: httpsUrl.optional(),
93786
+ vendor: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).describe(
93787
+ "Optional 0x address of a vendor to invite directly; the task is addressed to that wallet and shows up for them. Anyone may still propose."
93788
+ ).optional()
93324
93789
  }
93325
93790
  );
93326
93791
  var tasksProposeTool = descriptor(
@@ -93345,42 +93810,43 @@ var tasksAwardTool = descriptor(
93345
93810
  { ...participant, proposalId: id }
93346
93811
  );
93347
93812
  var tasksSignTool = descriptor(
93348
- "Does not move money. Sign the current counterparty scope locally after the human confirms the money direction via counterparty; a worker may also create the unfunded escrow with the local vault wallet.",
93349
- moneyParticipant
93813
+ "Signs the user's own task scope locally with the user's vault wallet after the human confirms the money direction via counterparty; a worker may also create the unfunded escrow; nothing is custodial. Does not move money. Waits up to 60 seconds for vAPI to index a created escrow by default.",
93814
+ { ...moneyParticipant, wait: waitForIndexer }
93350
93815
  );
93351
93816
  var tasksFundTool = descriptor(
93352
- "Moves money: locks the task amount in USDC escrow subject to the acting wallet's policy and daily cap. MCP cannot grant human approval; amounts above the approval threshold are refused with approval:true.",
93353
- moneyParticipant
93817
+ "Executes the user's own funding of this task from the user's vault wallet, within the spend policy the user configured; nothing is custodial. MCP cannot grant human approval; amounts above the approval threshold are refused with approval:true. Waits up to 60 seconds for vAPI to index the locked escrow by default.",
93818
+ { ...moneyParticipant, wait: waitForIndexer }
93354
93819
  );
93355
93820
  var tasksDeliverTool = descriptor(
93356
- "Does not move money. Upload local delivery files, freeze the manifest and record delivery with the local vault wallet.",
93821
+ "Does not move money. Upload local delivery files, freeze the manifest and record delivery with the local vault wallet. Waits up to 60 seconds for vAPI to index the delivery by default.",
93357
93822
  {
93358
93823
  ...moneyParticipant,
93824
+ wait: waitForIndexer,
93359
93825
  files: external_exports.array(localPath).min(TASK_LIMITS.deliveryFilesMin).max(TASK_LIMITS.deliveryFilesMax),
93360
93826
  note: external_exports.string().max(TASK_LIMITS.deliveryNoteMax).refine((value) => value.trim().length > 0)
93361
93827
  }
93362
93828
  );
93363
93829
  var tasksReleaseTool = descriptor(
93364
- "Moves money: pays the worker from escrow with the local vault wallet. Returns gross \xB7 fee \xB7 net using the deployed fee.",
93365
- moneyParticipant
93830
+ "Executes the user's own payment to the worker from task escrow with the user's vault wallet; nothing is custodial. Returns gross \xB7 fee \xB7 net using the deployed fee. Waits up to 60 seconds for vAPI to index the release by default.",
93831
+ { ...moneyParticipant, wait: waitForIndexer }
93366
93832
  );
93367
93833
  var tasksRefundTool = descriptor(
93368
- "Moves money: returns escrowed USDC to the poster with the local vault wallet. Returns gross \xB7 fee \xB7 net using the deployed fee.",
93834
+ "Executes the user's own refund of escrowed USDC to the poster with the user's vault wallet; nothing is custodial. Returns gross \xB7 fee \xB7 net using the deployed fee.",
93369
93835
  moneyParticipant
93370
93836
  );
93371
93837
  var tasksDisputeTool = descriptor(
93372
- "Moves money: approves the verified dispute fee and raises a dispute with the local vault wallet. Applies task and daily caps; MCP refuses human approval with approval:true. Accepts a precomputed evidence hash.",
93838
+ "Executes the user's own approval of the verified dispute fee and raises a dispute with the user's vault wallet; nothing is custodial. Applies task and daily caps; MCP refuses human approval with approval:true. Accepts a precomputed evidence hash.",
93373
93839
  {
93374
93840
  ...moneyParticipant,
93375
93841
  evidenceHash: external_exports.string().regex(TASK_LIMITS.disputeEvidenceHash)
93376
93842
  }
93377
93843
  );
93378
93844
  var tasksCounterEvidenceTool = descriptor(
93379
- "Moves money: approves the verified dispute fee and submits counter-evidence as the non-opener before the onchain deadline. Applies task and daily caps; MCP refuses human approval with approval:true.",
93845
+ "Executes the user's own counter-evidence submission and approval of the verified dispute fee with the user's vault wallet as the non-opener before the onchain deadline; nothing is custodial. Applies task and daily caps; MCP refuses human approval with approval:true.",
93380
93846
  { ...moneyParticipant, evidenceHash: external_exports.string().regex(TASK_LIMITS.disputeEvidenceHash) }
93381
93847
  );
93382
93848
  var tasksResolveUnmatchedTool = descriptor(
93383
- "Moves money: resolves an unmatched dispute after the onchain counter-evidence deadline when no counter-evidence was submitted.",
93849
+ "Executes the user's own resolution of an unmatched dispute with the user's vault wallet after the onchain counter-evidence deadline when no counter-evidence was submitted; nothing is custodial.",
93384
93850
  moneyParticipant
93385
93851
  );
93386
93852
  var tasksMessageTool = descriptor(
@@ -93404,8 +93870,8 @@ var tasksWatchTool = descriptor(
93404
93870
  }
93405
93871
  );
93406
93872
  var tasksStatusTool = descriptor(
93407
- "Does not move money. Read the public task card and receipt URL when settled; sign-in is not required.",
93408
- { id }
93873
+ "Does not move money. Read signed-in chain state and participant events, or the public task card without sign-in.",
93874
+ participant
93409
93875
  );
93410
93876
  var signInHint = "Call auth.link for the acting wallet.";
93411
93877
  function lazyTasksChain(factory, pending) {
@@ -93545,6 +94011,22 @@ function createTasksTools(options) {
93545
94011
  };
93546
94012
  };
93547
94013
  }
94014
+ async function waitAfterChain(ctx, orderId, milestoneId, target) {
94015
+ return await taskRequest(
94016
+ target,
94017
+ "getOrder",
94018
+ () => waitForMilestone(ctx.client, {
94019
+ orderId,
94020
+ milestoneId,
94021
+ target,
94022
+ timeoutMs: 6e4,
94023
+ intervalMs: 3e3,
94024
+ ...options.sleep === void 0 ? {} : { sleep: options.sleep },
94025
+ now
94026
+ }),
94027
+ ctx
94028
+ );
94029
+ }
93548
94030
  async function feeAction(verb, input2) {
93549
94031
  const ctx = await acting(input2.wallet);
93550
94032
  const policy = await taskPolicyForWallet({
@@ -93587,7 +94069,12 @@ function createTasksTools(options) {
93587
94069
  throw new TaskInputError("deadline must be at least 10 minutes from now.");
93588
94070
  const ctx = await acting(input2.wallet);
93589
94071
  const outcome = await postTask(ctx, {
93590
- order: { title: input2.title, description: input2.brief, policyFamily: "general-digital" },
94072
+ order: {
94073
+ title: input2.title,
94074
+ description: input2.brief,
94075
+ policyFamily: "general-digital",
94076
+ ...input2.vendor === void 0 ? {} : { invitedProviderAddress: input2.vendor }
94077
+ },
93591
94078
  amount: parseUsdToBaseUnits(input2.amountUsd),
93592
94079
  deadlineAt: new Date(postedAt.getTime() + deadlineDuration).toISOString(),
93593
94080
  ...input2.intake === void 0 ? {} : { intake: input2.intake },
@@ -93645,15 +94132,15 @@ function createTasksTools(options) {
93645
94132
  const ctx = await acting(input2.wallet);
93646
94133
  const signerAddress = (await options.session.addressesFor(ctx.selected.name)).address;
93647
94134
  try {
93648
- return taskResult(
93649
- await signTaskScope(ctx, {
93650
- id: input2.id,
93651
- counterparty: input2.counterparty,
93652
- signerAddress,
93653
- bindings: createScopeBindings(home),
93654
- signMessage: async (message) => (await unlock(ctx.selected.name)()).signMessage(message)
93655
- })
93656
- );
94135
+ const outcome = await signTaskScope(ctx, {
94136
+ id: input2.id,
94137
+ counterparty: input2.counterparty,
94138
+ signerAddress,
94139
+ bindings: createScopeBindings(home),
94140
+ signMessage: async (message) => (await unlock(ctx.selected.name)()).signMessage(message)
94141
+ });
94142
+ const wait2 = input2.wait && outcome.escrowCreation ? await waitAfterChain(ctx, input2.id, outcome.escrowCreation.milestone.id, "created") : null;
94143
+ return taskResult({ ...outcome, wait: wait2 });
93657
94144
  } catch (error61) {
93658
94145
  if (!(error61 instanceof TasksScopeCreationError)) throw error61;
93659
94146
  try {
@@ -93689,28 +94176,31 @@ function createTasksTools(options) {
93689
94176
  // Stdio has no human approval channel. Model arguments cannot grant approval.
93690
94177
  approval: { granted: false }
93691
94178
  });
93692
- return taskResult(outcome, !outcome.ok);
94179
+ const wait2 = input2.wait && outcome.ok ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "locked") : null;
94180
+ return taskResult({ ...outcome, wait: wait2 }, !outcome.ok);
93693
94181
  },
93694
94182
  async deliver(input2) {
93695
94183
  const files = (await Promise.all(input2.files.map(readTaskFile))).map(
93696
94184
  ({ fileName: name, bytes, contentType }) => ({ name, bytes, contentType })
93697
94185
  );
93698
- return taskResult(
93699
- await deliverTaskOperation(await acting(input2.wallet), {
93700
- id: input2.id,
93701
- ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty },
93702
- files,
93703
- note: input2.note
93704
- })
93705
- );
94186
+ const ctx = await acting(input2.wallet);
94187
+ const outcome = await deliverTaskOperation(ctx, {
94188
+ id: input2.id,
94189
+ ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty },
94190
+ files,
94191
+ note: input2.note
94192
+ });
94193
+ const wait2 = input2.wait ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "delivered") : null;
94194
+ return taskResult({ ...outcome, wait: wait2 });
93706
94195
  },
93707
94196
  async release(input2) {
93708
- return taskResult(
93709
- await releaseTaskOperation(await acting(input2.wallet), {
93710
- id: input2.id,
93711
- ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty }
93712
- })
93713
- );
94197
+ const ctx = await acting(input2.wallet);
94198
+ const outcome = await releaseTaskOperation(ctx, {
94199
+ id: input2.id,
94200
+ ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty }
94201
+ });
94202
+ const wait2 = input2.wait ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "released") : null;
94203
+ return taskResult({ ...outcome, wait: wait2 });
93714
94204
  },
93715
94205
  async refund(input2) {
93716
94206
  return taskResult(
@@ -93777,7 +94267,11 @@ function createTasksTools(options) {
93777
94267
  }
93778
94268
  },
93779
94269
  async status(input2) {
93780
- return taskResult(await taskStatus(await context(void 0, true), { id: input2.id }));
94270
+ await options.wallets?.reload();
94271
+ const publicOnly = input2.wallet === void 0 && options.session.activeName === void 0 && options.wallets !== void 0 && options.wallets.names().length === 0;
94272
+ const candidate = await context(input2.wallet, publicOnly);
94273
+ const ctx = candidate.token || publicOnly ? candidate : await context(void 0, true);
94274
+ return taskResult(await taskStatus(ctx, { id: input2.id, signedIn: Boolean(ctx.token) }));
93781
94275
  }
93782
94276
  };
93783
94277
  }
@@ -94534,6 +95028,11 @@ var statsToolResultSchema = external_exports.object({
94534
95028
  )
94535
95029
  })
94536
95030
  });
95031
+ function objectOutputSchema(schema) {
95032
+ if (!schema) return {};
95033
+ const json2 = external_exports.toJSONSchema(schema);
95034
+ return json2.type === "object" ? { outputSchema: json2 } : {};
95035
+ }
94537
95036
  var VapiMcpServer = class {
94538
95037
  #tools = /* @__PURE__ */ new Map();
94539
95038
  #onClose;
@@ -94557,7 +95056,7 @@ var VapiMcpServer = class {
94557
95056
  name,
94558
95057
  ...tool.description ? { description: tool.description } : {},
94559
95058
  inputSchema: external_exports.toJSONSchema(tool.inputSchema),
94560
- ...tool.outputSchema ? { outputSchema: external_exports.toJSONSchema(tool.outputSchema) } : {}
95059
+ ...objectOutputSchema(tool.outputSchema)
94561
95060
  }))
94562
95061
  };
94563
95062
  }
@@ -95428,7 +95927,13 @@ function toolError(error61) {
95428
95927
  {
95429
95928
  error: error61.message,
95430
95929
  code: error61.code,
95431
- ...error61.possibleSettlement ? { possibleSettlement: error61.possibleSettlement } : {},
95930
+ ...error61.possibleSettlement ? {
95931
+ possibleSettlement: Object.fromEntries(
95932
+ Object.entries(error61.possibleSettlement).filter(
95933
+ ([key2]) => key2 !== "authorizationTransaction"
95934
+ )
95935
+ )
95936
+ } : {},
95432
95937
  ...error61.paymentRejection ? { paymentRejection: error61.paymentRejection } : {},
95433
95938
  ...error61.confirmedSettlement ? { confirmedSettlement: error61.confirmedSettlement } : {}
95434
95939
  },
@@ -98922,7 +99427,7 @@ async function readProcessStdin() {
98922
99427
  }
98923
99428
 
98924
99429
  // ../cli/src/version.ts
98925
- var CLI_VERSION = "0.9.0";
99430
+ var CLI_VERSION = "0.9.4";
98926
99431
 
98927
99432
  // ../cli/src/status.ts
98928
99433
  async function statusCommand(argv, json2, io, dependencies) {
@@ -102424,7 +102929,7 @@ function createLocalRuntime(options) {
102424
102929
  const processCommand = options.processCommand ?? defaultProcessCommand;
102425
102930
  const ownsProcess = (handle, pid) => processCommand(pid)?.includes(runResultPath(home, handle.runId)) === true;
102426
102931
  const closeFd = options.closeFd ?? closeSync2;
102427
- const readFile30 = options.readFile ?? nodeReadFile;
102932
+ const readFile31 = options.readFile ?? nodeReadFile;
102428
102933
  const now = options.now ?? (() => /* @__PURE__ */ new Date());
102429
102934
  const openLog = options.openLog ?? ((path) => {
102430
102935
  mkdirSync2(runsDirectory(home), { recursive: true, mode: 448 });
@@ -102479,7 +102984,7 @@ function createLocalRuntime(options) {
102479
102984
  return handle;
102480
102985
  },
102481
102986
  async status(handle) {
102482
- const result = await readResultFile(readFile30, runResultPath(home, handle.runId));
102987
+ const result = await readResultFile(readFile31, runResultPath(home, handle.runId));
102483
102988
  if (result !== void 0) return result;
102484
102989
  const pid = localPid(handle);
102485
102990
  if (pid === void 0 || handle.kind !== "local") {
@@ -102582,10 +103087,10 @@ function childArguments(member, run) {
102582
103087
  ...run.drawUsd ? ["--draw", run.drawUsd] : []
102583
103088
  ];
102584
103089
  }
102585
- async function readResultFile(readFile30, path) {
103090
+ async function readResultFile(readFile31, path) {
102586
103091
  let text;
102587
103092
  try {
102588
- text = await readFile30(path, "utf8");
103093
+ text = await readFile31(path, "utf8");
102589
103094
  } catch (error61) {
102590
103095
  if (hasCode3(error61, "ENOENT")) return void 0;
102591
103096
  return { state: "failed", detail: "unreadable result file" };
@@ -103435,7 +103940,7 @@ function isMcpInstallApp(value) {
103435
103940
  function serverEntry(home, registry2) {
103436
103941
  return {
103437
103942
  command: "npx",
103438
- args: ["-y", "vapi-network", "mcp"],
103943
+ args: ["-y", "vapi-network@latest", "mcp"],
103439
103944
  env: { VAPI_HOME: home, VAPI_REGISTRY_URL: registry2 }
103440
103945
  };
103441
103946
  }
@@ -103484,7 +103989,7 @@ function tomlConfig(existing, entry) {
103484
103989
  const block = [
103485
103990
  "[mcp_servers.vapi]",
103486
103991
  'command = "npx"',
103487
- 'args = ["-y", "vapi-network", "mcp"]',
103992
+ 'args = ["-y", "vapi-network@latest", "mcp"]',
103488
103993
  `env = { VAPI_HOME = "${escapeToml(entry.env.VAPI_HOME)}", VAPI_REGISTRY_URL = "${escapeToml(entry.env.VAPI_REGISTRY_URL)}" }`,
103489
103994
  ""
103490
103995
  ].join("\n");
@@ -103651,13 +104156,13 @@ async function sendConfig(dependencies) {
103651
104156
  // ../cli/src/setup.ts
103652
104157
  import { rm as rm5 } from "node:fs/promises";
103653
104158
  import { join as join26 } from "node:path";
103654
- var SETUP_ARGUMENT_ERROR = "vapi setup accepts only --no-cloud-backup; a recovery phrase is typed at the prompt, never passed on the command line.";
104159
+ 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.`;
103655
104160
  var VAULT_CHOICE = "Create a new vault, or restore one from a recovery phrase? [new/restore] ";
103656
104161
  async function setupCommand(argv, json2, io, dependencies) {
103657
104162
  let parsed;
103658
104163
  try {
103659
104164
  parsed = parseArguments(argv, {
103660
- valueOptions: /* @__PURE__ */ new Set(),
104165
+ valueOptions: /* @__PURE__ */ new Set(["--accounts"]),
103661
104166
  booleanOptions: /* @__PURE__ */ new Set(["--no-cloud-backup"]),
103662
104167
  maximumPositionals: 0
103663
104168
  });
@@ -103668,6 +104173,7 @@ async function setupCommand(argv, json2, io, dependencies) {
103668
104173
  const paths = getVapiPaths();
103669
104174
  const steps = [];
103670
104175
  const humanIo = json2 ? stderrIo(io) : io;
104176
+ const accountCount = parseAccountCount(parsed.one("--accounts"));
103671
104177
  if (!await fileExists2(paths.config)) {
103672
104178
  await writeDefaultConfig(paths.config, process.env, { networks: ["base"] });
103673
104179
  steps.push("config");
@@ -103678,6 +104184,7 @@ async function setupCommand(argv, json2, io, dependencies) {
103678
104184
  let changedVault = false;
103679
104185
  let changedAccount = false;
103680
104186
  let changedLink = false;
104187
+ let scannedAddresses;
103681
104188
  if (!await fileExists2(join26(paths.directory, "vault.json"))) {
103682
104189
  const choice = await vaultChoice(dependencies);
103683
104190
  if (choice === "restore") {
@@ -103685,12 +104192,14 @@ async function setupCommand(argv, json2, io, dependencies) {
103685
104192
  throw new Error("Restoring needs a terminal to type the phrase.");
103686
104193
  }
103687
104194
  const readSecret = dependencies.prompts?.secret ?? promptForSecret;
103688
- await restoreVaultFromPhrase(
104195
+ const restored = await restoreVaultFromPhrase(
103689
104196
  await readSecret("Recovery phrase: "),
103690
104197
  config2,
103691
104198
  humanIo,
103692
- dependencies
104199
+ dependencies,
104200
+ accountCount
103693
104201
  );
104202
+ scannedAddresses = restored.scannedAddresses;
103694
104203
  store = await WalletStore.open(paths.directory, {
103695
104204
  secrets: getSecretStore(dependencies),
103696
104205
  env: dependencies.env ?? process.env,
@@ -103743,22 +104252,35 @@ async function setupCommand(argv, json2, io, dependencies) {
103743
104252
  }
103744
104253
  if (json2) {
103745
104254
  io.stdout(
103746
- JSON.stringify({ vault, account, address: address4, linked, steps, cloudBackup })
104255
+ JSON.stringify({
104256
+ vault,
104257
+ account,
104258
+ address: address4,
104259
+ linked,
104260
+ steps,
104261
+ cloudBackup,
104262
+ ...scannedAddresses === void 0 ? {} : { scannedAddresses }
104263
+ })
103747
104264
  );
103748
104265
  }
103749
104266
  }
103750
- async function restoreVaultFromPhrase(phrase, config2, io, dependencies) {
104267
+ async function restoreVaultFromPhrase(phrase, config2, io, dependencies, accountCount) {
103751
104268
  const paths = getVapiPaths();
103752
104269
  const validatedPhrase = validateRecoveryPhrase(phrase);
103753
104270
  const readBalance3 = baseUsdcBalanceReader(config2, dependencies);
103754
104271
  const key2 = await loadOrCreateDeviceKey({ secrets: getSecretStore(dependencies) });
103755
104272
  let names;
104273
+ let scannedAddresses = 0;
103756
104274
  try {
103757
104275
  const restored = await restoreVault({
103758
104276
  path: join26(paths.directory, "vault.json"),
103759
104277
  key: key2,
103760
104278
  phrase: validatedPhrase,
103761
104279
  probe: async (address4) => await readBalance3(address4) > 0n,
104280
+ ...accountCount === void 0 ? {} : { accountCount },
104281
+ onScanComplete: (count) => {
104282
+ scannedAddresses = count;
104283
+ },
103762
104284
  ...dependencies.now === void 0 ? {} : { now: dependencies.now }
103763
104285
  });
103764
104286
  names = restored.accounts().map((account) => account.name);
@@ -103770,8 +104292,25 @@ async function restoreVaultFromPhrase(phrase, config2, io, dependencies) {
103770
104292
  ...names[0] === void 0 ? {} : { wallet: names[0] },
103771
104293
  detail: `${names.length} account(s)`
103772
104294
  });
103773
- io.stdout(`Vault restored with ${names.length} account(s): ${names.join(", ")}`);
103774
- return { names };
104295
+ io.stdout(
104296
+ `Vault restored with ${names.length} account(s): ${names.join(", ")}. ${scannedAddresses} address(es) scanned.`
104297
+ );
104298
+ return { names, scannedAddresses };
104299
+ }
104300
+ function parseAccountCount(value) {
104301
+ if (value === void 0) return void 0;
104302
+ if (!/^\d+$/u.test(value)) {
104303
+ throw new UsageError(
104304
+ `--accounts must be a positive integer no greater than ${MAX_RESTORE_ACCOUNTS}.`
104305
+ );
104306
+ }
104307
+ const count = Number(value);
104308
+ if (!Number.isSafeInteger(count) || count < 1 || count > MAX_RESTORE_ACCOUNTS) {
104309
+ throw new UsageError(
104310
+ `--accounts must be a positive integer no greater than ${MAX_RESTORE_ACCOUNTS}.`
104311
+ );
104312
+ }
104313
+ return count;
103775
104314
  }
103776
104315
  async function vaultChoice(dependencies) {
103777
104316
  const answer = dependencies.prompts?.line === void 0 ? isInteractive(dependencies) ? await promptForLine(VAULT_CHOICE) : "" : await dependencies.prompts.line(VAULT_CHOICE);
@@ -103871,10 +104410,10 @@ var TASK_HELP = `Usage:
103871
104410
  vapi task propose <id> --price <usd> --duration <duration> --note <text> [--account <name>] [--json]
103872
104411
  vapi task submit <id> --proof <https-url> [--proof <https-url>...] [--file <path>...] [--account <name>] [--json]
103873
104412
  vapi task award <id> <proposalId> [--account <name>] [--json]
103874
- vapi task sign <id> [--yes] [--counterparty <0x\u2026>] [--account <name>] [--json]
103875
- vapi task fund <id> [--yes] [--counterparty <0x\u2026>] [--account <name>] [--json]
103876
- vapi task deliver <id> --files <path...> --note <text> [--counterparty <0x\u2026>] [--account <name>] [--json]
103877
- vapi task release <id> [--counterparty <0x\u2026>] [--account <name>] [--json]
104413
+ vapi task sign <id> [--yes] [--no-wait] [--timeout 120s] [--counterparty <0x\u2026>] [--account <name>] [--json]
104414
+ vapi task fund <id> [--yes] [--no-wait] [--timeout 120s] [--counterparty <0x\u2026>] [--account <name>] [--json]
104415
+ vapi task deliver <id> --files <path...> --note <text> [--no-wait] [--timeout 120s] [--counterparty <0x\u2026>] [--account <name>] [--json]
104416
+ vapi task release <id> [--no-wait] [--timeout 120s] [--counterparty <0x\u2026>] [--account <name>] [--json]
103878
104417
  vapi task refund <id> [--counterparty <0x\u2026>] [--account <name>] [--json]
103879
104418
  vapi task dispute <id> --evidence-hash <0x + 64 hex> [--yes] [--counterparty <0x\u2026>] [--account <name>] [--json]
103880
104419
  vapi task counter-evidence <id> --evidence-hash <0x + 64 hex> [--yes] [--counterparty <0x\u2026>] [--account <name>] [--json]
@@ -103897,23 +104436,25 @@ Exit codes:
103897
104436
  2 policy refusal only (JSON ok:false with reason policy.perTask or policy.perDay)
103898
104437
  3 approval needed in non-interactive mode
103899
104438
 
103900
- Fund, deliver, release, refund, dispute, counter-evidence, resolve-unmatched and watch auto-release sign with the local vault wallet. The CLI waits for two confirmations and records pending transactions for recovery. It never retries a chain mutation automatically.`;
104439
+ Fund, deliver, release, refund, dispute, counter-evidence, resolve-unmatched and watch auto-release sign with the local vault wallet. The CLI waits for two confirmations and records pending transactions for recovery. It never retries a chain mutation automatically. Sign, fund, deliver and release wait up to 120s for vAPI to index a confirmed transaction unless --no-wait is set; an indexing timeout keeps exit code 0.`;
103901
104440
  var IMPLEMENTED_VERBS = TASKS_CLIENT_VERBS;
103902
104441
  var USAGE = `Usage: vapi task <${IMPLEMENTED_VERBS.join("|")}>. Run vapi task --help.`;
103903
104442
  var TaskCommandError = class extends Error {
103904
- constructor(code, message, manifestHash) {
104443
+ constructor(code, message, manifestHash, prefixCode = false) {
103905
104444
  super(message);
103906
104445
  this.code = code;
103907
104446
  this.manifestHash = manifestHash;
104447
+ this.prefixCode = prefixCode;
103908
104448
  this.name = "TaskCommandError";
103909
104449
  }
103910
104450
  code;
103911
104451
  manifestHash;
104452
+ prefixCode;
103912
104453
  };
103913
104454
  function mapTaskError(error61) {
103914
104455
  if (error61 instanceof TaskInputError) return new UsageError(error61.message);
103915
104456
  if (error61 instanceof TaskOperationError)
103916
- return new TaskCommandError(error61.code, error61.message, error61.manifestHash);
104457
+ return new TaskCommandError(error61.code, error61.message, error61.manifestHash, true);
103917
104458
  return error61;
103918
104459
  }
103919
104460
  async function mapped(operation) {
@@ -104132,11 +104673,13 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104132
104673
  "--intake",
104133
104674
  "--max-awards",
104134
104675
  "--webhook"
104135
- ] : verb === "propose" ? ["--price", "--duration", "--note"] : verb === "submit" ? ["--proof", "--file"] : verb === "thread" ? ["--after"] : verb === "deliver" ? ["--files", "--note"] : ["dispute", "counter-evidence"].includes(verb) ? ["--evidence-hash"] : verb === "watch" ? ["--until", "--timeout", "--interval"] : []
104676
+ ] : verb === "propose" ? ["--price", "--duration", "--note"] : verb === "submit" ? ["--proof", "--file"] : verb === "thread" ? ["--after"] : verb === "deliver" ? ["--files", "--note"] : ["dispute", "counter-evidence"].includes(verb) ? ["--evidence-hash"] : verb === "watch" ? ["--until", "--timeout", "--interval"] : [],
104677
+ ...["sign", "fund", "deliver", "release"].includes(verb) ? ["--timeout"] : []
104136
104678
  ]),
104137
104679
  booleanOptions: /* @__PURE__ */ new Set([
104138
104680
  ...verb === "search" ? ["--open"] : [],
104139
104681
  ...["sign", "fund", "dispute", "counter-evidence"].includes(verb) ? ["--yes"] : [],
104682
+ ...["sign", "fund", "deliver", "release"].includes(verb) ? ["--no-wait"] : [],
104140
104683
  ...verb === "watch" ? ["--auto-release"] : []
104141
104684
  ]),
104142
104685
  repeatableOptions: /* @__PURE__ */ new Set([
@@ -104292,7 +104835,7 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104292
104835
  throw new UsageError("message needs text between 1 and 10000 characters.");
104293
104836
  }
104294
104837
  if (verb === "thread") cursor2 = optionalInteger(parsed.one("--after"), "--after");
104295
- const context = await taskContext(parsed, io, dependencies, verb === "status");
104838
+ const context = await taskContext(parsed, io, dependencies);
104296
104839
  if (verb === "show" || verb === "status") {
104297
104840
  if (verb === "show" && context.token) {
104298
104841
  const result = await showTask(context, { id: id2, signedIn: true });
@@ -104302,7 +104845,21 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104302
104845
  ...receipts.map((receipt) => `Receipt (from escrow): ${receipt.receiptUrl}`)
104303
104846
  ]);
104304
104847
  } else {
104305
- const result = verb === "status" ? await taskStatus(context, { id: id2 }) : await showTask(context, { id: id2, signedIn: false });
104848
+ const result = verb === "status" ? await taskStatus(context, { id: id2, signedIn: Boolean(context.token) }) : await showTask(context, { id: id2, signedIn: false });
104849
+ if ("chainState" in result) {
104850
+ const milestoneLines = result.chainState.milestones.map((milestone) => {
104851
+ const ordinal = "ordinal" in milestone && typeof milestone.ordinal === "number" && Number.isFinite(milestone.ordinal) ? milestone.ordinal : milestone.milestoneId;
104852
+ const state = "state" in milestone.read ? ` ${milestone.read.state}` : "";
104853
+ const explorer = milestone.explorerUrl ? ` ${milestone.explorerUrl}` : "";
104854
+ return `milestone ${ordinal}: ${milestone.read.status}${state}${explorer}`;
104855
+ });
104856
+ const eventLines = (result.events ?? []).slice(-10).map((event) => {
104857
+ const createdAt = "createdAt" in event && typeof event.createdAt === "string" ? event.createdAt : event.at;
104858
+ return `${event.sequence} ${event.type} ${createdAt}`;
104859
+ });
104860
+ taskOutput(io, json2, context, verb, result, [...milestoneLines, ...eventLines]);
104861
+ return;
104862
+ }
104306
104863
  const task = result.task;
104307
104864
  taskOutput(
104308
104865
  io,
@@ -104346,6 +104903,11 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104346
104903
  async function escrowTaskCommand(verb, id2, parsed, json2, io, dependencies, now) {
104347
104904
  taskCounterparty(parsed);
104348
104905
  if (verb === "watch") return await watchTask(id2, parsed, json2, io, dependencies, now);
104906
+ const waitsForIndex = ["sign", "fund", "deliver", "release"].includes(verb);
104907
+ const waitTimeoutText = parsed.one("--timeout") ?? "120s";
104908
+ const waitTimeoutMs = waitsForIndex ? parseTaskDuration2(waitTimeoutText, now) : void 0;
104909
+ if (waitTimeoutMs !== void 0 && waitTimeoutMs <= 0)
104910
+ throw new UsageError("--timeout must be positive.");
104349
104911
  const disputeEvidenceHash = ["dispute", "counter-evidence"].includes(verb) ? required3(parsed, "--evidence-hash") : void 0;
104350
104912
  const counterparty = taskCounterparty(parsed);
104351
104913
  if (disputeEvidenceHash !== void 0 && !TASK_LIMITS.disputeEvidenceHash.test(disputeEvidenceHash))
@@ -104395,9 +104957,24 @@ async function escrowTaskCommand(verb, id2, parsed, json2, io, dependencies, now
104395
104957
  return await account.signMessage({ message });
104396
104958
  }
104397
104959
  });
104398
- taskOutput(io, json2, displayContext, verb, result2, [
104960
+ if (!json2 && result2.escrowCreation?.resumedFromServer)
104961
+ io.stdout("The server had already prepared escrow creation; resumed from it.");
104962
+ const wait3 = result2.escrowCreation ? await waitForTaskIndex(
104963
+ context,
104964
+ dependencies,
104965
+ parsed,
104966
+ json2,
104967
+ io,
104968
+ id2,
104969
+ result2.escrowCreation,
104970
+ "created",
104971
+ "escrow creation",
104972
+ waitTimeoutText,
104973
+ waitTimeoutMs
104974
+ ) : null;
104975
+ taskOutput(io, json2, displayContext, verb, { ...result2, wait: wait3 }, [
104399
104976
  `Accepted scope for task ${id2}.`,
104400
- ...result2.escrowCreation ? ["Created the task escrow."] : []
104977
+ ...result2.escrowCreation && (wait3 === null || wait3.reached) ? ["escrow created"] : []
104401
104978
  ]);
104402
104979
  return;
104403
104980
  } catch (error61) {
@@ -104431,7 +105008,23 @@ async function escrowTaskCommand(verb, id2, parsed, json2, io, dependencies, now
104431
105008
  taskOutput(io, false, context, verb, {}, [`Prepared delivery manifest ${manifestHash}.`]);
104432
105009
  }
104433
105010
  });
104434
- taskOutput(io, json2, context, verb, outcome, [`Delivered task ${id2}.`]);
105011
+ const wait3 = await waitForTaskIndex(
105012
+ context,
105013
+ dependencies,
105014
+ parsed,
105015
+ json2,
105016
+ io,
105017
+ id2,
105018
+ outcome.result,
105019
+ "delivered",
105020
+ "delivery",
105021
+ waitTimeoutText,
105022
+ waitTimeoutMs
105023
+ );
105024
+ taskOutput(io, json2, context, verb, { ...outcome, wait: wait3 }, [
105025
+ ...wait3 === null || wait3.reached ? ["delivery recorded"] : [],
105026
+ ...outcome.result.resumedFromServer === true ? ["The server had already recorded this delivery; resumed from it."] : []
105027
+ ]);
104435
105028
  return;
104436
105029
  }
104437
105030
  const snapshot = await taskMoneySnapshot(context.client, id2, void 0, {
@@ -104494,15 +105087,82 @@ async function escrowTaskCommand(verb, id2, parsed, json2, io, dependencies, now
104494
105087
  }
104495
105088
  if (!outcome.ok && "declined" in outcome)
104496
105089
  throw new TaskCommandError("not_approved", "Not approved; nothing was signed.");
104497
- taskOutput(io, json2, context, verb, outcome, [
104498
- verb === "fund" ? `Funded task ${id2}.` : `Completed task ${verb} for ${id2}.`
104499
- ]);
105090
+ if (!json2 && outcome.result.resumedFromServer)
105091
+ io.stdout("The server had already prepared this task operation; resumed from it.");
105092
+ const wait3 = verb === "fund" ? await waitForTaskIndex(
105093
+ context,
105094
+ dependencies,
105095
+ parsed,
105096
+ json2,
105097
+ io,
105098
+ id2,
105099
+ outcome.result,
105100
+ "locked",
105101
+ "funding",
105102
+ waitTimeoutText,
105103
+ waitTimeoutMs
105104
+ ) : void 0;
105105
+ taskOutput(
105106
+ io,
105107
+ json2,
105108
+ context,
105109
+ verb,
105110
+ wait3 === void 0 ? outcome : { ...outcome, wait: wait3 },
105111
+ verb === "fund" ? wait3 === null || wait3?.reached ? ["escrow funded"] : [] : [`Completed task ${verb} for ${id2}.`]
105112
+ );
104500
105113
  return;
104501
105114
  }
104502
105115
  if (!json2) io.stdout("Policy: explicit user instruction.");
104503
105116
  const settlementInput = { id: id2, snapshot, ...counterparty === void 0 ? {} : { counterparty } };
104504
105117
  const result = verb === "release" ? await releaseTaskOperation(context, settlementInput) : verb === "refund" ? await refundTaskOperation(context, settlementInput) : await resolveUnmatchedTaskOperation(context, settlementInput);
104505
- taskOutput(io, json2, context, verb, result, [`Completed task ${verb} for ${id2}.`]);
105118
+ if (!json2 && result.result.resumedFromServer)
105119
+ io.stdout("The server had already prepared this task operation; resumed from it.");
105120
+ const wait2 = verb === "release" ? await waitForTaskIndex(
105121
+ context,
105122
+ dependencies,
105123
+ parsed,
105124
+ json2,
105125
+ io,
105126
+ id2,
105127
+ result.result,
105128
+ "released",
105129
+ "release",
105130
+ waitTimeoutText,
105131
+ waitTimeoutMs
105132
+ ) : void 0;
105133
+ taskOutput(
105134
+ io,
105135
+ json2,
105136
+ context,
105137
+ verb,
105138
+ wait2 === void 0 ? result : { ...result, wait: wait2 },
105139
+ verb === "release" ? wait2 === null || wait2?.reached ? ["funds released"] : [] : [`Completed task ${verb} for ${id2}.`]
105140
+ );
105141
+ }
105142
+ async function waitForTaskIndex(context, dependencies, parsed, json2, io, orderId, result, target, description, timeoutText, timeoutMs) {
105143
+ if (parsed.has("--no-wait")) return null;
105144
+ if (!json2)
105145
+ io.stdout(
105146
+ `confirmed on chain${result.blockNumber === void 0 ? "" : ` in block ${result.blockNumber}`}, waiting for vAPI to index\u2026`
105147
+ );
105148
+ const wait2 = await taskRequest2(
105149
+ description,
105150
+ "getOrder",
105151
+ () => waitForMilestone(context.client, {
105152
+ orderId,
105153
+ milestoneId: result.milestone.id,
105154
+ target,
105155
+ timeoutMs,
105156
+ intervalMs: 3e3,
105157
+ sleep: context.sleep,
105158
+ now: dependencies.now ?? (() => /* @__PURE__ */ new Date())
105159
+ })
105160
+ );
105161
+ if (!wait2.reached)
105162
+ io.stderr(
105163
+ `vAPI has not indexed the ${description} yet after ${timeoutText}; run vapi task status ${orderId} later.`
105164
+ );
105165
+ return wait2;
104506
105166
  }
104507
105167
  var ScopeApprovalNeeded = class extends Error {
104508
105168
  constructor(terms) {
@@ -105758,6 +106418,7 @@ async function referencedSleep(milliseconds, signal) {
105758
106418
  // ../cli/src/vault.ts
105759
106419
  import { join as join27 } from "node:path";
105760
106420
  var VAULT_USAGE = "Usage: vapi vault protect|unprotect|lock|unlock|status [--json]";
106421
+ var RESTORE_USAGE = "Usage: vapi restore [--accounts <n> | --from-owner [--owner <0x\u2026>]] [--json]";
105761
106422
  var LEGACY_PASSWORD_NOTICE = "VAPI_KEYSTORE_PASSWORD is deprecated for vault passwords; use VAPI_VAULT_PASSWORD instead.";
105762
106423
  async function vaultCommand(argv, json2, io, dependencies) {
105763
106424
  const subcommand = argv[0];
@@ -105787,9 +106448,17 @@ async function restoreCommand(argv, json2, io, dependencies) {
105787
106448
  await restoreFromOwnerCommand(argv, json2, io, dependencies);
105788
106449
  return;
105789
106450
  }
105790
- if (argv.length > 0) {
105791
- throw new UsageError("Usage: vapi restore [--from-owner [--owner <0x\u2026>]] [--json]");
106451
+ let parsed;
106452
+ try {
106453
+ parsed = parseArguments(argv, {
106454
+ valueOptions: /* @__PURE__ */ new Set(["--accounts"]),
106455
+ maximumPositionals: 0
106456
+ });
106457
+ } catch (error61) {
106458
+ if (error61 instanceof UsageError) throw new UsageError(RESTORE_USAGE);
106459
+ throw error61;
105792
106460
  }
106461
+ const accountCount = parseRestoreAccountCount(parsed.one("--accounts"));
105793
106462
  const paths = getVapiPaths();
105794
106463
  const path = join27(paths.directory, "vault.json");
105795
106464
  if (await fileExists2(path)) {
@@ -105803,13 +106472,39 @@ async function restoreCommand(argv, json2, io, dependencies) {
105803
106472
  const config2 = await readConfig(paths.config, json2 ? quietIo(io) : io);
105804
106473
  const phrase = isStdinInteractive(dependencies) ? await getPrompts(dependencies).secret("Recovery phrase: ") : await (dependencies.readStdin ?? readProcessStdin3)();
105805
106474
  const restoreIo = json2 ? quietIo(io) : io;
105806
- const { names } = await restoreVaultFromPhrase(phrase.trim(), config2, restoreIo, dependencies);
106475
+ const { names, scannedAddresses } = await restoreVaultFromPhrase(
106476
+ phrase.trim(),
106477
+ config2,
106478
+ restoreIo,
106479
+ dependencies,
106480
+ accountCount
106481
+ );
105807
106482
  if (json2) {
105808
- output3(io, true, { command: "restore", vault: "restored", accounts: names }, "");
106483
+ output3(
106484
+ io,
106485
+ true,
106486
+ { command: "restore", vault: "restored", accounts: names, scannedAddresses },
106487
+ ""
106488
+ );
105809
106489
  return;
105810
106490
  }
105811
106491
  io.stdout(`Run vapi setup to link ${names[0]}.`);
105812
106492
  }
106493
+ function parseRestoreAccountCount(value) {
106494
+ if (value === void 0) return void 0;
106495
+ if (!/^\d+$/u.test(value)) {
106496
+ throw new UsageError(
106497
+ `--accounts must be a positive integer no greater than ${MAX_RESTORE_ACCOUNTS}.`
106498
+ );
106499
+ }
106500
+ const count = Number(value);
106501
+ if (!Number.isSafeInteger(count) || count < 1 || count > MAX_RESTORE_ACCOUNTS) {
106502
+ throw new UsageError(
106503
+ `--accounts must be a positive integer no greater than ${MAX_RESTORE_ACCOUNTS}.`
106504
+ );
106505
+ }
106506
+ return count;
106507
+ }
105813
106508
  async function protectCommand(argv, json2, io, dependencies) {
105814
106509
  requireNoArguments(argv);
105815
106510
  const env = getEnvironment(dependencies);
@@ -105939,8 +106634,8 @@ var HELP_HEADING = "vAPI Network";
105939
106634
  var HELP = `${HELP_HEADING}
105940
106635
 
105941
106636
  Usage:
105942
- vapi init [--networks <base,arc,solana>] [--json]
105943
- vapi setup [--no-cloud-backup] [--json]
106637
+ vapi init [--networks <base,arc>] [--json]
106638
+ vapi setup [--no-cloud-backup] [--accounts <n>] [--json]
105944
106639
  vapi accounts [--all] [--json]
105945
106640
  vapi accounts add <name> [--label <text>] [--no-link] [--json]
105946
106641
  vapi accounts import <name> [--keystore <path> | --key-file <path>] [--label <text>] [--json]
@@ -105970,7 +106665,7 @@ Usage:
105970
106665
  vapi docs read <url-or-path> [--json]
105971
106666
  vapi search [query] [--kind <kind>] [--network <caip2>] [--limit <n>] [--cursor <cursor>] [--include-unverified] [--json]
105972
106667
  vapi inspect <id> [--endpoint <name>] [--json]
105973
- vapi pay <id-or-url> [--method <method>] [--endpoint <name>] [--body <json>] [--content-type <type>] [--network <caip2>] [--expected-pay-to <address>] [--max <amount>] [--account <name>] [--json]
106668
+ 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]
105974
106669
  vapi pay --resume <receipt-id> [--json]
105975
106670
  vapi check <url> [--method <method>] [--json]
105976
106671
  vapi balance [--account <name>] [--json]
@@ -106016,8 +106711,8 @@ Usage:
106016
106711
  vapi task status <id> [--account <name>] [--json]
106017
106712
  vapi export-key [--network <caip2>] [--account <name>] [--json]
106018
106713
  vapi backup [--account <name>] [--cloud [off]] [--json]
106019
- vapi restore [--from-owner [--owner <0x\u2026>]] [--json]
106020
- vapi import (--phrase | --key) [--account <name>] [--networks <base,arc,solana>] [--replace] [--force] [--json]
106714
+ vapi restore [--accounts <n> | --from-owner [--owner <0x\u2026>]] [--json]
106715
+ vapi import (--phrase | --key) [--account <name>] [--networks <base,arc>] [--replace] [--force] [--json]
106021
106716
  vapi passphrase [--account <name>] [--json]
106022
106717
  vapi vault protect [--json]
106023
106718
  vapi vault unprotect [--json]
@@ -106045,6 +106740,8 @@ Every command that touches a wallet takes \`--account <name>\`, falls back to \`
106045
106740
 
106046
106741
  \`vapi search\` answers with vAPI-verified listings plus the mirrored external catalogs. \`--include-unverified\` also returns self-listed APIs that passed vAPI's automated x402 probe but were never reviewed; every result is tagged \`[verified]\`, \`[requested]\`, \`[unverified]\` or \`[external]\`.
106047
106742
 
106743
+ Solana listings remain searchable; inspect and pay return \`unsupported_network\`. Solana keys are not part of the device vault yet.
106744
+
106048
106745
  \`vapi docs\` asks the public vAPI documentation assistant; \`vapi docs search\` searches documentation excerpts and \`vapi docs read\` reads one Markdown page. They need no account, wallet or payment.
106049
106746
 
106050
106747
  \`vapi task --help\` lists task options and availability. Task exit codes: 0 ok, 1 error, 2 policy refusal (JSON ok:false with a policy. reason) or invalid usage (JSON error), 3 approval needed in non-interactive mode. Posting moves no money; the current create-order contract does not store amount, deadline, intake, max awards or webhook yet.
@@ -106057,7 +106754,7 @@ Every command that touches a wallet takes \`--account <name>\`, falls back to \`
106057
106754
 
106058
106755
  \`vapi vault protect\` adds a password to the device vault. \`vapi vault unlock\` opens it on this device for 8 hours; for unattended use, set \`VAPI_VAULT_PASSWORD\`. \`vapi unlock\` and \`vapi lock\` remain aliases for one release.
106059
106756
 
106060
- \`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 an unused address. Set \`VAPI_NO_SECRETS=1\` to switch exports off entirely. Every export and every wallet change is logged to ~/.vapi/audit.log.
106757
+ \`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.
106061
106758
 
106062
106759
  \`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.
106063
106760
 
@@ -106434,6 +107131,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106434
107131
  error: message,
106435
107132
  exitCode: code,
106436
107133
  ...error61 instanceof RuntimeError ? { code: error61.code } : {},
107134
+ ...error61 instanceof VapiCallError ? { code: error61.code } : {},
106437
107135
  ...error61 instanceof DocsError ? { code: error61.code } : {},
106438
107136
  ...error61 instanceof RemoteKeyRefusedError ? { code: error61.code } : {},
106439
107137
  ...error61 instanceof TransferError ? { code: error61.code, moneyMoved: error61.moneyMoved } : {}
@@ -106441,7 +107139,10 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106441
107139
  );
106442
107140
  }
106443
107141
  } else {
106444
- runIo.stderr(message);
107142
+ const errorCode2 = taskInvocation && error61 instanceof TaskCommandError && error61.prefixCode ? errorCodeOf(error61) : void 0;
107143
+ runIo.stderr(
107144
+ errorCode2 !== void 0 && !message.startsWith(`${errorCode2}: `) ? `${errorCode2}: ${message}` : message
107145
+ );
106445
107146
  }
106446
107147
  if (shouldAutoUploadAfterFailure(argv.filter((argument) => argument !== "--json"))) {
106447
107148
  await autoUploadBackup(io, json2, dependencies);
@@ -106842,7 +107543,7 @@ async function inspectCommand(argv, json2, io, dependencies) {
106842
107543
  );
106843
107544
  output3(io, json2, result, formatInspect(result));
106844
107545
  }
106845
- var PAY_USAGE = "Usage: vapi pay <id-or-url> [--method <method>] [--endpoint <name>] [--body <json>] [--content-type <type>] [--network <caip2>] [--expected-pay-to <address>] [--max <amount>] [--account <name>] [--json]";
107546
+ var PAY_USAGE = "Usage: 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]";
106846
107547
  async function payCommand(argv, json2, io, dependencies) {
106847
107548
  if (argv.includes(RESUME_OPTION)) {
106848
107549
  await payResumeCommand(argv, json2, io, dependencies);
@@ -106858,11 +107559,13 @@ async function payCommand(argv, json2, io, dependencies) {
106858
107559
  "--expected-pay-to",
106859
107560
  "--max",
106860
107561
  "--max-price-usd",
107562
+ "--timeout",
106861
107563
  WALLET_OPTION5
106862
107564
  ]),
106863
107565
  maximumPositionals: 1
106864
107566
  });
106865
107567
  const target = requiredPositional(parsed.positionals[0], "<id-or-url>", PAY_USAGE);
107568
+ const timeoutSeconds = optionalBoundedInteger(parsed.one("--timeout"), "--timeout", 1, 300);
106866
107569
  const paths = getVapiPaths();
106867
107570
  const config2 = await readConfig(paths.config, io);
106868
107571
  const wallet = await targetWallet(parsed, dependencies);
@@ -106878,7 +107581,8 @@ async function payCommand(argv, json2, io, dependencies) {
106878
107581
  ...parsed.one("--content-type") ? { contentType: parsed.one("--content-type") } : {},
106879
107582
  ...parsed.one("--network") ? { network: parsed.one("--network") } : {},
106880
107583
  ...parsed.one("--expected-pay-to") ? { expectedPayTo: parsed.one("--expected-pay-to") } : {},
106881
- ...maxPriceUsd ? { maxPriceUsd } : {}
107584
+ ...maxPriceUsd ? { maxPriceUsd } : {},
107585
+ ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
106882
107586
  };
106883
107587
  const call2 = createCallPort({
106884
107588
  config: config2,
@@ -108553,7 +109257,7 @@ function buildNextSteps(address4) {
108553
109257
  formatNextStep("Pay", "vapi pay <ref> --max 0.02"),
108554
109258
  formatNextStep(
108555
109259
  "Agent",
108556
- 'add {"command":"npx","args":["-y","vapi-network","mcp"]} to your MCP config'
109260
+ 'add {"command":"npx","args":["-y","vapi-network@latest","mcp"]} to your MCP config'
108557
109261
  )
108558
109262
  ];
108559
109263
  }
@@ -108734,6 +109438,17 @@ function optionalPositiveInteger(value, option) {
108734
109438
  if (result === 0) throw new UsageError(`${option} must be a positive integer.`);
108735
109439
  return result;
108736
109440
  }
109441
+ function optionalBoundedInteger(value, option, minimum, maximum) {
109442
+ if (value === void 0) return void 0;
109443
+ if (!/^\d+$/.test(value)) {
109444
+ throw new UsageError(`${option} must be an integer from ${minimum} to ${maximum}.`);
109445
+ }
109446
+ const parsed = Number(value);
109447
+ if (!Number.isSafeInteger(parsed) || parsed < minimum || parsed > maximum) {
109448
+ throw new UsageError(`${option} must be an integer from ${minimum} to ${maximum}.`);
109449
+ }
109450
+ return parsed;
109451
+ }
108737
109452
  function optionalUsdAmount(value, option) {
108738
109453
  if (value === void 0) return void 0;
108739
109454
  if (!/^\d+(?:\.\d{1,2})?$/.test(value)) {
@@ -108794,12 +109509,138 @@ function parseInitNetworks(value) {
108794
109509
  }
108795
109510
  for (const network of networks) {
108796
109511
  if (network !== "base" && network !== "arc" && network !== "solana") {
108797
- throw new UsageError("--networks supports base, arc and solana.");
109512
+ throw new UsageError("--networks supports base and arc; Solana vault setup is unavailable.");
108798
109513
  }
108799
109514
  }
108800
109515
  return networks;
108801
109516
  }
108802
109517
 
109518
+ // ../cli/src/update-check.ts
109519
+ import { lookup } from "node:dns/promises";
109520
+ import { mkdir as mkdir21, readFile as readFile30, writeFile as writeFile12 } from "node:fs/promises";
109521
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
109522
+ var CHECK_TIMEOUT_MS = 1500;
109523
+ var LATEST_URL = "https://registry.npmjs.org/vapi-network/latest";
109524
+ async function runCliWithUpdateCheck(argv = process.argv.slice(2), io = {
109525
+ stdout: (message) => console.log(message),
109526
+ stderr: (message) => console.error(message)
109527
+ }, dependencies = {}, options = {}) {
109528
+ const notice = checkForUpdate({ ...options, env: options.env ?? dependencies.env, argv });
109529
+ const code = await runCli(argv, io, dependencies);
109530
+ const message = await notice;
109531
+ if (message) io.stderr(message);
109532
+ return code;
109533
+ }
109534
+ async function checkForUpdate(options = {}) {
109535
+ const env = options.env ?? process.env;
109536
+ const argv = options.argv ?? process.argv.slice(2);
109537
+ 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) {
109538
+ return void 0;
109539
+ }
109540
+ const controller = new AbortController();
109541
+ let timer;
109542
+ try {
109543
+ return await Promise.race([
109544
+ latestNotice(options, env, controller.signal),
109545
+ new Promise((resolve3) => {
109546
+ timer = setTimeout(() => {
109547
+ controller.abort();
109548
+ resolve3(void 0);
109549
+ }, CHECK_TIMEOUT_MS);
109550
+ })
109551
+ ]);
109552
+ } catch {
109553
+ return void 0;
109554
+ } finally {
109555
+ if (timer !== void 0) clearTimeout(timer);
109556
+ controller.abort();
109557
+ }
109558
+ }
109559
+ async function latestNotice(options, env, signal) {
109560
+ const paths = getVapiPaths(options.home ?? (env.VAPI_HOME?.trim() || void 0));
109561
+ const now = (options.nowMs ?? Date.now)();
109562
+ let cached2;
109563
+ try {
109564
+ const value = JSON.parse(await readFile30(paths.updateCheck, "utf8"));
109565
+ if (isRecord12(value) && typeof value.checkedAt === "number" && Number.isFinite(value.checkedAt) && typeof value.latest === "string" && parseVersion(value.latest)) {
109566
+ cached2 = { checkedAt: value.checkedAt, latest: value.latest };
109567
+ }
109568
+ } catch {
109569
+ }
109570
+ signal.throwIfAborted();
109571
+ let latest = cached2?.latest ?? CLI_VERSION;
109572
+ if (cached2 === void 0 || now - cached2.checkedAt >= CHECK_INTERVAL_MS || now < cached2.checkedAt) {
109573
+ await mkdir21(paths.directory, { recursive: true });
109574
+ signal.throwIfAborted();
109575
+ await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
109576
+ signal.throwIfAborted();
109577
+ const fetchImpl = options.fetchImpl ?? createPublicFetch({
109578
+ allowPrivateNetwork: false,
109579
+ lookup: async (hostname4) => {
109580
+ let onAbort;
109581
+ const aborted2 = new Promise((_resolve, reject) => {
109582
+ onAbort = () => reject(signal.reason);
109583
+ signal.addEventListener("abort", onAbort, { once: true });
109584
+ });
109585
+ try {
109586
+ signal.throwIfAborted();
109587
+ const addresses = await Promise.race([lookup(hostname4, { all: true }), aborted2]);
109588
+ return addresses.map(({ address: address4 }) => address4);
109589
+ } finally {
109590
+ signal.removeEventListener("abort", onAbort);
109591
+ }
109592
+ }
109593
+ });
109594
+ const response = await fetchImpl(LATEST_URL, { signal, redirect: "error" });
109595
+ if (!response.ok) return void 0;
109596
+ const body = await response.json();
109597
+ signal.throwIfAborted();
109598
+ if (!isRecord12(body) || typeof body.version !== "string" || !parseVersion(body.version)) {
109599
+ return void 0;
109600
+ }
109601
+ latest = body.version;
109602
+ await writeFile12(paths.updateCheck, JSON.stringify({ checkedAt: now, latest }), { mode: 384 });
109603
+ }
109604
+ signal.throwIfAborted();
109605
+ return isNewerVersion(latest, CLI_VERSION) ? `vapi-network ${latest} is available (you have ${CLI_VERSION}). Update: npm i -g vapi-network@latest` : void 0;
109606
+ }
109607
+ function isRecord12(value) {
109608
+ return typeof value === "object" && value !== null && !Array.isArray(value);
109609
+ }
109610
+ function parseVersion(version5) {
109611
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z.-]+))?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/.exec(
109612
+ version5
109613
+ );
109614
+ if (!match) return void 0;
109615
+ const prerelease = match[4]?.split(".");
109616
+ if (prerelease?.some((part) => part === "" || /^\d+$/.test(part) && /^0\d/.test(part))) {
109617
+ return void 0;
109618
+ }
109619
+ return { core: match.slice(1, 4).map(BigInt), prerelease };
109620
+ }
109621
+ function isNewerVersion(latest, current) {
109622
+ const next = parseVersion(latest);
109623
+ const running = parseVersion(current);
109624
+ for (let index2 = 0; index2 < 3; index2 += 1) {
109625
+ if (next.core[index2] !== running.core[index2]) return next.core[index2] > running.core[index2];
109626
+ }
109627
+ if (running.prerelease === void 0) return false;
109628
+ if (next.prerelease === void 0) return true;
109629
+ for (let index2 = 0; index2 < Math.max(next.prerelease.length, running.prerelease.length); index2 += 1) {
109630
+ const a = next.prerelease[index2];
109631
+ const b = running.prerelease[index2];
109632
+ if (a === b) continue;
109633
+ if (a === void 0) return false;
109634
+ if (b === void 0) return true;
109635
+ const aNumeric = /^\d+$/.test(a);
109636
+ const bNumeric = /^\d+$/.test(b);
109637
+ if (aNumeric && bNumeric) return BigInt(a) > BigInt(b);
109638
+ if (aNumeric !== bNumeric) return !aNumeric;
109639
+ return a > b;
109640
+ }
109641
+ return false;
109642
+ }
109643
+
108803
109644
  // src/client.ts
108804
109645
  import { homedir as homedir3 } from "node:os";
108805
109646
  import { join as join29 } from "node:path";
@@ -108834,10 +109675,18 @@ async function createVapiClient(options = {}) {
108834
109675
  }
108835
109676
  const address4 = storedAddress;
108836
109677
  let accountPromise;
108837
- const account = () => {
108838
- if (injected !== void 0) return Promise.resolve(injected);
108839
- accountPromise ??= unlockOnce();
108840
- return accountPromise;
109678
+ const account = async () => {
109679
+ if (injected !== void 0) return injected;
109680
+ try {
109681
+ if (accountPromise !== void 0 && !env.VAPI_VAULT_PASSWORD?.trim()) {
109682
+ await wallets.assertSigningAuthority(selected.name);
109683
+ }
109684
+ accountPromise ??= unlockOnce();
109685
+ return await accountPromise;
109686
+ } catch (error61) {
109687
+ accountPromise = void 0;
109688
+ throw error61;
109689
+ }
108841
109690
  };
108842
109691
  const unlockOnce = async () => {
108843
109692
  if (await wallets.hasVaultAccount(selected.name)) {
@@ -108984,7 +109833,10 @@ async function createVapiClient(options = {}) {
108984
109833
  account: await account(),
108985
109834
  wallet: selected.name,
108986
109835
  spendCaps,
108987
- currentSpendCaps,
109836
+ currentSpendCaps: async () => {
109837
+ await account();
109838
+ return await currentSpendCaps();
109839
+ },
108988
109840
  chat: async (request) => await routerChat(deps, request),
108989
109841
  approve: runOptions.approve ?? (async () => false),
108990
109842
  ...runOptions.onEvent === void 0 ? {} : { onEvent: runOptions.onEvent },