@agentcash/discovery 0.1.4 → 1.0.1

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
@@ -1,23 +1,104 @@
1
- // src/flags.ts
2
- var LEGACY_SUNSET_DATE = "2026-03-24";
3
- var DEFAULT_COMPAT_MODE = "on";
4
- var STRICT_ESCALATION_CODES = [
5
- "LEGACY_WELL_KNOWN_USED",
6
- "LEGACY_DNS_USED",
7
- "LEGACY_DNS_PLAIN_URL",
8
- "LEGACY_MISSING_METHOD",
9
- "LEGACY_INSTRUCTIONS_USED",
10
- "LEGACY_OWNERSHIP_PROOFS_USED",
11
- "INTEROP_MPP_USED"
12
- ];
1
+ // src/core/source/openapi/index.ts
2
+ import { okAsync, ResultAsync as ResultAsync2 } from "neverthrow";
13
3
 
14
- // src/mmm-enabled.ts
15
- var isMmmEnabled = () => "0.1.4".includes("-mmm");
4
+ // src/schemas.ts
5
+ import { z } from "zod";
6
+ var OpenApiPaymentInfoSchema = z.object({
7
+ pricingMode: z.enum(["fixed", "range", "quote"]),
8
+ price: z.string().optional(),
9
+ minPrice: z.string().optional(),
10
+ maxPrice: z.string().optional(),
11
+ protocols: z.array(z.string()).optional()
12
+ });
13
+ var OpenApiOperationSchema = z.object({
14
+ operationId: z.string().optional(),
15
+ summary: z.string().optional(),
16
+ description: z.string().optional(),
17
+ tags: z.array(z.string()).optional(),
18
+ security: z.array(z.record(z.string(), z.array(z.string()))).optional(),
19
+ parameters: z.array(
20
+ z.object({
21
+ in: z.string(),
22
+ name: z.string(),
23
+ schema: z.unknown().optional(),
24
+ required: z.boolean().optional()
25
+ })
26
+ ).optional(),
27
+ requestBody: z.object({
28
+ required: z.boolean().optional(),
29
+ content: z.record(z.string(), z.object({ schema: z.unknown().optional() }))
30
+ }).optional(),
31
+ responses: z.record(z.string(), z.unknown()).optional(),
32
+ "x-payment-info": OpenApiPaymentInfoSchema.optional()
33
+ });
34
+ var OpenApiPathItemSchema = z.object({
35
+ get: OpenApiOperationSchema.optional(),
36
+ post: OpenApiOperationSchema.optional(),
37
+ put: OpenApiOperationSchema.optional(),
38
+ delete: OpenApiOperationSchema.optional(),
39
+ patch: OpenApiOperationSchema.optional(),
40
+ head: OpenApiOperationSchema.optional(),
41
+ options: OpenApiOperationSchema.optional(),
42
+ trace: OpenApiOperationSchema.optional()
43
+ });
44
+ var OpenApiDocSchema = z.object({
45
+ // TODO(zdql): We should inherit a canonical OpenAPI schema and then extend with our types.
46
+ openapi: z.string(),
47
+ info: z.object({
48
+ title: z.string(),
49
+ version: z.string(),
50
+ description: z.string().optional(),
51
+ guidance: z.string().optional()
52
+ }),
53
+ servers: z.array(z.object({ url: z.string() })).optional(),
54
+ tags: z.array(z.object({ name: z.string() })).optional(),
55
+ components: z.object({ securitySchemes: z.record(z.string(), z.unknown()).optional() }).optional(),
56
+ "x-discovery": z.record(z.string(), z.unknown()).optional(),
57
+ paths: z.record(z.string(), OpenApiPathItemSchema)
58
+ });
59
+ var WellKnownDocSchema = z.object({
60
+ version: z.number().optional(),
61
+ resources: z.array(z.string()).default([]),
62
+ mppResources: z.array(z.string()).optional(),
63
+ // isMmmEnabled
64
+ description: z.string().optional(),
65
+ ownershipProofs: z.array(z.string()).optional(),
66
+ instructions: z.string().optional()
67
+ });
68
+ var WellKnownParsedSchema = z.object({
69
+ routes: z.array(
70
+ z.object({
71
+ path: z.string(),
72
+ method: z.enum(["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "TRACE"])
73
+ })
74
+ ),
75
+ instructions: z.string().optional()
76
+ });
77
+
78
+ // src/core/source/openapi/utils.ts
79
+ function isRecord(value) {
80
+ return value !== null && typeof value === "object" && !Array.isArray(value);
81
+ }
82
+ function hasSecurity(operation, scheme) {
83
+ return operation.security?.some((s) => scheme in s) ?? false;
84
+ }
85
+ function has402Response(operation) {
86
+ return Boolean(operation.responses?.["402"]);
87
+ }
88
+ function inferAuthMode(operation) {
89
+ const hasXPaymentInfo = Boolean(operation["x-payment-info"]);
90
+ const hasPayment = hasXPaymentInfo || has402Response(operation);
91
+ const hasApiKey = hasSecurity(operation, "apiKey");
92
+ const hasSiwx = hasSecurity(operation, "siwx");
93
+ if (hasPayment && hasApiKey) return "apiKey+paid";
94
+ if (hasXPaymentInfo) return "paid";
95
+ if (hasPayment) return hasSiwx ? "siwx" : "paid";
96
+ if (hasApiKey) return "apiKey";
97
+ if (hasSiwx) return "siwx";
98
+ return void 0;
99
+ }
16
100
 
17
- // src/core/constants.ts
18
- var OPENAPI_PATH_CANDIDATES = ["/openapi.json", "/.well-known/openapi.json"];
19
- var WELL_KNOWN_MPP_PATH = "/.well-known/mpp";
20
- var LLMS_TOKEN_WARNING_THRESHOLD = 2500;
101
+ // src/core/lib/constants.ts
21
102
  var HTTP_METHODS = /* @__PURE__ */ new Set([
22
103
  "GET",
23
104
  "POST",
@@ -28,10 +109,9 @@ var HTTP_METHODS = /* @__PURE__ */ new Set([
28
109
  "OPTIONS",
29
110
  "TRACE"
30
111
  ]);
31
- var DEFAULT_PROBE_METHODS = ["GET", "POST"];
32
112
  var DEFAULT_MISSING_METHOD = "POST";
33
113
 
34
- // src/core/url.ts
114
+ // src/core/lib/url.ts
35
115
  function normalizeOrigin(target) {
36
116
  const trimmed = target.trim();
37
117
  const withProtocol = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
@@ -49,9 +129,6 @@ function normalizePath(pathname) {
49
129
  const normalized = prefixed.replace(/\/+/g, "/");
50
130
  return normalized !== "/" ? normalized.replace(/\/$/, "") : "/";
51
131
  }
52
- function toResourceKey(origin, method, path) {
53
- return `${origin} ${method} ${normalizePath(path)}`;
54
- }
55
132
  function parseMethod(value) {
56
133
  if (!value) return void 0;
57
134
  const upper = value.toUpperCase();
@@ -66,1347 +143,1024 @@ function toAbsoluteUrl(origin, value) {
66
143
  }
67
144
  }
68
145
 
69
- // src/core/warnings.ts
70
- function warning(code, severity, message, options) {
71
- return {
72
- code,
73
- severity,
74
- message,
75
- ...options?.hint ? { hint: options.hint } : {},
76
- ...options?.stage ? { stage: options.stage } : {},
77
- ...options?.resourceKey ? { resourceKey: options.resourceKey } : {}
78
- };
79
- }
80
- function applyStrictEscalation(warnings, strict) {
81
- if (!strict) return warnings;
82
- return warnings.map((entry) => {
83
- if (!STRICT_ESCALATION_CODES.includes(entry.code)) {
84
- return entry;
85
- }
86
- if (entry.severity === "error") return entry;
87
- return {
88
- ...entry,
89
- severity: "error",
90
- message: `${entry.message} (strict mode escalated)`
91
- };
92
- });
146
+ // src/core/source/fetch.ts
147
+ import { ResultAsync } from "neverthrow";
148
+ function toFetchError(err) {
149
+ const cause = err instanceof DOMException && (err.name === "TimeoutError" || err.name === "AbortError") ? "timeout" : "network";
150
+ return { cause, message: String(err) };
93
151
  }
94
- function dedupeWarnings(warnings) {
95
- const seen = /* @__PURE__ */ new Set();
96
- const output = [];
97
- for (const item of warnings) {
98
- const key = `${item.code}|${item.severity}|${item.stage ?? ""}|${item.resourceKey ?? ""}|${item.message}`;
99
- if (seen.has(key)) continue;
100
- seen.add(key);
101
- output.push(item);
102
- }
103
- return output;
152
+ function fetchSafe(url, init) {
153
+ return ResultAsync.fromPromise(fetch(url, init), toFetchError);
104
154
  }
105
155
 
106
- // src/core/normalize.ts
107
- function createResource(input, confidence, trustTier) {
108
- const normalizedOrigin = normalizeOrigin(input.origin);
109
- const normalizedPath = normalizePath(input.path);
110
- return {
111
- resourceKey: toResourceKey(normalizedOrigin, input.method, normalizedPath),
112
- origin: normalizedOrigin,
113
- method: input.method,
114
- path: normalizedPath,
115
- source: input.source,
116
- verified: false,
117
- ...input.protocolHints?.length ? { protocolHints: [...new Set(input.protocolHints)] } : {},
118
- ...input.priceHint ? { priceHint: input.priceHint } : {},
119
- ...input.pricing ? { pricing: input.pricing } : {},
120
- ...input.authHint ? { authHint: input.authHint } : {},
121
- ...input.summary ? { summary: input.summary } : {},
122
- confidence,
123
- trustTier,
124
- ...input.links ? { links: input.links } : {}
125
- };
126
- }
156
+ // src/mmm-enabled.ts
157
+ var isMmmEnabled = () => "1.0.1".includes("-mmm");
127
158
 
128
- // src/compat/legacy-x402scan/wellKnown.ts
129
- function isRecord(value) {
130
- return value !== null && typeof value === "object" && !Array.isArray(value);
131
- }
132
- function parseLegacyResourceEntry(entry) {
133
- const trimmed = entry.trim();
134
- if (!trimmed) return null;
135
- const parts = trimmed.split(/\s+/);
136
- if (parts.length >= 2) {
137
- const maybeMethod = parseMethod(parts[0]);
138
- if (maybeMethod) {
139
- const target = parts.slice(1).join(" ");
140
- return { method: maybeMethod, target };
141
- }
142
- }
143
- if (trimmed.startsWith("/") || /^https?:\/\//i.test(trimmed)) {
144
- return { target: trimmed };
145
- }
146
- return null;
147
- }
148
- function parseWellKnownPayload(payload, origin, sourceUrl) {
149
- const warnings = [
150
- warning(
151
- "LEGACY_WELL_KNOWN_USED",
152
- "warn",
153
- "Using legacy /.well-known/x402 compatibility path. Migrate to OpenAPI-first.",
154
- {
155
- stage: "well-known/x402"
156
- }
157
- )
158
- ];
159
- if (!isRecord(payload)) {
160
- warnings.push(
161
- warning("PARSE_FAILED", "error", "Legacy well-known payload is not an object", {
162
- stage: "well-known/x402"
163
- })
164
- );
165
- return { resources: [], warnings, raw: payload };
166
- }
167
- const resourcesRaw = Array.isArray(payload.resources) ? payload.resources.filter((entry) => typeof entry === "string") : [];
168
- if (resourcesRaw.length === 0) {
169
- warnings.push(
170
- warning("STAGE_EMPTY", "warn", "Legacy well-known has no valid resources array", {
171
- stage: "well-known/x402"
172
- })
173
- );
174
- }
175
- const instructions = typeof payload.instructions === "string" ? payload.instructions : void 0;
176
- const ownershipProofs = Array.isArray(payload.ownershipProofs) ? payload.ownershipProofs.filter((entry) => typeof entry === "string") : [];
177
- if (instructions) {
178
- warnings.push(
179
- warning(
180
- "LEGACY_INSTRUCTIONS_USED",
181
- "warn",
182
- "Using /.well-known/x402.instructions as compatibility guidance fallback. Prefer llms.txt.",
183
- {
184
- stage: "well-known/x402",
185
- hint: "Move guidance to llms.txt and reference via x-discovery.llmsTxtUrl in OpenAPI."
186
- }
187
- )
188
- );
189
- }
190
- if (ownershipProofs.length > 0) {
191
- warnings.push(
192
- warning(
193
- "LEGACY_OWNERSHIP_PROOFS_USED",
194
- "warn",
195
- "Using /.well-known/x402.ownershipProofs compatibility field. Prefer OpenAPI provenance extension.",
196
- {
197
- stage: "well-known/x402",
198
- hint: "Move ownership proofs to x-discovery.ownershipProofs in OpenAPI."
199
- }
200
- )
201
- );
202
- }
203
- const resources = [];
204
- for (const rawEntry of resourcesRaw) {
205
- const parsed = parseLegacyResourceEntry(rawEntry);
206
- if (!parsed) {
207
- warnings.push(
208
- warning("PARSE_FAILED", "warn", `Invalid legacy resource entry: ${rawEntry}`, {
209
- stage: "well-known/x402"
210
- })
211
- );
212
- continue;
213
- }
214
- const absolute = toAbsoluteUrl(origin, parsed.target);
215
- if (!absolute) {
216
- warnings.push(
217
- warning("PARSE_FAILED", "warn", `Invalid legacy resource URL: ${rawEntry}`, {
218
- stage: "well-known/x402"
219
- })
220
- );
221
- continue;
222
- }
223
- const method = parsed.method ?? DEFAULT_MISSING_METHOD;
224
- if (!parsed.method) {
225
- warnings.push(
226
- warning(
227
- "LEGACY_MISSING_METHOD",
228
- "warn",
229
- `Legacy resource '${rawEntry}' missing method. Defaulting to ${DEFAULT_MISSING_METHOD}.`,
230
- {
231
- stage: "well-known/x402"
232
- }
233
- )
159
+ // src/core/source/openapi/index.ts
160
+ var OpenApiParsedSchema = OpenApiDocSchema.transform((doc) => {
161
+ const routes = [];
162
+ for (const [rawPath, pathItem] of Object.entries(doc.paths)) {
163
+ for (const httpMethod of [...HTTP_METHODS]) {
164
+ const operation = pathItem[httpMethod.toLowerCase()];
165
+ if (!operation) continue;
166
+ const authMode = inferAuthMode(operation) ?? void 0;
167
+ if (!authMode) continue;
168
+ const p = operation["x-payment-info"];
169
+ const protocols = (p?.protocols ?? []).filter(
170
+ (proto) => proto !== "mpp" || isMmmEnabled()
234
171
  );
172
+ if ((authMode === "paid" || authMode === "siwx") && !has402Response(operation)) continue;
173
+ if (authMode === "paid" && protocols.length === 0) continue;
174
+ const pricing = authMode === "paid" && p ? {
175
+ pricingMode: p.pricingMode,
176
+ ...p.price ? { price: p.price } : {},
177
+ ...p.minPrice ? { minPrice: p.minPrice } : {},
178
+ ...p.maxPrice ? { maxPrice: p.maxPrice } : {}
179
+ } : void 0;
180
+ const summary = operation.summary ?? operation.description;
181
+ routes.push({
182
+ path: normalizePath(rawPath),
183
+ method: httpMethod.toUpperCase(),
184
+ ...summary ? { summary } : {},
185
+ authMode,
186
+ ...protocols.length ? { protocols } : {},
187
+ ...pricing ? { pricing } : {}
188
+ });
235
189
  }
236
- const path = normalizePath(absolute.pathname);
237
- resources.push(
238
- createResource(
239
- {
240
- origin: absolute.origin,
241
- method,
242
- path,
243
- source: "well-known/x402",
244
- summary: `${method} ${path}`,
245
- authHint: "paid",
246
- protocolHints: ["x402"],
247
- links: {
248
- wellKnownUrl: sourceUrl,
249
- discoveryUrl: sourceUrl
250
- }
251
- },
252
- 0.65,
253
- ownershipProofs.length > 0 ? "ownership_verified" : "origin_hosted"
254
- )
255
- );
256
190
  }
257
191
  return {
258
- resources,
259
- warnings,
260
- raw: payload
192
+ info: {
193
+ title: doc.info.title,
194
+ ...doc.info.description ? { description: doc.info.description } : {},
195
+ version: doc.info.version
196
+ },
197
+ routes,
198
+ ...doc.info.guidance ? { guidance: doc.info.guidance } : {}
261
199
  };
262
- }
263
- async function runWellKnownX402Stage(options) {
264
- const stageUrl = options.url ?? `${options.origin}/.well-known/x402`;
200
+ });
201
+ async function parseBody(response, url) {
265
202
  try {
266
- const response = await options.fetcher(stageUrl, {
267
- method: "GET",
268
- headers: { Accept: "application/json", ...options.headers },
269
- signal: options.signal
270
- });
271
- if (!response.ok) {
272
- if (response.status === 404) {
273
- return {
274
- stage: "well-known/x402",
275
- valid: false,
276
- resources: [],
277
- warnings: [],
278
- links: { wellKnownUrl: stageUrl }
279
- };
280
- }
281
- return {
282
- stage: "well-known/x402",
283
- valid: false,
284
- resources: [],
285
- warnings: [
286
- warning("FETCH_FAILED", "warn", `Legacy well-known fetch failed (${response.status})`, {
287
- stage: "well-known/x402"
288
- })
289
- ],
290
- links: { wellKnownUrl: stageUrl }
291
- };
292
- }
293
203
  const payload = await response.json();
294
- const parsed = parseWellKnownPayload(payload, options.origin, stageUrl);
295
- return {
296
- stage: "well-known/x402",
297
- valid: parsed.resources.length > 0,
298
- resources: parsed.resources,
299
- warnings: parsed.warnings,
300
- links: { wellKnownUrl: stageUrl },
301
- ...options.includeRaw ? { raw: parsed.raw } : {}
302
- };
303
- } catch (error) {
304
- return {
305
- stage: "well-known/x402",
306
- valid: false,
307
- resources: [],
308
- warnings: [
309
- warning(
310
- "FETCH_FAILED",
311
- "warn",
312
- `Legacy well-known fetch exception: ${error instanceof Error ? error.message : String(error)}`,
313
- {
314
- stage: "well-known/x402"
315
- }
316
- )
317
- ],
318
- links: { wellKnownUrl: stageUrl }
319
- };
204
+ const parsed = OpenApiParsedSchema.safeParse(payload);
205
+ if (!parsed.success) return null;
206
+ return { raw: payload, ...parsed.data, fetchedUrl: url };
207
+ } catch {
208
+ return null;
320
209
  }
321
210
  }
322
-
323
- // src/compat/legacy-x402scan/dns.ts
324
- function parseDnsRecord(record) {
325
- const trimmed = record.trim();
326
- if (!trimmed) return null;
327
- if (/^https?:\/\//i.test(trimmed)) {
328
- return { url: trimmed, legacyPlainUrl: true };
329
- }
330
- const parts = trimmed.split(";").map((entry) => entry.trim()).filter(Boolean);
331
- const keyValues = /* @__PURE__ */ new Map();
332
- for (const part of parts) {
333
- const separator = part.indexOf("=");
334
- if (separator <= 0) continue;
335
- const key = part.slice(0, separator).trim().toLowerCase();
336
- const value = part.slice(separator + 1).trim();
337
- if (key && value) keyValues.set(key, value);
338
- }
339
- if (keyValues.get("v") !== "x4021") return null;
340
- const url = keyValues.get("url");
341
- if (!url || !/^https?:\/\//i.test(url)) return null;
342
- return { url, legacyPlainUrl: false };
211
+ function getOpenAPI(origin, headers, signal, specificationOverrideUrl) {
212
+ const url = specificationOverrideUrl ?? `${origin}/openapi.json`;
213
+ return fetchSafe(url, {
214
+ method: "GET",
215
+ headers: { Accept: "application/json", ...headers },
216
+ signal
217
+ }).andThen((response) => {
218
+ if (!response.ok) return okAsync(null);
219
+ return ResultAsync2.fromSafePromise(parseBody(response, url));
220
+ });
343
221
  }
344
- async function runDnsStage(options) {
345
- if (!options.txtResolver) {
346
- return {
347
- stage: "dns/_x402",
348
- valid: false,
349
- resources: [],
350
- warnings: []
351
- };
352
- }
353
- const origin = normalizeOrigin(options.origin);
354
- const hostname = new URL(origin).hostname;
355
- const fqdn = `_x402.${hostname}`;
356
- let records;
357
- try {
358
- records = await options.txtResolver(fqdn);
359
- } catch (error) {
360
- return {
361
- stage: "dns/_x402",
362
- valid: false,
363
- resources: [],
364
- warnings: [
365
- warning(
366
- "FETCH_FAILED",
367
- "warn",
368
- `DNS TXT lookup failed for ${fqdn}: ${error instanceof Error ? error.message : String(error)}`,
369
- { stage: "dns/_x402" }
370
- )
371
- ]
372
- };
373
- }
374
- if (records.length === 0) {
375
- return {
376
- stage: "dns/_x402",
377
- valid: false,
378
- resources: [],
379
- warnings: []
380
- };
381
- }
382
- const warnings = [
383
- warning(
384
- "LEGACY_DNS_USED",
385
- "warn",
386
- "Using DNS _x402 compatibility path. Migrate to OpenAPI-first discovery.",
222
+
223
+ // src/core/source/wellknown/index.ts
224
+ import { okAsync as okAsync2, ResultAsync as ResultAsync3 } from "neverthrow";
225
+ function toWellKnownParsed(origin, doc) {
226
+ const routes = doc.resources.flatMap((entry) => {
227
+ const trimmed = entry.trim();
228
+ if (!trimmed) return [];
229
+ const parts = trimmed.split(/\s+/);
230
+ const maybeMethod = parts.length >= 2 ? parseMethod(parts[0]) : void 0;
231
+ const target = maybeMethod ? parts.slice(1).join(" ") : trimmed;
232
+ const absolute = toAbsoluteUrl(origin, target);
233
+ if (!absolute) return [];
234
+ return [
387
235
  {
388
- stage: "dns/_x402"
236
+ path: normalizePath(absolute.pathname),
237
+ method: maybeMethod ?? DEFAULT_MISSING_METHOD
389
238
  }
390
- )
391
- ];
392
- const urls = [];
393
- for (const record of records) {
394
- const parsed = parseDnsRecord(record);
395
- if (!parsed) {
396
- warnings.push(
397
- warning("PARSE_FAILED", "warn", `Invalid DNS _x402 TXT record: ${record}`, {
398
- stage: "dns/_x402"
399
- })
400
- );
401
- continue;
402
- }
403
- urls.push(parsed.url);
404
- if (parsed.legacyPlainUrl) {
405
- warnings.push(
406
- warning("LEGACY_DNS_PLAIN_URL", "warn", `Legacy plain URL TXT format used: ${record}`, {
407
- stage: "dns/_x402",
408
- hint: "Use v=x4021;url=<https-url> format."
409
- })
410
- );
411
- }
412
- }
413
- if (urls.length === 0) {
414
- return {
415
- stage: "dns/_x402",
416
- valid: false,
417
- resources: [],
418
- warnings,
419
- ...options.includeRaw ? { raw: { dnsRecords: records } } : {}
420
- };
421
- }
422
- const mergedWarnings = [...warnings];
423
- const mergedResources = [];
424
- const rawDocuments = [];
425
- for (const url of urls) {
426
- const stageResult = await runWellKnownX402Stage({
427
- origin,
428
- url,
429
- fetcher: options.fetcher,
430
- headers: options.headers,
431
- signal: options.signal,
432
- includeRaw: options.includeRaw
433
- });
434
- mergedResources.push(...stageResult.resources);
435
- mergedWarnings.push(...stageResult.warnings);
436
- if (options.includeRaw && stageResult.raw !== void 0) {
437
- rawDocuments.push({ url, document: stageResult.raw });
438
- }
439
- }
440
- const deduped = /* @__PURE__ */ new Map();
441
- for (const resource of mergedResources) {
442
- if (!deduped.has(resource.resourceKey)) {
443
- deduped.set(resource.resourceKey, {
444
- ...resource,
445
- source: "dns/_x402",
446
- links: {
447
- ...resource.links,
448
- discoveryUrl: resource.links?.discoveryUrl
449
- }
450
- });
451
- }
452
- }
453
- return {
454
- stage: "dns/_x402",
455
- valid: deduped.size > 0,
456
- resources: [...deduped.values()],
457
- warnings: mergedWarnings,
458
- ...options.includeRaw ? { raw: { dnsRecords: records, documents: rawDocuments } } : {}
459
- };
460
- }
461
-
462
- // src/compat/interop-mpp/wellKnownMpp.ts
463
- function isRecord2(value) {
464
- return value !== null && typeof value === "object" && !Array.isArray(value);
239
+ ];
240
+ });
241
+ return { routes, ...doc.instructions ? { instructions: doc.instructions } : {} };
465
242
  }
466
- async function runInteropMppStage(options) {
467
- const url = `${options.origin}${WELL_KNOWN_MPP_PATH}`;
243
+ async function parseBody2(response, origin, url) {
468
244
  try {
469
- const response = await options.fetcher(url, {
470
- method: "GET",
471
- headers: { Accept: "application/json", ...options.headers },
472
- signal: options.signal
473
- });
474
- if (!response.ok) {
475
- return {
476
- stage: "interop/mpp",
477
- valid: false,
478
- resources: [],
479
- warnings: []
480
- };
481
- }
482
245
  const payload = await response.json();
483
- if (!isRecord2(payload)) {
484
- return {
485
- stage: "interop/mpp",
486
- valid: false,
487
- resources: [],
488
- warnings: [
489
- warning("PARSE_FAILED", "warn", "Interop /.well-known/mpp payload is not an object", {
490
- stage: "interop/mpp"
491
- })
492
- ],
493
- ...options.includeRaw ? { raw: payload } : {}
494
- };
495
- }
496
- const warnings = [
497
- warning(
498
- "INTEROP_MPP_USED",
499
- "info",
500
- "Using /.well-known/mpp interop adapter. This is additive and non-canonical.",
501
- {
502
- stage: "interop/mpp",
503
- hint: "Use for registry indexing only, not canonical runtime routing."
504
- }
505
- )
506
- ];
507
- const resources = [];
508
- const fromStringResources = Array.isArray(payload.resources) ? payload.resources.filter((entry) => typeof entry === "string") : [];
509
- for (const entry of fromStringResources) {
510
- const parts = entry.trim().split(/\s+/);
511
- let method = parseMethod(parts[0]);
512
- let path = parts.join(" ");
513
- if (method) {
514
- path = parts.slice(1).join(" ");
515
- } else {
516
- method = "POST";
517
- }
518
- const normalizedPath = normalizePath(path);
519
- resources.push(
520
- createResource(
521
- {
522
- origin: options.origin,
523
- method,
524
- path: normalizedPath,
525
- source: "interop/mpp",
526
- summary: `${method} ${normalizedPath}`,
527
- authHint: "paid",
528
- protocolHints: ["mpp"],
529
- links: { discoveryUrl: url }
530
- },
531
- 0.45,
532
- "unverified"
533
- )
534
- );
535
- }
536
- const fromServiceObjects = Array.isArray(payload.services) ? payload.services.filter((entry) => isRecord2(entry)) : [];
537
- for (const service of fromServiceObjects) {
538
- const path = typeof service.path === "string" ? service.path : void 0;
539
- const method = parseMethod(typeof service.method === "string" ? service.method : void 0) ?? "POST";
540
- if (!path) continue;
541
- const normalizedPath = normalizePath(path);
542
- resources.push(
543
- createResource(
544
- {
545
- origin: options.origin,
546
- method,
547
- path: normalizedPath,
548
- source: "interop/mpp",
549
- summary: typeof service.summary === "string" ? service.summary : `${method} ${normalizedPath}`,
550
- authHint: "paid",
551
- protocolHints: ["mpp"],
552
- links: { discoveryUrl: url }
553
- },
554
- 0.45,
555
- "unverified"
556
- )
557
- );
558
- }
559
- const deduped = /* @__PURE__ */ new Map();
560
- for (const resource of resources) {
561
- if (!deduped.has(resource.resourceKey)) deduped.set(resource.resourceKey, resource);
562
- }
563
- return {
564
- stage: "interop/mpp",
565
- valid: deduped.size > 0,
566
- resources: [...deduped.values()],
567
- warnings,
568
- ...options.includeRaw ? { raw: payload } : {}
569
- };
570
- } catch (error) {
571
- return {
572
- stage: "interop/mpp",
573
- valid: false,
574
- resources: [],
575
- warnings: [
576
- warning(
577
- "FETCH_FAILED",
578
- "warn",
579
- `Interop /.well-known/mpp fetch failed: ${error instanceof Error ? error.message : String(error)}`,
580
- {
581
- stage: "interop/mpp"
582
- }
583
- )
584
- ]
585
- };
246
+ const doc = WellKnownDocSchema.safeParse(payload);
247
+ if (!doc.success) return null;
248
+ const parsed = WellKnownParsedSchema.safeParse(toWellKnownParsed(origin, doc.data));
249
+ if (!parsed.success) return null;
250
+ return { raw: payload, ...parsed.data, fetchedUrl: url };
251
+ } catch {
252
+ return null;
586
253
  }
587
254
  }
588
-
589
- // src/core/token.ts
590
- function estimateTokenCount(text) {
591
- return Math.ceil(text.length / 4);
255
+ function getWellKnown(origin, headers, signal) {
256
+ const url = `${origin}/.well-known/x402`;
257
+ return fetchSafe(url, {
258
+ method: "GET",
259
+ headers: { Accept: "application/json", ...headers },
260
+ signal
261
+ }).andThen((response) => {
262
+ if (!response.ok) return okAsync2(null);
263
+ return ResultAsync3.fromSafePromise(parseBody2(response, origin, url));
264
+ });
592
265
  }
593
266
 
594
- // src/core/openapi-utils.ts
595
- function isRecord3(value) {
596
- return value !== null && typeof value === "object" && !Array.isArray(value);
267
+ // src/core/layers/l2.ts
268
+ function formatPrice(pricing) {
269
+ if (pricing.pricingMode === "fixed") return `$${pricing.price}`;
270
+ if (pricing.pricingMode === "range") return `$${pricing.minPrice}-$${pricing.maxPrice}`;
271
+ return pricing.maxPrice ? `up to $${pricing.maxPrice}` : "quote";
272
+ }
273
+ function checkL2ForOpenAPI(openApi) {
274
+ const routes = openApi.routes.map((route) => ({
275
+ path: route.path,
276
+ method: route.method,
277
+ summary: route.summary ?? `${route.method} ${route.path}`,
278
+ ...route.authMode ? { authMode: route.authMode } : {},
279
+ ...route.pricing ? { price: formatPrice(route.pricing) } : {},
280
+ ...route.protocols?.length ? { protocols: route.protocols } : {}
281
+ }));
282
+ return {
283
+ ...openApi.info.title ? { title: openApi.info.title } : {},
284
+ ...openApi.info.description ? { description: openApi.info.description } : {},
285
+ routes,
286
+ source: "openapi"
287
+ };
597
288
  }
598
- function hasSecurity(operation, scheme) {
599
- const security = operation.security;
600
- return Array.isArray(security) && security.some((s) => isRecord3(s) && scheme in s);
289
+ function checkL2ForWellknown(wellKnown) {
290
+ const routes = wellKnown.routes.map((route) => ({
291
+ path: route.path,
292
+ method: route.method,
293
+ summary: `${route.method} ${route.path}`,
294
+ authMode: "paid",
295
+ protocols: ["x402"]
296
+ }));
297
+ return { routes, source: "well-known/x402" };
601
298
  }
602
- function has402Response(operation) {
603
- const responses = operation.responses;
604
- if (!isRecord3(responses)) return false;
605
- return Boolean(responses["402"]);
299
+
300
+ // src/core/layers/l4.ts
301
+ function checkL4ForOpenAPI(openApi) {
302
+ if (openApi.guidance) {
303
+ return { guidance: openApi.guidance, source: "openapi" };
304
+ }
305
+ return null;
606
306
  }
607
- function inferAuthMode(operation) {
608
- if (isRecord3(operation["x-payment-info"])) return "paid";
609
- if (has402Response(operation)) {
610
- if (hasSecurity(operation, "siwx")) return "siwx";
611
- return "paid";
307
+ function checkL4ForWellknown(wellKnown) {
308
+ if (wellKnown.instructions) {
309
+ return { guidance: wellKnown.instructions, source: "well-known/x402" };
612
310
  }
613
- if (hasSecurity(operation, "apiKey")) return "apiKey";
614
- if (hasSecurity(operation, "siwx")) return "siwx";
615
- return void 0;
311
+ return null;
616
312
  }
617
313
 
618
- // src/core/openapi.ts
619
- function asString(value) {
620
- return typeof value === "string" && value.length > 0 ? value : void 0;
621
- }
622
- function parsePriceValue(value) {
623
- if (typeof value === "string" && value.length > 0) return value;
624
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
625
- return void 0;
314
+ // src/core/lib/tokens.ts
315
+ function estimateTokenCount(text) {
316
+ return Math.ceil(text.length / 4);
626
317
  }
627
- function parseProtocols(paymentInfo) {
628
- const protocols = paymentInfo.protocols;
629
- if (!Array.isArray(protocols)) return [];
630
- return protocols.filter(
631
- (entry) => typeof entry === "string" && entry.length > 0
318
+
319
+ // src/core/types/discover.ts
320
+ var GuidanceMode = /* @__PURE__ */ ((GuidanceMode2) => {
321
+ GuidanceMode2["Auto"] = "auto";
322
+ GuidanceMode2["Always"] = "always";
323
+ GuidanceMode2["Never"] = "never";
324
+ return GuidanceMode2;
325
+ })(GuidanceMode || {});
326
+
327
+ // src/runtime/discover.ts
328
+ var GUIDANCE_AUTO_INCLUDE_MAX_TOKENS_LENGTH = 1e3;
329
+ function withGuidance(base, l4, guidanceMode) {
330
+ if (guidanceMode === "never" /* Never */) return { ...base, guidanceAvailable: !!l4 };
331
+ if (!l4) return { ...base, guidanceAvailable: false };
332
+ const tokens = estimateTokenCount(l4.guidance);
333
+ if (guidanceMode === "always" /* Always */ || tokens <= GUIDANCE_AUTO_INCLUDE_MAX_TOKENS_LENGTH) {
334
+ return { ...base, guidanceAvailable: true, guidanceTokens: tokens, guidance: l4.guidance };
335
+ }
336
+ return { ...base, guidanceAvailable: true, guidanceTokens: tokens };
337
+ }
338
+ async function discoverOriginSchema(options) {
339
+ const origin = normalizeOrigin(options.target);
340
+ const guidanceMode = options.guidance ?? "auto" /* Auto */;
341
+ const openApiResult = await getOpenAPI(
342
+ origin,
343
+ options.headers,
344
+ options.signal,
345
+ options.specificationOverrideUrl
632
346
  );
633
- }
634
- async function runOpenApiStage(options) {
635
- const warnings = [];
636
- const resources = [];
637
- let fetchedUrl;
638
- let document;
639
- for (const path of OPENAPI_PATH_CANDIDATES) {
640
- const url = `${options.origin}${path}`;
641
- try {
642
- const response = await options.fetcher(url, {
643
- method: "GET",
644
- headers: { Accept: "application/json", ...options.headers },
645
- signal: options.signal
646
- });
647
- if (!response.ok) {
648
- if (response.status !== 404) {
649
- warnings.push(
650
- warning("FETCH_FAILED", "warn", `OpenAPI fetch failed (${response.status}) at ${url}`, {
651
- stage: "openapi"
652
- })
653
- );
654
- }
655
- continue;
656
- }
657
- const payload = await response.json();
658
- if (!isRecord3(payload)) {
659
- warnings.push(
660
- warning("PARSE_FAILED", "error", `OpenAPI payload at ${url} is not a JSON object`, {
661
- stage: "openapi"
662
- })
663
- );
664
- continue;
665
- }
666
- document = payload;
667
- fetchedUrl = url;
668
- break;
669
- } catch (error) {
670
- warnings.push(
671
- warning(
672
- "FETCH_FAILED",
673
- "warn",
674
- `OpenAPI fetch exception at ${url}: ${error instanceof Error ? error.message : String(error)}`,
675
- { stage: "openapi" }
676
- )
677
- );
678
- }
679
- }
680
- if (!document || !fetchedUrl) {
681
- return {
682
- stage: "openapi",
683
- valid: false,
684
- resources: [],
685
- warnings
347
+ const openApi = openApiResult.isOk() ? openApiResult.value : null;
348
+ if (openApi) {
349
+ const l22 = checkL2ForOpenAPI(openApi);
350
+ const l42 = checkL4ForOpenAPI(openApi);
351
+ const base2 = {
352
+ found: true,
353
+ origin,
354
+ source: "openapi",
355
+ ...l22.title ? { info: { title: l22.title, ...l22.description ? { description: l22.description } : {} } } : {},
356
+ endpoints: l22.routes
686
357
  };
358
+ return withGuidance(base2, l42, guidanceMode);
687
359
  }
688
- const hasTopLevel = typeof document.openapi === "string" && isRecord3(document.info) && typeof document.info.title === "string" && typeof document.info.version === "string" && isRecord3(document.paths);
689
- if (!hasTopLevel) {
690
- warnings.push(
691
- warning("OPENAPI_TOP_LEVEL_INVALID", "error", "OpenAPI required fields are missing", {
692
- stage: "openapi"
693
- })
694
- );
360
+ const wellKnownResult = await getWellKnown(origin, options.headers, options.signal);
361
+ if (wellKnownResult.isErr()) {
695
362
  return {
696
- stage: "openapi",
697
- valid: false,
698
- resources: [],
699
- warnings,
700
- links: { openapiUrl: fetchedUrl },
701
- ...options.includeRaw ? { raw: document } : {}
363
+ found: false,
364
+ origin,
365
+ cause: wellKnownResult.error.cause,
366
+ message: wellKnownResult.error.message
702
367
  };
703
368
  }
704
- const paths = document.paths;
705
- const discovery = isRecord3(document["x-discovery"]) ? document["x-discovery"] : void 0;
706
- const ownershipProofs = Array.isArray(discovery?.ownershipProofs) ? discovery.ownershipProofs.filter((entry) => typeof entry === "string") : [];
707
- const llmsTxtUrl = asString(discovery?.llmsTxtUrl);
708
- if (ownershipProofs.length > 0) {
709
- warnings.push(
710
- warning("OPENAPI_OWNERSHIP_PROOFS_PRESENT", "info", "OpenAPI ownership proofs detected", {
711
- stage: "openapi"
712
- })
713
- );
714
- }
715
- for (const [rawPath, rawPathItem] of Object.entries(paths)) {
716
- if (!isRecord3(rawPathItem)) {
717
- warnings.push(
718
- warning("OPENAPI_OPERATION_INVALID", "warn", `Path item ${rawPath} is not an object`, {
719
- stage: "openapi"
720
- })
721
- );
722
- continue;
723
- }
724
- for (const [rawMethod, rawOperation] of Object.entries(rawPathItem)) {
725
- const method = parseMethod(rawMethod);
726
- if (!method) continue;
727
- if (!isRecord3(rawOperation)) {
728
- warnings.push(
729
- warning(
730
- "OPENAPI_OPERATION_INVALID",
731
- "warn",
732
- `${rawMethod.toUpperCase()} ${rawPath} is not an object`,
733
- {
734
- stage: "openapi"
735
- }
736
- )
737
- );
738
- continue;
739
- }
740
- const operation = rawOperation;
741
- const summary = asString(operation.summary) ?? asString(operation.description);
742
- if (!summary) {
743
- warnings.push(
744
- warning(
745
- "OPENAPI_SUMMARY_MISSING",
746
- "warn",
747
- `${method} ${rawPath} missing summary/description, using fallback summary`,
748
- { stage: "openapi" }
749
- )
750
- );
751
- }
752
- const authMode = inferAuthMode(operation);
753
- if (!authMode) {
754
- warnings.push(
755
- warning(
756
- "OPENAPI_AUTH_MODE_MISSING",
757
- "error",
758
- `${method} ${rawPath} missing auth mode (no x-payment-info, 402 response, or security scheme)`,
759
- {
760
- stage: "openapi"
761
- }
762
- )
763
- );
764
- continue;
765
- }
766
- if ((authMode === "paid" || authMode === "siwx") && !has402Response(operation)) {
767
- warnings.push(
768
- warning(
769
- "OPENAPI_402_MISSING",
770
- "error",
771
- `${method} ${rawPath} requires 402 response for authMode=${authMode}`,
772
- { stage: "openapi" }
773
- )
774
- );
775
- continue;
776
- }
777
- const paymentInfo = isRecord3(operation["x-payment-info"]) ? operation["x-payment-info"] : void 0;
778
- const protocols = paymentInfo ? parseProtocols(paymentInfo) : [];
779
- if (authMode === "paid" && protocols.length === 0) {
780
- warnings.push(
781
- warning(
782
- "OPENAPI_PAID_PROTOCOLS_MISSING",
783
- "error",
784
- `${method} ${rawPath} must define x-payment-info.protocols when authMode=paid`,
785
- { stage: "openapi" }
786
- )
787
- );
788
- continue;
789
- }
790
- let pricing;
791
- let priceHint;
792
- if (paymentInfo && authMode === "paid") {
793
- const pricingModeRaw = asString(paymentInfo.pricingMode);
794
- const price = parsePriceValue(paymentInfo.price);
795
- const minPrice = parsePriceValue(paymentInfo.minPrice);
796
- const maxPrice = parsePriceValue(paymentInfo.maxPrice);
797
- const inferredPricingMode = pricingModeRaw ?? (price ? "fixed" : minPrice && maxPrice ? "range" : "quote");
798
- if (inferredPricingMode !== "fixed" && inferredPricingMode !== "range" && inferredPricingMode !== "quote") {
799
- warnings.push(
800
- warning(
801
- "OPENAPI_PRICING_INVALID",
802
- "error",
803
- `${method} ${rawPath} has invalid pricingMode`,
804
- {
805
- stage: "openapi"
806
- }
807
- )
808
- );
809
- continue;
810
- }
811
- if (inferredPricingMode === "fixed" && !price) {
812
- warnings.push(
813
- warning(
814
- "OPENAPI_PRICING_INVALID",
815
- "error",
816
- `${method} ${rawPath} fixed pricing requires price`,
817
- {
818
- stage: "openapi"
819
- }
820
- )
821
- );
822
- continue;
823
- }
824
- if (inferredPricingMode === "range") {
825
- if (!minPrice || !maxPrice) {
826
- warnings.push(
827
- warning(
828
- "OPENAPI_PRICING_INVALID",
829
- "error",
830
- `${method} ${rawPath} range pricing requires minPrice and maxPrice`,
831
- { stage: "openapi" }
832
- )
833
- );
834
- continue;
835
- }
836
- const min = Number(minPrice);
837
- const max = Number(maxPrice);
838
- if (!Number.isFinite(min) || !Number.isFinite(max) || min > max) {
839
- warnings.push(
840
- warning(
841
- "OPENAPI_PRICING_INVALID",
842
- "error",
843
- `${method} ${rawPath} range pricing requires numeric minPrice <= maxPrice`,
844
- { stage: "openapi" }
845
- )
846
- );
847
- continue;
848
- }
849
- }
850
- pricing = {
851
- pricingMode: inferredPricingMode,
852
- ...price ? { price } : {},
853
- ...minPrice ? { minPrice } : {},
854
- ...maxPrice ? { maxPrice } : {}
855
- };
856
- priceHint = inferredPricingMode === "fixed" ? price : inferredPricingMode === "range" ? `${minPrice}-${maxPrice}` : maxPrice;
857
- }
858
- const resource = createResource(
859
- {
860
- origin: options.origin,
861
- method,
862
- path: normalizePath(rawPath),
863
- source: "openapi",
864
- summary: summary ?? `${method} ${normalizePath(rawPath)}`,
865
- authHint: authMode,
866
- protocolHints: protocols,
867
- ...priceHint ? { priceHint } : {},
868
- ...pricing ? { pricing } : {},
869
- links: {
870
- openapiUrl: fetchedUrl,
871
- ...llmsTxtUrl ? { llmsTxtUrl } : {}
872
- }
873
- },
874
- 0.95,
875
- ownershipProofs.length > 0 ? "ownership_verified" : "origin_hosted"
876
- );
877
- resources.push(resource);
878
- }
879
- }
880
- if (llmsTxtUrl) {
881
- try {
882
- const llmsResponse = await options.fetcher(llmsTxtUrl, {
883
- method: "GET",
884
- headers: { Accept: "text/plain", ...options.headers },
885
- signal: options.signal
886
- });
887
- if (llmsResponse.ok) {
888
- const llmsText = await llmsResponse.text();
889
- const tokenCount = estimateTokenCount(llmsText);
890
- if (tokenCount > LLMS_TOKEN_WARNING_THRESHOLD) {
891
- warnings.push(
892
- warning(
893
- "LLMSTXT_TOO_LARGE",
894
- "warn",
895
- `llms.txt estimated ${tokenCount} tokens (threshold ${LLMS_TOKEN_WARNING_THRESHOLD})`,
896
- {
897
- stage: "openapi",
898
- hint: "Keep llms.txt concise and domain-level only."
899
- }
900
- )
901
- );
902
- }
903
- if (options.includeRaw) {
904
- return {
905
- stage: "openapi",
906
- valid: resources.length > 0,
907
- resources,
908
- warnings,
909
- links: { openapiUrl: fetchedUrl, llmsTxtUrl },
910
- raw: {
911
- openapi: document,
912
- llmsTxt: llmsText
913
- }
914
- };
915
- }
916
- } else {
917
- warnings.push(
918
- warning(
919
- "LLMSTXT_FETCH_FAILED",
920
- "warn",
921
- `llms.txt fetch failed (${llmsResponse.status})`,
922
- {
923
- stage: "openapi"
924
- }
925
- )
926
- );
927
- }
928
- } catch (error) {
929
- warnings.push(
930
- warning(
931
- "LLMSTXT_FETCH_FAILED",
932
- "warn",
933
- `llms.txt fetch failed: ${error instanceof Error ? error.message : String(error)}`,
934
- { stage: "openapi" }
935
- )
936
- );
937
- }
938
- }
369
+ const wellKnown = wellKnownResult.value;
370
+ if (!wellKnown) return { found: false, origin, cause: "not_found" };
371
+ const l2 = checkL2ForWellknown(wellKnown);
372
+ const l4 = checkL4ForWellknown(wellKnown);
373
+ const base = {
374
+ found: true,
375
+ origin,
376
+ source: "well-known/x402",
377
+ endpoints: l2.routes
378
+ };
379
+ return withGuidance(base, l4, guidanceMode);
380
+ }
381
+
382
+ // src/core/source/probe/index.ts
383
+ import { ResultAsync as ResultAsync4 } from "neverthrow";
384
+
385
+ // src/core/protocols/x402/v1/schema.ts
386
+ function extractSchemas(accepts) {
387
+ const first = accepts[0];
388
+ if (!isRecord(first)) return {};
389
+ const outputSchema = isRecord(first.outputSchema) ? first.outputSchema : void 0;
939
390
  return {
940
- stage: "openapi",
941
- valid: resources.length > 0,
942
- resources,
943
- warnings,
944
- links: {
945
- openapiUrl: fetchedUrl,
946
- ...llmsTxtUrl ? { llmsTxtUrl } : {}
947
- },
948
- ...options.includeRaw ? { raw: { openapi: document } } : {}
391
+ ...outputSchema && isRecord(outputSchema.input) ? { inputSchema: outputSchema.input } : {},
392
+ ...outputSchema && isRecord(outputSchema.output) ? { outputSchema: outputSchema.output } : {}
949
393
  };
950
394
  }
951
395
 
952
- // src/core/probe.ts
953
- function detectAuthHintFrom402Payload(payload) {
954
- if (payload && typeof payload === "object") {
955
- const asRecord = payload;
956
- const extensions = asRecord.extensions;
957
- if (extensions && typeof extensions === "object") {
958
- const extRecord = extensions;
959
- if (extRecord["sign-in-with-x"]) return "siwx";
960
- }
961
- }
962
- return "paid";
396
+ // src/core/protocols/x402/shared.ts
397
+ function asNonEmptyString(value) {
398
+ if (typeof value !== "string") return void 0;
399
+ const trimmed = value.trim();
400
+ return trimmed.length > 0 ? trimmed : void 0;
963
401
  }
964
- function detectProtocols(response) {
965
- const protocols = /* @__PURE__ */ new Set();
966
- const directHeader = response.headers.get("x-payment-protocol");
967
- if (directHeader) {
968
- for (const part of directHeader.split(",")) {
969
- const protocol = part.trim().toLowerCase();
970
- if (protocol) protocols.add(protocol);
971
- }
972
- }
973
- const authHeader = response.headers.get("www-authenticate")?.toLowerCase() ?? "";
974
- if (authHeader.includes("x402")) protocols.add("x402");
402
+ function asPositiveNumber(value) {
403
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
404
+ }
405
+ function pushIssue(issues, issue) {
406
+ issues.push({ stage: "payment_required", ...issue });
407
+ }
408
+
409
+ // src/core/protocols/x402/v1/network.ts
410
+ function validateNetwork(networkRaw, index, issues) {
411
+ if (networkRaw === "solana-mainnet-beta") {
412
+ pushIssue(issues, {
413
+ code: "NETWORK_SOLANA_ALIAS_INVALID",
414
+ severity: "error",
415
+ message: `Accept at index ${index} uses invalid Solana network alias`,
416
+ hint: "Use 'solana' (v1) or canonical Solana CAIP reference (v2).",
417
+ path: `accepts[${index}].network`,
418
+ expected: "solana",
419
+ actual: networkRaw
420
+ });
421
+ return void 0;
422
+ }
423
+ if (networkRaw.startsWith("solana-") && networkRaw !== "solana-devnet") {
424
+ pushIssue(issues, {
425
+ code: "NETWORK_SOLANA_ALIAS_INVALID",
426
+ severity: "error",
427
+ message: `Accept at index ${index} uses unsupported Solana network alias`,
428
+ hint: "Use 'solana' or 'solana-devnet' for v1 payloads.",
429
+ path: `accepts[${index}].network`,
430
+ actual: networkRaw
431
+ });
432
+ return void 0;
433
+ }
434
+ return networkRaw;
435
+ }
436
+
437
+ // src/core/protocols/x402/v1/accepts.ts
438
+ function validateAccept(acceptRaw, index, issues) {
439
+ if (!isRecord(acceptRaw)) {
440
+ pushIssue(issues, {
441
+ code: "X402_ACCEPT_ENTRY_INVALID",
442
+ severity: "error",
443
+ message: `Accept at index ${index} must be an object`,
444
+ path: `accepts[${index}]`
445
+ });
446
+ return null;
447
+ }
448
+ const scheme = asNonEmptyString(acceptRaw.scheme);
449
+ const networkRaw = asNonEmptyString(acceptRaw.network);
450
+ const payTo = asNonEmptyString(acceptRaw.payTo);
451
+ const asset = asNonEmptyString(acceptRaw.asset);
452
+ const amount = asNonEmptyString(acceptRaw.maxAmountRequired);
453
+ const maxTimeoutSeconds = asPositiveNumber(acceptRaw.maxTimeoutSeconds);
454
+ if (!scheme)
455
+ pushIssue(issues, {
456
+ code: "X402_ACCEPT_ENTRY_INVALID",
457
+ severity: "error",
458
+ message: `Accept at index ${index} is missing scheme`,
459
+ path: `accepts[${index}].scheme`
460
+ });
461
+ if (!networkRaw)
462
+ pushIssue(issues, {
463
+ code: "X402_ACCEPT_ENTRY_INVALID",
464
+ severity: "error",
465
+ message: `Accept at index ${index} is missing network`,
466
+ path: `accepts[${index}].network`
467
+ });
468
+ if (!amount)
469
+ pushIssue(issues, {
470
+ code: "X402_ACCEPT_ENTRY_INVALID",
471
+ severity: "error",
472
+ message: `Accept at index ${index} is missing maxAmountRequired`,
473
+ path: `accepts[${index}].maxAmountRequired`
474
+ });
475
+ if (!payTo)
476
+ pushIssue(issues, {
477
+ code: "X402_ACCEPT_ENTRY_INVALID",
478
+ severity: "error",
479
+ message: `Accept at index ${index} is missing payTo`,
480
+ path: `accepts[${index}].payTo`
481
+ });
482
+ if (!asset)
483
+ pushIssue(issues, {
484
+ code: "X402_ACCEPT_ENTRY_INVALID",
485
+ severity: "error",
486
+ message: `Accept at index ${index} is missing asset`,
487
+ path: `accepts[${index}].asset`
488
+ });
489
+ if (!maxTimeoutSeconds)
490
+ pushIssue(issues, {
491
+ code: "X402_ACCEPT_ENTRY_INVALID",
492
+ severity: "error",
493
+ message: `Accept at index ${index} is missing or has invalid maxTimeoutSeconds`,
494
+ path: `accepts[${index}].maxTimeoutSeconds`
495
+ });
496
+ const normalizedNetwork = networkRaw ? validateNetwork(networkRaw, index, issues) : void 0;
497
+ return {
498
+ index,
499
+ network: normalizedNetwork ?? networkRaw ?? "unknown",
500
+ networkRaw: networkRaw ?? "unknown",
501
+ scheme,
502
+ asset,
503
+ payTo,
504
+ amount,
505
+ maxTimeoutSeconds
506
+ };
507
+ }
508
+ function validateAccepts(accepts, issues) {
509
+ return accepts.flatMap((accept, index) => {
510
+ const result = validateAccept(accept, index, issues);
511
+ return result ? [result] : [];
512
+ });
513
+ }
514
+
515
+ // src/core/protocols/x402/v1/payment-options.ts
516
+ function extractPaymentOptions(accepts) {
517
+ return accepts.flatMap((accept) => {
518
+ if (!isRecord(accept)) return [];
519
+ const network = asNonEmptyString(accept.network);
520
+ const asset = asNonEmptyString(accept.asset);
521
+ const maxAmountRequired = asNonEmptyString(accept.maxAmountRequired);
522
+ if (!network || !asset || !maxAmountRequired) return [];
523
+ const scheme = asNonEmptyString(accept.scheme);
524
+ const payTo = asNonEmptyString(accept.payTo);
525
+ const maxTimeoutSeconds = asPositiveNumber(accept.maxTimeoutSeconds);
526
+ return [
527
+ {
528
+ protocol: "x402",
529
+ version: 1,
530
+ network,
531
+ asset,
532
+ maxAmountRequired,
533
+ ...scheme ? { scheme } : {},
534
+ ...payTo ? { payTo } : {},
535
+ ...maxTimeoutSeconds ? { maxTimeoutSeconds } : {}
536
+ }
537
+ ];
538
+ });
539
+ }
540
+
541
+ // src/core/protocols/x402/v2/schema.ts
542
+ function extractSchemas2(payload) {
543
+ if (!isRecord(payload)) return {};
544
+ const extensions = isRecord(payload.extensions) ? payload.extensions : void 0;
545
+ const bazaar = extensions && isRecord(extensions.bazaar) ? extensions.bazaar : void 0;
546
+ const schema = bazaar && isRecord(bazaar.schema) ? bazaar.schema : void 0;
547
+ if (!schema) return {};
548
+ const schemaProps = isRecord(schema.properties) ? schema.properties : void 0;
549
+ if (!schemaProps) return {};
550
+ const inputProps = isRecord(schemaProps.input) ? schemaProps.input : void 0;
551
+ const inputProperties = inputProps && isRecord(inputProps.properties) ? inputProps.properties : void 0;
552
+ const inputSchema = (inputProperties && isRecord(inputProperties.body) ? inputProperties.body : void 0) ?? (inputProperties && isRecord(inputProperties.queryParams) ? inputProperties.queryParams : void 0);
553
+ const outputProps = isRecord(schemaProps.output) ? schemaProps.output : void 0;
554
+ const outputProperties = outputProps && isRecord(outputProps.properties) ? outputProps.properties : void 0;
555
+ const outputSchema = outputProperties && isRecord(outputProperties.example) ? outputProperties.example : void 0;
556
+ return {
557
+ ...inputSchema ? { inputSchema } : {},
558
+ ...outputSchema ? { outputSchema } : {}
559
+ };
560
+ }
561
+
562
+ // src/core/protocols/x402/v2/solana.ts
563
+ var CANONICAL_BY_REF = {
564
+ "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "solana",
565
+ EtWTRABZaYq6iMfeYKouRu166VU2xqa1: "solana-devnet",
566
+ "4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z": "solana-testnet"
567
+ };
568
+ var ALIAS_BY_REF = {
569
+ mainnet: "solana",
570
+ devnet: "solana-devnet",
571
+ testnet: "solana-testnet"
572
+ };
573
+ function validateSolanaReference(reference, networkRaw, index, issues) {
574
+ const canonical = CANONICAL_BY_REF[reference];
575
+ if (canonical) return canonical;
576
+ const alias = ALIAS_BY_REF[reference];
577
+ if (alias) {
578
+ pushIssue(issues, {
579
+ code: "NETWORK_SOLANA_ALIAS_COMPAT",
580
+ severity: "warn",
581
+ message: `Accept at index ${index} uses compatibility Solana reference '${reference}'`,
582
+ hint: "Use canonical Solana CAIP references for deterministic behavior.",
583
+ path: `accepts[${index}].network`,
584
+ actual: networkRaw
585
+ });
586
+ return alias;
587
+ }
588
+ pushIssue(issues, {
589
+ code: "NETWORK_REFERENCE_UNKNOWN",
590
+ severity: "error",
591
+ message: `Accept at index ${index} uses unknown Solana reference '${reference}'`,
592
+ hint: "Use canonical references for mainnet/devnet/testnet.",
593
+ path: `accepts[${index}].network`,
594
+ actual: networkRaw
595
+ });
596
+ return void 0;
597
+ }
598
+
599
+ // src/core/protocols/x402/v2/network.ts
600
+ function validateNetwork2(networkRaw, index, issues) {
601
+ if (!/^[^:\s]+:[^:\s]+$/.test(networkRaw)) {
602
+ pushIssue(issues, {
603
+ code: "NETWORK_CAIP2_INVALID",
604
+ severity: "error",
605
+ message: `Accept at index ${index} has invalid CAIP-2 network format`,
606
+ hint: "Expected '<namespace>:<reference>', e.g. 'eip155:8453' or 'solana:5eykt4...'.",
607
+ path: `accepts[${index}].network`,
608
+ expected: "<namespace>:<reference>",
609
+ actual: networkRaw
610
+ });
611
+ return void 0;
612
+ }
613
+ const [namespace, reference] = networkRaw.split(":");
614
+ if (namespace === "eip155") {
615
+ if (!/^\d+$/.test(reference)) {
616
+ pushIssue(issues, {
617
+ code: "NETWORK_EIP155_REFERENCE_INVALID",
618
+ severity: "error",
619
+ message: `Accept at index ${index} has invalid eip155 reference`,
620
+ hint: "Use a numeric chain id, e.g. 'eip155:8453'.",
621
+ path: `accepts[${index}].network`,
622
+ expected: "eip155:<numeric-chain-id>",
623
+ actual: networkRaw
624
+ });
625
+ return void 0;
626
+ }
627
+ return networkRaw;
628
+ }
629
+ if (namespace === "solana") {
630
+ return validateSolanaReference(reference, networkRaw, index, issues);
631
+ }
632
+ return networkRaw;
633
+ }
634
+
635
+ // src/core/protocols/x402/v2/accepts.ts
636
+ function validateAccept2(acceptRaw, index, issues) {
637
+ if (!isRecord(acceptRaw)) {
638
+ pushIssue(issues, {
639
+ code: "X402_ACCEPT_ENTRY_INVALID",
640
+ severity: "error",
641
+ message: `Accept at index ${index} must be an object`,
642
+ path: `accepts[${index}]`
643
+ });
644
+ return null;
645
+ }
646
+ const scheme = asNonEmptyString(acceptRaw.scheme);
647
+ const networkRaw = asNonEmptyString(acceptRaw.network);
648
+ const payTo = asNonEmptyString(acceptRaw.payTo);
649
+ const asset = asNonEmptyString(acceptRaw.asset);
650
+ const amount = asNonEmptyString(acceptRaw.amount);
651
+ const maxTimeoutSeconds = asPositiveNumber(acceptRaw.maxTimeoutSeconds);
652
+ if (!scheme)
653
+ pushIssue(issues, {
654
+ code: "X402_ACCEPT_ENTRY_INVALID",
655
+ severity: "error",
656
+ message: `Accept at index ${index} is missing scheme`,
657
+ path: `accepts[${index}].scheme`
658
+ });
659
+ if (!networkRaw)
660
+ pushIssue(issues, {
661
+ code: "X402_ACCEPT_ENTRY_INVALID",
662
+ severity: "error",
663
+ message: `Accept at index ${index} is missing network`,
664
+ path: `accepts[${index}].network`
665
+ });
666
+ if (!amount)
667
+ pushIssue(issues, {
668
+ code: "X402_ACCEPT_ENTRY_INVALID",
669
+ severity: "error",
670
+ message: `Accept at index ${index} is missing amount`,
671
+ path: `accepts[${index}].amount`
672
+ });
673
+ if (!payTo)
674
+ pushIssue(issues, {
675
+ code: "X402_ACCEPT_ENTRY_INVALID",
676
+ severity: "error",
677
+ message: `Accept at index ${index} is missing payTo`,
678
+ path: `accepts[${index}].payTo`
679
+ });
680
+ if (!asset)
681
+ pushIssue(issues, {
682
+ code: "X402_ACCEPT_ENTRY_INVALID",
683
+ severity: "error",
684
+ message: `Accept at index ${index} is missing asset`,
685
+ path: `accepts[${index}].asset`
686
+ });
687
+ if (!maxTimeoutSeconds)
688
+ pushIssue(issues, {
689
+ code: "X402_ACCEPT_ENTRY_INVALID",
690
+ severity: "error",
691
+ message: `Accept at index ${index} is missing or has invalid maxTimeoutSeconds`,
692
+ path: `accepts[${index}].maxTimeoutSeconds`
693
+ });
694
+ const normalizedNetwork = networkRaw ? validateNetwork2(networkRaw, index, issues) : void 0;
695
+ return {
696
+ index,
697
+ network: normalizedNetwork ?? networkRaw ?? "unknown",
698
+ networkRaw: networkRaw ?? "unknown",
699
+ scheme,
700
+ asset,
701
+ payTo,
702
+ amount,
703
+ maxTimeoutSeconds
704
+ };
705
+ }
706
+ function validateAccepts2(accepts, issues) {
707
+ return accepts.flatMap((accept, index) => {
708
+ const result = validateAccept2(accept, index, issues);
709
+ return result ? [result] : [];
710
+ });
711
+ }
712
+
713
+ // src/core/protocols/x402/v2/payment-options.ts
714
+ function extractPaymentOptions2(accepts) {
715
+ return accepts.flatMap((accept) => {
716
+ if (!isRecord(accept)) return [];
717
+ const network = asNonEmptyString(accept.network);
718
+ const asset = asNonEmptyString(accept.asset);
719
+ const amount = asNonEmptyString(accept.amount);
720
+ if (!network || !asset || !amount) return [];
721
+ const scheme = asNonEmptyString(accept.scheme);
722
+ const payTo = asNonEmptyString(accept.payTo);
723
+ const maxTimeoutSeconds = asPositiveNumber(accept.maxTimeoutSeconds);
724
+ return [
725
+ {
726
+ protocol: "x402",
727
+ version: 2,
728
+ network,
729
+ asset,
730
+ amount,
731
+ ...scheme ? { scheme } : {},
732
+ ...payTo ? { payTo } : {},
733
+ ...maxTimeoutSeconds ? { maxTimeoutSeconds } : {}
734
+ }
735
+ ];
736
+ });
737
+ }
738
+
739
+ // src/core/protocols/x402/index.ts
740
+ function parseVersion(payload) {
741
+ if (!isRecord(payload)) return void 0;
742
+ const v = payload.x402Version;
743
+ if (v === 1 || v === 2) return v;
744
+ return void 0;
745
+ }
746
+ function detectAuthHint(payload) {
747
+ if (isRecord(payload) && isRecord(payload.extensions)) {
748
+ if (payload.extensions["api-key"]) return "apiKey+paid";
749
+ if (payload.extensions["sign-in-with-x"]) return "siwx";
750
+ }
751
+ return "paid";
752
+ }
753
+ function extractPaymentOptions3(payload) {
754
+ if (!isRecord(payload)) return [];
755
+ const version = parseVersion(payload);
756
+ const accepts = Array.isArray(payload.accepts) ? payload.accepts : [];
757
+ if (version === 1) return extractPaymentOptions(accepts);
758
+ if (version === 2) return extractPaymentOptions2(accepts);
759
+ return [];
760
+ }
761
+ function extractSchemas3(payload) {
762
+ if (!isRecord(payload)) return {};
763
+ const version = parseVersion(payload);
764
+ if (version === 2) return extractSchemas2(payload);
765
+ if (version === 1) {
766
+ const accepts = Array.isArray(payload.accepts) ? payload.accepts : [];
767
+ return extractSchemas(accepts);
768
+ }
769
+ return {};
770
+ }
771
+ function parseInputSchema(payload) {
772
+ const schema = extractSchemas3(payload).inputSchema;
773
+ return schema;
774
+ }
775
+ function parseOutputSchema(payload) {
776
+ const schema = extractSchemas3(payload).outputSchema;
777
+ return schema;
778
+ }
779
+
780
+ // src/core/protocols/x402/v1/parse-payment-required.ts
781
+ async function parsePaymentRequiredBody(response) {
782
+ const payload = await response.clone().json();
783
+ if (!isRecord(payload) || payload.x402Version !== 1) return null;
784
+ return payload;
785
+ }
786
+
787
+ // src/core/protocols/x402/v2/parse-payment-required.ts
788
+ function parsePaymentRequiredBody2(headerValue) {
789
+ const payload = JSON.parse(atob(headerValue));
790
+ if (!isRecord(payload) || payload.x402Version !== 2) return null;
791
+ return payload;
792
+ }
793
+
794
+ // src/core/source/probe/index.ts
795
+ function isUsableStatus(status) {
796
+ return status === 402 || status >= 200 && status < 300;
797
+ }
798
+ function detectProtocols(response) {
799
+ const protocols = /* @__PURE__ */ new Set();
800
+ const directHeader = response.headers.get("x-payment-protocol");
801
+ if (directHeader) {
802
+ for (const part of directHeader.split(",")) {
803
+ const protocol = part.trim().toLowerCase();
804
+ if (protocol) protocols.add(protocol);
805
+ }
806
+ }
807
+ const authHeader = response.headers.get("www-authenticate")?.toLowerCase() ?? "";
808
+ if (authHeader.includes("x402")) protocols.add("x402");
975
809
  if (isMmmEnabled() && authHeader.includes("mpp")) protocols.add("mpp");
976
810
  return [...protocols];
977
811
  }
978
- async function runProbeStage(options) {
979
- const candidates = options.probeCandidates ?? [];
980
- if (candidates.length === 0) {
981
- return {
982
- stage: "probe",
983
- valid: false,
984
- resources: [],
985
- warnings: [
986
- warning(
987
- "PROBE_STAGE_SKIPPED",
988
- "info",
989
- "Probe stage skipped because no probe candidates were provided.",
990
- { stage: "probe" }
991
- )
992
- ]
993
- };
812
+ function buildProbeUrl(url, method, inputBody) {
813
+ if (!inputBody || method !== "GET" && method !== "HEAD") return url;
814
+ const u = new URL(url);
815
+ for (const [key, value] of Object.entries(inputBody)) {
816
+ u.searchParams.set(key, String(value));
994
817
  }
995
- const resources = [];
996
- const warnings = [];
997
- for (const candidate of candidates) {
998
- const path = normalizePath(candidate.path);
999
- const methods = candidate.methods?.length ? candidate.methods : DEFAULT_PROBE_METHODS;
1000
- for (const method of methods) {
1001
- const url = `${options.origin}${path}`;
1002
- try {
1003
- const response = await options.fetcher(url, {
1004
- method,
1005
- headers: {
1006
- Accept: "application/json, text/plain;q=0.9, */*;q=0.8",
1007
- ...options.headers
1008
- },
1009
- signal: options.signal
1010
- });
1011
- if (response.status !== 402 && (response.status < 200 || response.status >= 300)) {
1012
- continue;
1013
- }
818
+ return u.toString();
819
+ }
820
+ function probeMethod(url, method, path, headers, signal, inputBody) {
821
+ const hasBody = inputBody !== void 0 && method !== "GET" && method !== "HEAD";
822
+ const probeUrl = buildProbeUrl(url, method, inputBody);
823
+ return fetchSafe(probeUrl, {
824
+ method,
825
+ headers: {
826
+ Accept: "application/json, text/plain;q=0.9, */*;q=0.8",
827
+ ...hasBody ? { "Content-Type": "application/json" } : {},
828
+ ...headers
829
+ },
830
+ ...hasBody ? { body: JSON.stringify(inputBody) } : {},
831
+ signal
832
+ }).andThen((response) => {
833
+ if (!isUsableStatus(response.status)) return ResultAsync4.fromSafePromise(Promise.resolve(null));
834
+ return ResultAsync4.fromSafePromise(
835
+ (async () => {
1014
836
  let authHint = response.status === 402 ? "paid" : "unprotected";
837
+ let paymentRequiredBody;
1015
838
  if (response.status === 402) {
1016
839
  try {
1017
- const payload = await response.clone().json();
1018
- authHint = detectAuthHintFrom402Payload(payload);
840
+ const headerValue = response.headers.get("payment-required");
841
+ const parsed = headerValue !== null ? parsePaymentRequiredBody2(headerValue) : await parsePaymentRequiredBody(response);
842
+ if (parsed !== null) {
843
+ paymentRequiredBody = parsed;
844
+ authHint = detectAuthHint(paymentRequiredBody);
845
+ }
1019
846
  } catch {
1020
847
  }
1021
848
  }
1022
- const protocolHints = detectProtocols(response);
1023
- resources.push(
1024
- createResource(
1025
- {
1026
- origin: options.origin,
1027
- method,
1028
- path,
1029
- source: "probe",
1030
- summary: `${method} ${path}`,
1031
- authHint,
1032
- ...protocolHints.length ? { protocolHints } : {}
1033
- },
1034
- 0.6,
1035
- "runtime_verified"
1036
- )
1037
- );
1038
- } catch (error) {
1039
- warnings.push(
1040
- warning(
1041
- "FETCH_FAILED",
1042
- "info",
1043
- `Probe ${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,
1044
- { stage: "probe" }
1045
- )
1046
- );
1047
- }
849
+ const protocols = detectProtocols(response);
850
+ const wwwAuthenticate = response.headers.get("www-authenticate") ?? void 0;
851
+ return {
852
+ path,
853
+ method,
854
+ authHint,
855
+ ...protocols.length ? { protocols } : {},
856
+ ...paymentRequiredBody !== void 0 ? { paymentRequiredBody } : {},
857
+ ...wwwAuthenticate ? { wwwAuthenticate } : {}
858
+ };
859
+ })()
860
+ );
861
+ });
862
+ }
863
+ function getProbe(url, headers, signal, inputBody) {
864
+ const path = normalizePath(new URL(url).pathname || "/");
865
+ return ResultAsync4.fromSafePromise(
866
+ Promise.all(
867
+ [...HTTP_METHODS].map(
868
+ (method) => probeMethod(url, method, path, headers, signal, inputBody).match(
869
+ (result) => result,
870
+ () => null
871
+ )
872
+ )
873
+ ).then((results) => results.filter((r) => r !== null))
874
+ );
875
+ }
876
+
877
+ // src/core/protocols/mpp/index.ts
878
+ var TEMPO_DEFAULT_CHAIN_ID = 4217;
879
+ function parseAuthParams(segment) {
880
+ const params = {};
881
+ const re = /(\w+)=(?:"([^"]*)"|'([^']*)')/g;
882
+ let match;
883
+ while ((match = re.exec(segment)) !== null) {
884
+ params[match[1]] = match[2] ?? match[3] ?? "";
885
+ }
886
+ return params;
887
+ }
888
+ function extractPaymentOptions4(wwwAuthenticate) {
889
+ if (!isMmmEnabled() || !wwwAuthenticate) return [];
890
+ const options = [];
891
+ for (const segment of wwwAuthenticate.split(/,\s*(?=Payment\s)/i)) {
892
+ const stripped = segment.replace(/^Payment\s+/i, "").trim();
893
+ const params = parseAuthParams(stripped);
894
+ const paymentMethod = params["method"];
895
+ const intent = params["intent"];
896
+ const realm = params["realm"];
897
+ const description = params["description"];
898
+ const requestStr = params["request"];
899
+ if (!paymentMethod || !intent || !realm || !requestStr) continue;
900
+ let request;
901
+ try {
902
+ const parsed = JSON.parse(requestStr);
903
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) continue;
904
+ request = parsed;
905
+ } catch {
906
+ continue;
1048
907
  }
908
+ const asset = typeof request["currency"] === "string" ? request["currency"] : void 0;
909
+ const amountRaw = request["amount"];
910
+ const amount = typeof amountRaw === "string" ? amountRaw : typeof amountRaw === "number" ? String(amountRaw) : void 0;
911
+ const decimals = typeof request["decimals"] === "number" ? request["decimals"] : void 0;
912
+ const payTo = typeof request["recipient"] === "string" ? request["recipient"] : void 0;
913
+ const methodDetails = request["methodDetails"];
914
+ const chainId = methodDetails !== null && typeof methodDetails === "object" && !Array.isArray(methodDetails) && typeof methodDetails["chainId"] === "number" ? methodDetails["chainId"] : TEMPO_DEFAULT_CHAIN_ID;
915
+ if (!asset || !amount) continue;
916
+ options.push({
917
+ protocol: "mpp",
918
+ // isMmmEnabled
919
+ paymentMethod,
920
+ intent,
921
+ realm,
922
+ network: `tempo:${String(chainId)}`,
923
+ // isMmmEnabled
924
+ asset,
925
+ amount,
926
+ ...decimals != null ? { decimals } : {},
927
+ ...payTo ? { payTo } : {},
928
+ ...description ? { description } : {}
929
+ });
1049
930
  }
1050
- return {
1051
- stage: "probe",
1052
- valid: resources.length > 0,
1053
- resources,
1054
- warnings
1055
- };
931
+ return options;
1056
932
  }
1057
933
 
1058
- // src/core/upgrade.ts
1059
- var UPGRADE_WARNING_CODES = [
1060
- "LEGACY_WELL_KNOWN_USED",
1061
- "LEGACY_DNS_USED",
1062
- "LEGACY_DNS_PLAIN_URL",
1063
- "LEGACY_INSTRUCTIONS_USED",
1064
- "LEGACY_OWNERSHIP_PROOFS_USED",
1065
- "OPENAPI_AUTH_MODE_MISSING",
1066
- "OPENAPI_TOP_LEVEL_INVALID"
1067
- ];
1068
- var UPGRADE_WARNING_CODE_SET = new Set(UPGRADE_WARNING_CODES);
1069
- function computeUpgradeSignal(warnings) {
1070
- const reasons = warnings.map((entry) => entry.code).filter((code, index, list) => list.indexOf(code) === index).filter((code) => UPGRADE_WARNING_CODE_SET.has(code));
934
+ // src/core/layers/l3.ts
935
+ function findMatchingOpenApiPath(paths, targetPath) {
936
+ const exact = paths[targetPath];
937
+ if (isRecord(exact)) return { matchedPath: targetPath, pathItem: exact };
938
+ for (const [specPath, entry] of Object.entries(paths)) {
939
+ if (!isRecord(entry)) continue;
940
+ const pattern = specPath.replace(/\{[^}]+\}/g, "[^/]+");
941
+ const regex = new RegExp(`^${pattern}$`);
942
+ if (regex.test(targetPath)) {
943
+ return { matchedPath: specPath, pathItem: entry };
944
+ }
945
+ }
946
+ return null;
947
+ }
948
+ function resolveRef(document, ref, seen) {
949
+ if (!ref.startsWith("#/")) return void 0;
950
+ if (seen.has(ref)) return { $circular: ref };
951
+ seen.add(ref);
952
+ const parts = ref.slice(2).split("/");
953
+ let current = document;
954
+ for (const part of parts) {
955
+ if (!isRecord(current)) return void 0;
956
+ current = current[part];
957
+ if (current === void 0) return void 0;
958
+ }
959
+ if (isRecord(current)) return resolveRefs(document, current, seen);
960
+ return current;
961
+ }
962
+ function resolveRefs(document, obj, seen, depth = 0) {
963
+ if (depth > 4) return obj;
964
+ const resolved = {};
965
+ for (const [key, value] of Object.entries(obj)) {
966
+ if (key === "$ref" && typeof value === "string") {
967
+ const deref = resolveRef(document, value, seen);
968
+ if (isRecord(deref)) {
969
+ Object.assign(resolved, deref);
970
+ } else {
971
+ resolved[key] = value;
972
+ }
973
+ continue;
974
+ }
975
+ if (isRecord(value)) {
976
+ resolved[key] = resolveRefs(document, value, seen, depth + 1);
977
+ continue;
978
+ }
979
+ if (Array.isArray(value)) {
980
+ resolved[key] = value.map(
981
+ (item) => isRecord(item) ? resolveRefs(document, item, seen, depth + 1) : item
982
+ );
983
+ continue;
984
+ }
985
+ resolved[key] = value;
986
+ }
987
+ return resolved;
988
+ }
989
+ function extractRequestBodySchema(operationSchema) {
990
+ const requestBody = operationSchema.requestBody;
991
+ if (!isRecord(requestBody)) return void 0;
992
+ const content = requestBody.content;
993
+ if (!isRecord(content)) return void 0;
994
+ const jsonMediaType = content["application/json"];
995
+ if (isRecord(jsonMediaType) && isRecord(jsonMediaType.schema)) {
996
+ return jsonMediaType.schema;
997
+ }
998
+ for (const mediaType of Object.values(content)) {
999
+ if (isRecord(mediaType) && isRecord(mediaType.schema)) {
1000
+ return mediaType.schema;
1001
+ }
1002
+ }
1003
+ return void 0;
1004
+ }
1005
+ function extractOutputSchema(operationSchema) {
1006
+ const responses = operationSchema.responses;
1007
+ if (!isRecord(responses)) return void 0;
1008
+ const candidate = responses["200"] ?? responses["201"] ?? Object.entries(responses).find(([k]) => k.startsWith("2"))?.[1];
1009
+ if (!isRecord(candidate)) return void 0;
1010
+ const content = candidate.content;
1011
+ if (!isRecord(content)) return void 0;
1012
+ const json = content["application/json"];
1013
+ if (isRecord(json) && isRecord(json.schema)) return json.schema;
1014
+ for (const mediaType of Object.values(content)) {
1015
+ if (isRecord(mediaType) && isRecord(mediaType.schema)) return mediaType.schema;
1016
+ }
1017
+ return void 0;
1018
+ }
1019
+ function extractParameters(operationSchema) {
1020
+ const params = operationSchema.parameters;
1021
+ if (!Array.isArray(params)) return [];
1022
+ return params.filter((value) => isRecord(value));
1023
+ }
1024
+ function extractInputSchema(operationSchema) {
1025
+ const requestBody = extractRequestBodySchema(operationSchema);
1026
+ const parameters = extractParameters(operationSchema);
1027
+ if (!requestBody && parameters.length === 0) return void 0;
1028
+ if (requestBody && parameters.length === 0) return requestBody;
1071
1029
  return {
1072
- upgradeSuggested: reasons.length > 0,
1073
- upgradeReasons: reasons
1030
+ ...requestBody ? { requestBody } : {},
1031
+ ...parameters.length > 0 ? { parameters } : {}
1074
1032
  };
1075
1033
  }
1076
-
1077
- // src/core/discovery.ts
1078
- function mergeResources(target, incoming, resourceWarnings) {
1079
- const warnings = [];
1080
- for (const resource of incoming) {
1081
- const existing = target.get(resource.resourceKey);
1082
- if (!existing) {
1083
- target.set(resource.resourceKey, resource);
1084
- continue;
1085
- }
1086
- const conflict = existing.authHint !== resource.authHint || existing.priceHint !== resource.priceHint || JSON.stringify(existing.protocolHints ?? []) !== JSON.stringify(resource.protocolHints ?? []);
1087
- if (conflict) {
1088
- const conflictWarning = warning(
1089
- "CROSS_SOURCE_CONFLICT",
1090
- "warn",
1091
- `Resource conflict for ${resource.resourceKey}; keeping higher-precedence source ${existing.source} over ${resource.source}.`,
1092
- {
1093
- resourceKey: resource.resourceKey
1094
- }
1095
- );
1096
- warnings.push(conflictWarning);
1097
- resourceWarnings[resource.resourceKey] = [
1098
- ...resourceWarnings[resource.resourceKey] ?? [],
1099
- conflictWarning
1100
- ];
1101
- continue;
1034
+ function parseOperationPrice(operation) {
1035
+ const paymentInfo = operation["x-payment-info"];
1036
+ if (!isRecord(paymentInfo)) return void 0;
1037
+ function toFiniteNumber(value) {
1038
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1039
+ if (typeof value === "string" && value.trim().length > 0) {
1040
+ const parsed = Number(value);
1041
+ if (Number.isFinite(parsed)) return parsed;
1102
1042
  }
1103
- target.set(resource.resourceKey, {
1104
- ...existing,
1105
- summary: existing.summary ?? resource.summary,
1106
- links: { ...resource.links, ...existing.links },
1107
- confidence: Math.max(existing.confidence ?? 0, resource.confidence ?? 0)
1108
- });
1043
+ return void 0;
1109
1044
  }
1110
- return warnings;
1045
+ const fixed = toFiniteNumber(paymentInfo.price);
1046
+ if (fixed != null) return `$${String(fixed)}`;
1047
+ const min = toFiniteNumber(paymentInfo.minPrice);
1048
+ const max = toFiniteNumber(paymentInfo.maxPrice);
1049
+ if (min != null && max != null) return `$${String(min)}-$${String(max)}`;
1050
+ return void 0;
1051
+ }
1052
+ function parseOperationProtocols(operation) {
1053
+ const paymentInfo = operation["x-payment-info"];
1054
+ if (!isRecord(paymentInfo) || !Array.isArray(paymentInfo.protocols)) return void 0;
1055
+ const protocols = paymentInfo.protocols.filter(
1056
+ (protocol) => typeof protocol === "string" && protocol.length > 0 && (protocol !== "mpp" || isMmmEnabled())
1057
+ );
1058
+ return protocols.length > 0 ? protocols : void 0;
1111
1059
  }
1112
- function toTrace(stageResult, startedAt) {
1060
+ function getL3ForOpenAPI(openApi, path, method) {
1061
+ const document = openApi.raw;
1062
+ const paths = isRecord(document.paths) ? document.paths : void 0;
1063
+ if (!paths) return null;
1064
+ const matched = findMatchingOpenApiPath(paths, path);
1065
+ if (!matched) return null;
1066
+ const operation = matched.pathItem[method.toLowerCase()];
1067
+ if (!isRecord(operation)) return null;
1068
+ const resolvedOperation = resolveRefs(document, operation, /* @__PURE__ */ new Set());
1069
+ const summary = typeof resolvedOperation.summary === "string" ? resolvedOperation.summary : typeof resolvedOperation.description === "string" ? resolvedOperation.description : void 0;
1113
1070
  return {
1114
- stage: stageResult.stage,
1115
- attempted: true,
1116
- valid: stageResult.valid,
1117
- resourceCount: stageResult.resources.length,
1118
- durationMs: Date.now() - startedAt,
1119
- warnings: stageResult.warnings,
1120
- ...stageResult.links ? { links: stageResult.links } : {}
1071
+ source: "openapi",
1072
+ ...summary ? { summary } : {},
1073
+ authMode: inferAuthMode(resolvedOperation) ?? void 0,
1074
+ estimatedPrice: parseOperationPrice(resolvedOperation),
1075
+ protocols: parseOperationProtocols(resolvedOperation),
1076
+ inputSchema: extractInputSchema(resolvedOperation),
1077
+ outputSchema: extractOutputSchema(resolvedOperation)
1121
1078
  };
1122
1079
  }
1123
- async function runOverrideStage(options) {
1124
- const warnings = [];
1125
- for (const overrideUrl of options.overrideUrls) {
1126
- const normalized = overrideUrl.trim();
1127
- if (!normalized) continue;
1128
- try {
1129
- const response = await options.fetcher(normalized, {
1130
- method: "GET",
1131
- headers: { Accept: "application/json, text/plain;q=0.9", ...options.headers },
1132
- signal: options.signal
1133
- });
1134
- if (!response.ok) {
1135
- warnings.push(
1136
- warning(
1137
- "FETCH_FAILED",
1138
- "warn",
1139
- `Override fetch failed (${response.status}) at ${normalized}`,
1140
- {
1141
- stage: "override"
1142
- }
1143
- )
1144
- );
1145
- continue;
1146
- }
1147
- const bodyText = await response.text();
1148
- let parsedJson;
1149
- try {
1150
- parsedJson = JSON.parse(bodyText);
1151
- } catch {
1152
- parsedJson = void 0;
1153
- }
1154
- if (parsedJson && typeof parsedJson === "object" && !Array.isArray(parsedJson) && "openapi" in parsedJson && "paths" in parsedJson) {
1155
- const openapiResult = await runOpenApiStage({
1156
- origin: options.origin,
1157
- fetcher: async (input, init) => {
1158
- const inputString = String(input);
1159
- if (inputString === `${options.origin}/openapi.json` || inputString === `${options.origin}/.well-known/openapi.json`) {
1160
- return new Response(bodyText, {
1161
- status: 200,
1162
- headers: { "content-type": "application/json" }
1163
- });
1164
- }
1165
- return options.fetcher(input, init);
1166
- },
1167
- headers: options.headers,
1168
- signal: options.signal,
1169
- includeRaw: options.includeRaw
1170
- });
1171
- return {
1172
- ...openapiResult,
1173
- stage: "override",
1174
- warnings: [
1175
- warning("OVERRIDE_USED", "info", `Using explicit override source ${normalized}`, {
1176
- stage: "override"
1177
- }),
1178
- ...openapiResult.warnings
1179
- ]
1180
- };
1181
- }
1182
- if (parsedJson && typeof parsedJson === "object" && !Array.isArray(parsedJson)) {
1183
- const parsedWellKnown = parseWellKnownPayload(parsedJson, options.origin, normalized);
1184
- if (parsedWellKnown.resources.length > 0) {
1185
- return {
1186
- stage: "override",
1187
- valid: true,
1188
- resources: parsedWellKnown.resources,
1189
- warnings: [
1190
- warning("OVERRIDE_USED", "info", `Using explicit override source ${normalized}`, {
1191
- stage: "override"
1192
- }),
1193
- ...parsedWellKnown.warnings
1194
- ],
1195
- links: { discoveryUrl: normalized },
1196
- ...options.includeRaw ? { raw: parsedWellKnown.raw } : {}
1197
- };
1198
- }
1199
- }
1200
- } catch (error) {
1201
- warnings.push(
1202
- warning(
1203
- "FETCH_FAILED",
1204
- "warn",
1205
- `Override fetch exception at ${normalized}: ${error instanceof Error ? error.message : String(error)}`,
1206
- { stage: "override" }
1207
- )
1208
- );
1209
- continue;
1210
- }
1211
- const fallbackWellKnownResult = await runWellKnownX402Stage({
1212
- origin: options.origin,
1213
- url: normalized,
1214
- fetcher: options.fetcher,
1215
- headers: options.headers,
1216
- signal: options.signal,
1217
- includeRaw: options.includeRaw
1218
- });
1219
- if (fallbackWellKnownResult.valid) {
1220
- return {
1221
- ...fallbackWellKnownResult,
1222
- stage: "override",
1223
- warnings: [
1224
- warning("OVERRIDE_USED", "info", `Using explicit override source ${normalized}`, {
1225
- stage: "override"
1226
- }),
1227
- ...fallbackWellKnownResult.warnings
1228
- ]
1229
- };
1230
- }
1231
- warnings.push(...fallbackWellKnownResult.warnings);
1232
- }
1080
+ function getL3ForProbe(probe, path, method) {
1081
+ const probeResult = probe.find((r) => r.path === path && r.method === method);
1082
+ if (!probeResult) return null;
1083
+ const inputSchema = probeResult.paymentRequiredBody ? parseInputSchema(probeResult.paymentRequiredBody) : void 0;
1084
+ const outputSchema = probeResult.paymentRequiredBody ? parseOutputSchema(probeResult.paymentRequiredBody) : void 0;
1085
+ const paymentOptions = [
1086
+ ...probeResult.paymentRequiredBody ? extractPaymentOptions3(probeResult.paymentRequiredBody) : [],
1087
+ ...isMmmEnabled() ? extractPaymentOptions4(probeResult.wwwAuthenticate) : []
1088
+ // isMmmEnabled
1089
+ ];
1233
1090
  return {
1234
- stage: "override",
1235
- valid: false,
1236
- resources: [],
1237
- warnings
1091
+ source: "probe",
1092
+ authMode: probeResult.authHint,
1093
+ ...probeResult.protocols?.length ? { protocols: probeResult.protocols } : {},
1094
+ ...inputSchema ? { inputSchema } : {},
1095
+ ...outputSchema ? { outputSchema } : {},
1096
+ ...paymentOptions.length ? { paymentOptions } : {}
1238
1097
  };
1239
1098
  }
1240
- async function runDiscovery({
1241
- detailed,
1242
- options
1243
- }) {
1244
- const fetcher = options.fetcher ?? fetch;
1245
- const compatMode = options.compatMode ?? DEFAULT_COMPAT_MODE;
1246
- const strictCompat = compatMode === "strict";
1247
- const rawView = detailed ? options.rawView ?? "none" : "none";
1248
- const includeRaw = rawView === "full";
1249
- const includeInteropMpp = detailed && Boolean(options.includeInteropMpp);
1250
- const origin = normalizeOrigin(options.target);
1251
- const warnings = [];
1252
- const trace = [];
1253
- const resourceWarnings = {};
1254
- const rawSources = {};
1255
- const merged = /* @__PURE__ */ new Map();
1256
- if (compatMode !== "off") {
1257
- warnings.push(
1258
- warning(
1259
- "COMPAT_MODE_ENABLED",
1260
- compatMode === "strict" ? "warn" : "info",
1261
- `Compatibility mode is '${compatMode}'. Legacy adapters are active.`
1262
- )
1263
- );
1264
- }
1265
- const stages = [];
1266
- if (options.overrideUrls && options.overrideUrls.length > 0) {
1267
- stages.push(
1268
- () => runOverrideStage({
1269
- origin,
1270
- overrideUrls: options.overrideUrls ?? [],
1271
- fetcher,
1272
- headers: options.headers,
1273
- signal: options.signal,
1274
- includeRaw
1275
- })
1276
- );
1277
- }
1278
- stages.push(
1279
- () => runOpenApiStage({
1280
- origin,
1281
- fetcher,
1282
- headers: options.headers,
1283
- signal: options.signal,
1284
- includeRaw
1285
- })
1286
- );
1287
- if (compatMode !== "off") {
1288
- stages.push(
1289
- () => runWellKnownX402Stage({
1290
- origin,
1291
- fetcher,
1292
- headers: options.headers,
1293
- signal: options.signal,
1294
- includeRaw
1295
- })
1099
+ function getL3(openApi, probe, path, method) {
1100
+ if (openApi) return getL3ForOpenAPI(openApi, path, method);
1101
+ return getL3ForProbe(probe, path, method);
1102
+ }
1103
+
1104
+ // src/runtime/check-endpoint.ts
1105
+ function getAdvisoriesForOpenAPI(openApi, path) {
1106
+ return [...HTTP_METHODS].flatMap((method) => {
1107
+ const l3 = getL3ForOpenAPI(openApi, path, method);
1108
+ return l3 ? [{ method, ...l3 }] : [];
1109
+ });
1110
+ }
1111
+ function getAdvisoriesForProbe(probe, path) {
1112
+ return [...HTTP_METHODS].flatMap((method) => {
1113
+ const l3 = getL3ForProbe(probe, path, method);
1114
+ return l3 ? [{ method, ...l3 }] : [];
1115
+ });
1116
+ }
1117
+ async function checkEndpointSchema(options) {
1118
+ const endpoint = new URL(options.url);
1119
+ const origin = normalizeOrigin(endpoint.origin);
1120
+ const path = normalizePath(endpoint.pathname || "/");
1121
+ if (options.sampleInputBody !== void 0) {
1122
+ const probeResult2 = await getProbe(
1123
+ options.url,
1124
+ options.headers,
1125
+ options.signal,
1126
+ options.sampleInputBody
1296
1127
  );
1297
- stages.push(
1298
- () => runDnsStage({
1128
+ if (probeResult2.isErr()) {
1129
+ return {
1130
+ found: false,
1299
1131
  origin,
1300
- fetcher,
1301
- txtResolver: options.txtResolver,
1302
- headers: options.headers,
1303
- signal: options.signal,
1304
- includeRaw
1305
- })
1306
- );
1307
- if (includeInteropMpp && isMmmEnabled()) {
1308
- stages.push(
1309
- () => runInteropMppStage({
1310
- origin,
1311
- fetcher,
1312
- headers: options.headers,
1313
- signal: options.signal,
1314
- includeRaw
1315
- })
1316
- );
1317
- }
1318
- }
1319
- stages.push(
1320
- () => runProbeStage({
1321
- origin,
1322
- fetcher,
1323
- headers: options.headers,
1324
- signal: options.signal,
1325
- probeCandidates: options.probeCandidates
1326
- })
1327
- );
1328
- let selectedStage;
1329
- for (const runStage of stages) {
1330
- const startedAt = Date.now();
1331
- const stageResult = await runStage();
1332
- stageResult.warnings = applyStrictEscalation(stageResult.warnings, strictCompat);
1333
- trace.push(toTrace(stageResult, startedAt));
1334
- warnings.push(...stageResult.warnings);
1335
- if (stageResult.resources.length > 0) {
1336
- for (const stageWarning of stageResult.warnings) {
1337
- if (stageWarning.resourceKey) {
1338
- resourceWarnings[stageWarning.resourceKey] = [
1339
- ...resourceWarnings[stageWarning.resourceKey] ?? [],
1340
- stageWarning
1341
- ];
1342
- }
1343
- }
1344
- }
1345
- if (includeRaw && stageResult.raw !== void 0) {
1346
- if (stageResult.stage === "openapi" || stageResult.stage === "override") {
1347
- const rawObject = stageResult.raw;
1348
- if (rawObject.openapi !== void 0) rawSources.openapi = rawObject.openapi;
1349
- if (typeof rawObject.llmsTxt === "string") rawSources.llmsTxt = rawObject.llmsTxt;
1350
- }
1351
- if (stageResult.stage === "well-known/x402" || stageResult.stage === "override") {
1352
- rawSources.wellKnownX402 = [...rawSources.wellKnownX402 ?? [], stageResult.raw];
1353
- }
1354
- if (stageResult.stage === "dns/_x402") {
1355
- const rawObject = stageResult.raw;
1356
- if (Array.isArray(rawObject.dnsRecords)) {
1357
- rawSources.dnsRecords = rawObject.dnsRecords;
1358
- }
1359
- }
1360
- if (stageResult.stage === "interop/mpp") {
1361
- rawSources.interopMpp = stageResult.raw;
1362
- }
1363
- }
1364
- if (!stageResult.valid) {
1365
- continue;
1366
- }
1367
- const mergeWarnings = mergeResources(merged, stageResult.resources, resourceWarnings);
1368
- warnings.push(...mergeWarnings);
1369
- if (!detailed) {
1370
- selectedStage = selectedStage ?? stageResult.stage;
1371
- break;
1132
+ path,
1133
+ cause: probeResult2.error.cause,
1134
+ message: probeResult2.error.message
1135
+ };
1372
1136
  }
1373
- }
1374
- if (merged.size === 0) {
1375
- warnings.push(
1376
- warning(
1377
- "NO_DISCOVERY_SOURCES",
1378
- "error",
1379
- "No discovery stage returned first-valid-non-empty results."
1380
- )
1381
- );
1382
- }
1383
- const dedupedWarnings = dedupeWarnings(warnings);
1384
- const upgradeSignal = computeUpgradeSignal(dedupedWarnings);
1385
- const resources = [...merged.values()];
1386
- if (!detailed) {
1137
+ const advisories2 = getAdvisoriesForProbe(probeResult2.value, path);
1138
+ if (advisories2.length > 0) return { found: true, origin, path, advisories: advisories2 };
1139
+ return { found: false, origin, path, cause: "not_found" };
1140
+ }
1141
+ const openApiResult = await getOpenAPI(origin, options.headers, options.signal);
1142
+ const openApi = openApiResult.isOk() ? openApiResult.value : null;
1143
+ if (openApi) {
1144
+ const advisories2 = getAdvisoriesForOpenAPI(openApi, path);
1145
+ if (advisories2.length > 0) return { found: true, origin, path, advisories: advisories2 };
1146
+ return { found: false, origin, path, cause: "not_found" };
1147
+ }
1148
+ const probeResult = await getProbe(options.url, options.headers, options.signal);
1149
+ if (probeResult.isErr()) {
1387
1150
  return {
1151
+ found: false,
1388
1152
  origin,
1389
- resources,
1390
- warnings: dedupedWarnings,
1391
- compatMode,
1392
- ...upgradeSignal,
1393
- ...selectedStage ? { selectedStage } : {}
1153
+ path,
1154
+ cause: probeResult.error.cause,
1155
+ message: probeResult.error.message
1394
1156
  };
1395
1157
  }
1396
- return {
1397
- origin,
1398
- resources,
1399
- warnings: dedupedWarnings,
1400
- compatMode,
1401
- ...upgradeSignal,
1402
- selectedStage: trace.find((entry) => entry.valid)?.stage,
1403
- trace,
1404
- resourceWarnings,
1405
- ...includeRaw ? { rawSources } : {}
1406
- };
1158
+ const advisories = getAdvisoriesForProbe(probeResult.value, path);
1159
+ if (advisories.length > 0) return { found: true, origin, path, advisories };
1160
+ return { found: false, origin, path, cause: "not_found" };
1407
1161
  }
1408
1162
 
1409
- // src/validation/codes.ts
1163
+ // src/x402scan-validation/codes.ts
1410
1164
  var VALIDATION_CODES = {
1411
1165
  COINBASE_SCHEMA_INVALID: "COINBASE_SCHEMA_INVALID",
1412
1166
  X402_NOT_OBJECT: "X402_NOT_OBJECT",
@@ -1429,7 +1183,7 @@ var VALIDATION_CODES = {
1429
1183
  METADATA_OG_IMAGE_MISSING: "METADATA_OG_IMAGE_MISSING"
1430
1184
  };
1431
1185
 
1432
- // src/validation/metadata.ts
1186
+ // src/x402scan-validation/metadata.ts
1433
1187
  function hasText(value) {
1434
1188
  return typeof value === "string" && value.trim().length > 0;
1435
1189
  }
@@ -1489,42 +1243,21 @@ function evaluateMetadataCompleteness(metadata) {
1489
1243
  return issues;
1490
1244
  }
1491
1245
 
1492
- // src/validation/payment-required.ts
1246
+ // src/x402scan-validation/payment-required.ts
1493
1247
  import { parsePaymentRequired } from "@x402/core/schemas";
1494
- var SOLANA_CANONICAL_BY_REF = {
1495
- "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp": "solana",
1496
- EtWTRABZaYq6iMfeYKouRu166VU2xqa1: "solana-devnet",
1497
- "4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z": "solana-testnet"
1498
- };
1499
- var SOLANA_ALIAS_BY_REF = {
1500
- mainnet: "solana",
1501
- devnet: "solana-devnet",
1502
- testnet: "solana-testnet"
1503
- };
1504
- function isRecord4(value) {
1248
+
1249
+ // src/flags.ts
1250
+ var DEFAULT_COMPAT_MODE = "on";
1251
+
1252
+ // src/x402scan-validation/payment-required.ts
1253
+ function isRecord2(value) {
1505
1254
  return typeof value === "object" && value !== null && !Array.isArray(value);
1506
1255
  }
1507
- function asNonEmptyString(value) {
1508
- if (typeof value !== "string") return void 0;
1509
- const trimmed = value.trim();
1510
- return trimmed.length > 0 ? trimmed : void 0;
1511
- }
1512
- function asPositiveNumber(value) {
1513
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
1514
- }
1515
- function pushIssue(issues, issue) {
1516
- issues.push({
1517
- stage: issue.stage ?? "payment_required",
1518
- ...issue
1519
- });
1256
+ function pushIssue2(issues, issue) {
1257
+ issues.push({ stage: "payment_required", ...issue });
1520
1258
  }
1521
1259
  function summarizeIssues(issues) {
1522
- const summary = {
1523
- errorCount: 0,
1524
- warnCount: 0,
1525
- infoCount: 0,
1526
- byCode: {}
1527
- };
1260
+ const summary = { errorCount: 0, warnCount: 0, infoCount: 0, byCode: {} };
1528
1261
  for (const issue of issues) {
1529
1262
  if (issue.severity === "error") summary.errorCount += 1;
1530
1263
  else if (issue.severity === "warn") summary.warnCount += 1;
@@ -1547,202 +1280,23 @@ function zodPathToString(path) {
1547
1280
  }
1548
1281
  function parseWithCoinbaseStructuralGate(payload, issues) {
1549
1282
  const baseParsed = parsePaymentRequired(payload);
1550
- if (baseParsed.success) {
1551
- return baseParsed.data;
1552
- }
1283
+ if (baseParsed.success) return baseParsed.data;
1553
1284
  for (const issue of baseParsed.error.issues) {
1554
- pushIssue(issues, {
1555
- code: VALIDATION_CODES.COINBASE_SCHEMA_INVALID,
1556
- severity: "error",
1557
- message: `Coinbase schema validation failed: ${issue.message}`,
1558
- path: zodPathToString(issue.path),
1559
- actual: issue.code
1560
- });
1561
- }
1562
- return void 0;
1563
- }
1564
- function validateV2Network(networkRaw, index, issues) {
1565
- if (!/^[^:\s]+:[^:\s]+$/.test(networkRaw)) {
1566
- pushIssue(issues, {
1567
- code: VALIDATION_CODES.NETWORK_CAIP2_INVALID,
1568
- severity: "error",
1569
- message: `Accept at index ${index} has invalid CAIP-2 network format`,
1570
- hint: "Expected '<namespace>:<reference>', e.g. 'eip155:8453' or 'solana:5eykt4...'.",
1571
- path: `accepts[${index}].network`,
1572
- expected: "<namespace>:<reference>",
1573
- actual: networkRaw
1574
- });
1575
- return void 0;
1576
- }
1577
- const [namespace, reference] = networkRaw.split(":");
1578
- if (namespace === "eip155") {
1579
- if (!/^\d+$/.test(reference)) {
1580
- pushIssue(issues, {
1581
- code: VALIDATION_CODES.NETWORK_EIP155_REFERENCE_INVALID,
1582
- severity: "error",
1583
- message: `Accept at index ${index} has invalid eip155 reference`,
1584
- hint: "Use a numeric chain id, e.g. 'eip155:8453'.",
1585
- path: `accepts[${index}].network`,
1586
- expected: "eip155:<numeric-chain-id>",
1587
- actual: networkRaw
1588
- });
1589
- return void 0;
1590
- }
1591
- return networkRaw;
1592
- }
1593
- if (namespace === "solana") {
1594
- const canonical = SOLANA_CANONICAL_BY_REF[reference];
1595
- if (canonical) return canonical;
1596
- const alias = SOLANA_ALIAS_BY_REF[reference];
1597
- if (alias) {
1598
- pushIssue(issues, {
1599
- code: VALIDATION_CODES.NETWORK_SOLANA_ALIAS_COMPAT,
1600
- severity: "warn",
1601
- message: `Accept at index ${index} uses compatibility Solana reference '${reference}'`,
1602
- hint: "Use canonical Solana CAIP references for deterministic behavior.",
1603
- path: `accepts[${index}].network`,
1604
- actual: networkRaw
1605
- });
1606
- return alias;
1607
- }
1608
- pushIssue(issues, {
1609
- code: VALIDATION_CODES.NETWORK_REFERENCE_UNKNOWN,
1610
- severity: "error",
1611
- message: `Accept at index ${index} uses unknown Solana reference '${reference}'`,
1612
- hint: "Use canonical references for mainnet/devnet/testnet.",
1613
- path: `accepts[${index}].network`,
1614
- actual: networkRaw
1615
- });
1616
- return void 0;
1617
- }
1618
- return networkRaw;
1619
- }
1620
- function validateV1Network(networkRaw, index, issues) {
1621
- if (networkRaw === "solana-mainnet-beta") {
1622
- pushIssue(issues, {
1623
- code: VALIDATION_CODES.NETWORK_SOLANA_ALIAS_INVALID,
1624
- severity: "error",
1625
- message: `Accept at index ${index} uses invalid Solana network alias`,
1626
- hint: "Use 'solana' (v1) or canonical Solana CAIP reference (v2).",
1627
- path: `accepts[${index}].network`,
1628
- expected: "solana",
1629
- actual: networkRaw
1630
- });
1631
- return void 0;
1632
- }
1633
- if (networkRaw.startsWith("solana-") && networkRaw !== "solana-devnet") {
1634
- pushIssue(issues, {
1635
- code: VALIDATION_CODES.NETWORK_SOLANA_ALIAS_INVALID,
1636
- severity: "error",
1637
- message: `Accept at index ${index} uses unsupported Solana network alias`,
1638
- hint: "Use 'solana' or 'solana-devnet' for v1 payloads.",
1639
- path: `accepts[${index}].network`,
1640
- actual: networkRaw
1641
- });
1642
- return void 0;
1643
- }
1644
- if (networkRaw.includes(":")) {
1645
- return validateV2Network(networkRaw, index, issues);
1646
- }
1647
- return networkRaw;
1648
- }
1649
- function validateAccept(acceptRaw, index, version, issues) {
1650
- if (!isRecord4(acceptRaw)) {
1651
- pushIssue(issues, {
1652
- code: VALIDATION_CODES.X402_ACCEPT_ENTRY_INVALID,
1653
- severity: "error",
1654
- message: `Accept at index ${index} must be an object`,
1655
- path: `accepts[${index}]`
1656
- });
1657
- return null;
1658
- }
1659
- const scheme = asNonEmptyString(acceptRaw.scheme);
1660
- const networkRaw = asNonEmptyString(acceptRaw.network);
1661
- const payTo = asNonEmptyString(acceptRaw.payTo);
1662
- const asset = asNonEmptyString(acceptRaw.asset);
1663
- const maxTimeoutSeconds = asPositiveNumber(acceptRaw.maxTimeoutSeconds);
1664
- const amount = version === 2 ? asNonEmptyString(acceptRaw.amount) : asNonEmptyString(acceptRaw.maxAmountRequired);
1665
- if (!scheme) {
1666
- pushIssue(issues, {
1667
- code: VALIDATION_CODES.X402_ACCEPT_ENTRY_INVALID,
1668
- severity: "error",
1669
- message: `Accept at index ${index} is missing scheme`,
1670
- path: `accepts[${index}].scheme`
1671
- });
1672
- }
1673
- if (!networkRaw) {
1674
- pushIssue(issues, {
1675
- code: VALIDATION_CODES.X402_ACCEPT_ENTRY_INVALID,
1676
- severity: "error",
1677
- message: `Accept at index ${index} is missing network`,
1678
- path: `accepts[${index}].network`
1679
- });
1680
- }
1681
- if (!amount) {
1682
- pushIssue(issues, {
1683
- code: VALIDATION_CODES.X402_ACCEPT_ENTRY_INVALID,
1684
- severity: "error",
1685
- message: `Accept at index ${index} is missing ${version === 2 ? "amount" : "maxAmountRequired"}`,
1686
- path: `accepts[${index}].${version === 2 ? "amount" : "maxAmountRequired"}`
1687
- });
1688
- }
1689
- if (!payTo) {
1690
- pushIssue(issues, {
1691
- code: VALIDATION_CODES.X402_ACCEPT_ENTRY_INVALID,
1692
- severity: "error",
1693
- message: `Accept at index ${index} is missing payTo`,
1694
- path: `accepts[${index}].payTo`
1695
- });
1696
- }
1697
- if (!asset) {
1698
- pushIssue(issues, {
1699
- code: VALIDATION_CODES.X402_ACCEPT_ENTRY_INVALID,
1700
- severity: "error",
1701
- message: `Accept at index ${index} is missing asset`,
1702
- path: `accepts[${index}].asset`
1703
- });
1704
- }
1705
- if (!maxTimeoutSeconds) {
1706
- pushIssue(issues, {
1707
- code: VALIDATION_CODES.X402_ACCEPT_ENTRY_INVALID,
1708
- severity: "error",
1709
- message: `Accept at index ${index} is missing or has invalid maxTimeoutSeconds`,
1710
- path: `accepts[${index}].maxTimeoutSeconds`
1711
- });
1712
- }
1713
- let normalizedNetwork;
1714
- if (networkRaw) {
1715
- normalizedNetwork = version === 2 ? validateV2Network(networkRaw, index, issues) : validateV1Network(networkRaw, index, issues);
1716
- }
1717
- return {
1718
- index,
1719
- network: normalizedNetwork ?? networkRaw ?? "unknown",
1720
- networkRaw: networkRaw ?? "unknown",
1721
- scheme,
1722
- asset,
1723
- payTo,
1724
- amount,
1725
- maxTimeoutSeconds
1726
- };
1285
+ pushIssue2(issues, {
1286
+ code: VALIDATION_CODES.COINBASE_SCHEMA_INVALID,
1287
+ severity: "error",
1288
+ message: `Coinbase schema validation failed: ${issue.message}`,
1289
+ path: zodPathToString(issue.path),
1290
+ actual: issue.code
1291
+ });
1292
+ }
1293
+ return void 0;
1727
1294
  }
1728
1295
  function getSchemaPresence(payload, accepts, version) {
1729
- if (version === 1) {
1730
- const first = accepts[0];
1731
- if (!isRecord4(first)) {
1732
- return { hasInputSchema: false, hasOutputSchema: false };
1733
- }
1734
- const outputSchema = isRecord4(first.outputSchema) ? first.outputSchema : void 0;
1735
- return {
1736
- hasInputSchema: outputSchema?.input !== void 0 && outputSchema.input !== null,
1737
- hasOutputSchema: outputSchema?.output !== void 0 && outputSchema.output !== null
1738
- };
1739
- }
1740
- const extensions = isRecord4(payload.extensions) ? payload.extensions : void 0;
1741
- const bazaar = extensions && isRecord4(extensions.bazaar) ? extensions.bazaar : void 0;
1742
- const info = bazaar && isRecord4(bazaar.info) ? bazaar.info : void 0;
1296
+ const schemas = version === 1 ? extractSchemas(accepts) : extractSchemas2(payload);
1743
1297
  return {
1744
- hasInputSchema: info?.input !== void 0 && info.input !== null,
1745
- hasOutputSchema: info?.output !== void 0 && info.output !== null
1298
+ hasInputSchema: schemas.inputSchema !== void 0,
1299
+ hasOutputSchema: schemas.outputSchema !== void 0
1746
1300
  };
1747
1301
  }
1748
1302
  function validatePaymentRequiredDetailed(payload, options = {}) {
@@ -1750,21 +1304,15 @@ function validatePaymentRequiredDetailed(payload, options = {}) {
1750
1304
  const compatMode = options.compatMode ?? DEFAULT_COMPAT_MODE;
1751
1305
  const requireInputSchema = options.requireInputSchema ?? true;
1752
1306
  const requireOutputSchema = options.requireOutputSchema ?? true;
1753
- if (!isRecord4(payload)) {
1754
- pushIssue(issues, {
1307
+ if (!isRecord2(payload)) {
1308
+ pushIssue2(issues, {
1755
1309
  code: VALIDATION_CODES.X402_NOT_OBJECT,
1756
1310
  severity: "error",
1757
1311
  message: "Payment required payload must be a JSON object",
1758
1312
  path: "$"
1759
1313
  });
1760
- if (options.metadata) {
1761
- issues.push(...evaluateMetadataCompleteness(options.metadata));
1762
- }
1763
- return {
1764
- valid: false,
1765
- issues,
1766
- summary: summarizeIssues(issues)
1767
- };
1314
+ if (options.metadata) issues.push(...evaluateMetadataCompleteness(options.metadata));
1315
+ return { valid: false, issues, summary: summarizeIssues(issues) };
1768
1316
  }
1769
1317
  const coinbaseParsed = parseWithCoinbaseStructuralGate(payload, issues);
1770
1318
  const versionRaw = payload.x402Version;
@@ -1772,14 +1320,14 @@ function validatePaymentRequiredDetailed(payload, options = {}) {
1772
1320
  if (versionRaw === 1 || versionRaw === 2) {
1773
1321
  version = versionRaw;
1774
1322
  } else if (versionRaw === void 0) {
1775
- pushIssue(issues, {
1323
+ pushIssue2(issues, {
1776
1324
  code: VALIDATION_CODES.X402_VERSION_MISSING,
1777
1325
  severity: "error",
1778
1326
  message: "x402Version is required",
1779
1327
  path: "x402Version"
1780
1328
  });
1781
1329
  } else {
1782
- pushIssue(issues, {
1330
+ pushIssue2(issues, {
1783
1331
  code: VALIDATION_CODES.X402_VERSION_UNSUPPORTED,
1784
1332
  severity: "error",
1785
1333
  message: `Unsupported x402Version '${String(versionRaw)}'`,
@@ -1791,14 +1339,14 @@ function validatePaymentRequiredDetailed(payload, options = {}) {
1791
1339
  const acceptsRaw = payload.accepts;
1792
1340
  let accepts = [];
1793
1341
  if (acceptsRaw === void 0) {
1794
- pushIssue(issues, {
1342
+ pushIssue2(issues, {
1795
1343
  code: VALIDATION_CODES.X402_ACCEPTS_MISSING,
1796
1344
  severity: "error",
1797
1345
  message: "accepts is required",
1798
1346
  path: "accepts"
1799
1347
  });
1800
1348
  } else if (!Array.isArray(acceptsRaw)) {
1801
- pushIssue(issues, {
1349
+ pushIssue2(issues, {
1802
1350
  code: VALIDATION_CODES.X402_ACCEPTS_INVALID,
1803
1351
  severity: "error",
1804
1352
  message: "accepts must be an array",
@@ -1807,7 +1355,7 @@ function validatePaymentRequiredDetailed(payload, options = {}) {
1807
1355
  } else {
1808
1356
  accepts = acceptsRaw;
1809
1357
  if (accepts.length === 0) {
1810
- pushIssue(issues, {
1358
+ pushIssue2(issues, {
1811
1359
  code: VALIDATION_CODES.X402_ACCEPTS_EMPTY,
1812
1360
  severity: "error",
1813
1361
  message: "accepts must contain at least one payment requirement",
@@ -1815,52 +1363,45 @@ function validatePaymentRequiredDetailed(payload, options = {}) {
1815
1363
  });
1816
1364
  }
1817
1365
  }
1818
- const normalizedAccepts = [];
1819
1366
  if (version && Array.isArray(accepts)) {
1820
- accepts.forEach((accept, index) => {
1821
- const normalized = validateAccept(accept, index, version, issues);
1822
- if (normalized) normalizedAccepts.push(normalized);
1823
- });
1367
+ const normalizedAccepts = version === 1 ? validateAccepts(accepts, issues) : validateAccepts2(accepts, issues);
1824
1368
  const schemaPresence = getSchemaPresence(payload, accepts, version);
1825
1369
  if (requireInputSchema && !schemaPresence.hasInputSchema) {
1826
- pushIssue(issues, {
1370
+ pushIssue2(issues, {
1827
1371
  code: VALIDATION_CODES.SCHEMA_INPUT_MISSING,
1828
1372
  severity: "error",
1829
1373
  message: "Input schema is missing",
1830
1374
  hint: "Include input schema details so clients can invoke the endpoint correctly.",
1831
- path: version === 1 ? "accepts[0].outputSchema.input" : "extensions.bazaar.info.input"
1375
+ path: version === 1 ? "accepts[0].outputSchema.input" : "extensions.bazaar.schema.properties.input"
1832
1376
  });
1833
1377
  }
1834
1378
  if (requireOutputSchema && !schemaPresence.hasOutputSchema) {
1835
- pushIssue(issues, {
1379
+ pushIssue2(issues, {
1836
1380
  code: VALIDATION_CODES.SCHEMA_OUTPUT_MISSING,
1837
1381
  severity: outputSchemaMissingSeverity(compatMode),
1838
1382
  message: "Output schema is missing",
1839
1383
  hint: "Include output schema details so clients can validate responses.",
1840
- path: version === 1 ? "accepts[0].outputSchema.output" : "extensions.bazaar.info.output"
1384
+ path: version === 1 ? "accepts[0].outputSchema.output" : "extensions.bazaar.schema.properties.output"
1841
1385
  });
1842
1386
  }
1843
- if (options.metadata) {
1844
- issues.push(...evaluateMetadataCompleteness(options.metadata));
1845
- }
1387
+ if (options.metadata) issues.push(...evaluateMetadataCompleteness(options.metadata));
1846
1388
  const summary2 = summarizeIssues(issues);
1389
+ const normalized = {
1390
+ version,
1391
+ accepts: normalizedAccepts,
1392
+ hasInputSchema: schemaPresence.hasInputSchema,
1393
+ hasOutputSchema: schemaPresence.hasOutputSchema
1394
+ };
1847
1395
  return {
1848
1396
  valid: summary2.errorCount === 0,
1849
1397
  version,
1850
1398
  parsed: coinbaseParsed ?? payload,
1851
- normalized: {
1852
- version,
1853
- accepts: normalizedAccepts,
1854
- hasInputSchema: schemaPresence.hasInputSchema,
1855
- hasOutputSchema: schemaPresence.hasOutputSchema
1856
- },
1399
+ normalized,
1857
1400
  issues,
1858
1401
  summary: summary2
1859
1402
  };
1860
1403
  }
1861
- if (options.metadata) {
1862
- issues.push(...evaluateMetadataCompleteness(options.metadata));
1863
- }
1404
+ if (options.metadata) issues.push(...evaluateMetadataCompleteness(options.metadata));
1864
1405
  const summary = summarizeIssues(issues);
1865
1406
  return {
1866
1407
  valid: summary.errorCount === 0,
@@ -1871,645 +1412,202 @@ function validatePaymentRequiredDetailed(payload, options = {}) {
1871
1412
  };
1872
1413
  }
1873
1414
 
1874
- // src/adapters/mcp.ts
1875
- var DEFAULT_GUIDANCE_AUTO_INCLUDE_MAX_TOKENS = 1e3;
1876
- var OPENAPI_METHODS = [
1877
- "GET",
1878
- "POST",
1879
- "PUT",
1880
- "DELETE",
1881
- "PATCH",
1882
- "HEAD",
1883
- "OPTIONS",
1884
- "TRACE"
1885
- ];
1886
- function toFiniteNumber(value) {
1887
- if (typeof value === "number" && Number.isFinite(value)) return value;
1888
- if (typeof value === "string" && value.trim().length > 0) {
1889
- const parsed = Number(value);
1890
- if (Number.isFinite(parsed)) return parsed;
1891
- }
1892
- return void 0;
1893
- }
1894
- function formatPriceHintFromResource(resource) {
1895
- const pricing = resource.pricing;
1896
- if (pricing) {
1897
- if (pricing.pricingMode === "fixed" && pricing.price) {
1898
- return pricing.price.startsWith("$") ? pricing.price : `$${pricing.price}`;
1899
- }
1900
- if (pricing.pricingMode === "range" && pricing.minPrice && pricing.maxPrice) {
1901
- const min = pricing.minPrice.startsWith("$") ? pricing.minPrice : `$${pricing.minPrice}`;
1902
- const max = pricing.maxPrice.startsWith("$") ? pricing.maxPrice : `$${pricing.maxPrice}`;
1903
- return `${min}-${max}`;
1904
- }
1415
+ // src/audit/codes.ts
1416
+ var AUDIT_CODES = {
1417
+ // ─── Source presence ─────────────────────────────────────────────────────────
1418
+ OPENAPI_NOT_FOUND: "OPENAPI_NOT_FOUND",
1419
+ WELLKNOWN_NOT_FOUND: "WELLKNOWN_NOT_FOUND",
1420
+ // ─── OpenAPI quality ─────────────────────────────────────────────────────────
1421
+ OPENAPI_NO_ROUTES: "OPENAPI_NO_ROUTES",
1422
+ // ─── L2 route-list checks ────────────────────────────────────────────────────
1423
+ L2_NO_ROUTES: "L2_NO_ROUTES",
1424
+ L2_ROUTE_COUNT_HIGH: "L2_ROUTE_COUNT_HIGH",
1425
+ L2_AUTH_MODE_MISSING: "L2_AUTH_MODE_MISSING",
1426
+ L2_PRICE_MISSING_ON_PAID: "L2_PRICE_MISSING_ON_PAID",
1427
+ L2_PROTOCOLS_MISSING_ON_PAID: "L2_PROTOCOLS_MISSING_ON_PAID",
1428
+ // ─── L3 endpoint advisory checks ─────────────────────────────────────────────
1429
+ L3_NOT_FOUND: "L3_NOT_FOUND",
1430
+ L3_INPUT_SCHEMA_MISSING: "L3_INPUT_SCHEMA_MISSING",
1431
+ L3_AUTH_MODE_MISSING: "L3_AUTH_MODE_MISSING",
1432
+ L3_PROTOCOLS_MISSING_ON_PAID: "L3_PROTOCOLS_MISSING_ON_PAID",
1433
+ // ─── L4 guidance checks ──────────────────────────────────────────────────────
1434
+ L4_GUIDANCE_MISSING: "L4_GUIDANCE_MISSING",
1435
+ L4_GUIDANCE_TOO_LONG: "L4_GUIDANCE_TOO_LONG"
1436
+ };
1437
+
1438
+ // src/audit/warnings.ts
1439
+ var GUIDANCE_TOO_LONG_CHARS = 4e3;
1440
+ var ROUTE_COUNT_HIGH = 40;
1441
+ function getWarningsForOpenAPI(openApi) {
1442
+ if (openApi === null) {
1443
+ return [
1444
+ {
1445
+ code: AUDIT_CODES.OPENAPI_NOT_FOUND,
1446
+ severity: "info",
1447
+ message: "No OpenAPI specification found at this origin.",
1448
+ hint: "Expose an OpenAPI spec (e.g. /openapi.json) for richer discovery."
1449
+ }
1450
+ ];
1905
1451
  }
1906
- if (!resource.priceHint) return void 0;
1907
- const hint = resource.priceHint.trim();
1908
- if (hint.length === 0) return void 0;
1909
- if (hint.startsWith("$")) return hint;
1910
- if (hint.includes("-")) {
1911
- const [min, max] = hint.split("-", 2).map((part) => part.trim());
1912
- if (min && max) return `$${min}-$${max}`;
1452
+ const warnings = [];
1453
+ if (openApi.routes.length === 0) {
1454
+ warnings.push({
1455
+ code: AUDIT_CODES.OPENAPI_NO_ROUTES,
1456
+ severity: "warn",
1457
+ message: "OpenAPI spec found but contains no route definitions.",
1458
+ hint: "Add paths to your OpenAPI spec so agents can discover endpoints.",
1459
+ path: "paths"
1460
+ });
1913
1461
  }
1914
- return `$${hint}`;
1462
+ return warnings;
1915
1463
  }
1916
- function deriveMcpAuthMode(resource) {
1917
- if (!resource) return void 0;
1918
- const hint = resource.authHint;
1919
- if (hint === "paid" || hint === "siwx" || hint === "apiKey" || hint === "unprotected") {
1920
- return hint;
1464
+ function getWarningsForWellKnown(wellKnown) {
1465
+ if (wellKnown === null) {
1466
+ return [
1467
+ {
1468
+ code: AUDIT_CODES.WELLKNOWN_NOT_FOUND,
1469
+ severity: "info",
1470
+ message: "No /.well-known/x402 resource found at this origin.",
1471
+ hint: "Expose /.well-known/x402 as a fallback for agents that cannot read OpenAPI."
1472
+ }
1473
+ ];
1921
1474
  }
1922
- return void 0;
1475
+ return [];
1923
1476
  }
1924
- function inferFailureCause(warnings) {
1925
- const openapiWarnings = warnings.filter((w) => w.stage === "openapi");
1926
- const parseWarning = openapiWarnings.find(
1927
- (w) => w.code === "PARSE_FAILED" || w.code === "OPENAPI_TOP_LEVEL_INVALID" || w.code === "OPENAPI_OPERATION_INVALID" || w.code === "OPENAPI_PRICING_INVALID"
1928
- );
1929
- if (parseWarning) {
1930
- return { cause: "parse", message: parseWarning.message };
1477
+ function getWarningsForL2(l2) {
1478
+ const warnings = [];
1479
+ if (l2.routes.length === 0) {
1480
+ warnings.push({
1481
+ code: AUDIT_CODES.L2_NO_ROUTES,
1482
+ severity: "warn",
1483
+ message: "No routes found from any discovery source."
1484
+ });
1485
+ return warnings;
1931
1486
  }
1932
- const fetchWarning = openapiWarnings.find((w) => w.code === "FETCH_FAILED");
1933
- if (fetchWarning) {
1934
- const msg = fetchWarning.message.toLowerCase();
1935
- if (msg.includes("timeout") || msg.includes("timed out") || msg.includes("abort")) {
1936
- return { cause: "timeout", message: fetchWarning.message };
1937
- }
1938
- return { cause: "network", message: fetchWarning.message };
1487
+ if (l2.routes.length > ROUTE_COUNT_HIGH) {
1488
+ warnings.push({
1489
+ code: AUDIT_CODES.L2_ROUTE_COUNT_HIGH,
1490
+ severity: "warn",
1491
+ message: `High route count (${l2.routes.length}) may exceed agent token budgets for zero-hop injection.`,
1492
+ hint: "Consider grouping routes or reducing the advertised surface."
1493
+ });
1939
1494
  }
1940
- return { cause: "not_found" };
1941
- }
1942
- function getOpenApiInfo(document) {
1943
- if (!isRecord3(document) || !isRecord3(document.info)) return void 0;
1944
- if (typeof document.info.title !== "string") return void 0;
1945
- return {
1946
- title: document.info.title,
1947
- ...typeof document.info.version === "string" ? { version: document.info.version } : {},
1948
- ...typeof document.info.description === "string" ? { description: document.info.description } : {}
1949
- };
1950
- }
1951
- function getGuidanceUrl(result) {
1952
- const fromTrace = result.trace.find((entry) => entry.links?.llmsTxtUrl)?.links?.llmsTxtUrl;
1953
- if (fromTrace) return fromTrace;
1954
- const fromResource = result.resources.find((resource) => resource.links?.llmsTxtUrl)?.links?.llmsTxtUrl;
1955
- if (fromResource) return fromResource;
1956
- return void 0;
1957
- }
1958
- async function resolveGuidance(options) {
1959
- let guidanceText = typeof options.result.rawSources?.llmsTxt === "string" ? options.result.rawSources.llmsTxt : void 0;
1960
- if (!guidanceText) {
1961
- const guidanceUrl = getGuidanceUrl(options.result) ?? `${options.result.origin}/llms.txt`;
1962
- const fetcher = options.fetcher ?? fetch;
1963
- try {
1964
- const response = await fetcher(guidanceUrl, {
1965
- method: "GET",
1966
- headers: { Accept: "text/plain", ...options.headers },
1967
- signal: options.signal
1495
+ for (const route of l2.routes) {
1496
+ const loc = `${route.method} ${route.path}`;
1497
+ if (!route.authMode) {
1498
+ warnings.push({
1499
+ code: AUDIT_CODES.L2_AUTH_MODE_MISSING,
1500
+ severity: "warn",
1501
+ message: `Route ${loc} is missing an auth mode declaration.`,
1502
+ hint: "Set x-payment-info.authMode (or securitySchemes) so agents know if payment is required.",
1503
+ path: route.path
1968
1504
  });
1969
- if (response.ok) guidanceText = await response.text();
1970
- } catch {
1971
- }
1972
- }
1973
- if (!guidanceText) {
1974
- return { guidanceAvailable: false };
1975
- }
1976
- const guidanceTokens = estimateTokenCount(guidanceText);
1977
- const threshold = options.guidanceAutoIncludeMaxTokens ?? DEFAULT_GUIDANCE_AUTO_INCLUDE_MAX_TOKENS;
1978
- const shouldInclude = options.includeGuidance === true || options.includeGuidance == null && guidanceTokens <= threshold;
1979
- return {
1980
- guidanceAvailable: true,
1981
- guidanceTokens,
1982
- ...shouldInclude ? { guidance: guidanceText } : {}
1983
- };
1984
- }
1985
- function extractPathsDocument(document) {
1986
- if (!isRecord3(document)) return void 0;
1987
- if (!isRecord3(document.paths)) return void 0;
1988
- return document.paths;
1989
- }
1990
- function findMatchingOpenApiPath(paths, targetPath) {
1991
- const exact = paths[targetPath];
1992
- if (isRecord3(exact)) return { matchedPath: targetPath, pathItem: exact };
1993
- for (const [specPath, entry] of Object.entries(paths)) {
1994
- if (!isRecord3(entry)) continue;
1995
- const pattern = specPath.replace(/\{[^}]+\}/g, "[^/]+");
1996
- const regex = new RegExp(`^${pattern}$`);
1997
- if (regex.test(targetPath)) {
1998
- return { matchedPath: specPath, pathItem: entry };
1999
1505
  }
2000
- }
2001
- return null;
2002
- }
2003
- function resolveRef(document, ref, seen) {
2004
- if (!ref.startsWith("#/")) return void 0;
2005
- if (seen.has(ref)) return { $circular: ref };
2006
- seen.add(ref);
2007
- const parts = ref.slice(2).split("/");
2008
- let current = document;
2009
- for (const part of parts) {
2010
- if (!isRecord3(current)) return void 0;
2011
- current = current[part];
2012
- if (current === void 0) return void 0;
2013
- }
2014
- if (isRecord3(current)) return resolveRefs(document, current, seen);
2015
- return current;
2016
- }
2017
- function resolveRefs(document, obj, seen, depth = 0) {
2018
- if (depth > 4) return obj;
2019
- const resolved = {};
2020
- for (const [key, value] of Object.entries(obj)) {
2021
- if (key === "$ref" && typeof value === "string") {
2022
- const deref = resolveRef(document, value, seen);
2023
- if (isRecord3(deref)) {
2024
- Object.assign(resolved, deref);
2025
- } else {
2026
- resolved[key] = value;
1506
+ if (route.authMode === "paid") {
1507
+ if (!route.price) {
1508
+ warnings.push({
1509
+ code: AUDIT_CODES.L2_PRICE_MISSING_ON_PAID,
1510
+ severity: "warn",
1511
+ message: `Paid route ${loc} has no price hint.`,
1512
+ hint: "Add x-payment-info.price (or minPrice/maxPrice) so agents can budget before calling.",
1513
+ path: route.path
1514
+ });
1515
+ }
1516
+ if (!route.protocols?.length) {
1517
+ warnings.push({
1518
+ code: AUDIT_CODES.L2_PROTOCOLS_MISSING_ON_PAID,
1519
+ severity: "info",
1520
+ message: `Paid route ${loc} does not declare supported payment protocols.`,
1521
+ hint: "Add x-payment-info.protocols (e.g. ['x402']) to signal which payment flows are accepted.",
1522
+ path: route.path
1523
+ });
2027
1524
  }
2028
- continue;
2029
- }
2030
- if (isRecord3(value)) {
2031
- resolved[key] = resolveRefs(document, value, seen, depth + 1);
2032
- continue;
2033
- }
2034
- if (Array.isArray(value)) {
2035
- resolved[key] = value.map(
2036
- (item) => isRecord3(item) ? resolveRefs(document, item, seen, depth + 1) : item
2037
- );
2038
- continue;
2039
- }
2040
- resolved[key] = value;
2041
- }
2042
- return resolved;
2043
- }
2044
- function extractRequestBodySchema(operationSchema) {
2045
- const requestBody = operationSchema.requestBody;
2046
- if (!isRecord3(requestBody)) return void 0;
2047
- const content = requestBody.content;
2048
- if (!isRecord3(content)) return void 0;
2049
- const jsonMediaType = content["application/json"];
2050
- if (isRecord3(jsonMediaType) && isRecord3(jsonMediaType.schema)) {
2051
- return jsonMediaType.schema;
2052
- }
2053
- for (const mediaType of Object.values(content)) {
2054
- if (isRecord3(mediaType) && isRecord3(mediaType.schema)) {
2055
- return mediaType.schema;
2056
- }
2057
- }
2058
- return void 0;
2059
- }
2060
- function extractParameters(operationSchema) {
2061
- const params = operationSchema.parameters;
2062
- if (!Array.isArray(params)) return [];
2063
- return params.filter((value) => isRecord3(value));
2064
- }
2065
- function extractInputSchema(operationSchema) {
2066
- const requestBody = extractRequestBodySchema(operationSchema);
2067
- const parameters = extractParameters(operationSchema);
2068
- if (!requestBody && parameters.length === 0) return void 0;
2069
- if (requestBody && parameters.length === 0) return requestBody;
2070
- return {
2071
- ...requestBody ? { requestBody } : {},
2072
- ...parameters.length > 0 ? { parameters } : {}
2073
- };
2074
- }
2075
- function parseOperationPrice(operation) {
2076
- const paymentInfo = operation["x-payment-info"];
2077
- if (!isRecord3(paymentInfo)) return void 0;
2078
- const fixed = toFiniteNumber(paymentInfo.price);
2079
- if (fixed != null) return `$${String(fixed)}`;
2080
- const min = toFiniteNumber(paymentInfo.minPrice);
2081
- const max = toFiniteNumber(paymentInfo.maxPrice);
2082
- if (min != null && max != null) return `$${String(min)}-$${String(max)}`;
2083
- return void 0;
2084
- }
2085
- function parseOperationProtocols(operation) {
2086
- const paymentInfo = operation["x-payment-info"];
2087
- if (!isRecord3(paymentInfo) || !Array.isArray(paymentInfo.protocols)) return void 0;
2088
- const protocols = paymentInfo.protocols.filter(
2089
- (protocol) => typeof protocol === "string" && protocol.length > 0
2090
- );
2091
- return protocols.length > 0 ? protocols : void 0;
2092
- }
2093
- function createResourceMap(result) {
2094
- const map = /* @__PURE__ */ new Map();
2095
- for (const resource of result.resources) {
2096
- map.set(resource.resourceKey, resource);
2097
- }
2098
- return map;
2099
- }
2100
- function toMcpEndpointSummary(resource) {
2101
- const method = parseMethod(resource.method);
2102
- if (!method) return void 0;
2103
- const price = formatPriceHintFromResource(resource);
2104
- const authMode = deriveMcpAuthMode(resource);
2105
- return {
2106
- path: resource.path,
2107
- method,
2108
- summary: resource.summary ?? `${method} ${resource.path}`,
2109
- ...price ? { price } : {},
2110
- ...resource.protocolHints?.length ? { protocols: [...resource.protocolHints] } : {},
2111
- ...authMode ? { authMode } : {}
2112
- };
2113
- }
2114
- async function discoverForMcp(options) {
2115
- const result = await runDiscovery({
2116
- detailed: true,
2117
- options: {
2118
- target: options.target,
2119
- compatMode: options.compatMode ?? "off",
2120
- rawView: "full",
2121
- fetcher: options.fetcher,
2122
- headers: options.headers,
2123
- signal: options.signal
2124
1525
  }
2125
- });
2126
- if (result.resources.length === 0) {
2127
- const failure = inferFailureCause(result.warnings);
2128
- return {
2129
- found: false,
2130
- origin: result.origin,
2131
- cause: failure.cause,
2132
- ...failure.message ? { message: failure.message } : {},
2133
- warnings: result.warnings
2134
- };
2135
1526
  }
2136
- const source = result.selectedStage ?? "openapi";
2137
- const endpoints = result.resources.map(toMcpEndpointSummary).filter((endpoint) => endpoint != null).sort((a, b) => {
2138
- if (a.path !== b.path) return a.path.localeCompare(b.path);
2139
- return a.method.localeCompare(b.method);
2140
- });
2141
- const guidance = await resolveGuidance({
2142
- result,
2143
- includeGuidance: options.includeGuidance,
2144
- guidanceAutoIncludeMaxTokens: options.guidanceAutoIncludeMaxTokens,
2145
- fetcher: options.fetcher,
2146
- headers: options.headers,
2147
- signal: options.signal
2148
- });
2149
- return {
2150
- found: true,
2151
- origin: result.origin,
2152
- source,
2153
- ...getOpenApiInfo(result.rawSources?.openapi) ? { info: getOpenApiInfo(result.rawSources?.openapi) } : {},
2154
- ...guidance,
2155
- endpoints,
2156
- warnings: result.warnings
2157
- };
1527
+ return warnings;
2158
1528
  }
2159
- async function inspectEndpointForMcp(options) {
2160
- const endpoint = new URL(options.endpointUrl);
2161
- const origin = normalizeOrigin(endpoint.origin);
2162
- const path = normalizePath(endpoint.pathname || "/");
2163
- const result = await runDiscovery({
2164
- detailed: true,
2165
- options: {
2166
- target: options.target,
2167
- compatMode: options.compatMode ?? "off",
2168
- rawView: "full",
2169
- fetcher: options.fetcher,
2170
- headers: options.headers,
2171
- signal: options.signal
2172
- }
2173
- });
2174
- const document = result.rawSources?.openapi;
2175
- const paths = extractPathsDocument(document);
2176
- const resourceMap = createResourceMap(result);
2177
- const advisories = {};
2178
- const specMethods = [];
2179
- if (paths) {
2180
- const matched = findMatchingOpenApiPath(paths, path);
2181
- if (matched) {
2182
- for (const candidate of OPENAPI_METHODS) {
2183
- const operation = matched.pathItem[candidate.toLowerCase()];
2184
- if (!isRecord3(operation) || !isRecord3(document)) continue;
2185
- specMethods.push(candidate);
2186
- const resolvedOperation = resolveRefs(document, operation, /* @__PURE__ */ new Set());
2187
- const resource = resourceMap.get(toResourceKey(origin, candidate, matched.matchedPath));
2188
- const formattedPrice = resource ? formatPriceHintFromResource(resource) : void 0;
2189
- const operationSummary = typeof resolvedOperation.summary === "string" ? resolvedOperation.summary : typeof resolvedOperation.description === "string" ? resolvedOperation.description : void 0;
2190
- const operationPrice = parseOperationPrice(resolvedOperation);
2191
- const operationProtocols = parseOperationProtocols(resolvedOperation);
2192
- const operationAuthMode = inferAuthMode(resolvedOperation) ?? "unprotected";
2193
- const inputSchema = extractInputSchema(resolvedOperation);
2194
- advisories[candidate] = {
2195
- method: candidate,
2196
- ...resource?.summary || operationSummary ? {
2197
- summary: resource?.summary ?? operationSummary
2198
- } : {},
2199
- ...formattedPrice || operationPrice ? {
2200
- estimatedPrice: formattedPrice ?? operationPrice
2201
- } : {},
2202
- ...resource?.protocolHints?.length || operationProtocols ? {
2203
- protocols: resource?.protocolHints ?? operationProtocols
2204
- } : {},
2205
- ...deriveMcpAuthMode(resource) || operationAuthMode ? {
2206
- authMode: deriveMcpAuthMode(resource) ?? operationAuthMode
2207
- } : {},
2208
- ...inputSchema ? { inputSchema } : {},
2209
- operationSchema: resolvedOperation
2210
- };
1529
+ function getWarningsForL3(l3) {
1530
+ if (l3 === null) {
1531
+ return [
1532
+ {
1533
+ code: AUDIT_CODES.L3_NOT_FOUND,
1534
+ severity: "info",
1535
+ message: "No spec data found for this endpoint.",
1536
+ hint: "Ensure the path is defined in your OpenAPI spec or reachable via probe."
2211
1537
  }
2212
- }
2213
- }
2214
- if (specMethods.length === 0) {
2215
- for (const method of OPENAPI_METHODS) {
2216
- const resource = resourceMap.get(toResourceKey(origin, method, path));
2217
- if (!resource) continue;
2218
- specMethods.push(method);
2219
- const formattedPrice = formatPriceHintFromResource(resource);
2220
- advisories[method] = {
2221
- method,
2222
- ...resource.summary ? { summary: resource.summary } : {},
2223
- ...formattedPrice ? { estimatedPrice: formattedPrice } : {},
2224
- ...resource.protocolHints?.length ? { protocols: [...resource.protocolHints] } : {},
2225
- ...deriveMcpAuthMode(resource) ? { authMode: deriveMcpAuthMode(resource) } : {}
2226
- };
2227
- }
2228
- }
2229
- if (specMethods.length === 0) {
2230
- const failure = inferFailureCause(result.warnings);
2231
- return {
2232
- found: false,
2233
- origin,
2234
- path,
2235
- cause: failure.cause,
2236
- ...failure.message ? { message: failure.message } : {},
2237
- warnings: result.warnings
2238
- };
1538
+ ];
2239
1539
  }
2240
- return {
2241
- found: true,
2242
- origin,
2243
- path,
2244
- specMethods,
2245
- advisories,
2246
- warnings: result.warnings
2247
- };
2248
- }
2249
-
2250
- // src/harness.ts
2251
- var INTENT_TRIGGERS = ["x402", "mpp", "pay for", "micropayment", "agentic commerce"];
2252
- var CLIENT_PROFILES = {
2253
- "claude-code": {
2254
- id: "claude-code",
2255
- label: "Claude Code MCP Harness",
2256
- surface: "mcp",
2257
- defaultContextWindowTokens: 2e5,
2258
- zeroHopBudgetPercent: 0.1,
2259
- notes: "Targets environments where MCP context can use roughly 10% of total context."
2260
- },
2261
- "skill-cli": {
2262
- id: "skill-cli",
2263
- label: "Skill + CLI Harness",
2264
- surface: "skill-cli",
2265
- defaultContextWindowTokens: 2e5,
2266
- zeroHopBudgetPercent: 0.02,
2267
- notes: "Targets constrained skill contexts with title/description-heavy routing."
2268
- },
2269
- "generic-mcp": {
2270
- id: "generic-mcp",
2271
- label: "Generic MCP Harness",
2272
- surface: "mcp",
2273
- defaultContextWindowTokens: 128e3,
2274
- zeroHopBudgetPercent: 0.05,
2275
- notes: "Conservative MCP profile when specific client budgets are unknown."
2276
- },
2277
- generic: {
2278
- id: "generic",
2279
- label: "Generic Agent Harness",
2280
- surface: "generic",
2281
- defaultContextWindowTokens: 128e3,
2282
- zeroHopBudgetPercent: 0.03,
2283
- notes: "Fallback profile for unknown clients."
1540
+ const warnings = [];
1541
+ if (!l3.authMode) {
1542
+ warnings.push({
1543
+ code: AUDIT_CODES.L3_AUTH_MODE_MISSING,
1544
+ severity: "warn",
1545
+ message: "Endpoint has no auth mode in the spec.",
1546
+ hint: "Declare auth mode via security schemes or x-payment-info so agents can plan payment."
1547
+ });
2284
1548
  }
2285
- };
2286
- function isFirstPartyDomain(hostname) {
2287
- const normalized = hostname.toLowerCase();
2288
- return normalized.endsWith(".dev") && normalized.startsWith("stable");
2289
- }
2290
- function safeHostname(origin) {
2291
- try {
2292
- return new URL(origin).hostname;
2293
- } catch {
2294
- return origin.replace(/^https?:\/\//, "").split("/")[0] ?? origin;
1549
+ if (l3.authMode === "paid" && !l3.inputSchema) {
1550
+ warnings.push({
1551
+ code: AUDIT_CODES.L3_INPUT_SCHEMA_MISSING,
1552
+ severity: "warn",
1553
+ message: "Paid endpoint is missing an input schema.",
1554
+ hint: "Add a requestBody or parameters schema so agents can construct valid payloads."
1555
+ });
2295
1556
  }
2296
- }
2297
- function previewText(text) {
2298
- if (!text) return null;
2299
- const compact = text.replace(/\s+/g, " ").trim();
2300
- if (!compact) return null;
2301
- return compact.length > 220 ? `${compact.slice(0, 217)}...` : compact;
2302
- }
2303
- function toAuthModeCount(resources) {
2304
- const counts = {
2305
- paid: 0,
2306
- siwx: 0,
2307
- apiKey: 0,
2308
- unprotected: 0,
2309
- unknown: 0
2310
- };
2311
- for (const resource of resources) {
2312
- const mode = resource.authHint;
2313
- if (mode === "paid" || mode === "siwx" || mode === "apiKey" || mode === "unprotected") {
2314
- counts[mode] += 1;
2315
- } else {
2316
- counts.unknown += 1;
2317
- }
1557
+ if (l3.authMode === "paid" && !l3.protocols?.length) {
1558
+ warnings.push({
1559
+ code: AUDIT_CODES.L3_PROTOCOLS_MISSING_ON_PAID,
1560
+ severity: "info",
1561
+ message: "Paid endpoint does not declare supported payment protocols.",
1562
+ hint: "Add x-payment-info.protocols (e.g. ['x402']) to the operation."
1563
+ });
2318
1564
  }
2319
- return counts;
2320
- }
2321
- function toSourceCount(resources) {
2322
- return resources.reduce(
2323
- (acc, resource) => {
2324
- acc[resource.source] = (acc[resource.source] ?? 0) + 1;
2325
- return acc;
2326
- },
2327
- {}
2328
- );
2329
- }
2330
- function toL2Entries(resources) {
2331
- return [...resources].sort((a, b) => {
2332
- if (a.path !== b.path) return a.path.localeCompare(b.path);
2333
- if (a.method !== b.method) return a.method.localeCompare(b.method);
2334
- return a.resourceKey.localeCompare(b.resourceKey);
2335
- }).map((resource) => ({
2336
- resourceKey: resource.resourceKey,
2337
- method: resource.method,
2338
- path: resource.path,
2339
- source: resource.source,
2340
- authMode: resource.authHint ?? null
2341
- }));
1565
+ return warnings;
2342
1566
  }
2343
- function getLlmsTxtInfo(result) {
2344
- const llmsTxtUrl = result.trace.find((entry) => entry.links?.llmsTxtUrl)?.links?.llmsTxtUrl ?? result.resources.find((resource) => resource.links?.llmsTxtUrl)?.links?.llmsTxtUrl ?? null;
2345
- const llmsTxt = result.rawSources?.llmsTxt;
2346
- if (llmsTxt) {
2347
- return {
2348
- llmsTxtUrl,
2349
- llmsTxtTokenEstimate: estimateTokenCount(llmsTxt),
2350
- guidancePreview: previewText(llmsTxt),
2351
- guidanceStatus: "present"
2352
- };
2353
- }
2354
- if (llmsTxtUrl) {
2355
- const failed = result.warnings.some((warning2) => warning2.code === "LLMSTXT_FETCH_FAILED");
2356
- return {
2357
- llmsTxtUrl,
2358
- llmsTxtTokenEstimate: 0,
2359
- guidancePreview: null,
2360
- guidanceStatus: failed ? "advertised_but_unfetched" : "missing"
2361
- };
1567
+ function getWarningsForL4(l4) {
1568
+ if (l4 === null) {
1569
+ return [
1570
+ {
1571
+ code: AUDIT_CODES.L4_GUIDANCE_MISSING,
1572
+ severity: "info",
1573
+ message: "No guidance text found (llms.txt or OpenAPI info.guidance).",
1574
+ hint: "Add an info.guidance field to your OpenAPI spec or expose /llms.txt for agent-readable instructions."
1575
+ }
1576
+ ];
2362
1577
  }
2363
- return {
2364
- llmsTxtUrl: null,
2365
- llmsTxtTokenEstimate: 0,
2366
- guidancePreview: null,
2367
- guidanceStatus: "not_advertised"
2368
- };
2369
- }
2370
- function getHarnessClientProfile(client = "claude-code") {
2371
- return CLIENT_PROFILES[client] ?? CLIENT_PROFILES.generic;
2372
- }
2373
- function listHarnessClientProfiles() {
2374
- return Object.values(CLIENT_PROFILES);
2375
- }
2376
- function buildContextHarnessReport(options) {
2377
- const client = getHarnessClientProfile(options.client);
2378
- const contextWindowTokens = options.contextWindowTokens ?? client.defaultContextWindowTokens;
2379
- const zeroHopBudgetTokens = Math.floor(contextWindowTokens * client.zeroHopBudgetPercent);
2380
- const hostname = safeHostname(options.result.origin);
2381
- const domainClass = isFirstPartyDomain(hostname) ? "first-party" : "ugc";
2382
- const l0Summary = "Route payment-capable intents to agentcash and use install/discover commands for progressive disclosure.";
2383
- const l1Summary = "Expose installed domain routing hints and trigger fan-out into L2/L3 commands when user intent matches domain capabilities.";
2384
- const l0EstimatedTokens = estimateTokenCount(
2385
- `${INTENT_TRIGGERS.join(", ")} npx agentcash install npx agentcash install-ext`
2386
- );
2387
- const l1EstimatedTokens = estimateTokenCount(
2388
- `${hostname} ${l1Summary} npx agentcash discover ${hostname} npx agentcash discover ${hostname} --verbose`
2389
- );
2390
- const llmsInfo = getLlmsTxtInfo(options.result);
2391
- return {
2392
- target: options.target,
2393
- origin: options.result.origin,
2394
- client,
2395
- budget: {
2396
- contextWindowTokens,
2397
- zeroHopBudgetTokens,
2398
- estimatedZeroHopTokens: l0EstimatedTokens + l1EstimatedTokens,
2399
- withinBudget: l0EstimatedTokens + l1EstimatedTokens <= zeroHopBudgetTokens
2400
- },
2401
- levels: {
2402
- l0: {
2403
- layer: "L0",
2404
- intentTriggers: INTENT_TRIGGERS,
2405
- installCommand: "npx agentcash install",
2406
- deliverySurfaces: ["MCP", "Skill+CLI"],
2407
- summary: l0Summary,
2408
- estimatedTokens: l0EstimatedTokens
2409
- },
2410
- l1: {
2411
- layer: "L1",
2412
- domain: hostname,
2413
- domainClass,
2414
- selectedDiscoveryStage: options.result.selectedStage ?? null,
2415
- summary: l1Summary,
2416
- fanoutCommands: [
2417
- `npx agentcash discover ${hostname}`,
2418
- `npx agentcash discover ${hostname} --verbose`
2419
- ],
2420
- estimatedTokens: l1EstimatedTokens
2421
- },
2422
- l2: {
2423
- layer: "L2",
2424
- command: `npx agentcash discover ${hostname}`,
2425
- tokenLight: true,
2426
- resourceCount: options.result.resources.length,
2427
- resources: toL2Entries(options.result.resources)
2428
- },
2429
- l3: {
2430
- layer: "L3",
2431
- command: `npx agentcash discover ${hostname} --verbose`,
2432
- detailLevel: "endpoint-schema-and-metadata",
2433
- countsByAuthMode: toAuthModeCount(options.result.resources),
2434
- countsBySource: toSourceCount(options.result.resources),
2435
- pricedResourceCount: options.result.resources.filter(
2436
- (resource) => resource.authHint === "paid"
2437
- ).length
2438
- },
2439
- l4: {
2440
- layer: "L4",
2441
- guidanceSource: llmsInfo.llmsTxtUrl ? "llms.txt" : "none",
2442
- llmsTxtUrl: llmsInfo.llmsTxtUrl,
2443
- llmsTxtTokenEstimate: llmsInfo.llmsTxtTokenEstimate,
2444
- guidancePreview: llmsInfo.guidancePreview,
2445
- guidanceStatus: llmsInfo.guidanceStatus
2446
- },
2447
- l5: {
2448
- layer: "L5",
2449
- status: "out_of_scope",
2450
- note: "Cross-domain composition is intentionally out of scope for discovery v1."
1578
+ if (l4.guidance.length > GUIDANCE_TOO_LONG_CHARS) {
1579
+ return [
1580
+ {
1581
+ code: AUDIT_CODES.L4_GUIDANCE_TOO_LONG,
1582
+ severity: "warn",
1583
+ message: `Guidance text is ${l4.guidance.length} characters, which may exceed zero-hop token budgets.`,
1584
+ hint: "Trim guidance to under ~4000 characters for reliable zero-hop context injection."
2451
1585
  }
2452
- },
2453
- diagnostics: {
2454
- warningCount: options.result.warnings.length,
2455
- errorWarningCount: options.result.warnings.filter((warning2) => warning2.severity === "error").length,
2456
- selectedStage: options.result.selectedStage ?? null,
2457
- upgradeSuggested: options.result.upgradeSuggested,
2458
- upgradeReasons: options.result.upgradeReasons
2459
- }
2460
- };
2461
- }
2462
- async function auditContextHarness(options) {
2463
- const result = await runDiscovery({
2464
- detailed: true,
2465
- options: {
2466
- ...options,
2467
- rawView: "full"
2468
- }
2469
- });
2470
- return buildContextHarnessReport({
2471
- target: options.target,
2472
- result,
2473
- client: options.client,
2474
- contextWindowTokens: options.contextWindowTokens
2475
- });
2476
- }
2477
- function defaultHarnessProbeCandidates(report) {
2478
- const methodsByPath = /* @__PURE__ */ new Map();
2479
- for (const resource of report.levels.l2.resources) {
2480
- const methods = methodsByPath.get(resource.path) ?? /* @__PURE__ */ new Set();
2481
- methods.add(resource.method);
2482
- methodsByPath.set(resource.path, methods);
1586
+ ];
2483
1587
  }
2484
- return [...methodsByPath.entries()].map(([path, methods]) => ({
2485
- path,
2486
- methods: [...methods]
2487
- }));
2488
- }
2489
-
2490
- // src/index.ts
2491
- async function discover(options) {
2492
- return await runDiscovery({ detailed: false, options });
2493
- }
2494
- async function discoverDetailed(options) {
2495
- return await runDiscovery({ detailed: true, options });
1588
+ return [];
2496
1589
  }
2497
1590
  export {
2498
- DEFAULT_COMPAT_MODE,
2499
- LEGACY_SUNSET_DATE,
2500
- STRICT_ESCALATION_CODES,
2501
- UPGRADE_WARNING_CODES,
1591
+ AUDIT_CODES,
1592
+ GuidanceMode,
2502
1593
  VALIDATION_CODES,
2503
- auditContextHarness,
2504
- buildContextHarnessReport,
2505
- computeUpgradeSignal,
2506
- defaultHarnessProbeCandidates,
2507
- discover,
2508
- discoverDetailed,
2509
- discoverForMcp,
1594
+ checkEndpointSchema,
1595
+ checkL2ForOpenAPI,
1596
+ checkL2ForWellknown,
1597
+ checkL4ForOpenAPI,
1598
+ checkL4ForWellknown,
1599
+ discoverOriginSchema,
2510
1600
  evaluateMetadataCompleteness,
2511
- getHarnessClientProfile,
2512
- inspectEndpointForMcp,
2513
- listHarnessClientProfiles,
1601
+ getL3,
1602
+ getL3ForOpenAPI,
1603
+ getL3ForProbe,
1604
+ getOpenAPI,
1605
+ getProbe,
1606
+ getWarningsForL2,
1607
+ getWarningsForL3,
1608
+ getWarningsForL4,
1609
+ getWarningsForOpenAPI,
1610
+ getWarningsForWellKnown,
1611
+ getWellKnown,
2514
1612
  validatePaymentRequiredDetailed
2515
1613
  };