@fetchbrain.com/sdk 0.9.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/README.md CHANGED
@@ -33,9 +33,6 @@ $ node scraper.js # first run — the brain learns
33
33
  INFO FetchBrain: 🧠 Finished! recalled: 0/3 (0.0%), learned: 3, scraped: 3, duration: 6.4s
34
34
 
35
35
  $ node scraper.js # every run after that
36
- INFO FetchBrain: Recalled: https://example.com/p/1042 [default]
37
- INFO FetchBrain: Recalled: https://example.com/p/1043 [default]
38
- INFO FetchBrain: Recalled: https://example.com/p/1044 [default]
39
36
  INFO FetchBrain: 🧠 Finished! recalled: 3/3 (100.0%), learned: 0, scraped: 0, duration: 0.3s
40
37
  ```
41
38
 
@@ -253,7 +250,8 @@ interface FetchBrainConfig {
253
250
  onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when recalled data is delivered
254
251
  extractForLearning?: (data: unknown) => Record<string, unknown>; // Transform each record before it is learned
255
252
  refreshOnRebuild?: boolean; // Scope learn, recall and ask to the current build (*_BUILD_ID env var) (default: false)
256
- timeout?: number; // Handler-time recall, stats and telemetry timeout in ms (default: 1500)
253
+ timeout?: number; // Handler-time recall, stats and telemetry timeout in ms, 1-2147483647 (default: 1500)
254
+ askTimeout?: number; // ask() timeout in ms, 1-2147483647 (default: 60000); a per-call `timeout` wins
257
255
  batch?: { maxSize?: number; maxWait?: number }; // Request batching (default: 50 items / 50ms)
258
256
  circuitBreaker?: {
259
257
  failureThreshold?: number; // Failures before the circuit opens (default: 3)
@@ -265,6 +263,7 @@ interface FetchBrainConfig {
265
263
  reportRuns?: boolean; // Send the end-of-run report: run id, timestamps, counts per label (default: true)
266
264
  learnUrlField?: string; // Accepted but not currently applied
267
265
  debug?: boolean; // Enable debug logging (default: false)
266
+ logUrl?: (request: LogUrlRequest) => string | undefined; // How a request appears in SDK log lines (default: its URL)
268
267
  }
269
268
  ```
270
269
 
@@ -364,6 +363,33 @@ FetchBrain.enhance(crawler, {
364
363
 
365
364
  Hook errors are swallowed (logged at debug) — they never break the crawl.
366
365
 
366
+ ### Logging and request URLs (`logUrl`)
367
+
368
+ Per-request lines (recalled, learning, bypassed, used brain data) are logged
369
+ at debug level only, so they print only with `debug: true`. At the default
370
+ level you see warnings and the end-of-run summary.
371
+
372
+ A log line that names a request shows its URL. If your URLs are private (an
373
+ internal or mobile API endpoint, a token in the query string) or your run log
374
+ is visible to others, pass `logUrl` to control what is printed:
375
+
376
+ ```typescript
377
+ FetchBrain.enhance(crawler, {
378
+ apiKey: process.env.FETCHBRAIN_API_KEY,
379
+ // receives { url, uniqueKey, label, userData }
380
+ logUrl: ({ label, userData }) => `${label ?? "default"} #${userData.productId}`,
381
+ // or hide it entirely: logUrl: () => undefined
382
+ });
383
+ ```
384
+
385
+ - Return a string to print it in place of the URL, or `undefined` to print
386
+ the line without one.
387
+ - If `logUrl` throws or returns anything other than a non-empty string, the
388
+ URL is left out (never printed raw) and the crawl continues.
389
+ - It applies to FetchBrain's log lines and error messages only. Recall and
390
+ learn still send the request to the API (see
391
+ [What leaves your process](#what-leaves-your-process)).
392
+
367
393
  ### Choosing which handlers run
368
394
 
369
395
  Fine-grained routing control with `alwaysRun` — run every handler, none, or
@@ -406,8 +432,9 @@ console.log(res.answer); // synthesized answer
406
432
  console.log(res.sources); // scored sources
407
433
  ```
408
434
 
409
- Pick the model that writes the answer with `model` — the default is
410
- `"llama-3.3-70b"`, included on every plan. Premium models like
435
+ Pick the model that writes the answer with `model` — the default is Gemma 4
436
+ 26B (`"gemma-4-26b"`, included on every plan; `"llama-3.3-70b"` is also
437
+ included). Premium models like
411
438
  `"kimi-k2.5"` and `"kimi-k2.6"` use extra ask credits and need a paid plan,
412
439
  and `"byok"` answers with your own linked provider model (configured in the
413
440
  dashboard, billed to your provider):
@@ -420,6 +447,20 @@ const res = await client.ask("blue widgets under $50", {
420
447
  console.log(res.model); // slug actually used (reveals fallbacks)
421
448
  ```
422
449
 
450
+ An answer can take tens of seconds, so `ask()` waits up to 60s by default.
451
+ Change that for every call with the `askTimeout` option, or for one call
452
+ with `timeout` (ms), which wins over `askTimeout`. Both accept 1 to 2147483647 ms
453
+ (about 24.8 days); any other value (0, negative, `NaN`, `Infinity`) is ignored and
454
+ the default is used:
455
+
456
+ ```typescript
457
+ const client = new FetchBrainClient({ apiKey, askTimeout: 30_000 });
458
+ const res = await client.ask("blue widgets under $50", { answer: true, timeout: 90_000 });
459
+ ```
460
+
461
+ `ask()` has its own circuit breaker: slow or failing asks never pause recall
462
+ or learn for your crawl, and a paused recall doesn't stop `ask()`.
463
+
423
464
  Every plan includes a monthly ask allowance (100 free → 60,000 on Scale);
424
465
  asks never consume your recall quota.
425
466
 
@@ -517,7 +558,7 @@ Timeouts per call type:
517
558
  | Recall in the handler (batched) | `timeout` option, default 1.5s |
518
559
  | Recall at enqueue (`preRecall`, bulk) | 3s per chunk of up to 100 requests |
519
560
  | Learn (batched, sent in the background) | 5s |
520
- | `ask()` | 10s |
561
+ | `ask()` | `askTimeout` option (default 60s), or `timeout` per call |
521
562
  | `stats()` and telemetry | `timeout` option, default 1.5s |
522
563
 
523
564
  A FetchBrain outage costs you *optimization*, not your crawl: SDK calls
package/dist/index.d.mts CHANGED
@@ -1,9 +1,14 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-CPyPUGeb.mjs';
2
- export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-CPyPUGeb.mjs';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-BCbMwaYW.mjs';
2
+ export { p as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, o as LogUrlRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, q as TelemetryRequest, r as TelemetryResponse } from './types-BCbMwaYW.mjs';
3
3
 
4
4
  declare class FetchBrainClient {
5
5
  private config;
6
6
  private circuitBreaker;
7
+ /**
8
+ * ask() has its own breaker: slow or failing asks must not pause recall/learn,
9
+ * and an open recall breaker must not block ask.
10
+ */
11
+ private askCircuitBreaker;
7
12
  private batcher;
8
13
  private learnBatcher;
9
14
  private logger;
@@ -65,11 +70,15 @@ declare class FetchBrainClient {
65
70
  * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
66
71
  * credits), or "byok" to answer with your own linked provider model.
67
72
  * Omit it for the default model.
73
+ *
74
+ * `timeout` (ms, 1-2147483647) overrides the `askTimeout` option for this call;
75
+ * an invalid value falls back to `askTimeout`.
68
76
  */
69
77
  ask(question: string, opts?: {
70
78
  answer?: boolean;
71
79
  limit?: number;
72
80
  model?: string;
81
+ timeout?: number;
73
82
  }): Promise<AskResponse>;
74
83
  /**
75
84
  * Execute a batch query against the API
@@ -81,6 +90,15 @@ declare class FetchBrainClient {
81
90
  * Execute a batch learn against the API
82
91
  */
83
92
  private executeBatchLearn;
93
+ /**
94
+ * POST one learn batch, retrying once after a jittered wait on a timeout,
95
+ * network error or 5xx. Learns run off the crawl's hot path, so a short
96
+ * stall is not an outage: in the 2026-11-28 load test one storage shard
97
+ * paused for ~5 s, the ~3 learns a run keeps in flight all timed out
98
+ * together, and that opened the breaker shared with recall. Only a batch
99
+ * that fails twice reaches executeBatchLearn's breaker accounting.
100
+ */
101
+ private sendLearnWithRetry;
84
102
  /** Fold one batch response into the change totals (called once per HTTP batch). */
85
103
  private accumulateChanges;
86
104
  /** Change counts so far (a copy). */
@@ -263,7 +281,13 @@ declare class CircuitBreaker {
263
281
  private lastFailureTime;
264
282
  private config;
265
283
  private logger;
266
- constructor(config: Partial<CircuitBreakerConfig> | undefined, logger: Logger);
284
+ private name?;
285
+ /**
286
+ * `name` labels this breaker's log lines when a client runs more than one
287
+ * (the ask breaker opening must not read as if recall and learn stopped).
288
+ */
289
+ constructor(config: Partial<CircuitBreakerConfig> | undefined, logger: Logger, name?: string);
290
+ private label;
267
291
  /**
268
292
  * Check if requests should be allowed through
269
293
  */
package/dist/index.d.ts CHANGED
@@ -1,9 +1,14 @@
1
- import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-CPyPUGeb.js';
2
- export { o as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, p as TelemetryRequest, q as TelemetryResponse } from './types-CPyPUGeb.js';
1
+ import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnedData, b as LearnResponse, S as StatsResponse, A as AskResponse, C as ChangeStats, c as RunReport, d as RunFlag, e as CircuitState, T as TelemetryData, f as TelemetryConfig, g as CircuitBreakerConfig, h as Logger, B as BatchConfig, i as LogLevel } from './types-BCbMwaYW.js';
2
+ export { p as ChangeDetectionConfig, D as DriftItem, m as LearnRequest, o as LogUrlRequest, M as MemoryDepth, j as RecallRequest, k as RecallResponse, l as RecallResultItem, n as RecalledEvent, q as TelemetryRequest, r as TelemetryResponse } from './types-BCbMwaYW.js';
3
3
 
4
4
  declare class FetchBrainClient {
5
5
  private config;
6
6
  private circuitBreaker;
7
+ /**
8
+ * ask() has its own breaker: slow or failing asks must not pause recall/learn,
9
+ * and an open recall breaker must not block ask.
10
+ */
11
+ private askCircuitBreaker;
7
12
  private batcher;
8
13
  private learnBatcher;
9
14
  private logger;
@@ -65,11 +70,15 @@ declare class FetchBrainClient {
65
70
  * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
66
71
  * credits), or "byok" to answer with your own linked provider model.
67
72
  * Omit it for the default model.
73
+ *
74
+ * `timeout` (ms, 1-2147483647) overrides the `askTimeout` option for this call;
75
+ * an invalid value falls back to `askTimeout`.
68
76
  */
69
77
  ask(question: string, opts?: {
70
78
  answer?: boolean;
71
79
  limit?: number;
72
80
  model?: string;
81
+ timeout?: number;
73
82
  }): Promise<AskResponse>;
74
83
  /**
75
84
  * Execute a batch query against the API
@@ -81,6 +90,15 @@ declare class FetchBrainClient {
81
90
  * Execute a batch learn against the API
82
91
  */
83
92
  private executeBatchLearn;
93
+ /**
94
+ * POST one learn batch, retrying once after a jittered wait on a timeout,
95
+ * network error or 5xx. Learns run off the crawl's hot path, so a short
96
+ * stall is not an outage: in the 2026-11-28 load test one storage shard
97
+ * paused for ~5 s, the ~3 learns a run keeps in flight all timed out
98
+ * together, and that opened the breaker shared with recall. Only a batch
99
+ * that fails twice reaches executeBatchLearn's breaker accounting.
100
+ */
101
+ private sendLearnWithRetry;
84
102
  /** Fold one batch response into the change totals (called once per HTTP batch). */
85
103
  private accumulateChanges;
86
104
  /** Change counts so far (a copy). */
@@ -263,7 +281,13 @@ declare class CircuitBreaker {
263
281
  private lastFailureTime;
264
282
  private config;
265
283
  private logger;
266
- constructor(config: Partial<CircuitBreakerConfig> | undefined, logger: Logger);
284
+ private name?;
285
+ /**
286
+ * `name` labels this breaker's log lines when a client runs more than one
287
+ * (the ask breaker opening must not read as if recall and learn stopped).
288
+ */
289
+ constructor(config: Partial<CircuitBreakerConfig> | undefined, logger: Logger, name?: string);
290
+ private label;
267
291
  /**
268
292
  * Check if requests should be allowed through
269
293
  */
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
  /**
@@ -669,9 +704,12 @@ var FetchBrainClient = class {
669
704
  * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra 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) {