evidence-mcp-dev 0.2.42 → 0.2.44
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 +523 -274
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -164,9 +164,9 @@ async function cdpUrl(endpoint) {
|
|
|
164
164
|
}
|
|
165
165
|
return u.toString().replace(/\/$/, "");
|
|
166
166
|
}
|
|
167
|
-
var
|
|
168
|
-
var
|
|
169
|
-
var
|
|
167
|
+
var stageKind = (endpoint) => isCdp(endpoint) ? "chrome" : "playwright";
|
|
168
|
+
var stageName = (b) => `${b.kind} ${b.label}`;
|
|
169
|
+
var STAGE_PREFIX = /^(?:playwright|chrome|browser|fetch-proxy) [^:]+: /;
|
|
170
170
|
var hostOf = (endpoint) => {
|
|
171
171
|
try {
|
|
172
172
|
return new URL(isCdp(endpoint) ? cdpHttp(endpoint) : endpoint);
|
|
@@ -183,10 +183,10 @@ function browserHeadless(endpoint, cfg = browserConfig()) {
|
|
|
183
183
|
if (isCdp(endpoint)) return false;
|
|
184
184
|
return cfg.headless === "auto" ? false : cfg.headless;
|
|
185
185
|
}
|
|
186
|
-
function
|
|
186
|
+
function browserStages(cfg = browserConfig()) {
|
|
187
187
|
return cfg.browsers.map((endpoint) => {
|
|
188
188
|
const u = hostOf(endpoint);
|
|
189
|
-
return { kind:
|
|
189
|
+
return { kind: stageKind(endpoint), host: u?.hostname ?? endpoint, port: Number(u?.port) || (isCdp(endpoint) ? CHROME_PORT : PLAYWRIGHT_PORT), label: browserLabel(endpoint), endpoint, headless: browserHeadless(endpoint, cfg) };
|
|
190
190
|
});
|
|
191
191
|
}
|
|
192
192
|
var CHALLENGE = /just a moment|nur einen moment|attention required|verify you are human|human verification|checking your browser|access denied/i;
|
|
@@ -233,7 +233,7 @@ async function context(endpoint, cfg) {
|
|
|
233
233
|
const ctx = await browser.newContext({ ...CONTEXT_OPTS, ...existsSync3(state) ? { storageState: state } : {} });
|
|
234
234
|
return { ctx, browser };
|
|
235
235
|
}
|
|
236
|
-
throw new Error(`not a browser
|
|
236
|
+
throw new Error(`not a browser stage: ${endpoint}`);
|
|
237
237
|
})();
|
|
238
238
|
ctxs.set(endpoint, p);
|
|
239
239
|
p.catch(() => {
|
|
@@ -739,7 +739,7 @@ function renderCitation(nodes2) {
|
|
|
739
739
|
const el = nodes2.find((x) => ["element-citation", "mixed-citation", "citation", "nlm-citation"].includes(tagOf(x)));
|
|
740
740
|
if (!el) return squash(inlineText(nodes2));
|
|
741
741
|
const f = kids(el);
|
|
742
|
-
const
|
|
742
|
+
const get4 = (tag) => f.filter((x) => tagOf(x) === tag).map((x) => squash(inlineText(kids(x))));
|
|
743
743
|
const names2 = f.filter((x) => tagOf(x) === "person-group").flatMap((g) => kids(g)).map((x) => {
|
|
744
744
|
const t = tagOf(x);
|
|
745
745
|
if (t === "etal") return "et al";
|
|
@@ -751,11 +751,11 @@ function renderCitation(nodes2) {
|
|
|
751
751
|
}
|
|
752
752
|
return "";
|
|
753
753
|
}).filter(Boolean);
|
|
754
|
-
const vol =
|
|
755
|
-
const pages = fp ? lp ? `${fp}-${lp}` : fp :
|
|
756
|
-
const where = [
|
|
754
|
+
const vol = get4("volume")[0], issue = get4("issue")[0], fp = get4("fpage")[0], lp = get4("lpage")[0];
|
|
755
|
+
const pages = fp ? lp ? `${fp}-${lp}` : fp : get4("elocation-id")[0];
|
|
756
|
+
const where = [get4("source")[0], get4("year")[0] ? `${get4("year")[0]};` : "", vol ? `${vol}${issue ? `(${issue})` : ""}` : "", pages ? `:${pages}` : ""].filter(Boolean).join("").replace(/;$/, "");
|
|
757
757
|
const ids = f.filter((x) => tagOf(x) === "pub-id").map((x) => `${attr(x, "pub-id-type")}:${squash(plainText(kids(x)))}`);
|
|
758
|
-
return [names2.join(", "), [...
|
|
758
|
+
return [names2.join(", "), [...get4("article-title"), ...get4("chapter-title")][0], where, ...ids].filter(Boolean).join(". ").replace(/\.\./g, ".");
|
|
759
759
|
}
|
|
760
760
|
var FN_LABELS = {
|
|
761
761
|
"conflict": "Conflicts of interest",
|
|
@@ -1214,12 +1214,12 @@ var UNRESOLVED_GLYPH = /[\u0001-\u0008\u000b\u000c\u000e-\u001f]/g;
|
|
|
1214
1214
|
var countUnresolved = (text4) => (text4.match(UNRESOLVED_GLYPH) ?? []).length;
|
|
1215
1215
|
var looksLikePdf = (bytes) => bytes.subarray(0, 5).toString("latin1") === "%PDF-";
|
|
1216
1216
|
|
|
1217
|
-
// src/unlock.ts
|
|
1217
|
+
// src/unlock/brightdata.ts
|
|
1218
1218
|
import { request as httpsRequest } from "https";
|
|
1219
1219
|
var ENDPOINT = "https://api.brightdata.com/request";
|
|
1220
1220
|
var TIMEOUT_MS2 = 6e4;
|
|
1221
1221
|
function post(url, init) {
|
|
1222
|
-
return new Promise((
|
|
1222
|
+
return new Promise((resolve5, reject) => {
|
|
1223
1223
|
const req = httpsRequest(url, { method: "POST", headers: { ...init.headers, "Content-Length": String(Buffer.byteLength(init.body)) }, signal: init.signal }, (res) => {
|
|
1224
1224
|
const chunks = [];
|
|
1225
1225
|
res.on("data", (c) => chunks.push(c));
|
|
@@ -1227,7 +1227,7 @@ function post(url, init) {
|
|
|
1227
1227
|
res.on("end", () => {
|
|
1228
1228
|
const body = Buffer.concat(chunks);
|
|
1229
1229
|
const status = res.statusCode ?? 0;
|
|
1230
|
-
|
|
1230
|
+
resolve5({
|
|
1231
1231
|
ok: status >= 200 && status < 300,
|
|
1232
1232
|
status,
|
|
1233
1233
|
headers: { get: (name) => {
|
|
@@ -1242,10 +1242,10 @@ function post(url, init) {
|
|
|
1242
1242
|
req.end(init.body);
|
|
1243
1243
|
});
|
|
1244
1244
|
}
|
|
1245
|
-
var
|
|
1246
|
-
async function
|
|
1247
|
-
const token =
|
|
1248
|
-
if (!token) throw new Error("
|
|
1245
|
+
var apiKey = () => process.env.FH_BRIGHTDATA_API_KEY?.trim() || "";
|
|
1246
|
+
async function get(url, postImpl = post) {
|
|
1247
|
+
const token = apiKey();
|
|
1248
|
+
if (!token) throw new Error("not configured");
|
|
1249
1249
|
const zone = process.env.FH_BRIGHTDATA_ZONE?.trim() || "mcp_unlocker";
|
|
1250
1250
|
const res = await postImpl(ENDPOINT, {
|
|
1251
1251
|
method: "POST",
|
|
@@ -1253,12 +1253,95 @@ async function unlock(url, postImpl = post) {
|
|
|
1253
1253
|
body: JSON.stringify({ zone, url, format: "raw" }),
|
|
1254
1254
|
signal: AbortSignal.timeout(TIMEOUT_MS2)
|
|
1255
1255
|
});
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
}
|
|
1256
|
+
const why = res.headers.get("x-brd-err-msg") ?? res.headers.get("x-brd-error");
|
|
1257
|
+
if (!res.ok) throw new Error(`unlocker HTTP ${res.status}${why ? `: ${why}` : ""}`);
|
|
1258
|
+
if (res.headers.get("x-brd-error")) throw new Error(`unlocker refused: ${why}`);
|
|
1260
1259
|
return { bytes: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") ?? "" };
|
|
1261
1260
|
}
|
|
1261
|
+
var brightdata = { name: "brightdata", keyVar: "FH_BRIGHTDATA_API_KEY", get: (url) => get(url) };
|
|
1262
|
+
|
|
1263
|
+
// src/unlock/zenrows.ts
|
|
1264
|
+
var TIMEOUT_MS3 = 6e4;
|
|
1265
|
+
var ACCOUNT = /* @__PURE__ */ new Set([401, 402, 403, 429]);
|
|
1266
|
+
async function get2(url, fetchImpl = fetch) {
|
|
1267
|
+
const key = process.env.FH_ZENROWS_API_KEY?.trim();
|
|
1268
|
+
if (!key) throw new Error("not configured");
|
|
1269
|
+
const r = await fetchImpl(`https://api.zenrows.com/v1/?apikey=${encodeURIComponent(key)}&url=${encodeURIComponent(url)}&mode=auto`, { signal: AbortSignal.timeout(TIMEOUT_MS3) });
|
|
1270
|
+
const bytes = Buffer.from(await r.arrayBuffer());
|
|
1271
|
+
if (!r.ok) {
|
|
1272
|
+
let why = "";
|
|
1273
|
+
try {
|
|
1274
|
+
const j = JSON.parse(bytes.toString("utf8"));
|
|
1275
|
+
why = j.title || j.detail || j.code || "";
|
|
1276
|
+
} catch {
|
|
1277
|
+
why = bytes.toString("utf8").slice(0, 120).trim();
|
|
1278
|
+
}
|
|
1279
|
+
throw new Error(ACCOUNT.has(r.status) ? `unlocker HTTP ${r.status}${why ? `: ${why}` : ""}` : `HTTP ${r.status}${why ? ` ${why}` : ""}`);
|
|
1280
|
+
}
|
|
1281
|
+
return { bytes, contentType: r.headers.get("content-type") ?? "" };
|
|
1282
|
+
}
|
|
1283
|
+
var zenrows = { name: "zenrows", keyVar: "FH_ZENROWS_API_KEY", get: (url) => get2(url) };
|
|
1284
|
+
|
|
1285
|
+
// src/unlock/zyte.ts
|
|
1286
|
+
var TIMEOUT_MS4 = 6e4;
|
|
1287
|
+
var ACCOUNT2 = /* @__PURE__ */ new Set([401, 402, 403, 429]);
|
|
1288
|
+
async function get3(url, fetchImpl = fetch) {
|
|
1289
|
+
const key = process.env.FH_ZYTE_API_KEY?.trim();
|
|
1290
|
+
if (!key) throw new Error("not configured");
|
|
1291
|
+
const r = await fetchImpl("https://api.zyte.com/v1/extract", {
|
|
1292
|
+
method: "POST",
|
|
1293
|
+
signal: AbortSignal.timeout(TIMEOUT_MS4),
|
|
1294
|
+
headers: { authorization: `Basic ${Buffer.from(`${key}:`).toString("base64")}`, "content-type": "application/json" },
|
|
1295
|
+
body: JSON.stringify({ url, httpResponseBody: true, httpResponseHeaders: true })
|
|
1296
|
+
});
|
|
1297
|
+
const j = await r.json().catch(() => ({}));
|
|
1298
|
+
if (!r.ok) {
|
|
1299
|
+
const why = j.title || j.detail || "";
|
|
1300
|
+
throw new Error(ACCOUNT2.has(r.status) ? `unlocker HTTP ${r.status}${why ? `: ${why}` : ""}` : `HTTP ${r.status}${why ? ` ${why}` : ""}`);
|
|
1301
|
+
}
|
|
1302
|
+
if (j.statusCode && j.statusCode >= 400) throw new Error(`HTTP ${j.statusCode}`);
|
|
1303
|
+
const contentType = j.httpResponseHeaders?.find((h) => h.name.toLowerCase() === "content-type")?.value ?? "";
|
|
1304
|
+
return { bytes: Buffer.from(j.httpResponseBody ?? "", "base64"), contentType };
|
|
1305
|
+
}
|
|
1306
|
+
var zyte = { name: "zyte", keyVar: "FH_ZYTE_API_KEY", get: (url) => get3(url) };
|
|
1307
|
+
|
|
1308
|
+
// src/unlock.ts
|
|
1309
|
+
var SERVICES = [zenrows, zyte, brightdata];
|
|
1310
|
+
var UNLOCKER_NAMES = SERVICES.map((s) => s.name);
|
|
1311
|
+
var UNLOCKER_PREFIX = new RegExp(`^(${UNLOCKER_NAMES.join("|")}): `);
|
|
1312
|
+
var accountProblem = (reason) => /^unlocker (HTTP 4\d\d|refused)/.test(reason);
|
|
1313
|
+
var keyed = (s, env) => !!env[s.keyVar]?.trim();
|
|
1314
|
+
function resolve3(env) {
|
|
1315
|
+
const listed = (env.FH_UNLOCKERS ?? "").split(",").map((n) => n.trim().toLowerCase()).filter(Boolean);
|
|
1316
|
+
if (!listed.length) return { order: SERVICES.filter((s) => keyed(s, env)).map((s) => s.name), problems: [] };
|
|
1317
|
+
const problems = [], order2 = [];
|
|
1318
|
+
for (const n of listed) {
|
|
1319
|
+
const s = SERVICES.find((x) => x.name === n);
|
|
1320
|
+
if (!s) problems.push(`FH_UNLOCKERS: unknown unlocker "${n}" (built-in: ${UNLOCKER_NAMES.join(", ")})`);
|
|
1321
|
+
else if (!keyed(s, env)) problems.push(`FH_UNLOCKERS: "${n}" listed, but ${s.keyVar} is unset`);
|
|
1322
|
+
else if (!order2.includes(n)) order2.push(n);
|
|
1323
|
+
}
|
|
1324
|
+
return { order: order2, problems };
|
|
1325
|
+
}
|
|
1326
|
+
var unlockers = (env = process.env) => resolve3(env).order;
|
|
1327
|
+
var unlockerProblems = (env = process.env) => resolve3(env).problems;
|
|
1328
|
+
var unlockerConfigured = () => unlockers().length > 0;
|
|
1329
|
+
async function unlock(url, name) {
|
|
1330
|
+
const s = SERVICES.find((x) => x.name === name);
|
|
1331
|
+
if (!s) throw new Error(`unknown unlocker ${name}`);
|
|
1332
|
+
return s.get(url);
|
|
1333
|
+
}
|
|
1334
|
+
var HEALTH_URL = "https://example.com/";
|
|
1335
|
+
async function unlockerHealth(name, unlockImpl = unlock) {
|
|
1336
|
+
const t0 = Date.now();
|
|
1337
|
+
try {
|
|
1338
|
+
const u = await unlockImpl(HEALTH_URL, name);
|
|
1339
|
+
const ok = /Example Domain/.test(u.bytes.toString("utf8"));
|
|
1340
|
+
return { ok, ms: Date.now() - t0, error: ok ? null : u.bytes.length ? `unexpected answer (${u.bytes.length} bytes)` : "empty answer" };
|
|
1341
|
+
} catch (e) {
|
|
1342
|
+
return { ok: false, ms: Date.now() - t0, error: e instanceof Error ? e.message : String(e) };
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1262
1345
|
|
|
1263
1346
|
// src/walls.ts
|
|
1264
1347
|
import { mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "fs";
|
|
@@ -2379,7 +2462,7 @@ var host = (url) => {
|
|
|
2379
2462
|
}
|
|
2380
2463
|
};
|
|
2381
2464
|
var file = (dir, h) => join5(dir, "walls", `${h.replace(/[^a-z0-9.-]/g, "_")}.json`);
|
|
2382
|
-
var legacy = (
|
|
2465
|
+
var legacy = (stage2) => stage2.replace(/^(playwright|chrome) /, "browser ");
|
|
2383
2466
|
function read(dir, h) {
|
|
2384
2467
|
try {
|
|
2385
2468
|
return JSON.parse(readFileSync3(file(dir, h), "utf8"));
|
|
@@ -2387,28 +2470,28 @@ function read(dir, h) {
|
|
|
2387
2470
|
return {};
|
|
2388
2471
|
}
|
|
2389
2472
|
}
|
|
2390
|
-
function walled(url,
|
|
2473
|
+
function walled(url, stage2, dir = FH_EVIDENCE_DIR) {
|
|
2391
2474
|
const h = host(url);
|
|
2392
2475
|
if (!h) return null;
|
|
2393
2476
|
const all = read(dir, h);
|
|
2394
|
-
const r = all[
|
|
2477
|
+
const r = all[stage2] ?? all[legacy(stage2)];
|
|
2395
2478
|
return r && r.streak >= WALL_STREAK && daysSince(r.date) < settings().retry_after_days ? r : null;
|
|
2396
2479
|
}
|
|
2397
|
-
function
|
|
2480
|
+
function recordStage(url, stage2, ok, reason = "", dir = FH_EVIDENCE_DIR) {
|
|
2398
2481
|
const h = host(url);
|
|
2399
2482
|
if (!h) return;
|
|
2400
|
-
const why = reason.replace(/^((?:playwright|chrome|browser|fetch-proxy) [^:]+|brightdata): /, "");
|
|
2483
|
+
const why = reason.replace(/^((?:playwright|chrome|browser|fetch-proxy) [^:]+|brightdata|zenrows|zyte): /, "");
|
|
2401
2484
|
if (!ok && !WALL2.test(why)) return;
|
|
2402
2485
|
const all = read(dir, h);
|
|
2403
|
-
const lk = legacy(
|
|
2404
|
-
if (lk !==
|
|
2405
|
-
all[
|
|
2486
|
+
const lk = legacy(stage2);
|
|
2487
|
+
if (lk !== stage2 && all[lk]) {
|
|
2488
|
+
all[stage2] ??= all[lk];
|
|
2406
2489
|
delete all[lk];
|
|
2407
2490
|
}
|
|
2408
2491
|
if (ok) {
|
|
2409
|
-
if (!all[
|
|
2410
|
-
delete all[
|
|
2411
|
-
} else all[
|
|
2492
|
+
if (!all[stage2]) return;
|
|
2493
|
+
delete all[stage2];
|
|
2494
|
+
} else all[stage2] = { streak: (all[stage2]?.streak ?? 0) + 1, date: now(), reason: why };
|
|
2412
2495
|
try {
|
|
2413
2496
|
mkdirSync3(join5(dir, "walls"), { recursive: true });
|
|
2414
2497
|
writeAtomic(file(dir, h), JSON.stringify(all) + "\n");
|
|
@@ -2469,35 +2552,40 @@ async function download(tier, p, candidates, ctx) {
|
|
|
2469
2552
|
if (w) ctx.onTry?.(`${target.url} skipped ${name}: ${wallNote(w)}`);
|
|
2470
2553
|
else {
|
|
2471
2554
|
r = note(await tryOne(p, target, tier, { proxy: f.proxy, label: f.label }));
|
|
2472
|
-
|
|
2555
|
+
recordStage(target.url, name, r.ok, r.ok ? "" : r.reason);
|
|
2473
2556
|
ctx.onTry?.(r.ok ? `${target.url} ok ${name}` : `${target.url} failed ${name}: ${bare(r.reason)}`);
|
|
2474
2557
|
}
|
|
2475
2558
|
}
|
|
2476
2559
|
const UNLOCK = /^(HTTP 403|wall page)/;
|
|
2477
2560
|
let browsed = false;
|
|
2478
|
-
for (const b of
|
|
2561
|
+
for (const b of browserStages()) {
|
|
2479
2562
|
if (r.ok) break;
|
|
2480
2563
|
const climbs = browsed ? climbsOn(r.reason, true) : climbsOn(plainReason) || climbsOn(bare(r.reason));
|
|
2481
2564
|
if (c.headers || c.service || !climbs) break;
|
|
2482
2565
|
browsed = true;
|
|
2483
|
-
const name =
|
|
2566
|
+
const name = stageName(b);
|
|
2484
2567
|
const w = walled(target.url, name);
|
|
2485
2568
|
if (w) {
|
|
2486
2569
|
ctx.onTry?.(`${target.url} skipped ${name}: ${wallNote(w)}`);
|
|
2487
2570
|
continue;
|
|
2488
2571
|
}
|
|
2489
2572
|
r = note(await tryOne(p, target, tier, { browser: b.endpoint, label: b.label }));
|
|
2490
|
-
|
|
2573
|
+
recordStage(target.url, name, r.ok, r.ok ? "" : r.reason);
|
|
2491
2574
|
ctx.onTry?.(r.ok ? `${target.url} ok ${name}` : `${target.url} failed ${name}: ${bare(r.reason)}`);
|
|
2492
2575
|
if (!r.ok && bare(r.reason).startsWith(MISMATCH)) ctx.onAlert?.(`${name}: ${bare(r.reason)}`);
|
|
2493
2576
|
}
|
|
2494
|
-
const
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2577
|
+
const unlockable = !r.ok && !c.headers && !c.service && (browsed ? /^(HTTP 403|wall page|playwright |chrome |browser )/.test(why(r.reason)) : UNLOCK.test(plainReason) || UNLOCK.test(why(bare(r.reason))));
|
|
2578
|
+
for (const u of unlockable ? unlockers() : []) {
|
|
2579
|
+
const uw = walled(target.url, u);
|
|
2580
|
+
if (uw) {
|
|
2581
|
+
ctx.onTry?.(`${target.url} skipped ${u}: ${wallNote(uw)}`);
|
|
2582
|
+
continue;
|
|
2583
|
+
}
|
|
2584
|
+
r = note(await tryOne(p, target, tier, { unlocker: u }));
|
|
2585
|
+
recordStage(target.url, u, r.ok, r.ok ? "" : r.reason);
|
|
2586
|
+
ctx.onTry?.(r.ok ? `${target.url} ok ${u}` : `${target.url} failed ${u}: ${bare(r.reason)}`);
|
|
2587
|
+
if (!r.ok && accountProblem(bare(r.reason))) ctx.onAlert?.(`${u}: ${bare(r.reason)}`);
|
|
2588
|
+
if (r.ok) break;
|
|
2501
2589
|
}
|
|
2502
2590
|
if (r.ok) return r;
|
|
2503
2591
|
reasons.push(`${gone ?? r.reason}: ${hostOf2(c.url)}`);
|
|
@@ -2513,12 +2601,12 @@ function climbsOn(reason, afterBrowser = false) {
|
|
|
2513
2601
|
const r = reason.replace(/^not a pdf \((.*)\)$/, "$1");
|
|
2514
2602
|
return CLIMB.test(r) || afterBrowser && /^(playwright|chrome|browser) /.test(r);
|
|
2515
2603
|
}
|
|
2516
|
-
var viaPrefix = (via) => via === "plain" ? "" :
|
|
2517
|
-
var bare = (reason) => reason.replace(
|
|
2604
|
+
var viaPrefix = (via) => via === "plain" ? "" : "unlocker" in via ? `${via.unlocker}: ` : "proxy" in via ? `${fetchProxyName(via)}: ` : `${stageName({ kind: stageKind(via.browser), label: via.label })}: `;
|
|
2605
|
+
var bare = (reason) => reason.replace(UNLOCKER_PREFIX, "").replace(STAGE_PREFIX, "");
|
|
2518
2606
|
async function tryOne(p, c, tier, via = "plain") {
|
|
2519
2607
|
let got;
|
|
2520
2608
|
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 ?? {} });
|
|
2609
|
+
got = typeof via === "object" && "unlocker" in via ? await unlock(c.url, via.unlocker) : 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 ?? {} });
|
|
2522
2610
|
} catch (e) {
|
|
2523
2611
|
const body = e?.body;
|
|
2524
2612
|
if (c.service && body?.trim()) return { ok: false, reason: `${errMsg(e)} \u2014 ${serviceMessage(Buffer.from(body), e.contentType)}`, url: e?.url };
|
|
@@ -2526,7 +2614,7 @@ async function tryOne(p, c, tier, via = "plain") {
|
|
|
2526
2614
|
}
|
|
2527
2615
|
const { bytes, contentType } = got;
|
|
2528
2616
|
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:
|
|
2617
|
+
if (typeof via === "object" && "unlocker" in via && !bytes.length) return { ok: false, reason: `${via.unlocker}: empty response` };
|
|
2530
2618
|
const r = await convertBytes(p, bytes, contentType);
|
|
2531
2619
|
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
2620
|
return { ok: true, tier, format: r.format, raw: r.format === "pdf" ? bytes : bytes.toString("utf8"), md: r.md, version: c.version };
|
|
@@ -2643,7 +2731,7 @@ function elsevierToJats(xml) {
|
|
|
2643
2731
|
var WINDOW_MS = 6e4;
|
|
2644
2732
|
var PER_WINDOW = 10;
|
|
2645
2733
|
var MAX_WAIT_MS = 65e3;
|
|
2646
|
-
var
|
|
2734
|
+
var TIMEOUT_MS5 = 1e4;
|
|
2647
2735
|
var calls = [];
|
|
2648
2736
|
async function pace() {
|
|
2649
2737
|
const now2 = Date.now();
|
|
@@ -2655,7 +2743,7 @@ async function coreFetch(url, key) {
|
|
|
2655
2743
|
const headers = { "User-Agent": LIBRARY_UA, Authorization: `Bearer ${key}` };
|
|
2656
2744
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
2657
2745
|
await pace();
|
|
2658
|
-
const res = await fetch(url, { headers, signal: AbortSignal.timeout(
|
|
2746
|
+
const res = await fetch(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS5), redirect: "follow" });
|
|
2659
2747
|
if (res.ok) return await res.text();
|
|
2660
2748
|
const body = await res.text().catch(() => "");
|
|
2661
2749
|
if (res.status === 429 && attempt === 0) {
|
|
@@ -2668,8 +2756,8 @@ async function coreFetch(url, key) {
|
|
|
2668
2756
|
}
|
|
2669
2757
|
throw new Error("HTTP 429");
|
|
2670
2758
|
}
|
|
2671
|
-
function coreTier(
|
|
2672
|
-
const key =
|
|
2759
|
+
function coreTier(apiKey2) {
|
|
2760
|
+
const key = apiKey2?.trim();
|
|
2673
2761
|
return {
|
|
2674
2762
|
name: "core",
|
|
2675
2763
|
applies: (p) => p.doi ? true : "no doi",
|
|
@@ -2950,9 +3038,19 @@ var VARIABLES = [
|
|
|
2950
3038
|
"FH_PLAYWRIGHT_2",
|
|
2951
3039
|
"FH_CHROME_1",
|
|
2952
3040
|
"FH_PLAYWRIGHT_HEADLESS",
|
|
3041
|
+
"FH_VERIFY_PROVIDER",
|
|
3042
|
+
"FH_VERIFY_PERPLEXITY_MODEL",
|
|
3043
|
+
"FH_VERIFY_PERPLEXITY_URL",
|
|
3044
|
+
"FH_VERIFY_PERPLEXITY_API_KEY",
|
|
3045
|
+
"FH_VERIFY_GOOGLE_MODEL",
|
|
3046
|
+
"FH_VERIFY_GOOGLE_URL",
|
|
3047
|
+
"FH_VERIFY_GOOGLE_API_KEY",
|
|
3048
|
+
"FH_VERIFY_OPENAI_MODEL",
|
|
3049
|
+
"FH_VERIFY_OPENAI_URL",
|
|
3050
|
+
"FH_VERIFY_OPENAI_API_KEY",
|
|
3051
|
+
"FH_VERIFY_MODEL",
|
|
2953
3052
|
"FH_VERIFY_URL",
|
|
2954
3053
|
"FH_VERIFY_API_KEY",
|
|
2955
|
-
"FH_VERIFY_MODEL",
|
|
2956
3054
|
"FH_VERIFY_THRESHOLD",
|
|
2957
3055
|
"FH_VERIFY_TIMEOUT_SECS",
|
|
2958
3056
|
"FH_RETRY_AFTER_DAYS",
|
|
@@ -2960,7 +3058,10 @@ var VARIABLES = [
|
|
|
2960
3058
|
"FH_REFRESH_AFTER_DAYS",
|
|
2961
3059
|
"FH_SEARCH_CACHE_DAYS",
|
|
2962
3060
|
"FH_NCBI_API_KEY",
|
|
2963
|
-
"
|
|
3061
|
+
"FH_UNLOCKERS",
|
|
3062
|
+
"FH_ZENROWS_API_KEY",
|
|
3063
|
+
"FH_ZYTE_API_KEY",
|
|
3064
|
+
"FH_BRIGHTDATA_API_KEY",
|
|
2964
3065
|
"FH_BRIGHTDATA_ZONE"
|
|
2965
3066
|
];
|
|
2966
3067
|
var sources = (env = process.env) => Object.fromEntries(VARIABLES.map((v) => [v, sourceOf(v, env)]));
|
|
@@ -3004,6 +3105,158 @@ function resolveTiers(env = process.env) {
|
|
|
3004
3105
|
return { tiers, all, source: sourceOf("FH_TIERS", env), problems };
|
|
3005
3106
|
}
|
|
3006
3107
|
|
|
3108
|
+
// src/verify/google.ts
|
|
3109
|
+
var google = {
|
|
3110
|
+
name: "google",
|
|
3111
|
+
defaultModel: "gemini-decision-1",
|
|
3112
|
+
hostedUrl: "https://generativelanguage.googleapis.com",
|
|
3113
|
+
keyPrefixes: ["AIza", "AQ."],
|
|
3114
|
+
// AQ.: the newer AI Studio keys
|
|
3115
|
+
modelPrefix: "gemini-",
|
|
3116
|
+
matches: (host3) => host3 === "generativelanguage.googleapis.com",
|
|
3117
|
+
windowChars: () => 8e5,
|
|
3118
|
+
request: ({ base_url, api_key, model, state, questions }) => ({
|
|
3119
|
+
url: `${base_url}/v1beta/decisions`,
|
|
3120
|
+
headers: { "content-type": "application/json", ...api_key ? { "x-goog-api-key": api_key } : {} },
|
|
3121
|
+
body: JSON.stringify({ model, input: googleInput(state), questions })
|
|
3122
|
+
})
|
|
3123
|
+
};
|
|
3124
|
+
function googleInput(state) {
|
|
3125
|
+
if (typeof state === "string") return state;
|
|
3126
|
+
if (!state || typeof state !== "object") return JSON.stringify(state);
|
|
3127
|
+
return Object.entries(state).map(([k, v]) => ({ type: "text", text: JSON.stringify({ [k]: v }) + "\n" }));
|
|
3128
|
+
}
|
|
3129
|
+
|
|
3130
|
+
// src/verify/openai.ts
|
|
3131
|
+
var openai = {
|
|
3132
|
+
name: "openai",
|
|
3133
|
+
defaultModel: "gpt-6-luna",
|
|
3134
|
+
hostedUrl: "https://api.openai.com",
|
|
3135
|
+
keyPrefixes: ["sk-"],
|
|
3136
|
+
modelPrefix: "gpt-",
|
|
3137
|
+
matches: (host3) => host3 === "api.openai.com",
|
|
3138
|
+
windowChars: () => 4e5,
|
|
3139
|
+
// its context limit for decisions is not documented: half of the others', a longer paper is windowed
|
|
3140
|
+
request: ({ base_url, api_key, model, state, questions }) => ({
|
|
3141
|
+
url: `${base_url}/v1/decisions`,
|
|
3142
|
+
headers: { "content-type": "application/json", ...api_key ? { authorization: `Bearer ${api_key}` } : {} },
|
|
3143
|
+
body: JSON.stringify({
|
|
3144
|
+
model,
|
|
3145
|
+
input: typeof state === "string" ? state : [{ role: "user", content: [{ type: "input_json", data: state }] }],
|
|
3146
|
+
questions: Object.entries(questions).map(([name, q]) => ({ type: "predicate", name, instructions: q.instructions }))
|
|
3147
|
+
})
|
|
3148
|
+
}),
|
|
3149
|
+
parse: (body) => {
|
|
3150
|
+
const list5 = body.answers;
|
|
3151
|
+
if (!Array.isArray(list5)) return null;
|
|
3152
|
+
const out = {};
|
|
3153
|
+
for (const a of list5) {
|
|
3154
|
+
if (a.type === "refusal") throw new Error(`refused to answer "${a.name}"`);
|
|
3155
|
+
if (a.name && typeof a.probability === "number") out[a.name] = { noul: a.probability };
|
|
3156
|
+
}
|
|
3157
|
+
return out;
|
|
3158
|
+
}
|
|
3159
|
+
};
|
|
3160
|
+
|
|
3161
|
+
// src/verify/perplexity.ts
|
|
3162
|
+
var perplexity = {
|
|
3163
|
+
name: "perplexity",
|
|
3164
|
+
defaultModel: "pplx-decider-flash-v1.2",
|
|
3165
|
+
hostedUrl: "https://api.perplexity.ai",
|
|
3166
|
+
keyPrefixes: ["pplx-"],
|
|
3167
|
+
modelPrefix: "pplx-",
|
|
3168
|
+
matches: (host3) => host3 === "api.perplexity.ai",
|
|
3169
|
+
// Hosted takes 256k tokens in one request (a 50k-token paper in 2 s); the
|
|
3170
|
+
// Mac app is limited to 32k and slows steeply beyond 25k, so it windows.
|
|
3171
|
+
windowChars: (baseUrl) => {
|
|
3172
|
+
try {
|
|
3173
|
+
return new URL(baseUrl).hostname === "api.perplexity.ai" ? 8e5 : 9e4;
|
|
3174
|
+
} catch {
|
|
3175
|
+
return 9e4;
|
|
3176
|
+
}
|
|
3177
|
+
},
|
|
3178
|
+
request: ({ base_url, api_key, model, state, questions }) => ({
|
|
3179
|
+
url: `${base_url}/v1/decisions`,
|
|
3180
|
+
headers: { "content-type": "application/json", ...api_key ? { authorization: `Bearer ${api_key}` } : {} },
|
|
3181
|
+
body: JSON.stringify({ model, state, questions })
|
|
3182
|
+
})
|
|
3183
|
+
};
|
|
3184
|
+
|
|
3185
|
+
// src/verify/providers.ts
|
|
3186
|
+
var PROVIDERS = [google, openai, perplexity];
|
|
3187
|
+
var PROVIDER_NAMES = PROVIDERS.map((p) => p.name);
|
|
3188
|
+
var providerByName = (name) => PROVIDERS.find((p) => p.name === name) ?? null;
|
|
3189
|
+
var providerForKey = (key) => PROVIDERS.find((p) => p.keyPrefixes.some((k) => key.startsWith(k))) ?? null;
|
|
3190
|
+
function providerFor(baseUrl) {
|
|
3191
|
+
let host3 = "";
|
|
3192
|
+
try {
|
|
3193
|
+
host3 = new URL(baseUrl).hostname;
|
|
3194
|
+
} catch {
|
|
3195
|
+
}
|
|
3196
|
+
return PROVIDERS.find((p) => p.matches(host3)) ?? PROVIDERS[PROVIDERS.length - 1];
|
|
3197
|
+
}
|
|
3198
|
+
|
|
3199
|
+
// src/verify/config.ts
|
|
3200
|
+
var cleanUrl = (u) => u.replace(/\/+$/, "").replace(/\/(v1beta|v1)(\/decisions)?$|\/decisions$/, "");
|
|
3201
|
+
function resolve4(env) {
|
|
3202
|
+
const problems = [];
|
|
3203
|
+
const field2 = (p, f) => {
|
|
3204
|
+
const own = p ? `FH_VERIFY_${p.name.toUpperCase()}_${f}` : "";
|
|
3205
|
+
if (own && str(own, env)) return [str(own, env), own];
|
|
3206
|
+
const plain3 = str(`FH_VERIFY_${f}`, env);
|
|
3207
|
+
return [plain3, plain3 || !own ? `FH_VERIFY_${f}` : own];
|
|
3208
|
+
};
|
|
3209
|
+
const filled = (p) => !!(str(`FH_VERIFY_${p.name.toUpperCase()}_URL`, env) || str(`FH_VERIFY_${p.name.toUpperCase()}_API_KEY`, env));
|
|
3210
|
+
const name = str("FH_VERIFY_PROVIDER", env).toLowerCase();
|
|
3211
|
+
let provider = null;
|
|
3212
|
+
if (name) {
|
|
3213
|
+
provider = providerByName(name);
|
|
3214
|
+
if (!provider) return { cfg: null, problems: [`FH_VERIFY_PROVIDER: unknown provider "${name}" (built-in: ${PROVIDER_NAMES.join(", ")}): verification is off`] };
|
|
3215
|
+
} else {
|
|
3216
|
+
const sections2 = PROVIDER_NAMES.map((n) => providerByName(n)).filter(filled);
|
|
3217
|
+
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`] };
|
|
3218
|
+
provider = sections2[0] ?? null;
|
|
3219
|
+
}
|
|
3220
|
+
const [key, keyVar] = field2(provider, "API_KEY");
|
|
3221
|
+
const [url, urlVar] = field2(provider, "URL");
|
|
3222
|
+
const api_key = key || null;
|
|
3223
|
+
let base_url = cleanUrl(url);
|
|
3224
|
+
if (!base_url && !api_key) {
|
|
3225
|
+
if (provider) problems.push(`FH_VERIFY_PROVIDER=${provider.name}, but neither ${urlVar} nor ${keyVar} is set: verification is off`);
|
|
3226
|
+
return { cfg: null, problems };
|
|
3227
|
+
}
|
|
3228
|
+
if (!provider) provider = (api_key ? providerForKey(api_key) : null) ?? providerFor(base_url);
|
|
3229
|
+
const keyOf = api_key ? providerForKey(api_key) : null;
|
|
3230
|
+
if (keyOf && keyOf !== provider) problems.push(`${keyVar} looks like a ${keyOf.name} key, but the provider is ${provider.name}`);
|
|
3231
|
+
if (!base_url) base_url = provider.hostedUrl;
|
|
3232
|
+
if (!api_key && provider.matches(new URL(base_url).hostname)) problems.push(`${provider.name}'s hosted endpoint needs a key, and ${keyVar} is empty`);
|
|
3233
|
+
const [m, modelVar] = field2(provider, "MODEL");
|
|
3234
|
+
const model = m && m.startsWith(provider.modelPrefix) ? m : provider.defaultModel;
|
|
3235
|
+
if (m && !m.startsWith(provider.modelPrefix)) problems.push(`${modelVar}=${m} is not a ${provider.name} model: ${provider.defaultModel} is used`);
|
|
3236
|
+
return {
|
|
3237
|
+
problems,
|
|
3238
|
+
cfg: {
|
|
3239
|
+
provider,
|
|
3240
|
+
base_url,
|
|
3241
|
+
api_key,
|
|
3242
|
+
model,
|
|
3243
|
+
threshold: num("FH_VERIFY_THRESHOLD", 0.5, env, (n) => n > 0 && n < 1),
|
|
3244
|
+
window_chars: provider.windowChars(base_url, model),
|
|
3245
|
+
timeout_seconds: num("FH_VERIFY_TIMEOUT_SECS", 60, env, (n) => n > 0)
|
|
3246
|
+
}
|
|
3247
|
+
};
|
|
3248
|
+
}
|
|
3249
|
+
var verifyConfig = (env = process.env) => resolve4(env).cfg;
|
|
3250
|
+
var verifyProblems = (env = process.env) => resolve4(env).problems;
|
|
3251
|
+
function isLocal(baseUrl) {
|
|
3252
|
+
try {
|
|
3253
|
+
const h = new URL(baseUrl).hostname;
|
|
3254
|
+
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);
|
|
3255
|
+
} catch {
|
|
3256
|
+
return false;
|
|
3257
|
+
}
|
|
3258
|
+
}
|
|
3259
|
+
|
|
3007
3260
|
// src/log.ts
|
|
3008
3261
|
import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync4, renameSync as renameSync2, statSync } from "fs";
|
|
3009
3262
|
import { hostname } from "os";
|
|
@@ -3120,10 +3373,10 @@ import { z } from "zod";
|
|
|
3120
3373
|
// src/cascade.ts
|
|
3121
3374
|
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
3375
|
var BLOCKED = /^(challenge not cleared|empty response)/i;
|
|
3123
|
-
var
|
|
3376
|
+
var STAGE = /^((?:playwright|chrome|browser|fetch-proxy) [^:]+|brightdata|zenrows|zyte|unlocker): /;
|
|
3124
3377
|
function isPermanent(reason, retryBlocked = false) {
|
|
3125
3378
|
return reason.split(";").every((r) => {
|
|
3126
|
-
const b = r.trim().replace(
|
|
3379
|
+
const b = r.trim().replace(STAGE, "");
|
|
3127
3380
|
return PERMANENT.test(b) || !retryBlocked && BLOCKED.test(b);
|
|
3128
3381
|
});
|
|
3129
3382
|
}
|
|
@@ -3224,185 +3477,10 @@ function libraryIdForUrl(raw) {
|
|
|
3224
3477
|
}
|
|
3225
3478
|
|
|
3226
3479
|
// src/info.ts
|
|
3227
|
-
import { existsSync as
|
|
3480
|
+
import { existsSync as existsSync6, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
|
|
3228
3481
|
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
3482
|
function* metaFiles(dir) {
|
|
3405
|
-
if (!
|
|
3483
|
+
if (!existsSync6(dir)) return;
|
|
3406
3484
|
for (const name of readdirSync3(dir)) {
|
|
3407
3485
|
const p = join8(dir, name);
|
|
3408
3486
|
if (statSync3(p).isDirectory()) yield* metaFiles(p);
|
|
@@ -3427,9 +3505,10 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3427
3505
|
evidence_dir: libraryDir,
|
|
3428
3506
|
host: host3,
|
|
3429
3507
|
tiers: tiers.all,
|
|
3430
|
-
config: { ...settings(), problems: tiers.problems, sources: sources() },
|
|
3508
|
+
config: { ...settings(), problems: [...tiers.problems, ...verifyProblems(), ...unlockerProblems()], sources: sources() },
|
|
3431
3509
|
download: downloadInfo(),
|
|
3432
3510
|
verify: verifyInfo(),
|
|
3511
|
+
unlockers: unlockers().map((provider) => ({ provider })),
|
|
3433
3512
|
entries: 0,
|
|
3434
3513
|
size_bytes: 0,
|
|
3435
3514
|
size: "",
|
|
@@ -3442,11 +3521,11 @@ function libraryInfo(libraryDir, host3, tiers = resolveTiers()) {
|
|
|
3442
3521
|
concerns: 0,
|
|
3443
3522
|
updates: 0
|
|
3444
3523
|
};
|
|
3445
|
-
for (const type of
|
|
3524
|
+
for (const type of existsSync6(libraryDir) ? readdirSync3(libraryDir) : []) {
|
|
3446
3525
|
const typeDir = join8(libraryDir, type);
|
|
3447
3526
|
if (!statSync3(typeDir).isDirectory()) continue;
|
|
3448
3527
|
for (const meta of metaFiles(typeDir)) {
|
|
3449
|
-
const md =
|
|
3528
|
+
const md = readFileSync5(meta, "utf8");
|
|
3450
3529
|
const raw = field(md, "level") || "unknown";
|
|
3451
3530
|
const level = raw === "abstract" && field(md, "has_abstract") === "no" ? "title" : raw;
|
|
3452
3531
|
info.entries++;
|
|
@@ -3485,7 +3564,7 @@ function noticeTypes(md, metaPath) {
|
|
|
3485
3564
|
return out;
|
|
3486
3565
|
}
|
|
3487
3566
|
try {
|
|
3488
|
-
const xml =
|
|
3567
|
+
const xml = readFileSync5(metaPath.replace(/-meta\.md$/, "-abstract.xml"), "utf8");
|
|
3489
3568
|
for (const m of xml.matchAll(/<CommentsCorrections RefType="([A-Za-z]+)"/g)) if (XML_TYPES[m[1]]) out.add(XML_TYPES[m[1]]);
|
|
3490
3569
|
} catch {
|
|
3491
3570
|
}
|
|
@@ -3493,11 +3572,11 @@ function noticeTypes(md, metaPath) {
|
|
|
3493
3572
|
}
|
|
3494
3573
|
function verifyInfo() {
|
|
3495
3574
|
const v = verifyConfig();
|
|
3496
|
-
return v ? { model: v.model, base_url: v.base_url, local: isLocal(v.base_url) } : null;
|
|
3575
|
+
return v ? { provider: v.provider.name, model: v.model, base_url: v.base_url, local: isLocal(v.base_url) } : null;
|
|
3497
3576
|
}
|
|
3498
3577
|
function downloadInfo() {
|
|
3499
|
-
const
|
|
3500
|
-
return { fetch: true, fetch_proxy: fetchProxy(), playwright: { version: PLAYWRIGHT_VERSION, servers:
|
|
3578
|
+
const stages = browserStages();
|
|
3579
|
+
return { fetch: true, fetch_proxy: fetchProxy(), playwright: { version: PLAYWRIGHT_VERSION, servers: stages.filter((b) => b.kind === "playwright") }, chrome: stages.filter((b) => b.kind === "chrome"), unlocker: unlockerConfigured() };
|
|
3501
3580
|
}
|
|
3502
3581
|
|
|
3503
3582
|
// src/read.ts
|
|
@@ -3714,6 +3793,51 @@ function stem(w) {
|
|
|
3714
3793
|
return w;
|
|
3715
3794
|
}
|
|
3716
3795
|
|
|
3796
|
+
// src/verify/decider.ts
|
|
3797
|
+
var RETRY_MS = 2e3;
|
|
3798
|
+
var WAIT_SCALE = 1;
|
|
3799
|
+
var RATE_LIMITED = /rate limit|quota|resource.?exhausted/i;
|
|
3800
|
+
function waitSeconds(r, msg) {
|
|
3801
|
+
const asked = Number(/retry in (\d+(?:\.\d+)?)\s*s/i.exec(msg)?.[1] ?? r.headers.get("retry-after") ?? NaN);
|
|
3802
|
+
return Math.min(60, Number.isFinite(asked) && asked > 0 ? asked + 1 : 15);
|
|
3803
|
+
}
|
|
3804
|
+
function decider(cfg, fetchFn = fetch) {
|
|
3805
|
+
return async (state, questions) => {
|
|
3806
|
+
const { url, headers, body } = cfg.provider.request({ base_url: cfg.base_url, api_key: cfg.api_key, model: cfg.model, state, questions });
|
|
3807
|
+
let waits = 0;
|
|
3808
|
+
for (let attempt = 0; ; attempt++) {
|
|
3809
|
+
let r;
|
|
3810
|
+
try {
|
|
3811
|
+
r = await fetchFn(url, { method: "POST", headers, body, signal: AbortSignal.timeout(cfg.timeout_seconds * 1e3) });
|
|
3812
|
+
} catch (e) {
|
|
3813
|
+
const name = e instanceof Error ? e.name : "";
|
|
3814
|
+
const cause = e.cause;
|
|
3815
|
+
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)`);
|
|
3816
|
+
throw new Error(`${cfg.model}: ${cause?.message ?? (e instanceof Error ? e.message : String(e))}`);
|
|
3817
|
+
}
|
|
3818
|
+
const j = await r.json().catch(() => ({}));
|
|
3819
|
+
let answers;
|
|
3820
|
+
try {
|
|
3821
|
+
answers = cfg.provider.parse ? cfg.provider.parse(j) : j.answers ?? null;
|
|
3822
|
+
} catch (e) {
|
|
3823
|
+
throw new Error(`${cfg.model}: ${e instanceof Error ? e.message : String(e)}`);
|
|
3824
|
+
}
|
|
3825
|
+
if (answers) return answers;
|
|
3826
|
+
const msg = typeof j.error === "string" ? j.error : j.error?.message;
|
|
3827
|
+
if ((r.status === 429 || RATE_LIMITED.test(msg ?? "")) && waits < 2) {
|
|
3828
|
+
waits++;
|
|
3829
|
+
await new Promise((res) => setTimeout(res, waitSeconds(r, msg ?? "") * 1e3 * WAIT_SCALE));
|
|
3830
|
+
continue;
|
|
3831
|
+
}
|
|
3832
|
+
if (attempt === 0 && ([502, 503, 504].includes(r.status) || /temporarily unavailable|overloaded|try again|retry your request/i.test(msg ?? ""))) {
|
|
3833
|
+
await new Promise((res) => setTimeout(res, RETRY_MS));
|
|
3834
|
+
continue;
|
|
3835
|
+
}
|
|
3836
|
+
throw new Error(msg ? `${cfg.model}: ${msg}` : `${cfg.model}: HTTP ${r.status} without an answer`);
|
|
3837
|
+
}
|
|
3838
|
+
};
|
|
3839
|
+
}
|
|
3840
|
+
|
|
3717
3841
|
// src/doi.ts
|
|
3718
3842
|
var NCBI_ESEARCH = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
|
|
3719
3843
|
async function pmidForDoi(doi) {
|
|
@@ -3867,7 +3991,7 @@ function parseCsl(json2) {
|
|
|
3867
3991
|
|
|
3868
3992
|
// src/urlfetch.ts
|
|
3869
3993
|
import { createHash as createHash2 } from "crypto";
|
|
3870
|
-
import { existsSync as
|
|
3994
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync6 } from "fs";
|
|
3871
3995
|
import { join as join9 } from "path";
|
|
3872
3996
|
|
|
3873
3997
|
// src/pagemeta.ts
|
|
@@ -4031,8 +4155,8 @@ function renderUrlMeta(m) {
|
|
|
4031
4155
|
return lines.map(([k, v]) => `${k}: ${v}`).join("\n") + "\n";
|
|
4032
4156
|
}
|
|
4033
4157
|
function readUrlMeta(p) {
|
|
4034
|
-
if (!
|
|
4035
|
-
const md =
|
|
4158
|
+
if (!existsSync7(p.meta)) return null;
|
|
4159
|
+
const md = readFileSync6(p.meta, "utf8");
|
|
4036
4160
|
const f = (k) => {
|
|
4037
4161
|
const m = new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md);
|
|
4038
4162
|
return m ? m[1].trim() : "";
|
|
@@ -4078,16 +4202,16 @@ function isScriptShell(markdownOrHtml) {
|
|
|
4078
4202
|
const words3 = text4.split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length;
|
|
4079
4203
|
return { shell: words3 < EMPTY_WORDS || words3 < SHELL_WORDS && SHELL_PHRASE.test(text4), words: words3 };
|
|
4080
4204
|
}
|
|
4081
|
-
var viaName = (via) => typeof via === "object" ? "proxy" in via ? fetchProxyName(via) :
|
|
4082
|
-
async function
|
|
4205
|
+
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;
|
|
4206
|
+
async function stage(url, via) {
|
|
4083
4207
|
const name = viaName(via);
|
|
4084
4208
|
let got;
|
|
4085
4209
|
try {
|
|
4086
|
-
got = via === "
|
|
4210
|
+
got = typeof via === "object" && "unlocker" in via ? await unlock(url, via.unlocker) : typeof via === "object" ? "proxy" in via ? await fetchBytes(url, BROWSER_HEADERS, via.proxy) : await browserFetch(url, via.browser) : await fetchBytes(url, BROWSER_HEADERS);
|
|
4087
4211
|
} catch (e) {
|
|
4088
4212
|
return { ok: false, reason: errMsg(e), url: e?.url, via: name };
|
|
4089
4213
|
}
|
|
4090
|
-
if (via === "
|
|
4214
|
+
if (typeof via === "object" && "unlocker" in via && !got.bytes.length) return { ok: false, reason: "empty response", via: name };
|
|
4091
4215
|
const r = { ok: true, bytes: got.bytes, contentType: got.contentType, url: got.url ?? url, via: name };
|
|
4092
4216
|
if (!looksLikePdf(got.bytes)) {
|
|
4093
4217
|
const text4 = got.bytes.toString("utf8");
|
|
@@ -4105,7 +4229,7 @@ async function rung(url, via) {
|
|
|
4105
4229
|
return r;
|
|
4106
4230
|
}
|
|
4107
4231
|
var climb = async (url, onTry, onAlert) => {
|
|
4108
|
-
let r = await
|
|
4232
|
+
let r = await stage(url, "fetch");
|
|
4109
4233
|
const firstReason = r.ok ? void 0 : r.reason;
|
|
4110
4234
|
let gone;
|
|
4111
4235
|
const seen = (g) => {
|
|
@@ -4126,36 +4250,41 @@ var climb = async (url, onTry, onAlert) => {
|
|
|
4126
4250
|
const w = walled(target, name);
|
|
4127
4251
|
if (w) onTry?.(`skipped ${name}: ${wallNote(w)}`);
|
|
4128
4252
|
else {
|
|
4129
|
-
r = seen(await
|
|
4130
|
-
|
|
4253
|
+
r = seen(await stage(target, { proxy: f.proxy, label: f.label }));
|
|
4254
|
+
recordStage(target, name, r.ok, r.ok ? "" : r.reason);
|
|
4131
4255
|
if (!r.ok && r.shell && !shell) shell = r.shell;
|
|
4132
4256
|
onTry?.(r.ok ? `ok ${name}` : `failed ${name}: ${r.reason}`);
|
|
4133
4257
|
}
|
|
4134
4258
|
}
|
|
4135
|
-
for (const b of
|
|
4259
|
+
for (const b of browserStages()) {
|
|
4136
4260
|
if (!escalates(r)) break;
|
|
4137
|
-
const name =
|
|
4261
|
+
const name = stageName(b);
|
|
4138
4262
|
const w = walled(target, name);
|
|
4139
4263
|
if (w) {
|
|
4140
4264
|
onTry?.(`skipped ${name}: ${wallNote(w)}`);
|
|
4141
4265
|
continue;
|
|
4142
4266
|
}
|
|
4143
|
-
r = seen(await
|
|
4144
|
-
|
|
4267
|
+
r = seen(await stage(target, { browser: b.endpoint, label: b.label }));
|
|
4268
|
+
recordStage(target, name, r.ok, r.ok ? "" : r.reason);
|
|
4145
4269
|
if (!r.ok && r.shell && !shell) shell = r.shell;
|
|
4146
4270
|
onTry?.(r.ok ? `ok ${name}` : `failed ${name}: ${r.reason}`);
|
|
4147
4271
|
if (!r.ok && r.reason.startsWith(MISMATCH)) onAlert?.(`${name}: ${r.reason}`);
|
|
4148
4272
|
}
|
|
4149
|
-
const
|
|
4150
|
-
|
|
4151
|
-
|
|
4152
|
-
|
|
4153
|
-
|
|
4154
|
-
|
|
4155
|
-
|
|
4273
|
+
const unlockable = !r.ok && (!plainVia(r) || met(r, /^(HTTP 403|wall page|script shell)/));
|
|
4274
|
+
for (const u of unlockable ? unlockers() : []) {
|
|
4275
|
+
const uw = walled(target, u);
|
|
4276
|
+
if (uw) {
|
|
4277
|
+
onTry?.(`skipped ${u}: ${wallNote(uw)}`);
|
|
4278
|
+
continue;
|
|
4279
|
+
}
|
|
4280
|
+
r = seen(await stage(target, { unlocker: u }));
|
|
4281
|
+
recordStage(target, u, r.ok, r.ok ? "" : r.reason);
|
|
4282
|
+
onTry?.(r.ok ? `ok ${u}` : `failed ${u}: ${r.reason}`);
|
|
4283
|
+
if (!r.ok && accountProblem(r.reason)) onAlert?.(`${u}: ${r.reason}`);
|
|
4284
|
+
if (r.ok) break;
|
|
4156
4285
|
}
|
|
4157
4286
|
if (!r.ok && shell) {
|
|
4158
|
-
onTry?.("shell kept: no
|
|
4287
|
+
onTry?.("shell kept: no stage rendered the page, the script shell is served");
|
|
4159
4288
|
return shell;
|
|
4160
4289
|
}
|
|
4161
4290
|
return r.ok || r.via === "fetch" ? r : { ...r, first: gone ?? firstReason };
|
|
@@ -4323,7 +4452,7 @@ function titleLine(m, md) {
|
|
|
4323
4452
|
}
|
|
4324
4453
|
function serve(requested, p, m, args, cached) {
|
|
4325
4454
|
const maxLength = args.max_length ?? 5e3, startIndex = args.start_index ?? 0;
|
|
4326
|
-
const read2 = (file3) =>
|
|
4455
|
+
const read2 = (file3) => existsSync7(file3) ? readFileSync6(file3, "utf8") : "";
|
|
4327
4456
|
if (args.title_only) return { ok: true, text: `Contents of ${requested}:
|
|
4328
4457
|
${titleLine(m, read2(p.md))}`, cached, meta: m };
|
|
4329
4458
|
const rawFile = m.files.find((f) => !f.endsWith("-meta.md") && !f.endsWith("-page.md"));
|
|
@@ -4348,9 +4477,9 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
|
|
|
4348
4477
|
let stored = readUrlMeta(p);
|
|
4349
4478
|
if (stored && fresh(stored) && stored.format === "html" && olderConverter(stored.converted_by, converter)) {
|
|
4350
4479
|
const html = stored.files.find((f) => f.endsWith("-page.html"));
|
|
4351
|
-
if (html &&
|
|
4480
|
+
if (html && existsSync7(join9(p.entryDir, html))) {
|
|
4352
4481
|
try {
|
|
4353
|
-
const page = await convert(
|
|
4482
|
+
const page = await convert(readFileSync6(join9(p.entryDir, html)), stored.content_type || "text/html", stored.final_url || stored.url);
|
|
4354
4483
|
if (page.md !== null) {
|
|
4355
4484
|
writeAtomic(p.md, page.md);
|
|
4356
4485
|
writeUrlMeta(p, { ...stored, title: page.title, converted_by: converter, ...sourceFields(page) });
|
|
@@ -4392,10 +4521,128 @@ async function libraryFetch(libraryDir, requested, args, converter, logs = {}, f
|
|
|
4392
4521
|
return answer(m, false);
|
|
4393
4522
|
}
|
|
4394
4523
|
|
|
4395
|
-
// src/
|
|
4524
|
+
// src/verify/cache.ts
|
|
4396
4525
|
import { createHash as createHash3 } from "crypto";
|
|
4397
4526
|
import { existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync8 } from "fs";
|
|
4398
4527
|
import { dirname as dirname3, join as join10 } from "path";
|
|
4528
|
+
|
|
4529
|
+
// src/verify/verify.ts
|
|
4530
|
+
import { existsSync as existsSync8, readFileSync as readFileSync7 } from "fs";
|
|
4531
|
+
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.";
|
|
4532
|
+
function cleanMarkdown(md) {
|
|
4533
|
+
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");
|
|
4534
|
+
}
|
|
4535
|
+
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;
|
|
4536
|
+
function dropReferences(md) {
|
|
4537
|
+
let out = md;
|
|
4538
|
+
for (; ; ) {
|
|
4539
|
+
REF_HEAD.lastIndex = 0;
|
|
4540
|
+
const m = REF_HEAD.exec(out);
|
|
4541
|
+
if (!m) return out;
|
|
4542
|
+
const level = m[1]?.length ?? 6;
|
|
4543
|
+
const rest = out.slice(m.index + m[0].length);
|
|
4544
|
+
const next = new RegExp(`^#{1,${level}}\\s`, "m").exec(rest);
|
|
4545
|
+
out = out.slice(0, m.index) + (next ? rest.slice(next.index) : "");
|
|
4546
|
+
}
|
|
4547
|
+
}
|
|
4548
|
+
function paperYearOnly(md) {
|
|
4549
|
+
return md.replace(/^(#[^\n]*\n\n)([^\n]*· (?:PMID \d+|DOI 10\.)[^\n]*)$/m, (_, title, line) => {
|
|
4550
|
+
const year = / · (\d{4})(?: · |$)/.exec(line)?.[1];
|
|
4551
|
+
return year ? `${title}${year}` : title.trimEnd();
|
|
4552
|
+
});
|
|
4553
|
+
}
|
|
4554
|
+
function windows(md, max) {
|
|
4555
|
+
const out = [];
|
|
4556
|
+
let cur = "";
|
|
4557
|
+
for (const s of cleanMarkdown(md).split(/\n(?=#)/)) {
|
|
4558
|
+
if (cur && cur.length + s.length + 1 > max) {
|
|
4559
|
+
out.push(cur);
|
|
4560
|
+
cur = "";
|
|
4561
|
+
}
|
|
4562
|
+
cur += (cur ? "\n" : "") + s.slice(0, max);
|
|
4563
|
+
}
|
|
4564
|
+
if (cur) out.push(cur);
|
|
4565
|
+
return out.length ? out : [""];
|
|
4566
|
+
}
|
|
4567
|
+
var MONTH = /^(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|June?|July?|Aug(ust)?|Sep(t(ember)?)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\.?$/;
|
|
4568
|
+
var namesAuthor = (group) => (group.match(/\b[A-Z][\p{L}'’-]+/gu) ?? []).some((w) => !MONTH.test(w));
|
|
4569
|
+
function citationGroups(claim) {
|
|
4570
|
+
const one = /[(\[][^()\[\]]*?\b(1[89]\d\d|20\d\d)[a-z]?\b[^()\[\]]*[)\]]/g;
|
|
4571
|
+
const groups = [];
|
|
4572
|
+
let last = -1;
|
|
4573
|
+
for (const m of claim.matchAll(one)) {
|
|
4574
|
+
if (!namesAuthor(m[0])) continue;
|
|
4575
|
+
const between = claim.slice(last, m.index);
|
|
4576
|
+
if (last >= 0 && /^[\s;,]*(and|&)?[\s;,]*$/i.test(between)) {
|
|
4577
|
+
groups[groups.length - 1] += between + m[0];
|
|
4578
|
+
} else groups.push(m[0]);
|
|
4579
|
+
last = m.index + m[0].length;
|
|
4580
|
+
}
|
|
4581
|
+
return groups;
|
|
4582
|
+
}
|
|
4583
|
+
function fragment(claim) {
|
|
4584
|
+
const body = claim.trim().replace(/^[-*+]\s+/, "").replace(/^\*\*[^*]+:\*\*\s*/, "").replace(/^[("'\u201c]+/, "");
|
|
4585
|
+
const first = /^(\S+)/.exec(body)?.[1] ?? "";
|
|
4586
|
+
const oddsRatio = first === "OR" && /^OR\s+(\d|=|\(|of\b|for\b)/.test(body);
|
|
4587
|
+
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`;
|
|
4588
|
+
return null;
|
|
4589
|
+
}
|
|
4590
|
+
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.";
|
|
4591
|
+
function correctedText(md) {
|
|
4592
|
+
const i = md.indexOf(`
|
|
4593
|
+
${CORRECTED_HEADING}
|
|
4594
|
+
`);
|
|
4595
|
+
if (i < 0) return null;
|
|
4596
|
+
return md.slice(i + CORRECTED_HEADING.length + 2).split("\n").filter((l) => l.trim() && !/^NLM corrected these sentences/.test(l)).join("\n").trim() || null;
|
|
4597
|
+
}
|
|
4598
|
+
async function readPaper(raw, libraryDir = FH_EVIDENCE_DIR) {
|
|
4599
|
+
const p = parseId(raw);
|
|
4600
|
+
if (p.error) return { id: p.requested, error: p.error };
|
|
4601
|
+
const paths = entryPaths(libraryDir, p.type, p.id);
|
|
4602
|
+
if (!entryExists(paths)) return { id: p.requested, error: "not in library" };
|
|
4603
|
+
const full = existsSync8(paths.fulltextMd);
|
|
4604
|
+
if (full) return { id: p.requested, basis: "full_text", text: readFileSync7(paths.fulltextMd, "utf8") };
|
|
4605
|
+
const meta = readMeta(paths);
|
|
4606
|
+
return { id: p.requested, basis: meta.has_abstract ? "abstract" : "title", text: readFileSync7(paths.md, "utf8") };
|
|
4607
|
+
}
|
|
4608
|
+
async function verifyClaim(claim, id, cfg, decide, read2 = readPaper) {
|
|
4609
|
+
const out = { claim, id, verdict: "error", reason: null, score: null, basis: null, windows: 0, glyphs_unresolved: 0, superseded: null, model: cfg?.model ?? null };
|
|
4610
|
+
const words3 = claim.trim().split(/\s+/).filter(Boolean).length;
|
|
4611
|
+
if (!words3) return { ...out, error: "claim empty" };
|
|
4612
|
+
if (words3 < 3) return { ...out, error: "claim too short to be a finding" };
|
|
4613
|
+
const frag = fragment(claim);
|
|
4614
|
+
if (frag) return { ...out, error: frag };
|
|
4615
|
+
const groups = citationGroups(claim);
|
|
4616
|
+
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` };
|
|
4617
|
+
const paper = await read2(id);
|
|
4618
|
+
out.id = paper.id;
|
|
4619
|
+
if ("error" in paper) return { ...out, error: paper.error };
|
|
4620
|
+
if (!cfg || !decide) return { ...out, error: "no verify model configured (FH_VERIFY_URL)" };
|
|
4621
|
+
out.basis = paper.basis;
|
|
4622
|
+
out.glyphs_unresolved = countUnresolved(paper.text);
|
|
4623
|
+
if (paper.basis === "title") return { ...out, verdict: "fail", reason: NOTHING_TO_VERIFY };
|
|
4624
|
+
const ws = windows(paper.text, cfg.window_chars);
|
|
4625
|
+
out.windows = ws.length;
|
|
4626
|
+
try {
|
|
4627
|
+
let score = 0;
|
|
4628
|
+
for (const w of ws) {
|
|
4629
|
+
const a = await decide({ paper: w, statement: claim }, { backed: { type: "noul", instructions: QUESTION } });
|
|
4630
|
+
score = Math.max(score, a.backed?.noul ?? 0);
|
|
4631
|
+
}
|
|
4632
|
+
out.score = score;
|
|
4633
|
+
const corrected = correctedText(paper.text);
|
|
4634
|
+
if (corrected) {
|
|
4635
|
+
const a = await decide({ corrected, statement: claim }, { superseded: { type: "noul", instructions: SUPERSEDED } });
|
|
4636
|
+
out.superseded = (a.superseded?.noul ?? 0) >= 0.5;
|
|
4637
|
+
}
|
|
4638
|
+
} catch (e) {
|
|
4639
|
+
return { ...out, error: e instanceof Error ? e.message : String(e) };
|
|
4640
|
+
}
|
|
4641
|
+
if (out.score >= cfg.threshold) return { ...out, verdict: "pass" };
|
|
4642
|
+
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" };
|
|
4643
|
+
}
|
|
4644
|
+
|
|
4645
|
+
// src/verify/cache.ts
|
|
4399
4646
|
var sha = (s) => createHash3("sha1").update(s).digest("hex");
|
|
4400
4647
|
var normalizeClaim = (claim) => claim.replace(/\s+/g, " ").trim();
|
|
4401
4648
|
function foldClaim(claim) {
|
|
@@ -4849,8 +5096,8 @@ function readMissing(p) {
|
|
|
4849
5096
|
const f = missingFile(p);
|
|
4850
5097
|
if (!existsSync12(f)) return null;
|
|
4851
5098
|
const md = readFileSync11(f, "utf8");
|
|
4852
|
-
const
|
|
4853
|
-
const checked =
|
|
5099
|
+
const get4 = (k) => /^$/.test(k) ? "" : (new RegExp(`^${k}:[ \\t]*(.*)$`, "m").exec(md)?.[1] ?? "").trim();
|
|
5100
|
+
const checked = get4("checked"), reason = get4("reason");
|
|
4854
5101
|
return checked ? { checked, reason: reason || "not found" } : null;
|
|
4855
5102
|
}
|
|
4856
5103
|
function freshMissing(p, retryDays) {
|
|
@@ -4978,7 +5225,7 @@ Tools
|
|
|
4978
5225
|
- fh_clinicaltrials_search_studies(query | intervention | condition, status?, sort?, max_results?) \u2014 search ClinicalTrials.gov: the total and rows in columns order (NCT ID, title, status, phase, enrollment, dates, primary outcome, conditions, interventions, has_results). Cached a week.
|
|
4979
5226
|
- fh_clinicaltrials_get_study_record(nct) \u2014 one trial as a review needs it (status, design, enrollment, dates, outcomes, eligibility, result publications, summary), from the stored record; added first when missing.
|
|
4980
5227
|
- fh_clinicaltrials_get_study_results(nct, max_chars?) \u2014 a trial's posted results as Markdown, capped; the outcome titles listed for fh_library_read.
|
|
4981
|
-
- fh_fetch_url(url, max_length?, start_index?, raw?, title_only?) \u2014 a web page as Markdown, same call and same answer as the standard fetch tool ("Contents of <url>:" and the page, cut at max_length with a note on how to continue). Prefer it for every URL: a cached page answers from disk, a walled or script-rendered page
|
|
5228
|
+
- fh_fetch_url(url, max_length?, start_index?, raw?, title_only?) \u2014 a web page as Markdown, same call and same answer as the standard fetch tool ("Contents of <url>:" and the page, cut at max_length with a note on how to continue). Prefer it for every URL: a cached page answers from disk, a walled or script-rendered page runs through the browser and unlocker stages in one call. PDFs as Markdown. title_only returns the title line alone \u2014 enough to verify a link, at a few tokens.
|
|
4982
5229
|
|
|
4983
5230
|
Hints
|
|
4984
5231
|
- fh_library_read and fh_verify_claim store a missing record themselves; the fh_library_read answer then carries added: true. No fh_library_add necessary first.
|
|
@@ -5430,17 +5677,18 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5430
5677
|
const { cached, ...r } = await verifyCached(claim, id, cfg, cfg ? decider(cfg) : null, FH_EVIDENCE_DIR);
|
|
5431
5678
|
if (!r.error && r.score !== null) bump("verify", cached);
|
|
5432
5679
|
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}`);
|
|
5680
|
+
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
5681
|
return { content: [{ type: "text", text: verdictAnswer(r) }] };
|
|
5435
5682
|
}
|
|
5436
5683
|
);
|
|
5437
5684
|
server2.tool(
|
|
5438
5685
|
"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 download
|
|
5686
|
+
"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, the last download stages in the order tried, and whether each answers right now (unlockers); this server's cache hits and misses for fh_verify_claim and fh_fetch_url since it started (cache).",
|
|
5440
5687
|
{},
|
|
5441
5688
|
async () => {
|
|
5442
5689
|
const info = libraryInfo(FH_EVIDENCE_DIR, HOST);
|
|
5443
5690
|
const cfg = verifyConfig();
|
|
5691
|
+
const unlockerChecks = Promise.all(info.unlockers.map((u) => unlockerHealth(u.provider)));
|
|
5444
5692
|
if (info.verify && cfg) {
|
|
5445
5693
|
const t0 = Date.now();
|
|
5446
5694
|
try {
|
|
@@ -5450,7 +5698,8 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5450
5698
|
info.verify = { ...info.verify, ok: false, ms: Date.now() - t0, error: e instanceof Error ? e.message : String(e) };
|
|
5451
5699
|
}
|
|
5452
5700
|
}
|
|
5453
|
-
|
|
5701
|
+
info.unlockers = (await unlockerChecks).map((h, i) => ({ ...info.unlockers[i], ...h }));
|
|
5702
|
+
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("")}`);
|
|
5454
5703
|
const s = currentStats();
|
|
5455
5704
|
const cache = s ? { since: s.started, verify: s.verify, fetch: s.fetch, search: s.search, pubmed: s.pubmed } : null;
|
|
5456
5705
|
return { content: [{ type: "text", text: compact2({ package: pkg.name, version: pkg.version, log: LOG_FILE, ...info, cache }) }] };
|
|
@@ -5458,7 +5707,7 @@ ${st.funding.map((f) => `- ${f}`).join("\n")}` : ""].filter(Boolean).join("\n\n"
|
|
|
5458
5707
|
);
|
|
5459
5708
|
server2.tool(
|
|
5460
5709
|
"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
|
|
5710
|
+
`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
5711
|
{
|
|
5463
5712
|
url: z.string().describe("URL to fetch"),
|
|
5464
5713
|
// Optional, not .default(5000): the log tells a model that set none from one that asked for 5000.
|
|
@@ -5640,6 +5889,6 @@ registerTools(server);
|
|
|
5640
5889
|
startStats(pkg);
|
|
5641
5890
|
migrateLogName();
|
|
5642
5891
|
log("startup", null, `${pkg.name} ${pkg.version}`);
|
|
5643
|
-
for (const problem of resolveTiers().problems) log("startup", null, `!! ${problem}`);
|
|
5892
|
+
for (const problem of [...resolveTiers().problems, ...verifyProblems(), ...unlockerProblems()]) log("startup", null, `!! ${problem}`);
|
|
5644
5893
|
var transport = new StdioServerTransport();
|
|
5645
5894
|
await server.connect(transport);
|