@fetchbrain.com/sdk 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -11
- package/dist/index.d.mts +27 -3
- package/dist/index.d.ts +27 -3
- package/dist/index.js +206 -55
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +206 -55
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +2 -1
- package/dist/mock/index.d.ts +2 -1
- package/dist/mock/index.js +1 -1
- package/dist/mock/index.js.map +1 -1
- package/dist/mock/index.mjs +1 -1
- package/dist/mock/index.mjs.map +1 -1
- package/dist/{types-B579TMo9.d.mts → types-BCbMwaYW.d.mts} +32 -2
- package/dist/{types-B579TMo9.d.ts → types-BCbMwaYW.d.ts} +32 -2
- package/package.json +3 -2
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
|
-
`"
|
|
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()` |
|
|
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
|
|
@@ -575,9 +616,42 @@ never relearned.
|
|
|
575
616
|
|
|
576
617
|
When a run finishes, the SDK sends a small report containing exactly: the run
|
|
577
618
|
id, start and end timestamps, totals for scraped, learned and recalled pages,
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
619
|
+
requests skipped, late recalls and bypassed pages, per request label how many
|
|
620
|
+
pages were scraped, came back empty or failed, and your build id only when
|
|
621
|
+
`refreshOnRebuild` is on. It contains no URLs and no scraped data.
|
|
622
|
+
|
|
623
|
+
| Field | Meaning |
|
|
624
|
+
| --- | --- |
|
|
625
|
+
| `scraped` | pages whose handler ran to completion (unknown pages, and known pages matched by `alwaysRun`) |
|
|
626
|
+
| `learned` | records the brain accepted from this run |
|
|
627
|
+
| `recalled` | known pages served from memory, whether or not their handler also ran |
|
|
628
|
+
| `requestsSkipped` | known pages served from memory **without a fetch**: pre-recalled when they were enqueued, so Crawlee never requested them |
|
|
629
|
+
| `lateRecalls` | known pages served from memory **after** they were fetched: the recall happened in your handler, so the request was already spent |
|
|
630
|
+
| `bypassed` | pages handled outside FetchBrain because of `skipLabels` |
|
|
631
|
+
|
|
632
|
+
Every count covers one `run()` call. A request is counted once, after it
|
|
633
|
+
succeeded (its handler finished, or its recalled data was pushed), so a retry
|
|
634
|
+
never counts it twice and a request that finally fails is not counted. The
|
|
635
|
+
per-label counts are the exception: they count every attempt, so failure and
|
|
636
|
+
empty rates see each retry. Each `run()` call gets its own run id: on a platform that sets
|
|
637
|
+
a run id, the first call uses it as-is and later calls in the same process
|
|
638
|
+
(another `run()`, or a second crawler) add `-2`, `-3` and so on.
|
|
639
|
+
|
|
640
|
+
Requests skipped is what saves you requests. Late recalls are pages that came
|
|
641
|
+
from the queue without a [pre-recall](#recall-at-enqueue-time-prerecall):
|
|
642
|
+
links from `enqueueLinks()` or the context `addRequests()`, and every known page
|
|
643
|
+
on a `retryOnBlocked` crawler, plus non-GET requests without an explicit
|
|
644
|
+
`uniqueKey` (pre-recall can't identify them at enqueue time; set one to let it).
|
|
645
|
+
Known requests you marked `skipNavigation` yourself count only as `recalled`,
|
|
646
|
+
never as late recalls: they were never fetched.
|
|
647
|
+
When a run has late recalls, the summary line is followed by a tip such as:
|
|
648
|
+
|
|
649
|
+
```
|
|
650
|
+
3 pages were recalled after they were fetched; enqueue them with context.crawler.addRequests([...]) to skip the fetch (non-GET requests also need an explicit uniqueKey).
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
The tip is not shown on `retryOnBlocked` crawlers (their blocked-check needs
|
|
654
|
+
the fetch, so those pages can't skip it) or when `preRecall` is `false`. A page counts as "pushed no data" when your handler pushed nothing
|
|
581
655
|
through `context.pushData` or the SDK's `pushData` export (pages written
|
|
582
656
|
straight to Crawlee's static `Dataset.pushData` are counted that way too), and
|
|
583
657
|
retries count once per attempt. The report is sent with the same standard
|
|
@@ -634,7 +708,7 @@ or route those requests through `skipLabels`, which sends nothing for them.
|
|
|
634
708
|
`ask()` sends your question and options. Telemetry sends nothing unless you
|
|
635
709
|
[opt in](#telemetry-opt-in). At the end of a run the SDK also sends a small
|
|
636
710
|
[run report](#run-report): run id, start/end timestamps, scraped/learned/recalled
|
|
637
|
-
counts, per-label page counts, and a build id only with `refreshOnRebuild`
|
|
711
|
+
counts, requests skipped, late recalls and bypassed counts, per-label page counts, and a build id only with `refreshOnRebuild`
|
|
638
712
|
(`reportRuns: false` turns it off).
|
|
639
713
|
|
|
640
714
|
## Telemetry (opt-in)
|
|
@@ -655,6 +729,16 @@ so they're linked to your account. They're used to improve FetchBrain's
|
|
|
655
729
|
recommendations (proxy recommendations, block detection, configuration
|
|
656
730
|
tuning); aggregated statistics may inform recommendations for other users.
|
|
657
731
|
|
|
732
|
+
**How long it's kept:** raw entries are deleted about 30 days after they're
|
|
733
|
+
received (a daily cleanup), and all of your entries are deleted when you
|
|
734
|
+
delete your account (a very large history may take the daily cleanup a few
|
|
735
|
+
days to finish, never longer than the 30 days above).
|
|
736
|
+
Per-domain aggregate counts (requests, successes, blocks and block rate for a
|
|
737
|
+
hostname, with no URLs and no account link) are kept. Per-domain statistics
|
|
738
|
+
are aggregated per domain, not per account: entries from every account that
|
|
739
|
+
scraped a hostname add to the same counts, and they are not deleted with your
|
|
740
|
+
account.
|
|
741
|
+
|
|
658
742
|
**When it's collected:** one entry per request FetchBrain handles
|
|
659
743
|
(`skipLabels` requests are excluded), after your handler finishes — or
|
|
660
744
|
whenever the request fails inside the SDK's wrapper, including failures
|
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-
|
|
2
|
-
export {
|
|
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
|
-
|
|
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-
|
|
2
|
-
export {
|
|
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
|
-
|
|
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
|
*/
|