Repository navigation
Expand file tree
/
Copy pathworker.js
More file actions
1334 lines (1308 loc) · 60.8 KB
/
Copy pathworker.js
File metadata and controls
1334 lines (1308 loc) · 60.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// BOUNDARY RULE: this tree implements what an unauthenticated caller can observe about
// CleanExtract and deliberately omits operator surfaces a caller cannot: Stripe issuance,
// bearer-gated admin stats, and funnel telemetry. A behaviour belongs here when an
// unauthenticated caller can observe it from outside; everything else stays out.
import { classifyOutcome, FETCH_TIMEOUT_MS } from "./outcome.js";
import { outlineMarkdown, selectSections, markdownFingerprint } from "./sections.js";
//
// HTML extraction and URL safety
function unescapeHtml(str) {
if (!str) return "";
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/ /g, " ").replace(/&#(\d+);/g, (match, dec) => String.fromCharCode(dec));
}
function plainText(html) {
return unescapeHtml((html || "").replace(/<br\s*[\/]?>/gi, " ").replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim();
}
function escapeTableCell(value) {
return plainText(value).replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
}
function htmlTableToMarkdown(tableHtml) {
const rows = [];
const rowPattern = /<tr\b[^>]*>([\s\S]*?)<\/tr>/gi;
let rowMatch;
while ((rowMatch = rowPattern.exec(tableHtml)) !== null) {
const cells = [];
let hasHeaderCell = false;
const cellPattern = /<(th|td)\b[^>]*>([\s\S]*?)<\/\1>/gi;
let cellMatch;
while ((cellMatch = cellPattern.exec(rowMatch[1])) !== null) {
hasHeaderCell = hasHeaderCell || cellMatch[1].toLowerCase() === "th";
cells.push(escapeTableCell(cellMatch[2]));
}
if (cells.length > 0) rows.push({ cells, hasHeaderCell });
}
if (rows.length === 0) return "";
const columnCount = Math.max(...rows.map((row) => row.cells.length));
const normalize = (cells) => [...cells, ...Array(columnCount - cells.length).fill("")];
const firstRowIsHeader = rows[0].hasHeaderCell;
const header = firstRowIsHeader ? normalize(rows[0].cells) : Array(columnCount).fill("");
const body = firstRowIsHeader ? rows.slice(1) : rows;
const lines = [
`| ${header.join(" | ")} |`,
`| ${Array(columnCount).fill("---").join(" | ")} |`,
...body.map((row) => `| ${normalize(row.cells).join(" | ")} |`)
];
return lines.join("\n");
}
function attributeValue(tag, attribute) {
const match = tag.match(new RegExp(`${attribute}\\s*=\\s*["']([^"']*)["']`, "i"));
return match ? unescapeHtml(match[1].trim()) : null;
}
function metaContent(rawHtml, selectors) {
const tags = rawHtml.match(/<meta\b[^>]*>/gi) || [];
for (const tag of tags) {
const name = (attributeValue(tag, "name") || attributeValue(tag, "property") || "").toLowerCase();
if (selectors.includes(name)) {
const content = attributeValue(tag, "content");
if (content) return content;
}
}
return null;
}
function extractHtmlMetadata(rawHtml, sourceUrl = null) {
const titleMatch = (rawHtml || "").match(/<title[^>]*>([\s\S]*?)<\/title>/i);
const htmlTag = (rawHtml || "").match(/<html\b[^>]*>/i)?.[0] || "";
const canonicalTag = (rawHtml || "").match(/<link\b[^>]*rel\s*=\s*["'][^"']*canonical[^"']*["'][^>]*>/i)?.[0] || (rawHtml || "").match(/<link\b[^>]*href\s*=\s*["'][^"']+["'][^>]*rel\s*=\s*["'][^"']*canonical[^"']*["'][^>]*>/i)?.[0] || "";
const canonicalHref = attributeValue(canonicalTag, "href");
let canonicalUrl = canonicalHref;
if (canonicalHref && sourceUrl) {
try {
canonicalUrl = new URL(canonicalHref, sourceUrl).toString();
} catch (error) {
canonicalUrl = canonicalHref;
}
}
return {
title: titleMatch ? plainText(titleMatch[1]) : "Extracted Content",
description: metaContent(rawHtml || "", ["description", "og:description", "twitter:description"]),
author: metaContent(rawHtml || "", ["author", "article:author"]),
published_time: metaContent(rawHtml || "", ["article:published_time", "date", "datepublished"]),
language: attributeValue(htmlTag, "lang"),
canonical_url: canonicalUrl || sourceUrl || null,
site_name: metaContent(rawHtml || "", ["og:site_name"])
};
}
function cleanHtmlToMarkdown(rawHtml, sourceUrl = null) {
let text = rawHtml || "";
const metadata = extractHtmlMetadata(text, sourceUrl);
const tables = [];
text = text.replace(/<table\b[^>]*>[\s\S]*?<\/table>/gi, (tableHtml) => {
const placeholder = `CLEANEXTRACT_TABLE_PLACEHOLDER_${tables.length}`;
tables.push(htmlTableToMarkdown(tableHtml));
return `
${placeholder}
`;
});
const title = metadata.title;
text = text.replace(/<title[^>]*>[\s\S]*?<\/title>/gi, "");
text = text.replace(/<(script|style|nav|footer|header|aside|iframe|noscript|svg)[^>]*>[\s\S]*?<\/\1>/gi, "");
text = text.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, "\n\n# $1\n\n");
text = text.replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, "\n\n## $1\n\n");
text = text.replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, "\n\n### $1\n\n");
text = text.replace(/<h[4-6][^>]*>([\s\S]*?)<\/h[4-6]>/gi, "\n\n#### $1\n\n");
text = text.replace(/<a[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi, (m, href, linkText) => {
const cleanLinkText = linkText.replace(/<[^>]+>/g, "").trim();
if (!cleanLinkText) return "";
return `[${cleanLinkText}](${href})`;
});
text = text.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, "\n- $1");
text = text.replace(/<p[^>]*>([\s\S]*?)<\/p>/gi, "\n\n$1\n\n");
text = text.replace(/<br\s*[\/]?>/gi, "\n");
text = text.replace(/<[^>]+>/g, " ");
text = unescapeHtml(text);
const lines = text.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
const markdownBody = lines.join("\n\n");
let finalMarkdown = sourceUrl ? `# ${title}
*Source: [${sourceUrl}](${sourceUrl})*
${markdownBody}` : `# ${title}
${markdownBody}`;
tables.forEach((table, index) => {
finalMarkdown = finalMarkdown.replace(`CLEANEXTRACT_TABLE_PLACEHOLDER_${index}`, table);
});
const rawBytes = rawHtml.length;
const cleanBytes = finalMarkdown.length;
const rawTokens = Math.max(1, Math.floor(rawBytes / 4));
const cleanTokens = Math.max(1, Math.floor(cleanBytes / 4));
const tokensSaved = Math.max(0, rawTokens - cleanTokens);
const compressionRatio = `${Math.max(0, Math.round((1 - cleanBytes / Math.max(1, rawBytes)) * 100))}%`;
return {
title,
markdown: finalMarkdown,
tokens_saved: tokensSaved,
compression_ratio: compressionRatio,
raw_bytes: rawBytes,
clean_bytes: cleanBytes,
metadata
};
}
function isSafePublicUrl(urlString) {
try {
const parsed = new URL(urlString);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
return { safe: false, reason: "Unsupported protocol (only HTTP/HTTPS allowed)" };
}
const hostname = parsed.hostname.toLowerCase().trim();
if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal") || hostname.endsWith(".lan") || hostname.endsWith(".home") || hostname.endsWith(".arpa") || hostname.endsWith(".corp")) {
return { safe: false, reason: "Local/internal hostname access is forbidden" };
}
const ipv4Regex = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
const ipMatch = hostname.match(ipv4Regex);
if (ipMatch) {
const o1 = parseInt(ipMatch[1], 10);
const o2 = parseInt(ipMatch[2], 10);
const o3 = parseInt(ipMatch[3], 10);
const o4 = parseInt(ipMatch[4], 10);
if ([o1, o2, o3, o4].some((octet) => octet < 0 || octet > 255)) {
return { safe: false, reason: "Invalid IPv4 address" };
}
if (o1 === 0) return { safe: false, reason: "Access to 0.0.0.0/8 is forbidden" };
if (o1 === 10) return { safe: false, reason: "Private RFC 1918 IP address forbidden" };
if (o1 === 100 && o2 >= 64 && o2 <= 127) return { safe: false, reason: "Carrier-grade NAT IP address forbidden" };
if (o1 === 127) return { safe: false, reason: "Loopback IP address forbidden" };
if (o1 === 169 && o2 === 254) return { safe: false, reason: "Cloud metadata / link-local IP forbidden" };
if (o1 === 172 && o2 >= 16 && o2 <= 31) return { safe: false, reason: "Private RFC 1918 IP address forbidden" };
if (o1 === 192 && o2 === 0 && o3 === 0) return { safe: false, reason: "Reserved IP address forbidden" };
if (o1 === 192 && o2 === 0 && o3 === 2 || o1 === 198 && o2 === 51 && o3 === 100 || o1 === 203 && o2 === 0 && o3 === 113) {
return { safe: false, reason: "Test/documentation IP address forbidden" };
}
if (o1 === 192 && o2 === 168) return { safe: false, reason: "Private RFC 1918 IP address forbidden" };
if (o1 >= 224) return { safe: false, reason: "Multicast or reserved IP address forbidden" };
}
if (hostname.includes(":")) {
const hClean = hostname.replace(/^\[|\]$/g, "").toLowerCase();
if (hClean === "::1" || hClean === "::" || hClean.startsWith("fc") || hClean.startsWith("fd") || hClean.startsWith("fe80") || hClean.startsWith("::ffff:")) {
return { safe: false, reason: "Private/loopback IPv6 address forbidden" };
}
}
return { safe: true, parsedUrl: parsed.toString() };
} catch (e) {
return { safe: false, reason: `Malformed URL: ${e.message}` };
}
}
var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
var ResponseSizeLimitError = class extends Error {
constructor(maxResponseBytes) {
super(`Upstream response exceeded ${maxResponseBytes}-byte limit`);
this.name = "ResponseSizeLimitError";
this.maxResponseBytes = maxResponseBytes;
}
};
function responseWithByteLimit(response, maxResponseBytes) {
const declaredBytes = Number(response.headers.get("Content-Length"));
if (Number.isFinite(declaredBytes) && declaredBytes > maxResponseBytes) {
response.body?.cancel().catch(() => {
});
throw new ResponseSizeLimitError(maxResponseBytes);
}
if (!response.body) return response;
const reader = response.body.getReader();
let receivedBytes = 0;
const limitedBody = new ReadableStream({
async pull(controller) {
try {
const { done, value } = await reader.read();
if (done) {
controller.close();
return;
}
receivedBytes += value.byteLength;
if (receivedBytes > maxResponseBytes) {
const error = new ResponseSizeLimitError(maxResponseBytes);
await reader.cancel(error).catch(() => {
});
controller.error(error);
return;
}
controller.enqueue(value);
} catch (error) {
controller.error(error);
}
},
cancel(reason) {
return reader.cancel(reason);
}
});
return new Response(limitedBody, {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
}
async function safeFetch(urlString, init = {}, { maxRedirects = 5, maxResponseBytes } = {}) {
if (!Number.isInteger(maxRedirects) || maxRedirects < 0) {
throw new TypeError("maxRedirects must be a non-negative integer");
}
if (maxResponseBytes !== void 0 && (!Number.isInteger(maxResponseBytes) || maxResponseBytes <= 0)) {
throw new TypeError("maxResponseBytes must be a positive integer");
}
let currentUrl = urlString;
for (let hop = 0; ; hop += 1) {
const safety = isSafePublicUrl(currentUrl);
if (!safety.safe) {
throw new Error(`SSRF blocked: ${safety.reason}`);
}
const response = await fetch(safety.parsedUrl, { ...init, redirect: "manual" });
if (!REDIRECT_STATUSES.has(response.status)) {
return maxResponseBytes === void 0 ? response : responseWithByteLimit(response, maxResponseBytes);
}
const location = response.headers.get("Location");
if (!location) {
return response;
}
if (hop >= maxRedirects) {
throw new Error(`Redirect limit exceeded (${maxRedirects})`);
}
await response.body?.cancel();
currentUrl = new URL(location, safety.parsedUrl).toString();
}
}
// MCP transport and CORS
function corsHeaders() {
return {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, PAYMENT-SIGNATURE, X-402-Payment-Proof, MCP-Protocol-Version, Mcp-Method, Mcp-Name",
"Access-Control-Expose-Headers": "PAYMENT-REQUIRED, PAYMENT-RESPONSE, WWW-Authenticate, X-402-Payment-Required, X-402-Price-USD, X-402-Network, X-402-Receiver-Address, X-402-Token-Contract, MCP-Protocol-Version"
};
}
function validateMcpOrigin(request) {
const origin = request.headers.get("Origin");
if (!origin) return true;
try {
const parsed = new URL(origin);
return parsed.protocol === "https:"
&& parsed.hostname.toLowerCase() === "extract.getstringer.app";
} catch (e) {
return false;
}
}
function forbiddenOriginResponse() {
return new Response(JSON.stringify({ error: "Forbidden Origin" }), {
status: 403,
headers: {
"Content-Type": "application/json",
"Vary": "Origin"
}
});
}
function mcpJson(payload, status = 200, extraHeaders = {}) {
return new Response(JSON.stringify(payload), {
status,
headers: {
"Content-Type": "application/json",
...corsHeaders(),
...extraHeaders
}
});
}
function mcpError(id, code, message, status = 400, data = null) {
const error = { code, message };
if (data !== null) {
error.data = data;
}
return mcpJson({ jsonrpc: "2.0", id: id ?? null, error }, status);
}
// x402 v2 payment verification and settlement
var RECEIVER_ADDRESS = "0xAA2a4F7092d05E8e801fcF2711a5146702CCF9a1";
var USDC_CONTRACT_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
var BASE_NETWORK = "eip155:8453";
function encodeBase64Json(value) {
const bytes = new TextEncoder().encode(JSON.stringify(value));
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
}
function decodeBase64Json(value) {
try {
const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
const binary = atob(padded);
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
return JSON.parse(new TextDecoder().decode(bytes));
} catch (error) {
throw new Error("PAYMENT-SIGNATURE must contain base64-encoded JSON");
}
}
function atomicUnits(priceUsd) {
if (!Number.isFinite(priceUsd) || priceUsd <= 0) {
throw new Error("Payment price must be a positive finite number");
}
return String(Math.round(priceUsd * 1e6));
}
function makePaymentRequirements(priceUsd) {
return {
scheme: "exact",
network: BASE_NETWORK,
amount: atomicUnits(priceUsd),
asset: USDC_CONTRACT_ADDRESS,
payTo: RECEIVER_ADDRESS,
maxTimeoutSeconds: 300,
extra: { name: "USD Coin", version: "2" }
};
}
function sameAddress(left, right) {
return typeof left === "string" && typeof right === "string" && left.toLowerCase() === right.toLowerCase();
}
function validateV2Payload(paymentPayload, requirements) {
if (!paymentPayload || paymentPayload.x402Version !== 2) return "Unsupported x402 version";
if (!paymentPayload.payload || typeof paymentPayload.payload !== "object") return "Missing x402 payment payload";
const accepted = paymentPayload.accepted;
if (!accepted || typeof accepted !== "object") return "Missing accepted payment requirements";
if (accepted.scheme !== requirements.scheme) return "Payment scheme mismatch";
if (accepted.network !== requirements.network) return "Payment network mismatch";
if (String(accepted.amount) !== requirements.amount) return "Payment amount mismatch";
if (!sameAddress(accepted.asset, requirements.asset)) return "Payment asset mismatch";
if (!sameAddress(accepted.payTo, requirements.payTo)) return "Payment recipient mismatch";
const authorization = paymentPayload.payload.authorization;
if (!authorization || typeof authorization !== "object") return "Missing EIP-3009 authorization";
if (!sameAddress(authorization.to, requirements.payTo)) return "Authorization recipient mismatch";
if (String(authorization.value) !== requirements.amount) return "Authorization amount mismatch";
if (!/^0x[a-fA-F0-9]{64}$/.test(authorization.nonce || "")) return "Malformed EIP-3009 nonce";
if (!/^0x[a-fA-F0-9]{130}$/.test(paymentPayload.payload.signature || "")) return "Malformed EIP-712 signature";
return null;
}
function facilitatorConfig(env) {
const rawUrl = env?.X402_FACILITATOR_URL;
if (!rawUrl) return { error: "Base mainnet x402 facilitator is not configured" };
try {
const parsed = new URL(rawUrl);
if (parsed.protocol !== "https:") return { error: "x402 facilitator URL must use HTTPS" };
return { url: parsed.toString().replace(/\/$/, "") };
} catch (error) {
return { error: "x402 facilitator URL is invalid" };
}
}
async function callFacilitator(operation, body, env) {
const config = facilitatorConfig(env);
if (config.error) return { ok: false, error: config.error };
const headers = { "Content-Type": "application/json" };
if (env?.X402_FACILITATOR_AUTHORIZATION) {
headers.Authorization = env.X402_FACILITATOR_AUTHORIZATION;
}
try {
const response = await fetch(`${config.url}/${operation}`, {
method: "POST",
headers,
body: JSON.stringify(body)
});
const result = await response.json().catch(() => null);
if (!response.ok) {
return { ok: false, error: `x402 facilitator ${operation} failed with HTTP ${response.status}` };
}
if (!result || typeof result !== "object") {
return { ok: false, error: `x402 facilitator ${operation} returned invalid JSON` };
}
return { ok: true, result };
} catch (error) {
return { ok: false, error: `x402 facilitator ${operation} request failed` };
}
}
async function isRedeemed(key, env) {
if (!env?.PROCESSED_PROOFS) return false;
try {
return Boolean(await env.PROCESSED_PROOFS.get(key));
} catch (error) {
console.error(JSON.stringify({
message: "processed proof lookup failed",
error: error instanceof Error ? error.message : String(error)
}));
return false;
}
}
async function recordRedemption(key, receipt, env) {
if (!env?.PROCESSED_PROOFS) return;
try {
await env.PROCESSED_PROOFS.put(key, JSON.stringify(receipt), { expirationTtl: 86400 * 30 });
} catch (error) {
console.error(JSON.stringify({
message: "processed proof write failed",
error: error instanceof Error ? error.message : String(error)
}));
}
}
async function verifyV2Payment(signatureHeader, env, requiredPriceUsd) {
let paymentPayload;
try {
paymentPayload = decodeBase64Json(signatureHeader);
} catch (error) {
return { valid: false, rail: null, error: error.message };
}
const requirements = makePaymentRequirements(requiredPriceUsd);
const payloadError = validateV2Payload(paymentPayload, requirements);
if (payloadError) return { valid: false, rail: null, error: payloadError };
const nonceKey = `x402:${paymentPayload.payload.authorization.nonce.toLowerCase()}`;
if (await isRedeemed(nonceKey, env)) {
return { valid: false, rail: null, error: "Payment authorization already redeemed" };
}
const facilitatorBody = { x402Version: 2, paymentPayload, paymentRequirements: requirements };
const verification = await callFacilitator("verify", facilitatorBody, env);
if (!verification.ok) return { valid: false, rail: null, error: verification.error };
if (verification.result.isValid !== true) {
return {
valid: false,
rail: null,
error: `Payment authorization rejected: ${verification.result.invalidReason || "invalid"}`
};
}
return {
valid: true,
rail: "x402",
payer: verification.result.payer || paymentPayload.payload.authorization.from || null,
pending_settlement: { facilitatorBody, nonceKey }
};
}
async function verifyPayment(proofHeader, env, requiredPriceUsd = 0.05) {
if (proofHeader && /^0x[a-fA-F0-9]{64}$/.test(proofHeader)) {
return {
valid: false,
rail: null,
error: "Legacy transaction-hash proofs are not accepted; use an x402 v2 PAYMENT-SIGNATURE"
};
}
if (proofHeader) return verifyV2Payment(proofHeader, env, requiredPriceUsd);
return { valid: false, rail: null, error: "Missing payment authorization" };
}
async function settlePayment(paymentVerdict, env) {
if (!paymentVerdict?.valid) return paymentVerdict;
if (!paymentVerdict.pending_settlement) return paymentVerdict;
const { facilitatorBody, nonceKey } = paymentVerdict.pending_settlement;
if (await isRedeemed(nonceKey, env)) {
return { valid: false, rail: null, error: "Payment authorization already redeemed" };
}
const settlementCall = await callFacilitator("settle", facilitatorBody, env);
if (!settlementCall.ok) return { valid: false, rail: null, error: settlementCall.error };
const settlement = settlementCall.result;
if (settlement.success !== true) {
return { valid: false, rail: null, error: `Payment settlement failed: ${settlement.errorReason || "unknown"}` };
}
if (!/^0x[a-fA-F0-9]{64}$/.test(settlement.transaction || "")) {
return { valid: false, rail: null, error: "Facilitator returned no valid settlement transaction" };
}
if (settlement.network !== BASE_NETWORK) {
return { valid: false, rail: null, error: "Facilitator settled on the wrong network" };
}
const receipt = {
success: true,
transaction: settlement.transaction.toLowerCase(),
network: settlement.network,
payer: settlement.payer || paymentVerdict.payer || null,
amount: facilitatorBody.paymentRequirements.amount
};
await recordRedemption(nonceKey, { ...receipt, redeemed_at: (/* @__PURE__ */ new Date()).toISOString() }, env);
return { valid: true, rail: "x402", tx_hash: receipt.transaction, settlement: receipt };
}
function paymentResponseHeader(paymentVerdict) {
return paymentVerdict?.settlement ? encodeBase64Json(paymentVerdict.settlement) : null;
}
function make402Response(serviceName, priceUsd, errorDetail = null, challengePrefix = "inv", resourceUrl = null) {
const challengeToken = `${challengePrefix}_${crypto.randomUUID()}`;
const requirements = makePaymentRequirements(priceUsd);
const paymentRequired = {
x402Version: 2,
error: errorDetail || "PAYMENT-SIGNATURE header is required",
resource: {
url: resourceUrl || "https://extract.getstringer.app",
description: `${serviceName} paid request`,
mimeType: "application/json",
serviceName
},
accepts: [requirements],
extensions: {}
};
return new Response(JSON.stringify({
...paymentRequired,
error_code: "PAYMENT_REQUIRED",
challenge: challengeToken,
price_usd: priceUsd
}), {
status: 402,
headers: {
"Content-Type": "application/json",
...corsHeaders(),
"PAYMENT-REQUIRED": encodeBase64Json(paymentRequired),
"WWW-Authenticate": `x402 realm="${serviceName}", token="${challengeToken}", amount="${priceUsd.toFixed(4)}", currency="USDC", network="${BASE_NETWORK}", receiver="${RECEIVER_ADDRESS}"`,
"X-402-Payment-Required": "true",
"X-402-Price-USD": priceUsd.toFixed(4),
"X-402-Network": BASE_NETWORK,
"X-402-Receiver-Address": RECEIVER_ADDRESS,
"X-402-Token-Contract": USDC_CONTRACT_ADDRESS
}
});
}
// CleanExtract Worker routes
var PRICE_USD = 0.05;
var MAX_FETCHED_BODY_BYTES = 1048576;
var MAX_OUTPUT_CEILING_BYTES = 1048576;
var CONTENT_RATIO_THRESHOLD = 0.05;
// The hosted service grants three lifetime calls, metered per network address. Keep the
// public reference implementation on the same contract: no signup, claim header, or reset.
var FREE_CALL_LIMIT = 3;
var ORIGIN_PROTECTED_DISCOVERY_PATHS = new Set([
"/robots.txt",
"/sitemap.xml",
"/llms-full.txt"
]);
var ROBOTS_TEXT = `User-agent: *
Allow: /
Sitemap: https://extract.getstringer.app/sitemap.xml
`;
var SITEMAP_XML = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://extract.getstringer.app/</loc></url>
<url><loc>https://extract.getstringer.app/info</loc></url>
<url><loc>https://extract.getstringer.app/llms.txt</loc></url>
</urlset>
`;
var LLMS_TEXT = `# CleanExtract
> Free page outline, selected sections, and charges only for usable content.
- Free allowance: the first 3 calls are free, total; no signup and no claim header, and it does not reset
- Paid price after the allowance: USD 0.05 per usable extraction. A call is charged only when it returns usable content.
- Free outline: clean_extract_outline or POST /v1/outline. Returns status, title, total_bytes, fingerprint, and sections without page text.
- Select sections: pass sections such as ["s2", "s3"] to clean_extract or POST /v1/execute. Success names sections_returned and sections_missing; a byte ceiling reports output_bounds.sections_dropped.
- Named uncharged failures: upstream_timeout (504), upstream_http_error (502), bot_challenge (422), js_shell (422), empty_extraction (422), sections_not_found (422).
- Structured-data recovery: JSON-LD, __NEXT_DATA__, or parseable window.__NUXT__ article text reports fallback_used. CleanExtract does not run JavaScript.
- MCP transport: https://extract.getstringer.app/mcp
- MCP protocol: Streamable HTTP
- Tools: clean_extract and clean_extract_outline
- REST endpoint: https://extract.getstringer.app/v1/execute
- Payment: x402 v2 USDC on Base mainnet (eip155:8453)
An unpaid caller receives up to 3 usable extraction calls free with no signup and no claim header. The outline is free. After the allowance is exhausted, or when the caller cannot be identified, a paid extraction returns an x402 challenge.
`;
var AGENT_CARD = {
name: "Stringer CleanExtract",
description: "Charged only for usable content. Free outline, selected sections, and structured-data recovery. Failures: upstream_timeout, upstream_http_error, bot_challenge, js_shell, empty_extraction, sections_not_found.",
version: "0.4.0",
url: "https://extract.getstringer.app",
mcp_endpoint: "https://extract.getstringer.app/mcp",
tool: "clean_extract",
outline_tool: "clean_extract_outline",
price_usd: PRICE_USD,
free_allowance: { calls: FREE_CALL_LIMIT, scope: "lifetime", resets: false },
payment_rail: "x402 v2 USDC on Base mainnet",
stage: "DEPLOYED"
};
var NO_OAUTH_AUTHORIZATION_SERVER = {
error: "no_oauth_authorization_server",
service: "Stringer CleanExtract",
oauth_authorization_server: false,
payment: "x402 v2 USDC on Base mainnet",
mcp_endpoint: "https://extract.getstringer.app/mcp"
};
var NO_OAUTH_PROTECTED_RESOURCE = {
resource: "https://extract.getstringer.app",
oauth_protected: false,
payment: "x402 v2 USDC on Base mainnet",
mcp_endpoint: "https://extract.getstringer.app/mcp"
};
function discoveryResponse(body, contentType, method) {
return new Response(method === "HEAD" ? null : body, {
headers: {
"Content-Type": contentType,
"Cache-Control": "public, max-age=300"
}
});
}
function discoveryJsonResponse(body, method) {
return new Response(method === "HEAD" ? null : JSON.stringify(body, null, 2), {
headers: {
"Content-Type": "application/json",
...corsHeaders(),
"Cache-Control": "public, max-age=300"
}
});
}
function paymentProof(request) {
return request.headers.get("PAYMENT-SIGNATURE") || request.headers.get("X-402-Payment-Proof");
}
// Pseudonymise the caller address before anything stores it. A bare SHA-256 of an IP is
// not a pseudonym: IPv4 is 2^32 addresses, so the whole keyspace inverts on a laptop, and
// these values persist as Durable Object names. Keying the digest makes the mapping
// irreversible without the key and rotatable when the mapping should be gone. There is no
// unkeyed fallback: a missing key closes the free tier loudly instead of quietly
// downgrading it to a reversible digest.
async function callerFingerprint(value, env) {
const secret = typeof env?.FREE_TIER_HASH_KEY === "string" ? env.FREE_TIER_HASH_KEY.trim() : "";
if (!secret) {
console.error(JSON.stringify({
event_type: "free_tier_error",
operation: "fingerprint",
error: "FREE_TIER_HASH_KEY is not configured; the free tier stays closed until it is"
}));
return null;
}
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value));
return Array.from(new Uint8Array(signature), (byte) => byte.toString(16).padStart(2, "0")).join("");
}
async function claimFreeCall(request, env, transport) {
const callerIp = request.headers.get("CF-Connecting-IP")?.trim();
if (!callerIp || !env?.FREE_TIER_LIMITER) return { allowed: false, exhausted: false };
const callerHash = await callerFingerprint(callerIp.toLowerCase(), env);
if (!callerHash) return { allowed: false, exhausted: false };
try {
const stub = env.FREE_TIER_LIMITER.getByName(callerHash);
const response = await stub.fetch("https://free-tier.internal/claim", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ caller_hash: callerHash, transport })
});
if (!response.ok) return { allowed: false, exhausted: false };
const claim = await response.json();
if (claim.allowed) return { ...claim, callerHash, stub };
return { allowed: false, exhausted: true, remaining: 0, reset_at: claim.reset_at ?? null };
} catch (error) {
console.error(JSON.stringify({
event_type: "free_tier_error",
operation: "claim",
error: error instanceof Error ? error.message : String(error)
}));
return { allowed: false, exhausted: false };
}
}
// The five refusal classifications a 402 carries. Wake 280 split a single challenge counter
// into these so a caller can tell a rejected payment from an absent one. The bundle reason
// (wake 291) is a paid-rail internal and stays out of this reduced tree.
const X402_CHALLENGE_REASONS = Object.freeze([
"settlement_failed_after_verify",
"payment_rejected",
"payment_absent",
"allowance_exhausted_challenge",
"terms_probe_challenge",
]);
function paymentRefusalReason(authorization) {
if (authorization?.freeDenial?.exhausted) return "allowance_exhausted_challenge";
return authorization?.paymentPresented ? "payment_rejected" : "payment_absent";
}
function logPaymentRefusal(reason, transport, paymentVerdict, callerHash) {
console.log(JSON.stringify({
event_type: "payment_refused",
reason,
transport,
error: paymentVerdict?.error ?? null,
caller_hash: callerHash ?? null,
}));
}
async function callerHashForRequest(request, env) {
const callerIp = request.headers.get("CF-Connecting-IP")?.trim();
if (!callerIp) return null;
return callerFingerprint(callerIp.toLowerCase(), env);
}
async function authorizeCall(request, env, transport) {
const proof = paymentProof(request);
const callerHash = await callerHashForRequest(request, env);
if (proof) {
const paymentVerdict = await verifyPayment(proof, env);
return paymentVerdict.valid
? { allowed: true, accessTier: "paid", paymentVerdict, paymentPresented: true, callerHash }
: { allowed: false, paymentVerdict, paymentPresented: true, callerHash };
}
return { allowed: true, accessTier: "free_pending", transport, paymentPresented: false, callerHash };
}
async function activateFreeAllowance(request, env, authorization) {
if (authorization.accessTier !== "free_pending") return authorization;
const freeClaim = await claimFreeCall(request, env, authorization.transport);
if (freeClaim.allowed) return { allowed: true, accessTier: "free", freeClaim };
return {
allowed: false,
freeDenial: freeClaim,
paymentVerdict: await verifyPayment(null, env),
paymentPresented: false,
callerHash: freeClaim.callerHash ?? authorization.callerHash ?? null
};
}
function makeFreeDenied402(authorization, transport) {
const serviceName = transport === "mcp" ? "CleanExtract MCP" : "CleanExtract";
const resourceUrl = transport === "mcp" ? "https://extract.getstringer.app/mcp" : "https://extract.getstringer.app/v1/execute";
if (!authorization.freeDenial?.exhausted) {
return make402Response(serviceName, PRICE_USD, authorization.paymentVerdict.error, "inv_cleanextract", resourceUrl);
}
const response = make402Response(
serviceName,
PRICE_USD,
`Free allowance exhausted: ${FREE_CALL_LIMIT} free calls, total. The allowance is metered per network address and does not reset, so a shared or corporate network may reach this before you have called 3 times. Pay the challenge below to continue.`,
"inv_cleanextract",
resourceUrl
);
response.headers.set("X-Stringer-Free-Remaining", "0");
return response;
}
// A request that names no work at all: `{}` on REST, or empty `arguments` on MCP. An unpaid
// caller sending one is asking what this resource costs, not asking for an extraction, and
// is owed the x402 challenge -- a directory validator probes exactly this way, and answering
// it with a 400 hides the price. A body carrying keys but no url_or_html is a real request
// with a real mistake and still gets the field error.
function isTermsProbe(payload) {
return !payload || typeof payload !== "object" || Object.keys(payload).length === 0;
}
async function fetchPublicHtml(target, env) {
const timeoutMs = Number.isInteger(env?.FETCH_TIMEOUT_MS) && env.FETCH_TIMEOUT_MS > 0 && env.FETCH_TIMEOUT_MS <= FETCH_TIMEOUT_MS
? env.FETCH_TIMEOUT_MS : FETCH_TIMEOUT_MS;
try {
const response = await safeFetch(target, {
headers: { "User-Agent": "CleanExtract/1.0" },
signal: AbortSignal.timeout(timeoutMs)
}, { maxResponseBytes: MAX_FETCHED_BODY_BYTES });
return { ok: response.ok, status: response.status, headers: response.headers, rawHtml: await response.text() };
} catch (error) {
return {
ok: false,
timeout: error?.name === "TimeoutError" || error?.name === "AbortError",
error: error instanceof ResponseSizeLimitError ? error.message : "Upstream fetch failed"
};
}
}
function assessExtractionQuality(rawHtml, extracted, sourceUrl) {
const encoder = new TextEncoder();
const sourceBytes = encoder.encode(rawHtml).length;
const envelope = sourceUrl ? `# ${extracted.title}\n\n*Source: [${sourceUrl}](${sourceUrl})*` : `# ${extracted.title}`;
const content = extracted.markdown.startsWith(envelope) ? extracted.markdown.slice(envelope.length).trim() : extracted.markdown.trim();
const extractedContentBytes = encoder.encode(content).length;
const ratio = sourceBytes ? extractedContentBytes / sourceBytes : 0;
const band = extractedContentBytes === 0 ? "zero" : ratio < CONTENT_RATIO_THRESHOLD ? "below_threshold" : "at_or_above_threshold";
return {
content_ratio_band: band,
source_bytes: sourceBytes,
fetched_bytes: sourceUrl ? sourceBytes : null,
extracted_content_bytes: extractedContentBytes,
extracted_to_source_ratio: Number(ratio.toFixed(3)),
extracted_to_fetched_ratio: sourceUrl ? Number(ratio.toFixed(3)) : null,
below_ratio_threshold: CONTENT_RATIO_THRESHOLD,
reason: band === "zero" ? "content-to-source byte ratio 0.0%: the delivered markdown carries no source-authored bytes"
: `content-to-source byte ratio ${(ratio * 100).toFixed(2)}% is ${band === "below_threshold" ? "below" : "at or above"} the 5% size threshold`
};
}
function outputCeilingError(value) {
if (value === undefined) return null;
return Number.isInteger(value) && value >= 1 && value <= MAX_OUTPUT_CEILING_BYTES
? null : `max_output_bytes must be an integer from 1 to ${MAX_OUTPUT_CEILING_BYTES}`;
}
function sectionsInputError(value) {
if (value === undefined) return null;
return Array.isArray(value) && value.length >= 1 && value.length <= 50
&& value.every((id) => typeof id === "string" && /^s[1-9][0-9]*$/.test(id))
? null : "sections must be an array of 1 to 50 section ids such as s1";
}
function boundMarkdown(markdown, maxOutputBytes, parts = null) {
if (maxOutputBytes === undefined) return { markdown, receipt: null };
const encoded = new TextEncoder().encode(markdown);
let bounded = markdown;
let returnedBytes = encoded.length;
let sectionsDropped = [];
let firstSectionByteCut = false;
if (encoded.length > maxOutputBytes) {
const segments = parts ?? selectSections(markdown, outlineMarkdown(markdown).map((s) => s.id)).parts;
if (segments.length && new TextEncoder().encode(segments[0].body).length <= maxOutputBytes) {
let kept = "";
let count = 0;
for (const segment of segments) {
if (new TextEncoder().encode(kept + segment.body).length > maxOutputBytes) break;
kept += segment.body;
count += 1;
}
bounded = kept;
returnedBytes = new TextEncoder().encode(kept).length;
sectionsDropped = segments.slice(count).map((s) => s.id);
} else {
firstSectionByteCut = true;
sectionsDropped = segments.slice(1).map((s) => s.id);
returnedBytes = maxOutputBytes;
const decoder = new TextDecoder("utf-8", { fatal: true });
while (returnedBytes > 0) {
try { bounded = decoder.decode(encoded.slice(0, returnedBytes)); break; }
catch { returnedBytes -= 1; }
}
if (!returnedBytes) bounded = "";
}
}
return { markdown: bounded, receipt: {
ceiling_requested: true, max_output_bytes: maxOutputBytes,
truncation_occurred: returnedBytes < encoded.length,
original_output_bytes: encoded.length, returned_output_bytes: returnedBytes,
dropped_output_bytes: encoded.length - returnedBytes, sections_dropped: sectionsDropped,
first_section_byte_cut: firstSectionByteCut, re_request_with_max_output_bytes: encoded.length
} };
}
async function extractTarget(target, env, sections) {
let rawHtml = target;
let sourceUrl = null;
let fetchResult = null;
if (target.startsWith("http://") || target.startsWith("https://")) {
const safety = isSafePublicUrl(target);
if (!safety.safe) return { invalid: `SSRF blocked: ${safety.reason}` };
sourceUrl = safety.parsedUrl;
fetchResult = await fetchPublicHtml(sourceUrl, env);
rawHtml = fetchResult.rawHtml ?? "";
}
let extracted = fetchResult && !fetchResult.ok ? null : cleanHtmlToMarkdown(rawHtml, sourceUrl);
let quality = extracted ? assessExtractionQuality(rawHtml, extracted, sourceUrl) : null;
let outcome = classifyOutcome({ fetchResult, rawHtml, extracted, quality });
if (outcome.fallback) {
const fallback = outcome.fallback;
const envelope = sourceUrl ? `# ${extracted.title}\n\n*Source: [${sourceUrl}](${sourceUrl})*` : `# ${extracted.title}`;
const markdown = `${envelope}\n\n${fallback.markdown}`;
const cleanBytes = markdown.length;
extracted = { ...extracted, markdown, clean_bytes: cleanBytes,
tokens_saved: Math.max(0, Math.floor(rawHtml.length / 4) - Math.max(1, Math.floor(cleanBytes / 4))),
compression_ratio: `${Math.max(0, Math.round((1 - cleanBytes / Math.max(1, rawHtml.length)) * 100))}%` };
quality = assessExtractionQuality(rawHtml, extracted, sourceUrl);
outcome = { ...classifyOutcome({ fetchResult, rawHtml, extracted, quality }), fallback_used: fallback.source };
}
const selectedSections = extracted && sections ? selectSections(extracted.markdown, sections) : null;
if (selectedSections && outcome.charged) {
outcome = { ...classifyOutcome({ fetchResult, rawHtml, extracted, quality, selectedSections }), fallback_used: outcome.fallback_used };
}
return { rawHtml, sourceUrl, extracted, quality, outcome, selectedSections };
}
function outcomeHttpStatus(outcome) {
return outcome.status === "upstream_timeout" ? 504 : outcome.status === "upstream_http_error" ? 502 : 422;
}
function failureData(extraction) {
const { outcome, selectedSections } = extraction;
return { status: outcome.status, reason: outcome.reason, charged: false,
...(selectedSections && outcome.status === "sections_not_found"
? { sections_missing: selectedSections.sections_missing, available_sections: selectedSections.available_sections } : {}) };
}
async function outlineResult(target, env) {
const extraction = await extractTarget(target, env);
if (extraction.invalid || !extraction.outcome.charged) return { extraction };
const { extracted, outcome } = extraction;
return { extraction, result: { status: "ok", title: extracted.title,
...(outcome.fallback_used ? { fallback_used: outcome.fallback_used } : {}),
total_bytes: new TextEncoder().encode(extracted.markdown).length,
fingerprint: await markdownFingerprint(extracted.markdown), sections: outlineMarkdown(extracted.markdown) } };
}
function restError(message, status) {
return new Response(
JSON.stringify({ error: status === 400 ? "Bad Request" : "Bad Gateway", message }),
{
status,
headers: { "Content-Type": "application/json", ...corsHeaders() }
}
);
}
async function finalizePaidResponse(response, paymentVerdict, callerHash, env, serviceName, resourceUrl, transport) {
if (!response.ok) return response;
const settlement = await settlePayment(paymentVerdict, env);
if (!settlement.valid) {
const reason = "settlement_failed_after_verify";
logPaymentRefusal(reason, transport, settlement, callerHash);
return make402Response(serviceName, PRICE_USD, settlement.error, "inv_cleanextract", resourceUrl);
}
const settlementHeader = paymentResponseHeader(settlement);
if (settlementHeader) response.headers.set("PAYMENT-RESPONSE", settlementHeader);
return response;
}
async function finalizeFreeResponse(response, freeClaim, transport, resourceUrl, outcome = null) {
const charged = response.ok && (outcome?.charged ?? true);
const receipt = {
receipt_id: freeClaim.receipt_id,
access_tier: "free",
transport,
caller_hash: freeClaim.callerHash,
status: response.status,
outcome: charged ? "success" : "not_charged",
recorded_at: (/* @__PURE__ */ new Date()).toISOString(),
resource_url: resourceUrl
};
try {
await freeClaim.stub.fetch("https://free-tier.internal/finalize", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(receipt)
});
} catch (error) {
console.error(JSON.stringify({
event_type: "free_tier_error",
operation: "finalize",
receipt_id: receipt.receipt_id,
error: error instanceof Error ? error.message : String(error)
}));
}
response.headers.set("X-Stringer-Access-Tier", "free");
response.headers.set("X-Stringer-Receipt-ID", freeClaim.receipt_id);
response.headers.set("X-Stringer-Free-Remaining", String(freeClaim.remaining + (charged ? 0 : 1)));
return response;
}
async function finalizeAuthorizedResponse(response, authorization, env, serviceName, resourceUrl, transport, outcome = null) {
if (authorization.accessTier === "free") {
return finalizeFreeResponse(response, authorization.freeClaim, transport, resourceUrl, outcome);
}
return finalizePaidResponse(response, authorization.paymentVerdict, authorization.callerHash, env, serviceName, resourceUrl, transport);
}
function mcpToolDefinition() {
return {
name: "clean_extract",
description: "Extract a full page or selected sections. A call is charged only when it returns usable content; 3 usable extractions are free, total, then USD 0.05. Use the free clean_extract_outline first. Uncharged failures name upstream_timeout, upstream_http_error, bot_challenge, js_shell, empty_extraction, or sections_not_found. Recovery names fallback_used.",
inputSchema: {
type: "object",
properties: {
url_or_html: {
type: "string",
description: "The public URL or raw HTML string to convert into markdown."
},
sections: { type: "array", minItems: 1, maxItems: 50, items: { type: "string", pattern: "^s[1-9][0-9]*$" } },
max_output_bytes: { type: "integer", minimum: 1, maximum: MAX_OUTPUT_CEILING_BYTES }
},
required: ["url_or_html"]
}
};
}
function mcpOutlineDefinition() {
return { name: "clean_extract_outline",
description: "Free outline with section ids, headings, byte sizes, and a fingerprint, without page text or payment. A later clean_extract call can select sections and is charged only for usable content. Uncharged failures name upstream_timeout, upstream_http_error, bot_challenge, js_shell, empty_extraction, or sections_not_found. Recovery names fallback_used.",
inputSchema: { type: "object", properties: { url_or_html: { type: "string" } }, required: ["url_or_html"] } };
}
async function callMcpTool(id, params, env) {
const target = params?.arguments?.url_or_html;
if (typeof target !== "string" || target.length === 0) {
return { response: mcpError(id, -32602, "url_or_html must be a non-empty string", 400) };
}
const ceilingError = outputCeilingError(params?.arguments?.max_output_bytes);
if (ceilingError) return { response: mcpError(id, -32602, ceilingError, 400) };
const sectionsError = sectionsInputError(params?.arguments?.sections);
if (sectionsError) return { response: mcpError(id, -32602, sectionsError, 400) };
const extraction = await extractTarget(target, env, params?.arguments?.sections);
if (extraction.invalid) return { response: mcpError(id, -32602, extraction.invalid, 400) };
const { extracted, quality, outcome, selectedSections } = extraction;
if (!outcome.charged) {
return { response: mcpError(id, -32000, outcome.reason, outcomeHttpStatus(outcome), failureData(extraction)), outcome };