vapi-network 0.9.0 → 0.9.2

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
@@ -10186,7 +10186,7 @@ __export(src_exports, {
10186
10186
  MARKETPLACE_KINDS: () => MARKETPLACE_KINDS,
10187
10187
  MARKETPLACE_RANKING_VERSION: () => MARKETPLACE_RANKING_VERSION,
10188
10188
  MovementError: () => MovementError,
10189
- NETWORKS: () => NETWORKS,
10189
+ NETWORKS: () => NETWORKS2,
10190
10190
  ONRAMP_FALLBACK_INSTRUCTIONS: () => ONRAMP_FALLBACK_INSTRUCTIONS,
10191
10191
  ONRAMP_NETWORK: () => ONRAMP_NETWORK,
10192
10192
  PASSPHRASE_ENVIRONMENT_VARIABLE: () => PASSPHRASE_ENVIRONMENT_VARIABLE,
@@ -10201,6 +10201,7 @@ __export(src_exports, {
10201
10201
  SIGN_IN_WITH_X: () => SIGN_IN_WITH_X,
10202
10202
  SIWxError: () => SIWxError,
10203
10203
  SOLANA_DERIVATION_PATH: () => SOLANA_DERIVATION_PATH,
10204
+ SOLANA_DEVNET_CAIP2: () => SOLANA_DEVNET_CAIP2,
10204
10205
  SOLANA_MAINNET_CAIP2: () => SOLANA_MAINNET_CAIP2,
10205
10206
  SOLANA_MAINNET_USDC: () => SOLANA_MAINNET_USDC,
10206
10207
  STATS_RANGES: () => STATS_RANGES,
@@ -10324,6 +10325,7 @@ __export(src_exports, {
10324
10325
  getNetworkDefinition: () => getNetworkDefinition,
10325
10326
  getVapiPaths: () => getVapiPaths,
10326
10327
  isCallableListing: () => isCallableListing,
10328
+ isDiscoveryCatalogError: () => isDiscoveryCatalogError,
10327
10329
  isEvmPaymentRequirements: () => isEvmPaymentRequirements,
10328
10330
  isMirroredHit: () => isMirroredHit,
10329
10331
  isMissingFile: () => isMissingFile,
@@ -10356,6 +10358,7 @@ __export(src_exports, {
10356
10358
  lowerAccountCaps: () => lowerAccountCaps,
10357
10359
  marketplaceBadgeCodeSchema: () => marketplaceBadgeCodeSchema,
10358
10360
  marketplaceBadgeSchema: () => marketplaceBadgeSchema,
10361
+ marketplaceDiscoveryEnvelopeSchema: () => marketplaceDiscoveryEnvelopeSchema,
10359
10362
  marketplaceDiscoveryInputSchema: () => marketplaceDiscoveryInputSchema,
10360
10363
  marketplaceDiscoveryPageSchema: () => marketplaceDiscoveryPageSchema,
10361
10364
  marketplaceExecutionMethodSchema: () => marketplaceExecutionMethodSchema,
@@ -29342,378 +29345,6 @@ function date4(params) {
29342
29345
  return _coercedDate(ZodDate, params);
29343
29346
  }
29344
29347
 
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
29348
  // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/index.js
29718
29349
  init_exports();
29719
29350
 
@@ -39990,6 +39621,7 @@ var ARC_MAINNET_CAIP2 = "eip155:5042";
39990
39621
  var ARC_TESTNET_CAIP2 = "eip155:5042002";
39991
39622
  var SOLANA_MAINNET_CAIP2 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d";
39992
39623
  var X402_SOLANA_MAINNET_CAIP2 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
39624
+ var SOLANA_DEVNET_CAIP2 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
39993
39625
  var SOLANA_MAINNET_USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
39994
39626
  function canonicalIdentity(usdc, eip712Domain) {
39995
39627
  return Object.freeze({
@@ -40033,375 +39665,184 @@ var BROWSER_ENABLED_X402_NETWORK_CONFIG = Object.freeze({
40033
39665
  [ARC_TESTNET_CAIP2]: browserNetwork(arcTestnetUsdc)
40034
39666
  });
40035
39667
 
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);
39668
+ // ../core/src/marketplace-contracts.ts
39669
+ var MARKETPLACE_DISCOVERY_PROTOCOL = "vapi.marketplace.discovery/1";
39670
+ var MARKETPLACE_RANKING_VERSION = "marketplace-ranking-v1";
39671
+ var MARKETPLACE_KINDS = ["api", "service_offer", "open_request"];
39672
+ var MARKETPLACE_EXECUTION_METHODS = [
39673
+ "GET",
39674
+ "HEAD",
39675
+ "POST",
39676
+ "PUT",
39677
+ "PATCH",
39678
+ "DELETE"
39679
+ ];
39680
+ var marketplaceExecutionMethodSchema = external_exports.enum(MARKETPLACE_EXECUTION_METHODS);
39681
+ var marketplaceKindSchema = external_exports.enum(MARKETPLACE_KINDS);
39682
+ var EXECUTION_MODES = ["direct", "gateway"];
39683
+ var executionModeSchema = external_exports.enum(EXECUTION_MODES);
39684
+ var PROVENANCES = ["indexed", "self_listed", "partner"];
39685
+ var provenanceSchema = external_exports.enum(PROVENANCES);
39686
+ var FIRST_PARTY_PROVENANCES = ["self_listed", "partner"];
39687
+ var firstPartyProvenanceSchema = external_exports.enum(FIRST_PARTY_PROVENANCES);
39688
+ var LISTING_GROUPS = ["vapi", "added", "partner", "external"];
39689
+ var listingGroupSchema = external_exports.enum(LISTING_GROUPS);
39690
+ var listingFeeSchema = external_exports.looseObject({
39691
+ bps: external_exports.number().int().min(0),
39692
+ label: external_exports.string()
39693
+ });
39694
+ var LISTING_VERIFICATIONS = ["none", "requested", "verified"];
39695
+ var listingVerificationSchema = external_exports.enum(LISTING_VERIFICATIONS);
39696
+ var listingVerificationFieldSchema = listingVerificationSchema.default("none").catch("none");
39697
+ var listingLivenessSchema = external_exports.looseObject({
39698
+ uptime7d: external_exports.number().min(0).max(1),
39699
+ latencyP50Ms: external_exports.number().nonnegative().nullable(),
39700
+ latencyP95Ms: external_exports.number().nonnegative().nullable(),
39701
+ checks7d: external_exports.number().int().nonnegative()
39702
+ });
39703
+ var listingConformanceSchema = external_exports.looseObject({
39704
+ declaredVersion: external_exports.union([external_exports.literal(1), external_exports.literal(2)]).nullable(),
39705
+ versionConformant: external_exports.boolean(),
39706
+ offerTransport: external_exports.enum(["body", "header", "both"]),
39707
+ issues: external_exports.array(external_exports.string())
39708
+ });
39709
+ var listingIdentitySchema = external_exports.looseObject({
39710
+ erc8004Id: external_exports.string().trim().min(1),
39711
+ reputation: external_exports.looseObject({
39712
+ score: external_exports.number().finite(),
39713
+ count: external_exports.number().int().nonnegative()
39714
+ }).optional().catch(void 0)
39715
+ });
39716
+ var listingDisclosureShape = {
39717
+ group: listingGroupSchema.optional(),
39718
+ fee: listingFeeSchema.optional(),
39719
+ verification: listingVerificationFieldSchema,
39720
+ liveness: listingLivenessSchema.optional().catch(void 0),
39721
+ conformance: listingConformanceSchema.optional().catch(void 0),
39722
+ identity: listingIdentitySchema.optional().catch(void 0)
40045
39723
  };
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
- }
39724
+ var marketplaceBadgeCodeSchema = external_exports.enum([
39725
+ "live_x402",
39726
+ "partner",
39727
+ "payout_wallet_confirmed",
39728
+ "vapi_verified",
39729
+ "external_catalog",
39730
+ "approved_vendor"
39731
+ ]);
39732
+ var marketplaceBadgeSchema = external_exports.looseObject({
39733
+ code: marketplaceBadgeCodeSchema,
39734
+ label: external_exports.string().trim().min(1).max(80)
39735
+ });
39736
+ var marketplacePublicFactSchema = external_exports.looseObject({
39737
+ label: external_exports.string().trim().min(1).max(80),
39738
+ value: external_exports.string().trim().min(1).max(160)
39739
+ });
39740
+ var marketplaceHrefSchema = external_exports.union([
39741
+ external_exports.string().trim().min(1).max(2048).regex(/^\/(?!\/)/),
39742
+ external_exports.url().max(2048).regex(/^https:\/\//)
39743
+ ]);
39744
+ var marketplaceCardSchema = external_exports.looseObject({
39745
+ title: external_exports.string().trim().min(1).max(160),
39746
+ summary: external_exports.string().trim().min(1).max(1e3),
39747
+ byline: external_exports.string().trim().min(1).max(160).optional(),
39748
+ bylineHref: marketplaceHrefSchema.optional(),
39749
+ badges: external_exports.array(marketplaceBadgeSchema).max(8),
39750
+ facts: external_exports.array(marketplacePublicFactSchema).max(12)
39751
+ });
39752
+ var marketplaceHitBase = {
39753
+ ref: external_exports.string().trim().min(1).max(512),
39754
+ card: marketplaceCardSchema,
39755
+ ...listingDisclosureShape
40283
39756
  };
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.`);
39757
+ var invokeApiActionSchema = external_exports.looseObject({
39758
+ type: external_exports.literal("invoke_api"),
39759
+ href: marketplaceHrefSchema
39760
+ });
39761
+ var firstPartyApiMarketplaceHitSchema = external_exports.looseObject({
39762
+ ...marketplaceHitBase,
39763
+ kind: external_exports.literal("api"),
39764
+ provenance: firstPartyProvenanceSchema,
39765
+ execution: external_exports.looseObject({
39766
+ mode: executionModeSchema
39767
+ }),
39768
+ action: invokeApiActionSchema
39769
+ });
39770
+ var mirroredApiMarketplaceHitSchema = external_exports.looseObject({
39771
+ ...marketplaceHitBase,
39772
+ kind: external_exports.literal("api"),
39773
+ provenance: external_exports.literal("indexed"),
39774
+ execution: external_exports.looseObject({
39775
+ mode: external_exports.literal("direct"),
39776
+ url: external_exports.url().max(2048).regex(/^https:\/\/(?![^/?#]*@)/),
39777
+ method: marketplaceExecutionMethodSchema.nullable(),
39778
+ network: external_exports.string().trim().max(160).transform((network) => {
39779
+ if (network === "solana") return X402_SOLANA_MAINNET_CAIP2;
39780
+ if (network === "solana-devnet") return SOLANA_DEVNET_CAIP2;
39781
+ return network;
39782
+ }).pipe(
39783
+ external_exports.union([
39784
+ external_exports.string().regex(/^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/),
39785
+ // Persisted mainnet configs also use the full genesis hash.
39786
+ external_exports.literal(SOLANA_MAINNET_CAIP2)
39787
+ ])
39788
+ )
39789
+ }),
39790
+ action: invokeApiActionSchema
39791
+ });
39792
+ var apiMarketplaceHitSchema = external_exports.discriminatedUnion("provenance", [
39793
+ firstPartyApiMarketplaceHitSchema,
39794
+ mirroredApiMarketplaceHitSchema
39795
+ ]);
39796
+ var serviceOfferMarketplaceHitSchema = external_exports.looseObject({
39797
+ ...marketplaceHitBase,
39798
+ kind: external_exports.literal("service_offer"),
39799
+ action: external_exports.looseObject({
39800
+ type: external_exports.literal("start_engagement"),
39801
+ href: marketplaceHrefSchema
39802
+ })
39803
+ });
39804
+ var openRequestMarketplaceHitSchema = external_exports.looseObject({
39805
+ ...marketplaceHitBase,
39806
+ kind: external_exports.literal("open_request"),
39807
+ action: external_exports.looseObject({
39808
+ type: external_exports.literal("propose_to_request"),
39809
+ href: marketplaceHrefSchema
39810
+ })
39811
+ });
39812
+ var marketplaceHitSchema = external_exports.union([
39813
+ apiMarketplaceHitSchema,
39814
+ serviceOfferMarketplaceHitSchema,
39815
+ openRequestMarketplaceHitSchema
39816
+ ]);
39817
+ var marketplaceDiscoveryInputSchema = external_exports.strictObject({
39818
+ q: external_exports.string().trim().max(200).optional(),
39819
+ kinds: external_exports.array(marketplaceKindSchema).min(1).max(MARKETPLACE_KINDS.length).optional(),
39820
+ network: external_exports.string().trim().min(1).max(160).optional(),
39821
+ cursor: external_exports.string().trim().min(1).max(4096).optional(),
39822
+ limit: external_exports.number().int().min(1).max(50).optional(),
39823
+ includeUnverified: external_exports.boolean().optional()
39824
+ }).superRefine((input2, context) => {
39825
+ if (input2.kinds && new Set(input2.kinds).size !== input2.kinds.length) {
39826
+ context.addIssue({
39827
+ code: "custom",
39828
+ path: ["kinds"],
39829
+ message: "Marketplace kinds must be unique"
39830
+ });
40373
39831
  }
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);
39832
+ });
39833
+ function isMirroredHit(hit) {
39834
+ return hit.kind === "api" && hit.provenance === "indexed";
40404
39835
  }
39836
+ var marketplaceDiscoveryEnvelopeSchema = external_exports.looseObject({
39837
+ protocol: external_exports.literal(MARKETPLACE_DISCOVERY_PROTOCOL),
39838
+ items: external_exports.array(external_exports.unknown()),
39839
+ nextCursor: external_exports.string().min(1).max(4096).nullable(),
39840
+ unavailableKinds: external_exports.array(marketplaceKindSchema).max(MARKETPLACE_KINDS.length),
39841
+ rankingVersion: external_exports.literal(MARKETPLACE_RANKING_VERSION)
39842
+ });
39843
+ var marketplaceDiscoveryPageSchema = marketplaceDiscoveryEnvelopeSchema.extend({
39844
+ items: external_exports.array(marketplaceHitSchema)
39845
+ });
40405
39846
 
40406
39847
  // ../../node_modules/.pnpm/@solana+errors@5.5.1_typescript@6.0.3/node_modules/@solana/errors/dist/index.node.mjs
40407
39848
  var SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;
@@ -45383,16 +44824,16 @@ var DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;
45383
44824
  var DEFAULT_COMPUTE_UNIT_LIMIT = 2e4;
45384
44825
  var MAX_MEMO_BYTES = 256;
45385
44826
  var SOLANA_MAINNET_CAIP22 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
45386
- var SOLANA_DEVNET_CAIP2 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
44827
+ var SOLANA_DEVNET_CAIP22 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
45387
44828
  var SOLANA_TESTNET_CAIP2 = "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";
45388
44829
  var V1_TO_V2_NETWORK_MAP = {
45389
44830
  solana: SOLANA_MAINNET_CAIP22,
45390
- "solana-devnet": SOLANA_DEVNET_CAIP2,
44831
+ "solana-devnet": SOLANA_DEVNET_CAIP22,
45391
44832
  "solana-testnet": SOLANA_TESTNET_CAIP2
45392
44833
  };
45393
44834
  function normalizeNetwork(network) {
45394
44835
  if (network.includes(":")) {
45395
- const supported = [SOLANA_MAINNET_CAIP22, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];
44836
+ const supported = [SOLANA_MAINNET_CAIP22, SOLANA_DEVNET_CAIP22, SOLANA_TESTNET_CAIP2];
45396
44837
  if (!supported.includes(network)) {
45397
44838
  throw new Error(`Unsupported SVM network: ${network}`);
45398
44839
  }
@@ -45440,7 +44881,7 @@ var DEFAULT_ASSETS = {
45440
44881
  tokenProgram: TOKEN_2022_PROGRAM_ADDRESS2
45441
44882
  }
45442
44883
  ],
45443
- [SOLANA_DEVNET_CAIP2]: [
44884
+ [SOLANA_DEVNET_CAIP22]: [
45444
44885
  {
45445
44886
  asset: USDC_DEVNET_ADDRESS,
45446
44887
  decimals: 6,
@@ -45495,7 +44936,7 @@ var findDefaultAsset = (asset, network) => {
45495
44936
  function createRpcClient(network, customRpcUrl) {
45496
44937
  const caip2Network = normalizeNetwork(network);
45497
44938
  switch (caip2Network) {
45498
- case SOLANA_DEVNET_CAIP2: {
44939
+ case SOLANA_DEVNET_CAIP22: {
45499
44940
  const url2 = customRpcUrl || DEVNET_RPC_URL;
45500
44941
  return createSolanaRpc(devnet(url2));
45501
44942
  }
@@ -45693,6 +45134,376 @@ var ExactSvmScheme = class {
45693
45134
  var addressEncoder = getAddressEncoder();
45694
45135
  var compiledMessageDecoder = getCompiledTransactionMessageDecoder();
45695
45136
 
45137
+ // ../core/src/net-guard.ts
45138
+ import { lookup as dnsLookup } from "node:dns/promises";
45139
+ import { request as httpRequest } from "node:http";
45140
+ import { request as httpsRequest } from "node:https";
45141
+ import { isIP } from "node:net";
45142
+ import { Readable } from "node:stream";
45143
+ var defaultLookup = async (hostname4) => {
45144
+ const addresses = await dnsLookup(hostname4, { all: true });
45145
+ return addresses.map(({ address: address4 }) => address4);
45146
+ };
45147
+ async function assertPublicUrl(url2, options) {
45148
+ if (url2.username || url2.password) {
45149
+ throw guardError(url2);
45150
+ }
45151
+ if (url2.protocol !== "http:" && url2.protocol !== "https:") {
45152
+ throw guardError(url2);
45153
+ }
45154
+ if (options.allowPrivateNetwork) {
45155
+ return;
45156
+ }
45157
+ const hostname4 = normalizeHostname(url2.hostname);
45158
+ const lowercaseHostname = hostname4.toLowerCase();
45159
+ if (!lowercaseHostname || lowercaseHostname === "localhost" || lowercaseHostname.endsWith(".localhost") || lowercaseHostname.endsWith(".local") || lowercaseHostname.endsWith(".internal")) {
45160
+ throw guardError(url2);
45161
+ }
45162
+ if (isIP(hostname4)) {
45163
+ if (isNonPublicAddress(hostname4)) {
45164
+ throw guardError(url2);
45165
+ }
45166
+ return;
45167
+ }
45168
+ let addresses;
45169
+ try {
45170
+ addresses = await withTimeout2(
45171
+ (options.lookup ?? defaultLookup)(hostname4),
45172
+ options.timeoutMs ?? 5e3
45173
+ );
45174
+ } catch {
45175
+ throw guardError(url2);
45176
+ }
45177
+ if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
45178
+ throw guardError(url2);
45179
+ }
45180
+ }
45181
+ function createPublicFetch(options) {
45182
+ const lookupFn = options.lookup ?? defaultLookup;
45183
+ return (async (input2, init) => {
45184
+ const url2 = new URL(input2 instanceof Request ? input2.url : input2);
45185
+ await assertPublicUrl(url2, {
45186
+ allowPrivateNetwork: options.allowPrivateNetwork,
45187
+ lookup: lookupFn,
45188
+ timeoutMs: 5e3
45189
+ });
45190
+ const normalized = new Request(input2, init);
45191
+ const bytes = normalized.body ? Buffer.from(await normalized.arrayBuffer()) : null;
45192
+ return await new Promise((resolve3, reject) => {
45193
+ const requestOptions2 = {
45194
+ method: normalized.method,
45195
+ headers: Object.fromEntries(normalized.headers),
45196
+ signal: normalized.signal,
45197
+ ...options.allowPrivateNetwork ? {} : { lookup: pinnedLookup(lookupFn) }
45198
+ };
45199
+ const onResponse = (incoming) => {
45200
+ try {
45201
+ const headers = new Headers();
45202
+ for (const [name, value] of Object.entries(incoming.headers)) {
45203
+ if (Array.isArray(value)) {
45204
+ for (const item of value) headers.append(name, item);
45205
+ } else if (value !== void 0) {
45206
+ headers.set(name, value);
45207
+ }
45208
+ }
45209
+ const status = incoming.statusCode ?? 500;
45210
+ const bodyForbidden = normalized.method === "HEAD" || [204, 205, 304].includes(status);
45211
+ if (bodyForbidden) incoming.resume();
45212
+ const response = new Response(
45213
+ bodyForbidden ? null : Readable.toWeb(incoming),
45214
+ { status, statusText: incoming.statusMessage, headers }
45215
+ );
45216
+ Object.defineProperty(response, "url", { value: url2.toString() });
45217
+ resolve3(response);
45218
+ } catch (error61) {
45219
+ incoming.destroy();
45220
+ reject(error61);
45221
+ }
45222
+ };
45223
+ const request = url2.protocol === "https:" ? httpsRequest(url2, requestOptions2, onResponse) : httpRequest(url2, requestOptions2, onResponse);
45224
+ request.on("error", reject);
45225
+ if (bytes) request.write(bytes);
45226
+ request.end();
45227
+ });
45228
+ });
45229
+ }
45230
+ function pinnedLookup(lookup) {
45231
+ return (hostname4, dnsOptions, callback) => {
45232
+ void lookup(normalizeHostname(hostname4)).then((addresses) => {
45233
+ if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
45234
+ callback(guardError(new URL(`https://${hostname4}`)), "");
45235
+ return;
45236
+ }
45237
+ const address4 = addresses[0];
45238
+ const family = isIP(address4);
45239
+ callback(
45240
+ null,
45241
+ dnsOptions.all ? [{ address: address4, family }] : address4,
45242
+ dnsOptions.all ? void 0 : family
45243
+ );
45244
+ }).catch(
45245
+ (error61) => callback(error61 instanceof Error ? error61 : new Error("DNS lookup failed."), "")
45246
+ );
45247
+ };
45248
+ }
45249
+ async function withTimeout2(operation, timeoutMs) {
45250
+ let timeout;
45251
+ try {
45252
+ return await Promise.race([
45253
+ operation,
45254
+ new Promise((_resolve, reject) => {
45255
+ timeout = setTimeout(() => reject(new Error("DNS lookup timed out.")), timeoutMs);
45256
+ })
45257
+ ]);
45258
+ } finally {
45259
+ if (timeout) clearTimeout(timeout);
45260
+ }
45261
+ }
45262
+ function normalizeHostname(hostname4) {
45263
+ const unbracketed = hostname4.startsWith("[") && hostname4.endsWith("]") ? hostname4.slice(1, -1) : hostname4;
45264
+ return unbracketed.endsWith(".") ? unbracketed.slice(0, -1) : unbracketed;
45265
+ }
45266
+ function isNonPublicAddress(address4) {
45267
+ const normalized = normalizeHostname(address4);
45268
+ const version5 = isIP(normalized);
45269
+ if (version5 === 4) {
45270
+ return isNonPublicIpv4(parseIpv4(normalized));
45271
+ }
45272
+ if (version5 === 6) {
45273
+ return isNonPublicIpv6(parseIpv6(normalized));
45274
+ }
45275
+ return true;
45276
+ }
45277
+ function parseIpv4(address4) {
45278
+ const octets = address4.split(".").map(Number);
45279
+ return [octets[0], octets[1], octets[2], octets[3]];
45280
+ }
45281
+ function isNonPublicIpv4([first, second, third]) {
45282
+ 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;
45283
+ }
45284
+ function parseIpv6(address4) {
45285
+ let normalized = address4.toLowerCase();
45286
+ const lastColon = normalized.lastIndexOf(":");
45287
+ const dottedTail = normalized.slice(lastColon + 1);
45288
+ if (dottedTail.includes(".")) {
45289
+ const [first, second, third, fourth] = parseIpv4(dottedTail);
45290
+ normalized = `${normalized.slice(0, lastColon + 1)}${(first << 8 | second).toString(16)}:${(third << 8 | fourth).toString(16)}`;
45291
+ }
45292
+ const halves = normalized.split("::");
45293
+ const left = halves[0] ? halves[0].split(":").map(parseHex) : [];
45294
+ const right = halves[1] ? halves[1].split(":").map(parseHex) : [];
45295
+ const omittedCount = 8 - left.length - right.length;
45296
+ return halves.length === 2 ? [...left, ...Array.from({ length: omittedCount }, () => 0), ...right] : left;
45297
+ }
45298
+ function parseHex(value) {
45299
+ return Number.parseInt(value, 16);
45300
+ }
45301
+ function isNonPublicIpv6(hextets) {
45302
+ if (hextets.slice(0, 5).every((hextet) => hextet === 0) && hextets[5] === 65535) {
45303
+ const embeddedIpv4 = [
45304
+ hextets[6] >> 8,
45305
+ hextets[6] & 255,
45306
+ hextets[7] >> 8,
45307
+ hextets[7] & 255
45308
+ ];
45309
+ return isNonPublicIpv4(embeddedIpv4);
45310
+ }
45311
+ if (hextets.slice(0, 6).every((hextet) => hextet === 0)) {
45312
+ const compatibleIpv4 = [
45313
+ hextets[6] >> 8,
45314
+ hextets[6] & 255,
45315
+ hextets[7] >> 8,
45316
+ hextets[7] & 255
45317
+ ];
45318
+ if (isNonPublicIpv4(compatibleIpv4)) return true;
45319
+ }
45320
+ const isUnspecified = hextets.every((hextet) => hextet === 0);
45321
+ const isLoopback = hextets.slice(0, 7).every((hextet) => hextet === 0) && hextets[7] === 1;
45322
+ const first = hextets[0];
45323
+ const isUniqueLocal = first >= 64512 && first <= 65023;
45324
+ const isLinkLocal = first >= 65152 && first <= 65215;
45325
+ const isSiteLocal = first >= 65216 && first <= 65279;
45326
+ const isMulticast = first >= 65280;
45327
+ const isDocumentation = first === 8193 && hextets[1] === 3512;
45328
+ return isUnspecified || isLoopback || isUniqueLocal || isLinkLocal || isSiteLocal || isMulticast || isDocumentation;
45329
+ }
45330
+ function guardError(url2) {
45331
+ return new Error(
45332
+ `URL hostname ${JSON.stringify(url2.hostname)} is not allowed; private or internal destinations require allowPrivateNetwork true in the vAPI config.`
45333
+ );
45334
+ }
45335
+
45336
+ // ../core/src/networks.ts
45337
+ var USDC_DECIMALS = 6;
45338
+ var DEFAULT_ARC_GAS_HEADROOM_ATOMIC = 50000n;
45339
+ var NETWORKS2 = {
45340
+ [BASE_MAINNET_CAIP2]: {
45341
+ family: "evm",
45342
+ chainId: 8453,
45343
+ name: "Base mainnet",
45344
+ usdc: CANONICAL_X402_USDC_NETWORKS[BASE_MAINNET_CAIP2].usdc,
45345
+ gasToken: "ETH",
45346
+ rpcEnv: "BASE_RPC_URL",
45347
+ publicRpcUrl: "https://mainnet.base.org",
45348
+ explorerUrl: "https://basescan.org"
45349
+ },
45350
+ [ARC_MAINNET_CAIP2]: {
45351
+ family: "evm",
45352
+ chainId: 5042,
45353
+ name: "Arc mainnet",
45354
+ usdc: CANONICAL_X402_USDC_NETWORKS[ARC_MAINNET_CAIP2].usdc,
45355
+ gasToken: "USDC",
45356
+ rpcEnv: "ARC_RPC_URL",
45357
+ publicRpcUrl: "https://rpc.mainnet.arc.io",
45358
+ explorerUrl: "https://explorer.arc.io"
45359
+ },
45360
+ [ARC_TESTNET_CAIP2]: {
45361
+ family: "evm",
45362
+ chainId: 5042002,
45363
+ name: "Arc testnet",
45364
+ usdc: CANONICAL_X402_USDC_NETWORKS[ARC_TESTNET_CAIP2].usdc,
45365
+ gasToken: "USDC",
45366
+ rpcEnv: "ARC_TESTNET_RPC_URL"
45367
+ },
45368
+ [SOLANA_MAINNET_CAIP2]: {
45369
+ family: "svm",
45370
+ name: "Solana mainnet",
45371
+ usdc: SOLANA_MAINNET_USDC,
45372
+ gasToken: "SOL",
45373
+ rpcEnv: "SOLANA_RPC_URL",
45374
+ publicRpcUrl: "https://api.mainnet-beta.solana.com"
45375
+ },
45376
+ [X402_SOLANA_MAINNET_CAIP2]: {
45377
+ family: "svm",
45378
+ name: "Solana mainnet",
45379
+ usdc: SOLANA_MAINNET_USDC,
45380
+ gasToken: "SOL",
45381
+ rpcEnv: "SOLANA_RPC_URL",
45382
+ publicRpcUrl: "https://api.mainnet-beta.solana.com"
45383
+ }
45384
+ };
45385
+ function parseEip155ChainId(network) {
45386
+ const match = /^eip155:(\d+)$/.exec(network);
45387
+ if (!match) {
45388
+ throw new Error(`Unsupported network ${network}; expected eip155:<chainId>.`);
45389
+ }
45390
+ const chainId = Number(match[1]);
45391
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) {
45392
+ throw new Error(`Invalid EVM chain ID in network ${network}.`);
45393
+ }
45394
+ return chainId;
45395
+ }
45396
+ function isSolanaNetwork(network) {
45397
+ return network === SOLANA_MAINNET_CAIP2 || network === X402_SOLANA_MAINNET_CAIP2;
45398
+ }
45399
+ function usesUsdcGas(network) {
45400
+ try {
45401
+ return getNetworkDefinition(network).gasToken === "USDC";
45402
+ } catch {
45403
+ return false;
45404
+ }
45405
+ }
45406
+ function explorerTransactionUrl(network, hash5) {
45407
+ try {
45408
+ const explorerUrl = getNetworkDefinition(network).explorerUrl;
45409
+ return explorerUrl ? `${explorerUrl}/tx/${hash5}` : void 0;
45410
+ } catch {
45411
+ return void 0;
45412
+ }
45413
+ }
45414
+ function explorerAddressUrl(network, address4) {
45415
+ try {
45416
+ const explorerUrl = getNetworkDefinition(network).explorerUrl;
45417
+ return explorerUrl ? `${explorerUrl}/address/${address4}` : void 0;
45418
+ } catch {
45419
+ return void 0;
45420
+ }
45421
+ }
45422
+ function areSamePaymentNetwork(left, right) {
45423
+ return left === right || isSolanaNetwork(left) && isSolanaNetwork(right);
45424
+ }
45425
+ function isSupportedPaymentNetwork(network) {
45426
+ if (isSolanaNetwork(network)) return true;
45427
+ try {
45428
+ parseEip155ChainId(network);
45429
+ return true;
45430
+ } catch {
45431
+ return false;
45432
+ }
45433
+ }
45434
+ function configuredNetworkFor(networks, network) {
45435
+ const configured = networks[network];
45436
+ if (configured) return configured;
45437
+ if (network === X402_SOLANA_MAINNET_CAIP2) return networks[SOLANA_MAINNET_CAIP2];
45438
+ if (network === SOLANA_MAINNET_CAIP2) return networks[X402_SOLANA_MAINNET_CAIP2];
45439
+ return void 0;
45440
+ }
45441
+ function getNetworkDefinition(network) {
45442
+ const known = NETWORKS2[network];
45443
+ if (known) {
45444
+ return known;
45445
+ }
45446
+ const chainId = parseEip155ChainId(network);
45447
+ return {
45448
+ family: "evm",
45449
+ chainId,
45450
+ name: network,
45451
+ usdc: getAddress("0x0000000000000000000000000000000000000000"),
45452
+ gasToken: "ETH",
45453
+ rpcEnv: ""
45454
+ };
45455
+ }
45456
+ function requireRpcUrl(network, configured) {
45457
+ const definition = getNetworkDefinition(network);
45458
+ const envUrl = definition.rpcEnv ? process.env[definition.rpcEnv]?.trim() : void 0;
45459
+ const rpcUrl = envUrl || configured.rpcUrl.trim();
45460
+ if (rpcUrl) {
45461
+ return rpcUrl;
45462
+ }
45463
+ if (network === ARC_TESTNET_CAIP2) {
45464
+ throw new Error(
45465
+ "Arc testnet RPC is required. Set ARC_TESTNET_RPC_URL or add rpcUrl for eip155:5042002 in config.json."
45466
+ );
45467
+ }
45468
+ throw new Error(`RPC URL is required for ${network}.`);
45469
+ }
45470
+ function createChain(network, rpcUrl) {
45471
+ const definition = getNetworkDefinition(network);
45472
+ if (definition.family !== "evm" || definition.chainId === void 0) {
45473
+ throw new Error(`Network ${network} is not an EVM chain.`);
45474
+ }
45475
+ return defineChain({
45476
+ id: definition.chainId,
45477
+ name: definition.name,
45478
+ nativeCurrency: definition.gasToken === "USDC" ? { name: "USDC", symbol: "USDC", decimals: USDC_DECIMALS } : { name: "Ether", symbol: "ETH", decimals: 18 },
45479
+ rpcUrls: {
45480
+ default: { http: [rpcUrl] }
45481
+ },
45482
+ ...definition.explorerUrl ? {
45483
+ blockExplorers: {
45484
+ default: { name: `${definition.name} explorer`, url: definition.explorerUrl }
45485
+ }
45486
+ } : {}
45487
+ });
45488
+ }
45489
+ function createNetworkPublicClient(network, configured, options = {}) {
45490
+ const rpcUrl = requireRpcUrl(network, configured);
45491
+ return createPublicClient({
45492
+ chain: createChain(network, rpcUrl),
45493
+ transport: createNetworkHttpTransport(rpcUrl, options)
45494
+ });
45495
+ }
45496
+ function createNetworkHttpTransport(rpcUrl, options = {}) {
45497
+ const fetchFn = options.fetch ?? createPublicFetch({
45498
+ allowPrivateNetwork: options.allowPrivateNetwork ?? false,
45499
+ ...options.lookup ? { lookup: options.lookup } : {}
45500
+ });
45501
+ return http(rpcUrl, { fetchFn, fetchOptions: { redirect: "manual" } });
45502
+ }
45503
+ function formatUsdc(amountAtomic2) {
45504
+ return formatUnits(amountAtomic2, USDC_DECIMALS);
45505
+ }
45506
+
45696
45507
  // ../core/src/x402.ts
45697
45508
  var MAX_CHALLENGE_BYTES = 1048576;
45698
45509
  var MAX_UINT256 = (1n << 256n) - 1n;
@@ -46552,6 +46363,237 @@ function isRecord2(value) {
46552
46363
  return typeof value === "object" && value !== null && !Array.isArray(value);
46553
46364
  }
46554
46365
 
46366
+ // ../core/src/call-contracts-wire.ts
46367
+ var CALLABLE_KIND = "agent";
46368
+ var CALLABLE_CATEGORIES = ["ai", "data", "crypto", "compute", "search"];
46369
+ var callableCategorySchema = external_exports.enum(CALLABLE_CATEGORIES);
46370
+ var DISCOVERY_CATEGORIES = [...CALLABLE_CATEGORIES, "other"];
46371
+ var discoveryCategorySchema = external_exports.enum(DISCOVERY_CATEGORIES);
46372
+ var CALLABLE_CATEGORY_LABELS = {
46373
+ ai: { catalog: "AI / LLM", publish: "AI and models" },
46374
+ data: { catalog: "Data", publish: "Data" },
46375
+ crypto: { catalog: "Crypto", publish: "Crypto" },
46376
+ compute: { catalog: "Compute", publish: "Compute" },
46377
+ search: { catalog: "Search", publish: "Search" }
46378
+ };
46379
+ var CALLABLE_CATEGORY_SET = new Set(CALLABLE_CATEGORIES);
46380
+ function isCallableListing(kind, category) {
46381
+ return kind === CALLABLE_KIND && CALLABLE_CATEGORY_SET.has(category);
46382
+ }
46383
+ var serviceTierSchema = external_exports.enum(["listed", "verified", "partner"]);
46384
+ var discoveryEndpointSchema = external_exports.looseObject({
46385
+ name: external_exports.string(),
46386
+ method: external_exports.string(),
46387
+ url: external_exports.url(),
46388
+ price: external_exports.string(),
46389
+ description: external_exports.string(),
46390
+ operationId: external_exports.string().trim().min(1).optional(),
46391
+ requestContentType: external_exports.string().trim().min(1).optional(),
46392
+ requestSchema: external_exports.json().optional(),
46393
+ responseContentType: external_exports.string().trim().min(1).optional(),
46394
+ pathTemplate: external_exports.string().trim().min(1).optional(),
46395
+ pathParameters: external_exports.array(external_exports.string().trim().min(1)).optional(),
46396
+ payment: external_exports.union([
46397
+ external_exports.looseObject({
46398
+ scheme: external_exports.literal("exact"),
46399
+ network: external_exports.string().regex(/^eip155:\d+$/),
46400
+ asset: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
46401
+ payTo: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
46402
+ checkedAt: external_exports.iso.datetime()
46403
+ }),
46404
+ external_exports.looseObject({
46405
+ scheme: external_exports.literal("exact"),
46406
+ network: external_exports.union([
46407
+ external_exports.string().regex(/^solana:[-_a-zA-Z0-9]{1,32}$/),
46408
+ external_exports.literal(SOLANA_MAINNET_CAIP2)
46409
+ ]),
46410
+ asset: external_exports.string().refine(isSolanaAddress, "Expected a Solana base58 address."),
46411
+ payTo: external_exports.string().refine(isSolanaAddress, "Expected a Solana base58 address."),
46412
+ checkedAt: external_exports.iso.datetime()
46413
+ })
46414
+ ]).optional()
46415
+ });
46416
+ var serviceSummarySchema = external_exports.looseObject({
46417
+ id: external_exports.string(),
46418
+ name: external_exports.string(),
46419
+ description: external_exports.string(),
46420
+ category: discoveryCategorySchema,
46421
+ tier: serviceTierSchema,
46422
+ ...listingDisclosureShape,
46423
+ verified: external_exports.boolean(),
46424
+ wrapped: external_exports.boolean(),
46425
+ price: external_exports.string(),
46426
+ networks: external_exports.array(external_exports.string()),
46427
+ endpoints: external_exports.array(discoveryEndpointSchema)
46428
+ });
46429
+ var searchServicesResponseSchema = external_exports.looseObject({
46430
+ services: external_exports.array(serviceSummarySchema)
46431
+ });
46432
+ var listServicesResponseSchema = searchServicesResponseSchema;
46433
+ var discoveryServiceSchema = serviceSummarySchema;
46434
+ var discoveryResponseSchema = searchServicesResponseSchema;
46435
+
46436
+ // ../core/src/call-contracts.ts
46437
+ var DiscoveryCatalogError = class extends Error {
46438
+ constructor(code, message, serviceId, paymentNetworks) {
46439
+ super(message);
46440
+ this.paymentNetworks = paymentNetworks;
46441
+ this.code = code;
46442
+ this.serviceId = serviceId;
46443
+ }
46444
+ paymentNetworks;
46445
+ name = "DiscoveryCatalogError";
46446
+ code;
46447
+ serviceId;
46448
+ };
46449
+ function isDiscoveryCatalogError(error61) {
46450
+ if (!(error61 instanceof Error) || error61.name !== "DiscoveryCatalogError" || !("code" in error61) || typeof error61.code !== "string") {
46451
+ return false;
46452
+ }
46453
+ const networks = Reflect.get(error61, "paymentNetworks");
46454
+ return networks === void 0 || Array.isArray(networks) && networks.every((network) => typeof network === "string");
46455
+ }
46456
+ function parseDiscovery(raw) {
46457
+ const parsed = discoveryResponseSchema.safeParse(raw);
46458
+ if (!parsed.success) {
46459
+ const malformedUrl = parsed.error.issues.find(
46460
+ (issue2) => issue2.path.at(-1) === "url" && issue2.path.includes("endpoints")
46461
+ );
46462
+ if (malformedUrl) {
46463
+ const serviceIndex = pathIndexAfter(malformedUrl.path, "services");
46464
+ const serviceId = rawServiceId(raw, serviceIndex);
46465
+ throw new DiscoveryCatalogError(
46466
+ "malformed_url",
46467
+ `Service ${JSON.stringify(serviceId ?? "unknown")} has a malformed endpoint URL.`,
46468
+ serviceId
46469
+ );
46470
+ }
46471
+ throw new DiscoveryCatalogError("invalid_discovery", "Discovery response is malformed.");
46472
+ }
46473
+ for (const service of parsed.data.services) {
46474
+ buildTargets(service);
46475
+ }
46476
+ const resolveListing = (serviceId, endpointName) => {
46477
+ const service = parsed.data.services.find((candidate) => candidate.id === serviceId);
46478
+ if (!service) {
46479
+ throw new DiscoveryCatalogError(
46480
+ "service_not_found",
46481
+ `No payable endpoint found for service ${JSON.stringify(serviceId)}.`,
46482
+ serviceId
46483
+ );
46484
+ }
46485
+ return { service, endpoint: resolveTarget(service, endpointName) };
46486
+ };
46487
+ return {
46488
+ services: parsed.data.services,
46489
+ resolve: (serviceId, endpointName) => resolveListing(serviceId, endpointName).endpoint,
46490
+ resolveListing
46491
+ };
46492
+ }
46493
+ function resolveTarget(service, endpointName) {
46494
+ const { targets, targetsByName } = buildTargets(service);
46495
+ if (endpointName !== void 0) {
46496
+ const selected = targetsByName.get(endpointName.trim());
46497
+ if (!selected) {
46498
+ throw new DiscoveryCatalogError(
46499
+ "endpoint_not_found",
46500
+ `Service ${JSON.stringify(service.id)} has no endpoint ${JSON.stringify(endpointName)}. Available endpoints: ${[...targetsByName.keys()].join(", ")}.`,
46501
+ service.id
46502
+ );
46503
+ }
46504
+ return { ...selected };
46505
+ }
46506
+ if (targets.size !== 1) {
46507
+ const paymentNetworks = service.endpoints.flatMap(
46508
+ (endpoint) => endpoint.payment ? [endpoint.payment.network] : []
46509
+ );
46510
+ throw new DiscoveryCatalogError(
46511
+ "ambiguous_default",
46512
+ `Service ${JSON.stringify(service.id)} has ${targets.size} distinct payable endpoints. Choose one with endpoint: ${[...targetsByName.keys()].join(", ")}.`,
46513
+ service.id,
46514
+ paymentNetworks.length === service.endpoints.length ? paymentNetworks : void 0
46515
+ );
46516
+ }
46517
+ return targets.values().next().value;
46518
+ }
46519
+ function buildTargets(service) {
46520
+ if (service.endpoints.length === 0) {
46521
+ throw new DiscoveryCatalogError(
46522
+ "no_endpoint",
46523
+ `Service ${JSON.stringify(service.id)} has no payable endpoint.`,
46524
+ service.id
46525
+ );
46526
+ }
46527
+ const namedEndpoints = [...service.endpoints].sort(
46528
+ (left, right) => compareNames(left.name.trim(), right.name.trim())
46529
+ );
46530
+ const names = /* @__PURE__ */ new Set();
46531
+ const targets = /* @__PURE__ */ new Map();
46532
+ const targetsByName = /* @__PURE__ */ new Map();
46533
+ for (const endpoint of namedEndpoints) {
46534
+ const name = endpoint.name.trim();
46535
+ if (!name) {
46536
+ throw new DiscoveryCatalogError(
46537
+ "invalid_endpoint_name",
46538
+ `Service ${JSON.stringify(service.id)} has a blank endpoint name.`,
46539
+ service.id
46540
+ );
46541
+ }
46542
+ if (names.has(name)) {
46543
+ throw new DiscoveryCatalogError(
46544
+ "duplicate_endpoint_name",
46545
+ `Service ${JSON.stringify(service.id)} has duplicate endpoint name ${JSON.stringify(name)}.`,
46546
+ service.id
46547
+ );
46548
+ }
46549
+ names.add(name);
46550
+ const method = endpoint.method.trim().toUpperCase();
46551
+ if (!method) {
46552
+ throw new DiscoveryCatalogError(
46553
+ "blank_method",
46554
+ `Service ${JSON.stringify(service.id)} has a blank endpoint method.`,
46555
+ service.id
46556
+ );
46557
+ }
46558
+ const url2 = new URL(endpoint.url);
46559
+ if (url2.protocol !== "http:" && url2.protocol !== "https:") {
46560
+ throw new DiscoveryCatalogError(
46561
+ "malformed_url",
46562
+ `Service ${JSON.stringify(service.id)} has a non-HTTP endpoint URL.`,
46563
+ service.id
46564
+ );
46565
+ }
46566
+ const transportKey = `${method}\0${endpoint.url}`;
46567
+ const normalized = { ...endpoint, name, method };
46568
+ targetsByName.set(name, normalized);
46569
+ if (!targets.has(transportKey)) targets.set(transportKey, normalized);
46570
+ }
46571
+ return { targets, targetsByName };
46572
+ }
46573
+ function compareNames(left, right) {
46574
+ return left < right ? -1 : left > right ? 1 : 0;
46575
+ }
46576
+ function pathIndexAfter(path, key2) {
46577
+ const keyIndex = path.indexOf(key2);
46578
+ const candidate = path[keyIndex + 1];
46579
+ return typeof candidate === "number" ? candidate : void 0;
46580
+ }
46581
+ function rawServiceId(raw, serviceIndex) {
46582
+ if (serviceIndex === void 0 || typeof raw !== "object" || raw === null) {
46583
+ return void 0;
46584
+ }
46585
+ const services = Reflect.get(raw, "services");
46586
+ if (!Array.isArray(services)) {
46587
+ return void 0;
46588
+ }
46589
+ const service = services[serviceIndex];
46590
+ if (typeof service !== "object" || service === null) {
46591
+ return void 0;
46592
+ }
46593
+ const id2 = Reflect.get(service, "id");
46594
+ return typeof id2 === "string" ? id2 : void 0;
46595
+ }
46596
+
46555
46597
  // ../core/src/sweep.ts
46556
46598
  var ERC20_ABI = [
46557
46599
  {
@@ -47403,7 +47445,7 @@ var configSchema = external_exports.object({
47403
47445
  }
47404
47446
  for (const [network, configured] of Object.entries(config2.networks)) {
47405
47447
  if (isSolanaNetwork(network)) {
47406
- if (configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
47448
+ if (configured.usdc !== NETWORKS2[SOLANA_MAINNET_CAIP2].usdc) {
47407
47449
  context.addIssue({
47408
47450
  code: "custom",
47409
47451
  path: ["networks", network, "usdc"],
@@ -47414,7 +47456,7 @@ var configSchema = external_exports.object({
47414
47456
  }
47415
47457
  try {
47416
47458
  const usdc = getAddress(configured.usdc);
47417
- if ((network === ARC_MAINNET_CAIP2 || network === ARC_TESTNET_CAIP2) && usdc !== getAddress(NETWORKS[network].usdc)) {
47459
+ if ((network === ARC_MAINNET_CAIP2 || network === ARC_TESTNET_CAIP2) && usdc !== getAddress(NETWORKS2[network].usdc)) {
47418
47460
  context.addIssue({
47419
47461
  code: "custom",
47420
47462
  path: ["networks", network, "usdc"],
@@ -47566,15 +47608,15 @@ function getDefaultConfig(source = process.env, options = {}) {
47566
47608
  const tasksEscrowFactoryOverrides = tasksFactoryOverridesFromEnv(source);
47567
47609
  if (requested.has("base") || requested.has(BASE_MAINNET_CAIP2)) {
47568
47610
  networks[BASE_MAINNET_CAIP2] = {
47569
- rpcUrl: source.BASE_RPC_URL?.trim() || NETWORKS[BASE_MAINNET_CAIP2].publicRpcUrl,
47570
- usdc: NETWORKS[BASE_MAINNET_CAIP2].usdc
47611
+ rpcUrl: source.BASE_RPC_URL?.trim() || NETWORKS2[BASE_MAINNET_CAIP2].publicRpcUrl,
47612
+ usdc: NETWORKS2[BASE_MAINNET_CAIP2].usdc
47571
47613
  };
47572
47614
  }
47573
47615
  const arcMainnetRpcUrl = source.ARC_RPC_URL?.trim();
47574
47616
  if (arcMainnetRpcUrl || requested.has("arc") || requested.has(ARC_MAINNET_CAIP2)) {
47575
47617
  networks[ARC_MAINNET_CAIP2] = {
47576
- rpcUrl: arcMainnetRpcUrl || NETWORKS[ARC_MAINNET_CAIP2].publicRpcUrl,
47577
- usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc
47618
+ rpcUrl: arcMainnetRpcUrl || NETWORKS2[ARC_MAINNET_CAIP2].publicRpcUrl,
47619
+ usdc: NETWORKS2[ARC_MAINNET_CAIP2].usdc
47578
47620
  };
47579
47621
  }
47580
47622
  const arcTestnetRpcUrl = source.ARC_TESTNET_RPC_URL?.trim();
@@ -47586,14 +47628,14 @@ function getDefaultConfig(source = process.env, options = {}) {
47586
47628
  }
47587
47629
  networks[ARC_TESTNET_CAIP2] = {
47588
47630
  rpcUrl: arcTestnetRpcUrl,
47589
- usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc
47631
+ usdc: NETWORKS2[ARC_TESTNET_CAIP2].usdc
47590
47632
  };
47591
47633
  }
47592
47634
  const solanaRpcUrl = source.SOLANA_RPC_URL?.trim();
47593
47635
  if (solanaRpcUrl || requested.has("solana") || requested.has(SOLANA_MAINNET_CAIP2)) {
47594
47636
  networks[SOLANA_MAINNET_CAIP2] = {
47595
- rpcUrl: solanaRpcUrl || NETWORKS[SOLANA_MAINNET_CAIP2].publicRpcUrl,
47596
- usdc: NETWORKS[SOLANA_MAINNET_CAIP2].usdc
47637
+ rpcUrl: solanaRpcUrl || NETWORKS2[SOLANA_MAINNET_CAIP2].publicRpcUrl,
47638
+ usdc: NETWORKS2[SOLANA_MAINNET_CAIP2].usdc
47597
47639
  };
47598
47640
  }
47599
47641
  return {
@@ -47651,21 +47693,21 @@ Run vapi init to write the new URLs to ${path}.`
47651
47693
  if (arcMainnetRpcUrl) {
47652
47694
  const existing = config2.networks[ARC_MAINNET_CAIP2];
47653
47695
  config2.networks[ARC_MAINNET_CAIP2] = {
47654
- ...existing ?? { usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc },
47696
+ ...existing ?? { usdc: NETWORKS2[ARC_MAINNET_CAIP2].usdc },
47655
47697
  rpcUrl: arcMainnetRpcUrl
47656
47698
  };
47657
47699
  }
47658
47700
  if (arcTestnetRpcUrl) {
47659
47701
  const existing = config2.networks[ARC_TESTNET_CAIP2];
47660
47702
  config2.networks[ARC_TESTNET_CAIP2] = {
47661
- ...existing ?? { usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc },
47703
+ ...existing ?? { usdc: NETWORKS2[ARC_TESTNET_CAIP2].usdc },
47662
47704
  rpcUrl: arcTestnetRpcUrl
47663
47705
  };
47664
47706
  }
47665
47707
  if (solanaRpcUrl) {
47666
47708
  config2.networks[SOLANA_MAINNET_CAIP2] = {
47667
47709
  rpcUrl: solanaRpcUrl,
47668
- usdc: config2.networks[SOLANA_MAINNET_CAIP2]?.usdc ?? NETWORKS[SOLANA_MAINNET_CAIP2].usdc
47710
+ usdc: config2.networks[SOLANA_MAINNET_CAIP2]?.usdc ?? NETWORKS2[SOLANA_MAINNET_CAIP2].usdc
47669
47711
  };
47670
47712
  }
47671
47713
  if (registryUrl) {
@@ -47678,7 +47720,7 @@ Run vapi init to write the new URLs to ${path}.`
47678
47720
  for (const [network, configured] of Object.entries(config2.networks)) {
47679
47721
  configured.rpcUrl = configured.rpcUrl.trim();
47680
47722
  configured.usdc = configured.usdc.trim();
47681
- if (isSolanaNetwork(network) && configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
47723
+ if (isSolanaNetwork(network) && configured.usdc !== NETWORKS2[SOLANA_MAINNET_CAIP2].usdc) {
47682
47724
  throw new Error(`Network ${network} must use canonical Solana mainnet USDC.`);
47683
47725
  }
47684
47726
  if (!configured.rpcUrl) delete config2.networks[network];
@@ -47734,14 +47776,14 @@ async function enableDefaultNetwork(network, path = getVapiPaths().config, sourc
47734
47776
  const config2 = await loadConfig(path, source);
47735
47777
  if (network === "solana") {
47736
47778
  config2.networks[SOLANA_MAINNET_CAIP2] = {
47737
- rpcUrl: source.SOLANA_RPC_URL?.trim() || NETWORKS[SOLANA_MAINNET_CAIP2].publicRpcUrl,
47738
- usdc: NETWORKS[SOLANA_MAINNET_CAIP2].usdc
47779
+ rpcUrl: source.SOLANA_RPC_URL?.trim() || NETWORKS2[SOLANA_MAINNET_CAIP2].publicRpcUrl,
47780
+ usdc: NETWORKS2[SOLANA_MAINNET_CAIP2].usdc
47739
47781
  };
47740
47782
  } else {
47741
47783
  const existing = config2.networks[ARC_MAINNET_CAIP2];
47742
47784
  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
47785
+ ...existing ?? { usdc: NETWORKS2[ARC_MAINNET_CAIP2].usdc },
47786
+ rpcUrl: source.ARC_RPC_URL?.trim() || NETWORKS2[ARC_MAINNET_CAIP2].publicRpcUrl
47745
47787
  };
47746
47788
  }
47747
47789
  await writeConfigFile(path, config2);
@@ -78023,7 +78065,7 @@ function createRunBudget(args) {
78023
78065
  import { mkdir as mkdir15, writeFile as writeFile8 } from "node:fs/promises";
78024
78066
  import { arch, platform, release } from "node:os";
78025
78067
  import { join as join13 } from "node:path";
78026
- var VAPI_CLIENT_VERSION = "0.9.0";
78068
+ var VAPI_CLIENT_VERSION = "0.9.2";
78027
78069
  async function createSupportReport(options) {
78028
78070
  const message = options.message.trim();
78029
78071
  if (!message) throw new Error("Support report message must not be empty.");
@@ -79536,6 +79578,7 @@ var missingTasksChain = {
79536
79578
 
79537
79579
  // ../core/src/tasks/types.ts
79538
79580
  var uuidSchema = external_exports.uuid();
79581
+ var profileIdSchema = external_exports.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/);
79539
79582
  var isoDateTimeSchema = external_exports.iso.datetime();
79540
79583
  var addressSchema5 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/).transform((value) => value.toLowerCase());
79541
79584
  var bytes32Schema = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform((value) => value.toLowerCase());
@@ -79873,7 +79916,7 @@ var deliveryResponseSchema = external_exports.looseObject({
79873
79916
  version: external_exports.number().int().positive(),
79874
79917
  manifest: manifestResponseSchema,
79875
79918
  manifestHash: bytes32Schema,
79876
- submittedByProfileId: uuidSchema,
79919
+ submittedByProfileId: profileIdSchema,
79877
79920
  createdAt: isoDateTimeSchema
79878
79921
  });
79879
79922
  var orderDeliveryResponseSchema = external_exports.looseObject({
@@ -79979,7 +80022,7 @@ var reviewResponseSchema = external_exports.looseObject({
79979
80022
  id: uuidSchema,
79980
80023
  workOrderId: uuidSchema,
79981
80024
  clientAddress: addressSchema5,
79982
- vendorProfileId: uuidSchema,
80025
+ vendorProfileId: profileIdSchema,
79983
80026
  rating: external_exports.number().int().min(1).max(5),
79984
80027
  body: external_exports.string(),
79985
80028
  subRatings: external_exports.json().nullable(),
@@ -80522,12 +80565,15 @@ function createTasksClient(options) {
80522
80565
  const parsed2 = serverErrorSchema.safeParse(errorBody);
80523
80566
  const server = parsed2.success ? parsed2.data : void 0;
80524
80567
  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}`;
80568
+ const serverCode = nested?.code ?? server?.code;
80569
+ const serverMessage = (typeof server?.error === "string" ? server.error : nested?.message) || server?.message;
80570
+ const fallback = response.statusText || `HTTP ${response.status}`;
80571
+ 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
80572
  throw new TasksClientError(
80527
80573
  "http",
80528
80574
  message,
80529
80575
  response.status,
80530
- nested?.code ?? server?.code,
80576
+ serverCode,
80531
80577
  response.headers.get("Retry-After") ?? void 0
80532
80578
  );
80533
80579
  }
@@ -80930,9 +80976,10 @@ function safeTasksChainError(cause, broadcast, authorizationExposed, txHash) {
80930
80976
  let message = "Task chain operation failed.";
80931
80977
  if (cause instanceof TasksValidationError || cause instanceof TasksChainError)
80932
80978
  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) {
80979
+ else if (cause instanceof TasksClientError) {
80980
+ const code = cause.serverCode ?? (cause.status ? `http_${cause.status}` : cause.code);
80981
+ message = cause.status === 401 || cause.status === 403 ? `${code} (status ${cause.status})` : `${code}: ${cause.message}`;
80982
+ } else if (cause instanceof Error) {
80936
80983
  const short = "shortMessage" in cause && typeof cause.shortMessage === "string" ? cause.shortMessage : void 0;
80937
80984
  let statusCode;
80938
80985
  const seen = /* @__PURE__ */ new Set();
@@ -81740,6 +81787,44 @@ function createTasksChain(options) {
81740
81787
  return idempotencyKey;
81741
81788
  });
81742
81789
  }
81790
+ async function prepareOrResume(prepare, expected, idempotencyKey, kind, steps, authorizationExposed = false, beforeSign) {
81791
+ let prepared;
81792
+ let resumedFromServer = false;
81793
+ try {
81794
+ prepared = await prepare();
81795
+ } catch (error61) {
81796
+ if (!uncertainPreparation(error61)) throw error61;
81797
+ const fresh = await order(expected.milestone.workOrderId);
81798
+ const matches = fresh.milestones.filter((item) => item.id === expected.milestone.id);
81799
+ if (matches.length !== 1 || matches[0].workOrderId !== fresh.id)
81800
+ throw new TasksValidationError("The task milestone does not match its parent order.");
81801
+ const selected = matches[0];
81802
+ const operation = selected.chainOperation;
81803
+ if (expected.verb === "deliver" && selected.delivery && !operation)
81804
+ throw new TasksValidationError(
81805
+ "The server recorded this delivery but has no chain operation for it; open the task in the console to continue."
81806
+ );
81807
+ if (!operation || operation.kind !== kind || !(typeof steps === "string" ? [steps] : steps).includes(operation.step) || !["prepared", "submitted", "confirmed"].includes(operation.state))
81808
+ throw error61;
81809
+ if (expected.verb === "deliver" && selected.delivery && selected.delivery.manifestHash !== expected.manifestHash)
81810
+ throw new TasksValidationError(
81811
+ "The server recorded a different delivery manifest; refusing to continue."
81812
+ );
81813
+ prepared = {
81814
+ operation,
81815
+ milestone: { id: selected.id, workOrderId: selected.workOrderId }
81816
+ };
81817
+ resumedFromServer = true;
81818
+ }
81819
+ const result = await execute(
81820
+ prepared,
81821
+ expected,
81822
+ idempotencyKey,
81823
+ authorizationExposed,
81824
+ beforeSign
81825
+ );
81826
+ return resumedFromServer ? { ...result, resumedFromServer: true } : result;
81827
+ }
81743
81828
  async function verifyReceipt(operation, expected, hash5) {
81744
81829
  const rpc = rpcFor(expected.deployment.chainId);
81745
81830
  const receipt = await rpc.waitForTransactionReceipt({ hash: hash5, confirmations });
@@ -81781,6 +81866,7 @@ function createTasksChain(options) {
81781
81866
  throw new TasksValidationError(
81782
81867
  "The RPC transaction input does not match the verified task plan."
81783
81868
  );
81869
+ return receipt.blockNumber.toString();
81784
81870
  }
81785
81871
  async function retryConflict(call2) {
81786
81872
  let waited = 0;
@@ -81808,6 +81894,7 @@ function createTasksChain(options) {
81808
81894
  current = { ...initial, operation: live };
81809
81895
  let broadcast = current.operation.state === "submitted";
81810
81896
  let txHash = current.operation.transactionHash ?? void 0;
81897
+ let blockNumber;
81811
81898
  const operationId = initial.operation.id;
81812
81899
  function checkTransition(previous, next) {
81813
81900
  if (previous !== next && !(previous === "approve-usdc" && next === afterApproval))
@@ -81843,7 +81930,7 @@ function createTasksChain(options) {
81843
81930
  if (!operation.transactionHash)
81844
81931
  throw new TasksValidationError("The confirmed task operation has no transaction hash.");
81845
81932
  if (!checkpoint) {
81846
- await verifyReceipt(operation, expected, operation.transactionHash);
81933
+ blockNumber = await verifyReceipt(operation, expected, operation.transactionHash);
81847
81934
  await pending.complete(operation.id, operation.step, current);
81848
81935
  }
81849
81936
  const fresh = await order(expected.milestone.workOrderId);
@@ -81852,7 +81939,12 @@ function createTasksChain(options) {
81852
81939
  );
81853
81940
  if (!resultMilestone)
81854
81941
  throw new TasksValidationError("The reconciled task milestone is unavailable.");
81855
- return { txHash: operation.transactionHash, operation, milestone: resultMilestone };
81942
+ return {
81943
+ txHash: operation.transactionHash,
81944
+ operation,
81945
+ milestone: resultMilestone,
81946
+ blockNumber
81947
+ };
81856
81948
  }
81857
81949
  const rpc = rpcFor(expected.deployment.chainId);
81858
81950
  if (operation.state === "prepared") {
@@ -82048,7 +82140,7 @@ function createTasksChain(options) {
82048
82140
  }
82049
82141
  if (operation.state !== "submitted" || !operation.transactionHash)
82050
82142
  throw new TasksValidationError("The task operation has no submitted transaction.");
82051
- await verifyReceipt(operation, expected, operation.transactionHash);
82143
+ blockNumber = await verifyReceipt(operation, expected, operation.transactionHash);
82052
82144
  const reconciled = await retryConflict(
82053
82145
  () => client.reconcileOperation(
82054
82146
  operation.id,
@@ -82071,6 +82163,7 @@ function createTasksChain(options) {
82071
82163
  if (reconciled.operation.state !== "confirmed" && !(operation.step === "approve-usdc" && reconciled.operation.state === "prepared" && reconciled.operation.step === afterApproval))
82072
82164
  throw new TasksValidationError("The task transaction was not reconciled.");
82073
82165
  await pending.complete(operation.id, operation.step, reconciled);
82166
+ if (reconciled.operation.step !== operation.step) blockNumber = void 0;
82074
82167
  current = reconciled;
82075
82168
  }
82076
82169
  throw new TasksValidationError("The task operation exceeded its allowed step transitions.");
@@ -82105,14 +82198,16 @@ function createTasksChain(options) {
82105
82198
  );
82106
82199
  const prepareKey = await preparation(input2, verb, { evidenceHash: input2.evidenceHash });
82107
82200
  const call2 = verb === "dispute" ? client.disputeEscrow.bind(client) : client.counterEvidenceEscrow.bind(client);
82108
- return await execute(
82109
- await call2(
82201
+ return await prepareOrResume(
82202
+ () => call2(
82110
82203
  input2.escrowId,
82111
82204
  { evidenceHash: input2.evidenceHash },
82112
82205
  { idempotencyKey: prepareKey }
82113
82206
  ),
82114
82207
  { ...expected, evidenceHash: input2.evidenceHash },
82115
82208
  prepareKey,
82209
+ verb === "dispute" ? "escrow-dispute" : "escrow-counter-evidence",
82210
+ expected.steps,
82116
82211
  exposed,
82117
82212
  input2.beforeSign
82118
82213
  );
@@ -82132,11 +82227,34 @@ function createTasksChain(options) {
82132
82227
  await options.bindings.put(binding);
82133
82228
  },
82134
82229
  createEscrow: (input2) => safe(async () => {
82135
- const workOrder = await order(input2.orderId);
82230
+ let workOrder = await order(input2.orderId);
82136
82231
  const ready = await deployment();
82137
- const prepared = await client.createEscrow(input2.orderId, {
82138
- idempotencyKey: input2.idempotencyKey
82139
- });
82232
+ let prepared;
82233
+ let resumedFromServer = false;
82234
+ try {
82235
+ prepared = await client.createEscrow(input2.orderId, {
82236
+ idempotencyKey: input2.idempotencyKey
82237
+ });
82238
+ } catch (error61) {
82239
+ if (!uncertainPreparation(error61)) throw error61;
82240
+ const fresh = await order(input2.orderId);
82241
+ const candidates = fresh.milestones.filter((item) => {
82242
+ const previous = workOrder.milestones.find((prior) => prior.id === item.id);
82243
+ const operation = item.chainOperation;
82244
+ return item.workOrderId === input2.orderId && previous && operation && operation.kind === "escrow-create" && operation.step === "create-escrow" && (previous.escrowState === null || previous.chainOperation?.id === operation.id);
82245
+ });
82246
+ if (candidates.length !== 1) throw error61;
82247
+ const selected2 = candidates[0];
82248
+ prepared = {
82249
+ operation: selected2.chainOperation,
82250
+ milestone: {
82251
+ id: selected2.id,
82252
+ workOrderId: selected2.workOrderId
82253
+ }
82254
+ };
82255
+ workOrder = fresh;
82256
+ resumedFromServer = true;
82257
+ }
82140
82258
  const selected = workOrder.milestones.find((item) => item.id === prepared.milestone.id);
82141
82259
  if (!selected || selected.workOrderId !== input2.orderId)
82142
82260
  throw new TasksValidationError(
@@ -82146,11 +82264,12 @@ function createTasksChain(options) {
82146
82264
  { escrowId: selected.id, idempotencyKey: input2.idempotencyKey },
82147
82265
  "createEscrow"
82148
82266
  );
82149
- return await execute(
82267
+ const result = await execute(
82150
82268
  prepared,
82151
82269
  await expectation(selected, ready, "createEscrow", ["create-escrow"], input2.counterparty),
82152
82270
  prepareKey
82153
82271
  );
82272
+ return resumedFromServer ? { ...result, resumedFromServer: true } : result;
82154
82273
  }),
82155
82274
  async fund(input2) {
82156
82275
  let exposed = true;
@@ -82238,10 +82357,14 @@ function createTasksChain(options) {
82238
82357
  }
82239
82358
  exposed = true;
82240
82359
  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);
82360
+ return await prepareOrResume(
82361
+ () => client.fundEscrow(input2.escrowId, body, { idempotencyKey: prepareKey }),
82362
+ expected,
82363
+ prepareKey,
82364
+ "escrow-funding",
82365
+ expected.steps,
82366
+ exposed
82367
+ );
82245
82368
  } catch (cause) {
82246
82369
  throw chainError(cause, false, exposed);
82247
82370
  }
@@ -82266,22 +82389,26 @@ function createTasksChain(options) {
82266
82389
  manifest: frozen.manifest,
82267
82390
  note: input2.note
82268
82391
  });
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,
82392
+ return await prepareOrResume(
82393
+ async () => {
82394
+ const prepared = await client.deliverEscrow(
82395
+ input2.escrowId,
82396
+ { fileIds: frozen.manifest.files.map((file2) => file2.fileId), note: input2.note },
82397
+ { idempotencyKey: prepareKey }
82398
+ );
82399
+ if (prepared.delivery.manifestHash !== frozen.manifestHash)
82400
+ throw new TasksValidationError(
82401
+ "The server task delivery manifest hash does not match the local manifest."
82402
+ );
82403
+ return prepared;
82404
+ },
82280
82405
  {
82281
82406
  ...expected,
82282
82407
  manifestHash: frozen.manifestHash
82283
82408
  },
82284
- prepareKey
82409
+ prepareKey,
82410
+ "escrow-delivery",
82411
+ "submit-delivery"
82285
82412
  );
82286
82413
  }),
82287
82414
  release: (input2) => safe(async () => {
@@ -82295,10 +82422,12 @@ function createTasksChain(options) {
82295
82422
  input2.counterparty
82296
82423
  );
82297
82424
  const prepareKey = await preparation(input2, "release");
82298
- return await execute(
82299
- await client.releaseEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82425
+ return await prepareOrResume(
82426
+ () => client.releaseEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82300
82427
  expected,
82301
- prepareKey
82428
+ prepareKey,
82429
+ "escrow-release",
82430
+ "release-funds"
82302
82431
  );
82303
82432
  }),
82304
82433
  refund: (input2) => safe(async () => {
@@ -82312,10 +82441,12 @@ function createTasksChain(options) {
82312
82441
  input2.counterparty
82313
82442
  );
82314
82443
  const prepareKey = await preparation(input2, "refund");
82315
- return await execute(
82316
- await client.refundEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82444
+ return await prepareOrResume(
82445
+ () => client.refundEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82317
82446
  expected,
82318
- prepareKey
82447
+ prepareKey,
82448
+ "escrow-release",
82449
+ "refund-buyer"
82319
82450
  );
82320
82451
  }),
82321
82452
  disputeFee: (input2) => safe(async () => {
@@ -82343,16 +82474,21 @@ function createTasksChain(options) {
82343
82474
  input2.counterparty
82344
82475
  );
82345
82476
  const prepareKey = await preparation(input2, "resolve-unmatched");
82346
- return execute(
82347
- await client.resolveUnmatchedEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82477
+ return prepareOrResume(
82478
+ () => client.resolveUnmatchedEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
82348
82479
  expected,
82349
- prepareKey
82480
+ prepareKey,
82481
+ "escrow-unmatched-resolution",
82482
+ "resolve-unmatched-dispute"
82350
82483
  );
82351
82484
  }),
82352
82485
  signScopeMessage: (message) => safe(() => account.signMessage({ message }))
82353
82486
  };
82354
82487
  }
82355
82488
  var chainError = safeTasksChainError;
82489
+ function uncertainPreparation(error61) {
82490
+ return error61 instanceof TasksClientError && ((error61.status ?? 0) >= 400 || error61.code === "network" || error61.code === "timeout");
82491
+ }
82356
82492
  function retryDelay(header, now) {
82357
82493
  if (/^\d+(?:\.\d+)?$/u.test(header.trim())) return Math.max(1, Math.ceil(Number(header) * 1e3));
82358
82494
  const date5 = Date.parse(header);
@@ -82369,6 +82505,60 @@ function alreadySent(error61) {
82369
82505
  return error61 instanceof Error && /already known|known transaction|nonce (?:is )?too low/iu.test(error61.message);
82370
82506
  }
82371
82507
 
82508
+ // ../core/src/tasks/wait.ts
82509
+ async function waitForMilestone(client, input2) {
82510
+ const timeoutMs = input2.timeoutMs ?? 12e4;
82511
+ const intervalMs = input2.intervalMs ?? 3e3;
82512
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
82513
+ throw new RangeError("The milestone wait timeout must be non-negative and finite.");
82514
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0)
82515
+ throw new RangeError("The milestone wait interval must be positive and finite.");
82516
+ const sleep = input2.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
82517
+ const now = input2.now ?? (() => /* @__PURE__ */ new Date());
82518
+ const started = now().getTime();
82519
+ const deadline = started + timeoutMs;
82520
+ let polls = 0;
82521
+ let milestone;
82522
+ function result(reached) {
82523
+ return { reached, milestone, polls, elapsedMs: now().getTime() - started };
82524
+ }
82525
+ for (; ; ) {
82526
+ const remaining = deadline - now().getTime();
82527
+ if (remaining <= 0) return result(false);
82528
+ const controller = new AbortController();
82529
+ const timer = setTimeout(() => controller.abort(), remaining);
82530
+ let response;
82531
+ polls++;
82532
+ try {
82533
+ response = await client.getOrder(input2.orderId, { signal: controller.signal });
82534
+ } catch (error61) {
82535
+ if (controller.signal.aborted) return result(false);
82536
+ throw error61;
82537
+ } finally {
82538
+ clearTimeout(timer);
82539
+ }
82540
+ if (controller.signal.aborted || now().getTime() >= deadline) return result(false);
82541
+ const { workOrder } = response;
82542
+ milestone = workOrder.id === input2.orderId && workOrder.version === "work-order-view-v1" ? workOrder.milestones.find(
82543
+ (item) => item.id === input2.milestoneId && item.workOrderId === input2.orderId
82544
+ ) : void 0;
82545
+ if (milestone && reachedTarget(milestone, input2.target)) return result(true);
82546
+ await sleep(Math.min(intervalMs, deadline - now().getTime()));
82547
+ }
82548
+ }
82549
+ function reachedTarget(milestone, target) {
82550
+ switch (target) {
82551
+ case "created":
82552
+ return milestone.escrowState !== null;
82553
+ case "locked":
82554
+ return ["locked", "submitted", "disputed", "resolved"].includes(milestone.escrowState ?? "");
82555
+ case "delivered":
82556
+ return ["submitted", "disputed", "resolved"].includes(milestone.escrowState ?? "");
82557
+ case "released":
82558
+ return milestone.escrowState === "resolved";
82559
+ }
82560
+ }
82561
+
82372
82562
  // ../core/src/tasks/rpc.ts
82373
82563
  function createTasksRpcFor(config2, options = {}) {
82374
82564
  const clients = /* @__PURE__ */ new Map();
@@ -83485,7 +83675,10 @@ async function taskRequest(verb, route, operation, options) {
83485
83675
  "not_signed_in",
83486
83676
  `${verb} needs sign-in. ${options.signInHint}`
83487
83677
  );
83488
- throw new TaskOperationError(error61.serverCode ?? error61.code, error61.message);
83678
+ throw new TaskOperationError(
83679
+ error61.serverCode ?? (error61.status ? `http_${error61.status}` : error61.code),
83680
+ error61.message
83681
+ );
83489
83682
  }
83490
83683
  throw error61;
83491
83684
  }
@@ -83606,7 +83799,8 @@ function proposalTerms(id2, address4, deployment, terms) {
83606
83799
  return {
83607
83800
  version: "work-proposal-v1",
83608
83801
  workOrderId: id2,
83609
- providerAddress: address4,
83802
+ // The server lowercases addresses before canonicalizing the signed payload.
83803
+ providerAddress: address4.toLowerCase(),
83610
83804
  pricingModel: "fixed",
83611
83805
  milestones: [
83612
83806
  {
@@ -83993,6 +84187,55 @@ async function showTask(context, input2) {
83993
84187
  };
83994
84188
  }
83995
84189
  async function taskStatus(context, input2) {
84190
+ if (input2.signedIn) {
84191
+ const chainState = await taskRequest(
84192
+ "status",
84193
+ "chainState",
84194
+ async () => {
84195
+ try {
84196
+ return await context.client.chainState(input2.id);
84197
+ } catch (error61) {
84198
+ if (error61 instanceof TasksClientError && error61.status === 404) {
84199
+ if (isMissingTaskEntity(error61.serverCode, error61.message))
84200
+ throw new TaskOperationError("not_found", error61.message);
84201
+ throw new TaskOperationError(
84202
+ "not_available",
84203
+ "GET /v1/work-orders/:id/chain-state is not available on this server."
84204
+ );
84205
+ }
84206
+ throw error61;
84207
+ }
84208
+ },
84209
+ context
84210
+ );
84211
+ if (chainState.workOrderId !== input2.id)
84212
+ throw new TaskOperationError("invalid_response", "The response belongs to a different task.");
84213
+ const page = await taskRequest(
84214
+ "status",
84215
+ "events",
84216
+ async () => {
84217
+ try {
84218
+ return await context.client.events(input2.id, { wait: 0 });
84219
+ } catch (error61) {
84220
+ if (error61 instanceof TasksClientError && error61.status === 404) {
84221
+ if (isMissingTaskEntity(error61.serverCode, error61.message)) return null;
84222
+ throw new TaskOperationError(
84223
+ "not_available",
84224
+ "GET /v1/work-orders/:id/events is not available on this server."
84225
+ );
84226
+ }
84227
+ throw error61;
84228
+ }
84229
+ },
84230
+ context
84231
+ );
84232
+ return {
84233
+ task: { id: input2.id },
84234
+ chainState,
84235
+ events: page ? [...page.events].sort((a, b) => a.sequence - b.sequence) : null,
84236
+ nextAfter: page?.nextAfter ?? null
84237
+ };
84238
+ }
83996
84239
  const task = await taskRequest(
83997
84240
  "status",
83998
84241
  "publicTask",
@@ -84348,6 +84591,7 @@ var searchEventSchema = external_exports.strictObject({
84348
84591
  source: external_exports.string().min(1),
84349
84592
  latencyMs: external_exports.number().nonnegative().finite(),
84350
84593
  count: external_exports.number().int().nonnegative(),
84594
+ dropped: external_exports.number().int().nonnegative().optional(),
84351
84595
  error: external_exports.string().optional()
84352
84596
  })
84353
84597
  ),
@@ -87598,7 +87842,7 @@ var memberBundleConfigSchema = external_exports.unknown().refine((value) => !has
87598
87842
  external_exports.strictObject({ usdc: external_exports.string() })
87599
87843
  ).refine(
87600
87844
  (networks) => Object.entries(networks).every(
87601
- ([id2, network]) => isMemberBundleNetwork(id2) && network.usdc === NETWORKS[id2].usdc
87845
+ ([id2, network]) => isMemberBundleNetwork(id2) && network.usdc === NETWORKS2[id2].usdc
87602
87846
  ),
87603
87847
  { message: "Expected the canonical USDC token of each network." }
87604
87848
  ).refine((networks) => Object.keys(networks).length === 1, {
@@ -87637,14 +87881,14 @@ function memberBundleConfig(owner, network) {
87637
87881
  return {
87638
87882
  discoveryUrl,
87639
87883
  marketplaceDiscoveryUrl,
87640
- networks: { [network]: { usdc: NETWORKS[network].usdc } }
87884
+ networks: { [network]: { usdc: NETWORKS2[network].usdc } }
87641
87885
  };
87642
87886
  }
87643
87887
  function headlessConfigFromBundle(config2) {
87644
87888
  const networks = {};
87645
87889
  for (const [id2, network] of Object.entries(config2.networks)) {
87646
87890
  if (!isMemberBundleNetwork(id2) || network === void 0) continue;
87647
- networks[id2] = { rpcUrl: NETWORKS[id2].publicRpcUrl, usdc: network.usdc };
87891
+ networks[id2] = { rpcUrl: NETWORKS2[id2].publicRpcUrl, usdc: network.usdc };
87648
87892
  }
87649
87893
  return configSchema.parse({
87650
87894
  discoveryUrl: config2.discoveryUrl,
@@ -87737,7 +87981,7 @@ function parseStoredTokens(value) {
87737
87981
  }
87738
87982
  }
87739
87983
  function isMemberBundleNetwork(id2) {
87740
- return Object.hasOwn(NETWORKS, id2) && typeof NETWORKS[id2].publicRpcUrl === "string";
87984
+ return Object.hasOwn(NETWORKS2, id2) && typeof NETWORKS2[id2].publicRpcUrl === "string";
87741
87985
  }
87742
87986
  function hasForbiddenConfigKey(value) {
87743
87987
  if (Array.isArray(value)) return value.some(hasForbiddenConfigKey);
@@ -87942,6 +88186,7 @@ __export(src_exports3, {
87942
88186
  STARTING_RECONCILIATION_TIMEOUT_MS: () => STARTING_RECONCILIATION_TIMEOUT_MS,
87943
88187
  SwarmRunError: () => SwarmRunError,
87944
88188
  UNTRUSTED_NOTICE: () => UNTRUSTED_NOTICE,
88189
+ VapiCallError: () => VapiCallError,
87945
88190
  WalletSession: () => WalletSession,
87946
88191
  accountsSend: () => accountsSend,
87947
88192
  accountsSendInputSchema: () => accountsSendInputSchema,
@@ -88397,11 +88642,28 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
88397
88642
  }
88398
88643
  }
88399
88644
  });
88400
- const page = marketplaceDiscoveryPageSchema.parse(await response.json());
88401
- mergedCount = page.items.length;
88645
+ const envelope = marketplaceDiscoveryEnvelopeSchema.parse(await response.json());
88646
+ const items = [];
88647
+ let dropped = 0;
88648
+ for (const [index2, rawItem] of envelope.items.entries()) {
88649
+ const parsed = marketplaceHitSchema.safeParse(rawItem);
88650
+ if (parsed.success) {
88651
+ items.push(parsed.data);
88652
+ continue;
88653
+ }
88654
+ dropped += 1;
88655
+ try {
88656
+ options.debug?.(`vAPI marketplace discovery dropped invalid row at index ${index2}.`);
88657
+ } catch {
88658
+ }
88659
+ }
88660
+ mergedCount = items.length;
88402
88661
  const attempt = attempts.at(-1);
88403
- if (attempt) attempt.count = mergedCount;
88404
- return page;
88662
+ if (attempt) {
88663
+ attempt.count = mergedCount;
88664
+ if (dropped > 0) attempt.dropped = dropped;
88665
+ }
88666
+ return { ...envelope, items };
88405
88667
  } finally {
88406
88668
  if (options.searchesPath) {
88407
88669
  await appendSearchEvent(
@@ -88685,6 +88947,34 @@ var VapiCallError = class extends Error {
88685
88947
  paymentRejection;
88686
88948
  confirmedSettlement;
88687
88949
  };
88950
+ var SOLANA_PAYMENTS_UNSUPPORTED_MESSAGE = "Solana payments are not supported in this version of vAPI yet; they arrive in a later release.";
88951
+ function isSolanaCaip2(network) {
88952
+ return network.startsWith("solana:");
88953
+ }
88954
+ function listingPaymentNetwork(endpointNetwork, serviceNetworks) {
88955
+ if (endpointNetwork !== void 0) return endpointNetwork;
88956
+ return serviceNetworks?.length && serviceNetworks.every(isSolanaCaip2) ? serviceNetworks[0] : void 0;
88957
+ }
88958
+ function assertSupportedListingNetwork(network) {
88959
+ if (network !== void 0 && isSolanaCaip2(network)) {
88960
+ throw new VapiCallError(
88961
+ "unsupported_network",
88962
+ `${SOLANA_PAYMENTS_UNSUPPORTED_MESSAGE} This listing pays on ${network}.`
88963
+ );
88964
+ }
88965
+ }
88966
+ function assertSupportedListingResolution(error61) {
88967
+ if (isDiscoveryCatalogError(error61) && error61.code === "ambiguous_default" && error61.paymentNetworks?.length && error61.paymentNetworks.every(isSolanaCaip2)) {
88968
+ assertSupportedListingNetwork(error61.paymentNetworks[0]);
88969
+ }
88970
+ }
88971
+ function payableConfig(config2, account) {
88972
+ if (account.solana !== void 0) return config2;
88973
+ const networks = Object.fromEntries(
88974
+ Object.entries(config2.networks).filter(([network]) => !isSolanaCaip2(network))
88975
+ );
88976
+ return { ...config2, networks };
88977
+ }
88688
88978
  var MAX_RESPONSE_BYTES = 1048576;
88689
88979
  var BODY_HEADER_NAMES = [
88690
88980
  "content-encoding",
@@ -88699,7 +88989,9 @@ async function callService(args) {
88699
88989
  try {
88700
88990
  execution = await executeCallService(args, trace);
88701
88991
  } catch (error61) {
88702
- await recordCallError(args, error61, trace).catch(() => void 0);
88992
+ if (!(error61 instanceof VapiCallError && error61.code === "unsupported_network")) {
88993
+ await recordCallError(args, error61, trace).catch(() => void 0);
88994
+ }
88703
88995
  throw error61;
88704
88996
  }
88705
88997
  try {
@@ -88747,10 +89039,16 @@ async function executeCallService(args, trace) {
88747
89039
  config2,
88748
89040
  fetchImpl
88749
89041
  );
89042
+ } catch (error61) {
89043
+ assertSupportedListingResolution(error61);
89044
+ throw error61;
88750
89045
  } finally {
88751
89046
  trace.phases.discoverMs = elapsed2(trace, discoverStarted);
88752
89047
  }
88753
89048
  }
89049
+ assertSupportedListingNetwork(
89050
+ listingPaymentNetwork(endpoint?.payment?.network, endpoint?.serviceNetworks)
89051
+ );
88754
89052
  const requestedNetwork = normalizeRequiredNetwork(input2.network);
88755
89053
  const listingNetwork = endpoint?.payment?.network;
88756
89054
  if (requestedNetwork && listingNetwork && !areSamePaymentNetwork(requestedNetwork, listingNetwork)) {
@@ -88966,7 +89264,7 @@ async function executeCallService(args, trace) {
88966
89264
  challenge: challengeAttempt,
88967
89265
  account,
88968
89266
  caps: args.spendCaps ?? config2.spendCaps,
88969
- config: config2,
89267
+ config: payableConfig(config2, account),
88970
89268
  send: async (paidRequest) => {
88971
89269
  paidAttempt = await fetchWithGuardedRedirects(paidRequest, false);
88972
89270
  return paidAttempt;
@@ -89216,7 +89514,7 @@ async function resolveCallEndpoint(id2, endpointName, marketplaceHit, config2, f
89216
89514
  try {
89217
89515
  return registeredEndpoint(await resolveServiceListing(id2, config2, fetchImpl, endpointName));
89218
89516
  } catch (error61) {
89219
- if (!(error61 instanceof DiscoveryCatalogError) || error61.code !== "service_not_found") {
89517
+ if (!isDiscoveryCatalogError(error61) || error61.code !== "service_not_found") {
89220
89518
  throw error61;
89221
89519
  }
89222
89520
  const discovered = await findMarketplaceApiByRef(id2, config2, fetchImpl);
@@ -89256,6 +89554,7 @@ function registeredEndpoint(listing, verification) {
89256
89554
  return {
89257
89555
  ...listing.endpoint,
89258
89556
  verification: verification ?? listing.service.verification,
89557
+ serviceNetworks: listing.service.networks,
89259
89558
  registered: true,
89260
89559
  resolvedListing: true
89261
89560
  };
@@ -89494,14 +89793,17 @@ async function inspectService(input2, config2, fetchImpl) {
89494
89793
  try {
89495
89794
  listing = await resolveServiceListing(input2.id, config2, fetchImpl, input2.endpoint);
89496
89795
  } catch (error61) {
89497
- if (input2.endpoint || !(error61 instanceof DiscoveryCatalogError) || error61.code !== "service_not_found") {
89796
+ assertSupportedListingResolution(error61);
89797
+ if (input2.endpoint || !isDiscoveryCatalogError(error61) || error61.code !== "service_not_found") {
89498
89798
  throw error61;
89499
89799
  }
89500
89800
  const hit = await findMarketplaceApiByRef(input2.id, config2, fetchImpl);
89501
89801
  if (!hit || hit.kind !== "api" || hit.provenance !== "indexed") throw error61;
89802
+ assertSupportedListingNetwork(hit.execution.network);
89502
89803
  return inspectIndexedHit(hit);
89503
89804
  }
89504
89805
  const { endpoint, service } = listing;
89806
+ assertSupportedListingNetwork(listingPaymentNetwork(endpoint.payment?.network, service.networks));
89505
89807
  return {
89506
89808
  name: endpoint.name,
89507
89809
  method: endpoint.method,
@@ -93274,6 +93576,7 @@ var moneyParticipant = {
93274
93576
  "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
93577
  ).optional()
93276
93578
  };
93579
+ var waitForIndexer = external_exports.boolean().default(true).describe("Wait up to 60 seconds for vAPI to index the chain result before returning.");
93277
93580
  var cursor = external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
93278
93581
  function usdWithinEscrow(value, positive = false) {
93279
93582
  try {
@@ -93320,7 +93623,10 @@ var tasksPostTool = descriptor(
93320
93623
  deadline: external_exports.string(),
93321
93624
  intake: external_exports.enum(["proposals", "submissions"]).optional(),
93322
93625
  maxAwards: external_exports.number().int().min(TASK_LIMITS.maxAwardsMin).max(TASK_LIMITS.maxAwardsMax).optional(),
93323
- webhookUrl: httpsUrl.optional()
93626
+ webhookUrl: httpsUrl.optional(),
93627
+ vendor: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).describe(
93628
+ "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."
93629
+ ).optional()
93324
93630
  }
93325
93631
  );
93326
93632
  var tasksProposeTool = descriptor(
@@ -93345,42 +93651,43 @@ var tasksAwardTool = descriptor(
93345
93651
  { ...participant, proposalId: id }
93346
93652
  );
93347
93653
  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
93654
+ "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.",
93655
+ { ...moneyParticipant, wait: waitForIndexer }
93350
93656
  );
93351
93657
  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
93658
+ "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.",
93659
+ { ...moneyParticipant, wait: waitForIndexer }
93354
93660
  );
93355
93661
  var tasksDeliverTool = descriptor(
93356
- "Does not move money. Upload local delivery files, freeze the manifest and record delivery with the local vault wallet.",
93662
+ "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
93663
  {
93358
93664
  ...moneyParticipant,
93665
+ wait: waitForIndexer,
93359
93666
  files: external_exports.array(localPath).min(TASK_LIMITS.deliveryFilesMin).max(TASK_LIMITS.deliveryFilesMax),
93360
93667
  note: external_exports.string().max(TASK_LIMITS.deliveryNoteMax).refine((value) => value.trim().length > 0)
93361
93668
  }
93362
93669
  );
93363
93670
  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
93671
+ "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.",
93672
+ { ...moneyParticipant, wait: waitForIndexer }
93366
93673
  );
93367
93674
  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.",
93675
+ "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
93676
  moneyParticipant
93370
93677
  );
93371
93678
  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.",
93679
+ "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
93680
  {
93374
93681
  ...moneyParticipant,
93375
93682
  evidenceHash: external_exports.string().regex(TASK_LIMITS.disputeEvidenceHash)
93376
93683
  }
93377
93684
  );
93378
93685
  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.",
93686
+ "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
93687
  { ...moneyParticipant, evidenceHash: external_exports.string().regex(TASK_LIMITS.disputeEvidenceHash) }
93381
93688
  );
93382
93689
  var tasksResolveUnmatchedTool = descriptor(
93383
- "Moves money: resolves an unmatched dispute after the onchain counter-evidence deadline when no counter-evidence was submitted.",
93690
+ "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
93691
  moneyParticipant
93385
93692
  );
93386
93693
  var tasksMessageTool = descriptor(
@@ -93404,8 +93711,8 @@ var tasksWatchTool = descriptor(
93404
93711
  }
93405
93712
  );
93406
93713
  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 }
93714
+ "Does not move money. Read signed-in chain state and participant events, or the public task card without sign-in.",
93715
+ participant
93409
93716
  );
93410
93717
  var signInHint = "Call auth.link for the acting wallet.";
93411
93718
  function lazyTasksChain(factory, pending) {
@@ -93545,6 +93852,22 @@ function createTasksTools(options) {
93545
93852
  };
93546
93853
  };
93547
93854
  }
93855
+ async function waitAfterChain(ctx, orderId, milestoneId, target) {
93856
+ return await taskRequest(
93857
+ target,
93858
+ "getOrder",
93859
+ () => waitForMilestone(ctx.client, {
93860
+ orderId,
93861
+ milestoneId,
93862
+ target,
93863
+ timeoutMs: 6e4,
93864
+ intervalMs: 3e3,
93865
+ ...options.sleep === void 0 ? {} : { sleep: options.sleep },
93866
+ now
93867
+ }),
93868
+ ctx
93869
+ );
93870
+ }
93548
93871
  async function feeAction(verb, input2) {
93549
93872
  const ctx = await acting(input2.wallet);
93550
93873
  const policy = await taskPolicyForWallet({
@@ -93587,7 +93910,12 @@ function createTasksTools(options) {
93587
93910
  throw new TaskInputError("deadline must be at least 10 minutes from now.");
93588
93911
  const ctx = await acting(input2.wallet);
93589
93912
  const outcome = await postTask(ctx, {
93590
- order: { title: input2.title, description: input2.brief, policyFamily: "general-digital" },
93913
+ order: {
93914
+ title: input2.title,
93915
+ description: input2.brief,
93916
+ policyFamily: "general-digital",
93917
+ ...input2.vendor === void 0 ? {} : { invitedProviderAddress: input2.vendor }
93918
+ },
93591
93919
  amount: parseUsdToBaseUnits(input2.amountUsd),
93592
93920
  deadlineAt: new Date(postedAt.getTime() + deadlineDuration).toISOString(),
93593
93921
  ...input2.intake === void 0 ? {} : { intake: input2.intake },
@@ -93645,15 +93973,15 @@ function createTasksTools(options) {
93645
93973
  const ctx = await acting(input2.wallet);
93646
93974
  const signerAddress = (await options.session.addressesFor(ctx.selected.name)).address;
93647
93975
  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
- );
93976
+ const outcome = await signTaskScope(ctx, {
93977
+ id: input2.id,
93978
+ counterparty: input2.counterparty,
93979
+ signerAddress,
93980
+ bindings: createScopeBindings(home),
93981
+ signMessage: async (message) => (await unlock(ctx.selected.name)()).signMessage(message)
93982
+ });
93983
+ const wait2 = input2.wait && outcome.escrowCreation ? await waitAfterChain(ctx, input2.id, outcome.escrowCreation.milestone.id, "created") : null;
93984
+ return taskResult({ ...outcome, wait: wait2 });
93657
93985
  } catch (error61) {
93658
93986
  if (!(error61 instanceof TasksScopeCreationError)) throw error61;
93659
93987
  try {
@@ -93689,28 +94017,31 @@ function createTasksTools(options) {
93689
94017
  // Stdio has no human approval channel. Model arguments cannot grant approval.
93690
94018
  approval: { granted: false }
93691
94019
  });
93692
- return taskResult(outcome, !outcome.ok);
94020
+ const wait2 = input2.wait && outcome.ok ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "locked") : null;
94021
+ return taskResult({ ...outcome, wait: wait2 }, !outcome.ok);
93693
94022
  },
93694
94023
  async deliver(input2) {
93695
94024
  const files = (await Promise.all(input2.files.map(readTaskFile))).map(
93696
94025
  ({ fileName: name, bytes, contentType }) => ({ name, bytes, contentType })
93697
94026
  );
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
- );
94027
+ const ctx = await acting(input2.wallet);
94028
+ const outcome = await deliverTaskOperation(ctx, {
94029
+ id: input2.id,
94030
+ ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty },
94031
+ files,
94032
+ note: input2.note
94033
+ });
94034
+ const wait2 = input2.wait ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "delivered") : null;
94035
+ return taskResult({ ...outcome, wait: wait2 });
93706
94036
  },
93707
94037
  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
- );
94038
+ const ctx = await acting(input2.wallet);
94039
+ const outcome = await releaseTaskOperation(ctx, {
94040
+ id: input2.id,
94041
+ ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty }
94042
+ });
94043
+ const wait2 = input2.wait ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "released") : null;
94044
+ return taskResult({ ...outcome, wait: wait2 });
93714
94045
  },
93715
94046
  async refund(input2) {
93716
94047
  return taskResult(
@@ -93777,7 +94108,11 @@ function createTasksTools(options) {
93777
94108
  }
93778
94109
  },
93779
94110
  async status(input2) {
93780
- return taskResult(await taskStatus(await context(void 0, true), { id: input2.id }));
94111
+ await options.wallets?.reload();
94112
+ const publicOnly = input2.wallet === void 0 && options.session.activeName === void 0 && options.wallets !== void 0 && options.wallets.names().length === 0;
94113
+ const candidate = await context(input2.wallet, publicOnly);
94114
+ const ctx = candidate.token || publicOnly ? candidate : await context(void 0, true);
94115
+ return taskResult(await taskStatus(ctx, { id: input2.id, signedIn: Boolean(ctx.token) }));
93781
94116
  }
93782
94117
  };
93783
94118
  }
@@ -94534,6 +94869,11 @@ var statsToolResultSchema = external_exports.object({
94534
94869
  )
94535
94870
  })
94536
94871
  });
94872
+ function objectOutputSchema(schema) {
94873
+ if (!schema) return {};
94874
+ const json2 = external_exports.toJSONSchema(schema);
94875
+ return json2.type === "object" ? { outputSchema: json2 } : {};
94876
+ }
94537
94877
  var VapiMcpServer = class {
94538
94878
  #tools = /* @__PURE__ */ new Map();
94539
94879
  #onClose;
@@ -94557,7 +94897,7 @@ var VapiMcpServer = class {
94557
94897
  name,
94558
94898
  ...tool.description ? { description: tool.description } : {},
94559
94899
  inputSchema: external_exports.toJSONSchema(tool.inputSchema),
94560
- ...tool.outputSchema ? { outputSchema: external_exports.toJSONSchema(tool.outputSchema) } : {}
94900
+ ...objectOutputSchema(tool.outputSchema)
94561
94901
  }))
94562
94902
  };
94563
94903
  }
@@ -98922,7 +99262,7 @@ async function readProcessStdin() {
98922
99262
  }
98923
99263
 
98924
99264
  // ../cli/src/version.ts
98925
- var CLI_VERSION = "0.9.0";
99265
+ var CLI_VERSION = "0.9.2";
98926
99266
 
98927
99267
  // ../cli/src/status.ts
98928
99268
  async function statusCommand(argv, json2, io, dependencies) {
@@ -103871,10 +104211,10 @@ var TASK_HELP = `Usage:
103871
104211
  vapi task propose <id> --price <usd> --duration <duration> --note <text> [--account <name>] [--json]
103872
104212
  vapi task submit <id> --proof <https-url> [--proof <https-url>...] [--file <path>...] [--account <name>] [--json]
103873
104213
  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]
104214
+ vapi task sign <id> [--yes] [--no-wait] [--timeout 120s] [--counterparty <0x\u2026>] [--account <name>] [--json]
104215
+ vapi task fund <id> [--yes] [--no-wait] [--timeout 120s] [--counterparty <0x\u2026>] [--account <name>] [--json]
104216
+ vapi task deliver <id> --files <path...> --note <text> [--no-wait] [--timeout 120s] [--counterparty <0x\u2026>] [--account <name>] [--json]
104217
+ vapi task release <id> [--no-wait] [--timeout 120s] [--counterparty <0x\u2026>] [--account <name>] [--json]
103878
104218
  vapi task refund <id> [--counterparty <0x\u2026>] [--account <name>] [--json]
103879
104219
  vapi task dispute <id> --evidence-hash <0x + 64 hex> [--yes] [--counterparty <0x\u2026>] [--account <name>] [--json]
103880
104220
  vapi task counter-evidence <id> --evidence-hash <0x + 64 hex> [--yes] [--counterparty <0x\u2026>] [--account <name>] [--json]
@@ -103897,23 +104237,25 @@ Exit codes:
103897
104237
  2 policy refusal only (JSON ok:false with reason policy.perTask or policy.perDay)
103898
104238
  3 approval needed in non-interactive mode
103899
104239
 
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.`;
104240
+ 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
104241
  var IMPLEMENTED_VERBS = TASKS_CLIENT_VERBS;
103902
104242
  var USAGE = `Usage: vapi task <${IMPLEMENTED_VERBS.join("|")}>. Run vapi task --help.`;
103903
104243
  var TaskCommandError = class extends Error {
103904
- constructor(code, message, manifestHash) {
104244
+ constructor(code, message, manifestHash, prefixCode = false) {
103905
104245
  super(message);
103906
104246
  this.code = code;
103907
104247
  this.manifestHash = manifestHash;
104248
+ this.prefixCode = prefixCode;
103908
104249
  this.name = "TaskCommandError";
103909
104250
  }
103910
104251
  code;
103911
104252
  manifestHash;
104253
+ prefixCode;
103912
104254
  };
103913
104255
  function mapTaskError(error61) {
103914
104256
  if (error61 instanceof TaskInputError) return new UsageError(error61.message);
103915
104257
  if (error61 instanceof TaskOperationError)
103916
- return new TaskCommandError(error61.code, error61.message, error61.manifestHash);
104258
+ return new TaskCommandError(error61.code, error61.message, error61.manifestHash, true);
103917
104259
  return error61;
103918
104260
  }
103919
104261
  async function mapped(operation) {
@@ -104132,11 +104474,13 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104132
104474
  "--intake",
104133
104475
  "--max-awards",
104134
104476
  "--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"] : []
104477
+ ] : 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"] : [],
104478
+ ...["sign", "fund", "deliver", "release"].includes(verb) ? ["--timeout"] : []
104136
104479
  ]),
104137
104480
  booleanOptions: /* @__PURE__ */ new Set([
104138
104481
  ...verb === "search" ? ["--open"] : [],
104139
104482
  ...["sign", "fund", "dispute", "counter-evidence"].includes(verb) ? ["--yes"] : [],
104483
+ ...["sign", "fund", "deliver", "release"].includes(verb) ? ["--no-wait"] : [],
104140
104484
  ...verb === "watch" ? ["--auto-release"] : []
104141
104485
  ]),
104142
104486
  repeatableOptions: /* @__PURE__ */ new Set([
@@ -104292,7 +104636,7 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104292
104636
  throw new UsageError("message needs text between 1 and 10000 characters.");
104293
104637
  }
104294
104638
  if (verb === "thread") cursor2 = optionalInteger(parsed.one("--after"), "--after");
104295
- const context = await taskContext(parsed, io, dependencies, verb === "status");
104639
+ const context = await taskContext(parsed, io, dependencies);
104296
104640
  if (verb === "show" || verb === "status") {
104297
104641
  if (verb === "show" && context.token) {
104298
104642
  const result = await showTask(context, { id: id2, signedIn: true });
@@ -104302,7 +104646,21 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104302
104646
  ...receipts.map((receipt) => `Receipt (from escrow): ${receipt.receiptUrl}`)
104303
104647
  ]);
104304
104648
  } else {
104305
- const result = verb === "status" ? await taskStatus(context, { id: id2 }) : await showTask(context, { id: id2, signedIn: false });
104649
+ const result = verb === "status" ? await taskStatus(context, { id: id2, signedIn: Boolean(context.token) }) : await showTask(context, { id: id2, signedIn: false });
104650
+ if ("chainState" in result) {
104651
+ const milestoneLines = result.chainState.milestones.map((milestone) => {
104652
+ const ordinal = "ordinal" in milestone && typeof milestone.ordinal === "number" && Number.isFinite(milestone.ordinal) ? milestone.ordinal : milestone.milestoneId;
104653
+ const state = "state" in milestone.read ? ` ${milestone.read.state}` : "";
104654
+ const explorer = milestone.explorerUrl ? ` ${milestone.explorerUrl}` : "";
104655
+ return `milestone ${ordinal}: ${milestone.read.status}${state}${explorer}`;
104656
+ });
104657
+ const eventLines = (result.events ?? []).slice(-10).map((event) => {
104658
+ const createdAt = "createdAt" in event && typeof event.createdAt === "string" ? event.createdAt : event.at;
104659
+ return `${event.sequence} ${event.type} ${createdAt}`;
104660
+ });
104661
+ taskOutput(io, json2, context, verb, result, [...milestoneLines, ...eventLines]);
104662
+ return;
104663
+ }
104306
104664
  const task = result.task;
104307
104665
  taskOutput(
104308
104666
  io,
@@ -104346,6 +104704,11 @@ async function taskCommandInner(argv, json2, io, dependencies) {
104346
104704
  async function escrowTaskCommand(verb, id2, parsed, json2, io, dependencies, now) {
104347
104705
  taskCounterparty(parsed);
104348
104706
  if (verb === "watch") return await watchTask(id2, parsed, json2, io, dependencies, now);
104707
+ const waitsForIndex = ["sign", "fund", "deliver", "release"].includes(verb);
104708
+ const waitTimeoutText = parsed.one("--timeout") ?? "120s";
104709
+ const waitTimeoutMs = waitsForIndex ? parseTaskDuration2(waitTimeoutText, now) : void 0;
104710
+ if (waitTimeoutMs !== void 0 && waitTimeoutMs <= 0)
104711
+ throw new UsageError("--timeout must be positive.");
104349
104712
  const disputeEvidenceHash = ["dispute", "counter-evidence"].includes(verb) ? required3(parsed, "--evidence-hash") : void 0;
104350
104713
  const counterparty = taskCounterparty(parsed);
104351
104714
  if (disputeEvidenceHash !== void 0 && !TASK_LIMITS.disputeEvidenceHash.test(disputeEvidenceHash))
@@ -104395,9 +104758,24 @@ async function escrowTaskCommand(verb, id2, parsed, json2, io, dependencies, now
104395
104758
  return await account.signMessage({ message });
104396
104759
  }
104397
104760
  });
104398
- taskOutput(io, json2, displayContext, verb, result2, [
104761
+ if (!json2 && result2.escrowCreation?.resumedFromServer)
104762
+ io.stdout("The server had already prepared escrow creation; resumed from it.");
104763
+ const wait3 = result2.escrowCreation ? await waitForTaskIndex(
104764
+ context,
104765
+ dependencies,
104766
+ parsed,
104767
+ json2,
104768
+ io,
104769
+ id2,
104770
+ result2.escrowCreation,
104771
+ "created",
104772
+ "escrow creation",
104773
+ waitTimeoutText,
104774
+ waitTimeoutMs
104775
+ ) : null;
104776
+ taskOutput(io, json2, displayContext, verb, { ...result2, wait: wait3 }, [
104399
104777
  `Accepted scope for task ${id2}.`,
104400
- ...result2.escrowCreation ? ["Created the task escrow."] : []
104778
+ ...result2.escrowCreation && (wait3 === null || wait3.reached) ? ["escrow created"] : []
104401
104779
  ]);
104402
104780
  return;
104403
104781
  } catch (error61) {
@@ -104431,7 +104809,23 @@ async function escrowTaskCommand(verb, id2, parsed, json2, io, dependencies, now
104431
104809
  taskOutput(io, false, context, verb, {}, [`Prepared delivery manifest ${manifestHash}.`]);
104432
104810
  }
104433
104811
  });
104434
- taskOutput(io, json2, context, verb, outcome, [`Delivered task ${id2}.`]);
104812
+ const wait3 = await waitForTaskIndex(
104813
+ context,
104814
+ dependencies,
104815
+ parsed,
104816
+ json2,
104817
+ io,
104818
+ id2,
104819
+ outcome.result,
104820
+ "delivered",
104821
+ "delivery",
104822
+ waitTimeoutText,
104823
+ waitTimeoutMs
104824
+ );
104825
+ taskOutput(io, json2, context, verb, { ...outcome, wait: wait3 }, [
104826
+ ...wait3 === null || wait3.reached ? ["delivery recorded"] : [],
104827
+ ...outcome.result.resumedFromServer === true ? ["The server had already recorded this delivery; resumed from it."] : []
104828
+ ]);
104435
104829
  return;
104436
104830
  }
104437
104831
  const snapshot = await taskMoneySnapshot(context.client, id2, void 0, {
@@ -104494,15 +104888,82 @@ async function escrowTaskCommand(verb, id2, parsed, json2, io, dependencies, now
104494
104888
  }
104495
104889
  if (!outcome.ok && "declined" in outcome)
104496
104890
  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
- ]);
104891
+ if (!json2 && outcome.result.resumedFromServer)
104892
+ io.stdout("The server had already prepared this task operation; resumed from it.");
104893
+ const wait3 = verb === "fund" ? await waitForTaskIndex(
104894
+ context,
104895
+ dependencies,
104896
+ parsed,
104897
+ json2,
104898
+ io,
104899
+ id2,
104900
+ outcome.result,
104901
+ "locked",
104902
+ "funding",
104903
+ waitTimeoutText,
104904
+ waitTimeoutMs
104905
+ ) : void 0;
104906
+ taskOutput(
104907
+ io,
104908
+ json2,
104909
+ context,
104910
+ verb,
104911
+ wait3 === void 0 ? outcome : { ...outcome, wait: wait3 },
104912
+ verb === "fund" ? wait3 === null || wait3?.reached ? ["escrow funded"] : [] : [`Completed task ${verb} for ${id2}.`]
104913
+ );
104500
104914
  return;
104501
104915
  }
104502
104916
  if (!json2) io.stdout("Policy: explicit user instruction.");
104503
104917
  const settlementInput = { id: id2, snapshot, ...counterparty === void 0 ? {} : { counterparty } };
104504
104918
  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}.`]);
104919
+ if (!json2 && result.result.resumedFromServer)
104920
+ io.stdout("The server had already prepared this task operation; resumed from it.");
104921
+ const wait2 = verb === "release" ? await waitForTaskIndex(
104922
+ context,
104923
+ dependencies,
104924
+ parsed,
104925
+ json2,
104926
+ io,
104927
+ id2,
104928
+ result.result,
104929
+ "released",
104930
+ "release",
104931
+ waitTimeoutText,
104932
+ waitTimeoutMs
104933
+ ) : void 0;
104934
+ taskOutput(
104935
+ io,
104936
+ json2,
104937
+ context,
104938
+ verb,
104939
+ wait2 === void 0 ? result : { ...result, wait: wait2 },
104940
+ verb === "release" ? wait2 === null || wait2?.reached ? ["funds released"] : [] : [`Completed task ${verb} for ${id2}.`]
104941
+ );
104942
+ }
104943
+ async function waitForTaskIndex(context, dependencies, parsed, json2, io, orderId, result, target, description, timeoutText, timeoutMs) {
104944
+ if (parsed.has("--no-wait")) return null;
104945
+ if (!json2)
104946
+ io.stdout(
104947
+ `confirmed on chain${result.blockNumber === void 0 ? "" : ` in block ${result.blockNumber}`}, waiting for vAPI to index\u2026`
104948
+ );
104949
+ const wait2 = await taskRequest2(
104950
+ description,
104951
+ "getOrder",
104952
+ () => waitForMilestone(context.client, {
104953
+ orderId,
104954
+ milestoneId: result.milestone.id,
104955
+ target,
104956
+ timeoutMs,
104957
+ intervalMs: 3e3,
104958
+ sleep: context.sleep,
104959
+ now: dependencies.now ?? (() => /* @__PURE__ */ new Date())
104960
+ })
104961
+ );
104962
+ if (!wait2.reached)
104963
+ io.stderr(
104964
+ `vAPI has not indexed the ${description} yet after ${timeoutText}; run vapi task status ${orderId} later.`
104965
+ );
104966
+ return wait2;
104506
104967
  }
104507
104968
  var ScopeApprovalNeeded = class extends Error {
104508
104969
  constructor(terms) {
@@ -106434,6 +106895,7 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106434
106895
  error: message,
106435
106896
  exitCode: code,
106436
106897
  ...error61 instanceof RuntimeError ? { code: error61.code } : {},
106898
+ ...error61 instanceof VapiCallError ? { code: error61.code } : {},
106437
106899
  ...error61 instanceof DocsError ? { code: error61.code } : {},
106438
106900
  ...error61 instanceof RemoteKeyRefusedError ? { code: error61.code } : {},
106439
106901
  ...error61 instanceof TransferError ? { code: error61.code, moneyMoved: error61.moneyMoved } : {}
@@ -106441,7 +106903,10 @@ async function runCli(argv = process.argv.slice(2), io = processIo, dependencies
106441
106903
  );
106442
106904
  }
106443
106905
  } else {
106444
- runIo.stderr(message);
106906
+ const errorCode2 = taskInvocation && error61 instanceof TaskCommandError && error61.prefixCode ? errorCodeOf(error61) : void 0;
106907
+ runIo.stderr(
106908
+ errorCode2 !== void 0 && !message.startsWith(`${errorCode2}: `) ? `${errorCode2}: ${message}` : message
106909
+ );
106445
106910
  }
106446
106911
  if (shouldAutoUploadAfterFailure(argv.filter((argument) => argument !== "--json"))) {
106447
106912
  await autoUploadBackup(io, json2, dependencies);