@vapi-network/mcp 0.9.0 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -28903,365 +28903,6 @@ function date4(params) {
28903
28903
  return _coercedDate(ZodDate, params);
28904
28904
  }
28905
28905
 
28906
- // ../core/src/marketplace-contracts.ts
28907
- var MARKETPLACE_DISCOVERY_PROTOCOL = "vapi.marketplace.discovery/1";
28908
- var MARKETPLACE_RANKING_VERSION = "marketplace-ranking-v1";
28909
- var MARKETPLACE_KINDS = ["api", "service_offer", "open_request"];
28910
- var MARKETPLACE_EXECUTION_METHODS = [
28911
- "GET",
28912
- "HEAD",
28913
- "POST",
28914
- "PUT",
28915
- "PATCH",
28916
- "DELETE"
28917
- ];
28918
- var marketplaceExecutionMethodSchema = external_exports.enum(MARKETPLACE_EXECUTION_METHODS);
28919
- var marketplaceKindSchema = external_exports.enum(MARKETPLACE_KINDS);
28920
- var EXECUTION_MODES = ["direct", "gateway"];
28921
- var executionModeSchema = external_exports.enum(EXECUTION_MODES);
28922
- var PROVENANCES = ["indexed", "self_listed", "partner"];
28923
- var provenanceSchema = external_exports.enum(PROVENANCES);
28924
- var FIRST_PARTY_PROVENANCES = ["self_listed", "partner"];
28925
- var firstPartyProvenanceSchema = external_exports.enum(FIRST_PARTY_PROVENANCES);
28926
- var LISTING_GROUPS = ["vapi", "added", "partner", "external"];
28927
- var listingGroupSchema = external_exports.enum(LISTING_GROUPS);
28928
- var listingFeeSchema = external_exports.looseObject({
28929
- bps: external_exports.number().int().min(0),
28930
- label: external_exports.string()
28931
- });
28932
- var LISTING_VERIFICATIONS = ["none", "requested", "verified"];
28933
- var listingVerificationSchema = external_exports.enum(LISTING_VERIFICATIONS);
28934
- var listingVerificationFieldSchema = listingVerificationSchema.default("none").catch("none");
28935
- var listingLivenessSchema = external_exports.looseObject({
28936
- uptime7d: external_exports.number().min(0).max(1),
28937
- latencyP50Ms: external_exports.number().nonnegative().nullable(),
28938
- latencyP95Ms: external_exports.number().nonnegative().nullable(),
28939
- checks7d: external_exports.number().int().nonnegative()
28940
- });
28941
- var listingConformanceSchema = external_exports.looseObject({
28942
- declaredVersion: external_exports.union([external_exports.literal(1), external_exports.literal(2)]).nullable(),
28943
- versionConformant: external_exports.boolean(),
28944
- offerTransport: external_exports.enum(["body", "header", "both"]),
28945
- issues: external_exports.array(external_exports.string())
28946
- });
28947
- var listingIdentitySchema = external_exports.looseObject({
28948
- erc8004Id: external_exports.string().trim().min(1),
28949
- reputation: external_exports.looseObject({
28950
- score: external_exports.number().finite(),
28951
- count: external_exports.number().int().nonnegative()
28952
- }).optional().catch(void 0)
28953
- });
28954
- var listingDisclosureShape = {
28955
- group: listingGroupSchema.optional(),
28956
- fee: listingFeeSchema.optional(),
28957
- verification: listingVerificationFieldSchema,
28958
- liveness: listingLivenessSchema.optional().catch(void 0),
28959
- conformance: listingConformanceSchema.optional().catch(void 0),
28960
- identity: listingIdentitySchema.optional().catch(void 0)
28961
- };
28962
- var marketplaceBadgeCodeSchema = external_exports.enum([
28963
- "live_x402",
28964
- "partner",
28965
- "payout_wallet_confirmed",
28966
- "vapi_verified",
28967
- "external_catalog",
28968
- "approved_vendor"
28969
- ]);
28970
- var marketplaceBadgeSchema = external_exports.looseObject({
28971
- code: marketplaceBadgeCodeSchema,
28972
- label: external_exports.string().trim().min(1).max(80)
28973
- });
28974
- var marketplacePublicFactSchema = external_exports.looseObject({
28975
- label: external_exports.string().trim().min(1).max(80),
28976
- value: external_exports.string().trim().min(1).max(160)
28977
- });
28978
- var marketplaceHrefSchema = external_exports.union([
28979
- external_exports.string().trim().min(1).max(2048).regex(/^\/(?!\/)/),
28980
- external_exports.url().max(2048).regex(/^https:\/\//)
28981
- ]);
28982
- var marketplaceCardSchema = external_exports.looseObject({
28983
- title: external_exports.string().trim().min(1).max(160),
28984
- summary: external_exports.string().trim().min(1).max(1e3),
28985
- byline: external_exports.string().trim().min(1).max(160).optional(),
28986
- bylineHref: marketplaceHrefSchema.optional(),
28987
- badges: external_exports.array(marketplaceBadgeSchema).max(8),
28988
- facts: external_exports.array(marketplacePublicFactSchema).max(12)
28989
- });
28990
- var marketplaceHitBase = {
28991
- ref: external_exports.string().trim().min(1).max(512),
28992
- card: marketplaceCardSchema,
28993
- ...listingDisclosureShape
28994
- };
28995
- var invokeApiActionSchema = external_exports.looseObject({
28996
- type: external_exports.literal("invoke_api"),
28997
- href: marketplaceHrefSchema
28998
- });
28999
- var firstPartyApiMarketplaceHitSchema = external_exports.looseObject({
29000
- ...marketplaceHitBase,
29001
- kind: external_exports.literal("api"),
29002
- provenance: firstPartyProvenanceSchema,
29003
- execution: external_exports.looseObject({
29004
- mode: executionModeSchema
29005
- }),
29006
- action: invokeApiActionSchema
29007
- });
29008
- var mirroredApiMarketplaceHitSchema = external_exports.looseObject({
29009
- ...marketplaceHitBase,
29010
- kind: external_exports.literal("api"),
29011
- provenance: external_exports.literal("indexed"),
29012
- execution: external_exports.looseObject({
29013
- mode: external_exports.literal("direct"),
29014
- url: external_exports.url().max(2048).regex(/^https:\/\/(?![^/?#]*@)/),
29015
- method: marketplaceExecutionMethodSchema.nullable(),
29016
- network: external_exports.string().trim().max(160).regex(/^eip155:[1-9]\d*$/)
29017
- }),
29018
- action: invokeApiActionSchema
29019
- });
29020
- var apiMarketplaceHitSchema = external_exports.discriminatedUnion("provenance", [
29021
- firstPartyApiMarketplaceHitSchema,
29022
- mirroredApiMarketplaceHitSchema
29023
- ]);
29024
- var serviceOfferMarketplaceHitSchema = external_exports.looseObject({
29025
- ...marketplaceHitBase,
29026
- kind: external_exports.literal("service_offer"),
29027
- action: external_exports.looseObject({
29028
- type: external_exports.literal("start_engagement"),
29029
- href: marketplaceHrefSchema
29030
- })
29031
- });
29032
- var openRequestMarketplaceHitSchema = external_exports.looseObject({
29033
- ...marketplaceHitBase,
29034
- kind: external_exports.literal("open_request"),
29035
- action: external_exports.looseObject({
29036
- type: external_exports.literal("propose_to_request"),
29037
- href: marketplaceHrefSchema
29038
- })
29039
- });
29040
- var marketplaceHitSchema = external_exports.union([
29041
- apiMarketplaceHitSchema,
29042
- serviceOfferMarketplaceHitSchema,
29043
- openRequestMarketplaceHitSchema
29044
- ]);
29045
- var marketplaceDiscoveryInputSchema = external_exports.strictObject({
29046
- q: external_exports.string().trim().max(200).optional(),
29047
- kinds: external_exports.array(marketplaceKindSchema).min(1).max(MARKETPLACE_KINDS.length).optional(),
29048
- network: external_exports.string().trim().min(1).max(160).optional(),
29049
- cursor: external_exports.string().trim().min(1).max(4096).optional(),
29050
- limit: external_exports.number().int().min(1).max(50).optional(),
29051
- includeUnverified: external_exports.boolean().optional()
29052
- }).superRefine((input2, context) => {
29053
- if (input2.kinds && new Set(input2.kinds).size !== input2.kinds.length) {
29054
- context.addIssue({
29055
- code: "custom",
29056
- path: ["kinds"],
29057
- message: "Marketplace kinds must be unique"
29058
- });
29059
- }
29060
- });
29061
- function isMirroredHit(hit) {
29062
- return hit.kind === "api" && hit.provenance === "indexed";
29063
- }
29064
- var marketplaceDiscoveryPageSchema = external_exports.looseObject({
29065
- protocol: external_exports.literal(MARKETPLACE_DISCOVERY_PROTOCOL),
29066
- items: external_exports.array(marketplaceHitSchema),
29067
- nextCursor: external_exports.string().min(1).max(4096).nullable(),
29068
- unavailableKinds: external_exports.array(marketplaceKindSchema).max(MARKETPLACE_KINDS.length),
29069
- rankingVersion: external_exports.literal(MARKETPLACE_RANKING_VERSION)
29070
- });
29071
-
29072
- // ../core/src/call-contracts-wire.ts
29073
- var CALLABLE_CATEGORIES = ["ai", "data", "crypto", "compute", "search"];
29074
- var callableCategorySchema = external_exports.enum(CALLABLE_CATEGORIES);
29075
- var DISCOVERY_CATEGORIES = [...CALLABLE_CATEGORIES, "other"];
29076
- var discoveryCategorySchema = external_exports.enum(DISCOVERY_CATEGORIES);
29077
- var CALLABLE_CATEGORY_SET = new Set(CALLABLE_CATEGORIES);
29078
- var serviceTierSchema = external_exports.enum(["listed", "verified", "partner"]);
29079
- var discoveryEndpointSchema = external_exports.looseObject({
29080
- name: external_exports.string(),
29081
- method: external_exports.string(),
29082
- url: external_exports.url(),
29083
- price: external_exports.string(),
29084
- description: external_exports.string(),
29085
- operationId: external_exports.string().trim().min(1).optional(),
29086
- requestContentType: external_exports.string().trim().min(1).optional(),
29087
- requestSchema: external_exports.json().optional(),
29088
- responseContentType: external_exports.string().trim().min(1).optional(),
29089
- pathTemplate: external_exports.string().trim().min(1).optional(),
29090
- pathParameters: external_exports.array(external_exports.string().trim().min(1)).optional(),
29091
- payment: external_exports.looseObject({
29092
- scheme: external_exports.literal("exact"),
29093
- network: external_exports.string().regex(/^eip155:\d+$/),
29094
- asset: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
29095
- payTo: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
29096
- checkedAt: external_exports.iso.datetime()
29097
- }).optional()
29098
- });
29099
- var serviceSummarySchema = external_exports.looseObject({
29100
- id: external_exports.string(),
29101
- name: external_exports.string(),
29102
- description: external_exports.string(),
29103
- category: discoveryCategorySchema,
29104
- tier: serviceTierSchema,
29105
- ...listingDisclosureShape,
29106
- verified: external_exports.boolean(),
29107
- wrapped: external_exports.boolean(),
29108
- price: external_exports.string(),
29109
- networks: external_exports.array(external_exports.string()),
29110
- endpoints: external_exports.array(discoveryEndpointSchema)
29111
- });
29112
- var searchServicesResponseSchema = external_exports.looseObject({
29113
- services: external_exports.array(serviceSummarySchema)
29114
- });
29115
- var discoveryResponseSchema = searchServicesResponseSchema;
29116
-
29117
- // ../core/src/call-contracts.ts
29118
- var DiscoveryCatalogError = class extends Error {
29119
- name = "DiscoveryCatalogError";
29120
- code;
29121
- serviceId;
29122
- constructor(code, message, serviceId) {
29123
- super(message);
29124
- this.code = code;
29125
- this.serviceId = serviceId;
29126
- }
29127
- };
29128
- function parseDiscovery(raw) {
29129
- const parsed = discoveryResponseSchema.safeParse(raw);
29130
- if (!parsed.success) {
29131
- const malformedUrl = parsed.error.issues.find(
29132
- (issue2) => issue2.path.at(-1) === "url" && issue2.path.includes("endpoints")
29133
- );
29134
- if (malformedUrl) {
29135
- const serviceIndex = pathIndexAfter(malformedUrl.path, "services");
29136
- const serviceId = rawServiceId(raw, serviceIndex);
29137
- throw new DiscoveryCatalogError(
29138
- "malformed_url",
29139
- `Service ${JSON.stringify(serviceId ?? "unknown")} has a malformed endpoint URL.`,
29140
- serviceId
29141
- );
29142
- }
29143
- throw new DiscoveryCatalogError("invalid_discovery", "Discovery response is malformed.");
29144
- }
29145
- for (const service of parsed.data.services) {
29146
- buildTargets(service);
29147
- }
29148
- const resolveListing = (serviceId, endpointName) => {
29149
- const service = parsed.data.services.find((candidate) => candidate.id === serviceId);
29150
- if (!service) {
29151
- throw new DiscoveryCatalogError(
29152
- "service_not_found",
29153
- `No payable endpoint found for service ${JSON.stringify(serviceId)}.`,
29154
- serviceId
29155
- );
29156
- }
29157
- return { service, endpoint: resolveTarget(service, endpointName) };
29158
- };
29159
- return {
29160
- services: parsed.data.services,
29161
- resolve: (serviceId, endpointName) => resolveListing(serviceId, endpointName).endpoint,
29162
- resolveListing
29163
- };
29164
- }
29165
- function resolveTarget(service, endpointName) {
29166
- const { targets, targetsByName } = buildTargets(service);
29167
- if (endpointName !== void 0) {
29168
- const selected = targetsByName.get(endpointName.trim());
29169
- if (!selected) {
29170
- throw new DiscoveryCatalogError(
29171
- "endpoint_not_found",
29172
- `Service ${JSON.stringify(service.id)} has no endpoint ${JSON.stringify(endpointName)}. Available endpoints: ${[...targetsByName.keys()].join(", ")}.`,
29173
- service.id
29174
- );
29175
- }
29176
- return { ...selected };
29177
- }
29178
- if (targets.size !== 1) {
29179
- throw new DiscoveryCatalogError(
29180
- "ambiguous_default",
29181
- `Service ${JSON.stringify(service.id)} has ${targets.size} distinct payable endpoints. Choose one with endpoint: ${[...targetsByName.keys()].join(", ")}.`,
29182
- service.id
29183
- );
29184
- }
29185
- return targets.values().next().value;
29186
- }
29187
- function buildTargets(service) {
29188
- if (service.endpoints.length === 0) {
29189
- throw new DiscoveryCatalogError(
29190
- "no_endpoint",
29191
- `Service ${JSON.stringify(service.id)} has no payable endpoint.`,
29192
- service.id
29193
- );
29194
- }
29195
- const namedEndpoints = [...service.endpoints].sort(
29196
- (left, right) => compareNames(left.name.trim(), right.name.trim())
29197
- );
29198
- const names = /* @__PURE__ */ new Set();
29199
- const targets = /* @__PURE__ */ new Map();
29200
- const targetsByName = /* @__PURE__ */ new Map();
29201
- for (const endpoint of namedEndpoints) {
29202
- const name = endpoint.name.trim();
29203
- if (!name) {
29204
- throw new DiscoveryCatalogError(
29205
- "invalid_endpoint_name",
29206
- `Service ${JSON.stringify(service.id)} has a blank endpoint name.`,
29207
- service.id
29208
- );
29209
- }
29210
- if (names.has(name)) {
29211
- throw new DiscoveryCatalogError(
29212
- "duplicate_endpoint_name",
29213
- `Service ${JSON.stringify(service.id)} has duplicate endpoint name ${JSON.stringify(name)}.`,
29214
- service.id
29215
- );
29216
- }
29217
- names.add(name);
29218
- const method = endpoint.method.trim().toUpperCase();
29219
- if (!method) {
29220
- throw new DiscoveryCatalogError(
29221
- "blank_method",
29222
- `Service ${JSON.stringify(service.id)} has a blank endpoint method.`,
29223
- service.id
29224
- );
29225
- }
29226
- const url2 = new URL(endpoint.url);
29227
- if (url2.protocol !== "http:" && url2.protocol !== "https:") {
29228
- throw new DiscoveryCatalogError(
29229
- "malformed_url",
29230
- `Service ${JSON.stringify(service.id)} has a non-HTTP endpoint URL.`,
29231
- service.id
29232
- );
29233
- }
29234
- const transportKey = `${method}\0${endpoint.url}`;
29235
- const normalized = { ...endpoint, name, method };
29236
- targetsByName.set(name, normalized);
29237
- if (!targets.has(transportKey)) targets.set(transportKey, normalized);
29238
- }
29239
- return { targets, targetsByName };
29240
- }
29241
- function compareNames(left, right) {
29242
- return left < right ? -1 : left > right ? 1 : 0;
29243
- }
29244
- function pathIndexAfter(path, key2) {
29245
- const keyIndex = path.indexOf(key2);
29246
- const candidate = path[keyIndex + 1];
29247
- return typeof candidate === "number" ? candidate : void 0;
29248
- }
29249
- function rawServiceId(raw, serviceIndex) {
29250
- if (serviceIndex === void 0 || typeof raw !== "object" || raw === null) {
29251
- return void 0;
29252
- }
29253
- const services = Reflect.get(raw, "services");
29254
- if (!Array.isArray(services)) {
29255
- return void 0;
29256
- }
29257
- const service = services[serviceIndex];
29258
- if (typeof service !== "object" || service === null) {
29259
- return void 0;
29260
- }
29261
- const id2 = Reflect.get(service, "id");
29262
- return typeof id2 === "string" ? id2 : void 0;
29263
- }
29264
-
29265
28906
  // ../../node_modules/.pnpm/viem@2.56.1_typescript@6.0.3_zod@4.5.4/node_modules/viem/_esm/index.js
29266
28907
  init_exports();
29267
28908
 
@@ -38299,6 +37940,7 @@ var ARC_MAINNET_CAIP2 = "eip155:5042";
38299
37940
  var ARC_TESTNET_CAIP2 = "eip155:5042002";
38300
37941
  var SOLANA_MAINNET_CAIP2 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d";
38301
37942
  var X402_SOLANA_MAINNET_CAIP2 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
37943
+ var SOLANA_DEVNET_CAIP2 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
38302
37944
  var SOLANA_MAINNET_USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
38303
37945
  function canonicalIdentity(usdc, eip712Domain) {
38304
37946
  return Object.freeze({
@@ -38342,374 +37984,194 @@ var BROWSER_ENABLED_X402_NETWORK_CONFIG = Object.freeze({
38342
37984
  [ARC_TESTNET_CAIP2]: browserNetwork(arcTestnetUsdc)
38343
37985
  });
38344
37986
 
38345
- // ../core/src/net-guard.ts
38346
- import { lookup as dnsLookup } from "node:dns/promises";
38347
- import { request as httpRequest } from "node:http";
38348
- import { request as httpsRequest } from "node:https";
38349
- import { isIP } from "node:net";
38350
- import { Readable } from "node:stream";
38351
- var defaultLookup = async (hostname3) => {
38352
- const addresses = await dnsLookup(hostname3, { all: true });
38353
- return addresses.map(({ address: address4 }) => address4);
37987
+ // ../core/src/marketplace-contracts.ts
37988
+ var MARKETPLACE_DISCOVERY_PROTOCOL = "vapi.marketplace.discovery/1";
37989
+ var MARKETPLACE_RANKING_VERSION = "marketplace-ranking-v1";
37990
+ var MARKETPLACE_KINDS = ["api", "service_offer", "open_request"];
37991
+ var MARKETPLACE_EXECUTION_METHODS = [
37992
+ "GET",
37993
+ "HEAD",
37994
+ "POST",
37995
+ "PUT",
37996
+ "PATCH",
37997
+ "DELETE"
37998
+ ];
37999
+ var marketplaceExecutionMethodSchema = external_exports.enum(MARKETPLACE_EXECUTION_METHODS);
38000
+ var marketplaceKindSchema = external_exports.enum(MARKETPLACE_KINDS);
38001
+ var EXECUTION_MODES = ["direct", "gateway"];
38002
+ var executionModeSchema = external_exports.enum(EXECUTION_MODES);
38003
+ var PROVENANCES = ["indexed", "self_listed", "partner"];
38004
+ var provenanceSchema = external_exports.enum(PROVENANCES);
38005
+ var FIRST_PARTY_PROVENANCES = ["self_listed", "partner"];
38006
+ var firstPartyProvenanceSchema = external_exports.enum(FIRST_PARTY_PROVENANCES);
38007
+ var LISTING_GROUPS = ["vapi", "added", "partner", "external"];
38008
+ var listingGroupSchema = external_exports.enum(LISTING_GROUPS);
38009
+ var listingFeeSchema = external_exports.looseObject({
38010
+ bps: external_exports.number().int().min(0),
38011
+ label: external_exports.string()
38012
+ });
38013
+ var LISTING_VERIFICATIONS = ["none", "requested", "verified"];
38014
+ var listingVerificationSchema = external_exports.enum(LISTING_VERIFICATIONS);
38015
+ var listingVerificationFieldSchema = listingVerificationSchema.default("none").catch("none");
38016
+ var listingLivenessSchema = external_exports.looseObject({
38017
+ uptime7d: external_exports.number().min(0).max(1),
38018
+ latencyP50Ms: external_exports.number().nonnegative().nullable(),
38019
+ latencyP95Ms: external_exports.number().nonnegative().nullable(),
38020
+ checks7d: external_exports.number().int().nonnegative()
38021
+ });
38022
+ var listingConformanceSchema = external_exports.looseObject({
38023
+ declaredVersion: external_exports.union([external_exports.literal(1), external_exports.literal(2)]).nullable(),
38024
+ versionConformant: external_exports.boolean(),
38025
+ offerTransport: external_exports.enum(["body", "header", "both"]),
38026
+ issues: external_exports.array(external_exports.string())
38027
+ });
38028
+ var listingIdentitySchema = external_exports.looseObject({
38029
+ erc8004Id: external_exports.string().trim().min(1),
38030
+ reputation: external_exports.looseObject({
38031
+ score: external_exports.number().finite(),
38032
+ count: external_exports.number().int().nonnegative()
38033
+ }).optional().catch(void 0)
38034
+ });
38035
+ var listingDisclosureShape = {
38036
+ // Presentation metadata must not make an otherwise executable row vanish
38037
+ // when the registry adds a new group or changes the fee display shape.
38038
+ group: listingGroupSchema.optional().catch(void 0),
38039
+ fee: listingFeeSchema.optional().catch(void 0),
38040
+ verification: listingVerificationFieldSchema,
38041
+ liveness: listingLivenessSchema.optional().catch(void 0),
38042
+ conformance: listingConformanceSchema.optional().catch(void 0),
38043
+ identity: listingIdentitySchema.optional().catch(void 0)
38354
38044
  };
38355
- async function assertPublicUrl(url2, options) {
38356
- if (url2.username || url2.password) {
38357
- throw guardError(url2);
38358
- }
38359
- if (url2.protocol !== "http:" && url2.protocol !== "https:") {
38360
- throw guardError(url2);
38361
- }
38362
- if (options.allowPrivateNetwork) {
38363
- return;
38364
- }
38365
- const hostname3 = normalizeHostname(url2.hostname);
38366
- const lowercaseHostname = hostname3.toLowerCase();
38367
- if (!lowercaseHostname || lowercaseHostname === "localhost" || lowercaseHostname.endsWith(".localhost") || lowercaseHostname.endsWith(".local") || lowercaseHostname.endsWith(".internal")) {
38368
- throw guardError(url2);
38369
- }
38370
- if (isIP(hostname3)) {
38371
- if (isNonPublicAddress(hostname3)) {
38372
- throw guardError(url2);
38373
- }
38374
- return;
38375
- }
38376
- let addresses;
38377
- try {
38378
- addresses = await withTimeout2(
38379
- (options.lookup ?? defaultLookup)(hostname3),
38380
- options.timeoutMs ?? 5e3
38381
- );
38382
- } catch {
38383
- throw guardError(url2);
38384
- }
38385
- if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
38386
- throw guardError(url2);
38387
- }
38388
- }
38389
- function createPublicFetch(options) {
38390
- const lookupFn = options.lookup ?? defaultLookup;
38391
- return (async (input2, init) => {
38392
- const url2 = new URL(input2 instanceof Request ? input2.url : input2);
38393
- await assertPublicUrl(url2, {
38394
- allowPrivateNetwork: options.allowPrivateNetwork,
38395
- lookup: lookupFn,
38396
- timeoutMs: 5e3
38397
- });
38398
- const normalized = new Request(input2, init);
38399
- const bytes = normalized.body ? Buffer.from(await normalized.arrayBuffer()) : null;
38400
- return await new Promise((resolve, reject) => {
38401
- const requestOptions = {
38402
- method: normalized.method,
38403
- headers: Object.fromEntries(normalized.headers),
38404
- signal: normalized.signal,
38405
- ...options.allowPrivateNetwork ? {} : { lookup: pinnedLookup(lookupFn) }
38406
- };
38407
- const onResponse = (incoming) => {
38408
- try {
38409
- const headers = new Headers();
38410
- for (const [name, value] of Object.entries(incoming.headers)) {
38411
- if (Array.isArray(value)) {
38412
- for (const item of value) headers.append(name, item);
38413
- } else if (value !== void 0) {
38414
- headers.set(name, value);
38415
- }
38416
- }
38417
- const status = incoming.statusCode ?? 500;
38418
- const bodyForbidden = normalized.method === "HEAD" || [204, 205, 304].includes(status);
38419
- if (bodyForbidden) incoming.resume();
38420
- const response = new Response(
38421
- bodyForbidden ? null : Readable.toWeb(incoming),
38422
- { status, statusText: incoming.statusMessage, headers }
38423
- );
38424
- Object.defineProperty(response, "url", { value: url2.toString() });
38425
- resolve(response);
38426
- } catch (error61) {
38427
- incoming.destroy();
38428
- reject(error61);
38429
- }
38430
- };
38431
- const request = url2.protocol === "https:" ? httpsRequest(url2, requestOptions, onResponse) : httpRequest(url2, requestOptions, onResponse);
38432
- request.on("error", reject);
38433
- if (bytes) request.write(bytes);
38434
- request.end();
38435
- });
38436
- });
38437
- }
38438
- function pinnedLookup(lookup) {
38439
- return (hostname3, dnsOptions, callback) => {
38440
- void lookup(normalizeHostname(hostname3)).then((addresses) => {
38441
- if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
38442
- callback(guardError(new URL(`https://${hostname3}`)), "");
38443
- return;
38444
- }
38445
- const address4 = addresses[0];
38446
- const family = isIP(address4);
38447
- callback(
38448
- null,
38449
- dnsOptions.all ? [{ address: address4, family }] : address4,
38450
- dnsOptions.all ? void 0 : family
38451
- );
38452
- }).catch(
38453
- (error61) => callback(error61 instanceof Error ? error61 : new Error("DNS lookup failed."), "")
38454
- );
38455
- };
38456
- }
38457
- async function withTimeout2(operation, timeoutMs) {
38458
- let timeout;
38459
- try {
38460
- return await Promise.race([
38461
- operation,
38462
- new Promise((_resolve, reject) => {
38463
- timeout = setTimeout(() => reject(new Error("DNS lookup timed out.")), timeoutMs);
38464
- })
38465
- ]);
38466
- } finally {
38467
- if (timeout) clearTimeout(timeout);
38468
- }
38469
- }
38470
- function normalizeHostname(hostname3) {
38471
- const unbracketed = hostname3.startsWith("[") && hostname3.endsWith("]") ? hostname3.slice(1, -1) : hostname3;
38472
- return unbracketed.endsWith(".") ? unbracketed.slice(0, -1) : unbracketed;
38473
- }
38474
- function isNonPublicAddress(address4) {
38475
- const normalized = normalizeHostname(address4);
38476
- const version5 = isIP(normalized);
38477
- if (version5 === 4) {
38478
- return isNonPublicIpv4(parseIpv4(normalized));
38479
- }
38480
- if (version5 === 6) {
38481
- return isNonPublicIpv6(parseIpv6(normalized));
38482
- }
38483
- return true;
38484
- }
38485
- function parseIpv4(address4) {
38486
- const octets = address4.split(".").map(Number);
38487
- return [octets[0], octets[1], octets[2], octets[3]];
38488
- }
38489
- function isNonPublicIpv4([first, second, third]) {
38490
- 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;
38491
- }
38492
- function parseIpv6(address4) {
38493
- let normalized = address4.toLowerCase();
38494
- const lastColon = normalized.lastIndexOf(":");
38495
- const dottedTail = normalized.slice(lastColon + 1);
38496
- if (dottedTail.includes(".")) {
38497
- const [first, second, third, fourth] = parseIpv4(dottedTail);
38498
- normalized = `${normalized.slice(0, lastColon + 1)}${(first << 8 | second).toString(16)}:${(third << 8 | fourth).toString(16)}`;
38499
- }
38500
- const halves = normalized.split("::");
38501
- const left = halves[0] ? halves[0].split(":").map(parseHex) : [];
38502
- const right = halves[1] ? halves[1].split(":").map(parseHex) : [];
38503
- const omittedCount = 8 - left.length - right.length;
38504
- return halves.length === 2 ? [...left, ...Array.from({ length: omittedCount }, () => 0), ...right] : left;
38505
- }
38506
- function parseHex(value) {
38507
- return Number.parseInt(value, 16);
38508
- }
38509
- function isNonPublicIpv6(hextets) {
38510
- if (hextets.slice(0, 5).every((hextet) => hextet === 0) && hextets[5] === 65535) {
38511
- const embeddedIpv4 = [
38512
- hextets[6] >> 8,
38513
- hextets[6] & 255,
38514
- hextets[7] >> 8,
38515
- hextets[7] & 255
38516
- ];
38517
- return isNonPublicIpv4(embeddedIpv4);
38518
- }
38519
- if (hextets.slice(0, 6).every((hextet) => hextet === 0)) {
38520
- const compatibleIpv4 = [
38521
- hextets[6] >> 8,
38522
- hextets[6] & 255,
38523
- hextets[7] >> 8,
38524
- hextets[7] & 255
38525
- ];
38526
- if (isNonPublicIpv4(compatibleIpv4)) return true;
38527
- }
38528
- const isUnspecified = hextets.every((hextet) => hextet === 0);
38529
- const isLoopback = hextets.slice(0, 7).every((hextet) => hextet === 0) && hextets[7] === 1;
38530
- const first = hextets[0];
38531
- const isUniqueLocal = first >= 64512 && first <= 65023;
38532
- const isLinkLocal = first >= 65152 && first <= 65215;
38533
- const isSiteLocal = first >= 65216 && first <= 65279;
38534
- const isMulticast = first >= 65280;
38535
- const isDocumentation = first === 8193 && hextets[1] === 3512;
38536
- return isUnspecified || isLoopback || isUniqueLocal || isLinkLocal || isSiteLocal || isMulticast || isDocumentation;
38537
- }
38538
- function guardError(url2) {
38539
- return new Error(
38540
- `URL hostname ${JSON.stringify(url2.hostname)} is not allowed; private or internal destinations require allowPrivateNetwork true in the vAPI config.`
38541
- );
38542
- }
38543
-
38544
- // ../core/src/networks.ts
38545
- var USDC_DECIMALS = 6;
38546
- var NETWORKS = {
38547
- [BASE_MAINNET_CAIP2]: {
38548
- family: "evm",
38549
- chainId: 8453,
38550
- name: "Base mainnet",
38551
- usdc: CANONICAL_X402_USDC_NETWORKS[BASE_MAINNET_CAIP2].usdc,
38552
- gasToken: "ETH",
38553
- rpcEnv: "BASE_RPC_URL",
38554
- publicRpcUrl: "https://mainnet.base.org",
38555
- explorerUrl: "https://basescan.org"
38556
- },
38557
- [ARC_MAINNET_CAIP2]: {
38558
- family: "evm",
38559
- chainId: 5042,
38560
- name: "Arc mainnet",
38561
- usdc: CANONICAL_X402_USDC_NETWORKS[ARC_MAINNET_CAIP2].usdc,
38562
- gasToken: "USDC",
38563
- rpcEnv: "ARC_RPC_URL",
38564
- publicRpcUrl: "https://rpc.mainnet.arc.io",
38565
- explorerUrl: "https://explorer.arc.io"
38566
- },
38567
- [ARC_TESTNET_CAIP2]: {
38568
- family: "evm",
38569
- chainId: 5042002,
38570
- name: "Arc testnet",
38571
- usdc: CANONICAL_X402_USDC_NETWORKS[ARC_TESTNET_CAIP2].usdc,
38572
- gasToken: "USDC",
38573
- rpcEnv: "ARC_TESTNET_RPC_URL"
38574
- },
38575
- [SOLANA_MAINNET_CAIP2]: {
38576
- family: "svm",
38577
- name: "Solana mainnet",
38578
- usdc: SOLANA_MAINNET_USDC,
38579
- gasToken: "SOL",
38580
- rpcEnv: "SOLANA_RPC_URL",
38581
- publicRpcUrl: "https://api.mainnet-beta.solana.com"
38582
- },
38583
- [X402_SOLANA_MAINNET_CAIP2]: {
38584
- family: "svm",
38585
- name: "Solana mainnet",
38586
- usdc: SOLANA_MAINNET_USDC,
38587
- gasToken: "SOL",
38588
- rpcEnv: "SOLANA_RPC_URL",
38589
- publicRpcUrl: "https://api.mainnet-beta.solana.com"
38590
- }
38045
+ var marketplaceBadgeCodeSchema = external_exports.enum([
38046
+ "live_x402",
38047
+ "mpp",
38048
+ "partner",
38049
+ "payout_wallet_confirmed",
38050
+ "vapi_verified",
38051
+ "external_catalog",
38052
+ "approved_vendor",
38053
+ "unverified"
38054
+ ]);
38055
+ var marketplaceBadgeSchema = external_exports.looseObject({
38056
+ code: marketplaceBadgeCodeSchema,
38057
+ label: external_exports.string().trim().min(1).max(80)
38058
+ });
38059
+ var marketplacePublicFactSchema = external_exports.looseObject({
38060
+ label: external_exports.string().trim().min(1).max(80),
38061
+ value: external_exports.string().trim().min(1).max(160)
38062
+ });
38063
+ var marketplaceHrefSchema = external_exports.union([
38064
+ external_exports.string().trim().min(1).max(2048).regex(/^\/(?!\/)/),
38065
+ external_exports.url().max(2048).regex(/^https:\/\//)
38066
+ ]);
38067
+ var marketplaceCardSchema = external_exports.looseObject({
38068
+ title: external_exports.string().trim().min(1).max(160),
38069
+ summary: external_exports.string().trim().min(1).max(1e3),
38070
+ byline: external_exports.string().trim().min(1).max(160).optional(),
38071
+ bylineHref: marketplaceHrefSchema.optional(),
38072
+ badges: external_exports.preprocess(
38073
+ (badges) => Array.isArray(badges) ? badges.flatMap((badge) => {
38074
+ const parsed = marketplaceBadgeSchema.safeParse(badge);
38075
+ return parsed.success ? [parsed.data] : [];
38076
+ }) : badges,
38077
+ external_exports.array(marketplaceBadgeSchema).max(8)
38078
+ ),
38079
+ facts: external_exports.array(marketplacePublicFactSchema).max(12)
38080
+ });
38081
+ var marketplaceHitBase = {
38082
+ ref: external_exports.string().trim().min(1).max(512),
38083
+ card: marketplaceCardSchema,
38084
+ ...listingDisclosureShape
38591
38085
  };
38592
- function parseEip155ChainId(network) {
38593
- const match = /^eip155:(\d+)$/.exec(network);
38594
- if (!match) {
38595
- throw new Error(`Unsupported network ${network}; expected eip155:<chainId>.`);
38596
- }
38597
- const chainId = Number(match[1]);
38598
- if (!Number.isSafeInteger(chainId) || chainId <= 0) {
38599
- throw new Error(`Invalid EVM chain ID in network ${network}.`);
38600
- }
38601
- return chainId;
38602
- }
38603
- function isSolanaNetwork(network) {
38604
- return network === SOLANA_MAINNET_CAIP2 || network === X402_SOLANA_MAINNET_CAIP2;
38605
- }
38606
- function usesUsdcGas(network) {
38607
- try {
38608
- return getNetworkDefinition(network).gasToken === "USDC";
38609
- } catch {
38610
- return false;
38611
- }
38612
- }
38613
- function explorerTransactionUrl(network, hash5) {
38614
- try {
38615
- const explorerUrl = getNetworkDefinition(network).explorerUrl;
38616
- return explorerUrl ? `${explorerUrl}/tx/${hash5}` : void 0;
38617
- } catch {
38618
- return void 0;
38619
- }
38620
- }
38621
- function explorerAddressUrl(network, address4) {
38622
- try {
38623
- const explorerUrl = getNetworkDefinition(network).explorerUrl;
38624
- return explorerUrl ? `${explorerUrl}/address/${address4}` : void 0;
38625
- } catch {
38626
- return void 0;
38627
- }
38628
- }
38629
- function areSamePaymentNetwork(left, right) {
38630
- return left === right || isSolanaNetwork(left) && isSolanaNetwork(right);
38631
- }
38632
- function isSupportedPaymentNetwork(network) {
38633
- if (isSolanaNetwork(network)) return true;
38634
- try {
38635
- parseEip155ChainId(network);
38636
- return true;
38637
- } catch {
38638
- return false;
38639
- }
38640
- }
38641
- function configuredNetworkFor(networks, network) {
38642
- const configured = networks[network];
38643
- if (configured) return configured;
38644
- if (network === X402_SOLANA_MAINNET_CAIP2) return networks[SOLANA_MAINNET_CAIP2];
38645
- if (network === SOLANA_MAINNET_CAIP2) return networks[X402_SOLANA_MAINNET_CAIP2];
38646
- return void 0;
38647
- }
38648
- function getNetworkDefinition(network) {
38649
- const known = NETWORKS[network];
38650
- if (known) {
38651
- return known;
38652
- }
38653
- const chainId = parseEip155ChainId(network);
38654
- return {
38655
- family: "evm",
38656
- chainId,
38657
- name: network,
38658
- usdc: getAddress("0x0000000000000000000000000000000000000000"),
38659
- gasToken: "ETH",
38660
- rpcEnv: ""
38661
- };
38662
- }
38663
- function requireRpcUrl(network, configured) {
38664
- const definition = getNetworkDefinition(network);
38665
- const envUrl = definition.rpcEnv ? process.env[definition.rpcEnv]?.trim() : void 0;
38666
- const rpcUrl = envUrl || configured.rpcUrl.trim();
38667
- if (rpcUrl) {
38668
- return rpcUrl;
38669
- }
38670
- if (network === ARC_TESTNET_CAIP2) {
38671
- throw new Error(
38672
- "Arc testnet RPC is required. Set ARC_TESTNET_RPC_URL or add rpcUrl for eip155:5042002 in config.json."
38673
- );
38674
- }
38675
- throw new Error(`RPC URL is required for ${network}.`);
38676
- }
38677
- function createChain(network, rpcUrl) {
38678
- const definition = getNetworkDefinition(network);
38679
- if (definition.family !== "evm" || definition.chainId === void 0) {
38680
- throw new Error(`Network ${network} is not an EVM chain.`);
38086
+ var invokeApiActionSchema = external_exports.looseObject({
38087
+ type: external_exports.literal("invoke_api"),
38088
+ href: marketplaceHrefSchema
38089
+ });
38090
+ var firstPartyApiMarketplaceHitSchema = external_exports.looseObject({
38091
+ ...marketplaceHitBase,
38092
+ kind: external_exports.literal("api"),
38093
+ provenance: firstPartyProvenanceSchema,
38094
+ execution: external_exports.looseObject({
38095
+ mode: executionModeSchema
38096
+ }),
38097
+ action: invokeApiActionSchema
38098
+ });
38099
+ var mirroredApiMarketplaceHitSchema = external_exports.looseObject({
38100
+ ...marketplaceHitBase,
38101
+ kind: external_exports.literal("api"),
38102
+ provenance: external_exports.literal("indexed"),
38103
+ execution: external_exports.looseObject({
38104
+ mode: external_exports.literal("direct"),
38105
+ url: external_exports.url().max(2048).regex(/^https:\/\/(?![^/?#]*@)/),
38106
+ method: marketplaceExecutionMethodSchema.nullable(),
38107
+ network: external_exports.string().trim().max(160).transform((network) => {
38108
+ if (network === "solana") return X402_SOLANA_MAINNET_CAIP2;
38109
+ if (network === "solana-devnet") return SOLANA_DEVNET_CAIP2;
38110
+ return network;
38111
+ }).pipe(
38112
+ external_exports.union([
38113
+ external_exports.string().regex(/^[-a-z0-9]{3,8}:[-_a-zA-Z0-9]{1,32}$/),
38114
+ // Persisted mainnet configs also use the full genesis hash.
38115
+ external_exports.literal(SOLANA_MAINNET_CAIP2)
38116
+ ])
38117
+ )
38118
+ }),
38119
+ action: invokeApiActionSchema
38120
+ });
38121
+ var apiMarketplaceHitSchema = external_exports.discriminatedUnion("provenance", [
38122
+ firstPartyApiMarketplaceHitSchema,
38123
+ mirroredApiMarketplaceHitSchema
38124
+ ]);
38125
+ var serviceOfferMarketplaceHitSchema = external_exports.looseObject({
38126
+ ...marketplaceHitBase,
38127
+ kind: external_exports.literal("service_offer"),
38128
+ action: external_exports.looseObject({
38129
+ type: external_exports.literal("start_engagement"),
38130
+ href: marketplaceHrefSchema
38131
+ })
38132
+ });
38133
+ var openRequestMarketplaceHitSchema = external_exports.looseObject({
38134
+ ...marketplaceHitBase,
38135
+ kind: external_exports.literal("open_request"),
38136
+ action: external_exports.looseObject({
38137
+ type: external_exports.literal("propose_to_request"),
38138
+ href: marketplaceHrefSchema
38139
+ })
38140
+ });
38141
+ var marketplaceHitSchema = external_exports.union([
38142
+ apiMarketplaceHitSchema,
38143
+ serviceOfferMarketplaceHitSchema,
38144
+ openRequestMarketplaceHitSchema
38145
+ ]);
38146
+ var marketplaceDiscoveryInputSchema = external_exports.strictObject({
38147
+ q: external_exports.string().trim().max(200).optional(),
38148
+ kinds: external_exports.array(marketplaceKindSchema).min(1).max(MARKETPLACE_KINDS.length).optional(),
38149
+ network: external_exports.string().trim().min(1).max(160).optional(),
38150
+ cursor: external_exports.string().trim().min(1).max(4096).optional(),
38151
+ limit: external_exports.number().int().min(1).max(50).optional(),
38152
+ includeUnverified: external_exports.boolean().optional()
38153
+ }).superRefine((input2, context) => {
38154
+ if (input2.kinds && new Set(input2.kinds).size !== input2.kinds.length) {
38155
+ context.addIssue({
38156
+ code: "custom",
38157
+ path: ["kinds"],
38158
+ message: "Marketplace kinds must be unique"
38159
+ });
38681
38160
  }
38682
- return defineChain({
38683
- id: definition.chainId,
38684
- name: definition.name,
38685
- nativeCurrency: definition.gasToken === "USDC" ? { name: "USDC", symbol: "USDC", decimals: USDC_DECIMALS } : { name: "Ether", symbol: "ETH", decimals: 18 },
38686
- rpcUrls: {
38687
- default: { http: [rpcUrl] }
38688
- },
38689
- ...definition.explorerUrl ? {
38690
- blockExplorers: {
38691
- default: { name: `${definition.name} explorer`, url: definition.explorerUrl }
38692
- }
38693
- } : {}
38694
- });
38695
- }
38696
- function createNetworkPublicClient(network, configured, options = {}) {
38697
- const rpcUrl = requireRpcUrl(network, configured);
38698
- return createPublicClient({
38699
- chain: createChain(network, rpcUrl),
38700
- transport: createNetworkHttpTransport(rpcUrl, options)
38701
- });
38702
- }
38703
- function createNetworkHttpTransport(rpcUrl, options = {}) {
38704
- const fetchFn = options.fetch ?? createPublicFetch({
38705
- allowPrivateNetwork: options.allowPrivateNetwork ?? false,
38706
- ...options.lookup ? { lookup: options.lookup } : {}
38707
- });
38708
- return http(rpcUrl, { fetchFn, fetchOptions: { redirect: "manual" } });
38709
- }
38710
- function formatUsdc(amountAtomic2) {
38711
- return formatUnits(amountAtomic2, USDC_DECIMALS);
38161
+ });
38162
+ function isMirroredHit(hit) {
38163
+ return hit.kind === "api" && hit.provenance === "indexed";
38712
38164
  }
38165
+ var marketplaceDiscoveryEnvelopeSchema = external_exports.looseObject({
38166
+ protocol: external_exports.literal(MARKETPLACE_DISCOVERY_PROTOCOL),
38167
+ items: external_exports.array(external_exports.unknown()),
38168
+ nextCursor: external_exports.string().min(1).max(4096).nullable(),
38169
+ unavailableKinds: external_exports.array(marketplaceKindSchema).max(MARKETPLACE_KINDS.length),
38170
+ rankingVersion: external_exports.literal(MARKETPLACE_RANKING_VERSION)
38171
+ });
38172
+ var marketplaceDiscoveryPageSchema = marketplaceDiscoveryEnvelopeSchema.extend({
38173
+ items: external_exports.array(marketplaceHitSchema)
38174
+ });
38713
38175
 
38714
38176
  // ../../node_modules/.pnpm/@solana+errors@5.5.1_typescript@6.0.3/node_modules/@solana/errors/dist/index.node.mjs
38715
38177
  var SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;
@@ -43329,16 +42791,16 @@ var DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;
43329
42791
  var DEFAULT_COMPUTE_UNIT_LIMIT = 2e4;
43330
42792
  var MAX_MEMO_BYTES = 256;
43331
42793
  var SOLANA_MAINNET_CAIP22 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
43332
- var SOLANA_DEVNET_CAIP2 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
42794
+ var SOLANA_DEVNET_CAIP22 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
43333
42795
  var SOLANA_TESTNET_CAIP2 = "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";
43334
42796
  var V1_TO_V2_NETWORK_MAP = {
43335
42797
  solana: SOLANA_MAINNET_CAIP22,
43336
- "solana-devnet": SOLANA_DEVNET_CAIP2,
42798
+ "solana-devnet": SOLANA_DEVNET_CAIP22,
43337
42799
  "solana-testnet": SOLANA_TESTNET_CAIP2
43338
42800
  };
43339
42801
  function normalizeNetwork(network) {
43340
42802
  if (network.includes(":")) {
43341
- const supported = [SOLANA_MAINNET_CAIP22, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];
42803
+ const supported = [SOLANA_MAINNET_CAIP22, SOLANA_DEVNET_CAIP22, SOLANA_TESTNET_CAIP2];
43342
42804
  if (!supported.includes(network)) {
43343
42805
  throw new Error(`Unsupported SVM network: ${network}`);
43344
42806
  }
@@ -43386,7 +42848,7 @@ var DEFAULT_ASSETS = {
43386
42848
  tokenProgram: TOKEN_2022_PROGRAM_ADDRESS2
43387
42849
  }
43388
42850
  ],
43389
- [SOLANA_DEVNET_CAIP2]: [
42851
+ [SOLANA_DEVNET_CAIP22]: [
43390
42852
  {
43391
42853
  asset: USDC_DEVNET_ADDRESS,
43392
42854
  decimals: 6,
@@ -43441,7 +42903,7 @@ var findDefaultAsset = (asset, network) => {
43441
42903
  function createRpcClient(network, customRpcUrl) {
43442
42904
  const caip2Network = normalizeNetwork(network);
43443
42905
  switch (caip2Network) {
43444
- case SOLANA_DEVNET_CAIP2: {
42906
+ case SOLANA_DEVNET_CAIP22: {
43445
42907
  const url2 = customRpcUrl || DEVNET_RPC_URL;
43446
42908
  return createSolanaRpc(devnet(url2));
43447
42909
  }
@@ -43639,6 +43101,375 @@ var ExactSvmScheme = class {
43639
43101
  var addressEncoder = getAddressEncoder();
43640
43102
  var compiledMessageDecoder = getCompiledTransactionMessageDecoder();
43641
43103
 
43104
+ // ../core/src/net-guard.ts
43105
+ import { lookup as dnsLookup } from "node:dns/promises";
43106
+ import { request as httpRequest } from "node:http";
43107
+ import { request as httpsRequest } from "node:https";
43108
+ import { isIP } from "node:net";
43109
+ import { Readable } from "node:stream";
43110
+ var defaultLookup = async (hostname3) => {
43111
+ const addresses = await dnsLookup(hostname3, { all: true });
43112
+ return addresses.map(({ address: address4 }) => address4);
43113
+ };
43114
+ async function assertPublicUrl(url2, options) {
43115
+ if (url2.username || url2.password) {
43116
+ throw guardError(url2);
43117
+ }
43118
+ if (url2.protocol !== "http:" && url2.protocol !== "https:") {
43119
+ throw guardError(url2);
43120
+ }
43121
+ if (options.allowPrivateNetwork) {
43122
+ return;
43123
+ }
43124
+ const hostname3 = normalizeHostname(url2.hostname);
43125
+ const lowercaseHostname = hostname3.toLowerCase();
43126
+ if (!lowercaseHostname || lowercaseHostname === "localhost" || lowercaseHostname.endsWith(".localhost") || lowercaseHostname.endsWith(".local") || lowercaseHostname.endsWith(".internal")) {
43127
+ throw guardError(url2);
43128
+ }
43129
+ if (isIP(hostname3)) {
43130
+ if (isNonPublicAddress(hostname3)) {
43131
+ throw guardError(url2);
43132
+ }
43133
+ return;
43134
+ }
43135
+ let addresses;
43136
+ try {
43137
+ addresses = await withTimeout2(
43138
+ (options.lookup ?? defaultLookup)(hostname3),
43139
+ options.timeoutMs ?? 5e3
43140
+ );
43141
+ } catch {
43142
+ throw guardError(url2);
43143
+ }
43144
+ if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
43145
+ throw guardError(url2);
43146
+ }
43147
+ }
43148
+ function createPublicFetch(options) {
43149
+ const lookupFn = options.lookup ?? defaultLookup;
43150
+ return (async (input2, init) => {
43151
+ const url2 = new URL(input2 instanceof Request ? input2.url : input2);
43152
+ await assertPublicUrl(url2, {
43153
+ allowPrivateNetwork: options.allowPrivateNetwork,
43154
+ lookup: lookupFn,
43155
+ timeoutMs: 5e3
43156
+ });
43157
+ const normalized = new Request(input2, init);
43158
+ const bytes = normalized.body ? Buffer.from(await normalized.arrayBuffer()) : null;
43159
+ return await new Promise((resolve, reject) => {
43160
+ const requestOptions = {
43161
+ method: normalized.method,
43162
+ headers: Object.fromEntries(normalized.headers),
43163
+ signal: normalized.signal,
43164
+ ...options.allowPrivateNetwork ? {} : { lookup: pinnedLookup(lookupFn) }
43165
+ };
43166
+ const onResponse = (incoming) => {
43167
+ try {
43168
+ const headers = new Headers();
43169
+ for (const [name, value] of Object.entries(incoming.headers)) {
43170
+ if (Array.isArray(value)) {
43171
+ for (const item of value) headers.append(name, item);
43172
+ } else if (value !== void 0) {
43173
+ headers.set(name, value);
43174
+ }
43175
+ }
43176
+ const status = incoming.statusCode ?? 500;
43177
+ const bodyForbidden = normalized.method === "HEAD" || [204, 205, 304].includes(status);
43178
+ if (bodyForbidden) incoming.resume();
43179
+ const response = new Response(
43180
+ bodyForbidden ? null : Readable.toWeb(incoming),
43181
+ { status, statusText: incoming.statusMessage, headers }
43182
+ );
43183
+ Object.defineProperty(response, "url", { value: url2.toString() });
43184
+ resolve(response);
43185
+ } catch (error61) {
43186
+ incoming.destroy();
43187
+ reject(error61);
43188
+ }
43189
+ };
43190
+ const request = url2.protocol === "https:" ? httpsRequest(url2, requestOptions, onResponse) : httpRequest(url2, requestOptions, onResponse);
43191
+ request.on("error", reject);
43192
+ if (bytes) request.write(bytes);
43193
+ request.end();
43194
+ });
43195
+ });
43196
+ }
43197
+ function pinnedLookup(lookup) {
43198
+ return (hostname3, dnsOptions, callback) => {
43199
+ void lookup(normalizeHostname(hostname3)).then((addresses) => {
43200
+ if (addresses.length === 0 || addresses.some(isNonPublicAddress)) {
43201
+ callback(guardError(new URL(`https://${hostname3}`)), "");
43202
+ return;
43203
+ }
43204
+ const address4 = addresses[0];
43205
+ const family = isIP(address4);
43206
+ callback(
43207
+ null,
43208
+ dnsOptions.all ? [{ address: address4, family }] : address4,
43209
+ dnsOptions.all ? void 0 : family
43210
+ );
43211
+ }).catch(
43212
+ (error61) => callback(error61 instanceof Error ? error61 : new Error("DNS lookup failed."), "")
43213
+ );
43214
+ };
43215
+ }
43216
+ async function withTimeout2(operation, timeoutMs) {
43217
+ let timeout;
43218
+ try {
43219
+ return await Promise.race([
43220
+ operation,
43221
+ new Promise((_resolve, reject) => {
43222
+ timeout = setTimeout(() => reject(new Error("DNS lookup timed out.")), timeoutMs);
43223
+ })
43224
+ ]);
43225
+ } finally {
43226
+ if (timeout) clearTimeout(timeout);
43227
+ }
43228
+ }
43229
+ function normalizeHostname(hostname3) {
43230
+ const unbracketed = hostname3.startsWith("[") && hostname3.endsWith("]") ? hostname3.slice(1, -1) : hostname3;
43231
+ return unbracketed.endsWith(".") ? unbracketed.slice(0, -1) : unbracketed;
43232
+ }
43233
+ function isNonPublicAddress(address4) {
43234
+ const normalized = normalizeHostname(address4);
43235
+ const version5 = isIP(normalized);
43236
+ if (version5 === 4) {
43237
+ return isNonPublicIpv4(parseIpv4(normalized));
43238
+ }
43239
+ if (version5 === 6) {
43240
+ return isNonPublicIpv6(parseIpv6(normalized));
43241
+ }
43242
+ return true;
43243
+ }
43244
+ function parseIpv4(address4) {
43245
+ const octets = address4.split(".").map(Number);
43246
+ return [octets[0], octets[1], octets[2], octets[3]];
43247
+ }
43248
+ function isNonPublicIpv4([first, second, third]) {
43249
+ 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;
43250
+ }
43251
+ function parseIpv6(address4) {
43252
+ let normalized = address4.toLowerCase();
43253
+ const lastColon = normalized.lastIndexOf(":");
43254
+ const dottedTail = normalized.slice(lastColon + 1);
43255
+ if (dottedTail.includes(".")) {
43256
+ const [first, second, third, fourth] = parseIpv4(dottedTail);
43257
+ normalized = `${normalized.slice(0, lastColon + 1)}${(first << 8 | second).toString(16)}:${(third << 8 | fourth).toString(16)}`;
43258
+ }
43259
+ const halves = normalized.split("::");
43260
+ const left = halves[0] ? halves[0].split(":").map(parseHex) : [];
43261
+ const right = halves[1] ? halves[1].split(":").map(parseHex) : [];
43262
+ const omittedCount = 8 - left.length - right.length;
43263
+ return halves.length === 2 ? [...left, ...Array.from({ length: omittedCount }, () => 0), ...right] : left;
43264
+ }
43265
+ function parseHex(value) {
43266
+ return Number.parseInt(value, 16);
43267
+ }
43268
+ function isNonPublicIpv6(hextets) {
43269
+ if (hextets.slice(0, 5).every((hextet) => hextet === 0) && hextets[5] === 65535) {
43270
+ const embeddedIpv4 = [
43271
+ hextets[6] >> 8,
43272
+ hextets[6] & 255,
43273
+ hextets[7] >> 8,
43274
+ hextets[7] & 255
43275
+ ];
43276
+ return isNonPublicIpv4(embeddedIpv4);
43277
+ }
43278
+ if (hextets.slice(0, 6).every((hextet) => hextet === 0)) {
43279
+ const compatibleIpv4 = [
43280
+ hextets[6] >> 8,
43281
+ hextets[6] & 255,
43282
+ hextets[7] >> 8,
43283
+ hextets[7] & 255
43284
+ ];
43285
+ if (isNonPublicIpv4(compatibleIpv4)) return true;
43286
+ }
43287
+ const isUnspecified = hextets.every((hextet) => hextet === 0);
43288
+ const isLoopback = hextets.slice(0, 7).every((hextet) => hextet === 0) && hextets[7] === 1;
43289
+ const first = hextets[0];
43290
+ const isUniqueLocal = first >= 64512 && first <= 65023;
43291
+ const isLinkLocal = first >= 65152 && first <= 65215;
43292
+ const isSiteLocal = first >= 65216 && first <= 65279;
43293
+ const isMulticast = first >= 65280;
43294
+ const isDocumentation = first === 8193 && hextets[1] === 3512;
43295
+ return isUnspecified || isLoopback || isUniqueLocal || isLinkLocal || isSiteLocal || isMulticast || isDocumentation;
43296
+ }
43297
+ function guardError(url2) {
43298
+ return new Error(
43299
+ `URL hostname ${JSON.stringify(url2.hostname)} is not allowed; private or internal destinations require allowPrivateNetwork true in the vAPI config.`
43300
+ );
43301
+ }
43302
+
43303
+ // ../core/src/networks.ts
43304
+ var USDC_DECIMALS = 6;
43305
+ var NETWORKS2 = {
43306
+ [BASE_MAINNET_CAIP2]: {
43307
+ family: "evm",
43308
+ chainId: 8453,
43309
+ name: "Base mainnet",
43310
+ usdc: CANONICAL_X402_USDC_NETWORKS[BASE_MAINNET_CAIP2].usdc,
43311
+ gasToken: "ETH",
43312
+ rpcEnv: "BASE_RPC_URL",
43313
+ publicRpcUrl: "https://mainnet.base.org",
43314
+ explorerUrl: "https://basescan.org"
43315
+ },
43316
+ [ARC_MAINNET_CAIP2]: {
43317
+ family: "evm",
43318
+ chainId: 5042,
43319
+ name: "Arc mainnet",
43320
+ usdc: CANONICAL_X402_USDC_NETWORKS[ARC_MAINNET_CAIP2].usdc,
43321
+ gasToken: "USDC",
43322
+ rpcEnv: "ARC_RPC_URL",
43323
+ publicRpcUrl: "https://rpc.mainnet.arc.io",
43324
+ explorerUrl: "https://explorer.arc.io"
43325
+ },
43326
+ [ARC_TESTNET_CAIP2]: {
43327
+ family: "evm",
43328
+ chainId: 5042002,
43329
+ name: "Arc testnet",
43330
+ usdc: CANONICAL_X402_USDC_NETWORKS[ARC_TESTNET_CAIP2].usdc,
43331
+ gasToken: "USDC",
43332
+ rpcEnv: "ARC_TESTNET_RPC_URL"
43333
+ },
43334
+ [SOLANA_MAINNET_CAIP2]: {
43335
+ family: "svm",
43336
+ name: "Solana mainnet",
43337
+ usdc: SOLANA_MAINNET_USDC,
43338
+ gasToken: "SOL",
43339
+ rpcEnv: "SOLANA_RPC_URL",
43340
+ publicRpcUrl: "https://api.mainnet-beta.solana.com"
43341
+ },
43342
+ [X402_SOLANA_MAINNET_CAIP2]: {
43343
+ family: "svm",
43344
+ name: "Solana mainnet",
43345
+ usdc: SOLANA_MAINNET_USDC,
43346
+ gasToken: "SOL",
43347
+ rpcEnv: "SOLANA_RPC_URL",
43348
+ publicRpcUrl: "https://api.mainnet-beta.solana.com"
43349
+ }
43350
+ };
43351
+ function parseEip155ChainId(network) {
43352
+ const match = /^eip155:(\d+)$/.exec(network);
43353
+ if (!match) {
43354
+ throw new Error(`Unsupported network ${network}; expected eip155:<chainId>.`);
43355
+ }
43356
+ const chainId = Number(match[1]);
43357
+ if (!Number.isSafeInteger(chainId) || chainId <= 0) {
43358
+ throw new Error(`Invalid EVM chain ID in network ${network}.`);
43359
+ }
43360
+ return chainId;
43361
+ }
43362
+ function isSolanaNetwork(network) {
43363
+ return network === SOLANA_MAINNET_CAIP2 || network === X402_SOLANA_MAINNET_CAIP2;
43364
+ }
43365
+ function usesUsdcGas(network) {
43366
+ try {
43367
+ return getNetworkDefinition(network).gasToken === "USDC";
43368
+ } catch {
43369
+ return false;
43370
+ }
43371
+ }
43372
+ function explorerTransactionUrl(network, hash5) {
43373
+ try {
43374
+ const explorerUrl = getNetworkDefinition(network).explorerUrl;
43375
+ return explorerUrl ? `${explorerUrl}/tx/${hash5}` : void 0;
43376
+ } catch {
43377
+ return void 0;
43378
+ }
43379
+ }
43380
+ function explorerAddressUrl(network, address4) {
43381
+ try {
43382
+ const explorerUrl = getNetworkDefinition(network).explorerUrl;
43383
+ return explorerUrl ? `${explorerUrl}/address/${address4}` : void 0;
43384
+ } catch {
43385
+ return void 0;
43386
+ }
43387
+ }
43388
+ function areSamePaymentNetwork(left, right) {
43389
+ return left === right || isSolanaNetwork(left) && isSolanaNetwork(right);
43390
+ }
43391
+ function isSupportedPaymentNetwork(network) {
43392
+ if (isSolanaNetwork(network)) return true;
43393
+ try {
43394
+ parseEip155ChainId(network);
43395
+ return true;
43396
+ } catch {
43397
+ return false;
43398
+ }
43399
+ }
43400
+ function configuredNetworkFor(networks, network) {
43401
+ const configured = networks[network];
43402
+ if (configured) return configured;
43403
+ if (network === X402_SOLANA_MAINNET_CAIP2) return networks[SOLANA_MAINNET_CAIP2];
43404
+ if (network === SOLANA_MAINNET_CAIP2) return networks[X402_SOLANA_MAINNET_CAIP2];
43405
+ return void 0;
43406
+ }
43407
+ function getNetworkDefinition(network) {
43408
+ const known = NETWORKS2[network];
43409
+ if (known) {
43410
+ return known;
43411
+ }
43412
+ const chainId = parseEip155ChainId(network);
43413
+ return {
43414
+ family: "evm",
43415
+ chainId,
43416
+ name: network,
43417
+ usdc: getAddress("0x0000000000000000000000000000000000000000"),
43418
+ gasToken: "ETH",
43419
+ rpcEnv: ""
43420
+ };
43421
+ }
43422
+ function requireRpcUrl(network, configured) {
43423
+ const definition = getNetworkDefinition(network);
43424
+ const envUrl = definition.rpcEnv ? process.env[definition.rpcEnv]?.trim() : void 0;
43425
+ const rpcUrl = envUrl || configured.rpcUrl.trim();
43426
+ if (rpcUrl) {
43427
+ return rpcUrl;
43428
+ }
43429
+ if (network === ARC_TESTNET_CAIP2) {
43430
+ throw new Error(
43431
+ "Arc testnet RPC is required. Set ARC_TESTNET_RPC_URL or add rpcUrl for eip155:5042002 in config.json."
43432
+ );
43433
+ }
43434
+ throw new Error(`RPC URL is required for ${network}.`);
43435
+ }
43436
+ function createChain(network, rpcUrl) {
43437
+ const definition = getNetworkDefinition(network);
43438
+ if (definition.family !== "evm" || definition.chainId === void 0) {
43439
+ throw new Error(`Network ${network} is not an EVM chain.`);
43440
+ }
43441
+ return defineChain({
43442
+ id: definition.chainId,
43443
+ name: definition.name,
43444
+ nativeCurrency: definition.gasToken === "USDC" ? { name: "USDC", symbol: "USDC", decimals: USDC_DECIMALS } : { name: "Ether", symbol: "ETH", decimals: 18 },
43445
+ rpcUrls: {
43446
+ default: { http: [rpcUrl] }
43447
+ },
43448
+ ...definition.explorerUrl ? {
43449
+ blockExplorers: {
43450
+ default: { name: `${definition.name} explorer`, url: definition.explorerUrl }
43451
+ }
43452
+ } : {}
43453
+ });
43454
+ }
43455
+ function createNetworkPublicClient(network, configured, options = {}) {
43456
+ const rpcUrl = requireRpcUrl(network, configured);
43457
+ return createPublicClient({
43458
+ chain: createChain(network, rpcUrl),
43459
+ transport: createNetworkHttpTransport(rpcUrl, options)
43460
+ });
43461
+ }
43462
+ function createNetworkHttpTransport(rpcUrl, options = {}) {
43463
+ const fetchFn = options.fetch ?? createPublicFetch({
43464
+ allowPrivateNetwork: options.allowPrivateNetwork ?? false,
43465
+ ...options.lookup ? { lookup: options.lookup } : {}
43466
+ });
43467
+ return http(rpcUrl, { fetchFn, fetchOptions: { redirect: "manual" } });
43468
+ }
43469
+ function formatUsdc(amountAtomic2) {
43470
+ return formatUnits(amountAtomic2, USDC_DECIMALS);
43471
+ }
43472
+
43642
43473
  // ../core/src/x402.ts
43643
43474
  var MAX_CHALLENGE_BYTES = 1048576;
43644
43475
  var MAX_UINT256 = (1n << 256n) - 1n;
@@ -44396,6 +44227,242 @@ function isRecord2(value) {
44396
44227
  return typeof value === "object" && value !== null && !Array.isArray(value);
44397
44228
  }
44398
44229
 
44230
+ // ../core/src/call-contracts-wire.ts
44231
+ var CALLABLE_CATEGORIES = ["ai", "data", "crypto", "compute", "search"];
44232
+ var callableCategorySchema = external_exports.enum(CALLABLE_CATEGORIES);
44233
+ var DISCOVERY_CATEGORIES = [...CALLABLE_CATEGORIES, "other"];
44234
+ var discoveryCategorySchema = external_exports.string().trim().min(1);
44235
+ var CALLABLE_CATEGORY_SET = new Set(CALLABLE_CATEGORIES);
44236
+ var serviceTierSchema = external_exports.string().trim().min(1);
44237
+ var discoveryEndpointSchema = external_exports.looseObject({
44238
+ name: external_exports.string(),
44239
+ method: external_exports.string(),
44240
+ url: external_exports.url(),
44241
+ price: external_exports.string(),
44242
+ description: external_exports.string(),
44243
+ operationId: external_exports.string().trim().min(1).optional(),
44244
+ requestContentType: external_exports.string().trim().min(1).optional(),
44245
+ requestSchema: external_exports.json().optional(),
44246
+ responseContentType: external_exports.string().trim().min(1).optional(),
44247
+ pathTemplate: external_exports.string().trim().min(1).optional(),
44248
+ pathParameters: external_exports.array(external_exports.string().trim().min(1)).optional(),
44249
+ payment: external_exports.union([
44250
+ external_exports.looseObject({
44251
+ scheme: external_exports.literal("exact"),
44252
+ network: external_exports.string().regex(/^eip155:\d+$/),
44253
+ asset: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
44254
+ payTo: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/),
44255
+ checkedAt: external_exports.iso.datetime()
44256
+ }),
44257
+ external_exports.looseObject({
44258
+ scheme: external_exports.literal("exact"),
44259
+ network: external_exports.union([
44260
+ external_exports.string().regex(/^solana:[-_a-zA-Z0-9]{1,32}$/),
44261
+ external_exports.literal(SOLANA_MAINNET_CAIP2)
44262
+ ]),
44263
+ asset: external_exports.string().refine(isSolanaAddress, "Expected a Solana base58 address."),
44264
+ payTo: external_exports.string().refine(isSolanaAddress, "Expected a Solana base58 address."),
44265
+ checkedAt: external_exports.iso.datetime()
44266
+ }),
44267
+ external_exports.looseObject({
44268
+ protocol: external_exports.literal("mpp"),
44269
+ intent: external_exports.enum(["charge", "authorize", "subscription"]).nullable(),
44270
+ method: external_exports.string().trim().min(1).max(40).nullable(),
44271
+ checkedAt: external_exports.iso.datetime(),
44272
+ // Keep common x402 properties readable on the union while making it
44273
+ // impossible for MPP metadata to masquerade as executable x402 terms.
44274
+ network: external_exports.never().optional(),
44275
+ payTo: external_exports.never().optional()
44276
+ }),
44277
+ external_exports.looseObject({
44278
+ // Future payment protocols remain visible to callers so the payment
44279
+ // layer can refuse them explicitly instead of discovery losing the row.
44280
+ protocol: external_exports.string().trim().min(1).max(40),
44281
+ checkedAt: external_exports.iso.datetime(),
44282
+ network: external_exports.never().optional(),
44283
+ payTo: external_exports.never().optional()
44284
+ })
44285
+ ]).optional()
44286
+ });
44287
+ var serviceSummarySchema = external_exports.looseObject({
44288
+ id: external_exports.string(),
44289
+ name: external_exports.string(),
44290
+ description: external_exports.string(),
44291
+ category: discoveryCategorySchema,
44292
+ tier: serviceTierSchema,
44293
+ ...listingDisclosureShape,
44294
+ verified: external_exports.boolean(),
44295
+ wrapped: external_exports.boolean(),
44296
+ price: external_exports.string(),
44297
+ networks: external_exports.array(external_exports.string()),
44298
+ endpoints: external_exports.array(discoveryEndpointSchema)
44299
+ });
44300
+ var searchServicesResponseSchema = external_exports.looseObject({
44301
+ services: external_exports.array(serviceSummarySchema)
44302
+ });
44303
+ var discoveryResponseSchema = searchServicesResponseSchema;
44304
+
44305
+ // ../core/src/call-contracts.ts
44306
+ var DiscoveryCatalogError = class extends Error {
44307
+ constructor(code, message, serviceId, paymentNetworks) {
44308
+ super(message);
44309
+ this.paymentNetworks = paymentNetworks;
44310
+ this.code = code;
44311
+ this.serviceId = serviceId;
44312
+ }
44313
+ paymentNetworks;
44314
+ name = "DiscoveryCatalogError";
44315
+ code;
44316
+ serviceId;
44317
+ };
44318
+ function isDiscoveryCatalogError(error61) {
44319
+ if (!(error61 instanceof Error) || error61.name !== "DiscoveryCatalogError" || !("code" in error61) || typeof error61.code !== "string") {
44320
+ return false;
44321
+ }
44322
+ const networks = Reflect.get(error61, "paymentNetworks");
44323
+ return networks === void 0 || Array.isArray(networks) && networks.every((network) => typeof network === "string");
44324
+ }
44325
+ function parseDiscovery(raw) {
44326
+ const parsed = discoveryResponseSchema.safeParse(raw);
44327
+ if (!parsed.success) {
44328
+ const malformedUrl = parsed.error.issues.find(
44329
+ (issue2) => issue2.path.at(-1) === "url" && issue2.path.includes("endpoints")
44330
+ );
44331
+ if (malformedUrl) {
44332
+ const serviceIndex = pathIndexAfter(malformedUrl.path, "services");
44333
+ const serviceId = rawServiceId(raw, serviceIndex);
44334
+ throw new DiscoveryCatalogError(
44335
+ "malformed_url",
44336
+ `Service ${JSON.stringify(serviceId ?? "unknown")} has a malformed endpoint URL.`,
44337
+ serviceId
44338
+ );
44339
+ }
44340
+ throw new DiscoveryCatalogError("invalid_discovery", "Discovery response is malformed.");
44341
+ }
44342
+ for (const service of parsed.data.services) {
44343
+ buildTargets(service);
44344
+ }
44345
+ const resolveListing = (serviceId, endpointName) => {
44346
+ const service = parsed.data.services.find((candidate) => candidate.id === serviceId);
44347
+ if (!service) {
44348
+ throw new DiscoveryCatalogError(
44349
+ "service_not_found",
44350
+ `No payable endpoint found for service ${JSON.stringify(serviceId)}.`,
44351
+ serviceId
44352
+ );
44353
+ }
44354
+ return { service, endpoint: resolveTarget(service, endpointName) };
44355
+ };
44356
+ return {
44357
+ services: parsed.data.services,
44358
+ resolve: (serviceId, endpointName) => resolveListing(serviceId, endpointName).endpoint,
44359
+ resolveListing
44360
+ };
44361
+ }
44362
+ function resolveTarget(service, endpointName) {
44363
+ const { targets, targetsByName } = buildTargets(service);
44364
+ if (endpointName !== void 0) {
44365
+ const selected = targetsByName.get(endpointName.trim());
44366
+ if (!selected) {
44367
+ throw new DiscoveryCatalogError(
44368
+ "endpoint_not_found",
44369
+ `Service ${JSON.stringify(service.id)} has no endpoint ${JSON.stringify(endpointName)}. Available endpoints: ${[...targetsByName.keys()].join(", ")}.`,
44370
+ service.id
44371
+ );
44372
+ }
44373
+ return { ...selected };
44374
+ }
44375
+ if (targets.size !== 1) {
44376
+ const paymentNetworks = service.endpoints.flatMap(
44377
+ (endpoint) => typeof endpoint.payment?.network === "string" ? [endpoint.payment.network] : []
44378
+ );
44379
+ throw new DiscoveryCatalogError(
44380
+ "ambiguous_default",
44381
+ `Service ${JSON.stringify(service.id)} has ${targets.size} distinct payable endpoints. Choose one with endpoint: ${[...targetsByName.keys()].join(", ")}.`,
44382
+ service.id,
44383
+ paymentNetworks.length === service.endpoints.length ? paymentNetworks : void 0
44384
+ );
44385
+ }
44386
+ return targets.values().next().value;
44387
+ }
44388
+ function buildTargets(service) {
44389
+ if (service.endpoints.length === 0) {
44390
+ throw new DiscoveryCatalogError(
44391
+ "no_endpoint",
44392
+ `Service ${JSON.stringify(service.id)} has no payable endpoint.`,
44393
+ service.id
44394
+ );
44395
+ }
44396
+ const namedEndpoints = [...service.endpoints].sort(
44397
+ (left, right) => compareNames(left.name.trim(), right.name.trim())
44398
+ );
44399
+ const names = /* @__PURE__ */ new Set();
44400
+ const targets = /* @__PURE__ */ new Map();
44401
+ const targetsByName = /* @__PURE__ */ new Map();
44402
+ for (const endpoint of namedEndpoints) {
44403
+ const name = endpoint.name.trim();
44404
+ if (!name) {
44405
+ throw new DiscoveryCatalogError(
44406
+ "invalid_endpoint_name",
44407
+ `Service ${JSON.stringify(service.id)} has a blank endpoint name.`,
44408
+ service.id
44409
+ );
44410
+ }
44411
+ if (names.has(name)) {
44412
+ throw new DiscoveryCatalogError(
44413
+ "duplicate_endpoint_name",
44414
+ `Service ${JSON.stringify(service.id)} has duplicate endpoint name ${JSON.stringify(name)}.`,
44415
+ service.id
44416
+ );
44417
+ }
44418
+ names.add(name);
44419
+ const method = endpoint.method.trim().toUpperCase();
44420
+ if (!method) {
44421
+ throw new DiscoveryCatalogError(
44422
+ "blank_method",
44423
+ `Service ${JSON.stringify(service.id)} has a blank endpoint method.`,
44424
+ service.id
44425
+ );
44426
+ }
44427
+ const url2 = new URL(endpoint.url);
44428
+ if (url2.protocol !== "http:" && url2.protocol !== "https:") {
44429
+ throw new DiscoveryCatalogError(
44430
+ "malformed_url",
44431
+ `Service ${JSON.stringify(service.id)} has a non-HTTP endpoint URL.`,
44432
+ service.id
44433
+ );
44434
+ }
44435
+ const transportKey = `${method}\0${endpoint.url}`;
44436
+ const normalized = { ...endpoint, name, method };
44437
+ targetsByName.set(name, normalized);
44438
+ if (!targets.has(transportKey)) targets.set(transportKey, normalized);
44439
+ }
44440
+ return { targets, targetsByName };
44441
+ }
44442
+ function compareNames(left, right) {
44443
+ return left < right ? -1 : left > right ? 1 : 0;
44444
+ }
44445
+ function pathIndexAfter(path, key2) {
44446
+ const keyIndex = path.indexOf(key2);
44447
+ const candidate = path[keyIndex + 1];
44448
+ return typeof candidate === "number" ? candidate : void 0;
44449
+ }
44450
+ function rawServiceId(raw, serviceIndex) {
44451
+ if (serviceIndex === void 0 || typeof raw !== "object" || raw === null) {
44452
+ return void 0;
44453
+ }
44454
+ const services = Reflect.get(raw, "services");
44455
+ if (!Array.isArray(services)) {
44456
+ return void 0;
44457
+ }
44458
+ const service = services[serviceIndex];
44459
+ if (typeof service !== "object" || service === null) {
44460
+ return void 0;
44461
+ }
44462
+ const id2 = Reflect.get(service, "id");
44463
+ return typeof id2 === "string" ? id2 : void 0;
44464
+ }
44465
+
44399
44466
  // ../core/src/sweep.ts
44400
44467
  var ERC20_ABI = [
44401
44468
  {
@@ -45110,7 +45177,7 @@ var configSchema = external_exports.object({
45110
45177
  }
45111
45178
  for (const [network, configured] of Object.entries(config2.networks)) {
45112
45179
  if (isSolanaNetwork(network)) {
45113
- if (configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
45180
+ if (configured.usdc !== NETWORKS2[SOLANA_MAINNET_CAIP2].usdc) {
45114
45181
  context.addIssue({
45115
45182
  code: "custom",
45116
45183
  path: ["networks", network, "usdc"],
@@ -45121,7 +45188,7 @@ var configSchema = external_exports.object({
45121
45188
  }
45122
45189
  try {
45123
45190
  const usdc = getAddress(configured.usdc);
45124
- if ((network === ARC_MAINNET_CAIP2 || network === ARC_TESTNET_CAIP2) && usdc !== getAddress(NETWORKS[network].usdc)) {
45191
+ if ((network === ARC_MAINNET_CAIP2 || network === ARC_TESTNET_CAIP2) && usdc !== getAddress(NETWORKS2[network].usdc)) {
45125
45192
  context.addIssue({
45126
45193
  code: "custom",
45127
45194
  path: ["networks", network, "usdc"],
@@ -45148,7 +45215,8 @@ function getVapiPaths(directory = process.env.VAPI_HOME?.trim() || join2(homedir
45148
45215
  keystore: join2(directory, "keystore.json"),
45149
45216
  receipts: join2(directory, "receipts.jsonl"),
45150
45217
  searches: join2(directory, "searches.jsonl"),
45151
- ledger: join2(directory, "spend-ledger.json")
45218
+ ledger: join2(directory, "spend-ledger.json"),
45219
+ updateCheck: join2(directory, "update-check.json")
45152
45220
  };
45153
45221
  }
45154
45222
  var getAgentCashPaths = getVapiPaths;
@@ -45260,15 +45328,15 @@ function getDefaultConfig(source = process.env, options = {}) {
45260
45328
  const tasksEscrowFactoryOverrides = tasksFactoryOverridesFromEnv(source);
45261
45329
  if (requested.has("base") || requested.has(BASE_MAINNET_CAIP2)) {
45262
45330
  networks[BASE_MAINNET_CAIP2] = {
45263
- rpcUrl: source.BASE_RPC_URL?.trim() || NETWORKS[BASE_MAINNET_CAIP2].publicRpcUrl,
45264
- usdc: NETWORKS[BASE_MAINNET_CAIP2].usdc
45331
+ rpcUrl: source.BASE_RPC_URL?.trim() || NETWORKS2[BASE_MAINNET_CAIP2].publicRpcUrl,
45332
+ usdc: NETWORKS2[BASE_MAINNET_CAIP2].usdc
45265
45333
  };
45266
45334
  }
45267
45335
  const arcMainnetRpcUrl = source.ARC_RPC_URL?.trim();
45268
45336
  if (arcMainnetRpcUrl || requested.has("arc") || requested.has(ARC_MAINNET_CAIP2)) {
45269
45337
  networks[ARC_MAINNET_CAIP2] = {
45270
- rpcUrl: arcMainnetRpcUrl || NETWORKS[ARC_MAINNET_CAIP2].publicRpcUrl,
45271
- usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc
45338
+ rpcUrl: arcMainnetRpcUrl || NETWORKS2[ARC_MAINNET_CAIP2].publicRpcUrl,
45339
+ usdc: NETWORKS2[ARC_MAINNET_CAIP2].usdc
45272
45340
  };
45273
45341
  }
45274
45342
  const arcTestnetRpcUrl = source.ARC_TESTNET_RPC_URL?.trim();
@@ -45280,14 +45348,14 @@ function getDefaultConfig(source = process.env, options = {}) {
45280
45348
  }
45281
45349
  networks[ARC_TESTNET_CAIP2] = {
45282
45350
  rpcUrl: arcTestnetRpcUrl,
45283
- usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc
45351
+ usdc: NETWORKS2[ARC_TESTNET_CAIP2].usdc
45284
45352
  };
45285
45353
  }
45286
45354
  const solanaRpcUrl = source.SOLANA_RPC_URL?.trim();
45287
45355
  if (solanaRpcUrl || requested.has("solana") || requested.has(SOLANA_MAINNET_CAIP2)) {
45288
45356
  networks[SOLANA_MAINNET_CAIP2] = {
45289
- rpcUrl: solanaRpcUrl || NETWORKS[SOLANA_MAINNET_CAIP2].publicRpcUrl,
45290
- usdc: NETWORKS[SOLANA_MAINNET_CAIP2].usdc
45357
+ rpcUrl: solanaRpcUrl || NETWORKS2[SOLANA_MAINNET_CAIP2].publicRpcUrl,
45358
+ usdc: NETWORKS2[SOLANA_MAINNET_CAIP2].usdc
45291
45359
  };
45292
45360
  }
45293
45361
  return {
@@ -45345,21 +45413,21 @@ Run vapi init to write the new URLs to ${path}.`
45345
45413
  if (arcMainnetRpcUrl) {
45346
45414
  const existing = config2.networks[ARC_MAINNET_CAIP2];
45347
45415
  config2.networks[ARC_MAINNET_CAIP2] = {
45348
- ...existing ?? { usdc: NETWORKS[ARC_MAINNET_CAIP2].usdc },
45416
+ ...existing ?? { usdc: NETWORKS2[ARC_MAINNET_CAIP2].usdc },
45349
45417
  rpcUrl: arcMainnetRpcUrl
45350
45418
  };
45351
45419
  }
45352
45420
  if (arcTestnetRpcUrl) {
45353
45421
  const existing = config2.networks[ARC_TESTNET_CAIP2];
45354
45422
  config2.networks[ARC_TESTNET_CAIP2] = {
45355
- ...existing ?? { usdc: NETWORKS[ARC_TESTNET_CAIP2].usdc },
45423
+ ...existing ?? { usdc: NETWORKS2[ARC_TESTNET_CAIP2].usdc },
45356
45424
  rpcUrl: arcTestnetRpcUrl
45357
45425
  };
45358
45426
  }
45359
45427
  if (solanaRpcUrl) {
45360
45428
  config2.networks[SOLANA_MAINNET_CAIP2] = {
45361
45429
  rpcUrl: solanaRpcUrl,
45362
- usdc: config2.networks[SOLANA_MAINNET_CAIP2]?.usdc ?? NETWORKS[SOLANA_MAINNET_CAIP2].usdc
45430
+ usdc: config2.networks[SOLANA_MAINNET_CAIP2]?.usdc ?? NETWORKS2[SOLANA_MAINNET_CAIP2].usdc
45363
45431
  };
45364
45432
  }
45365
45433
  if (registryUrl) {
@@ -45372,7 +45440,7 @@ Run vapi init to write the new URLs to ${path}.`
45372
45440
  for (const [network, configured] of Object.entries(config2.networks)) {
45373
45441
  configured.rpcUrl = configured.rpcUrl.trim();
45374
45442
  configured.usdc = configured.usdc.trim();
45375
- if (isSolanaNetwork(network) && configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
45443
+ if (isSolanaNetwork(network) && configured.usdc !== NETWORKS2[SOLANA_MAINNET_CAIP2].usdc) {
45376
45444
  throw new Error(`Network ${network} must use canonical Solana mainnet USDC.`);
45377
45445
  }
45378
45446
  if (!configured.rpcUrl) delete config2.networks[network];
@@ -72999,7 +73067,7 @@ function createRunBudget(args) {
72999
73067
  import { mkdir as mkdir13, writeFile as writeFile7 } from "node:fs/promises";
73000
73068
  import { arch, platform, release } from "node:os";
73001
73069
  import { join as join11 } from "node:path";
73002
- var VAPI_CLIENT_VERSION = "0.9.0";
73070
+ var VAPI_CLIENT_VERSION = "0.9.4";
73003
73071
  async function createSupportReport(options) {
73004
73072
  const message = options.message.trim();
73005
73073
  if (!message) throw new Error("Support report message must not be empty.");
@@ -73272,7 +73340,7 @@ async function completeX402Payment(args) {
73272
73340
  let paidAttempt;
73273
73341
  const requestStarted = nowMs();
73274
73342
  try {
73275
- paidAttempt = await args.send(paidRequest);
73343
+ paidAttempt = await args.send(paidRequest, quote);
73276
73344
  } catch (error61) {
73277
73345
  if (trace) trace.phases.requestMs = elapsed(nowMs, requestStarted);
73278
73346
  throw settlementUnknown(
@@ -73290,7 +73358,7 @@ async function completeX402Payment(args) {
73290
73358
  const settleStarted = nowMs();
73291
73359
  const settlement = parseSettlementResponse(paidResponse.headers);
73292
73360
  const settlementOutcome = classifySettlement(settlement);
73293
- const receiptSettlement = sanitizeReceiptValue(settlement, receiptSecrets);
73361
+ const receiptSettlement = sanitizeReturnedValue(settlement, receiptSecrets);
73294
73362
  if (trace) {
73295
73363
  const transaction2 = settlementTransaction(receiptSettlement);
73296
73364
  const explorerUrl = transaction2 ? explorerTransactionUrl(quote.accepted.network, transaction2) : void 0;
@@ -73367,6 +73435,7 @@ async function completeX402Payment(args) {
73367
73435
  trace.phases.requestMs = (trace.phases.requestMs ?? 0) + elapsed(nowMs, bodyStarted);
73368
73436
  }
73369
73437
  }
73438
+ body = sanitizeReturnedValue(body, receiptSecrets);
73370
73439
  }
73371
73440
  const result = {
73372
73441
  response: paidResponse,
@@ -73375,7 +73444,11 @@ async function completeX402Payment(args) {
73375
73444
  quote,
73376
73445
  payer,
73377
73446
  ...payment.paymentId ? { paymentId: payment.paymentId } : {},
73378
- settlement,
73447
+ paymentProof: sanitizeReturnedValue(
73448
+ paidResponse.headers.get("x-vapi-payment-proof"),
73449
+ receiptSecrets
73450
+ ),
73451
+ settlement: receiptSettlement,
73379
73452
  settlementOutcome
73380
73453
  };
73381
73454
  if (settlementOutcome === "succeeded" && args.ceilingSweep) {
@@ -73512,19 +73585,70 @@ function sanitizeThrownError(error61, secrets) {
73512
73585
  }
73513
73586
  return new Error(message, cause === void 0 ? void 0 : { cause });
73514
73587
  }
73515
- function sanitizeReceiptValue(value, secrets, depth = 0) {
73588
+ function sanitizeReturnedValue(value, secrets) {
73516
73589
  if (typeof value === "string") return redactKnownSecrets(value, secrets);
73517
- if (value === null || typeof value !== "object") return value;
73518
- if (depth >= 16) return "[redacted nested settlement value]";
73519
- if (Array.isArray(value)) {
73520
- return value.map((item) => sanitizeReceiptValue(item, secrets, depth + 1));
73590
+ if (!isPlainReturnedContainer(value)) return value;
73591
+ const nodes = /* @__PURE__ */ new WeakMap();
73592
+ const ordered = [];
73593
+ const nodeFor = (source) => {
73594
+ const existing = nodes.get(source);
73595
+ if (existing) return existing;
73596
+ const copy = Array.isArray(source) ? new Array(source.length) : Object.create(Object.getPrototypeOf(source));
73597
+ const node2 = { source, copy, parents: /* @__PURE__ */ new Set(), changed: false };
73598
+ nodes.set(source, node2);
73599
+ ordered.push(node2);
73600
+ return node2;
73601
+ };
73602
+ const root = nodeFor(value);
73603
+ for (let index2 = 0; index2 < ordered.length; index2 += 1) {
73604
+ const node2 = ordered[index2];
73605
+ for (const [key2, item] of Object.entries(node2.source)) {
73606
+ const safeKey = Array.isArray(node2.source) ? key2 : redactKnownSecrets(key2, secrets);
73607
+ if (safeKey !== key2) node2.changed = true;
73608
+ if (typeof item === "string") {
73609
+ const safeItem = redactKnownSecrets(item, secrets);
73610
+ defineReturnedProperty(node2.copy, safeKey, safeItem);
73611
+ if (safeItem !== item) node2.changed = true;
73612
+ } else if (isPlainReturnedContainer(item)) {
73613
+ const child = nodeFor(item);
73614
+ child.parents.add(node2);
73615
+ defineReturnedProperty(node2.copy, safeKey, child.copy);
73616
+ } else {
73617
+ defineReturnedProperty(node2.copy, safeKey, item);
73618
+ }
73619
+ }
73521
73620
  }
73522
- return Object.fromEntries(
73523
- Object.entries(value).map(([key2, item]) => [
73524
- redactKnownSecrets(key2, secrets),
73525
- sanitizeReceiptValue(item, secrets, depth + 1)
73526
- ])
73527
- );
73621
+ const changed = ordered.filter((node2) => node2.changed);
73622
+ for (let index2 = 0; index2 < changed.length; index2 += 1) {
73623
+ for (const parent of changed[index2].parents) {
73624
+ if (parent.changed) continue;
73625
+ parent.changed = true;
73626
+ changed.push(parent);
73627
+ }
73628
+ }
73629
+ for (const node2 of ordered) {
73630
+ for (const [key2, item] of Object.entries(node2.source)) {
73631
+ if (!isPlainReturnedContainer(item)) continue;
73632
+ const safeKey = Array.isArray(node2.source) ? key2 : redactKnownSecrets(key2, secrets);
73633
+ const child = nodes.get(item);
73634
+ defineReturnedProperty(node2.copy, safeKey, child.changed ? child.copy : item);
73635
+ }
73636
+ }
73637
+ return root.changed ? root.copy : value;
73638
+ }
73639
+ function defineReturnedProperty(target, key2, value) {
73640
+ Object.defineProperty(target, key2, {
73641
+ value,
73642
+ enumerable: true,
73643
+ configurable: true,
73644
+ writable: true
73645
+ });
73646
+ }
73647
+ function isPlainReturnedContainer(value) {
73648
+ if (Array.isArray(value)) return true;
73649
+ if (value === null || typeof value !== "object") return false;
73650
+ const prototype = Object.getPrototypeOf(value);
73651
+ return prototype === Object.prototype || prototype === null;
73528
73652
  }
73529
73653
  function redactKnownSecrets(value, secrets) {
73530
73654
  let redacted = value;
@@ -73559,9 +73683,7 @@ function possibleSettlement(quote, payment, payer, receipt) {
73559
73683
  payTo: quote.accepted.payTo,
73560
73684
  payer,
73561
73685
  ...payment.paymentId ? { paymentId: payment.paymentId } : {},
73562
- ...isSvmPaymentRequirements(quote.accepted) ? {
73563
- authorizationTransaction: "transaction" in payment.payload.payload ? payment.payload.payload.transaction : ""
73564
- } : "authorization" in payment.payload.payload ? {
73686
+ ...isSvmPaymentRequirements(quote.accepted) ? {} : "authorization" in payment.payload.payload ? {
73565
73687
  authorizationNonce: payment.payload.payload.authorization.nonce,
73566
73688
  authorizationExpiresAt: payment.payload.payload.authorization.validBefore
73567
73689
  } : {},
@@ -73939,13 +74061,22 @@ async function sendRouterChat(deps, routerBaseUrl, routerKey, request, keyUsed)
73939
74061
  }
73940
74062
  const body = await responseText(response);
73941
74063
  if (!response.ok) {
73942
- if (response.status === 429 || body.includes("Budget has been exceeded") || body.includes("ExceededBudget")) {
74064
+ if (/budget (?:has been )?exceeded|exceededbudget/iu.test(body)) {
73943
74065
  throw new RouterClientError(
73944
74066
  "budget_exhausted",
73945
74067
  "The Router key has no remaining budget.",
73946
74068
  response.status
73947
74069
  );
73948
74070
  }
74071
+ if (response.status === 429) {
74072
+ const retryAfter = response.headers.get("retry-after")?.trim();
74073
+ const retrySeconds = retryAfter !== void 0 && /^\d+$/u.test(retryAfter) ? Number(retryAfter) : void 0;
74074
+ throw new RouterClientError(
74075
+ "rate_limited",
74076
+ `The vAPI Router is rate limited. ${retrySeconds !== void 0 && Number.isFinite(retrySeconds) ? `Retry after ${retrySeconds} seconds.` : "Wait and retry shortly."}`,
74077
+ response.status
74078
+ );
74079
+ }
73949
74080
  if (response.status === 401) {
73950
74081
  throw new RouterClientError(
73951
74082
  "no_router_key",
@@ -74448,6 +74579,7 @@ var missingTasksChain = {
74448
74579
 
74449
74580
  // ../core/src/tasks/types.ts
74450
74581
  var uuidSchema = external_exports.uuid();
74582
+ var profileIdSchema = external_exports.string().min(1).max(64).regex(/^[A-Za-z0-9_-]+$/);
74451
74583
  var isoDateTimeSchema = external_exports.iso.datetime();
74452
74584
  var addressSchema5 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/).transform((value) => value.toLowerCase());
74453
74585
  var bytes32Schema = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform((value) => value.toLowerCase());
@@ -74785,7 +74917,7 @@ var deliveryResponseSchema = external_exports.looseObject({
74785
74917
  version: external_exports.number().int().positive(),
74786
74918
  manifest: manifestResponseSchema,
74787
74919
  manifestHash: bytes32Schema,
74788
- submittedByProfileId: uuidSchema,
74920
+ submittedByProfileId: profileIdSchema,
74789
74921
  createdAt: isoDateTimeSchema
74790
74922
  });
74791
74923
  var orderDeliveryResponseSchema = external_exports.looseObject({
@@ -74891,7 +75023,7 @@ var reviewResponseSchema = external_exports.looseObject({
74891
75023
  id: uuidSchema,
74892
75024
  workOrderId: uuidSchema,
74893
75025
  clientAddress: addressSchema5,
74894
- vendorProfileId: uuidSchema,
75026
+ vendorProfileId: profileIdSchema,
74895
75027
  rating: external_exports.number().int().min(1).max(5),
74896
75028
  body: external_exports.string(),
74897
75029
  subRatings: external_exports.json().nullable(),
@@ -75434,12 +75566,15 @@ function createTasksClient(options) {
75434
75566
  const parsed2 = serverErrorSchema.safeParse(errorBody);
75435
75567
  const server = parsed2.success ? parsed2.data : void 0;
75436
75568
  const nested = typeof server?.error === "object" ? server.error : void 0;
75437
- const message = (typeof server?.error === "string" ? server.error : nested?.message) || server?.message || response.statusText || `HTTP ${response.status}`;
75569
+ const serverCode = nested?.code ?? server?.code;
75570
+ const serverMessage = (typeof server?.error === "string" ? server.error : nested?.message) || server?.message;
75571
+ const fallback = response.statusText || `HTTP ${response.status}`;
75572
+ 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);
75438
75573
  throw new TasksClientError(
75439
75574
  "http",
75440
75575
  message,
75441
75576
  response.status,
75442
- nested?.code ?? server?.code,
75577
+ serverCode,
75443
75578
  response.headers.get("Retry-After") ?? void 0
75444
75579
  );
75445
75580
  }
@@ -75842,9 +75977,10 @@ function safeTasksChainError(cause, broadcast, authorizationExposed, txHash) {
75842
75977
  let message = "Task chain operation failed.";
75843
75978
  if (cause instanceof TasksValidationError || cause instanceof TasksChainError)
75844
75979
  message = cause.message;
75845
- else if (cause instanceof TasksClientError)
75846
- message = `Tasks service request failed${cause.status === void 0 ? "" : ` (status ${cause.status})`}.`;
75847
- else if (cause instanceof Error) {
75980
+ else if (cause instanceof TasksClientError) {
75981
+ const code = cause.serverCode ?? (cause.status ? `http_${cause.status}` : cause.code);
75982
+ message = cause.status === 401 || cause.status === 403 ? `${code} (status ${cause.status})` : `${code}: ${cause.message}`;
75983
+ } else if (cause instanceof Error) {
75848
75984
  const short = "shortMessage" in cause && typeof cause.shortMessage === "string" ? cause.shortMessage : void 0;
75849
75985
  let statusCode;
75850
75986
  const seen = /* @__PURE__ */ new Set();
@@ -76630,6 +76766,44 @@ function createTasksChain(options) {
76630
76766
  return idempotencyKey;
76631
76767
  });
76632
76768
  }
76769
+ async function prepareOrResume(prepare, expected, idempotencyKey, kind, steps, authorizationExposed = false, beforeSign) {
76770
+ let prepared;
76771
+ let resumedFromServer = false;
76772
+ try {
76773
+ prepared = await prepare();
76774
+ } catch (error61) {
76775
+ if (!uncertainPreparation(error61)) throw error61;
76776
+ const fresh = await order(expected.milestone.workOrderId);
76777
+ const matches = fresh.milestones.filter((item) => item.id === expected.milestone.id);
76778
+ if (matches.length !== 1 || matches[0].workOrderId !== fresh.id)
76779
+ throw new TasksValidationError("The task milestone does not match its parent order.");
76780
+ const selected = matches[0];
76781
+ const operation = selected.chainOperation;
76782
+ if (expected.verb === "deliver" && selected.delivery && !operation)
76783
+ throw new TasksValidationError(
76784
+ "The server recorded this delivery but has no chain operation for it; open the task in the console to continue."
76785
+ );
76786
+ if (!operation || operation.kind !== kind || !(typeof steps === "string" ? [steps] : steps).includes(operation.step) || !["prepared", "submitted", "confirmed"].includes(operation.state))
76787
+ throw error61;
76788
+ if (expected.verb === "deliver" && selected.delivery && selected.delivery.manifestHash !== expected.manifestHash)
76789
+ throw new TasksValidationError(
76790
+ "The server recorded a different delivery manifest; refusing to continue."
76791
+ );
76792
+ prepared = {
76793
+ operation,
76794
+ milestone: { id: selected.id, workOrderId: selected.workOrderId }
76795
+ };
76796
+ resumedFromServer = true;
76797
+ }
76798
+ const result = await execute(
76799
+ prepared,
76800
+ expected,
76801
+ idempotencyKey,
76802
+ authorizationExposed,
76803
+ beforeSign
76804
+ );
76805
+ return resumedFromServer ? { ...result, resumedFromServer: true } : result;
76806
+ }
76633
76807
  async function verifyReceipt(operation, expected, hash5) {
76634
76808
  const rpc = rpcFor(expected.deployment.chainId);
76635
76809
  const receipt = await rpc.waitForTransactionReceipt({ hash: hash5, confirmations });
@@ -76671,6 +76845,7 @@ function createTasksChain(options) {
76671
76845
  throw new TasksValidationError(
76672
76846
  "The RPC transaction input does not match the verified task plan."
76673
76847
  );
76848
+ return receipt.blockNumber.toString();
76674
76849
  }
76675
76850
  async function retryConflict(call2) {
76676
76851
  let waited = 0;
@@ -76698,6 +76873,7 @@ function createTasksChain(options) {
76698
76873
  current = { ...initial, operation: live };
76699
76874
  let broadcast = current.operation.state === "submitted";
76700
76875
  let txHash = current.operation.transactionHash ?? void 0;
76876
+ let blockNumber;
76701
76877
  const operationId = initial.operation.id;
76702
76878
  function checkTransition(previous, next) {
76703
76879
  if (previous !== next && !(previous === "approve-usdc" && next === afterApproval))
@@ -76733,7 +76909,7 @@ function createTasksChain(options) {
76733
76909
  if (!operation.transactionHash)
76734
76910
  throw new TasksValidationError("The confirmed task operation has no transaction hash.");
76735
76911
  if (!checkpoint) {
76736
- await verifyReceipt(operation, expected, operation.transactionHash);
76912
+ blockNumber = await verifyReceipt(operation, expected, operation.transactionHash);
76737
76913
  await pending.complete(operation.id, operation.step, current);
76738
76914
  }
76739
76915
  const fresh = await order(expected.milestone.workOrderId);
@@ -76742,7 +76918,12 @@ function createTasksChain(options) {
76742
76918
  );
76743
76919
  if (!resultMilestone)
76744
76920
  throw new TasksValidationError("The reconciled task milestone is unavailable.");
76745
- return { txHash: operation.transactionHash, operation, milestone: resultMilestone };
76921
+ return {
76922
+ txHash: operation.transactionHash,
76923
+ operation,
76924
+ milestone: resultMilestone,
76925
+ blockNumber
76926
+ };
76746
76927
  }
76747
76928
  const rpc = rpcFor(expected.deployment.chainId);
76748
76929
  if (operation.state === "prepared") {
@@ -76938,7 +77119,7 @@ function createTasksChain(options) {
76938
77119
  }
76939
77120
  if (operation.state !== "submitted" || !operation.transactionHash)
76940
77121
  throw new TasksValidationError("The task operation has no submitted transaction.");
76941
- await verifyReceipt(operation, expected, operation.transactionHash);
77122
+ blockNumber = await verifyReceipt(operation, expected, operation.transactionHash);
76942
77123
  const reconciled = await retryConflict(
76943
77124
  () => client.reconcileOperation(
76944
77125
  operation.id,
@@ -76961,6 +77142,7 @@ function createTasksChain(options) {
76961
77142
  if (reconciled.operation.state !== "confirmed" && !(operation.step === "approve-usdc" && reconciled.operation.state === "prepared" && reconciled.operation.step === afterApproval))
76962
77143
  throw new TasksValidationError("The task transaction was not reconciled.");
76963
77144
  await pending.complete(operation.id, operation.step, reconciled);
77145
+ if (reconciled.operation.step !== operation.step) blockNumber = void 0;
76964
77146
  current = reconciled;
76965
77147
  }
76966
77148
  throw new TasksValidationError("The task operation exceeded its allowed step transitions.");
@@ -76995,14 +77177,16 @@ function createTasksChain(options) {
76995
77177
  );
76996
77178
  const prepareKey = await preparation(input2, verb, { evidenceHash: input2.evidenceHash });
76997
77179
  const call2 = verb === "dispute" ? client.disputeEscrow.bind(client) : client.counterEvidenceEscrow.bind(client);
76998
- return await execute(
76999
- await call2(
77180
+ return await prepareOrResume(
77181
+ () => call2(
77000
77182
  input2.escrowId,
77001
77183
  { evidenceHash: input2.evidenceHash },
77002
77184
  { idempotencyKey: prepareKey }
77003
77185
  ),
77004
77186
  { ...expected, evidenceHash: input2.evidenceHash },
77005
77187
  prepareKey,
77188
+ verb === "dispute" ? "escrow-dispute" : "escrow-counter-evidence",
77189
+ expected.steps,
77006
77190
  exposed,
77007
77191
  input2.beforeSign
77008
77192
  );
@@ -77022,11 +77206,34 @@ function createTasksChain(options) {
77022
77206
  await options.bindings.put(binding);
77023
77207
  },
77024
77208
  createEscrow: (input2) => safe(async () => {
77025
- const workOrder = await order(input2.orderId);
77209
+ let workOrder = await order(input2.orderId);
77026
77210
  const ready = await deployment();
77027
- const prepared = await client.createEscrow(input2.orderId, {
77028
- idempotencyKey: input2.idempotencyKey
77029
- });
77211
+ let prepared;
77212
+ let resumedFromServer = false;
77213
+ try {
77214
+ prepared = await client.createEscrow(input2.orderId, {
77215
+ idempotencyKey: input2.idempotencyKey
77216
+ });
77217
+ } catch (error61) {
77218
+ if (!uncertainPreparation(error61)) throw error61;
77219
+ const fresh = await order(input2.orderId);
77220
+ const candidates = fresh.milestones.filter((item) => {
77221
+ const previous = workOrder.milestones.find((prior) => prior.id === item.id);
77222
+ const operation = item.chainOperation;
77223
+ return item.workOrderId === input2.orderId && previous && operation && operation.kind === "escrow-create" && operation.step === "create-escrow" && (previous.escrowState === null || previous.chainOperation?.id === operation.id);
77224
+ });
77225
+ if (candidates.length !== 1) throw error61;
77226
+ const selected2 = candidates[0];
77227
+ prepared = {
77228
+ operation: selected2.chainOperation,
77229
+ milestone: {
77230
+ id: selected2.id,
77231
+ workOrderId: selected2.workOrderId
77232
+ }
77233
+ };
77234
+ workOrder = fresh;
77235
+ resumedFromServer = true;
77236
+ }
77030
77237
  const selected = workOrder.milestones.find((item) => item.id === prepared.milestone.id);
77031
77238
  if (!selected || selected.workOrderId !== input2.orderId)
77032
77239
  throw new TasksValidationError(
@@ -77036,11 +77243,12 @@ function createTasksChain(options) {
77036
77243
  { escrowId: selected.id, idempotencyKey: input2.idempotencyKey },
77037
77244
  "createEscrow"
77038
77245
  );
77039
- return await execute(
77246
+ const result = await execute(
77040
77247
  prepared,
77041
77248
  await expectation(selected, ready, "createEscrow", ["create-escrow"], input2.counterparty),
77042
77249
  prepareKey
77043
77250
  );
77251
+ return resumedFromServer ? { ...result, resumedFromServer: true } : result;
77044
77252
  }),
77045
77253
  async fund(input2) {
77046
77254
  let exposed = true;
@@ -77128,10 +77336,14 @@ function createTasksChain(options) {
77128
77336
  }
77129
77337
  exposed = true;
77130
77338
  await pending.markExposure(selected.id);
77131
- const prepared = await client.fundEscrow(input2.escrowId, body, {
77132
- idempotencyKey: prepareKey
77133
- });
77134
- return await execute(prepared, expected, prepareKey, exposed);
77339
+ return await prepareOrResume(
77340
+ () => client.fundEscrow(input2.escrowId, body, { idempotencyKey: prepareKey }),
77341
+ expected,
77342
+ prepareKey,
77343
+ "escrow-funding",
77344
+ expected.steps,
77345
+ exposed
77346
+ );
77135
77347
  } catch (cause) {
77136
77348
  throw chainError(cause, false, exposed);
77137
77349
  }
@@ -77156,22 +77368,26 @@ function createTasksChain(options) {
77156
77368
  manifest: frozen.manifest,
77157
77369
  note: input2.note
77158
77370
  });
77159
- const prepared = await client.deliverEscrow(
77160
- input2.escrowId,
77161
- { fileIds: frozen.manifest.files.map((file2) => file2.fileId), note: input2.note },
77162
- { idempotencyKey: prepareKey }
77163
- );
77164
- if (prepared.delivery.manifestHash !== frozen.manifestHash)
77165
- throw new TasksValidationError(
77166
- "The server task delivery manifest hash does not match the local manifest."
77167
- );
77168
- return await execute(
77169
- prepared,
77371
+ return await prepareOrResume(
77372
+ async () => {
77373
+ const prepared = await client.deliverEscrow(
77374
+ input2.escrowId,
77375
+ { fileIds: frozen.manifest.files.map((file2) => file2.fileId), note: input2.note },
77376
+ { idempotencyKey: prepareKey }
77377
+ );
77378
+ if (prepared.delivery.manifestHash !== frozen.manifestHash)
77379
+ throw new TasksValidationError(
77380
+ "The server task delivery manifest hash does not match the local manifest."
77381
+ );
77382
+ return prepared;
77383
+ },
77170
77384
  {
77171
77385
  ...expected,
77172
77386
  manifestHash: frozen.manifestHash
77173
77387
  },
77174
- prepareKey
77388
+ prepareKey,
77389
+ "escrow-delivery",
77390
+ "submit-delivery"
77175
77391
  );
77176
77392
  }),
77177
77393
  release: (input2) => safe(async () => {
@@ -77185,10 +77401,12 @@ function createTasksChain(options) {
77185
77401
  input2.counterparty
77186
77402
  );
77187
77403
  const prepareKey = await preparation(input2, "release");
77188
- return await execute(
77189
- await client.releaseEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
77404
+ return await prepareOrResume(
77405
+ () => client.releaseEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
77190
77406
  expected,
77191
- prepareKey
77407
+ prepareKey,
77408
+ "escrow-release",
77409
+ "release-funds"
77192
77410
  );
77193
77411
  }),
77194
77412
  refund: (input2) => safe(async () => {
@@ -77202,10 +77420,12 @@ function createTasksChain(options) {
77202
77420
  input2.counterparty
77203
77421
  );
77204
77422
  const prepareKey = await preparation(input2, "refund");
77205
- return await execute(
77206
- await client.refundEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
77423
+ return await prepareOrResume(
77424
+ () => client.refundEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
77207
77425
  expected,
77208
- prepareKey
77426
+ prepareKey,
77427
+ "escrow-release",
77428
+ "refund-buyer"
77209
77429
  );
77210
77430
  }),
77211
77431
  disputeFee: (input2) => safe(async () => {
@@ -77233,16 +77453,21 @@ function createTasksChain(options) {
77233
77453
  input2.counterparty
77234
77454
  );
77235
77455
  const prepareKey = await preparation(input2, "resolve-unmatched");
77236
- return execute(
77237
- await client.resolveUnmatchedEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
77456
+ return prepareOrResume(
77457
+ () => client.resolveUnmatchedEscrow(input2.escrowId, { idempotencyKey: prepareKey }),
77238
77458
  expected,
77239
- prepareKey
77459
+ prepareKey,
77460
+ "escrow-unmatched-resolution",
77461
+ "resolve-unmatched-dispute"
77240
77462
  );
77241
77463
  }),
77242
77464
  signScopeMessage: (message) => safe(() => account.signMessage({ message }))
77243
77465
  };
77244
77466
  }
77245
77467
  var chainError = safeTasksChainError;
77468
+ function uncertainPreparation(error61) {
77469
+ return error61 instanceof TasksClientError && ((error61.status ?? 0) >= 400 || error61.code === "network" || error61.code === "timeout");
77470
+ }
77246
77471
  function retryDelay(header, now) {
77247
77472
  if (/^\d+(?:\.\d+)?$/u.test(header.trim())) return Math.max(1, Math.ceil(Number(header) * 1e3));
77248
77473
  const date5 = Date.parse(header);
@@ -77259,6 +77484,60 @@ function alreadySent(error61) {
77259
77484
  return error61 instanceof Error && /already known|known transaction|nonce (?:is )?too low/iu.test(error61.message);
77260
77485
  }
77261
77486
 
77487
+ // ../core/src/tasks/wait.ts
77488
+ async function waitForMilestone(client, input2) {
77489
+ const timeoutMs = input2.timeoutMs ?? 12e4;
77490
+ const intervalMs = input2.intervalMs ?? 3e3;
77491
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0)
77492
+ throw new RangeError("The milestone wait timeout must be non-negative and finite.");
77493
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0)
77494
+ throw new RangeError("The milestone wait interval must be positive and finite.");
77495
+ const sleep = input2.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
77496
+ const now = input2.now ?? (() => /* @__PURE__ */ new Date());
77497
+ const started = now().getTime();
77498
+ const deadline = started + timeoutMs;
77499
+ let polls = 0;
77500
+ let milestone;
77501
+ function result(reached) {
77502
+ return { reached, milestone, polls, elapsedMs: now().getTime() - started };
77503
+ }
77504
+ for (; ; ) {
77505
+ const remaining = deadline - now().getTime();
77506
+ if (remaining <= 0) return result(false);
77507
+ const controller = new AbortController();
77508
+ const timer = setTimeout(() => controller.abort(), remaining);
77509
+ let response;
77510
+ polls++;
77511
+ try {
77512
+ response = await client.getOrder(input2.orderId, { signal: controller.signal });
77513
+ } catch (error61) {
77514
+ if (controller.signal.aborted) return result(false);
77515
+ throw error61;
77516
+ } finally {
77517
+ clearTimeout(timer);
77518
+ }
77519
+ if (controller.signal.aborted || now().getTime() >= deadline) return result(false);
77520
+ const { workOrder } = response;
77521
+ milestone = workOrder.id === input2.orderId && workOrder.version === "work-order-view-v1" ? workOrder.milestones.find(
77522
+ (item) => item.id === input2.milestoneId && item.workOrderId === input2.orderId
77523
+ ) : void 0;
77524
+ if (milestone && reachedTarget(milestone, input2.target)) return result(true);
77525
+ await sleep(Math.min(intervalMs, deadline - now().getTime()));
77526
+ }
77527
+ }
77528
+ function reachedTarget(milestone, target) {
77529
+ switch (target) {
77530
+ case "created":
77531
+ return milestone.escrowState !== null;
77532
+ case "locked":
77533
+ return ["locked", "submitted", "disputed", "resolved"].includes(milestone.escrowState ?? "");
77534
+ case "delivered":
77535
+ return ["submitted", "disputed", "resolved"].includes(milestone.escrowState ?? "");
77536
+ case "released":
77537
+ return milestone.escrowState === "resolved";
77538
+ }
77539
+ }
77540
+
77262
77541
  // ../core/src/tasks/rpc.ts
77263
77542
  function createTasksRpcFor(config2, options = {}) {
77264
77543
  const clients = /* @__PURE__ */ new Map();
@@ -78372,7 +78651,10 @@ async function taskRequest(verb, route, operation, options) {
78372
78651
  "not_signed_in",
78373
78652
  `${verb} needs sign-in. ${options.signInHint}`
78374
78653
  );
78375
- throw new TaskOperationError(error61.serverCode ?? error61.code, error61.message);
78654
+ throw new TaskOperationError(
78655
+ error61.serverCode ?? (error61.status ? `http_${error61.status}` : error61.code),
78656
+ error61.message
78657
+ );
78376
78658
  }
78377
78659
  throw error61;
78378
78660
  }
@@ -78493,7 +78775,8 @@ function proposalTerms(id2, address4, deployment, terms) {
78493
78775
  return {
78494
78776
  version: "work-proposal-v1",
78495
78777
  workOrderId: id2,
78496
- providerAddress: address4,
78778
+ // The server lowercases addresses before canonicalizing the signed payload.
78779
+ providerAddress: address4.toLowerCase(),
78497
78780
  pricingModel: "fixed",
78498
78781
  milestones: [
78499
78782
  {
@@ -78880,6 +79163,55 @@ async function showTask(context, input2) {
78880
79163
  };
78881
79164
  }
78882
79165
  async function taskStatus(context, input2) {
79166
+ if (input2.signedIn) {
79167
+ const chainState = await taskRequest(
79168
+ "status",
79169
+ "chainState",
79170
+ async () => {
79171
+ try {
79172
+ return await context.client.chainState(input2.id);
79173
+ } catch (error61) {
79174
+ if (error61 instanceof TasksClientError && error61.status === 404) {
79175
+ if (isMissingTaskEntity(error61.serverCode, error61.message))
79176
+ throw new TaskOperationError("not_found", error61.message);
79177
+ throw new TaskOperationError(
79178
+ "not_available",
79179
+ "GET /v1/work-orders/:id/chain-state is not available on this server."
79180
+ );
79181
+ }
79182
+ throw error61;
79183
+ }
79184
+ },
79185
+ context
79186
+ );
79187
+ if (chainState.workOrderId !== input2.id)
79188
+ throw new TaskOperationError("invalid_response", "The response belongs to a different task.");
79189
+ const page = await taskRequest(
79190
+ "status",
79191
+ "events",
79192
+ async () => {
79193
+ try {
79194
+ return await context.client.events(input2.id, { wait: 0 });
79195
+ } catch (error61) {
79196
+ if (error61 instanceof TasksClientError && error61.status === 404) {
79197
+ if (isMissingTaskEntity(error61.serverCode, error61.message)) return null;
79198
+ throw new TaskOperationError(
79199
+ "not_available",
79200
+ "GET /v1/work-orders/:id/events is not available on this server."
79201
+ );
79202
+ }
79203
+ throw error61;
79204
+ }
79205
+ },
79206
+ context
79207
+ );
79208
+ return {
79209
+ task: { id: input2.id },
79210
+ chainState,
79211
+ events: page ? [...page.events].sort((a, b) => a.sequence - b.sequence) : null,
79212
+ nextAfter: page?.nextAfter ?? null
79213
+ };
79214
+ }
78883
79215
  const task = await taskRequest(
78884
79216
  "status",
78885
79217
  "publicTask",
@@ -79235,6 +79567,7 @@ var searchEventSchema = external_exports.strictObject({
79235
79567
  source: external_exports.string().min(1),
79236
79568
  latencyMs: external_exports.number().nonnegative().finite(),
79237
79569
  count: external_exports.number().int().nonnegative(),
79570
+ dropped: external_exports.number().int().nonnegative().optional(),
79238
79571
  error: external_exports.string().optional()
79239
79572
  })
79240
79573
  ),
@@ -81954,11 +82287,28 @@ async function searchMarketplace(input2, config2, fetchImpl, options = {}) {
81954
82287
  }
81955
82288
  }
81956
82289
  });
81957
- const page = marketplaceDiscoveryPageSchema.parse(await response.json());
81958
- mergedCount = page.items.length;
82290
+ const envelope = marketplaceDiscoveryEnvelopeSchema.parse(await response.json());
82291
+ const items = [];
82292
+ let dropped = 0;
82293
+ for (const [index2, rawItem] of envelope.items.entries()) {
82294
+ const parsed = marketplaceHitSchema.safeParse(rawItem);
82295
+ if (parsed.success) {
82296
+ items.push(parsed.data);
82297
+ continue;
82298
+ }
82299
+ dropped += 1;
82300
+ try {
82301
+ options.debug?.(`vAPI marketplace discovery dropped invalid row at index ${index2}.`);
82302
+ } catch {
82303
+ }
82304
+ }
82305
+ mergedCount = items.length;
81959
82306
  const attempt = attempts.at(-1);
81960
- if (attempt) attempt.count = mergedCount;
81961
- return page;
82307
+ if (attempt) {
82308
+ attempt.count = mergedCount;
82309
+ if (dropped > 0) attempt.dropped = dropped;
82310
+ }
82311
+ return { ...envelope, items };
81962
82312
  } finally {
81963
82313
  if (options.searchesPath) {
81964
82314
  await appendSearchEvent(
@@ -82087,6 +82437,34 @@ var VapiCallError = class extends Error {
82087
82437
  paymentRejection;
82088
82438
  confirmedSettlement;
82089
82439
  };
82440
+ var SOLANA_PAYMENTS_UNSUPPORTED_MESSAGE = "Solana payments are not supported in this version of vAPI yet; they arrive in a later release.";
82441
+ function isSolanaCaip2(network) {
82442
+ return network.startsWith("solana:");
82443
+ }
82444
+ function listingPaymentNetwork(endpointNetwork, serviceNetworks) {
82445
+ if (endpointNetwork !== void 0) return endpointNetwork;
82446
+ return serviceNetworks?.length && serviceNetworks.every(isSolanaCaip2) ? serviceNetworks[0] : void 0;
82447
+ }
82448
+ function assertSupportedListingNetwork(network) {
82449
+ if (network !== void 0 && isSolanaCaip2(network)) {
82450
+ throw new VapiCallError(
82451
+ "unsupported_network",
82452
+ `${SOLANA_PAYMENTS_UNSUPPORTED_MESSAGE} This listing pays on ${network}.`
82453
+ );
82454
+ }
82455
+ }
82456
+ function assertSupportedListingResolution(error61) {
82457
+ if (isDiscoveryCatalogError(error61) && error61.code === "ambiguous_default" && error61.paymentNetworks?.length && error61.paymentNetworks.every(isSolanaCaip2)) {
82458
+ assertSupportedListingNetwork(error61.paymentNetworks[0]);
82459
+ }
82460
+ }
82461
+ function payableConfig(config2, account) {
82462
+ if (account.solana !== void 0) return config2;
82463
+ const networks = Object.fromEntries(
82464
+ Object.entries(config2.networks).filter(([network]) => !isSolanaCaip2(network))
82465
+ );
82466
+ return { ...config2, networks };
82467
+ }
82090
82468
  var MAX_RESPONSE_BYTES = 1048576;
82091
82469
  var BODY_HEADER_NAMES = [
82092
82470
  "content-encoding",
@@ -82096,12 +82474,15 @@ var BODY_HEADER_NAMES = [
82096
82474
  "content-type"
82097
82475
  ];
82098
82476
  async function callService(args) {
82477
+ validateTimeoutSeconds(args.input.timeoutSeconds);
82099
82478
  const trace = createCallTrace(args);
82100
82479
  let execution;
82101
82480
  try {
82102
82481
  execution = await executeCallService(args, trace);
82103
82482
  } catch (error61) {
82104
- await recordCallError(args, error61, trace).catch(() => void 0);
82483
+ if (!(error61 instanceof VapiCallError && (error61.code === "unsupported_network" || error61.code === "unsupported_payment"))) {
82484
+ await recordCallError(args, error61, trace).catch(() => void 0);
82485
+ }
82105
82486
  throw error61;
82106
82487
  }
82107
82488
  try {
@@ -82149,10 +82530,16 @@ async function executeCallService(args, trace) {
82149
82530
  config2,
82150
82531
  fetchImpl
82151
82532
  );
82533
+ } catch (error61) {
82534
+ assertSupportedListingResolution(error61);
82535
+ throw error61;
82152
82536
  } finally {
82153
82537
  trace.phases.discoverMs = elapsed2(trace, discoverStarted);
82154
82538
  }
82155
82539
  }
82540
+ assertSupportedListingNetwork(
82541
+ listingPaymentNetwork(endpoint?.payment?.network, endpoint?.serviceNetworks)
82542
+ );
82156
82543
  const requestedNetwork = normalizeRequiredNetwork(input2.network);
82157
82544
  const listingNetwork = endpoint?.payment?.network;
82158
82545
  if (requestedNetwork && listingNetwork && !areSamePaymentNetwork(requestedNetwork, listingNetwork)) {
@@ -82207,6 +82594,8 @@ async function executeCallService(args, trace) {
82207
82594
  body: method === "GET" || method === "HEAD" ? void 0 : requestBody
82208
82595
  });
82209
82596
  const request = createRequest(headers);
82597
+ const probeTimeoutMs = input2.timeoutSeconds === void 0 ? args.timeoutMs ?? 3e4 : Math.min(input2.timeoutSeconds, 30) * 1e3;
82598
+ let requestTimeoutMs = probeTimeoutMs;
82210
82599
  const fetchWithGuardedRedirects = async (candidateRequest, followRedirects = true) => {
82211
82600
  let currentRequest = candidateRequest;
82212
82601
  let followedRedirects = 0;
@@ -82214,7 +82603,7 @@ async function executeCallService(args, trace) {
82214
82603
  const attempt = await fetchAttempt(
82215
82604
  fetchImpl,
82216
82605
  new Request(currentRequest.clone(), { redirect: "manual" }),
82217
- args.timeoutMs ?? 3e4
82606
+ requestTimeoutMs
82218
82607
  );
82219
82608
  const response = attempt.response;
82220
82609
  if (!isRedirectStatus2(response.status)) {
@@ -82368,8 +82757,13 @@ async function executeCallService(args, trace) {
82368
82757
  challenge: challengeAttempt,
82369
82758
  account,
82370
82759
  caps: args.spendCaps ?? config2.spendCaps,
82371
- config: config2,
82372
- send: async (paidRequest) => {
82760
+ config: payableConfig(config2, account),
82761
+ send: async (paidRequest, quote) => {
82762
+ requestTimeoutMs = paidRequestTimeoutMs(
82763
+ input2.timeoutSeconds,
82764
+ args.timeoutMs,
82765
+ quote.accepted.maxTimeoutSeconds
82766
+ );
82373
82767
  paidAttempt = await fetchWithGuardedRedirects(paidRequest, false);
82374
82768
  return paidAttempt;
82375
82769
  },
@@ -82408,7 +82802,7 @@ async function executeCallService(args, trace) {
82408
82802
  asset: completed.quote.accepted.asset,
82409
82803
  payTo: completed.quote.accepted.payTo,
82410
82804
  settlement: settlementWithExplorer2(completed.settlement, completed.quote.accepted.network),
82411
- proof: completed.response.headers.get("x-vapi-payment-proof")
82805
+ proof: completed.paymentProof
82412
82806
  },
82413
82807
  ...verificationFor(endpoint),
82414
82808
  ...expectedRequestFor(endpoint, completed.response.status)
@@ -82618,7 +83012,7 @@ async function resolveCallEndpoint(id2, endpointName, marketplaceHit, config2, f
82618
83012
  try {
82619
83013
  return registeredEndpoint(await resolveServiceListing(id2, config2, fetchImpl, endpointName));
82620
83014
  } catch (error61) {
82621
- if (!(error61 instanceof DiscoveryCatalogError) || error61.code !== "service_not_found") {
83015
+ if (!isDiscoveryCatalogError(error61) || error61.code !== "service_not_found") {
82622
83016
  throw error61;
82623
83017
  }
82624
83018
  const discovered = await findMarketplaceApiByRef(id2, config2, fetchImpl);
@@ -82655,9 +83049,18 @@ async function resolveCallEndpoint(id2, endpointName, marketplaceHit, config2, f
82655
83049
  );
82656
83050
  }
82657
83051
  function registeredEndpoint(listing, verification) {
83052
+ const { payment, ...endpoint } = listing.endpoint;
83053
+ if (payment && (typeof payment.protocol === "string" || typeof payment.network !== "string")) {
83054
+ throw new VapiCallError(
83055
+ "unsupported_payment",
83056
+ `Payment protocol ${payment.protocol} is not supported. This client pays x402 exact USDC endpoints only.`
83057
+ );
83058
+ }
82658
83059
  return {
82659
- ...listing.endpoint,
83060
+ ...endpoint,
83061
+ ...payment ? { payment: { network: payment.network, payTo: payment.payTo } } : {},
82660
83062
  verification: verification ?? listing.service.verification,
83063
+ serviceNetworks: listing.service.networks,
82661
83064
  registered: true,
82662
83065
  resolvedListing: true
82663
83066
  };
@@ -82817,7 +83220,7 @@ async function readResponseBody2(response) {
82817
83220
  async function fetchAttempt(fetchImpl, request, timeoutMs) {
82818
83221
  const controller = new AbortController();
82819
83222
  let rejectTimeout = null;
82820
- const timeoutError = new Error(`API request timed out after ${timeoutMs}ms.`);
83223
+ const timeoutError = new Error(`API request timed out after ${timeoutMs / 1e3} seconds.`);
82821
83224
  const timedOut = new Promise((_resolve, reject) => {
82822
83225
  rejectTimeout = reject;
82823
83226
  });
@@ -82857,6 +83260,19 @@ async function fetchAttempt(fetchImpl, request, timeoutMs) {
82857
83260
  throw error61;
82858
83261
  }
82859
83262
  }
83263
+ function validateTimeoutSeconds(timeoutSeconds) {
83264
+ if (timeoutSeconds !== void 0 && (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 300)) {
83265
+ throw new Error("call timeoutSeconds must be an integer from 1 to 300 seconds.");
83266
+ }
83267
+ }
83268
+ function paidRequestTimeoutMs(timeoutSeconds, internalTimeoutMs, offerTimeoutSeconds) {
83269
+ const usableOfferTimeout = Number.isInteger(offerTimeoutSeconds) && offerTimeoutSeconds > 0 ? offerTimeoutSeconds : void 0;
83270
+ if (timeoutSeconds !== void 0) {
83271
+ return Math.min(timeoutSeconds, usableOfferTimeout ?? timeoutSeconds) * 1e3;
83272
+ }
83273
+ if (internalTimeoutMs !== void 0) return internalTimeoutMs;
83274
+ return usableOfferTimeout === void 0 ? 12e4 : Math.min(12e4, Math.max(3e4, usableOfferTimeout * 1e3));
83275
+ }
82860
83276
  function mapX402PaymentError(error61, resumeId) {
82861
83277
  if (!(error61 instanceof X402PaymentError)) return error61;
82862
83278
  if (error61.code === "payment_rejected") {
@@ -82872,9 +83288,10 @@ function mapX402PaymentError(error61, resumeId) {
82872
83288
  });
82873
83289
  }
82874
83290
  const resume = resumeId !== void 0 && error61.possibleSettlement?.authorizationNonce ? ` Check whether it settled with \`vapi pay --resume ${resumeId}\` before paying again.` : "";
83291
+ const timeoutDetail = error61.cause instanceof Error && error61.cause.message.startsWith("API request timed out after ") ? `${error61.cause.message} ` : "";
82875
83292
  return new VapiCallError(
82876
83293
  "settlement_unknown",
82877
- `${error61.message}${resume}`,
83294
+ `${timeoutDetail}${error61.message}${resume}`,
82878
83295
  error61.possibleSettlement,
82879
83296
  { cause: error61.cause }
82880
83297
  );
@@ -82896,14 +83313,17 @@ async function inspectService(input2, config2, fetchImpl) {
82896
83313
  try {
82897
83314
  listing = await resolveServiceListing(input2.id, config2, fetchImpl, input2.endpoint);
82898
83315
  } catch (error61) {
82899
- if (input2.endpoint || !(error61 instanceof DiscoveryCatalogError) || error61.code !== "service_not_found") {
83316
+ assertSupportedListingResolution(error61);
83317
+ if (input2.endpoint || !isDiscoveryCatalogError(error61) || error61.code !== "service_not_found") {
82900
83318
  throw error61;
82901
83319
  }
82902
83320
  const hit = await findMarketplaceApiByRef(input2.id, config2, fetchImpl);
82903
83321
  if (!hit || hit.kind !== "api" || hit.provenance !== "indexed") throw error61;
83322
+ assertSupportedListingNetwork(hit.execution.network);
82904
83323
  return inspectIndexedHit(hit);
82905
83324
  }
82906
83325
  const { endpoint, service } = listing;
83326
+ assertSupportedListingNetwork(listingPaymentNetwork(endpoint.payment?.network, service.networks));
82907
83327
  return {
82908
83328
  name: endpoint.name,
82909
83329
  method: endpoint.method,
@@ -83003,13 +83423,7 @@ var inspectToolResultSchema = external_exports.object({
83003
83423
  liveness: listingLivenessSchema.optional(),
83004
83424
  conformance: listingConformanceSchema.optional(),
83005
83425
  identity: listingIdentitySchema.optional(),
83006
- payment: external_exports.object({
83007
- scheme: external_exports.literal("exact"),
83008
- network: external_exports.string(),
83009
- asset: external_exports.string(),
83010
- payTo: external_exports.string(),
83011
- checkedAt: external_exports.string()
83012
- }).nullable()
83426
+ payment: discoveryEndpointSchema.shape.payment.unwrap().nullable()
83013
83427
  });
83014
83428
  var callSearchInputSchema = external_exports.object({
83015
83429
  query: external_exports.string().trim().max(200).optional().describe("Capability, API, service, or request."),
@@ -83038,7 +83452,10 @@ var callPayInputSchema = external_exports.object({
83038
83452
  (value) => /^0x[0-9a-fA-F]{40}$/.test(value) || isSolanaAddress(value),
83039
83453
  "Expected an EVM or Solana address."
83040
83454
  ).optional(),
83041
- maxPriceUsd: external_exports.union([external_exports.number().nonnegative(), external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/)]).optional()
83455
+ maxPriceUsd: external_exports.union([external_exports.number().nonnegative(), external_exports.string().regex(/^\d+(?:\.\d{1,6})?$/)]).optional(),
83456
+ timeoutSeconds: external_exports.number().int().min(1).max(300).optional().describe(
83457
+ "Seconds to wait for the paid response. Default: the provider's maxTimeoutSeconds, at most 120."
83458
+ )
83042
83459
  });
83043
83460
  var callSearch = defineAction({
83044
83461
  name: "call.search",
@@ -83301,7 +83718,7 @@ async function readResult(response, signal, secrets = []) {
83301
83718
  return {
83302
83719
  status: response.status,
83303
83720
  contentType: contentType === null ? null : redactKnownSecrets2(contentType, secrets),
83304
- body: sanitizeReturnedValue(await readResponseBody3(response, contentType, signal), secrets)
83721
+ body: sanitizeReturnedValue2(await readResponseBody3(response, contentType, signal), secrets)
83305
83722
  };
83306
83723
  }
83307
83724
  async function readResponseBody3(response, contentType, signal) {
@@ -83346,17 +83763,17 @@ function isJsonContentType2(value) {
83346
83763
  const mediaType = value?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
83347
83764
  return mediaType === "application/json" || mediaType.endsWith("+json");
83348
83765
  }
83349
- function sanitizeReturnedValue(value, secrets, depth = 0) {
83766
+ function sanitizeReturnedValue2(value, secrets, depth = 0) {
83350
83767
  if (typeof value === "string") return redactKnownSecrets2(value, secrets);
83351
83768
  if (value === null || typeof value !== "object") return value;
83352
83769
  if (depth >= 16) return "[redacted nested response value]";
83353
83770
  if (Array.isArray(value)) {
83354
- return value.map((item) => sanitizeReturnedValue(item, secrets, depth + 1));
83771
+ return value.map((item) => sanitizeReturnedValue2(item, secrets, depth + 1));
83355
83772
  }
83356
83773
  return Object.fromEntries(
83357
83774
  Object.entries(value).map(([key2, item]) => [
83358
83775
  redactKnownSecrets2(key2, secrets),
83359
- sanitizeReturnedValue(item, secrets, depth + 1)
83776
+ sanitizeReturnedValue2(item, secrets, depth + 1)
83360
83777
  ])
83361
83778
  );
83362
83779
  }
@@ -86676,6 +87093,7 @@ var moneyParticipant = {
86676
87093
  "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."
86677
87094
  ).optional()
86678
87095
  };
87096
+ var waitForIndexer = external_exports.boolean().default(true).describe("Wait up to 60 seconds for vAPI to index the chain result before returning.");
86679
87097
  var cursor = external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
86680
87098
  function usdWithinEscrow(value, positive = false) {
86681
87099
  try {
@@ -86722,7 +87140,10 @@ var tasksPostTool = descriptor(
86722
87140
  deadline: external_exports.string(),
86723
87141
  intake: external_exports.enum(["proposals", "submissions"]).optional(),
86724
87142
  maxAwards: external_exports.number().int().min(TASK_LIMITS.maxAwardsMin).max(TASK_LIMITS.maxAwardsMax).optional(),
86725
- webhookUrl: httpsUrl.optional()
87143
+ webhookUrl: httpsUrl.optional(),
87144
+ vendor: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).describe(
87145
+ "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."
87146
+ ).optional()
86726
87147
  }
86727
87148
  );
86728
87149
  var tasksProposeTool = descriptor(
@@ -86747,42 +87168,43 @@ var tasksAwardTool = descriptor(
86747
87168
  { ...participant, proposalId: id }
86748
87169
  );
86749
87170
  var tasksSignTool = descriptor(
86750
- "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.",
86751
- moneyParticipant
87171
+ "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.",
87172
+ { ...moneyParticipant, wait: waitForIndexer }
86752
87173
  );
86753
87174
  var tasksFundTool = descriptor(
86754
- "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.",
86755
- moneyParticipant
87175
+ "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.",
87176
+ { ...moneyParticipant, wait: waitForIndexer }
86756
87177
  );
86757
87178
  var tasksDeliverTool = descriptor(
86758
- "Does not move money. Upload local delivery files, freeze the manifest and record delivery with the local vault wallet.",
87179
+ "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.",
86759
87180
  {
86760
87181
  ...moneyParticipant,
87182
+ wait: waitForIndexer,
86761
87183
  files: external_exports.array(localPath).min(TASK_LIMITS.deliveryFilesMin).max(TASK_LIMITS.deliveryFilesMax),
86762
87184
  note: external_exports.string().max(TASK_LIMITS.deliveryNoteMax).refine((value) => value.trim().length > 0)
86763
87185
  }
86764
87186
  );
86765
87187
  var tasksReleaseTool = descriptor(
86766
- "Moves money: pays the worker from escrow with the local vault wallet. Returns gross \xB7 fee \xB7 net using the deployed fee.",
86767
- moneyParticipant
87188
+ "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.",
87189
+ { ...moneyParticipant, wait: waitForIndexer }
86768
87190
  );
86769
87191
  var tasksRefundTool = descriptor(
86770
- "Moves money: returns escrowed USDC to the poster with the local vault wallet. Returns gross \xB7 fee \xB7 net using the deployed fee.",
87192
+ "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.",
86771
87193
  moneyParticipant
86772
87194
  );
86773
87195
  var tasksDisputeTool = descriptor(
86774
- "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.",
87196
+ "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.",
86775
87197
  {
86776
87198
  ...moneyParticipant,
86777
87199
  evidenceHash: external_exports.string().regex(TASK_LIMITS.disputeEvidenceHash)
86778
87200
  }
86779
87201
  );
86780
87202
  var tasksCounterEvidenceTool = descriptor(
86781
- "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.",
87203
+ "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.",
86782
87204
  { ...moneyParticipant, evidenceHash: external_exports.string().regex(TASK_LIMITS.disputeEvidenceHash) }
86783
87205
  );
86784
87206
  var tasksResolveUnmatchedTool = descriptor(
86785
- "Moves money: resolves an unmatched dispute after the onchain counter-evidence deadline when no counter-evidence was submitted.",
87207
+ "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.",
86786
87208
  moneyParticipant
86787
87209
  );
86788
87210
  var tasksMessageTool = descriptor(
@@ -86806,8 +87228,8 @@ var tasksWatchTool = descriptor(
86806
87228
  }
86807
87229
  );
86808
87230
  var tasksStatusTool = descriptor(
86809
- "Does not move money. Read the public task card and receipt URL when settled; sign-in is not required.",
86810
- { id }
87231
+ "Does not move money. Read signed-in chain state and participant events, or the public task card without sign-in.",
87232
+ participant
86811
87233
  );
86812
87234
  var signInHint = "Call auth.link for the acting wallet.";
86813
87235
  function lazyTasksChain(factory, pending) {
@@ -86947,6 +87369,22 @@ function createTasksTools(options) {
86947
87369
  };
86948
87370
  };
86949
87371
  }
87372
+ async function waitAfterChain(ctx, orderId, milestoneId, target) {
87373
+ return await taskRequest(
87374
+ target,
87375
+ "getOrder",
87376
+ () => waitForMilestone(ctx.client, {
87377
+ orderId,
87378
+ milestoneId,
87379
+ target,
87380
+ timeoutMs: 6e4,
87381
+ intervalMs: 3e3,
87382
+ ...options.sleep === void 0 ? {} : { sleep: options.sleep },
87383
+ now
87384
+ }),
87385
+ ctx
87386
+ );
87387
+ }
86950
87388
  async function feeAction(verb, input2) {
86951
87389
  const ctx = await acting(input2.wallet);
86952
87390
  const policy = await taskPolicyForWallet({
@@ -86989,7 +87427,12 @@ function createTasksTools(options) {
86989
87427
  throw new TaskInputError("deadline must be at least 10 minutes from now.");
86990
87428
  const ctx = await acting(input2.wallet);
86991
87429
  const outcome = await postTask(ctx, {
86992
- order: { title: input2.title, description: input2.brief, policyFamily: "general-digital" },
87430
+ order: {
87431
+ title: input2.title,
87432
+ description: input2.brief,
87433
+ policyFamily: "general-digital",
87434
+ ...input2.vendor === void 0 ? {} : { invitedProviderAddress: input2.vendor }
87435
+ },
86993
87436
  amount: parseUsdToBaseUnits(input2.amountUsd),
86994
87437
  deadlineAt: new Date(postedAt.getTime() + deadlineDuration).toISOString(),
86995
87438
  ...input2.intake === void 0 ? {} : { intake: input2.intake },
@@ -87047,15 +87490,15 @@ function createTasksTools(options) {
87047
87490
  const ctx = await acting(input2.wallet);
87048
87491
  const signerAddress = (await options.session.addressesFor(ctx.selected.name)).address;
87049
87492
  try {
87050
- return taskResult(
87051
- await signTaskScope(ctx, {
87052
- id: input2.id,
87053
- counterparty: input2.counterparty,
87054
- signerAddress,
87055
- bindings: createScopeBindings(home),
87056
- signMessage: async (message) => (await unlock(ctx.selected.name)()).signMessage(message)
87057
- })
87058
- );
87493
+ const outcome = await signTaskScope(ctx, {
87494
+ id: input2.id,
87495
+ counterparty: input2.counterparty,
87496
+ signerAddress,
87497
+ bindings: createScopeBindings(home),
87498
+ signMessage: async (message) => (await unlock(ctx.selected.name)()).signMessage(message)
87499
+ });
87500
+ const wait2 = input2.wait && outcome.escrowCreation ? await waitAfterChain(ctx, input2.id, outcome.escrowCreation.milestone.id, "created") : null;
87501
+ return taskResult({ ...outcome, wait: wait2 });
87059
87502
  } catch (error61) {
87060
87503
  if (!(error61 instanceof TasksScopeCreationError)) throw error61;
87061
87504
  try {
@@ -87091,28 +87534,31 @@ function createTasksTools(options) {
87091
87534
  // Stdio has no human approval channel. Model arguments cannot grant approval.
87092
87535
  approval: { granted: false }
87093
87536
  });
87094
- return taskResult(outcome, !outcome.ok);
87537
+ const wait2 = input2.wait && outcome.ok ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "locked") : null;
87538
+ return taskResult({ ...outcome, wait: wait2 }, !outcome.ok);
87095
87539
  },
87096
87540
  async deliver(input2) {
87097
87541
  const files = (await Promise.all(input2.files.map(readTaskFile))).map(
87098
87542
  ({ fileName: name, bytes, contentType }) => ({ name, bytes, contentType })
87099
87543
  );
87100
- return taskResult(
87101
- await deliverTaskOperation(await acting(input2.wallet), {
87102
- id: input2.id,
87103
- ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty },
87104
- files,
87105
- note: input2.note
87106
- })
87107
- );
87544
+ const ctx = await acting(input2.wallet);
87545
+ const outcome = await deliverTaskOperation(ctx, {
87546
+ id: input2.id,
87547
+ ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty },
87548
+ files,
87549
+ note: input2.note
87550
+ });
87551
+ const wait2 = input2.wait ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "delivered") : null;
87552
+ return taskResult({ ...outcome, wait: wait2 });
87108
87553
  },
87109
87554
  async release(input2) {
87110
- return taskResult(
87111
- await releaseTaskOperation(await acting(input2.wallet), {
87112
- id: input2.id,
87113
- ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty }
87114
- })
87115
- );
87555
+ const ctx = await acting(input2.wallet);
87556
+ const outcome = await releaseTaskOperation(ctx, {
87557
+ id: input2.id,
87558
+ ...input2.counterparty === void 0 ? {} : { counterparty: input2.counterparty }
87559
+ });
87560
+ const wait2 = input2.wait ? await waitAfterChain(ctx, input2.id, outcome.result.milestone.id, "released") : null;
87561
+ return taskResult({ ...outcome, wait: wait2 });
87116
87562
  },
87117
87563
  async refund(input2) {
87118
87564
  return taskResult(
@@ -87179,7 +87625,11 @@ function createTasksTools(options) {
87179
87625
  }
87180
87626
  },
87181
87627
  async status(input2) {
87182
- return taskResult(await taskStatus(await context(void 0, true), { id: input2.id }));
87628
+ await options.wallets?.reload();
87629
+ const publicOnly = input2.wallet === void 0 && options.session.activeName === void 0 && options.wallets !== void 0 && options.wallets.names().length === 0;
87630
+ const candidate = await context(input2.wallet, publicOnly);
87631
+ const ctx = candidate.token || publicOnly ? candidate : await context(void 0, true);
87632
+ return taskResult(await taskStatus(ctx, { id: input2.id, signedIn: Boolean(ctx.token) }));
87183
87633
  }
87184
87634
  };
87185
87635
  }
@@ -87936,6 +88386,11 @@ var statsToolResultSchema = external_exports.object({
87936
88386
  )
87937
88387
  })
87938
88388
  });
88389
+ function objectOutputSchema(schema) {
88390
+ if (!schema) return {};
88391
+ const json2 = external_exports.toJSONSchema(schema);
88392
+ return json2.type === "object" ? { outputSchema: json2 } : {};
88393
+ }
87939
88394
  var VapiMcpServer = class {
87940
88395
  #tools = /* @__PURE__ */ new Map();
87941
88396
  #onClose;
@@ -87959,7 +88414,7 @@ var VapiMcpServer = class {
87959
88414
  name,
87960
88415
  ...tool.description ? { description: tool.description } : {},
87961
88416
  inputSchema: external_exports.toJSONSchema(tool.inputSchema),
87962
- ...tool.outputSchema ? { outputSchema: external_exports.toJSONSchema(tool.outputSchema) } : {}
88417
+ ...objectOutputSchema(tool.outputSchema)
87963
88418
  }))
87964
88419
  };
87965
88420
  }
@@ -88830,7 +89285,13 @@ function toolError(error61) {
88830
89285
  {
88831
89286
  error: error61.message,
88832
89287
  code: error61.code,
88833
- ...error61.possibleSettlement ? { possibleSettlement: error61.possibleSettlement } : {},
89288
+ ...error61.possibleSettlement ? {
89289
+ possibleSettlement: Object.fromEntries(
89290
+ Object.entries(error61.possibleSettlement).filter(
89291
+ ([key2]) => key2 !== "authorizationTransaction"
89292
+ )
89293
+ )
89294
+ } : {},
88834
89295
  ...error61.paymentRejection ? { paymentRejection: error61.paymentRejection } : {},
88835
89296
  ...error61.confirmedSettlement ? { confirmedSettlement: error61.confirmedSettlement } : {}
88836
89297
  },
@@ -88852,6 +89313,7 @@ export {
88852
89313
  STARTING_RECONCILIATION_TIMEOUT_MS,
88853
89314
  SwarmRunError,
88854
89315
  UNTRUSTED_NOTICE,
89316
+ VapiCallError,
88855
89317
  WalletSession,
88856
89318
  accountsSend,
88857
89319
  accountsSendInputSchema,