@fetchbrain.com/sdk 0.9.0 → 0.11.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.js CHANGED
@@ -13,13 +13,21 @@ var DEFAULT_CONFIG = {
13
13
  successThreshold: 1
14
14
  };
15
15
  var CircuitBreaker = class {
16
- constructor(config = {}, logger) {
16
+ /**
17
+ * `name` labels this breaker's log lines when a client runs more than one
18
+ * (the ask breaker opening must not read as if recall and learn stopped).
19
+ */
20
+ constructor(config = {}, logger, name) {
17
21
  this.state = "closed";
18
22
  this.failures = 0;
19
23
  this.successes = 0;
20
24
  this.lastFailureTime = 0;
21
25
  this.config = { ...DEFAULT_CONFIG, ...config };
22
26
  this.logger = logger;
27
+ this.name = name;
28
+ }
29
+ label(message) {
30
+ return this.name ? `${this.name} circuit: ${message}` : message;
23
31
  }
24
32
  /**
25
33
  * Check if requests should be allowed through
@@ -31,7 +39,7 @@ var CircuitBreaker = class {
31
39
  if (this.state === "open") {
32
40
  const now = Date.now();
33
41
  if (now - this.lastFailureTime >= this.config.resetTimeout) {
34
- this.logger.info("Circuit transitioning to half-open, testing API...");
42
+ this.logger.info(this.label("Circuit transitioning to half-open, testing API..."));
35
43
  this.state = "half-open";
36
44
  this.successes = 0;
37
45
  return false;
@@ -47,7 +55,7 @@ var CircuitBreaker = class {
47
55
  if (this.state === "half-open") {
48
56
  this.successes++;
49
57
  if (this.successes >= this.config.successThreshold) {
50
- this.logger.info("API recovered, circuit closed");
58
+ this.logger.info(this.label("API recovered, circuit closed"));
51
59
  this.reset();
52
60
  }
53
61
  } else if (this.state === "closed") {
@@ -61,13 +69,13 @@ var CircuitBreaker = class {
61
69
  this.failures++;
62
70
  this.lastFailureTime = Date.now();
63
71
  if (this.state === "half-open") {
64
- this.logger.warn("API still failing, circuit reopened");
72
+ this.logger.warn(this.label("API still failing, circuit reopened"));
65
73
  this.state = "open";
66
74
  return;
67
75
  }
68
76
  if (this.failures >= this.config.failureThreshold) {
69
77
  this.logger.warn(
70
- `Circuit opened after ${this.failures} failures. Scraper will continue without optimization.`
78
+ 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.`
71
79
  );
72
80
  this.state = "open";
73
81
  }
@@ -432,7 +440,7 @@ var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
432
440
  var DEFAULT_TIMEOUT = 1500;
433
441
  var REPORT_RUN_TIMEOUT = 3e3;
434
442
  var DEFAULT_LEARN_TIMEOUT = 5e3;
435
- var BULK_RECALL_TIMEOUT = 3e3;
443
+ var BULK_RECALL_TIMEOUT = 1e4;
436
444
  var MAX_BULK_ITEMS = 90;
437
445
  var KEY_REJECTED_PAUSE_MS = 6e4;
438
446
  var BULK_RECALL_CONCURRENCY = 5;
@@ -441,7 +449,23 @@ var MAX_LEARN_DATA_BYTES = 100 * 1024;
441
449
  function isOutage(error) {
442
450
  return !(error instanceof ApiError && error.status >= 400 && error.status < 500);
443
451
  }
444
- var ASK_TIMEOUT = 1e4;
452
+ var LEARN_RETRY_BASE_MS = 1e3;
453
+ var LEARN_RETRY_MAX_MS = 5e3;
454
+ function learnRetryDelayMs(error, random = Math.random) {
455
+ const hinted = error instanceof ApiError && error.retryAfterSec !== void 0 ? error.retryAfterSec * 1e3 : LEARN_RETRY_BASE_MS;
456
+ const base = Math.min(Math.max(hinted, 0), LEARN_RETRY_MAX_MS);
457
+ return base / 2 + random() * (base / 2);
458
+ }
459
+ var DEFAULT_ASK_TIMEOUT = 6e4;
460
+ var MAX_TIMER_MS = 2147483647;
461
+ function resolveTimeout(value, fallback, name, logger) {
462
+ if (value === void 0 || value === null) return fallback;
463
+ if (typeof value === "number" && Number.isFinite(value) && value >= 1 && value <= MAX_TIMER_MS) {
464
+ return value;
465
+ }
466
+ logger.debug(`ignoring invalid ${name} (${String(value)}); using ${fallback}ms. Use 1-${MAX_TIMER_MS} ms.`);
467
+ return fallback;
468
+ }
445
469
  function clampBatch(batch, cap) {
446
470
  return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
447
471
  }
@@ -495,6 +519,7 @@ var FetchBrainClient = class {
495
519
  this.learnCapWarnedUntil = 0;
496
520
  /** Change counts, accumulated once per learn HTTP batch (never per learn() promise). */
497
521
  this.changeStats = { changed: 0, unchanged: 0, firstSeen: 0, drift: [] };
522
+ this.logger = createLogger(config.debug ? "debug" : "info", true);
498
523
  this.config = {
499
524
  apiKey: config.apiKey,
500
525
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
@@ -502,7 +527,8 @@ var FetchBrainClient = class {
502
527
  learning: config.learning ?? true,
503
528
  alwaysRun: config.alwaysRun ?? false,
504
529
  refreshOnRebuild: config.refreshOnRebuild ?? false,
505
- timeout: config.timeout || DEFAULT_TIMEOUT,
530
+ timeout: resolveTimeout(config.timeout, DEFAULT_TIMEOUT, "timeout", this.logger),
531
+ askTimeout: resolveTimeout(config.askTimeout, DEFAULT_ASK_TIMEOUT, "askTimeout", this.logger),
506
532
  debug: config.debug || false,
507
533
  extractForLearning: config.extractForLearning,
508
534
  learnUrlField: config.learnUrlField,
@@ -516,11 +542,12 @@ var FetchBrainClient = class {
516
542
  // enhance-only; stored so getConfig() round-trips
517
543
  onRecalled: config.onRecalled,
518
544
  // enhance-only; stored so getConfig() round-trips
545
+ logUrl: config.logUrl,
546
+ // enhance-only; stored so getConfig() round-trips
519
547
  scraper: config.scraper,
520
548
  changeDetection: config.changeDetection,
521
549
  reportRuns: config.reportRuns ?? true
522
550
  };
523
- this.logger = createLogger(this.config.debug ? "debug" : "info", true);
524
551
  const scraper = resolveScraperName(config.scraper);
525
552
  this.scraperName = scraper.name;
526
553
  for (const source of scraper.rejected) {
@@ -532,6 +559,11 @@ var FetchBrainClient = class {
532
559
  this.config.circuitBreaker,
533
560
  this.logger
534
561
  );
562
+ this.askCircuitBreaker = new CircuitBreaker(
563
+ this.config.circuitBreaker,
564
+ this.logger,
565
+ "Ask"
566
+ );
535
567
  this.batcher = new RequestBatcher(
536
568
  (items) => this.executeBatchQuery(items),
537
569
  clampBatch(this.config.batch, MAX_BULK_ITEMS),
@@ -592,6 +624,7 @@ var FetchBrainClient = class {
592
624
  chunks.push(requests.slice(start, start + MAX_BULK_ITEMS));
593
625
  }
594
626
  const chunkResults = new Array(chunks.length);
627
+ const outcome = { outage: false, success: false };
595
628
  let next = 0;
596
629
  const worker = async () => {
597
630
  while (next < chunks.length) {
@@ -603,7 +636,7 @@ var FetchBrainClient = class {
603
636
  }
604
637
  try {
605
638
  const items = chunk.map((request, i) => ({ ref: String(i), request }));
606
- const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT);
639
+ const resultMap = await this.executeBatchQuery(items, BULK_RECALL_TIMEOUT, outcome);
607
640
  chunkResults[idx] = items.map((i) => resultMap.get(i.ref) ?? { known: false });
608
641
  } catch {
609
642
  chunkResults[idx] = chunk.map(() => ({ known: false, fallback: true }));
@@ -613,6 +646,8 @@ var FetchBrainClient = class {
613
646
  await Promise.all(
614
647
  Array.from({ length: Math.min(BULK_RECALL_CONCURRENCY, chunks.length) }, worker)
615
648
  );
649
+ if (outcome.outage) this.circuitBreaker.recordFailure();
650
+ else if (outcome.success) this.circuitBreaker.recordSuccess();
616
651
  return chunkResults.flat();
617
652
  }
618
653
  /**
@@ -666,12 +701,15 @@ var FetchBrainClient = class {
666
701
  * Ask a natural-language question, answered from everything the account has learned
667
702
  *
668
703
  * `model` picks the generation model for answer mode from the server's
669
- * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
704
+ * menu (e.g. "llama-3.3-70b", "glm-5.3" — larger models use more Ask
670
705
  * credits), or "byok" to answer with your own linked provider model.
671
706
  * Omit it for the default model.
707
+ *
708
+ * `timeout` (ms, 1-2147483647) overrides the `askTimeout` option for this call;
709
+ * an invalid value falls back to `askTimeout`.
672
710
  */
673
711
  async ask(question, opts) {
674
- if (this.circuitBreaker.isOpen()) {
712
+ if (this.isKeyRejected() || this.askCircuitBreaker.isOpen()) {
675
713
  return { sources: [], status: "unavailable" };
676
714
  }
677
715
  const askBody = {
@@ -691,9 +729,9 @@ var FetchBrainClient = class {
691
729
  method: "POST",
692
730
  body: JSON.stringify(askBody)
693
731
  },
694
- ASK_TIMEOUT
732
+ resolveTimeout(opts?.timeout, this.config.askTimeout, "ask timeout", this.logger)
695
733
  );
696
- this.circuitBreaker.recordSuccess();
734
+ this.askCircuitBreaker.recordSuccess();
697
735
  return response;
698
736
  } catch (error) {
699
737
  if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
@@ -704,7 +742,7 @@ var FetchBrainClient = class {
704
742
  error: error.serverError ?? error.message
705
743
  };
706
744
  }
707
- this.circuitBreaker.recordFailure();
745
+ this.askCircuitBreaker.recordFailure();
708
746
  this.logger.debug("Ask request failed:", error);
709
747
  return { sources: [], status: "unavailable" };
710
748
  }
@@ -712,7 +750,7 @@ var FetchBrainClient = class {
712
750
  /**
713
751
  * Execute a batch query against the API
714
752
  */
715
- async executeBatchQuery(items, timeout) {
753
+ async executeBatchQuery(items, timeout, outcome) {
716
754
  const results = /* @__PURE__ */ new Map();
717
755
  const request = {
718
756
  items,
@@ -731,7 +769,8 @@ var FetchBrainClient = class {
731
769
  },
732
770
  timeout
733
771
  );
734
- this.circuitBreaker.recordSuccess();
772
+ if (outcome) outcome.success = true;
773
+ else this.circuitBreaker.recordSuccess();
735
774
  for (const item of response.known) {
736
775
  results.set(item.ref, { known: true, data: item.data });
737
776
  }
@@ -740,8 +779,9 @@ var FetchBrainClient = class {
740
779
  }
741
780
  return results;
742
781
  } catch (error) {
743
- if (isOutage(error)) this.circuitBreaker.recordFailure();
744
- else this.noteRefusal(error);
782
+ if (!isOutage(error)) this.noteRefusal(error);
783
+ else if (outcome) outcome.outage = true;
784
+ else this.circuitBreaker.recordFailure();
745
785
  throw error;
746
786
  }
747
787
  }
@@ -764,14 +804,7 @@ var FetchBrainClient = class {
764
804
  request.build = platformBuildId;
765
805
  }
766
806
  try {
767
- const response = await this.makeRequest(
768
- "/v1/learn",
769
- {
770
- method: "POST",
771
- body: JSON.stringify(request)
772
- },
773
- DEFAULT_LEARN_TIMEOUT
774
- );
807
+ const response = await this.sendLearnWithRetry(request);
775
808
  this.circuitBreaker.recordSuccess();
776
809
  try {
777
810
  this.accumulateChanges(response);
@@ -803,6 +836,28 @@ var FetchBrainClient = class {
803
836
  throw error;
804
837
  }
805
838
  }
839
+ /**
840
+ * POST one learn batch, retrying once after a jittered wait on a timeout,
841
+ * network error or 5xx. Learns run off the crawl's hot path, so a short
842
+ * stall is not an outage: in the 2026-11-28 load test one storage shard
843
+ * paused for ~5 s, the ~3 learns a run keeps in flight all timed out
844
+ * together, and that opened the breaker shared with recall. Only a batch
845
+ * that fails twice reaches executeBatchLearn's breaker accounting.
846
+ */
847
+ async sendLearnWithRetry(request) {
848
+ const send = () => this.makeRequest(
849
+ "/v1/learn",
850
+ { method: "POST", body: JSON.stringify(request) },
851
+ DEFAULT_LEARN_TIMEOUT
852
+ );
853
+ try {
854
+ return await send();
855
+ } catch (error) {
856
+ if (!isOutage(error)) throw error;
857
+ await new Promise((resolve) => setTimeout(resolve, learnRetryDelayMs(error)));
858
+ return send();
859
+ }
860
+ }
806
861
  /** Fold one batch response into the change totals (called once per HTTP batch). */
807
862
  accumulateChanges(response) {
808
863
  const stats = this.changeStats;
@@ -861,6 +916,18 @@ var FetchBrainClient = class {
861
916
  () => controller.abort(),
862
917
  timeout ?? this.config.timeout
863
918
  );
919
+ const aborted = new Promise((_, reject) => {
920
+ const fail = () => reject(new DOMException("FetchBrain request timed out", "AbortError"));
921
+ if (controller.signal.aborted) fail();
922
+ else controller.signal.addEventListener("abort", fail, { once: true });
923
+ });
924
+ aborted.catch(() => {
925
+ });
926
+ const readBody = (response, read) => Promise.race([read(response), aborted]).catch((err) => {
927
+ response.body?.cancel().catch(() => {
928
+ });
929
+ throw err;
930
+ });
864
931
  const contextHeaders = {
865
932
  "X-FB-SDK": "js",
866
933
  "X-FB-Node": process.version || "unknown",
@@ -894,7 +961,7 @@ var FetchBrainClient = class {
894
961
  let serverError;
895
962
  let code;
896
963
  try {
897
- const errBody = await response.json();
964
+ const errBody = await readBody(response, (r) => r.json());
898
965
  if (typeof errBody.error === "string") serverError = errBody.error;
899
966
  const specific = errBody.details?.code ?? errBody.code;
900
967
  if (typeof specific === "string") code = specific;
@@ -908,7 +975,7 @@ var FetchBrainClient = class {
908
975
  parseRetryAfter(response.headers.get("Retry-After"))
909
976
  );
910
977
  }
911
- return await response.json();
978
+ return await readBody(response, (r) => r.json());
912
979
  } finally {
913
980
  clearTimeout(timeoutId);
914
981
  }
@@ -930,6 +997,7 @@ var FetchBrainClient = class {
930
997
  */
931
998
  resetCircuit() {
932
999
  this.circuitBreaker.reset();
1000
+ this.askCircuitBreaker.reset();
933
1001
  }
934
1002
  /**
935
1003
  * Clear pending batched requests
@@ -1205,12 +1273,32 @@ function buildRawRequest(request) {
1205
1273
  if (typeof r.payload === "string") body = r.payload;
1206
1274
  return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: labelText(r.label) };
1207
1275
  }
1208
- function warnDefaultUniqueKey(request, logger, warned) {
1276
+ function logUrlFor(request, logUrl) {
1277
+ if (!logUrl) return request.url;
1278
+ try {
1279
+ const shown = logUrl({
1280
+ url: request.url,
1281
+ uniqueKey: request.uniqueKey ?? request.url,
1282
+ label: labelText(request.label),
1283
+ userData: request.userData ?? {}
1284
+ });
1285
+ if (shown && typeof shown.then === "function") {
1286
+ Promise.resolve(shown).catch(() => {
1287
+ });
1288
+ return void 0;
1289
+ }
1290
+ return typeof shown === "string" && shown !== "" ? shown : void 0;
1291
+ } catch {
1292
+ return void 0;
1293
+ }
1294
+ }
1295
+ var urlSuffix = (shown) => shown ? `: ${shown}` : "";
1296
+ function warnDefaultUniqueKey(request, logger, warned, shownUrl) {
1209
1297
  const method = (request.method ?? "GET").toUpperCase();
1210
1298
  const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
1211
1299
  if (method !== "GET" && isDefault && !warned.has(request.url)) {
1212
1300
  warned.add(request.url);
1213
- 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.`);
1301
+ 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.`);
1214
1302
  }
1215
1303
  }
1216
1304
  var asyncContext = new async_hooks.AsyncLocalStorage();
@@ -1367,7 +1455,9 @@ var FetchBrain = class {
1367
1455
  runStats.totalRequests++;
1368
1456
  if (skipLabels && skipLabels.has(label || "default")) {
1369
1457
  runStats.bypassed++;
1370
- logger.debug(`Bypassing FetchBrain for [${label || "default"}]: ${url}`);
1458
+ if (config.debug) {
1459
+ logger.debug(`Bypassing FetchBrain for [${label || "default"}]${urlSuffix(logUrlFor(buildRawRequest(request), config.logUrl))}`);
1460
+ }
1371
1461
  await originalHandler.call(crawler, context);
1372
1462
  return;
1373
1463
  }
@@ -1377,7 +1467,9 @@ var FetchBrain = class {
1377
1467
  url
1378
1468
  });
1379
1469
  const rawRequest = buildRawRequest(request);
1380
- warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
1470
+ let shown;
1471
+ const shownUrl = () => (shown ?? (shown = { text: logUrlFor(rawRequest, config.logUrl) })).text;
1472
+ warnDefaultUniqueKey(rawRequest, logger, warnedKeys, shownUrl);
1381
1473
  let consumedStash;
1382
1474
  try {
1383
1475
  const preRecalled = request.userData?.__fetchBrainResult;
@@ -1398,13 +1490,13 @@ var FetchBrain = class {
1398
1490
  if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
1399
1491
  if (aiResult.fallback) {
1400
1492
  throw new Error(
1401
- `FetchBrain: ${url} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
1493
+ `FetchBrain: ${shownUrl() ?? "a request"} skipped its fetch at enqueue time and its remembered data could not be restored (API unreachable) \u2014 retrying.`
1402
1494
  );
1403
1495
  }
1404
1496
  runStats.dropped++;
1405
1497
  request.noRetry = true;
1406
1498
  throw new Error(
1407
- `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.`
1499
+ `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.`
1408
1500
  );
1409
1501
  }
1410
1502
  let usedAIData = false;
@@ -1430,7 +1522,7 @@ var FetchBrain = class {
1430
1522
  if (aiResult.known && aiResult.data && originalPushData) {
1431
1523
  usedAIData = true;
1432
1524
  await originalPushData.call(context, aiResult.data);
1433
- logger.info(`Used brain data: ${url}`);
1525
+ if (config.debug) logger.debug(`Used brain data${urlSuffix(shownUrl())}`);
1434
1526
  await fireOnRecalled(aiResult.data);
1435
1527
  }
1436
1528
  }
@@ -1443,7 +1535,7 @@ var FetchBrain = class {
1443
1535
  const handlerLabel = request.label;
1444
1536
  const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
1445
1537
  if (aiResult.known && aiResult.data && !runHandler) {
1446
- logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
1538
+ if (config.debug) logger.debug(`Recalled${urlSuffix(shownUrl())} [${handlerLabel || "default"}]`);
1447
1539
  if (originalPushData) {
1448
1540
  await originalPushData.call(context, aiResult.data);
1449
1541
  }
@@ -1468,11 +1560,11 @@ var FetchBrain = class {
1468
1560
  const counts = labelCounts(request.label);
1469
1561
  if (counts) counts.scraped++;
1470
1562
  if (aiResult.known) {
1471
- logger.info(
1472
- `Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
1473
- );
1474
- } else {
1475
- logger.debug(`Learning: ${url}`);
1563
+ if (config.debug) {
1564
+ logger.debug(`Running handler [${handlerLabel || "default"}] with recalled data available${urlSuffix(shownUrl())}`);
1565
+ }
1566
+ } else if (config.debug) {
1567
+ logger.debug(`Learning${urlSuffix(shownUrl())}`);
1476
1568
  }
1477
1569
  const learnItems = [];
1478
1570
  if (originalPushData && config.learning !== false) {