evidence-mcp-dev 0.2.43 → 0.2.45
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 +756 -363
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -62,6 +62,84 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
62
62
|
// src/http.ts
|
|
63
63
|
import { fetch as undiciFetch } from "undici";
|
|
64
64
|
|
|
65
|
+
// src/race.ts
|
|
66
|
+
var OPEN = /* @__PURE__ */ new Set();
|
|
67
|
+
function openRequest(write, name) {
|
|
68
|
+
const ctrl = new AbortController();
|
|
69
|
+
let closed = false;
|
|
70
|
+
const entry = { abandon: () => {
|
|
71
|
+
if (!closed) {
|
|
72
|
+
closed = true;
|
|
73
|
+
write(`abandoned ${name}: server stopped`);
|
|
74
|
+
}
|
|
75
|
+
} };
|
|
76
|
+
OPEN.add(entry);
|
|
77
|
+
write(`try ${name}`);
|
|
78
|
+
return {
|
|
79
|
+
signal: ctrl.signal,
|
|
80
|
+
abort: (why) => {
|
|
81
|
+
if (closed) return;
|
|
82
|
+
closed = true;
|
|
83
|
+
OPEN.delete(entry);
|
|
84
|
+
write(`aborted ${name}: ${why}`);
|
|
85
|
+
ctrl.abort(new Error(`aborted: ${why}`));
|
|
86
|
+
},
|
|
87
|
+
close: (line) => {
|
|
88
|
+
if (closed) return false;
|
|
89
|
+
closed = true;
|
|
90
|
+
OPEN.delete(entry);
|
|
91
|
+
write(line);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function abandonAll() {
|
|
97
|
+
for (const e of OPEN) e.abandon();
|
|
98
|
+
OPEN.clear();
|
|
99
|
+
}
|
|
100
|
+
async function firstOk(tasks, decisive = () => null) {
|
|
101
|
+
if (!tasks.length) return { won: null, results: [] };
|
|
102
|
+
const results2 = new Array(tasks.length);
|
|
103
|
+
const settled = new Array(tasks.length).fill(false);
|
|
104
|
+
return new Promise((resolve4) => {
|
|
105
|
+
let left = tasks.length, done = false;
|
|
106
|
+
const end = (won, why) => {
|
|
107
|
+
done = true;
|
|
108
|
+
tasks.forEach((t, j) => {
|
|
109
|
+
if (!settled[j]) t.abort(why);
|
|
110
|
+
});
|
|
111
|
+
resolve4({ won, results: results2 });
|
|
112
|
+
};
|
|
113
|
+
tasks.forEach((task, i) => {
|
|
114
|
+
task.go().then((r) => {
|
|
115
|
+
results2[i] = r;
|
|
116
|
+
settled[i] = true;
|
|
117
|
+
if (done) return;
|
|
118
|
+
const gone = r.ok ? null : decisive(r);
|
|
119
|
+
if (r.ok) end(r, `${task.name} won`);
|
|
120
|
+
else if (gone) end(null, `${task.name}: ${gone}`);
|
|
121
|
+
else if (--left === 0) {
|
|
122
|
+
done = true;
|
|
123
|
+
resolve4({ won: null, results: results2 });
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
function timeoutOr(ms, signal) {
|
|
130
|
+
if (!signal) return AbortSignal.timeout(ms);
|
|
131
|
+
const c = new AbortController();
|
|
132
|
+
const t = setTimeout(() => c.abort(new DOMException("The operation was aborted due to timeout", "TimeoutError")), ms);
|
|
133
|
+
if (signal.aborted) {
|
|
134
|
+
clearTimeout(t);
|
|
135
|
+
c.abort(signal.reason);
|
|
136
|
+
} else signal.addEventListener("abort", () => {
|
|
137
|
+
clearTimeout(t);
|
|
138
|
+
c.abort(signal.reason);
|
|
139
|
+
}, { once: true });
|
|
140
|
+
return c.signal;
|
|
141
|
+
}
|
|
142
|
+
|
|
65
143
|
// src/contact.ts
|
|
66
144
|
var DEFAULT = "hello@forever-healthy.org";
|
|
67
145
|
var contactEmail = (env = process.env) => str("FH_CONTACT_EMAIL", env) || DEFAULT;
|
|
@@ -266,10 +344,16 @@ async function closeBrowsers() {
|
|
|
266
344
|
}
|
|
267
345
|
}
|
|
268
346
|
}
|
|
269
|
-
async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
347
|
+
async function browserFetch(url, endpoint, cfg = browserConfig(), signal) {
|
|
348
|
+
url = toHttps(url);
|
|
270
349
|
const ctx = await context(endpoint, cfg);
|
|
271
350
|
touchIdle();
|
|
272
351
|
const page = await ctx.newPage();
|
|
352
|
+
const onAbort = () => {
|
|
353
|
+
page.close().catch(() => void 0);
|
|
354
|
+
};
|
|
355
|
+
if (signal?.aborted) onAbort();
|
|
356
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
273
357
|
try {
|
|
274
358
|
let pdfBest = null;
|
|
275
359
|
const pdfReads = [];
|
|
@@ -314,6 +398,8 @@ async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
|
314
398
|
}
|
|
315
399
|
if (!download2) await pause(DOWNLOAD_WAIT_MS / 5);
|
|
316
400
|
}
|
|
401
|
+
const landed = download2 ? download2.url() : page.url();
|
|
402
|
+
if (/^http:\/\//i.test(landed)) throw new Error(`${PLAIN_HTTP} (${new URL(landed).hostname})`);
|
|
317
403
|
if (download2) {
|
|
318
404
|
const d = download2;
|
|
319
405
|
const stream = await d.createReadStream();
|
|
@@ -350,6 +436,7 @@ async function browserFetch(url, endpoint, cfg = browserConfig()) {
|
|
|
350
436
|
const html = await page.content();
|
|
351
437
|
return { bytes: Buffer.from(html, "utf8"), contentType: contentType || "text/html", url: page.url(), via: "page" };
|
|
352
438
|
} finally {
|
|
439
|
+
signal?.removeEventListener("abort", onAbort);
|
|
353
440
|
await page.close().catch(() => void 0);
|
|
354
441
|
if (isRemote(endpoint)) await ctx.storageState({ path: stateFile(endpoint) }).catch(() => void 0);
|
|
355
442
|
}
|
|
@@ -386,12 +473,17 @@ function httpReason(status, body) {
|
|
|
386
473
|
return m ? `HTTP ${status} ${m[1] ?? m[2]}` : `HTTP ${status}`;
|
|
387
474
|
}
|
|
388
475
|
var DOWNLOAD_HEADERS = { "User-Agent": CHROME_UA, "Accept": "application/pdf,text/html,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.9" };
|
|
389
|
-
|
|
476
|
+
var toHttps = (url) => url.replace(/^http:\/\//i, "https://");
|
|
477
|
+
var PLAIN_HTTP = "redirected to plain http";
|
|
478
|
+
var isPlain = (url) => /^http:\/\//i.test(url);
|
|
479
|
+
async function fetchBytes(url, headers = DOWNLOAD_HEADERS, proxy, signal) {
|
|
480
|
+
url = toHttps(url);
|
|
390
481
|
let last = "unknown error", finalUrl = "", lastBody = "", lastType = "";
|
|
391
482
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
392
483
|
try {
|
|
393
|
-
const init = { headers, signal:
|
|
484
|
+
const init = { headers, signal: timeoutOr(TIMEOUT_MS, signal), redirect: "follow" };
|
|
394
485
|
const res = proxy ? await undiciFetch(url, { ...init, dispatcher: proxyAgent(proxy) }) : await fetch(url, init);
|
|
486
|
+
if (res.url && isPlain(res.url)) throw Object.assign(new Error(`${PLAIN_HTTP} (${new URL(res.url).hostname})`), { final: true });
|
|
395
487
|
if (res.ok) return { bytes: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "", url: res.url };
|
|
396
488
|
lastBody = (await res.text().catch(() => "")).slice(0, 4e3);
|
|
397
489
|
lastType = res.headers.get("content-type") ?? "";
|
|
@@ -399,9 +491,11 @@ async function fetchBytes(url, headers = DOWNLOAD_HEADERS, proxy) {
|
|
|
399
491
|
finalUrl = res.url;
|
|
400
492
|
if (res.status !== 429 && res.status < 500) break;
|
|
401
493
|
} catch (e) {
|
|
494
|
+
if (e.final) throw e;
|
|
402
495
|
const code = e?.cause;
|
|
403
496
|
last = e instanceof Error && e.name === "TimeoutError" ? "timeout" : e instanceof Error ? e.message + (code?.code ? ` (${code.code})` : code?.message ? ` (${code.message})` : "") : String(e);
|
|
404
497
|
}
|
|
498
|
+
if (signal?.aborted) break;
|
|
405
499
|
await new Promise((r) => setTimeout(r, 1500));
|
|
406
500
|
}
|
|
407
501
|
throw Object.assign(new Error(last), finalUrl ? { url: finalUrl } : {}, lastBody ? { body: lastBody, contentType: lastType } : {});
|
|
@@ -492,6 +586,36 @@ function checkFulltext(md, title, titleSource, doi, trusted = false, pdf = false
|
|
|
492
586
|
return { ok: true };
|
|
493
587
|
}
|
|
494
588
|
|
|
589
|
+
// src/hosts.ts
|
|
590
|
+
import { connect } from "net";
|
|
591
|
+
var UP_MS = 6e4;
|
|
592
|
+
var DOWN_MS = 5 * 6e4;
|
|
593
|
+
var PROBE_MS = 3e3;
|
|
594
|
+
var seen = /* @__PURE__ */ new Map();
|
|
595
|
+
var key = (host3, port) => `${host3}:${port}`;
|
|
596
|
+
function probe(host3, port, timeoutMs = PROBE_MS) {
|
|
597
|
+
const t0 = Date.now();
|
|
598
|
+
return new Promise((resolve4) => {
|
|
599
|
+
const s = connect({ host: host3, port });
|
|
600
|
+
const done = (error) => {
|
|
601
|
+
s.destroy();
|
|
602
|
+
resolve4({ up: !error, ms: Date.now() - t0, at: Date.now(), error });
|
|
603
|
+
};
|
|
604
|
+
s.setTimeout(timeoutMs, () => done(`no answer within ${timeoutMs / 1e3} s`));
|
|
605
|
+
s.once("connect", () => done(null));
|
|
606
|
+
s.once("error", (e) => done(e.code ?? e.message));
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
async function hostState(host3, port, onDown) {
|
|
610
|
+
const k = key(host3, port), now2 = Date.now(), old = seen.get(k);
|
|
611
|
+
if (old && now2 - old.at < (old.up ? UP_MS : DOWN_MS)) return old;
|
|
612
|
+
const s = await probe(host3, port);
|
|
613
|
+
seen.set(k, s);
|
|
614
|
+
if (!s.up && (!old || old.up)) onDown?.(s);
|
|
615
|
+
return s;
|
|
616
|
+
}
|
|
617
|
+
var downNote = (s) => `host down (${s.error}, since ${new Date(s.at).toTimeString().slice(0, 5)})`;
|
|
618
|
+
|
|
495
619
|
// src/html.ts
|
|
496
620
|
import TurndownService from "turndown";
|
|
497
621
|
import { gfm } from "@joplin/turndown-plugin-gfm";
|
|
@@ -739,7 +863,7 @@ function renderCitation(nodes2) {
|
|
|
739
863
|
const el = nodes2.find((x) => ["element-citation", "mixed-citation", "citation", "nlm-citation"].includes(tagOf(x)));
|
|
740
864
|
if (!el) return squash(inlineText(nodes2));
|
|
741
865
|
const f = kids(el);
|
|
742
|
-
const
|
|
866
|
+
const get4 = (tag) => f.filter((x) => tagOf(x) === tag).map((x) => squash(inlineText(kids(x))));
|
|
743
867
|
const names2 = f.filter((x) => tagOf(x) === "person-group").flatMap((g) => kids(g)).map((x) => {
|
|
744
868
|
const t = tagOf(x);
|
|
745
869
|
if (t === "etal") return "et al";
|
|
@@ -751,11 +875,11 @@ function renderCitation(nodes2) {
|
|
|
751
875
|
}
|
|
752
876
|
return "";
|
|
753
877
|
}).filter(Boolean);
|
|
754
|
-
const vol =
|
|
755
|
-
const pages = fp ? lp ? `${fp}-${lp}` : fp :
|
|
756
|
-
const where = [
|
|
878
|
+
const vol = get4("volume")[0], issue = get4("issue")[0], fp = get4("fpage")[0], lp = get4("lpage")[0];
|
|
879
|
+
const pages = fp ? lp ? `${fp}-${lp}` : fp : get4("elocation-id")[0];
|
|
880
|
+
const where = [get4("source")[0], get4("year")[0] ? `${get4("year")[0]};` : "", vol ? `${vol}${issue ? `(${issue})` : ""}` : "", pages ? `:${pages}` : ""].filter(Boolean).join("").replace(/;$/, "");
|
|
757
881
|
const ids = f.filter((x) => tagOf(x) === "pub-id").map((x) => `${attr(x, "pub-id-type")}:${squash(plainText(kids(x)))}`);
|
|
758
|
-
return [names2.join(", "), [...
|
|
882
|
+
return [names2.join(", "), [...get4("article-title"), ...get4("chapter-title")][0], where, ...ids].filter(Boolean).join(". ").replace(/\.\./g, ".");
|
|
759
883
|
}
|
|
760
884
|
var FN_LABELS = {
|
|
761
885
|
"conflict": "Conflicts of interest",
|
|
@@ -1197,13 +1321,13 @@ var COMPOUND_PREFIX = /* @__PURE__ */ new Set([
|
|
|
1197
1321
|
function dehyphenate(text4) {
|
|
1198
1322
|
if (!text4.includes(BREAK)) return text4;
|
|
1199
1323
|
const lower = text4.toLowerCase();
|
|
1200
|
-
const
|
|
1324
|
+
const seen2 = (s) => new RegExp(`(?<![a-z])${s}(?![a-z])`).test(lower);
|
|
1201
1325
|
return text4.replace(/([A-Za-z]+)\u0000\n([A-Za-z]+)/g, (m, x, y) => {
|
|
1202
1326
|
if (!/^[a-z]/.test(y)) return `${x}-${y}`;
|
|
1203
1327
|
if (SUSPENDED.has(y.toLowerCase())) return `${x}- ${y}`;
|
|
1204
1328
|
const hyph = `${x}-${y}`.toLowerCase(), joined3 = `${x}${y}`.toLowerCase();
|
|
1205
|
-
if (
|
|
1206
|
-
if (
|
|
1329
|
+
if (seen2(hyph)) return `${x}-${y}`;
|
|
1330
|
+
if (seen2(joined3)) return `${x}${y}`;
|
|
1207
1331
|
return COMPOUND_PREFIX.has(x.toLowerCase()) ? `${x}-${y}` : `${x}${y}`;
|
|
1208
1332
|
}).replace(/\u0000\n/g, "-\n").replace(/\u0000/g, "-");
|
|
1209
1333
|
}
|
|
@@ -1214,12 +1338,12 @@ var UNRESOLVED_GLYPH = /[\u0001-\u0008\u000b\u000c\u000e-\u001f]/g;
|
|
|
1214
1338
|
var countUnresolved = (text4) => (text4.match(UNRESOLVED_GLYPH) ?? []).length;
|
|
1215
1339
|
var looksLikePdf = (bytes) => bytes.subarray(0, 5).toString("latin1") === "%PDF-";
|
|
1216
1340
|
|
|
1217
|
-
// src/unlock.ts
|
|
1341
|
+
// src/unlock/brightdata.ts
|
|
1218
1342
|
import { request as httpsRequest } from "https";
|
|
1219
1343
|
var ENDPOINT = "https://api.brightdata.com/request";
|
|
1220
1344
|
var TIMEOUT_MS2 = 6e4;
|
|
1221
1345
|
function post(url, init) {
|
|
1222
|
-
return new Promise((
|
|
1346
|
+
return new Promise((resolve4, reject) => {
|
|
1223
1347
|
const req = httpsRequest(url, { method: "POST", headers: { ...init.headers, "Content-Length": String(Buffer.byteLength(init.body)) }, signal: init.signal }, (res) => {
|
|
1224
1348
|
const chunks = [];
|
|
1225
1349
|
res.on("data", (c) => chunks.push(c));
|
|
@@ -1227,7 +1351,7 @@ function post(url, init) {
|
|
|
1227
1351
|
res.on("end", () => {
|
|
1228
1352
|
const body = Buffer.concat(chunks);
|
|
1229
1353
|
const status = res.statusCode ?? 0;
|
|
1230
|
-
|
|
1354
|
+
resolve4({
|
|
1231
1355
|
ok: status >= 200 && status < 300,
|
|
1232
1356
|
status,
|
|
1233
1357
|
headers: { get: (name) => {
|
|
@@ -1242,23 +1366,93 @@ function post(url, init) {
|
|
|
1242
1366
|
req.end(init.body);
|
|
1243
1367
|
});
|
|
1244
1368
|
}
|
|
1245
|
-
var
|
|
1246
|
-
async function
|
|
1247
|
-
const token =
|
|
1248
|
-
if (!token) throw new Error("
|
|
1369
|
+
var apiKey = () => process.env.FH_BRIGHTDATA_API_KEY?.trim() || "";
|
|
1370
|
+
async function get(url, postImpl = post, signal) {
|
|
1371
|
+
const token = apiKey();
|
|
1372
|
+
if (!token) throw new Error("not configured");
|
|
1249
1373
|
const zone = process.env.FH_BRIGHTDATA_ZONE?.trim() || "mcp_unlocker";
|
|
1250
1374
|
const res = await postImpl(ENDPOINT, {
|
|
1251
1375
|
method: "POST",
|
|
1252
1376
|
headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
|
|
1253
1377
|
body: JSON.stringify({ zone, url, format: "raw" }),
|
|
1254
|
-
signal:
|
|
1378
|
+
signal: timeoutOr(TIMEOUT_MS2, signal)
|
|
1255
1379
|
});
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
}
|
|
1380
|
+
const why = res.headers.get("x-brd-err-msg") ?? res.headers.get("x-brd-error");
|
|
1381
|
+
if (!res.ok) throw new Error(`unlocker HTTP ${res.status}${why ? `: ${why}` : ""}`);
|
|
1382
|
+
if (res.headers.get("x-brd-error")) throw new Error(`unlocker refused: ${why}`);
|
|
1260
1383
|
return { bytes: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "" };
|
|
1261
1384
|
}
|
|
1385
|
+
var brightdata = { name: "brightdata", keyVar: "FH_BRIGHTDATA_API_KEY", get: (url, signal) => get(url, post, signal) };
|
|
1386
|
+
|
|
1387
|
+
// src/unlock/zenrows.ts
|
|
1388
|
+
var TIMEOUT_MS3 = 6e4;
|
|
1389
|
+
var ACCOUNT = /* @__PURE__ */ new Set([401, 402, 403, 429]);
|
|
1390
|
+
async function get2(url, fetchImpl = fetch, signal) {
|
|
1391
|
+
const key2 = process.env.FH_ZENROWS_API_KEY?.trim();
|
|
1392
|
+
if (!key2) throw new Error("not configured");
|
|
1393
|
+
const r = await fetchImpl(`https://api.zenrows.com/v1/?apikey=${encodeURIComponent(key2)}&url=${encodeURIComponent(url)}&mode=auto`, { signal: timeoutOr(TIMEOUT_MS3, signal) });
|
|
1394
|
+
const bytes = Buffer.from(await r.arrayBuffer());
|
|
1395
|
+
if (!r.ok) {
|
|
1396
|
+
let why = "";
|
|
1397
|
+
try {
|
|
1398
|
+
const j = JSON.parse(bytes.toString("utf8"));
|
|
1399
|
+
why = j.title || j.detail || j.code || "";
|
|
1400
|
+
} catch {
|
|
1401
|
+
why = bytes.toString("utf8").slice(0, 120).trim();
|
|
1402
|
+
}
|
|
1403
|
+
throw new Error(ACCOUNT.has(r.status) ? `unlocker HTTP ${r.status}${why ? `: ${why}` : ""}` : `HTTP ${r.status}${why ? ` ${why}` : ""}`);
|
|
1404
|
+
}
|
|
1405
|
+
return { bytes, contentType: r.headers.get("content-type") ?? "" };
|
|
1406
|
+
}
|
|
1407
|
+
var zenrows = { name: "zenrows", keyVar: "FH_ZENROWS_API_KEY", get: (url, signal) => get2(url, fetch, signal) };
|
|
1408
|
+
|
|
1409
|
+
// src/unlock/zyte.ts
|
|
1410
|
+
var TIMEOUT_MS4 = 6e4;
|
|
1411
|
+
var ACCOUNT2 = /* @__PURE__ */ new Set([401, 402, 403, 429]);
|
|
1412
|
+
async function get3(url, fetchImpl = fetch, signal) {
|
|
1413
|
+
const key2 = process.env.FH_ZYTE_API_KEY?.trim();
|
|
1414
|
+
if (!key2) throw new Error("not configured");
|
|
1415
|
+
const r = await fetchImpl("https://api.zyte.com/v1/extract", {
|
|
1416
|
+
method: "POST",
|
|
1417
|
+
signal: timeoutOr(TIMEOUT_MS4, signal),
|
|
1418
|
+
headers: { authorization: `Basic ${Buffer.from(`${key2}:`).toString("base64")}`, "content-type": "application/json" },
|
|
1419
|
+
body: JSON.stringify({ url, httpResponseBody: true, httpResponseHeaders: true })
|
|
1420
|
+
});
|
|
1421
|
+
const j = await r.json().catch(() => ({}));
|
|
1422
|
+
if (!r.ok) {
|
|
1423
|
+
const why = j.title || j.detail || "";
|
|
1424
|
+
throw new Error(ACCOUNT2.has(r.status) ? `unlocker HTTP ${r.status}${why ? `: ${why}` : ""}` : `HTTP ${r.status}${why ? ` ${why}` : ""}`);
|
|
1425
|
+
}
|
|
1426
|
+
if (j.statusCode && j.statusCode >= 400) throw new Error(`HTTP ${j.statusCode}`);
|
|
1427
|
+
const contentType = j.httpResponseHeaders?.find((h) => h.name.toLowerCase() === "content-type")?.value ?? "";
|
|
1428
|
+
return { bytes: Buffer.from(j.httpResponseBody ?? "", "base64"), contentType };
|
|
1429
|
+
}
|
|
1430
|
+
var zyte = { name: "zyte", keyVar: "FH_ZYTE_API_KEY", get: (url, signal) => get3(url, fetch, signal) };
|
|
1431
|
+
|
|
1432
|
+
// src/unlock.ts
|
|
1433
|
+
var SERVICES = [zenrows, zyte, brightdata];
|
|
1434
|
+
var UNLOCKER_NAMES = SERVICES.map((s) => s.name);
|
|
1435
|
+
var UNLOCKER_PREFIX = new RegExp(`^(${UNLOCKER_NAMES.join("|")}): `);
|
|
1436
|
+
var accountProblem = (reason) => /^unlocker (HTTP 4\d\d|refused)/.test(reason);
|
|
1437
|
+
var keyed = (s, env) => !!env[s.keyVar]?.trim();
|
|
1438
|
+
var unlockers = (env = process.env) => SERVICES.filter((s) => keyed(s, env)).map((s) => s.name);
|
|
1439
|
+
var unlockerConfigured = () => unlockers().length > 0;
|
|
1440
|
+
async function unlock(url, name, signal) {
|
|
1441
|
+
const s = SERVICES.find((x) => x.name === name);
|
|
1442
|
+
if (!s) throw new Error(`unknown unlocker ${name}`);
|
|
1443
|
+
return s.get(url, signal);
|
|
1444
|
+
}
|
|
1445
|
+
var HEALTH_URL = "https://example.com/";
|
|
1446
|
+
async function unlockerHealth(name, unlockImpl = unlock) {
|
|
1447
|
+
const t0 = Date.now();
|
|
1448
|
+
try {
|
|
1449
|
+
const u = await unlockImpl(HEALTH_URL, name);
|
|
1450
|
+
const ok = /Example Domain/.test(u.bytes.toString("utf8"));
|
|
1451
|
+
return { ok, ms: Date.now() - t0, error: ok ? null : u.bytes.length ? `unexpected answer (${u.bytes.length} bytes)` : "empty answer" };
|
|
1452
|
+
} catch (e) {
|
|
1453
|
+
return { ok: false, ms: Date.now() - t0, error: e instanceof Error ? e.message : String(e) };
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1262
1456
|
|
|
1263
1457
|
// src/walls.ts
|
|
1264
1458
|
import { mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "fs";
|
|
@@ -2397,7 +2591,7 @@ function walled(url, stage2, dir = FH_EVIDENCE_DIR) {
|
|
|
2397
2591
|
function recordStage(url, stage2, ok, reason = "", dir = FH_EVIDENCE_DIR) {
|
|
2398
2592
|
const h = host(url);
|
|
2399
2593
|
if (!h) return;
|
|
2400
|
-
const why = reason.replace(/^((?:playwright|chrome|browser|fetch-proxy) [^:]+|brightdata): /, "");
|
|
2594
|
+
const why = reason.replace(/^((?:playwright|chrome|browser|fetch-proxy) [^:]+|brightdata|zenrows|zyte): /, "");
|
|
2401
2595
|
if (!ok && !WALL2.test(why)) return;
|
|
2402
2596
|
const all = read(dir, h);
|
|
2403
2597
|
const lk = legacy(stage2);
|
|
@@ -2443,7 +2637,11 @@ function order(candidates) {
|
|
|
2443
2637
|
async function download(tier, p, candidates, ctx) {
|
|
2444
2638
|
const usable = candidates.filter((c) => !NCBI.test(c.url));
|
|
2445
2639
|
if (!usable.length && candidates.length) return miss(tier, "only pmc copies (covered by the pmc tier)");
|
|
2446
|
-
const ordered = order(usable
|
|
2640
|
+
const ordered = order(usable.map((c) => {
|
|
2641
|
+
const u = toHttps(c.url);
|
|
2642
|
+
if (u !== c.url) ctx.onTry?.(`http upgraded: ${c.url} \u2192 ${u}`);
|
|
2643
|
+
return u === c.url ? c : { ...c, url: u };
|
|
2644
|
+
})).filter((c) => !ctx.tried.has(c.url));
|
|
2447
2645
|
if (!ordered.length) return miss(tier, "only copies already tried");
|
|
2448
2646
|
const reasons = [];
|
|
2449
2647
|
for (let i = 0; i < ordered.length; i++) {
|
|
@@ -2456,53 +2654,61 @@ async function download(tier, p, candidates, ctx) {
|
|
|
2456
2654
|
if (!x.ok && !gone && /\bHTTP (404|410)\b/.test(x.reason)) gone = x.reason;
|
|
2457
2655
|
return x;
|
|
2458
2656
|
};
|
|
2459
|
-
let r = note(await tryOne(p, c, tier));
|
|
2460
|
-
const target = !r.ok && r.url && r.url !== c.url ? { ...c, url: r.url } : c;
|
|
2461
|
-
if (target !== c) ctx.onTry?.(`${c.url} \u2192 ${target.url}`);
|
|
2462
|
-
ctx.onTry?.(r.ok ? `${target.url} ok fetch` : `${target.url} failed fetch: ${r.reason}`);
|
|
2463
2657
|
const why = (reason) => reason.replace(/^not a pdf \((.*)\)$/, "$1");
|
|
2464
|
-
const
|
|
2658
|
+
const run = (cand, via, name) => {
|
|
2659
|
+
let req = null;
|
|
2660
|
+
return { name, abort: (why2) => req?.abort(why2), go: async () => {
|
|
2661
|
+
req = openRequest((line) => ctx.onTry?.(`${line} ${cand.url}`), name);
|
|
2662
|
+
const x0 = await tryOne(p, cand, tier, via, req.signal);
|
|
2663
|
+
if (req.signal.aborted) return { ok: false, reason: "aborted" };
|
|
2664
|
+
const x = note(x0);
|
|
2665
|
+
if (via !== "plain") recordStage(cand.url, name, x.ok, x.ok ? "" : x.reason);
|
|
2666
|
+
req.close(x.ok ? `ok ${name}` : `failed ${name}: ${via === "plain" ? x.reason : bare(x.reason)}`);
|
|
2667
|
+
if (!x.ok && (bare(x.reason).startsWith(MISMATCH) || accountProblem(bare(x.reason)))) ctx.onAlert?.(`${name}: ${bare(x.reason)}`);
|
|
2668
|
+
return x;
|
|
2669
|
+
} };
|
|
2670
|
+
};
|
|
2671
|
+
const skipped = (url, name) => {
|
|
2672
|
+
const w = walled(url, name);
|
|
2673
|
+
if (w) ctx.onTry?.(`skipped ${name}: ${wallNote(w)} ${url}`);
|
|
2674
|
+
return !!w;
|
|
2675
|
+
};
|
|
2676
|
+
const hostDown = async (host3, port, name, url) => {
|
|
2677
|
+
const h = await hostState(host3, port, (s) => ctx.onAlert?.(`${name}: ${downNote(s)}`));
|
|
2678
|
+
if (!h.up) ctx.onTry?.(`skipped ${name}: ${downNote(h)} ${url}`);
|
|
2679
|
+
return !h.up;
|
|
2680
|
+
};
|
|
2465
2681
|
const f = fetchProxy();
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2682
|
+
const first = [run(c, "plain", "fetch")];
|
|
2683
|
+
if (f && !c.service && !skipped(c.url, fetchProxyName(f)) && !await hostDown(f.host, f.port, fetchProxyName(f), c.url)) first.push(run(c, { proxy: f.proxy, label: f.label }, fetchProxyName(f)));
|
|
2684
|
+
const isGone = (x) => x.ok ? null : x.reason.match(/\bHTTP (404|410)\b/)?.[0] ?? null;
|
|
2685
|
+
const one = await firstOk(first, isGone);
|
|
2686
|
+
if (one.won) return one.won;
|
|
2687
|
+
const plain3 = one.results[0] ?? one.results.find(Boolean);
|
|
2688
|
+
const target = !plain3.ok && plain3.url && plain3.url !== c.url ? { ...c, url: plain3.url } : c;
|
|
2689
|
+
if (target !== c) ctx.onTry?.(`redirect ${c.url} \u2192 ${target.url}`);
|
|
2690
|
+
const plainReason = why(reasonOf(plain3));
|
|
2691
|
+
let r = one.results[1] ?? plain3;
|
|
2476
2692
|
const UNLOCK = /^(HTTP 403|wall page)/;
|
|
2477
2693
|
let browsed = false;
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
const
|
|
2481
|
-
|
|
2482
|
-
browsed =
|
|
2483
|
-
const
|
|
2484
|
-
|
|
2485
|
-
if (
|
|
2486
|
-
ctx.onTry?.(`${target.url} skipped ${name}: ${wallNote(w)}`);
|
|
2487
|
-
continue;
|
|
2488
|
-
}
|
|
2489
|
-
r = note(await tryOne(p, target, tier, { browser: b.endpoint, label: b.label }));
|
|
2490
|
-
recordStage(target.url, name, r.ok, r.ok ? "" : r.reason);
|
|
2491
|
-
ctx.onTry?.(r.ok ? `${target.url} ok ${name}` : `${target.url} failed ${name}: ${bare(r.reason)}`);
|
|
2492
|
-
if (!r.ok && bare(r.reason).startsWith(MISMATCH)) ctx.onAlert?.(`${name}: ${bare(r.reason)}`);
|
|
2493
|
-
}
|
|
2494
|
-
const uw = walled(target.url, "brightdata");
|
|
2495
|
-
if (uw && !r.ok && !c.headers && !c.service && unlockerConfigured()) ctx.onTry?.(`${target.url} skipped brightdata: ${wallNote(uw)}`);
|
|
2496
|
-
else if (!r.ok && !c.headers && !c.service && unlockerConfigured() && (browsed ? /^(HTTP 403|wall page|playwright |chrome |browser )/.test(why(r.reason)) : UNLOCK.test(plainReason) || UNLOCK.test(why(bare(r.reason))))) {
|
|
2497
|
-
r = note(await tryOne(p, target, tier, "unlocker"));
|
|
2498
|
-
recordStage(target.url, "brightdata", r.ok, r.ok ? "" : r.reason);
|
|
2499
|
-
ctx.onTry?.(r.ok ? `${target.url} ok brightdata` : `${target.url} failed brightdata: ${bare(r.reason)}`);
|
|
2500
|
-
if (!r.ok && /^unlocker HTTP 4\d\d/.test(bare(r.reason))) ctx.onAlert?.(`brightdata: ${bare(r.reason)}`);
|
|
2694
|
+
if (!gone && !c.headers && !c.service && (climbsOn(plainReason) || climbsOn(bare(reasonOf(r))))) {
|
|
2695
|
+
const open = browserStages().filter((b) => !skipped(target.url, stageName(b)));
|
|
2696
|
+
const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b), target.url)));
|
|
2697
|
+
const tasks = open.filter((_, i2) => !down[i2]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
|
|
2698
|
+
browsed = tasks.length > 0;
|
|
2699
|
+
const two = await firstOk(tasks, isGone);
|
|
2700
|
+
if (two.won) return two.won;
|
|
2701
|
+
if (two.results.length) r = two.results.filter(Boolean).pop();
|
|
2501
2702
|
}
|
|
2703
|
+
const unlockable = !gone && !r.ok && !c.headers && !c.service && (browsed ? /^(HTTP 403|wall page|playwright |chrome |browser )/.test(why(reasonOf(r))) : UNLOCK.test(plainReason) || UNLOCK.test(why(bare(reasonOf(r)))));
|
|
2704
|
+
const us = (unlockable ? unlockers() : []).filter((u) => !skipped(target.url, u));
|
|
2705
|
+
const three = await firstOk(us.map((u) => run(target, { unlocker: u }, u)), isGone);
|
|
2706
|
+
if (three.won) return three.won;
|
|
2707
|
+
if (three.results.length) r = three.results.filter(Boolean).pop();
|
|
2502
2708
|
if (r.ok) return r;
|
|
2503
2709
|
reasons.push(`${gone ?? r.reason}: ${hostOf2(c.url)}`);
|
|
2504
2710
|
if (link && !ctx.tried.has(link) && !NCBI.test(link) && !ordered.slice(i + 1).some((o) => o.url === link)) {
|
|
2505
|
-
ctx.onTry?.(
|
|
2711
|
+
ctx.onTry?.(`pdf link \u2192 ${link}`);
|
|
2506
2712
|
ordered.splice(i + 1, 0, { url: link, version: c.version, source: c.source, host: c.host, pdf: true });
|
|
2507
2713
|
}
|
|
2508
2714
|
}
|
|
@@ -2513,12 +2719,13 @@ function climbsOn(reason, afterBrowser = false) {
|
|
|
2513
2719
|
const r = reason.replace(/^not a pdf \((.*)\)$/, "$1");
|
|
2514
2720
|
return CLIMB.test(r) || afterBrowser && /^(playwright|chrome|browser) /.test(r);
|
|
2515
2721
|
}
|
|
2516
|
-
var viaPrefix = (via) => via === "plain" ? "" :
|
|
2517
|
-
var bare = (reason) => reason.replace(
|
|
2518
|
-
|
|
2722
|
+
var viaPrefix = (via) => via === "plain" ? "" : "unlocker" in via ? `${via.unlocker}: ` : "proxy" in via ? `${fetchProxyName(via)}: ` : `${stageName({ kind: stageKind(via.browser), label: via.label })}: `;
|
|
2723
|
+
var bare = (reason) => reason.replace(UNLOCKER_PREFIX, "").replace(STAGE_PREFIX, "");
|
|
2724
|
+
var reasonOf = (x) => x.ok ? "" : x.reason;
|
|
2725
|
+
async function tryOne(p, c, tier, via = "plain", signal) {
|
|
2519
2726
|
let got;
|
|
2520
2727
|
try {
|
|
2521
|
-
got = via === "unlocker" ? await unlock(c.url) : typeof via === "object" ? "proxy" in via ? await fetchBytes(c.url, { ...DOWNLOAD_HEADERS, ...c.headers ?? {} }, via.proxy) : await browserFetch(c.url, via.browser) : await fetchBytes(c.url, { ...DOWNLOAD_HEADERS, ...c.headers ?? {} });
|
|
2728
|
+
got = typeof via === "object" && "unlocker" in via ? await unlock(c.url, via.unlocker, signal) : typeof via === "object" ? "proxy" in via ? await fetchBytes(c.url, { ...DOWNLOAD_HEADERS, ...c.headers ?? {} }, via.proxy, signal) : await browserFetch(c.url, via.browser, void 0, signal) : await fetchBytes(c.url, { ...DOWNLOAD_HEADERS, ...c.headers ?? {} }, void 0, signal);
|
|
2522
2729
|
} catch (e) {
|
|
2523
2730
|
const body = e?.body;
|
|
2524
2731
|
if (c.service && body?.trim()) return { ok: false, reason: `${errMsg(e)} \u2014 ${serviceMessage(Buffer.from(body), e.contentType)}`, url: e?.url };
|
|
@@ -2526,7 +2733,7 @@ async function tryOne(p, c, tier, via = "plain") {
|
|
|
2526
2733
|
}
|
|
2527
2734
|
const { bytes, contentType } = got;
|
|
2528
2735
|
if (c.service && !looksLikePdf(bytes) && !isXmlArticle(bytes.toString("utf8"))) return { ok: false, reason: `service: ${serviceMessage(bytes, contentType)}`, url: got.url };
|
|
2529
|
-
if (via === "unlocker" && !bytes.length) return { ok: false, reason:
|
|
2736
|
+
if (typeof via === "object" && "unlocker" in via && !bytes.length) return { ok: false, reason: `${via.unlocker}: empty response` };
|
|
2530
2737
|
const r = await convertBytes(p, bytes, contentType);
|
|
2531
2738
|
if (!r.ok) return { ok: false, reason: c.pdf && r.format !== "pdf" ? `not a pdf (${r.reason})` : r.reason, url: got.url, pdfUrl: r.format === "html" ? pdfLink(bytes.toString("utf8"), got.url ?? c.url) : void 0 };
|
|
2532
2739
|
return { ok: true, tier, format: r.format, raw: r.format === "pdf" ? bytes : bytes.toString("utf8"), md: r.md, version: c.version };
|
|
@@ -2560,9 +2767,9 @@ function serviceMessage(bytes, contentType = "") {
|
|
|
2560
2767
|
function describe(reason, format, md) {
|
|
2561
2768
|
const words3 = md.split(/\s+/).filter(Boolean).length;
|
|
2562
2769
|
const headings2 = md.split("\n").filter((l) => /^#{2,6}\s/.test(l)).length;
|
|
2563
|
-
const
|
|
2564
|
-
if (reason === "no methods/results") return `no article body (${
|
|
2565
|
-
if (reason === "title missing") return `neither title nor DOI in text (${
|
|
2770
|
+
const seen2 = `${format}, ${words3} words, ${proseWords(md)} in prose, ${headings2} heading${headings2 === 1 ? "" : "s"}`;
|
|
2771
|
+
if (reason === "no methods/results") return `no article body (${seen2})`;
|
|
2772
|
+
if (reason === "title missing") return `neither title nor DOI in text (${seen2})`;
|
|
2566
2773
|
return reason;
|
|
2567
2774
|
}
|
|
2568
2775
|
async function convertBytes(p, bytes, contentType = "") {
|
|
@@ -2643,7 +2850,7 @@ function elsevierToJats(xml) {
|
|
|
2643
2850
|
var WINDOW_MS = 6e4;
|
|
2644
2851
|
var PER_WINDOW = 10;
|
|
2645
2852
|
var MAX_WAIT_MS = 65e3;
|
|
2646
|
-
var
|
|
2853
|
+
var TIMEOUT_MS5 = 1e4;
|
|
2647
2854
|
var calls = [];
|
|
2648
2855
|
async function pace() {
|
|
2649
2856
|
const now2 = Date.now();
|
|
@@ -2651,11 +2858,11 @@ async function pace() {
|
|
|
2651
2858
|
if (calls.length >= PER_WINDOW) await new Promise((r) => setTimeout(r, calls[0] + WINDOW_MS - now2 + 200));
|
|
2652
2859
|
calls.push(Date.now());
|
|
2653
2860
|
}
|
|
2654
|
-
async function coreFetch(url,
|
|
2655
|
-
const headers = { "User-Agent": LIBRARY_UA, Authorization: `Bearer ${
|
|
2861
|
+
async function coreFetch(url, key2) {
|
|
2862
|
+
const headers = { "User-Agent": LIBRARY_UA, Authorization: `Bearer ${key2}` };
|
|
2656
2863
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2657
2864
|
await pace();
|
|
2658
|
-
const res = await fetch(url, { headers, signal: AbortSignal.timeout(
|
|
2865
|
+
const res = await fetch(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS5), redirect: "follow" });
|
|
2659
2866
|
if (res.ok) return await res.text();
|
|
2660
2867
|
const body = await res.text().catch(() => "");
|
|
2661
2868
|
if (res.status === 429 && attempt === 0) {
|
|
@@ -2668,17 +2875,17 @@ async function coreFetch(url, key) {
|
|
|
2668
2875
|
}
|
|
2669
2876
|
throw new Error("HTTP 429");
|
|
2670
2877
|
}
|
|
2671
|
-
function coreTier(
|
|
2672
|
-
const
|
|
2878
|
+
function coreTier(apiKey2) {
|
|
2879
|
+
const key2 = apiKey2?.trim();
|
|
2673
2880
|
return {
|
|
2674
2881
|
name: "core",
|
|
2675
2882
|
applies: (p) => p.doi ? true : "no doi",
|
|
2676
2883
|
async run(p, ctx) {
|
|
2677
|
-
if (!
|
|
2884
|
+
if (!key2) return { ...miss(this.name, "needs api key"), skipped: true };
|
|
2678
2885
|
let data;
|
|
2679
2886
|
try {
|
|
2680
2887
|
const q = encodeURIComponent(`doi:"${p.doi}"`);
|
|
2681
|
-
data = JSON.parse(await coreFetch(`https://api.core.ac.uk/v3/search/works/?q=${q}&limit=5`,
|
|
2888
|
+
data = JSON.parse(await coreFetch(`https://api.core.ac.uk/v3/search/works/?q=${q}&limit=5`, key2));
|
|
2682
2889
|
} catch (e) {
|
|
2683
2890
|
return miss(this.name, errMsg(e));
|
|
2684
2891
|
}
|
|
@@ -2691,10 +2898,10 @@ function coreTier(apiKey) {
|
|
|
2691
2898
|
}
|
|
2692
2899
|
function coreCandidates(d) {
|
|
2693
2900
|
const out = [];
|
|
2694
|
-
const
|
|
2901
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2695
2902
|
const add = (url, pdf, host3) => {
|
|
2696
|
-
if (!url ||
|
|
2697
|
-
|
|
2903
|
+
if (!url || seen2.has(url)) return;
|
|
2904
|
+
seen2.add(url);
|
|
2698
2905
|
out.push({ url, version: "published", source: "core", host: host3, pdf });
|
|
2699
2906
|
};
|
|
2700
2907
|
for (const w of d.results ?? []) {
|
|
@@ -2727,10 +2934,10 @@ var europepmc = {
|
|
|
2727
2934
|
};
|
|
2728
2935
|
function europepmcCandidates(r, pmcid) {
|
|
2729
2936
|
const out = [];
|
|
2730
|
-
const
|
|
2937
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2731
2938
|
const add = (url, pdf, host3, version) => {
|
|
2732
|
-
if (!url ||
|
|
2733
|
-
|
|
2939
|
+
if (!url || seen2.has(url)) return;
|
|
2940
|
+
seen2.add(url);
|
|
2734
2941
|
out.push({ url, version, source: "europepmc", host: host3, pdf });
|
|
2735
2942
|
};
|
|
2736
2943
|
const id = (r.pmcid ?? pmcid ?? "").toUpperCase() || null;
|
|
@@ -2768,12 +2975,12 @@ var openalex = {
|
|
|
2768
2975
|
};
|
|
2769
2976
|
function openalexCandidates(d) {
|
|
2770
2977
|
const locs = [...d.best_oa_location ? [d.best_oa_location] : [], ...d.locations ?? []].filter((l) => l.is_oa);
|
|
2771
|
-
const
|
|
2978
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2772
2979
|
const out = [];
|
|
2773
2980
|
for (const l of locs) {
|
|
2774
2981
|
for (const [url, pdf] of [[l.pdf_url, true], [l.landing_page_url, false]]) {
|
|
2775
|
-
if (!url ||
|
|
2776
|
-
|
|
2982
|
+
if (!url || seen2.has(url) || /doi\.org\//.test(url)) continue;
|
|
2983
|
+
seen2.add(url);
|
|
2777
2984
|
out.push({ url, version: oaVersion(l.version), source: "openalex", host: l.source?.display_name ?? "unknown", pdf });
|
|
2778
2985
|
}
|
|
2779
2986
|
}
|
|
@@ -2825,17 +3032,17 @@ var hostOf3 = (url) => {
|
|
|
2825
3032
|
};
|
|
2826
3033
|
function tdmCandidates(work, tokens2 = {}, env = process.env) {
|
|
2827
3034
|
const links = (work.message?.link ?? []).filter((l) => l["intended-application"] === "text-mining" && l.URL);
|
|
2828
|
-
const
|
|
3035
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2829
3036
|
const candidates = [];
|
|
2830
3037
|
const missingTokens = /* @__PURE__ */ new Set();
|
|
2831
3038
|
for (const l of links) {
|
|
2832
3039
|
const ct = (l["content-type"] ?? "").toLowerCase();
|
|
2833
|
-
if (
|
|
3040
|
+
if (seen2.has(l.URL)) {
|
|
2834
3041
|
const prev = candidates.find((c) => c.url === l.URL);
|
|
2835
3042
|
if (prev && /pdf/.test(ct)) prev.pdf = true;
|
|
2836
3043
|
continue;
|
|
2837
3044
|
}
|
|
2838
|
-
|
|
3045
|
+
seen2.add(l.URL);
|
|
2839
3046
|
const rule = TOKENED.find((r) => r.host.test(hostOf3(l.URL)));
|
|
2840
3047
|
let headers;
|
|
2841
3048
|
if (rule) {
|
|
@@ -2894,12 +3101,12 @@ var unpaywall = {
|
|
|
2894
3101
|
};
|
|
2895
3102
|
function unpaywallCandidates(d) {
|
|
2896
3103
|
const locs = [...d.best_oa_location ? [d.best_oa_location] : [], ...d.oa_locations ?? []];
|
|
2897
|
-
const
|
|
3104
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
2898
3105
|
const out = [];
|
|
2899
3106
|
for (const l of locs) {
|
|
2900
3107
|
for (const [url, pdf] of [[l.url_for_pdf, true], [l.url ?? l.url_for_landing_page, false]]) {
|
|
2901
|
-
if (!url ||
|
|
2902
|
-
|
|
3108
|
+
if (!url || seen2.has(url)) continue;
|
|
3109
|
+
seen2.add(url);
|
|
2903
3110
|
out.push({ url, version: oaVersion(l.version), source: "unpaywall", host: l.host_type ?? "unknown", pdf });
|
|
2904
3111
|
}
|
|
2905
3112
|
}
|
|
@@ -2950,9 +3157,19 @@ var VARIABLES = [
|
|
|
2950
3157
|
"FH_PLAYWRIGHT_2",
|
|
2951
3158
|
"FH_CHROME_1",
|
|
2952
3159
|
"FH_PLAYWRIGHT_HEADLESS",
|
|
3160
|
+
"FH_VERIFY_PROVIDER",
|
|
3161
|
+
"FH_VERIFY_PERPLEXITY_MODEL",
|
|
3162
|
+
"FH_VERIFY_PERPLEXITY_URL",
|
|
3163
|
+
"FH_VERIFY_PERPLEXITY_API_KEY",
|
|
3164
|
+
"FH_VERIFY_GOOGLE_MODEL",
|
|
3165
|
+
"FH_VERIFY_GOOGLE_URL",
|
|
3166
|
+
"FH_VERIFY_GOOGLE_API_KEY",
|
|
3167
|
+
"FH_VERIFY_OPENAI_MODEL",
|
|
3168
|
+
"FH_VERIFY_OPENAI_URL",
|
|
3169
|
+
"FH_VERIFY_OPENAI_API_KEY",
|
|
3170
|
+
"FH_VERIFY_MODEL",
|
|
2953
3171
|
"FH_VERIFY_URL",
|
|
2954
3172
|
"FH_VERIFY_API_KEY",
|
|
2955
|
-
"FH_VERIFY_MODEL",
|
|
2956
3173
|
"FH_VERIFY_THRESHOLD",
|
|
2957
3174
|
"FH_VERIFY_TIMEOUT_SECS",
|
|
2958
3175
|
"FH_RETRY_AFTER_DAYS",
|
|
@@ -2960,7 +3177,9 @@ var VARIABLES = [
|
|
|
2960
3177
|
"FH_REFRESH_AFTER_DAYS",
|
|
2961
3178
|
"FH_SEARCH_CACHE_DAYS",
|
|
2962
3179
|
"FH_NCBI_API_KEY",
|
|
2963
|
-
"
|
|
3180
|
+
"FH_ZENROWS_API_KEY",
|
|
3181
|
+
"FH_ZYTE_API_KEY",
|
|
3182
|
+
"FH_BRIGHTDATA_API_KEY",
|
|
2964
3183
|
"FH_BRIGHTDATA_ZONE"
|
|
2965
3184
|
];
|
|
2966
3185
|
var sources = (env = process.env) => Object.fromEntries(VARIABLES.map((v) => [v, sourceOf(v, env)]));
|
|
@@ -2991,19 +3210,171 @@ function resolveTiers(env = process.env) {
|
|
|
2991
3210
|
if (proxyUrl) available.set("proxy", urlTier("proxy", proxyUrl, proxyHeaders(str("FH_PROXY_HEADERS", env))));
|
|
2992
3211
|
const listed = str("FH_TIERS", env);
|
|
2993
3212
|
const order2 = listed ? listed.split(",").map((s) => s.trim()).filter(Boolean) : [...available.keys()];
|
|
2994
|
-
const tiers = [],
|
|
3213
|
+
const tiers = [], seen2 = /* @__PURE__ */ new Set();
|
|
2995
3214
|
for (const name of order2) {
|
|
2996
|
-
if (
|
|
2997
|
-
|
|
3215
|
+
if (seen2.has(name)) continue;
|
|
3216
|
+
seen2.add(name);
|
|
2998
3217
|
const t = available.get(name);
|
|
2999
3218
|
if (t) tiers.push(t);
|
|
3000
3219
|
else if (name === "proxy") problems.push('FH_TIERS: "proxy" listed, but FH_PROXY_URL is unset');
|
|
3001
3220
|
else problems.push(`FH_TIERS: unknown tier "${name}" (built-in: ${BUILTIN.map((t2) => t2.name).join(", ")}; proxy when FH_PROXY_URL is set)`);
|
|
3002
3221
|
}
|
|
3003
|
-
const all = [...tiers.map((t) => ({ name: t.name, enabled: true })), ...[...available.keys()].filter((n) => !
|
|
3222
|
+
const all = [...tiers.map((t) => ({ name: t.name, enabled: true })), ...[...available.keys()].filter((n) => !seen2.has(n)).map((name) => ({ name, enabled: false }))];
|
|
3004
3223
|
return { tiers, all, source: sourceOf("FH_TIERS", env), problems };
|
|
3005
3224
|
}
|
|
3006
3225
|
|
|
3226
|
+
// src/verify/google.ts
|
|
3227
|
+
var google = {
|
|
3228
|
+
name: "google",
|
|
3229
|
+
defaultModel: "gemini-decision-1",
|
|
3230
|
+
hostedUrl: "https://generativelanguage.googleapis.com",
|
|
3231
|
+
keyPrefixes: ["AIza", "AQ."],
|
|
3232
|
+
// AQ.: the newer AI Studio keys
|
|
3233
|
+
modelPrefix: "gemini-",
|
|
3234
|
+
matches: (host3) => host3 === "generativelanguage.googleapis.com",
|
|
3235
|
+
windowChars: () => 8e5,
|
|
3236
|
+
request: ({ base_url, api_key, model, state, questions }) => ({
|
|
3237
|
+
url: `${base_url}/v1beta/decisions`,
|
|
3238
|
+
headers: { "content-type": "application/json", ...api_key ? { "x-goog-api-key": api_key } : {} },
|
|
3239
|
+
body: JSON.stringify({ model, input: googleInput(state), questions })
|
|
3240
|
+
})
|
|
3241
|
+
};
|
|
3242
|
+
function googleInput(state) {
|
|
3243
|
+
if (typeof state === "string") return state;
|
|
3244
|
+
if (!state || typeof state !== "object") return JSON.stringify(state);
|
|
3245
|
+
return Object.entries(state).map(([k, v]) => ({ type: "text", text: JSON.stringify({ [k]: v }) + "\n" }));
|
|
3246
|
+
}
|
|
3247
|
+
|
|
3248
|
+
// src/verify/openai.ts
|
|
3249
|
+
var openai = {
|
|
3250
|
+
name: "openai",
|
|
3251
|
+
defaultModel: "gpt-6-luna",
|
|
3252
|
+
hostedUrl: "https://api.openai.com",
|
|
3253
|
+
keyPrefixes: ["sk-"],
|
|
3254
|
+
modelPrefix: "gpt-",
|
|
3255
|
+
matches: (host3) => host3 === "api.openai.com",
|
|
3256
|
+
windowChars: () => 4e5,
|
|
3257
|
+
// its context limit for decisions is not documented: half of the others', a longer paper is windowed
|
|
3258
|
+
request: ({ base_url, api_key, model, state, questions }) => ({
|
|
3259
|
+
url: `${base_url}/v1/decisions`,
|
|
3260
|
+
headers: { "content-type": "application/json", ...api_key ? { authorization: `Bearer ${api_key}` } : {} },
|
|
3261
|
+
body: JSON.stringify({
|
|
3262
|
+
model,
|
|
3263
|
+
input: typeof state === "string" ? state : [{ role: "user", content: [{ type: "input_json", data: state }] }],
|
|
3264
|
+
questions: Object.entries(questions).map(([name, q]) => ({ type: "predicate", name, instructions: q.instructions }))
|
|
3265
|
+
})
|
|
3266
|
+
}),
|
|
3267
|
+
parse: (body) => {
|
|
3268
|
+
const list5 = body.answers;
|
|
3269
|
+
if (!Array.isArray(list5)) return null;
|
|
3270
|
+
const out = {};
|
|
3271
|
+
for (const a of list5) {
|
|
3272
|
+
if (a.type === "refusal") throw new Error(`refused to answer "${a.name}"`);
|
|
3273
|
+
if (a.name && typeof a.probability === "number") out[a.name] = { noul: a.probability };
|
|
3274
|
+
}
|
|
3275
|
+
return out;
|
|
3276
|
+
}
|
|
3277
|
+
};
|
|
3278
|
+
|
|
3279
|
+
// src/verify/perplexity.ts
|
|
3280
|
+
var perplexity = {
|
|
3281
|
+
name: "perplexity",
|
|
3282
|
+
defaultModel: "pplx-decider-flash-v1.2",
|
|
3283
|
+
hostedUrl: "https://api.perplexity.ai",
|
|
3284
|
+
keyPrefixes: ["pplx-"],
|
|
3285
|
+
modelPrefix: "pplx-",
|
|
3286
|
+
matches: (host3) => host3 === "api.perplexity.ai",
|
|
3287
|
+
// Hosted takes 256k tokens in one request (a 50k-token paper in 2 s); the
|
|
3288
|
+
// Mac app is limited to 32k and slows steeply beyond 25k, so it windows.
|
|
3289
|
+
windowChars: (baseUrl) => {
|
|
3290
|
+
try {
|
|
3291
|
+
return new URL(baseUrl).hostname === "api.perplexity.ai" ? 8e5 : 9e4;
|
|
3292
|
+
} catch {
|
|
3293
|
+
return 9e4;
|
|
3294
|
+
}
|
|
3295
|
+
},
|
|
3296
|
+
request: ({ base_url, api_key, model, state, questions }) => ({
|
|
3297
|
+
url: `${base_url}/v1/decisions`,
|
|
3298
|
+
headers: { "content-type": "application/json", ...api_key ? { authorization: `Bearer ${api_key}` } : {} },
|
|
3299
|
+
body: JSON.stringify({ model, state, questions })
|
|
3300
|
+
})
|
|
3301
|
+
};
|
|
3302
|
+
|
|
3303
|
+
// src/verify/providers.ts
|
|
3304
|
+
var PROVIDERS = [google, openai, perplexity];
|
|
3305
|
+
var PROVIDER_NAMES = PROVIDERS.map((p) => p.name);
|
|
3306
|
+
var providerByName = (name) => PROVIDERS.find((p) => p.name === name) ?? null;
|
|
3307
|
+
var providerForKey = (key2) => PROVIDERS.find((p) => p.keyPrefixes.some((k) => key2.startsWith(k))) ?? null;
|
|
3308
|
+
function providerFor(baseUrl) {
|
|
3309
|
+
let host3 = "";
|
|
3310
|
+
try {
|
|
3311
|
+
host3 = new URL(baseUrl).hostname;
|
|
3312
|
+
} catch {
|
|
3313
|
+
}
|
|
3314
|
+
return PROVIDERS.find((p) => p.matches(host3)) ?? PROVIDERS[PROVIDERS.length - 1];
|
|
3315
|
+
}
|
|
3316
|
+
|
|
3317
|
+
// src/verify/config.ts
|
|
3318
|
+
var cleanUrl = (u) => u.replace(/\/+$/, "").replace(/\/(v1beta|v1)(\/decisions)?$|\/decisions$/, "");
|
|
3319
|
+
function resolve3(env) {
|
|
3320
|
+
const problems = [];
|
|
3321
|
+
const field2 = (p, f) => {
|
|
3322
|
+
const own = p ? `FH_VERIFY_${p.name.toUpperCase()}_${f}` : "";
|
|
3323
|
+
if (own && str(own, env)) return [str(own, env), own];
|
|
3324
|
+
const plain3 = str(`FH_VERIFY_${f}`, env);
|
|
3325
|
+
return [plain3, plain3 || !own ? `FH_VERIFY_${f}` : own];
|
|
3326
|
+
};
|
|
3327
|
+
const filled = (p) => !!(str(`FH_VERIFY_${p.name.toUpperCase()}_URL`, env) || str(`FH_VERIFY_${p.name.toUpperCase()}_API_KEY`, env));
|
|
3328
|
+
const name = str("FH_VERIFY_PROVIDER", env).toLowerCase();
|
|
3329
|
+
let provider = null;
|
|
3330
|
+
if (name) {
|
|
3331
|
+
provider = providerByName(name);
|
|
3332
|
+
if (!provider) return { cfg: null, problems: [`FH_VERIFY_PROVIDER: unknown provider "${name}" (built-in: ${PROVIDER_NAMES.join(", ")}): verification is off`] };
|
|
3333
|
+
} else {
|
|
3334
|
+
const sections2 = PROVIDER_NAMES.map((n) => providerByName(n)).filter(filled);
|
|
3335
|
+
if (sections2.length > 1) return { cfg: null, problems: [`FH_VERIFY_PROVIDER is not set and several sections are filled in (${sections2.map((p) => p.name).join(", ")}): verification is off \u2014 name one`] };
|
|
3336
|
+
provider = sections2[0] ?? null;
|
|
3337
|
+
}
|
|
3338
|
+
const [key2, keyVar] = field2(provider, "API_KEY");
|
|
3339
|
+
const [url, urlVar] = field2(provider, "URL");
|
|
3340
|
+
const api_key = key2 || null;
|
|
3341
|
+
let base_url = cleanUrl(url);
|
|
3342
|
+
if (!base_url && !api_key) {
|
|
3343
|
+
if (provider) problems.push(`FH_VERIFY_PROVIDER=${provider.name}, but neither ${urlVar} nor ${keyVar} is set: verification is off`);
|
|
3344
|
+
return { cfg: null, problems };
|
|
3345
|
+
}
|
|
3346
|
+
if (!provider) provider = (api_key ? providerForKey(api_key) : null) ?? providerFor(base_url);
|
|
3347
|
+
const keyOf = api_key ? providerForKey(api_key) : null;
|
|
3348
|
+
if (keyOf && keyOf !== provider) problems.push(`${keyVar} looks like a ${keyOf.name} key, but the provider is ${provider.name}`);
|
|
3349
|
+
if (!base_url) base_url = provider.hostedUrl;
|
|
3350
|
+
if (!api_key && provider.matches(new URL(base_url).hostname)) problems.push(`${provider.name}'s hosted endpoint needs a key, and ${keyVar} is empty`);
|
|
3351
|
+
const [m, modelVar] = field2(provider, "MODEL");
|
|
3352
|
+
const model = m && m.startsWith(provider.modelPrefix) ? m : provider.defaultModel;
|
|
3353
|
+
if (m && !m.startsWith(provider.modelPrefix)) problems.push(`${modelVar}=${m} is not a ${provider.name} model: ${provider.defaultModel} is used`);
|
|
3354
|
+
return {
|
|
3355
|
+
problems,
|
|
3356
|
+
cfg: {
|
|
3357
|
+
provider,
|
|
3358
|
+
base_url,
|
|
3359
|
+
api_key,
|
|
3360
|
+
model,
|
|
3361
|
+
threshold: num("FH_VERIFY_THRESHOLD", 0.5, env, (n) => n > 0 && n < 1),
|
|
3362
|
+
window_chars: provider.windowChars(base_url, model),
|
|
3363
|
+
timeout_seconds: num("FH_VERIFY_TIMEOUT_SECS", 60, env, (n) => n > 0)
|
|
3364
|
+
}
|
|
3365
|
+
};
|
|
3366
|
+
}
|
|
3367
|
+
var verifyConfig = (env = process.env) => resolve3(env).cfg;
|
|
3368
|
+
var verifyProblems = (env = process.env) => resolve3(env).problems;
|
|
3369
|
+
function isLocal(baseUrl) {
|
|
3370
|
+
try {
|
|
3371
|
+
const h = new URL(baseUrl).hostname;
|
|
3372
|
+
return h === "localhost" || /^127\./.test(h) || h === "::1" || /^10\./.test(h) || /^192\.168\./.test(h) || /^172\.(1[6-9]|2\d|3[01])\./.test(h) || /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(h);
|
|
3373
|
+
} catch {
|
|
3374
|
+
return false;
|
|
3375
|
+
}
|
|
3376
|
+
}
|
|
3377
|
+
|
|
3007
3378
|
// src/log.ts
|
|
3008
3379
|
import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, renameSync as renameSync2, statSync } from "fs";
|
|
3009
3380
|
import { hostname } from "os";
|
|
@@ -3043,8 +3414,8 @@ function migrateLogName(dir = FH_EVIDENCE_DIR) {
|
|
|
3043
3414
|
}
|
|
3044
3415
|
}
|
|
3045
3416
|
function log(tool, id, message) {
|
|
3046
|
-
const clean2 = message.replace(/\x1b\[[0-9;]*m/g, "").replace(/\s*\n\s*/g, " | ");
|
|
3047
|
-
const line = `${stamp()} ${HOST} ${tool} ${id ?? "-"} ${clean2}
|
|
3417
|
+
const clean2 = message.replace(/\x1b\[[0-9;]*m/g, "").replace(/\s*\n\s*/g, " | ").replace(/https:\/\//g, "");
|
|
3418
|
+
const line = `${stamp()} ${HOST} ${tool} ${(id ?? "-").replace(/https:\/\//g, "")} ${clean2}
|
|
3048
3419
|
`;
|
|
3049
3420
|
try {
|
|
3050
3421
|
mkdirSync4(FH_EVIDENCE_DIR, { recursive: true });
|
|
@@ -3120,7 +3491,7 @@ import { z } from "zod";
|
|
|
3120
3491
|
// src/cascade.ts
|
|
3121
3492
|
var PERMANENT = /^(no pmcid|no doi|no pmid|no pmid or doi|no body|closed|no oa copy|no free copy|not in core|no full text|xml without body|template has no placeholder|title missing|title not in text|no methods\/results|no article body|scanned pdf|not a pdf|only copies already tried|only pmc copies|nothing located|unknown content|no text-mining links|needs [a-z/]+ token)/i;
|
|
3122
3493
|
var BLOCKED = /^(challenge not cleared|empty response)/i;
|
|
3123
|
-
var STAGE = /^((?:playwright|chrome|browser|fetch-proxy) [^:]+|brightdata|unlocker): /;
|
|
3494
|
+
var STAGE = /^((?:playwright|chrome|browser|fetch-proxy) [^:]+|brightdata|zenrows|zyte|unlocker): /;
|
|
3124
3495
|
function isPermanent(reason, retryBlocked = false) {
|
|
3125
3496
|
return reason.split(";").every((r) => {
|
|
3126
3497
|
const b = r.trim().replace(STAGE, "");
|
|
@@ -3224,185 +3595,10 @@ function libraryIdForUrl(raw) {
|
|
|
3224
3595
|
}
|
|
3225
3596
|
|
|
3226
3597
|
// src/info.ts
|
|
3227
|
-
import { existsSync as
|
|
3598
|
+
import { existsSync as existsSync6, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
|
|
3228
3599
|
import { dirname as dirname2, join as join8 } from "path";
|
|
3229
|
-
|
|
3230
|
-
// src/verify.ts
|
|
3231
|
-
import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
|
|
3232
|
-
var DEFAULT_MODEL = "pplx-decider-flash-v1.2";
|
|
3233
|
-
var QUESTION = "Does the paper state this, in substance? Ignore section labels and definitions of terms in parentheses. Every fact and number of the statement must be stated in the paper or follow from its numbers; a rounded number counts. If any part of the statement is absent from the paper or contradicted by it, answer false.";
|
|
3234
|
-
function verifyConfig(env = process.env) {
|
|
3235
|
-
const base_url = str("FH_VERIFY_URL", env).replace(/\/+$/, "");
|
|
3236
|
-
if (!base_url) return null;
|
|
3237
|
-
return {
|
|
3238
|
-
base_url,
|
|
3239
|
-
api_key: str("FH_VERIFY_API_KEY", env) || null,
|
|
3240
|
-
model: str("FH_VERIFY_MODEL", env) || DEFAULT_MODEL,
|
|
3241
|
-
threshold: num("FH_VERIFY_THRESHOLD", 0.5, env, (n) => n > 0 && n < 1),
|
|
3242
|
-
// Hosted takes 256k tokens in one request (a 50k-token paper in 2 s); the
|
|
3243
|
-
// Mac app is limited to 32k and slows steeply beyond 25k, so it windows.
|
|
3244
|
-
window_chars: isHosted(base_url) ? 8e5 : 9e4,
|
|
3245
|
-
timeout_seconds: num("FH_VERIFY_TIMEOUT_SECS", 60, env, (n) => n > 0)
|
|
3246
|
-
};
|
|
3247
|
-
}
|
|
3248
|
-
var isHosted = (baseUrl) => {
|
|
3249
|
-
try {
|
|
3250
|
-
return new URL(baseUrl).hostname === "api.perplexity.ai";
|
|
3251
|
-
} catch {
|
|
3252
|
-
return false;
|
|
3253
|
-
}
|
|
3254
|
-
};
|
|
3255
|
-
function isLocal(baseUrl) {
|
|
3256
|
-
try {
|
|
3257
|
-
const h = new URL(baseUrl).hostname;
|
|
3258
|
-
return h === "localhost" || /^127\./.test(h) || h === "::1" || /^10\./.test(h) || /^192\.168\./.test(h) || /^172\.(1[6-9]|2\d|3[01])\./.test(h) || /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(h);
|
|
3259
|
-
} catch {
|
|
3260
|
-
return false;
|
|
3261
|
-
}
|
|
3262
|
-
}
|
|
3263
|
-
function cleanMarkdown(md) {
|
|
3264
|
-
return paperYearOnly(dropReferences(md)).replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\]\([^)]*\)/g, "]").replace(/^\s*#+\s*(see more about|more for you|back to top)\b.*$/gim, "").replace(/\n{3,}/g, "\n\n");
|
|
3265
|
-
}
|
|
3266
|
-
var REF_HEAD = /^(#{1,6})\s*\**\s*(references|bibliography|literature cited|reference list|works cited|cited literature)\b[^\n]*$|^\**(references|bibliography|literature cited)\**:?[ \t]*$/gim;
|
|
3267
|
-
function dropReferences(md) {
|
|
3268
|
-
let out = md;
|
|
3269
|
-
for (; ; ) {
|
|
3270
|
-
REF_HEAD.lastIndex = 0;
|
|
3271
|
-
const m = REF_HEAD.exec(out);
|
|
3272
|
-
if (!m) return out;
|
|
3273
|
-
const level = m[1]?.length ?? 6;
|
|
3274
|
-
const rest = out.slice(m.index + m[0].length);
|
|
3275
|
-
const next = new RegExp(`^#{1,${level}}\\s`, "m").exec(rest);
|
|
3276
|
-
out = out.slice(0, m.index) + (next ? rest.slice(next.index) : "");
|
|
3277
|
-
}
|
|
3278
|
-
}
|
|
3279
|
-
function paperYearOnly(md) {
|
|
3280
|
-
return md.replace(/^(#[^\n]*\n\n)([^\n]*· (?:PMID \d+|DOI 10\.)[^\n]*)$/m, (_, title, line) => {
|
|
3281
|
-
const year = / · (\d{4})(?: · |$)/.exec(line)?.[1];
|
|
3282
|
-
return year ? `${title}${year}` : title.trimEnd();
|
|
3283
|
-
});
|
|
3284
|
-
}
|
|
3285
|
-
function windows(md, max) {
|
|
3286
|
-
const out = [];
|
|
3287
|
-
let cur = "";
|
|
3288
|
-
for (const s of cleanMarkdown(md).split(/\n(?=#)/)) {
|
|
3289
|
-
if (cur && cur.length + s.length + 1 > max) {
|
|
3290
|
-
out.push(cur);
|
|
3291
|
-
cur = "";
|
|
3292
|
-
}
|
|
3293
|
-
cur += (cur ? "\n" : "") + s.slice(0, max);
|
|
3294
|
-
}
|
|
3295
|
-
if (cur) out.push(cur);
|
|
3296
|
-
return out.length ? out : [""];
|
|
3297
|
-
}
|
|
3298
|
-
var MONTH = /^(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|June?|July?|Aug(ust)?|Sep(t(ember)?)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\.?$/;
|
|
3299
|
-
var namesAuthor = (group) => (group.match(/\b[A-Z][\p{L}'’-]+/gu) ?? []).some((w) => !MONTH.test(w));
|
|
3300
|
-
function citationGroups(claim) {
|
|
3301
|
-
const one = /[(\[][^()\[\]]*?\b(1[89]\d\d|20\d\d)[a-z]?\b[^()\[\]]*[)\]]/g;
|
|
3302
|
-
const groups = [];
|
|
3303
|
-
let last = -1;
|
|
3304
|
-
for (const m of claim.matchAll(one)) {
|
|
3305
|
-
if (!namesAuthor(m[0])) continue;
|
|
3306
|
-
const between = claim.slice(last, m.index);
|
|
3307
|
-
if (last >= 0 && /^[\s;,]*(and|&)?[\s;,]*$/i.test(between)) {
|
|
3308
|
-
groups[groups.length - 1] += between + m[0];
|
|
3309
|
-
} else groups.push(m[0]);
|
|
3310
|
-
last = m.index + m[0].length;
|
|
3311
|
-
}
|
|
3312
|
-
return groups;
|
|
3313
|
-
}
|
|
3314
|
-
function fragment(claim) {
|
|
3315
|
-
const body = claim.trim().replace(/^[-*+]\s+/, "").replace(/^\*\*[^*]+:\*\*\s*/, "").replace(/^[("'\u201c]+/, "");
|
|
3316
|
-
const first = /^(\S+)/.exec(body)?.[1] ?? "";
|
|
3317
|
-
const oddsRatio = first === "OR" && /^OR\s+(\d|=|\(|of\b|for\b)/.test(body);
|
|
3318
|
-
if (!oddsRatio && /^(and|or|but|nor|which|whereas|while)$/i.test(first.replace(/[,;:]$/, ""))) return `claim is a fragment: starts with "${first}" \u2014 send a complete statement with its subject`;
|
|
3319
|
-
return null;
|
|
3320
|
-
}
|
|
3321
|
-
var SUPERSEDED = "The corrected text replaces figures that the paper first published wrongly. Does the statement give a figure for a quantity the corrected text also gives, but with a different value \u2014 the superseded, uncorrected figure? If the statement's figures match the corrected text, or it concerns something the corrected text does not cover, answer false.";
|
|
3322
|
-
function correctedText(md) {
|
|
3323
|
-
const i = md.indexOf(`
|
|
3324
|
-
${CORRECTED_HEADING}
|
|
3325
|
-
`);
|
|
3326
|
-
if (i < 0) return null;
|
|
3327
|
-
return md.slice(i + CORRECTED_HEADING.length + 2).split("\n").filter((l) => l.trim() && !/^NLM corrected these sentences/.test(l)).join("\n").trim() || null;
|
|
3328
|
-
}
|
|
3329
|
-
var RETRY_MS = 2e3;
|
|
3330
|
-
function decider(cfg, fetchFn = fetch) {
|
|
3331
|
-
return async (state, questions) => {
|
|
3332
|
-
const headers = { "content-type": "application/json" };
|
|
3333
|
-
if (cfg.api_key) headers.authorization = `Bearer ${cfg.api_key}`;
|
|
3334
|
-
const body = JSON.stringify({ model: cfg.model, state, questions });
|
|
3335
|
-
for (let attempt = 0; ; attempt++) {
|
|
3336
|
-
let r;
|
|
3337
|
-
try {
|
|
3338
|
-
r = await fetchFn(`${cfg.base_url}/v1/decisions`, { method: "POST", headers, body, signal: AbortSignal.timeout(cfg.timeout_seconds * 1e3) });
|
|
3339
|
-
} catch (e) {
|
|
3340
|
-
const name = e instanceof Error ? e.name : "";
|
|
3341
|
-
const cause = e.cause;
|
|
3342
|
-
if (name === "TimeoutError" || name === "AbortError" || cause?.code === "UND_ERR_HEADERS_TIMEOUT") throw new Error(`${cfg.model}: no answer within ${cfg.timeout_seconds}s (${body.length} chars)`);
|
|
3343
|
-
throw new Error(`${cfg.model}: ${cause?.message ?? (e instanceof Error ? e.message : String(e))}`);
|
|
3344
|
-
}
|
|
3345
|
-
const j = await r.json().catch(() => ({}));
|
|
3346
|
-
if (j.answers) return j.answers;
|
|
3347
|
-
const msg = typeof j.error === "string" ? j.error : j.error?.message;
|
|
3348
|
-
if (attempt === 0 && ([502, 503, 504].includes(r.status) || /temporarily unavailable|overloaded|try again|retry your request/i.test(msg ?? ""))) {
|
|
3349
|
-
await new Promise((res) => setTimeout(res, RETRY_MS));
|
|
3350
|
-
continue;
|
|
3351
|
-
}
|
|
3352
|
-
throw new Error(msg ? `${cfg.model}: ${msg}` : `${cfg.model}: HTTP ${r.status} without an answer`);
|
|
3353
|
-
}
|
|
3354
|
-
};
|
|
3355
|
-
}
|
|
3356
|
-
async function readPaper(raw, libraryDir = FH_EVIDENCE_DIR) {
|
|
3357
|
-
const p = parseId(raw);
|
|
3358
|
-
if (p.error) return { id: p.requested, error: p.error };
|
|
3359
|
-
const paths = entryPaths(libraryDir, p.type, p.id);
|
|
3360
|
-
if (!entryExists(paths)) return { id: p.requested, error: "not in library" };
|
|
3361
|
-
const full = existsSync6(paths.fulltextMd);
|
|
3362
|
-
if (full) return { id: p.requested, basis: "full_text", text: readFileSync5(paths.fulltextMd, "utf8") };
|
|
3363
|
-
const meta = readMeta(paths);
|
|
3364
|
-
return { id: p.requested, basis: meta.has_abstract ? "abstract" : "title", text: readFileSync5(paths.md, "utf8") };
|
|
3365
|
-
}
|
|
3366
|
-
async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
|
|
3367
|
-
const out = { claim, id, verdict: "error", reason: null, score: null, basis: null, windows: 0, glyphs_unresolved: 0, superseded: null, model: cfg?.model ?? null };
|
|
3368
|
-
const words3 = claim.trim().split(/\s+/).filter(Boolean).length;
|
|
3369
|
-
if (!words3) return { ...out, error: "claim empty" };
|
|
3370
|
-
if (words3 < 3) return { ...out, error: "claim too short to be a finding" };
|
|
3371
|
-
const frag = fragment(claim);
|
|
3372
|
-
if (frag) return { ...out, error: frag };
|
|
3373
|
-
const groups = citationGroups(claim);
|
|
3374
|
-
if (groups.length) return { ...out, error: groups.length > 1 ? `compound claim: ${groups.length} citation groups ${groups.join(" ")} \u2014 one finding per call, without its sources` : `claim names a source ${groups[0]} \u2014 send the finding without its sources; the paper is the id` };
|
|
3375
|
-
const paper = await read2(id);
|
|
3376
|
-
out.id = paper.id;
|
|
3377
|
-
if ("error" in paper) return { ...out, error: paper.error };
|
|
3378
|
-
if (!cfg || !decide) return { ...out, error: "no verify model configured (FH_VERIFY_URL)" };
|
|
3379
|
-
out.basis = paper.basis;
|
|
3380
|
-
out.glyphs_unresolved = countUnresolved(paper.text);
|
|
3381
|
-
if (paper.basis === "title") return { ...out, verdict: "fail", reason: NOTHING_TO_VERIFY };
|
|
3382
|
-
const ws = windows(paper.text, cfg.window_chars);
|
|
3383
|
-
out.windows = ws.length;
|
|
3384
|
-
try {
|
|
3385
|
-
let score = 0;
|
|
3386
|
-
for (const w of ws) {
|
|
3387
|
-
const a = await decide({ paper: w, statement: claim }, { backed: { type: "noul", instructions: QUESTION } });
|
|
3388
|
-
score = Math.max(score, a.backed?.noul ?? 0);
|
|
3389
|
-
}
|
|
3390
|
-
out.score = score;
|
|
3391
|
-
const corrected = correctedText(paper.text);
|
|
3392
|
-
if (corrected) {
|
|
3393
|
-
const a = await decide({ corrected, statement: claim }, { superseded: { type: "noul", instructions: SUPERSEDED } });
|
|
3394
|
-
out.superseded = (a.superseded?.noul ?? 0) >= 0.5;
|
|
3395
|
-
}
|
|
3396
|
-
} catch (e) {
|
|
3397
|
-
return { ...out, error: e instanceof Error ? e.message : String(e) };
|
|
3398
|
-
}
|
|
3399
|
-
if (out.score >= cfg.threshold) return { ...out, verdict: "pass" };
|
|
3400
|
-
return paper.basis === "full_text" ? { ...out, verdict: "fail" } : { ...out, verdict: "unverifiable", reason: "only the abstract is stored and it does not state the claim; the full text may" };
|
|
3401
|
-
}
|
|
3402
|
-
|
|
3403
|
-
// src/info.ts
|
|
3404
3600
|
function* metaFiles(dir) {
|
|
3405
|
-
if (!
|
|
3601
|
+
if (!existsSync6(dir)) return;
|
|
3406
3602
|
for (const name of readdirSync3(dir)) {
|
|
3407
3603
|
const p = join8(dir, name);
|
|
3408
3604
|
if (statSync3(p).isDirectory()) yield* metaFiles(p);
|
|
@@ -3418,8 +3614,8 @@ var human = (n) => {
|
|
|
3418
3614
|
}
|
|
3419
3615
|
return i ? `${n.toFixed(1)} ${u[i]}` : `${n} B`;
|
|
3420
3616
|
};
|
|
3421
|
-
function field(md,
|
|
3422
|
-
const m = new RegExp(`^${
|
|
3617
|
+
function field(md, key2) {
|
|
3618
|
+
const m = new RegExp(`^${key2}:\\s*(.*)$`, "m").exec(md);
|
|
3423
3619
|
return m ? m[1].trim() : "";
|
|
3424
3620
|
}
|
|
3425
3621
|
function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
@@ -3427,9 +3623,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3427
3623
|
evidence_dir: libraryDir,
|
|
3428
3624
|
host: host3,
|
|
3429
3625
|
tiers: tiers.all,
|
|
3430
|
-
config: { ...settings(), problems: tiers.problems, sources: sources() },
|
|
3626
|
+
config: { ...settings(), problems: [...tiers.problems, ...verifyProblems()], sources: sources() },
|
|
3431
3627
|
download: downloadInfo(),
|
|
3432
3628
|
verify: verifyInfo(),
|
|
3629
|
+
unlockers: unlockers().map((provider) => ({ provider })),
|
|
3630
|
+
stages: ownStages(),
|
|
3433
3631
|
entries: 0,
|
|
3434
3632
|
size_bytes: 0,
|
|
3435
3633
|
size: "",
|
|
@@ -3442,11 +3640,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3442
3640
|
concerns: 0,
|
|
3443
3641
|
updates: 0
|
|
3444
3642
|
};
|
|
3445
|
-
for (const type of
|
|
3643
|
+
for (const type of existsSync6(libraryDir) ? readdirSync3(libraryDir) : []) {
|
|
3446
3644
|
const typeDir = join8(libraryDir, type);
|
|
3447
3645
|
if (!statSync3(typeDir).isDirectory()) continue;
|
|
3448
3646
|
for (const meta of metaFiles(typeDir)) {
|
|
3449
|
-
const md =
|
|
3647
|
+
const md = readFileSync5(meta, "utf8");
|
|
3450
3648
|
const raw = field(md, "level") || "unknown";
|
|
3451
3649
|
const level = raw === "abstract" && field(md, "has_abstract") === "no" ? "title" : raw;
|
|
3452
3650
|
info.entries++;
|
|
@@ -3485,15 +3683,19 @@ function noticeTypes(md, metaPath) {
|
|
|
3485
3683
|
return out;
|
|
3486
3684
|
}
|
|
3487
3685
|
try {
|
|
3488
|
-
const xml =
|
|
3686
|
+
const xml = readFileSync5(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
|
|
3489
3687
|
for (const m of xml.matchAll(/<CommentsCorrections RefType="([A-Za-z]+)"/g)) if (XML_TYPES[m[1]]) out.add(XML_TYPES[m[1]]);
|
|
3490
3688
|
} catch {
|
|
3491
3689
|
}
|
|
3492
3690
|
return out;
|
|
3493
3691
|
}
|
|
3692
|
+
function ownStages() {
|
|
3693
|
+
const f = fetchProxy();
|
|
3694
|
+
return [...f ? [{ name: fetchProxyName(f), host: f.host, port: f.port }] : [], ...browserStages().map((b) => ({ name: stageName(b), host: b.host, port: b.port }))];
|
|
3695
|
+
}
|
|
3494
3696
|
function verifyInfo() {
|
|
3495
3697
|
const v = verifyConfig();
|
|
3496
|
-
return v ? { model: v.model, base_url: v.base_url, local: isLocal(v.base_url) } : null;
|
|
3698
|
+
return v ? { provider: v.provider.name, model: v.model, base_url: v.base_url, local: isLocal(v.base_url) } : null;
|
|
3497
3699
|
}
|
|
3498
3700
|
function downloadInfo() {
|
|
3499
3701
|
const stages = browserStages();
|
|
@@ -3518,12 +3720,12 @@ function sections(md) {
|
|
|
3518
3720
|
out[i].bodyEnd = i + 1 < out.length && out[i + 1].start < out[i].end ? out[i + 1].start : out[i].end;
|
|
3519
3721
|
out[i].words = countWords(lines.slice(out[i].start + 1, out[i].end).join("\n"));
|
|
3520
3722
|
}
|
|
3521
|
-
const
|
|
3723
|
+
const seen2 = /* @__PURE__ */ new Map();
|
|
3522
3724
|
for (const s of out) {
|
|
3523
3725
|
const k = s.heading.toLowerCase();
|
|
3524
|
-
|
|
3726
|
+
seen2.set(k, [...seen2.get(k) ?? [], s]);
|
|
3525
3727
|
}
|
|
3526
|
-
for (const group of
|
|
3728
|
+
for (const group of seen2.values()) if (group.length > 1) group.forEach((s, i) => {
|
|
3527
3729
|
s.label = `${s.heading} [${i + 1}/${group.length}]`;
|
|
3528
3730
|
});
|
|
3529
3731
|
return out;
|
|
@@ -3714,6 +3916,51 @@ function stem(w) {
|
|
|
3714
3916
|
return w;
|
|
3715
3917
|
}
|
|
3716
3918
|
|
|
3919
|
+
// src/verify/decider.ts
|
|
3920
|
+
var RETRY_MS = 2e3;
|
|
3921
|
+
var WAIT_SCALE = 1;
|
|
3922
|
+
var RATE_LIMITED = /rate limit|quota|resource.?exhausted/i;
|
|
3923
|
+
function waitSeconds(r, msg) {
|
|
3924
|
+
const asked = Number(/retry in (\d+(?:\.\d+)?)\s*s/i.exec(msg)?.[1] ?? r.headers.get("retry-after") ?? NaN);
|
|
3925
|
+
return Math.min(60, Number.isFinite(asked) && asked > 0 ? asked + 1 : 15);
|
|
3926
|
+
}
|
|
3927
|
+
function decider(cfg, fetchFn = fetch) {
|
|
3928
|
+
return async (state, questions) => {
|
|
3929
|
+
const { url, headers, body } = cfg.provider.request({ base_url: cfg.base_url, api_key: cfg.api_key, model: cfg.model, state, questions });
|
|
3930
|
+
let waits = 0;
|
|
3931
|
+
for (let attempt = 0; ; attempt++) {
|
|
3932
|
+
let r;
|
|
3933
|
+
try {
|
|
3934
|
+
r = await fetchFn(url, { method: "POST", headers, body, signal: AbortSignal.timeout(cfg.timeout_seconds * 1e3) });
|
|
3935
|
+
} catch (e) {
|
|
3936
|
+
const name = e instanceof Error ? e.name : "";
|
|
3937
|
+
const cause = e.cause;
|
|
3938
|
+
if (name === "TimeoutError" || name === "AbortError" || cause?.code === "UND_ERR_HEADERS_TIMEOUT") throw new Error(`${cfg.model}: no answer within ${cfg.timeout_seconds}s (${body.length} chars)`);
|
|
3939
|
+
throw new Error(`${cfg.model}: ${cause?.message ?? (e instanceof Error ? e.message : String(e))}`);
|
|
3940
|
+
}
|
|
3941
|
+
const j = await r.json().catch(() => ({}));
|
|
3942
|
+
let answers;
|
|
3943
|
+
try {
|
|
3944
|
+
answers = cfg.provider.parse ? cfg.provider.parse(j) : j.answers ?? null;
|
|
3945
|
+
} catch (e) {
|
|
3946
|
+
throw new Error(`${cfg.model}: ${e instanceof Error ? e.message : String(e)}`);
|
|
3947
|
+
}
|
|
3948
|
+
if (answers) return answers;
|
|
3949
|
+
const msg = typeof j.error === "string" ? j.error : j.error?.message;
|
|
3950
|
+
if ((r.status === 429 || RATE_LIMITED.test(msg ?? "")) && waits < 2) {
|
|
3951
|
+
waits++;
|
|
3952
|
+
await new Promise((res) => setTimeout(res, waitSeconds(r, msg ?? "") * 1e3 * WAIT_SCALE));
|
|
3953
|
+
continue;
|
|
3954
|
+
}
|
|
3955
|
+
if (attempt === 0 && ([502, 503, 504].includes(r.status) || /temporarily unavailable|overloaded|try again|retry your request/i.test(msg ?? ""))) {
|
|
3956
|
+
await new Promise((res) => setTimeout(res, RETRY_MS));
|
|
3957
|
+
continue;
|
|
3958
|
+
}
|
|
3959
|
+
throw new Error(msg ? `${cfg.model}: ${msg}` : `${cfg.model}: HTTP ${r.status} without an answer`);
|
|
3960
|
+
}
|
|
3961
|
+
};
|
|
3962
|
+
}
|
|
3963
|
+
|
|
3717
3964
|
// src/doi.ts
|
|
3718
3965
|
var NCBI_ESEARCH = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
|
|
3719
3966
|
async function pmidForDoi(doi) {
|
|
@@ -3867,7 +4114,7 @@ function parseCsl(json2) {
|
|
|
3867
4114
|
|
|
3868
4115
|
// src/urlfetch.ts
|
|
3869
4116
|
import { createHash as createHash2 } from "crypto";
|
|
3870
|
-
import { existsSync as
|
|
4117
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync6 } from "fs";
|
|
3871
4118
|
import { join as join9 } from "path";
|
|
3872
4119
|
|
|
3873
4120
|
// src/pagemeta.ts
|
|
@@ -3926,9 +4173,9 @@ function metaTags(html) {
|
|
|
3926
4173
|
const head = html.slice(0, 3e5);
|
|
3927
4174
|
for (const m of head.matchAll(/<meta\b[^>]*>/gi)) {
|
|
3928
4175
|
const tag = m[0];
|
|
3929
|
-
const
|
|
4176
|
+
const key2 = (/\b(?:name|property|itemprop)\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1] ?? "").toLowerCase();
|
|
3930
4177
|
const val = /\bcontent\s*=\s*"([^"]*)"/i.exec(tag)?.[1] ?? /\bcontent\s*=\s*'([^']*)'/i.exec(tag)?.[1];
|
|
3931
|
-
if (
|
|
4178
|
+
if (key2 && val && val.trim()) out.set(key2, [...out.get(key2) ?? [], val.replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'").trim()]);
|
|
3932
4179
|
}
|
|
3933
4180
|
return out;
|
|
3934
4181
|
}
|
|
@@ -3947,8 +4194,8 @@ function pageMeta(html) {
|
|
|
3947
4194
|
};
|
|
3948
4195
|
const type = main ? typeOf(main) : null;
|
|
3949
4196
|
const publisher = names(main?.publisher)[0] ?? tag("og:site_name", "citation_journal_title", "citation_publisher", "dc.publisher")[0] ?? names(site)[0] ?? null;
|
|
3950
|
-
const
|
|
3951
|
-
const people = (a) => [...new Set(a)].filter((x) => !/^https?:/i.test(x) && (!publisher ||
|
|
4197
|
+
const key2 = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
4198
|
+
const people = (a) => [...new Set(a)].filter((x) => !/^https?:/i.test(x) && (!publisher || key2(x) !== key2(publisher)));
|
|
3952
4199
|
const fromLd = people(main ? names(main.author) : []);
|
|
3953
4200
|
return {
|
|
3954
4201
|
type: type === "WebPage" ? null : type,
|
|
@@ -4031,8 +4278,8 @@ function renderUrlMeta(m) {
|
|
|
4031
4278
|
return lines.map(([k, v]) => `${k}: ${v}`).join("\n") + "\n";
|
|
4032
4279
|
}
|
|
4033
4280
|
function readUrlMeta(p) {
|
|
4034
|
-
if (!
|
|
4035
|
-
const md =
|
|
4281
|
+
if (!existsSync7(p.meta)) return null;
|
|
4282
|
+
const md = readFileSync6(p.meta, "utf8");
|
|
4036
4283
|
const f = (k) => {
|
|
4037
4284
|
const m = new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md);
|
|
4038
4285
|
return m ? m[1].trim() : "";
|
|
@@ -4078,16 +4325,16 @@ function isScriptShell(markdownOrHtml) {
|
|
|
4078
4325
|
const words3 = text4.split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length;
|
|
4079
4326
|
return { shell: words3 < EMPTY_WORDS || words3 < SHELL_WORDS && SHELL_PHRASE.test(text4), words: words3 };
|
|
4080
4327
|
}
|
|
4081
|
-
var viaName = (via) => typeof via === "object" ? "proxy" in via ? fetchProxyName(via) : stageName({ kind: stageKind(via.browser), label: via.label }) : via;
|
|
4082
|
-
async function stage(url, via) {
|
|
4328
|
+
var viaName = (via) => typeof via === "object" ? "unlocker" in via ? via.unlocker : "proxy" in via ? fetchProxyName(via) : stageName({ kind: stageKind(via.browser), label: via.label }) : via;
|
|
4329
|
+
async function stage(url, via, signal) {
|
|
4083
4330
|
const name = viaName(via);
|
|
4084
4331
|
let got;
|
|
4085
4332
|
try {
|
|
4086
|
-
got = via === "
|
|
4333
|
+
got = typeof via === "object" && "unlocker" in via ? await unlock(url, via.unlocker, signal) : typeof via === "object" ? "proxy" in via ? await fetchBytes(url, BROWSER_HEADERS, via.proxy, signal) : await browserFetch(url, via.browser, void 0, signal) : await fetchBytes(url, BROWSER_HEADERS, void 0, signal);
|
|
4087
4334
|
} catch (e) {
|
|
4088
4335
|
return { ok: false, reason: errMsg(e), url: e?.url, via: name };
|
|
4089
4336
|
}
|
|
4090
|
-
if (via === "
|
|
4337
|
+
if (typeof via === "object" && "unlocker" in via && !got.bytes.length) return { ok: false, reason: "empty response", via: name };
|
|
4091
4338
|
const r = { ok: true, bytes: got.bytes, contentType: got.contentType, url: got.url ?? url, via: name };
|
|
4092
4339
|
if (!looksLikePdf(got.bytes)) {
|
|
4093
4340
|
const text4 = got.bytes.toString("utf8");
|
|
@@ -4104,56 +4351,79 @@ async function stage(url, via) {
|
|
|
4104
4351
|
}
|
|
4105
4352
|
return r;
|
|
4106
4353
|
}
|
|
4107
|
-
var climb = async (
|
|
4108
|
-
|
|
4109
|
-
|
|
4354
|
+
var climb = async (given, onTry, onAlert) => {
|
|
4355
|
+
const url = toHttps(given);
|
|
4356
|
+
if (url !== given) onTry?.(`http upgraded \u2192 ${url}`);
|
|
4110
4357
|
let gone;
|
|
4111
|
-
|
|
4112
|
-
|
|
4358
|
+
let shell;
|
|
4359
|
+
const seen2 = (g) => {
|
|
4360
|
+
if (!g.ok) {
|
|
4361
|
+
gone ??= goneReason(g.reason);
|
|
4362
|
+
if (g.shell && !shell) shell = g.shell;
|
|
4363
|
+
}
|
|
4113
4364
|
return g;
|
|
4114
4365
|
};
|
|
4115
|
-
|
|
4116
|
-
const
|
|
4117
|
-
|
|
4118
|
-
|
|
4366
|
+
const write = (line) => onTry?.(line);
|
|
4367
|
+
const run = (target2, via, name, after) => {
|
|
4368
|
+
let req = null;
|
|
4369
|
+
return {
|
|
4370
|
+
name,
|
|
4371
|
+
abort: (why) => req?.abort(why),
|
|
4372
|
+
go: async () => {
|
|
4373
|
+
req = openRequest(write, name);
|
|
4374
|
+
const g = await stage(target2, via, req.signal);
|
|
4375
|
+
if (req.signal.aborted) return { ok: false, reason: "aborted", via: name };
|
|
4376
|
+
seen2(g);
|
|
4377
|
+
if (via !== "fetch") recordStage(target2, name, g.ok, g.ok ? "" : g.reason);
|
|
4378
|
+
after?.(g);
|
|
4379
|
+
req.close(g.ok ? `ok ${name}` : `failed ${name}: ${g.reason}`);
|
|
4380
|
+
if (!g.ok && (g.reason.startsWith(MISMATCH) || accountProblem(g.reason))) onAlert?.(`${name}: ${g.reason}`);
|
|
4381
|
+
return g;
|
|
4382
|
+
}
|
|
4383
|
+
};
|
|
4384
|
+
};
|
|
4385
|
+
const skipped = (target2, name) => {
|
|
4386
|
+
const w = walled(target2, name);
|
|
4387
|
+
if (w) onTry?.(`skipped ${name}: ${wallNote(w)}`);
|
|
4388
|
+
return !!w;
|
|
4389
|
+
};
|
|
4390
|
+
const hostDown = async (host3, port, name) => {
|
|
4391
|
+
const h = await hostState(host3, port, (s) => onAlert?.(`${name}: ${downNote(s)}`));
|
|
4392
|
+
if (!h.up) onTry?.(`skipped ${name}: ${downNote(h)}`);
|
|
4393
|
+
return !h.up;
|
|
4394
|
+
};
|
|
4395
|
+
const f = fetchProxy();
|
|
4396
|
+
const proxyName = f ? fetchProxyName(f) : "";
|
|
4397
|
+
const first = [run(url, "fetch", "fetch", (g) => {
|
|
4398
|
+
if (!g.ok && g.url && g.url !== url) onTry?.(`redirect \u2192 ${g.url}`);
|
|
4399
|
+
})];
|
|
4400
|
+
if (f && !skipped(url, proxyName) && !await hostDown(f.host, f.port, proxyName)) first.push(run(url, { proxy: f.proxy, label: f.label }, proxyName));
|
|
4401
|
+
const isGone = (g) => g.ok ? null : goneReason(g.reason) ?? null;
|
|
4402
|
+
const one = await firstOk(first, isGone);
|
|
4403
|
+
if (one.won) return one.won;
|
|
4404
|
+
const plain3 = one.results[0] ?? one.results.find(Boolean);
|
|
4405
|
+
const firstReason = plain3.ok ? void 0 : plain3.reason;
|
|
4406
|
+
const target = !plain3.ok && plain3.url && plain3.url !== url ? plain3.url : url;
|
|
4407
|
+
let r = one.results[1] ?? plain3;
|
|
4119
4408
|
const plainVia = (g) => g.via === "fetch" || g.via.startsWith("fetch-proxy ");
|
|
4120
4409
|
const met = (g, re) => re.test(g.ok ? "" : g.reason) || plainVia(g) && re.test(firstReason ?? "");
|
|
4121
4410
|
const escalates = (g) => !g.ok && (!plainVia(g) || met(g, /^(HTTP 403|HTTP 429|wall page|script shell)/));
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
if (
|
|
4125
|
-
const
|
|
4126
|
-
const
|
|
4127
|
-
|
|
4128
|
-
|
|
4129
|
-
|
|
4130
|
-
|
|
4131
|
-
|
|
4132
|
-
|
|
4133
|
-
|
|
4134
|
-
|
|
4135
|
-
|
|
4136
|
-
|
|
4137
|
-
|
|
4138
|
-
const w = walled(target, name);
|
|
4139
|
-
if (w) {
|
|
4140
|
-
onTry?.(`skipped ${name}: ${wallNote(w)}`);
|
|
4141
|
-
continue;
|
|
4142
|
-
}
|
|
4143
|
-
r = seen(await stage(target, { browser: b.endpoint, label: b.label }));
|
|
4144
|
-
recordStage(target, name, r.ok, r.ok ? "" : r.reason);
|
|
4145
|
-
if (!r.ok && r.shell && !shell) shell = r.shell;
|
|
4146
|
-
onTry?.(r.ok ? `ok ${name}` : `failed ${name}: ${r.reason}`);
|
|
4147
|
-
if (!r.ok && r.reason.startsWith(MISMATCH)) onAlert?.(`${name}: ${r.reason}`);
|
|
4148
|
-
}
|
|
4149
|
-
const uw = !r.ok && unlockerConfigured() ? walled(target, "brightdata") : null;
|
|
4150
|
-
if (uw) onTry?.(`skipped brightdata: ${wallNote(uw)}`);
|
|
4151
|
-
else if (!r.ok && unlockerConfigured() && (!plainVia(r) || met(r, /^(HTTP 403|wall page|script shell)/))) {
|
|
4152
|
-
r = seen(await stage(target, "brightdata"));
|
|
4153
|
-
recordStage(target, "brightdata", r.ok, r.ok ? "" : r.reason);
|
|
4154
|
-
onTry?.(r.ok ? "ok brightdata" : `failed brightdata: ${r.reason}`);
|
|
4155
|
-
if (!r.ok && /^unlocker HTTP 4\d\d/.test(r.reason)) onAlert?.(`brightdata: ${r.reason}`);
|
|
4156
|
-
}
|
|
4411
|
+
const notThere = () => gone ? { ...r, ok: false, reason: gone, via: r.via } : null;
|
|
4412
|
+
if (gone) return { ...notThere(), first: gone };
|
|
4413
|
+
if (escalates(r)) {
|
|
4414
|
+
const open = browserStages().filter((b) => !skipped(target, stageName(b)));
|
|
4415
|
+
const down = await Promise.all(open.map((b) => hostDown(b.host, b.port, stageName(b))));
|
|
4416
|
+
const tasks = open.filter((_, i) => !down[i]).map((b) => run(target, { browser: b.endpoint, label: b.label }, stageName(b)));
|
|
4417
|
+
const two = await firstOk(tasks, isGone);
|
|
4418
|
+
if (two.won) return two.won;
|
|
4419
|
+
if (two.results.length) r = two.results.filter(Boolean).pop();
|
|
4420
|
+
if (gone) return { ...notThere(), first: gone };
|
|
4421
|
+
}
|
|
4422
|
+
const unlockable = !r.ok && (!plainVia(r) || met(r, /^(HTTP 403|wall page|script shell)/));
|
|
4423
|
+
const us = (unlockable ? unlockers() : []).filter((u) => !skipped(target, u));
|
|
4424
|
+
const three = await firstOk(us.map((u) => run(target, { unlocker: u }, u)), isGone);
|
|
4425
|
+
if (three.won) return three.won;
|
|
4426
|
+
if (three.results.length) r = three.results.filter(Boolean).pop();
|
|
4157
4427
|
if (!r.ok && shell) {
|
|
4158
4428
|
onTry?.("shell kept: no stage rendered the page, the script shell is served");
|
|
4159
4429
|
return shell;
|
|
@@ -4323,7 +4593,7 @@ function titleLine(m, md) {
|
|
|
4323
4593
|
}
|
|
4324
4594
|
function serve(requested, p, m, args, cached) {
|
|
4325
4595
|
const maxLength = args.max_length ?? 5e3, startIndex = args.start_index ?? 0;
|
|
4326
|
-
const read2 = (file3) =>
|
|
4596
|
+
const read2 = (file3) => existsSync7(file3) ? readFileSync6(file3, "utf8") : "";
|
|
4327
4597
|
if (args.title_only) return { ok: true, text: `Contents of ${requested}:
|
|
4328
4598
|
${titleLine(m, read2(p.md))}`, cached, meta: m };
|
|
4329
4599
|
const rawFile = m.files.find((f) => !f.endsWith("-meta.md") && !f.endsWith("-page.md"));
|
|
@@ -4348,9 +4618,9 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
|
|
|
4348
4618
|
let stored = readUrlMeta(p);
|
|
4349
4619
|
if (stored && fresh(stored) && stored.format === "html" && olderConverter(stored.converted_by, converter)) {
|
|
4350
4620
|
const html = stored.files.find((f) => f.endsWith("-page.html"));
|
|
4351
|
-
if (html &&
|
|
4621
|
+
if (html && existsSync7(join9(p.entryDir, html))) {
|
|
4352
4622
|
try {
|
|
4353
|
-
const page = await convert(
|
|
4623
|
+
const page = await convert(readFileSync6(join9(p.entryDir, html)), stored.content_type || "text/html", stored.final_url || stored.url);
|
|
4354
4624
|
if (page.md !== null) {
|
|
4355
4625
|
writeAtomic(p.md, page.md);
|
|
4356
4626
|
writeUrlMeta(p, { ...stored, title: page.title, converted_by: converter, ...sourceFields(page) });
|
|
@@ -4392,10 +4662,128 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
|
|
|
4392
4662
|
return answer(m, false);
|
|
4393
4663
|
}
|
|
4394
4664
|
|
|
4395
|
-
// src/
|
|
4665
|
+
// src/verify/cache.ts
|
|
4396
4666
|
import { createHash as createHash3 } from "crypto";
|
|
4397
4667
|
import { existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync8 } from "fs";
|
|
4398
4668
|
import { dirname as dirname3, join as join10 } from "path";
|
|
4669
|
+
|
|
4670
|
+
// src/verify/verify.ts
|
|
4671
|
+
import { existsSync as existsSync8, readFileSync as readFileSync7 } from "fs";
|
|
4672
|
+
var QUESTION = "Does the paper state this, in substance? Ignore section labels and definitions of terms in parentheses. Every fact and number of the statement must be stated in the paper or follow from its numbers; a rounded number counts. If any part of the statement is absent from the paper or contradicted by it, answer false.";
|
|
4673
|
+
function cleanMarkdown(md) {
|
|
4674
|
+
return paperYearOnly(dropReferences(md)).replace(/!\[[^\]]*\]\([^)]*\)/g, "").replace(/\]\([^)]*\)/g, "]").replace(/^\s*#+\s*(see more about|more for you|back to top)\b.*$/gim, "").replace(/\n{3,}/g, "\n\n");
|
|
4675
|
+
}
|
|
4676
|
+
var REF_HEAD = /^(#{1,6})\s*\**\s*(references|bibliography|literature cited|reference list|works cited|cited literature)\b[^\n]*$|^\**(references|bibliography|literature cited)\**:?[ \t]*$/gim;
|
|
4677
|
+
function dropReferences(md) {
|
|
4678
|
+
let out = md;
|
|
4679
|
+
for (; ; ) {
|
|
4680
|
+
REF_HEAD.lastIndex = 0;
|
|
4681
|
+
const m = REF_HEAD.exec(out);
|
|
4682
|
+
if (!m) return out;
|
|
4683
|
+
const level = m[1]?.length ?? 6;
|
|
4684
|
+
const rest = out.slice(m.index + m[0].length);
|
|
4685
|
+
const next = new RegExp(`^#{1,${level}}\\s`, "m").exec(rest);
|
|
4686
|
+
out = out.slice(0, m.index) + (next ? rest.slice(next.index) : "");
|
|
4687
|
+
}
|
|
4688
|
+
}
|
|
4689
|
+
function paperYearOnly(md) {
|
|
4690
|
+
return md.replace(/^(#[^\n]*\n\n)([^\n]*· (?:PMID \d+|DOI 10\.)[^\n]*)$/m, (_, title, line) => {
|
|
4691
|
+
const year = / · (\d{4})(?: · |$)/.exec(line)?.[1];
|
|
4692
|
+
return year ? `${title}${year}` : title.trimEnd();
|
|
4693
|
+
});
|
|
4694
|
+
}
|
|
4695
|
+
function windows(md, max) {
|
|
4696
|
+
const out = [];
|
|
4697
|
+
let cur = "";
|
|
4698
|
+
for (const s of cleanMarkdown(md).split(/\n(?=#)/)) {
|
|
4699
|
+
if (cur && cur.length + s.length + 1 > max) {
|
|
4700
|
+
out.push(cur);
|
|
4701
|
+
cur = "";
|
|
4702
|
+
}
|
|
4703
|
+
cur += (cur ? "\n" : "") + s.slice(0, max);
|
|
4704
|
+
}
|
|
4705
|
+
if (cur) out.push(cur);
|
|
4706
|
+
return out.length ? out : [""];
|
|
4707
|
+
}
|
|
4708
|
+
var MONTH = /^(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|June?|July?|Aug(ust)?|Sep(t(ember)?)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\.?$/;
|
|
4709
|
+
var namesAuthor = (group) => (group.match(/\b[A-Z][\p{L}'’-]+/gu) ?? []).some((w) => !MONTH.test(w));
|
|
4710
|
+
function citationGroups(claim) {
|
|
4711
|
+
const one = /[(\[][^()\[\]]*?\b(1[89]\d\d|20\d\d)[a-z]?\b[^()\[\]]*[)\]]/g;
|
|
4712
|
+
const groups = [];
|
|
4713
|
+
let last = -1;
|
|
4714
|
+
for (const m of claim.matchAll(one)) {
|
|
4715
|
+
if (!namesAuthor(m[0])) continue;
|
|
4716
|
+
const between = claim.slice(last, m.index);
|
|
4717
|
+
if (last >= 0 && /^[\s;,]*(and|&)?[\s;,]*$/i.test(between)) {
|
|
4718
|
+
groups[groups.length - 1] += between + m[0];
|
|
4719
|
+
} else groups.push(m[0]);
|
|
4720
|
+
last = m.index + m[0].length;
|
|
4721
|
+
}
|
|
4722
|
+
return groups;
|
|
4723
|
+
}
|
|
4724
|
+
function fragment(claim) {
|
|
4725
|
+
const body = claim.trim().replace(/^[-*+]\s+/, "").replace(/^\*\*[^*]+:\*\*\s*/, "").replace(/^[("'\u201c]+/, "");
|
|
4726
|
+
const first = /^(\S+)/.exec(body)?.[1] ?? "";
|
|
4727
|
+
const oddsRatio = first === "OR" && /^OR\s+(\d|=|\(|of\b|for\b)/.test(body);
|
|
4728
|
+
if (!oddsRatio && /^(and|or|but|nor|which|whereas|while)$/i.test(first.replace(/[,;:]$/, ""))) return `claim is a fragment: starts with "${first}" \u2014 send a complete statement with its subject`;
|
|
4729
|
+
return null;
|
|
4730
|
+
}
|
|
4731
|
+
var SUPERSEDED = "The corrected text replaces figures that the paper first published wrongly. Does the statement give a figure for a quantity the corrected text also gives, but with a different value \u2014 the superseded, uncorrected figure? If the statement's figures match the corrected text, or it concerns something the corrected text does not cover, answer false.";
|
|
4732
|
+
function correctedText(md) {
|
|
4733
|
+
const i = md.indexOf(`
|
|
4734
|
+
${CORRECTED_HEADING}
|
|
4735
|
+
`);
|
|
4736
|
+
if (i < 0) return null;
|
|
4737
|
+
return md.slice(i + CORRECTED_HEADING.length + 2).split("\n").filter((l) => l.trim() && !/^NLM corrected these sentences/.test(l)).join("\n").trim() || null;
|
|
4738
|
+
}
|
|
4739
|
+
async function readPaper(raw, libraryDir = FH_EVIDENCE_DIR) {
|
|
4740
|
+
const p = parseId(raw);
|
|
4741
|
+
if (p.error) return { id: p.requested, error: p.error };
|
|
4742
|
+
const paths = entryPaths(libraryDir, p.type, p.id);
|
|
4743
|
+
if (!entryExists(paths)) return { id: p.requested, error: "not in library" };
|
|
4744
|
+
const full = existsSync8(paths.fulltextMd);
|
|
4745
|
+
if (full) return { id: p.requested, basis: "full_text", text: readFileSync7(paths.fulltextMd, "utf8") };
|
|
4746
|
+
const meta = readMeta(paths);
|
|
4747
|
+
return { id: p.requested, basis: meta.has_abstract ? "abstract" : "title", text: readFileSync7(paths.md, "utf8") };
|
|
4748
|
+
}
|
|
4749
|
+
async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
|
|
4750
|
+
const out = { claim, id, verdict: "error", reason: null, score: null, basis: null, windows: 0, glyphs_unresolved: 0, superseded: null, model: cfg?.model ?? null };
|
|
4751
|
+
const words3 = claim.trim().split(/\s+/).filter(Boolean).length;
|
|
4752
|
+
if (!words3) return { ...out, error: "claim empty" };
|
|
4753
|
+
if (words3 < 3) return { ...out, error: "claim too short to be a finding" };
|
|
4754
|
+
const frag = fragment(claim);
|
|
4755
|
+
if (frag) return { ...out, error: frag };
|
|
4756
|
+
const groups = citationGroups(claim);
|
|
4757
|
+
if (groups.length) return { ...out, error: groups.length > 1 ? `compound claim: ${groups.length} citation groups ${groups.join(" ")} \u2014 one finding per call, without its sources` : `claim names a source ${groups[0]} \u2014 send the finding without its sources; the paper is the id` };
|
|
4758
|
+
const paper = await read2(id);
|
|
4759
|
+
out.id = paper.id;
|
|
4760
|
+
if ("error" in paper) return { ...out, error: paper.error };
|
|
4761
|
+
if (!cfg || !decide) return { ...out, error: "no verify model configured (FH_VERIFY_URL)" };
|
|
4762
|
+
out.basis = paper.basis;
|
|
4763
|
+
out.glyphs_unresolved = countUnresolved(paper.text);
|
|
4764
|
+
if (paper.basis === "title") return { ...out, verdict: "fail", reason: NOTHING_TO_VERIFY };
|
|
4765
|
+
const ws = windows(paper.text, cfg.window_chars);
|
|
4766
|
+
out.windows = ws.length;
|
|
4767
|
+
try {
|
|
4768
|
+
let score = 0;
|
|
4769
|
+
for (const w of ws) {
|
|
4770
|
+
const a = await decide({ paper: w, statement: claim }, { backed: { type: "noul", instructions: QUESTION } });
|
|
4771
|
+
score = Math.max(score, a.backed?.noul ?? 0);
|
|
4772
|
+
}
|
|
4773
|
+
out.score = score;
|
|
4774
|
+
const corrected = correctedText(paper.text);
|
|
4775
|
+
if (corrected) {
|
|
4776
|
+
const a = await decide({ corrected, statement: claim }, { superseded: { type: "noul", instructions: SUPERSEDED } });
|
|
4777
|
+
out.superseded = (a.superseded?.noul ?? 0) >= 0.5;
|
|
4778
|
+
}
|
|
4779
|
+
} catch (e) {
|
|
4780
|
+
return { ...out, error: e instanceof Error ? e.message : String(e) };
|
|
4781
|
+
}
|
|
4782
|
+
if (out.score >= cfg.threshold) return { ...out, verdict: "pass" };
|
|
4783
|
+
return paper.basis === "full_text" ? { ...out, verdict: "fail" } : { ...out, verdict: "unverifiable", reason: "only the abstract is stored and it does not state the claim; the full text may" };
|
|
4784
|
+
}
|
|
4785
|
+
|
|
4786
|
+
// src/verify/cache.ts
|
|
4399
4787
|
var sha = (s) => createHash3("sha1").update(s).digest("hex");
|
|
4400
4788
|
var normalizeClaim = (claim) => claim.replace(/\s+/g, " ").trim();
|
|
4401
4789
|
function foldClaim(claim) {
|
|
@@ -4407,7 +4795,7 @@ ${id}
|
|
|
4407
4795
|
${model}
|
|
4408
4796
|
${threshold}
|
|
4409
4797
|
${text4}`).slice(0, 16);
|
|
4410
|
-
var verdictFile = (libraryDir,
|
|
4798
|
+
var verdictFile = (libraryDir, key2) => join10(libraryDir, "verify", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
|
|
4411
4799
|
function readVerdict(file3) {
|
|
4412
4800
|
if (!existsSync9(file3)) return null;
|
|
4413
4801
|
try {
|
|
@@ -4524,7 +4912,7 @@ function normalizeQuery(q) {
|
|
|
4524
4912
|
return out;
|
|
4525
4913
|
}
|
|
4526
4914
|
var searchKey = (q) => createHash4("sha1").update(JSON.stringify(["clinicaltrials", q.query ?? "", q.intervention ?? "", q.condition ?? "", q.status, q.sort, q.max_results])).digest("hex").slice(0, 16);
|
|
4527
|
-
var searchFile = (libraryDir,
|
|
4915
|
+
var searchFile = (libraryDir, key2) => join11(libraryDir, "search", key2.slice(0, 2), key2.slice(0, 4), `${key2}.json`);
|
|
4528
4916
|
function searchUrl(q) {
|
|
4529
4917
|
const p = new URLSearchParams();
|
|
4530
4918
|
if (q.query) p.set("query.term", q.query);
|
|
@@ -4849,8 +5237,8 @@ function readMissing(p) {
|
|
|
4849
5237
|
const f = missingFile(p);
|
|
4850
5238
|
if (!existsSync12(f)) return null;
|
|
4851
5239
|
const md = readFileSync11(f, "utf8");
|
|
4852
|
-
const
|
|
4853
|
-
const checked =
|
|
5240
|
+
const get4 = (k) => /^$/.test(k) ? "" : (new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md)?.[1] ?? "").trim();
|
|
5241
|
+
const checked = get4("checked"), reason = get4("reason");
|
|
4854
5242
|
return checked ? { checked, reason: reason || "not found" } : null;
|
|
4855
5243
|
}
|
|
4856
5244
|
function freshMissing(p, retryDays) {
|
|
@@ -5147,11 +5535,11 @@ function registerTools(server2) {
|
|
|
5147
5535
|
);
|
|
5148
5536
|
const inflight2 = /* @__PURE__ */ new Map();
|
|
5149
5537
|
function addEntry(id) {
|
|
5150
|
-
const
|
|
5151
|
-
let p = inflight2.get(
|
|
5538
|
+
const key2 = parseId(id).requested;
|
|
5539
|
+
let p = inflight2.get(key2);
|
|
5152
5540
|
if (!p) {
|
|
5153
|
-
p = addEntryNow(id).finally(() => inflight2.delete(
|
|
5154
|
-
inflight2.set(
|
|
5541
|
+
p = addEntryNow(id).finally(() => inflight2.delete(key2));
|
|
5542
|
+
inflight2.set(key2, p);
|
|
5155
5543
|
}
|
|
5156
5544
|
return p;
|
|
5157
5545
|
}
|
|
@@ -5430,17 +5818,19 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5430
5818
|
const { cached, ...r } = await verifyCached(claim, id, cfg, cfg ? decider(cfg) : null, FH_EVIDENCE_DIR);
|
|
5431
5819
|
if (!r.error && r.score !== null) bump("verify", cached);
|
|
5432
5820
|
const secs = `${((Date.now() - t0) / 1e3).toFixed(1).padStart(4, "0")}s`;
|
|
5433
|
-
log("verify", r.id, r.error ? `${modelFailure(r.error, cfg) ? "!! " : ""}${secs} ${"error".padEnd(20)} ${r.error} | ${claim}` : `${secs} verdict=${r.verdict.padEnd(12)} basis=${r.basis.padEnd(9)} score=${r.score === null ? "- " : r.score.toFixed(3)}${r.windows > 1 ? ` windows=${r.windows}` : ""}${cached ? " cached" : ""}${r.superseded ? " superseded" : ""}${r.glyphs_unresolved ? ` glyphs=${r.glyphs_unresolved}` : ""} | ${claim}`);
|
|
5821
|
+
log("verify", r.id, r.error ? `${modelFailure(r.error, cfg) ? "!! " : ""}${secs} ${"error".padEnd(20)} ${r.error} | ${claim}` : `${secs} verdict=${r.verdict.padEnd(12)} basis=${r.basis.padEnd(9)} score=${r.score === null ? "- " : r.score.toFixed(3)}${cfg ? ` provider=${cfg.provider.name}` : ""}${r.windows > 1 ? ` windows=${r.windows}` : ""}${cached ? " cached" : ""}${r.superseded ? " superseded" : ""}${r.glyphs_unresolved ? ` glyphs=${r.glyphs_unresolved}` : ""} | ${claim}`);
|
|
5434
5822
|
return { content: [{ type: "text", text: verdictAnswer(r) }] };
|
|
5435
5823
|
}
|
|
5436
5824
|
);
|
|
5437
5825
|
server2.tool(
|
|
5438
5826
|
"fh_info",
|
|
5439
|
-
"The server and the whole library as JSON: this server's package name and version (which build is loaded), its log file; evidence directory (evidence_dir) and host; entry count and size on disk; per type (pmid, doi, dailymed, nct) the entries by level (full_text, abstract, title) and retractions; counts of retracted and not-citable entries and of errata, expressions of concern and updates; the retrieval sources in run order and which are off (tiers); the multi-stage download (download): the Playwright servers with the version they must run, the Chrome stages,
|
|
5827
|
+
"The server and the whole library as JSON: this server's package name and version (which build is loaded), its log file; evidence directory (evidence_dir) and host; entry count and size on disk; per type (pmid, doi, dailymed, nct) the entries by level (full_text, abstract, title) and retractions; counts of retracted and not-citable entries and of errata, expressions of concern and updates; the retrieval sources in run order and which are off (tiers); the multi-stage download (download): the Playwright servers with the version they must run, the Chrome stages, whether an unlocker is configured; the configuration and where each value came from \u2014 environment, .env or default, never the value (config); the decision model behind fh_verify_claim and whether it answers right now (verify); the unlockers and whether each answers right now (unlockers); our own stage hosts \u2014 fetch proxy, Playwright servers, Chrome \u2014 and whether each is reachable right now (stages); this server's cache hits and misses for fh_verify_claim and fh_fetch_url since it started (cache).",
|
|
5440
5828
|
{},
|
|
5441
5829
|
async () => {
|
|
5442
5830
|
const info = libraryInfo(FH_EVIDENCE_DIR, HOST);
|
|
5443
5831
|
const cfg = verifyConfig();
|
|
5832
|
+
const unlockerChecks = Promise.all(info.unlockers.map((u) => unlockerHealth(u.provider)));
|
|
5833
|
+
const stageChecks = Promise.all(info.stages.map((s2) => probe(s2.host, s2.port)));
|
|
5444
5834
|
if (info.verify && cfg) {
|
|
5445
5835
|
const t0 = Date.now();
|
|
5446
5836
|
try {
|
|
@@ -5450,7 +5840,9 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5450
5840
|
info.verify = { ...info.verify, ok: false, ms: Date.now() - t0, error: e instanceof Error ? e.message : String(e) };
|
|
5451
5841
|
}
|
|
5452
5842
|
}
|
|
5453
|
-
|
|
5843
|
+
info.unlockers = (await unlockerChecks).map((h, i) => ({ ...info.unlockers[i], ...h }));
|
|
5844
|
+
info.stages = (await stageChecks).map((h, i) => ({ ...info.stages[i], up: h.up, ms: h.ms, error: h.error }));
|
|
5845
|
+
log("info", null, `entries=${info.entries}${info.verify ? ` verify ${info.verify.model} ${info.verify.ok ? `ok ${info.verify.ms} ms` : `down: ${info.verify.error}`}` : " verify not configured"}${info.unlockers.map((u) => ` unlocker ${u.provider} ${u.ok ? `ok ${u.ms} ms` : `down: ${u.error}`}`).join("")}${info.stages.map((s2) => ` stage ${s2.name} ${s2.up ? `up ${s2.ms} ms` : `down: ${s2.error}`}`).join("")}`);
|
|
5454
5846
|
const s = currentStats();
|
|
5455
5847
|
const cache = s ? { since: s.started, verify: s.verify, fetch: s.fetch, search: s.search, pubmed: s.pubmed } : null;
|
|
5456
5848
|
return { content: [{ type: "text", text: compact2({ package: pkg.name, version: pkg.version, log: LOG_FILE, ...info, cache }) }] };
|
|
@@ -5458,7 +5850,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5458
5850
|
);
|
|
5459
5851
|
server2.tool(
|
|
5460
5852
|
"fh_fetch_url",
|
|
5461
|
-
`Fetch a web page as Markdown: the standard fetch tool, cached and hardened. Use it for any URL instead of a plain fetch or a browser. A page fetched in the last ${settings().refresh_after_days} days is answered from disk in milliseconds; a page a plain fetch cannot get (403, rate limit, bot wall, script-rendered) is fetched through the configured browsers and
|
|
5853
|
+
`Fetch a web page as Markdown: the standard fetch tool, cached and hardened. Use it for any URL instead of a plain fetch or a browser. A page fetched in the last ${settings().refresh_after_days} days is answered from disk in milliseconds; a page a plain fetch cannot get (403, rate limit, bot wall, script-rendered) is fetched through the configured browsers and unlockers in this one call. PDFs come back as Markdown. To verify a link, title_only returns just its title line. A PubMed, ClinicalTrials.gov, DailyMed or doi.org URL is answered from the library's record of it.`,
|
|
5462
5854
|
{
|
|
5463
5855
|
url: z.string().describe("URL to fetch"),
|
|
5464
5856
|
// Optional, not .default(5000): the log tells a model that set none from one that asked for 5000.
|
|
@@ -5640,6 +6032,7 @@ registerTools(server);
|
|
|
5640
6032
|
startStats(pkg);
|
|
5641
6033
|
migrateLogName();
|
|
5642
6034
|
log("startup", null, `${pkg.name} ${pkg.version}`);
|
|
5643
|
-
|
|
6035
|
+
process.on("exit", abandonAll);
|
|
6036
|
+
for (const problem of [...resolveTiers().problems, ...verifyProblems()]) log("startup", null, `!! ${problem}`);
|
|
5644
6037
|
var transport = new StdioServerTransport();
|
|
5645
6038
|
await server.connect(transport);
|