@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.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
  /**
@@ -664,12 +699,15 @@ var FetchBrainClient = class {
664
699
  * Ask a natural-language question, answered from everything the account has learned
665
700
  *
666
701
  * `model` picks the generation model for answer mode from the server's
667
- * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
702
+ * menu (e.g. "llama-3.3-70b", "glm-5.3" — larger models use more 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
@@ -1203,12 +1271,32 @@ function buildRawRequest(request) {
1203
1271
  if (typeof r.payload === "string") body = r.payload;
1204
1272
  return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: labelText(r.label) };
1205
1273
  }
1206
- 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) {
1207
1295
  const method = (request.method ?? "GET").toUpperCase();
1208
1296
  const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
1209
1297
  if (method !== "GET" && isDefault && !warned.has(request.url)) {
1210
1298
  warned.add(request.url);
1211
- 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.`);
1212
1300
  }
1213
1301
  }
1214
1302
  var asyncContext = new AsyncLocalStorage();
@@ -1365,7 +1453,9 @@ var FetchBrain = class {
1365
1453
  runStats.totalRequests++;
1366
1454
  if (skipLabels && skipLabels.has(label || "default")) {
1367
1455
  runStats.bypassed++;
1368
- 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
+ }
1369
1459
  await originalHandler.call(crawler, context);
1370
1460
  return;
1371
1461
  }
@@ -1375,7 +1465,9 @@ var FetchBrain = class {
1375
1465
  url
1376
1466
  });
1377
1467
  const rawRequest = buildRawRequest(request);
1378
- warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
1468
+ let shown;
1469
+ const shownUrl = () => (shown ?? (shown = { text: logUrlFor(rawRequest, config.logUrl) })).text;
1470
+ warnDefaultUniqueKey(rawRequest, logger, warnedKeys, shownUrl);
1379
1471
  let consumedStash;
1380
1472
  try {
1381
1473
  const preRecalled = request.userData?.__fetchBrainResult;
@@ -1396,13 +1488,13 @@ var FetchBrain = class {
1396
1488
  if (preRecalled?.known && request.skipNavigation && !(aiResult.known && aiResult.data)) {
1397
1489
  if (aiResult.fallback) {
1398
1490
  throw new Error(
1399
- `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.`
1400
1492
  );
1401
1493
  }
1402
1494
  runStats.dropped++;
1403
1495
  request.noRetry = true;
1404
1496
  throw new Error(
1405
- `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.`
1406
1498
  );
1407
1499
  }
1408
1500
  let usedAIData = false;
@@ -1428,7 +1520,7 @@ var FetchBrain = class {
1428
1520
  if (aiResult.known && aiResult.data && originalPushData) {
1429
1521
  usedAIData = true;
1430
1522
  await originalPushData.call(context, aiResult.data);
1431
- logger.info(`Used brain data: ${url}`);
1523
+ if (config.debug) logger.debug(`Used brain data${urlSuffix(shownUrl())}`);
1432
1524
  await fireOnRecalled(aiResult.data);
1433
1525
  }
1434
1526
  }
@@ -1441,7 +1533,7 @@ var FetchBrain = class {
1441
1533
  const handlerLabel = request.label;
1442
1534
  const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
1443
1535
  if (aiResult.known && aiResult.data && !runHandler) {
1444
- logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
1536
+ if (config.debug) logger.debug(`Recalled${urlSuffix(shownUrl())} [${handlerLabel || "default"}]`);
1445
1537
  if (originalPushData) {
1446
1538
  await originalPushData.call(context, aiResult.data);
1447
1539
  }
@@ -1466,11 +1558,11 @@ var FetchBrain = class {
1466
1558
  const counts = labelCounts(request.label);
1467
1559
  if (counts) counts.scraped++;
1468
1560
  if (aiResult.known) {
1469
- logger.info(
1470
- `Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
1471
- );
1472
- } else {
1473
- 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())}`);
1474
1566
  }
1475
1567
  const learnItems = [];
1476
1568
  if (originalPushData && config.learning !== false) {