@fetchbrain.com/sdk 0.4.0 → 0.5.1

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
@@ -7,7 +7,7 @@
7
7
 
8
8
  **Make your scrapers smarter with every run.**
9
9
 
10
- *Your crawler teaches it once. It recognizes forever.*
10
+ *Your crawler teaches it once. It recalls it on every run after.*
11
11
 
12
12
  [![CI](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/fetchbrain-com/sdk/actions/workflows/ci.yml) [![npm version](https://badge.fury.io/js/@fetchbrain.com%2Fsdk.svg)](https://www.npmjs.com/package/@fetchbrain.com/sdk) [![TypeScript](https://img.shields.io/badge/TypeScript-first-3178C6.svg)](https://www.typescriptlang.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
13
13
 
@@ -21,28 +21,25 @@ Every scraping run re-fetches thousands of pages you already scraped last
21
21
  time — paying for proxies, browsers, retries, and CAPTCHAs to learn things
22
22
  you already know.
23
23
 
24
- FetchBrain gives your scrapers a **shared memory pool**. Before each
25
- request, a crawler asks *"do I already know this request?"* — known
26
- requests come back in **~50ms** without touching the network; unknown ones
27
- run normally and are learned. Everything every scraper learns accumulates under
28
- your API key, run after run, scraper after scraper — a data asset that
24
+ FetchBrain gives each of your scrapers a **memory**. Before each request, a
25
+ crawler asks *"do I already know this request?"* — known requests come back
26
+ **in milliseconds** without your scraper fetching the page; unknown ones run
27
+ normally and are learned. Memory grows run after run, and `ask()` answers
28
+ plain-English questions from what you've learned — a data asset that
29
29
  compounds instead of costs. **Learning is always free.**
30
30
 
31
31
  ```text
32
32
  $ node scraper.js # first run — the brain learns
33
- ● learned example.com/p/1042 1.9s
34
- ● learned example.com/p/1043 2.3s
35
- ● learned example.com/p/1044 2.1s
33
+ INFO FetchBrain: 🧠 Finished! recalled: 0/3 (0.0%), learned: 3, scraped: 3, duration: 6.4s
36
34
 
37
35
  $ node scraper.js # every run after that
38
- ● known example.com/p/1042 0.05s ⚡ no fetch
39
- ● known example.com/p/1043 0.04s ⚡ no fetch
40
- ● known example.com/p/1044 0.05s ⚡ no fetch
41
-
42
- 🧠 Finished! recalled: 3/3 (100%), learned: 0, duration: 0.3s
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
+ INFO FetchBrain: 🧠 Finished! recalled: 3/3 (100.0%), learned: 0, scraped: 0, duration: 0.3s
43
40
  ```
44
41
 
45
- ### Try it in 60 seconds
42
+ ### Try it
46
43
 
47
44
  ```ts
48
45
  // scraper.mjs — run this twice and watch the second run skip the fetch
@@ -58,8 +55,8 @@ const crawler = new CheerioCrawler({
58
55
  FetchBrain.enhance(crawler, { apiKey: process.env.FETCHBRAIN_API_KEY });
59
56
 
60
57
  await crawler.run(["https://example.com/"]);
61
- // Run 1: ● learned example.com/ — your scraper fetched it and taught your brain
62
- // Run 2: ● known example.com/ ~50ms — recalled from memory, no HTTP request made
58
+ // Run 1: your scraper fetches the page and teaches your brain
59
+ // Run 2: recalled from memory in milliseconds, no HTTP request to example.com
63
60
  ```
64
61
 
65
62
  ## One line to adopt
@@ -88,37 +85,38 @@ That's it. Your handler only runs when there's something new to learn.
88
85
 
89
86
  | | Without | With FetchBrain |
90
87
  | --- | --- | --- |
91
- | **Repeat requests** | Full fetch, every run | Recalled in ~50ms, zero HTTP |
88
+ | **Repeat requests** | Full fetch, every run | Recalled in milliseconds |
92
89
  | **Proxy & compute spend** | Pay per fetch, every run | Pay only for what it knows |
93
- | **Blocks & CAPTCHAs** | Every run risks them | Known requests never touch the site |
94
- | **When the service is down** | — | Your crawl runs normally — guaranteed |
90
+ | **Blocks & CAPTCHAs** | Every run risks them | Pre-recalled known requests skip the fetch |
91
+ | **When the service is down** | — | Your crawl runs normally (circuit breaker, 500ms timeout) |
95
92
  | **Testing** | Mock it yourself | `MockFetchBrain` ships in the box |
96
93
 
97
- - ⚡ **Instant recall** — known requests skip the network entirely
98
- - 🌐 **Any request, not just pages** — HTML, JSON APIs, POSTs with bodies; identity is derived from the full request
99
- - 🎓 **Auto-learning** — every successful scrape teaches the brain, free
100
- - 🛡️ **Never breaks your crawl** — circuit breaker degrades gracefully; a FetchBrain outage costs you optimization, never data
101
- - 📦 **Built for scale** — request batching and deduping for high-concurrency crawlers
102
- - 🔌 **Crawlee-native** — CheerioCrawler, PlaywrightCrawler, and friends
103
- - 🔒 **Private by design** — your data is scoped to your key; only your requests, what you choose to learn, and platform identifiers (`*_ID` env vars) leave your process. Anonymized telemetry is **opt-in** ([opt-in telemetry](#telemetry-opt-in))
104
- - 🧪 **TypeScript-first** — full types, ESM + CJS, zero config
94
+ - **Recall before you fetch** — known requests are answered from memory; when they're recalled at enqueue time, the page is never fetched ([caveats](#recall-at-enqueue-time-prerecall))
95
+ - **Any request, not just pages** — HTML, JSON APIs, POSTs with bodies; identity is derived from the full request
96
+ - **Auto-learning** — every successful scrape teaches the brain, free
97
+ - **Never breaks your crawl** — the circuit breaker degrades gracefully; an outage costs you optimization, not your crawl (one deliberate exception: [expired memory](#recall-at-enqueue-time-prerecall))
98
+ - **Built for scale** — request batching and deduping for high-concurrency crawlers
99
+ - **Crawlee-native** — CheerioCrawler, PlaywrightCrawler, and friends
100
+ - **Transparent** — see exactly [what leaves your process](#what-leaves-your-process). Telemetry is **opt-in** and pseudonymous ([details](#telemetry-opt-in))
101
+ - **TypeScript-first** — full types, ESM + CJS; an API key is the only required option
105
102
 
106
103
  ## Who is it for?
107
104
 
108
- FetchBrain pays off wherever the **same expensive request gets made more
109
- than once** — across a fleet, across users, or across runs. It won't speed
110
- up a first-ever fetch of a brand-new URL, and it's not for freshness-critical
111
- monitoring where you always need the live value. Everywhere else, it compounds:
105
+ FetchBrain pays off wherever a scraper makes the **same expensive request more
106
+ than once** — across runs, scheduled jobs, or the users it serves. It won't
107
+ speed up a first-ever fetch of a brand-new URL, and it's not for
108
+ freshness-critical monitoring where you always need the live value.
109
+ Everywhere else, it compounds:
112
110
 
113
- **Data-service teams & aggregators** — fetch an expensive request once, serve
114
- it to every client and job. Overlapping crawls draw from one shared pool, so
115
- per-run proxy and compute cost falls as coverage grows — and `ask()` turns
116
- everything you've collected into a queryable corpus, with no warehouse to run.
111
+ **Data-service teams & aggregators** — each scraper fetches an expensive
112
+ request once and recalls it on every run after, so per-run proxy and compute
113
+ cost falls as coverage grows — and `ask()` turns what they've collected into
114
+ memory you can ask questions of, with no warehouse to run.
117
115
 
118
- **Product teams & AI agents** — apps and browsing agents that re-hit popular
116
+ **Product teams & AI agents** — apps and browsing agents that re-hit the same
119
117
  requests get them back in milliseconds, straight from memory: no fetch, no
120
- proxy, no block. The more your users (or agents) converge on the same
121
- requests, the more the pool pays off.
118
+ proxy, no block. The more often a scraper revisits the same requests, the more
119
+ its memory pays off.
122
120
 
123
121
  **Recurring crawls of stable data** — catalogs, specs, listings, company and
124
122
  reference data barely change between runs, so recall skips the fetch and each
@@ -126,7 +124,7 @@ scheduled run costs less. Keep volatile fields on `memory: "fresh"` so you
126
124
  never trade accuracy for speed.
127
125
 
128
126
  **Solo scraper developers** — start free: learning never costs anything, and
129
- the requests you've already made come back instantly instead of getting
127
+ the requests you've already made come back from memory instead of getting
130
128
  blocked or throttled. One line to add, one brain that grows with everything
131
129
  you scrape.
132
130
 
@@ -162,14 +160,19 @@ await crawler.run(urls);
162
160
  ## How it works
163
161
 
164
162
  ```
165
- Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data in ~50ms, no fetch
163
+ Your crawler ──▶ FetchBrain ──▶ knows this request? ──▶ YES ──▶ data in milliseconds, no fetch
166
164
  │
167
165
  └──▶ NO ──▶ your handler runs ──▶ brain learns, free
168
166
  ```
169
167
 
170
- 1. **Recall** — before each request, the SDK asks if the brain knows it
171
- 2. **Known** — data returns instantly and the fetch is skipped
172
- 3. **Learning** — unknown requests run through your handler as normal, and the result teaches the brain for every future run
168
+ 1. **Recall** — before each request (at enqueue time by default), the SDK asks if the brain knows it
169
+ 2. **Known** — the remembered data is pushed for you and your handler is skipped; requests recalled at enqueue also skip the fetch
170
+ 3. **Learning** — unknown requests run through your handler as normal, and the result teaches the brain for that scraper's future runs
171
+
172
+ Memory is always private to your account. Within it, scoping depends on
173
+ where the scraper runs ([details](#do-my-scrapers-share-memory)): on Apify
174
+ each actor has its own memory; everywhere else, all scrapers under one API
175
+ key share one memory.
173
176
 
174
177
  ### Memory depth
175
178
 
@@ -182,27 +185,57 @@ How old is too old? You decide, per crawler:
182
185
  | `standard` | 7 days | listings, catalogs |
183
186
  | `deep` | 30 days | slow-changing reference data |
184
187
 
185
- ## Take control in your handler
188
+ ## Brain context in handler
186
189
 
190
+ With the default `alwaysRun: false`, known requests skip your handler
191
+ entirely. Set `alwaysRun` (see [below](#choosing-which-handlers-run)) and
187
192
  `context.brain` puts the recall decision in your hands:
188
193
 
189
194
  ```typescript
190
- requestHandler: async ({ $, brain, pushData }) => {
195
+ import { FetchBrain, type FetchBrainContext } from "@fetchbrain.com/sdk";
196
+ import { CheerioCrawler } from "crawlee";
197
+
198
+ const crawler = FetchBrain.enhance(
199
+ new CheerioCrawler({
200
+ requestHandler: async (context) => {
201
+ const { $, pushData } = context;
202
+ // Crawlee's context types don't declare `brain`; FetchBrainContext describes it
203
+ const brain = (context as { brain?: FetchBrainContext }).brain;
204
+ if (brain?.known) {
205
+ // Option 1: push the remembered data and skip scraping
206
+ await brain.use();
207
+ return;
208
+ }
209
+ await pushData({ title: $("h1").text() }); // scrape + learn
210
+ },
211
+ }),
212
+ { apiKey: process.env.FETCHBRAIN_API_KEY, alwaysRun: true },
213
+ );
214
+ ```
215
+
216
+ Or compare what the brain remembers with what the page says now:
217
+
218
+ ```typescript
219
+ requestHandler: async (context) => {
220
+ const { $, pushData } = context;
221
+ const brain = (context as { brain?: FetchBrainContext }).brain;
222
+ const scraped = { title: $("h1").text() };
191
223
  if (brain?.known) {
192
- await brain.use(); // push the brain's data, skip scraping
193
- return;
224
+ console.log("Remembered:", brain.data, "Scraped:", scraped);
194
225
  }
195
- await pushData({ title: $("h1").text() }); // scrape + learn
226
+ await pushData(scraped); // learned only if the request was unknown
196
227
  },
197
228
  ```
198
229
 
230
+ ### `context.brain` properties
231
+
199
232
  | Property | Type | Description |
200
233
  | --- | --- | --- |
201
234
  | `known` | `boolean` | whether the brain knows this request |
202
235
  | `data` | `object` | the remembered data (if known) |
203
- | `use()` | `function` | push the brain's data and skip scraping |
236
+ | `use()` | `function` | push the remembered data and skip scraping |
204
237
 
205
- ### Configuration Options
238
+ ## Configuration options
206
239
 
207
240
  ```typescript
208
241
  interface FetchBrainConfig {
@@ -210,37 +243,128 @@ interface FetchBrainConfig {
210
243
  apiKey: string;
211
244
 
212
245
  // Optional
213
- baseUrl?: string; // API URL (default: production)
214
- memory?: MemoryDepth; // How far back the brain recalls
215
- learning?: boolean; // Enable AI learning (default: true)
216
- alwaysRun?: boolean | string | string[]; // Which handlers to run (default: false)
246
+ baseUrl?: string; // API URL (default: https://api.fetchbrain.com)
247
+ memory?: MemoryDepth; // How far back the brain recalls (default: "recent")
248
+ learning?: boolean; // Teach the brain from scraped data (default: true)
249
+ alwaysRun?: boolean | string | string[]; // Handlers that still run when a request is known (default: false)
217
250
  skipLabels?: string[]; // Labels that bypass FetchBrain entirely (default: none)
218
- timeout?: number; // Request timeout in ms (default: 500)
219
- debug?: boolean; // Enable debug logging
251
+ preRecall?: boolean; // Recall requests in bulk as they're enqueued (default: true)
252
+ onRecalled?: (event: RecalledEvent) => void | Promise<void>; // Per-record hook when recalled data is delivered
253
+ extractForLearning?: (data: unknown) => Record<string, unknown>; // Transform each record before it is learned
254
+ refreshOnRebuild?: boolean; // Scope learn, recall and ask to the current build (*_BUILD_ID env var) (default: false)
255
+ timeout?: number; // Handler-time recall, stats and telemetry timeout in ms (default: 500)
256
+ batch?: { maxSize?: number; maxWait?: number }; // Request batching (default: 50 items / 50ms)
257
+ circuitBreaker?: {
258
+ failureThreshold?: number; // Failures before the circuit opens (default: 3)
259
+ resetTimeout?: number; // ms before a retry is allowed (default: 30000)
260
+ successThreshold?: number; // Successes to close it again (default: 1)
261
+ };
262
+ telemetry?: TelemetryConfig; // Opt-in telemetry (default: { enabled: false })
263
+ learnUrlField?: string; // Accepted but not currently applied
264
+ debug?: boolean; // Enable debug logging (default: false)
220
265
  }
221
266
  ```
222
267
 
268
+ ### Recall at enqueue time (`preRecall`)
269
+
270
+ In `HttpCrawler`/`CheerioCrawler`, Crawlee performs the HTTP request *before*
271
+ your request handler runs — so a recall inside the handler is too late to
272
+ save the fetch. With `preRecall` (on by default), the SDK checks the brain
273
+ the moment requests enter the queue: each `crawler.addRequests()` array
274
+ becomes a single bulk recall, known requests are enqueued with Crawlee's
275
+ `skipNavigation` so their fetch never happens, and unknown requests carry
276
+ their recall result with them so the handler doesn't ask twice. Enqueue in
277
+ batches (one `addRequests` call per page of discovered items) to get the
278
+ most out of it. If the brain is unreachable, requests are enqueued unchanged
279
+ and your crawl proceeds at native speed — same graceful degradation as
280
+ everywhere else.
281
+
282
+ Things to know:
283
+
284
+ - **Scope** — pre-recall applies to arrays passed to `crawler.addRequests()`
285
+ or `crawler.run(requests)`. Crawlee's context-level `enqueueLinks()` and
286
+ context `addRequests()` reach the queue by other paths and are not
287
+ pre-recalled (they still get handler-time recall, but the fetch has
288
+ already happened). Inside a handler, enqueue follow-ups through the
289
+ crawler to keep the benefit:
290
+
291
+ ```typescript
292
+ requestHandler: async ({ $, request, crawler }) => {
293
+ const urls = $("a.product")
294
+ .map((_, a) => new URL($(a).attr("href") ?? "", request.url).href)
295
+ .get();
296
+ await crawler.addRequests(urls.map((url) => ({ url, label: "product" })));
297
+ },
298
+ ```
299
+ - **Metering** — known recalls are counted at enqueue time, so a known
300
+ duplicate that the queue later drops still counts.
301
+ - **Snapshot semantics** — the recall result is as of enqueue time. Anything
302
+ learned between enqueue and execution isn't picked up; the request is
303
+ simply scraped and re-learned.
304
+ - **Expired memory** — if a request skipped its fetch at enqueue but its
305
+ remembered data genuinely expired before it executed (e.g. across a process
306
+ restart), it fails once without retries and lands in your
307
+ `failedRequestHandler`, so the missing record is visible to your error
308
+ tooling. It will be re-scraped on a future run. (If the data merely couldn't
309
+ be restored because the API was briefly unreachable, the request fails
310
+ retryable and the next attempt restores it.)
311
+ - **`retryOnBlocked` crawlers** — Crawlee's blocked-request detection needs a
312
+ fetched response, so on these crawlers known requests keep their fetch;
313
+ recalled data still replaces the handler (no second recall, no re-scrape).
314
+
315
+ ### Reacting to recalled records (`onRecalled`)
316
+
317
+ When the brain knows a request, your handler is skipped and the remembered
318
+ data is pushed for you — which also skips any per-record bookkeeping living
319
+ in that handler (metrics, counters, follow-up enqueues). `onRecalled`
320
+ runs once per recalled record with `{ url, label, userData, data }` — both
321
+ when the handler is auto-skipped and when your own handler calls
322
+ `context.brain.use()`:
323
+
324
+ ```typescript
325
+ const recalledByLabel = new Map<string, number>();
326
+
327
+ FetchBrain.enhance(crawler, {
328
+ apiKey: process.env.FETCHBRAIN_API_KEY,
329
+ onRecalled: ({ label = "default" }) => {
330
+ recalledByLabel.set(label, (recalledByLabel.get(label) ?? 0) + 1);
331
+ },
332
+ });
333
+ ```
334
+
335
+ Hook errors are swallowed (logged at debug) — they never break the crawl.
336
+
337
+ ### Choosing which handlers run
338
+
223
339
  Fine-grained routing control with `alwaysRun` — run every handler, none, or
224
340
  only specific labels when a request is known:
225
341
 
226
342
  ```typescript
227
- FetchBrain.enhance(crawler, { alwaysRun: ["listing", "category"] });
343
+ FetchBrain.enhance(crawler, {
344
+ apiKey: process.env.FETCHBRAIN_API_KEY,
345
+ alwaysRun: ["listing", "category"],
346
+ });
228
347
  ```
229
348
 
230
349
  For dynamic requests that must always run live and aren't worth remembering
231
350
  (search results, pagination), use `skipLabels` instead: where `alwaysRun`
232
351
  still recalls (and can learn), `skipLabels` bypasses FetchBrain entirely —
233
- no recall round-trip, no learn — so those requests run at native speed:
352
+ no recall round-trip, no learn, no telemetry — so those requests run at
353
+ native speed:
234
354
 
235
355
  ```typescript
236
- FetchBrain.enhance(crawler, { skipLabels: ["search", "pagination"] });
356
+ FetchBrain.enhance(crawler, {
357
+ apiKey: process.env.FETCHBRAIN_API_KEY,
358
+ skipLabels: ["search", "pagination"],
359
+ });
237
360
  ```
238
361
 
239
362
  ## Ask your brain anything
240
363
 
241
- This is where the pool pays off twice: `ask()` searches across everything
242
- **all** your scrapers have ever learned — one question, your whole corpus,
243
- no exact URLs, no warehouse:
364
+ `ask()` answers from what's been learned — one question, no exact URLs, no
365
+ warehouse. From the SDK it uses the same scope as recall (see
366
+ [Do my scrapers share memory?](#do-my-scrapers-share-memory)); Ask Your Brain
367
+ in the dashboard answers across your whole account:
244
368
 
245
369
  ```typescript
246
370
  import { FetchBrainClient } from "@fetchbrain.com/sdk";
@@ -252,8 +376,8 @@ console.log(res.answer); // synthesized answer
252
376
  console.log(res.sources); // scored sources
253
377
  ```
254
378
 
255
- Pick the model that writes the answer with `model` — the default is Llama 3.3
256
- 70B (`"llama-3.3-70b"`, included on every plan). Premium models like
379
+ Pick the model that writes the answer with `model` — the default is
380
+ `"llama-3.3-70b"`, included on every plan. Premium models like
257
381
  `"kimi-k2.5"` and `"kimi-k2.6"` use extra ask credits and need a paid plan,
258
382
  and `"byok"` answers with your own linked provider model (configured in the
259
383
  dashboard, billed to your provider):
@@ -275,70 +399,35 @@ paid plan, `"byok"` with no linked provider — the response comes back with
275
399
  `status: "unavailable"`, which means the API itself is degraded or
276
400
  unreachable.
277
401
 
278
- ## Brain Context in Handler
402
+ ## Learning with `Dataset.pushData`
279
403
 
280
- Access brain data directly in your handler via `context.brain`:
404
+ > **Important:** the brain learns only from `context.pushData()` or the
405
+ > SDK's `pushData()` wrapper below. Data written with `Dataset.pushData()`
406
+ > directly is not learned, so those requests stay unknown on future runs.
281
407
 
282
- ```typescript
283
- const crawler = FetchBrain.enhance(
284
- new CheerioCrawler({
285
- requestHandler: async ({ $, request, brain, pushData }) => {
286
- // Check if the brain already knows this page
287
- if (brain?.known) {
288
- console.log("Brain knows this page");
289
-
290
- // Option 1: Use brain data directly (skip scraping)
291
- await brain.use();
292
- return;
293
-
294
- // Option 2: Compare brain data with scraped data
295
- // const scraped = { title: $('h1').text() };
296
- // console.log('Brain:', brain.data, 'Scraped:', scraped);
297
- }
298
-
299
- // Scrape normally if the brain doesn't know
300
- const data = { title: $("h1").text() };
301
- await pushData(data);
302
- },
303
- }),
304
- { apiKey: "your-api-key", alwaysRun: true },
305
- );
306
- ```
307
-
308
- ### `context.brain` Properties
309
-
310
- | Property | Type | Description |
311
- | --------- | -------- | ---------------------------------- |
312
- | `known` | boolean | Whether the brain knows this URL |
313
- | `data` | object | Brain data (if known) |
314
- | `use()` | function | Push brain data and skip scraping |
315
-
316
- ## Using Dataset.pushData
317
-
318
- > ⚠️ **Important**: AI learning **only happens** when you use `context.pushData()` or the SDK's `pushData()` wrapper below. Direct calls to `Dataset.pushData()` **will not trigger learning**, and the AI won't recognize these URLs in future runs.
319
-
320
- If you use `Dataset.pushData()` instead of `context.pushData()`, use our wrapper for automatic AI learning:
408
+ If you write with `Dataset.pushData()` instead of `context.pushData()`, use
409
+ the wrapper so the brain learns from it:
321
410
 
322
411
  ```typescript
323
412
  import { FetchBrain, pushData } from "@fetchbrain.com/sdk";
324
- import { Dataset } from "crawlee";
413
+ import { CheerioCrawler, Dataset } from "crawlee";
325
414
 
326
415
  const crawler = FetchBrain.enhance(
327
416
  new CheerioCrawler({
328
- requestHandler: async ({ $, request }) => {
417
+ requestHandler: async ({ $ }) => {
329
418
  const data = { title: $("h1").text() };
330
419
 
331
- // ✅ Use pushData wrapper for AI learning
420
+ // Learned: the SDK wrapper
332
421
  await pushData(data, Dataset);
333
422
 
334
- // ✅ Or with named dataset
423
+ // Learned: the wrapper with a named dataset
335
424
  await pushData(data, Dataset, "products");
336
425
 
337
- // ❌ This will NOT learn:
426
+ // Not learned:
338
427
  // await Dataset.pushData(data);
339
428
  },
340
429
  }),
341
- { apiKey: "your-api-key" },
430
+ { apiKey: process.env.FETCHBRAIN_API_KEY },
342
431
  );
343
432
  ```
344
433
 
@@ -348,7 +437,7 @@ const crawler = FetchBrain.enhance(
348
437
  import { FetchBrain } from "@fetchbrain.com/sdk";
349
438
 
350
439
  const brain = new FetchBrain({
351
- apiKey: "your-api-key",
440
+ apiKey: process.env.FETCHBRAIN_API_KEY,
352
441
  memory: "recent",
353
442
  });
354
443
 
@@ -368,17 +457,74 @@ if (result.known) {
368
457
  The circuit breaker is not an afterthought — it's the core design contract:
369
458
 
370
459
  - **Healthy** → full optimization
371
- - **Slow** (>500ms) → time out, continue without recall
372
- - **Down** → circuit opens, your scraper runs standalone
373
- - **Recovered** → circuit closes, optimization resumes
460
+ - **Slow** → the call times out and your crawl continues without it
461
+ - **Down** → after 3 consecutive failures the circuit opens and your scraper runs standalone
462
+ - **Recovered** → after 30 seconds the SDK tries again; on success the circuit closes and optimization resumes
463
+
464
+ Timeouts per call type:
465
+
466
+ | Call | Timeout |
467
+ | --- | --- |
468
+ | Recall in the handler (batched) | `timeout` option, default 500ms |
469
+ | Recall at enqueue (`preRecall`, bulk) | 3s per chunk of up to 100 requests |
470
+ | Learn (batched, sent in the background) | 5s |
471
+ | `ask()` | 10s |
472
+ | `stats()` and telemetry | `timeout` option, default 500ms |
473
+
474
+ A FetchBrain outage costs you *optimization*, not your crawl: SDK calls
475
+ degrade gracefully instead of throwing into it. The one deliberate
476
+ exception is [expired memory](#recall-at-enqueue-time-prerecall): a request
477
+ that skipped its fetch at enqueue and whose remembered data is gone fails
478
+ into your `failedRequestHandler` rather than disappearing silently.
479
+
480
+ ## What leaves your process
481
+
482
+ Every API call (recall, learn, ask, stats, telemetry) sends these headers:
374
483
 
375
- A FetchBrain problem can cost you *optimization*, never *data*. Every SDK
376
- call degrades gracefully; none of them throw into your crawl.
484
+ | Header | Value |
485
+ | --- | --- |
486
+ | `Authorization` | `Bearer <your API key>` |
487
+ | `X-FB-SDK` | `js` |
488
+ | `X-FB-Node` | your Node.js version (e.g. `v20.11.0`) |
489
+ | `X-FB-Platform` | your OS platform (e.g. `linux`) |
490
+ | `X-FB-Env` | the value of `NODE_ENV`, if set |
491
+ | `X-FB-Context` | JSON of environment variables named `*_ID`, plus `NODE_ENV`, `REGION` and `CI` (see below) |
492
+ | `X-FB-Crawler` | the crawler class name (e.g. `CheerioCrawler`), while a request is being handled |
493
+ | `X-FB-Label` | the request's Crawlee label, while a request is being handled |
494
+
495
+ `X-FB-Context` carries your platform identifiers; the API uses
496
+ `APIFY_ACTOR_ID` from it to scope memory per Apify actor (other `*_ID`
497
+ variables do not affect scoping) and `*BUILD_ID` for `refreshOnRebuild`. It includes
498
+ every environment variable whose name ends in `_ID`, plus `NODE_ENV`,
499
+ `REGION` and `CI`, except names containing `TOKEN`, `SECRET`, `PASSWORD`,
500
+ `CREDENTIAL`, `KEY`, `AUTH` or `COOKIE`, values that look like a JWT or a
501
+ URL with embedded `user:pass`, and values over 256 characters (2 KB total).
502
+ No other environment variables are sent. If you keep something private in
503
+ a variable ending in `_ID`, it will be sent.
504
+
505
+ Recall and learn also send the request itself: the full URL (including
506
+ query string), method, `uniqueKey`, label, string POST body, your
507
+ `userData` (minus the SDK's own keys), and the request headers **except**
508
+ `Authorization`, `Cookie` and `Set-Cookie`. Recall also sends your `memory`
509
+ depth; learn also sends the record you pushed (after `extractForLearning`).
510
+
511
+ With `refreshOnRebuild`, recall, learn and `ask()` also send a build ID: the
512
+ value of the first environment variable whose name ends in `BUILD_ID`. This
513
+ value is sent as-is — it does **not** go through the name, credential or
514
+ length filters `X-FB-Context` uses.
515
+
516
+ Other headers (for example
517
+ `Proxy-Authorization` or `X-API-Key`), `userData` values and POST bodies are
518
+ forwarded as-is — keep secrets out of them on requests FetchBrain handles,
519
+ or route those requests through `skipLabels`, which sends nothing for them.
520
+
521
+ `ask()` sends your question and options. Telemetry sends nothing unless you
522
+ [opt in](#telemetry-opt-in).
377
523
 
378
524
  ## Telemetry (opt-in)
379
525
 
380
- Telemetry is **off by default.** You can opt in to send anonymized
381
- operational diagnostics that help improve FetchBrain:
526
+ Telemetry is **off by default.** Nothing in this section is collected or
527
+ sent unless you opt in:
382
528
 
383
529
  ```typescript
384
530
  FetchBrain.enhance(crawler, {
@@ -387,16 +533,57 @@ FetchBrain.enhance(crawler, {
387
533
  });
388
534
  ```
389
535
 
390
- **What's sent** (all anonymized): domain (e.g. `walmart.com`), a SHA-256
391
- **hash** of the full URL, a generalized path pattern, timing and status
392
- codes, retry counts, proxy **country/type** and success, coarse session
393
- aggregates (age, error rate, cookie *count*), block indicators, and crawler
394
- type. **Never:** raw URLs, request/response bodies, cookies or their values,
395
- proxy IPs, credentials, or any PII.
536
+ **It's pseudonymous, not anonymous.** Entries are sent to the FetchBrain
537
+ API with your API key and the [headers above](#what-leaves-your-process),
538
+ so they're linked to your account. They're used to improve FetchBrain's
539
+ recommendations (proxy recommendations, block detection, configuration
540
+ tuning); aggregated statistics may inform recommendations for other users.
541
+
542
+ **When it's collected:** one entry per request FetchBrain handles
543
+ (`skipLabels` requests are excluded), after your handler finishes — or
544
+ whenever the request fails inside the SDK's wrapper, including failures
545
+ before your handler runs (e.g. [expired memory](#recall-at-enqueue-time-prerecall))
546
+ and on known requests. Known requests that are skipped successfully produce
547
+ no entry. A failure entry carries only the "always" fields (minus session),
548
+ `retryCount`, timing, and `blocked: true` with a `blockType` if one matches.
549
+ Entries are buffered in your process and sent in batches (every 50 entries,
550
+ every 30 seconds, and when the crawl finishes); send failures are ignored and
551
+ never affect your crawl.
552
+
553
+ **What's sent:**
554
+
555
+ | Field | Sent when | What it is |
556
+ | --- | --- | --- |
557
+ | `domain` | always | the URL's hostname, in plain text (e.g. `shop.example.com`) |
558
+ | `urlHash` | always | first 16 hex characters of an **unsalted** SHA-256 of the full URL, including the query string. Anyone with a candidate URL can compute the same hash, so it identifies URLs that are guessable. |
559
+ | `urlPattern` | always | the URL path with numeric segments, UUIDs and alphanumeric tokens of 20+ characters replaced by `*`; the query string is dropped. Everything else — slugs, usernames, words — is sent as-is (e.g. `/users/jane-doe/orders/*`). |
560
+ | `timestamp` | always | when the entry was collected |
561
+ | `crawlerType` | always | crawler class name, lowercased, without `Crawler` (e.g. `cheerio`) |
562
+ | `requestLabel` | always | the request's Crawlee label, if set |
563
+ | `sessionAge`, `sessionErrorScore` | on success, if the request has a Crawlee session | the session's usage count and error score |
564
+ | `statusCode` | `sharePerformance`, on success | HTTP status |
565
+ | `retryCount` | `sharePerformance` | Crawlee retry count |
566
+ | `responseTimeMs`, `totalTimeMs` | `sharePerformance` | time in ms from when the SDK starts handling the request (including recall) until your handler finishes or the request fails |
567
+ | `contentSize` | `sharePerformance`, on success | response body length, when the crawler exposes it |
568
+ | `blocked`, `blockType` | `shareSitePatterns` | `blocked` is true for status 403, 429 or 5xx, or when the request failed inside the SDK wrapper for any reason; `blockType` is the status code (4xx/5xx) or a category matched in the error message (`captcha`, `timeout`, `blocked`, `429` for "rate limit") — the message itself isn't sent |
569
+ | `proxyCountry`, `proxyType`, `proxySuccess` | `shareProxyInfo`, on success, if the request used a Crawlee proxy | the proxy's country code; `residential`, `mobile` or `datacenter`, guessed in your process from the proxy URL; and whether the status was below 400. The proxy URL, hostname, IP and credentials are not sent. |
570
+
571
+ **Sub-flags** — each defaults to `true` once telemetry is enabled; set one
572
+ to `false` to stop sending its fields. The "always" fields above are sent
573
+ whenever telemetry is enabled.
396
574
 
397
- Share selectively with the sub-flags — e.g.
398
- `telemetry: { enabled: true, shareProxyInfo: false }`. Collection is
399
- buffered, best-effort, and never blocks or fails your crawl.
575
+ ```typescript
576
+ telemetry: {
577
+ enabled: true, // default: false
578
+ sharePerformance: false, // default: true
579
+ shareSitePatterns: true, // default: true
580
+ shareProxyInfo: false, // default: true
581
+ }
582
+ ```
583
+
584
+ **Never sent by telemetry:** the raw URL or query string, request or response
585
+ bodies, your scraped requests' headers or cookies, error messages, or proxy
586
+ URLs and IPs.
400
587
 
401
588
  ## Testing
402
589
 
@@ -406,7 +593,7 @@ buffered, best-effort, and never blocks or fails your crawl.
406
593
  import { MockFetchBrain } from "@fetchbrain.com/sdk/mock";
407
594
 
408
595
  const mock = new MockFetchBrain({
409
- initialKnowledge: new Map([
596
+ initialMemory: new Map([
410
597
  ["https://example.com/product", { title: "Known Product" }],
411
598
  ]),
412
599
  });
@@ -415,14 +602,21 @@ const mock = new MockFetchBrain({
415
602
  const result = await mock.recall({ url: "https://example.com/product" });
416
603
  expect(result.known).toBe(true);
417
604
 
418
- // Ask a natural-language question against seeded knowledge
419
- const answer = await mock.ask("what is the price?");
605
+ // Ask a natural-language question against seeded memory
606
+ const answer = await mock.ask("known product");
420
607
  expect(answer.sources.length).toBeGreaterThan(0);
421
608
  console.log(answer.sources);
422
609
  ```
423
610
 
424
- There's also a local mock **server** (`npm run mock-server`) for running
425
- real crawlers against `http://localhost:3456` without an API key.
611
+ `initialMemory` replaces the older `initialKnowledge` option (still
612
+ accepted, deprecated), and `getMemorySize()` replaces `getKnowledgeSize()`.
613
+ Pass `learnCap: N` to make the mock reject learns after N entries, to test
614
+ how your crawl behaves at the monthly learning limit.
615
+
616
+ If you clone this repository, there's also a local mock **server**
617
+ (`npm run mock-server`) for running real crawlers against
618
+ `http://localhost:3456` without an API key (set `FB_MOCK_LEARN_CAP=N` to
619
+ simulate the learning limit). It isn't included in the npm package.
426
620
 
427
621
  ## Examples
428
622
 
@@ -432,30 +626,27 @@ real crawlers against `http://localhost:3456` without an API key.
432
626
  | [`manual-recall`](./examples/manual-recall) | recall/learn without Crawlee |
433
627
  | [`with-mock`](./examples/with-mock) | unit testing with `MockFetchBrain` |
434
628
 
435
- - **basic-cheerio** - CheerioCrawler with FetchBrain
436
- - **manual-recall** - Direct API usage without Crawlee
437
- - **with-mock** - Unit testing with MockFetchBrain
438
-
439
629
  ## FAQ
440
630
 
441
- **Does my scraped data train anyone else's brain?**
442
- No. Everything your scrapers teach is scoped to your API key. Your data
443
- answers only your recalls.
444
-
445
631
  **Do my scrapers share memory?**
446
- Yes — that's the point. Everything learned under your API key accumulates
447
- in one brain, and `ask()` searches across all of it. Recall is namespaced
448
- per scraper identity, so one scraper's responses never pollute
449
- another's results.
632
+ It depends on where they run. Memory is always private to your account.
633
+ - **On Apify**, each actor (`APIFY_ACTOR_ID`) has its own memory: recall and
634
+ SDK `ask()` calls from inside an actor only see what that actor learned.
635
+ - **Everywhere else**, all scrapers using the same API key share one memory —
636
+ scraper A can recall what scraper B learned.
637
+ - **Ask Your Brain in the dashboard** (and `ask()` calls with no platform
638
+ context) answers across everything your account has indexed.
450
639
 
451
640
  **What leaves my process?**
452
- By default: your requests, the data you choose to learn, and platform
453
- identifiers (env vars ending in `_ID`, plus `NODE_ENV`/`REGION`/`CI`). Never
454
- your general environment, credentials, or anything credential-shaped. If you
455
- opt into telemetry, anonymized access signal too — [see what](#telemetry-opt-in).
641
+ Your requests (minus `Authorization`, `Cookie` and `Set-Cookie` headers),
642
+ the data you choose to learn, your API key, and a small set of `X-FB-*`
643
+ headers including platform identifiers (env vars ending in `_ID`, plus
644
+ `NODE_ENV`/`REGION`/`CI`). The full list is in
645
+ [What leaves your process](#what-leaves-your-process). If you opt into
646
+ telemetry, the fields in [Telemetry](#telemetry-opt-in) too.
456
647
 
457
648
  **What does learning cost?**
458
- Nothing. Learning is always free — you pay only for known queries.
649
+ Nothing. Learning is always free — you pay only for known recalls.
459
650
 
460
651
  **What if the data changed since the brain learned it?**
461
652
  That's what memory depth is for: pick `fresh` (1h) for volatile data, or
@@ -464,8 +655,8 @@ set `refreshOnRebuild` to re-learn whenever you ship a new scraper build.
464
655
  ## Contributing
465
656
 
466
657
  Issues and PRs welcome — see [open issues](https://github.com/fetchbrain-com/sdk/issues).
467
- If FetchBrain saves your crawler time or money, **a ⭐ helps other scraper
468
- developers find it**.
658
+ If FetchBrain saves your crawler time or money, a GitHub star helps other
659
+ scraper developers find it.
469
660
 
470
661
  ## License
471
662