@fetchbrain.com/sdk 0.8.0 → 0.10.0

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.mjs CHANGED
@@ -11,13 +11,21 @@ var DEFAULT_CONFIG = {
11
11
  successThreshold: 1
12
12
  };
13
13
  var CircuitBreaker = class {
14
- constructor(config = {}, logger) {
14
+ /**
15
+ * `name` labels this breaker's log lines when a client runs more than one
16
+ * (the ask breaker opening must not read as if recall and learn stopped).
17
+ */
18
+ constructor(config = {}, logger, name) {
15
19
  this.state = "closed";
16
20
  this.failures = 0;
17
21
  this.successes = 0;
18
22
  this.lastFailureTime = 0;
19
23
  this.config = { ...DEFAULT_CONFIG, ...config };
20
24
  this.logger = logger;
25
+ this.name = name;
26
+ }
27
+ label(message) {
28
+ return this.name ? `${this.name} circuit: ${message}` : message;
21
29
  }
22
30
  /**
23
31
  * Check if requests should be allowed through
@@ -29,7 +37,7 @@ var CircuitBreaker = class {
29
37
  if (this.state === "open") {
30
38
  const now = Date.now();
31
39
  if (now - this.lastFailureTime >= this.config.resetTimeout) {
32
- this.logger.info("Circuit transitioning to half-open, testing API...");
40
+ this.logger.info(this.label("Circuit transitioning to half-open, testing API..."));
33
41
  this.state = "half-open";
34
42
  this.successes = 0;
35
43
  return false;
@@ -45,7 +53,7 @@ var CircuitBreaker = class {
45
53
  if (this.state === "half-open") {
46
54
  this.successes++;
47
55
  if (this.successes >= this.config.successThreshold) {
48
- this.logger.info("API recovered, circuit closed");
56
+ this.logger.info(this.label("API recovered, circuit closed"));
49
57
  this.reset();
50
58
  }
51
59
  } else if (this.state === "closed") {
@@ -59,13 +67,13 @@ var CircuitBreaker = class {
59
67
  this.failures++;
60
68
  this.lastFailureTime = Date.now();
61
69
  if (this.state === "half-open") {
62
- this.logger.warn("API still failing, circuit reopened");
70
+ this.logger.warn(this.label("API still failing, circuit reopened"));
63
71
  this.state = "open";
64
72
  return;
65
73
  }
66
74
  if (this.failures >= this.config.failureThreshold) {
67
75
  this.logger.warn(
68
- `Circuit opened after ${this.failures} failures. Scraper will continue without optimization.`
76
+ this.name ? `${this.name} circuit opened after ${this.failures} failures. ${this.name} calls are paused; recall and learn are unaffected.` : `Circuit opened after ${this.failures} failures. Scraper will continue without optimization.`
69
77
  );
70
78
  this.state = "open";
71
79
  }
@@ -430,7 +438,7 @@ var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
430
438
  var DEFAULT_TIMEOUT = 1500;
431
439
  var REPORT_RUN_TIMEOUT = 3e3;
432
440
  var DEFAULT_LEARN_TIMEOUT = 5e3;
433
- var BULK_RECALL_TIMEOUT = 3e3;
441
+ var BULK_RECALL_TIMEOUT = 1e4;
434
442
  var MAX_BULK_ITEMS = 90;
435
443
  var KEY_REJECTED_PAUSE_MS = 6e4;
436
444
  var BULK_RECALL_CONCURRENCY = 5;
@@ -439,7 +447,23 @@ var MAX_LEARN_DATA_BYTES = 100 * 1024;
439
447
  function isOutage(error) {
440
448
  return !(error instanceof ApiError && error.status >= 400 && error.status < 500);
441
449
  }
442
- var ASK_TIMEOUT = 1e4;
450
+ var LEARN_RETRY_BASE_MS = 1e3;
451
+ var LEARN_RETRY_MAX_MS = 5e3;
452
+ function learnRetryDelayMs(error, random = Math.random) {
453
+ const hinted = error instanceof ApiError && error.retryAfterSec !== void 0 ? error.retryAfterSec * 1e3 : LEARN_RETRY_BASE_MS;
454
+ const base = Math.min(Math.max(hinted, 0), LEARN_RETRY_MAX_MS);
455
+ return base / 2 + random() * (base / 2);
456
+ }
457
+ var DEFAULT_ASK_TIMEOUT = 6e4;
458
+ var MAX_TIMER_MS = 2147483647;
459
+ function resolveTimeout(value, fallback, name, logger) {
460
+ if (value === void 0 || value === null) return fallback;
461
+ if (typeof value === "number" && Number.isFinite(value) && value >= 1 && value <= MAX_TIMER_MS) {
462
+ return value;
463
+ }
464
+ logger.debug(`ignoring invalid ${name} (${String(value)}); using ${fallback}ms. Use 1-${MAX_TIMER_MS} ms.`);
465
+ return fallback;
466
+ }
443
467
  function clampBatch(batch, cap) {
444
468
  return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
445
469
  }
@@ -493,6 +517,7 @@ var FetchBrainClient = class {
493
517
  this.learnCapWarnedUntil = 0;
494
518
  /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
495
519
  this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
520
+ this.logger = createLogger(config.debug ? "debug" : "info", true);
496
521
  this.config = {
497
522
  apiKey: config.apiKey,
498
523
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
@@ -500,7 +525,8 @@ var FetchBrainClient = class {
500
525
  learning: config.learning ?? true,
501
526
  alwaysRun: config.alwaysRun ?? false,
502
527
  refreshOnRebuild: config.refreshOnRebuild ?? false,
503
- timeout: config.timeout || DEFAULT_TIMEOUT,
528
+ timeout: resolveTimeout(config.timeout, DEFAULT_TIMEOUT, "timeout", this.logger),
529
+ askTimeout: resolveTimeout(config.askTimeout, DEFAULT_ASK_TIMEOUT, "askTimeout", this.logger),
504
530
  debug: config.debug || false,
505
531
  extractForLearning: config.extractForLearning,
506
532
  learnUrlField: config.learnUrlField,
@@ -514,11 +540,12 @@ var FetchBrainClient = class {
514
540
  // enhance-only; stored so getConfig() round-trips
515
541
  onRecalled: config.onRecalled,
516
542
  // enhance-only; stored so getConfig() round-trips
543
+ logUrl: config.logUrl,
544
+ // enhance-only; stored so getConfig() round-trips
517
545
  scraper: config.scraper,
518
546
  changeDetection: config.changeDetection,
519
547
  reportRuns: config.reportRuns ?? true
520
548
  };
521
- this.logger = createLogger(this.config.debug ? "debug" : "info", true);
522
549
  const scraper = resolveScraperName(config.scraper);
523
550
  this.scraperName = scraper.name;
524
551
  for (const source of scraper.rejected) {
@@ -530,6 +557,11 @@ var FetchBrainClient = class {
530
557
  this.config.circuitBreaker,
531
558
  this.logger
532
559
  );
560
+ this.askCircuitBreaker = new CircuitBreaker(
561
+ this.config.circuitBreaker,
562
+ this.logger,
563
+ "Ask"
564
+ );
533
565
  this.batcher = new RequestBatcher(
534
566
  (items) => this.executeBatchQuery(items),
535
567
  clampBatch(this.config.batch, MAX_BULK_ITEMS),
@@ -590,6 +622,7 @@ var FetchBrainClient = class {
590
622
  chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
591
623
  }
592
624
  const chunkResults = new Array(chunks.length);
625
+ const outcome = { outage: false, success: false };
593
626
  let next = 0;
594
627
  const worker = async () => {
595
628
  while (next < chunks.length) {
@@ -601,7 +634,7 @@ var FetchBrainClient = class {
601
634
  }
602
635
  try {
603
636
  const items = chunk.map((request, i) => ({ ref: String(i), request }));
604
- const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
637
+ const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT, outcome);
605
638
  chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
606
639
  } catch {
607
640
  chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
@@ -611,6 +644,8 @@ var FetchBrainClient = class {
611
644
  await Promise.all(
612
645
  Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
613
646
  );
647
+ if (outcome.outage) this.circuitBreaker.recordFailure();
648
+ else if (outcome.success) this.circuitBreaker.recordSuccess();
614
649
  return chunkResults.flat();
615
650
  }
616
651
  /**
@@ -667,9 +702,12 @@ var FetchBrainClient = class {
667
702
  * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
668
703
  * credits), or "byok" to answer with your own linked provider model.
669
704
  * Omit it for the default model.
705
+ *
706
+ * `timeout` (ms, 1-2147483647) overrides the `askTimeout` option for this call;
707
+ * an invalid value falls back to `askTimeout`.
670
708
  */
671
709
  async ask(question, opts) {
672
- if (this.circuitBreaker.isOpen()) {
710
+ if (this.isKeyRejected() || this.askCircuitBreaker.isOpen()) {
673
711
  return { sources: [], status: "unavailable" };
674
712
  }
675
713
  const askBody = {
@@ -689,9 +727,9 @@ var FetchBrainClient = class {
689
727
  method: "POST",
690
728
  body: JSON.stringify(askBody)
691
729
  },
692
- ASK_TIMEOUT
730
+ resolveTimeout(opts?.timeout, this.config.askTimeout, "ask timeout", this.logger)
693
731
  );
694
- this.circuitBreaker.recordSuccess();
732
+ this.askCircuitBreaker.recordSuccess();
695
733
  return response;
696
734
  } catch (error) {
697
735
  if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
@@ -702,7 +740,7 @@ var FetchBrainClient = class {
702
740
  error: error.serverError ?? error.message
703
741
  };
704
742
  }
705
- this.circuitBreaker.recordFailure();
743
+ this.askCircuitBreaker.recordFailure();
706
744
  this.logger.debug("Ask request failed:", error);
707
745
  return { sources: [], status: "unavailable" };
708
746
  }
@@ -710,7 +748,7 @@ var FetchBrainClient = class {
710
748
  /**
711
749
  * Execute a batch query against the API
712
750
  */
713
- async executeBatchQuery(items, timeout) {
751
+ async executeBatchQuery(items, timeout, outcome) {
714
752
  const results = /* @__PURE__ */ new Map();
715
753
  const request = {
716
754
  items,
@@ -729,7 +767,8 @@ var FetchBrainClient = class {
729
767
  },
730
768
  timeout
731
769
  );
732
- this.circuitBreaker.recordSuccess();
770
+ if (outcome) outcome.success = true;
771
+ else this.circuitBreaker.recordSuccess();
733
772
  for (const item of response.known) {
734
773
  results.set(item.ref, { known: true, data: item.data });
735
774
  }
@@ -738,8 +777,9 @@ var FetchBrainClient = class {
738
777
  }
739
778
  return results;
740
779
  } catch (error) {
741
- if (isOutage(error)) this.circuitBreaker.recordFailure();
742
- else this.noteRefusal(error);
780
+ if (!isOutage(error)) this.noteRefusal(error);
781
+ else if (outcome) outcome.outage = true;
782
+ else this.circuitBreaker.recordFailure();
743
783
  throw error;
744
784
  }
745
785
  }
@@ -762,14 +802,7 @@ var FetchBrainClient = class {
762
802
  request.build = platformBuildId;
763
803
  }
764
804
  try {
765
- const response = await this.makeRequest(
766
- "/v1/learn",
767
- {
768
- method: "POST",
769
- body: JSON.stringify(request)
770
- },
771
- DEFAULT_LEARN_TIMEOUT
772
- );
805
+ const response = await this.sendLearnWithRetry(request);
773
806
  this.circuitBreaker.recordSuccess();
774
807
  try {
775
808
  this.accumulateChanges(response);
@@ -801,6 +834,28 @@ var FetchBrainClient = class {
801
834
  throw error;
802
835
  }
803
836
  }
837
+ /**
838
+ * POST one learn batch, retrying once after a jittered wait on a timeout,
839
+ * network error or 5xx. Learns run off the crawl's hot path, so a short
840
+ * stall is not an outage: in the 2026-11-28 load test one storage shard
841
+ * paused for ~5 s, the ~3 learns a run keeps in flight all timed out
842
+ * together, and that opened the breaker shared with recall. Only a batch
843
+ * that fails twice reaches executeBatchLearn's breaker accounting.
844
+ */
845
+ async sendLearnWithRetry(request) {
846
+ const send = () => this.makeRequest(
847
+ "/v1/learn",
848
+ { method: "POST", body: JSON.stringify(request) },
849
+ DEFAULT_LEARN_TIMEOUT
850
+ );
851
+ try {
852
+ return await send();
853
+ } catch (error) {
854
+ if (!isOutage(error)) throw error;
855
+ await new Promise((resolve) => setTimeout(resolve, learnRetryDelayMs(error)));
856
+ return send();
857
+ }
858
+ }
804
859
  /** Fold one batch response into the change totals (called once per HTTP batch). */
805
860
  accumulateChanges(response) {
806
861
  const stats = this.changeStats;
@@ -859,6 +914,18 @@ var FetchBrainClient = class {
859
914
  () => controller.abort(),
860
915
  timeout ?? this.config.timeout
861
916
  );
917
+ const aborted = new Promise((_, reject) => {
918
+ const fail = () => reject(new DOMException("FetchBrain request timed out", "AbortError"));
919
+ if (controller.signal.aborted) fail();
920
+ else controller.signal.addEventListener("abort", fail, { once: true });
921
+ });
922
+ aborted.catch(() => {
923
+ });
924
+ const readBody = (response, read) => Promise.race([read(response), aborted]).catch((err) => {
925
+ response.body?.cancel().catch(() => {
926
+ });
927
+ throw err;
928
+ });
862
929
  const contextHeaders = {
863
930
  "X-FB-SDK": "js",
864
931
  "X-FB-Node": process.version || "unknown",
@@ -892,7 +959,7 @@ var FetchBrainClient = class {
892
959
  let serverError;
893
960
  let code;
894
961
  try {
895
- const errBody = await response.json();
962
+ const errBody = await readBody(response, (r) => r.json());
896
963
  if (typeof errBody.error === "string") serverError = errBody.error;
897
964
  const specific = errBody.details?.code ?? errBody.code;
898
965
  if (typeof specific === "string") code = specific;
@@ -906,7 +973,7 @@ var FetchBrainClient = class {
906
973
  parseRetryAfter(response.headers.get("Retry-After"))
907
974
  );
908
975
  }
909
- return await response.json();
976
+ return await readBody(response, (r) => r.json());
910
977
  } finally {
911
978
  clearTimeout(timeoutId);
912
979
  }
@@ -928,6 +995,7 @@ var FetchBrainClient = class {
928
995
  */
929
996
  resetCircuit() {
930
997
  this.circuitBreaker.reset();
998
+ this.askCircuitBreaker.reset();
931
999
  }
932
1000
  /**
933
1001
  * Clear pending batched requests
@@ -1159,7 +1227,12 @@ function safeChangeStats(client) {
1159
1227
  }
1160
1228
  }
1161
1229
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
1162
- var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
1230
+ var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set([
1231
+ "fetchBrainRecalled",
1232
+ "fetchBrainData",
1233
+ "__fetchBrainResult",
1234
+ "__fetchBrainCounted"
1235
+ ]);
1163
1236
  var MAX_STASH_ENTRIES = 5e3;
1164
1237
  var MAX_STASH_BYTES = 256 * 1024 * 1024;
1165
1238
  var stashBytesCap = MAX_STASH_BYTES;
@@ -1198,12 +1271,32 @@ function buildRawRequest(request) {
1198
1271
  if (typeof r.payload === "string") body = r.payload;
1199
1272
  return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: labelText(r.label) };
1200
1273
  }
1201
- function warnDefaultUniqueKey(request, logger, warned) {
1274
+ function logUrlFor(request, logUrl) {
1275
+ if (!logUrl) return request.url;
1276
+ try {
1277
+ const shown = logUrl({
1278
+ url: request.url,
1279
+ uniqueKey: request.uniqueKey ?? request.url,
1280
+ label: labelText(request.label),
1281
+ userData: request.userData ?? {}
1282
+ });
1283
+ if (shown && typeof shown.then === "function") {
1284
+ Promise.resolve(shown).catch(() => {
1285
+ });
1286
+ return void 0;
1287
+ }
1288
+ return typeof shown === "string" && shown !== "" ? shown : void 0;
1289
+ } catch {
1290
+ return void 0;
1291
+ }
1292
+ }
1293
+ var urlSuffix = (shown) => shown ? `: ${shown}` : "";
1294
+ function warnDefaultUniqueKey(request, logger, warned, shownUrl) {
1202
1295
  const method = (request.method ?? "GET").toUpperCase();
1203
1296
  const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
1204
1297
  if (method !== "GET" && isDefault && !warned.has(request.url)) {
1205
1298
  warned.add(request.url);
1206
- logger.warn(`FetchBrain: ${method} ${request.url} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't get their own memory.`);
1299
+ logger.warn(`FetchBrain: ${method} ${shownUrl() ?? "request"} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't get their own memory.`);
1207
1300
  }
1208
1301
  }
1209
1302
  var asyncContext = new AsyncLocalStorage();
@@ -1278,6 +1371,10 @@ var FetchBrain = class {
1278
1371
  recalled: 0,
1279
1372
  aiSkipped: 0,
1280
1373
  // brain knew + skipped scraping
1374
+ requestsSkipped: 0,
1375
+ // recalled without a fetch (pre-recalled at enqueue + skipNavigation)
1376
+ lateRecalls: 0,
1377
+ // recalled after the page was already fetched
1281
1378
  learned: 0,
1282
1379
  scraped: 0,
1283
1380
  // Actually ran handler
@@ -1356,7 +1453,9 @@ var FetchBrain = class {
1356
1453
  runStats.totalRequests++;
1357
1454
  if (skipLabels && skipLabels.has(label || "default")) {
1358
1455
  runStats.bypassed++;
1359
- logger.debug(`Bypassing FetchBrain for [${label || "default"}]: ${url}`);
1456
+ if (config.debug) {
1457
+ logger.debug(`Bypassing FetchBrain for [${label || "default"}]${urlSuffix(logUrlFor(buildRawRequest(request), config.logUrl))}`);
1458
+ }
1360
1459
  await originalHandler.call(crawler, context);
1361
1460
  return;
1362
1461
  }
@@ -1366,7 +1465,9 @@ var FetchBrain = class {
1366
1465
  url
1367
1466
  });
1368
1467
  const rawRequest = buildRawRequest(request);
1369
- warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
1468
+ let shown;
1469
+ const shownUrl = () => (shown ?? (shown = { text: logUrlFor(rawRequest, config.logUrl) })).text;
1470
+ warnDefaultUniqueKey(rawRequest, logger, warnedKeys, shownUrl);
1370
1471
  let consumedStash;
1371
1472
  try {
1372
1473
  const preRecalled = request.userData?.__fetchBrainResult;
@@ -1387,13 +1488,13 @@ var FetchBrain = class {
1387
1488
  if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
1388
1489
  if (aiResult.fallback) {
1389
1490
  throw new Error(
1390
- `FetchBrain: ${url} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
1491
+ `FetchBrain: ${shownUrl() ?? "a request"} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
1391
1492
  );
1392
1493
  }
1393
1494
  runStats.dropped++;
1394
1495
  request.noRetry = true;
1395
1496
  throw new Error(
1396
- `FetchBrain: ${url} skipped its fetch at enqueue time but its remembered data is no longer available \u2014 failing without retries; it will be re-scraped on a future run.`
1497
+ `FetchBrain: ${shownUrl() ?? "a request"} skipped its fetch at enqueue time but its remembered data is no longer available \u2014 failing without retries; it will be re-scraped on a future run.`
1397
1498
  );
1398
1499
  }
1399
1500
  let usedAIData = false;
@@ -1419,7 +1520,7 @@ var FetchBrain = class {
1419
1520
  if (aiResult.known && aiResult.data && originalPushData) {
1420
1521
  usedAIData = true;
1421
1522
  await originalPushData.call(context, aiResult.data);
1422
- logger.info(`Used brain data: ${url}`);
1523
+ if (config.debug) logger.debug(`Used brain data${urlSuffix(shownUrl())}`);
1423
1524
  await fireOnRecalled(aiResult.data);
1424
1525
  }
1425
1526
  }
@@ -1432,25 +1533,36 @@ var FetchBrain = class {
1432
1533
  const handlerLabel = request.label;
1433
1534
  const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
1434
1535
  if (aiResult.known && aiResult.data && !runHandler) {
1435
- runStats.recalled++;
1436
- runStats.aiSkipped++;
1437
- logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
1536
+ if (config.debug) logger.debug(`Recalled${urlSuffix(shownUrl())} [${handlerLabel || "default"}]`);
1438
1537
  if (originalPushData) {
1439
1538
  await originalPushData.call(context, aiResult.data);
1440
1539
  }
1540
+ try {
1541
+ if (!request.userData?.__fetchBrainCounted) {
1542
+ request.userData = { ...request.userData, __fetchBrainCounted: true };
1543
+ runStats.recalled++;
1544
+ runStats.aiSkipped++;
1545
+ const skippedNav = request.skipNavigation === true;
1546
+ if (preRecalled?.known && skippedNav) {
1547
+ runStats.requestsSkipped++;
1548
+ } else if (!skippedNav) {
1549
+ runStats.lateRecalls++;
1550
+ }
1551
+ }
1552
+ } catch (countErr) {
1553
+ logger.debug(`Run stats skipped: ${countErr}`);
1554
+ }
1441
1555
  await fireOnRecalled(aiResult.data);
1442
1556
  return;
1443
1557
  }
1444
- runStats.scraped++;
1445
1558
  const counts = labelCounts(request.label);
1446
1559
  if (counts) counts.scraped++;
1447
1560
  if (aiResult.known) {
1448
- runStats.recalled++;
1449
- logger.info(
1450
- `Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
1451
- );
1452
- } else {
1453
- logger.debug(`Learning: ${url}`);
1561
+ if (config.debug) {
1562
+ logger.debug(`Running handler [${handlerLabel || "default"}] with recalled data available${urlSuffix(shownUrl())}`);
1563
+ }
1564
+ } else if (config.debug) {
1565
+ logger.debug(`Learning${urlSuffix(shownUrl())}`);
1454
1566
  }
1455
1567
  const learnItems = [];
1456
1568
  if (originalPushData && config.learning !== false) {
@@ -1477,6 +1589,15 @@ var FetchBrain = class {
1477
1589
  if (counts) counts.failed++;
1478
1590
  throw handlerErr;
1479
1591
  }
1592
+ try {
1593
+ if (!request.userData?.__fetchBrainCounted) {
1594
+ request.userData = { ...request.userData, __fetchBrainCounted: true };
1595
+ runStats.scraped++;
1596
+ if (aiResult.known) runStats.recalled++;
1597
+ }
1598
+ } catch (countErr) {
1599
+ logger.debug(`Run stats skipped: ${countErr}`);
1600
+ }
1480
1601
  if (counts && learnItems.length === 0 && originalPushData && config.learning !== false && !usedAIData && (!aiResult.known || relearn)) {
1481
1602
  counts.empty++;
1482
1603
  }
@@ -1574,7 +1695,17 @@ var FetchBrain = class {
1574
1695
  runStats.startTime = Date.now();
1575
1696
  const runStartedAt = new Date(runStats.startTime).toISOString();
1576
1697
  labelStats.clear();
1577
- const runBase = { scraped: runStats.scraped, learned: runStats.learned, recalled: runStats.recalled };
1698
+ const runBase = {
1699
+ totalRequests: runStats.totalRequests,
1700
+ bypassed: runStats.bypassed,
1701
+ dropped: runStats.dropped,
1702
+ scraped: runStats.scraped,
1703
+ learned: runStats.learned,
1704
+ recalled: runStats.recalled,
1705
+ aiSkipped: runStats.aiSkipped,
1706
+ requestsSkipped: runStats.requestsSkipped,
1707
+ lateRecalls: runStats.lateRecalls
1708
+ };
1578
1709
  const changeBase = safeChangeStats(client);
1579
1710
  const runId = nextRunId();
1580
1711
  try {
@@ -1591,8 +1722,19 @@ var FetchBrain = class {
1591
1722
  const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
1592
1723
  1
1593
1724
  );
1594
- const managedRequests = runStats.totalRequests - runStats.bypassed;
1595
- const savingsPercent = managedRequests > 0 ? (runStats.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1725
+ const run = {
1726
+ totalRequests: runStats.totalRequests - runBase.totalRequests,
1727
+ bypassed: runStats.bypassed - runBase.bypassed,
1728
+ dropped: runStats.dropped - runBase.dropped,
1729
+ scraped: runStats.scraped - runBase.scraped,
1730
+ learned: runStats.learned - runBase.learned,
1731
+ recalled: runStats.recalled - runBase.recalled,
1732
+ aiSkipped: runStats.aiSkipped - runBase.aiSkipped,
1733
+ requestsSkipped: runStats.requestsSkipped - runBase.requestsSkipped,
1734
+ lateRecalls: runStats.lateRecalls - runBase.lateRecalls
1735
+ };
1736
+ const managedRequests = run.totalRequests - run.bypassed;
1737
+ const savingsPercent = managedRequests > 0 ? (run.aiSkipped / managedRequests * 100).toFixed(1) : "0";
1596
1738
  let changes = { changed: 0, drift: [] };
1597
1739
  try {
1598
1740
  const now = safeChangeStats(client);
@@ -1607,8 +1749,13 @@ var FetchBrain = class {
1607
1749
  }
1608
1750
  const showChanged = config.changeDetection?.enabled === true || changes.changed > 0;
1609
1751
  logger.info(
1610
- `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${managedRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}` + (skipLabels ? `, bypassed: ${runStats.bypassed}` : "") + (runStats.dropped ? `, dropped: ${runStats.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
1752
+ `\u{1F9E0} Finished! recalled: ${run.recalled}/${managedRequests} (${savingsPercent}%), requests skipped: ${run.requestsSkipped}, learned: ${run.learned}, scraped: ${run.scraped}` + (skipLabels ? `, bypassed: ${run.bypassed}` : "") + (run.dropped ? `, dropped: ${run.dropped}` : "") + (showChanged ? `, changed: ${changes.changed}` : "") + `, duration: ${duration}s`
1611
1753
  );
1754
+ if (run.lateRecalls > 0 && !crawlerAny.retryOnBlocked && config.preRecall !== false) {
1755
+ logger.info(
1756
+ `${run.lateRecalls} ${run.lateRecalls === 1 ? "page was" : "pages were"} recalled after ${run.lateRecalls === 1 ? "it was" : "they were"} fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).`
1757
+ );
1758
+ }
1612
1759
  for (const item of changes.drift) {
1613
1760
  try {
1614
1761
  logger.warn(describeDrift(item));
@@ -1624,9 +1771,12 @@ var FetchBrain = class {
1624
1771
  build: config.refreshOnRebuild ? getPlatformBuildId() : void 0,
1625
1772
  startedAt: runStartedAt,
1626
1773
  endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1627
- scraped: runStats.scraped - runBase.scraped,
1628
- learned: runStats.learned - runBase.learned,
1629
- recalled: runStats.recalled - runBase.recalled,
1774
+ scraped: run.scraped,
1775
+ learned: run.learned,
1776
+ recalled: run.recalled,
1777
+ requestsSkipped: run.requestsSkipped,
1778
+ lateRecalls: run.lateRecalls,
1779
+ bypassed: run.bypassed,
1630
1780
  labels
1631
1781
  });
1632
1782
  for (const flag of Array.isArray(flags) ? flags : []) {
@@ -1659,10 +1809,11 @@ var FetchBrain = class {
1659
1809
  const r = slice[i];
1660
1810
  if (!r || typeof r.url !== "string") continue;
1661
1811
  const prior = r.userData?.__fetchBrainResult;
1662
- if (prior) {
1663
- if (prior.known && r.skipNavigation) r.skipNavigation = false;
1812
+ if (prior || r.userData?.__fetchBrainCounted) {
1813
+ if (prior?.known && r.skipNavigation) r.skipNavigation = false;
1664
1814
  const rest = { ...r.userData };
1665
1815
  delete rest.__fetchBrainResult;
1816
+ delete rest.__fetchBrainCounted;
1666
1817
  r.userData = rest;
1667
1818
  }
1668
1819
  if (r.skipNavigation) continue;