@fetchbrain.com/sdk 0.5.0 → 0.6.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 +325 -162
- package/dist/index.d.mts +18 -8
- package/dist/index.d.ts +18 -8
- package/dist/index.js +90 -12
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +90 -12
- package/dist/index.mjs.map +1 -1
- package/dist/mock/index.d.mts +17 -5
- package/dist/mock/index.d.ts +17 -5
- package/dist/mock/index.js +22 -12
- package/dist/mock/index.js.map +1 -1
- package/dist/mock/index.mjs +22 -12
- package/dist/mock/index.mjs.map +1 -1
- package/dist/{types-BbLgy1no.d.mts → types-B1MFygnZ.d.mts} +33 -22
- package/dist/{types-BbLgy1no.d.ts → types-B1MFygnZ.d.ts} +33 -22
- package/package.json +1 -3
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-
|
|
2
|
-
export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-
|
|
1
|
+
import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-B1MFygnZ.mjs';
|
|
2
|
+
export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-B1MFygnZ.mjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* FetchBrain API Client
|
|
@@ -15,6 +15,15 @@ declare class FetchBrainClient {
|
|
|
15
15
|
private batcher;
|
|
16
16
|
private learnBatcher;
|
|
17
17
|
private logger;
|
|
18
|
+
/**
|
|
19
|
+
* Epoch ms until which learns are paused after the API reported the monthly
|
|
20
|
+
* learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
|
|
21
|
+
*/
|
|
22
|
+
private learnPausedUntil;
|
|
23
|
+
/** Warn about the learn cap once per pause, independent of the pause state. */
|
|
24
|
+
private learnCapWarnedUntil;
|
|
25
|
+
/** Valid, normalized scraper name (option, else env var); undefined = default memory. */
|
|
26
|
+
private scraperName;
|
|
18
27
|
constructor(config: FetchBrainConfig);
|
|
19
28
|
/**
|
|
20
29
|
* Recall if FetchBrain "knows" a request
|
|
@@ -35,7 +44,7 @@ declare class FetchBrainClient {
|
|
|
35
44
|
*/
|
|
36
45
|
stats(): Promise<StatsResponse | null>;
|
|
37
46
|
/**
|
|
38
|
-
* Ask a natural-language question
|
|
47
|
+
* Ask a natural-language question, answered from everything the account has learned
|
|
39
48
|
*
|
|
40
49
|
* `model` picks the generation model for answer mode from the server's
|
|
41
50
|
* menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
|
|
@@ -127,7 +136,7 @@ interface FetchBrainContext {
|
|
|
127
136
|
* FetchBrain main class
|
|
128
137
|
*
|
|
129
138
|
* Provides the static enhance() method to wrap Crawlee crawlers
|
|
130
|
-
* with
|
|
139
|
+
* with brain recall and learning
|
|
131
140
|
*/
|
|
132
141
|
declare class FetchBrain {
|
|
133
142
|
private client;
|
|
@@ -181,9 +190,9 @@ interface DatasetLike {
|
|
|
181
190
|
open?: (name?: string | null) => Promise<DatasetLike>;
|
|
182
191
|
}
|
|
183
192
|
/**
|
|
184
|
-
*
|
|
193
|
+
* Learning-aware pushData wrapper
|
|
185
194
|
*
|
|
186
|
-
* Use this instead of Dataset.pushData()
|
|
195
|
+
* Use this instead of Dataset.pushData() so the brain learns from what you push.
|
|
187
196
|
* Works with both static Dataset class and dataset instances.
|
|
188
197
|
*
|
|
189
198
|
* @example
|
|
@@ -295,8 +304,9 @@ declare function createLogger(minLevel?: LogLevel, enabled?: boolean): Logger;
|
|
|
295
304
|
/**
|
|
296
305
|
* Telemetry Collection Module
|
|
297
306
|
*
|
|
298
|
-
* Collects
|
|
299
|
-
*
|
|
307
|
+
* Collects opt-in, pseudonymous performance and behavior data from Crawlee contexts
|
|
308
|
+
* (sent with the API key, so linked to the account). Raw URLs, bodies, proxy URLs/IPs
|
|
309
|
+
* and error messages are not collected; hostname, path pattern and label are.
|
|
300
310
|
*/
|
|
301
311
|
|
|
302
312
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-
|
|
2
|
-
export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-
|
|
1
|
+
import { F as FetchBrainConfig, R as RawRequest, a as RecallResult, L as LearnResponse, S as StatsResponse, A as AskResponse, C as CircuitState, T as TelemetryData, b as TelemetryConfig, c as CircuitBreakerConfig, d as Logger, B as BatchConfig, e as LogLevel } from './types-B1MFygnZ.js';
|
|
2
|
+
export { i as LearnRequest, M as MemoryDepth, f as RecallRequest, g as RecallResponse, h as RecallResultItem, j as RecalledEvent, k as TelemetryRequest, l as TelemetryResponse } from './types-B1MFygnZ.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* FetchBrain API Client
|
|
@@ -15,6 +15,15 @@ declare class FetchBrainClient {
|
|
|
15
15
|
private batcher;
|
|
16
16
|
private learnBatcher;
|
|
17
17
|
private logger;
|
|
18
|
+
/**
|
|
19
|
+
* Epoch ms until which learns are paused after the API reported the monthly
|
|
20
|
+
* learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
|
|
21
|
+
*/
|
|
22
|
+
private learnPausedUntil;
|
|
23
|
+
/** Warn about the learn cap once per pause, independent of the pause state. */
|
|
24
|
+
private learnCapWarnedUntil;
|
|
25
|
+
/** Valid, normalized scraper name (option, else env var); undefined = default memory. */
|
|
26
|
+
private scraperName;
|
|
18
27
|
constructor(config: FetchBrainConfig);
|
|
19
28
|
/**
|
|
20
29
|
* Recall if FetchBrain "knows" a request
|
|
@@ -35,7 +44,7 @@ declare class FetchBrainClient {
|
|
|
35
44
|
*/
|
|
36
45
|
stats(): Promise<StatsResponse | null>;
|
|
37
46
|
/**
|
|
38
|
-
* Ask a natural-language question
|
|
47
|
+
* Ask a natural-language question, answered from everything the account has learned
|
|
39
48
|
*
|
|
40
49
|
* `model` picks the generation model for answer mode from the server's
|
|
41
50
|
* menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
|
|
@@ -127,7 +136,7 @@ interface FetchBrainContext {
|
|
|
127
136
|
* FetchBrain main class
|
|
128
137
|
*
|
|
129
138
|
* Provides the static enhance() method to wrap Crawlee crawlers
|
|
130
|
-
* with
|
|
139
|
+
* with brain recall and learning
|
|
131
140
|
*/
|
|
132
141
|
declare class FetchBrain {
|
|
133
142
|
private client;
|
|
@@ -181,9 +190,9 @@ interface DatasetLike {
|
|
|
181
190
|
open?: (name?: string | null) => Promise<DatasetLike>;
|
|
182
191
|
}
|
|
183
192
|
/**
|
|
184
|
-
*
|
|
193
|
+
* Learning-aware pushData wrapper
|
|
185
194
|
*
|
|
186
|
-
* Use this instead of Dataset.pushData()
|
|
195
|
+
* Use this instead of Dataset.pushData() so the brain learns from what you push.
|
|
187
196
|
* Works with both static Dataset class and dataset instances.
|
|
188
197
|
*
|
|
189
198
|
* @example
|
|
@@ -295,8 +304,9 @@ declare function createLogger(minLevel?: LogLevel, enabled?: boolean): Logger;
|
|
|
295
304
|
/**
|
|
296
305
|
* Telemetry Collection Module
|
|
297
306
|
*
|
|
298
|
-
* Collects
|
|
299
|
-
*
|
|
307
|
+
* Collects opt-in, pseudonymous performance and behavior data from Crawlee contexts
|
|
308
|
+
* (sent with the API key, so linked to the account). Raw URLs, bodies, proxy URLs/IPs
|
|
309
|
+
* and error messages are not collected; hostname, path pattern and label are.
|
|
300
310
|
*/
|
|
301
311
|
|
|
302
312
|
/**
|
package/dist/index.js
CHANGED
|
@@ -323,16 +323,38 @@ var DENYLIST = /TOKEN|SECRET|PASSWORD|CREDENTIAL|KEY|AUTH|COOKIE/i;
|
|
|
323
323
|
var CREDENTIAL_VALUE = /^[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$|\/\/[^/\s@]+:[^/\s@]+@/;
|
|
324
324
|
var MAX_VALUE_LENGTH = 256;
|
|
325
325
|
var MAX_HEADER_LENGTH = 2048;
|
|
326
|
-
|
|
326
|
+
var SCRAPER_NAME_VAR = "FETCHBRAIN_SCRAPER_ID";
|
|
327
|
+
var SCRAPER_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
328
|
+
function normalizeScraperName(raw) {
|
|
329
|
+
const name = raw?.trim().toLowerCase();
|
|
330
|
+
return name && SCRAPER_NAME.test(name) ? name : void 0;
|
|
331
|
+
}
|
|
332
|
+
function resolveScraperName(option, env = process.env) {
|
|
333
|
+
const rejected = [];
|
|
334
|
+
const candidates = [
|
|
335
|
+
["option", option],
|
|
336
|
+
[SCRAPER_NAME_VAR, env[SCRAPER_NAME_VAR]]
|
|
337
|
+
];
|
|
338
|
+
for (const [source, raw] of candidates) {
|
|
339
|
+
if (raw === void 0 || raw.trim() === "") continue;
|
|
340
|
+
const name = normalizeScraperName(raw);
|
|
341
|
+
if (name) return { name, rejected };
|
|
342
|
+
rejected.push(source);
|
|
343
|
+
}
|
|
344
|
+
return { rejected };
|
|
345
|
+
}
|
|
346
|
+
function buildNativeContext(env = process.env, scraper) {
|
|
327
347
|
const context = {};
|
|
328
|
-
const
|
|
329
|
-
|
|
330
|
-
|
|
348
|
+
const name = normalizeScraperName(scraper);
|
|
349
|
+
if (name) context[SCRAPER_NAME_VAR] = name;
|
|
350
|
+
const names = Object.keys(env).filter((n) => n !== SCRAPER_NAME_VAR && ALLOWED_NAME.test(n) && !DENYLIST.test(n)).sort();
|
|
351
|
+
for (const varName of names) {
|
|
352
|
+
const value = env[varName];
|
|
331
353
|
if (!value || value.length > MAX_VALUE_LENGTH) continue;
|
|
332
354
|
if (CREDENTIAL_VALUE.test(value)) continue;
|
|
333
|
-
const candidate = { ...context, [
|
|
355
|
+
const candidate = { ...context, [varName]: value };
|
|
334
356
|
if (JSON.stringify(candidate).length > MAX_HEADER_LENGTH) break;
|
|
335
|
-
context[
|
|
357
|
+
context[varName] = value;
|
|
336
358
|
}
|
|
337
359
|
if (Object.keys(context).length === 0) return void 0;
|
|
338
360
|
return JSON.stringify(context);
|
|
@@ -355,13 +377,24 @@ function clampBatch(batch, cap) {
|
|
|
355
377
|
return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
|
|
356
378
|
}
|
|
357
379
|
var ApiError = class extends Error {
|
|
358
|
-
constructor(status, statusText, serverError) {
|
|
380
|
+
constructor(status, statusText, serverError, code, retryAfterSec) {
|
|
359
381
|
super(`API error: ${status} ${statusText}`);
|
|
360
382
|
this.status = status;
|
|
361
383
|
this.serverError = serverError;
|
|
384
|
+
this.code = code;
|
|
385
|
+
this.retryAfterSec = retryAfterSec;
|
|
362
386
|
this.name = "ApiError";
|
|
363
387
|
}
|
|
364
388
|
};
|
|
389
|
+
function parseRetryAfter(header) {
|
|
390
|
+
if (!header) return void 0;
|
|
391
|
+
const secs = Number(header);
|
|
392
|
+
if (Number.isFinite(secs)) return secs > 0 ? secs : void 0;
|
|
393
|
+
const at = Date.parse(header);
|
|
394
|
+
if (Number.isNaN(at)) return void 0;
|
|
395
|
+
const delta = (at - Date.now()) / 1e3;
|
|
396
|
+
return delta > 0 ? delta : void 0;
|
|
397
|
+
}
|
|
365
398
|
var currentContext = {};
|
|
366
399
|
function setScrapeContext(ctx) {
|
|
367
400
|
currentContext = ctx;
|
|
@@ -371,6 +404,13 @@ function clearScrapeContext() {
|
|
|
371
404
|
}
|
|
372
405
|
var FetchBrainClient = class {
|
|
373
406
|
constructor(config) {
|
|
407
|
+
/**
|
|
408
|
+
* Epoch ms until which learns are paused after the API reported the monthly
|
|
409
|
+
* learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
|
|
410
|
+
*/
|
|
411
|
+
this.learnPausedUntil = 0;
|
|
412
|
+
/** Warn about the learn cap once per pause, independent of the pause state. */
|
|
413
|
+
this.learnCapWarnedUntil = 0;
|
|
374
414
|
this.config = {
|
|
375
415
|
apiKey: config.apiKey,
|
|
376
416
|
baseUrl: config.baseUrl || DEFAULT_BASE_URL,
|
|
@@ -390,10 +430,18 @@ var FetchBrainClient = class {
|
|
|
390
430
|
// enhance-only; stored so getConfig() round-trips
|
|
391
431
|
preRecall: config.preRecall,
|
|
392
432
|
// enhance-only; stored so getConfig() round-trips
|
|
393
|
-
onRecalled: config.onRecalled
|
|
433
|
+
onRecalled: config.onRecalled,
|
|
394
434
|
// enhance-only; stored so getConfig() round-trips
|
|
435
|
+
scraper: config.scraper
|
|
395
436
|
};
|
|
396
437
|
this.logger = createLogger(this.config.debug ? "debug" : "info", true);
|
|
438
|
+
const scraper = resolveScraperName(config.scraper);
|
|
439
|
+
this.scraperName = scraper.name;
|
|
440
|
+
for (const source of scraper.rejected) {
|
|
441
|
+
this.logger.warn(
|
|
442
|
+
`ignoring invalid scraper name from ${source === "option" ? "the scraper option" : source}; use 1-64 lowercase letters, digits, '.', '_' or '-', starting with a letter or digit. ` + (scraper.name ? `Using "${scraper.name}" instead.` : "This scraper uses the shared default memory.")
|
|
443
|
+
);
|
|
444
|
+
}
|
|
397
445
|
this.circuitBreaker = new CircuitBreaker(
|
|
398
446
|
this.config.circuitBreaker,
|
|
399
447
|
this.logger
|
|
@@ -464,12 +512,15 @@ var FetchBrainClient = class {
|
|
|
464
512
|
if (!this.config.learning) {
|
|
465
513
|
return { status: "rejected", learned: 0 };
|
|
466
514
|
}
|
|
467
|
-
if (this.circuitBreaker.isOpen()) {
|
|
515
|
+
if (Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
|
|
468
516
|
return { status: "rejected", learned: 0 };
|
|
469
517
|
}
|
|
470
518
|
try {
|
|
471
519
|
return await this.learnBatcher.learn(request, data);
|
|
472
520
|
} catch (error) {
|
|
521
|
+
if (error instanceof ApiError && error.code === "LEARN_CAP_EXCEEDED") {
|
|
522
|
+
return { status: "rejected", learned: 0 };
|
|
523
|
+
}
|
|
473
524
|
this.logger.warn("Learn failed:", error);
|
|
474
525
|
return { status: "rejected", learned: 0 };
|
|
475
526
|
}
|
|
@@ -494,7 +545,7 @@ var FetchBrainClient = class {
|
|
|
494
545
|
}
|
|
495
546
|
}
|
|
496
547
|
/**
|
|
497
|
-
* Ask a natural-language question
|
|
548
|
+
* Ask a natural-language question, answered from everything the account has learned
|
|
498
549
|
*
|
|
499
550
|
* `model` picks the generation model for answer mode from the server's
|
|
500
551
|
* menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
|
|
@@ -600,6 +651,24 @@ var FetchBrainClient = class {
|
|
|
600
651
|
this.circuitBreaker.recordSuccess();
|
|
601
652
|
return response;
|
|
602
653
|
} catch (error) {
|
|
654
|
+
if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
|
|
655
|
+
if (error.code === "LEARN_CAP_EXCEEDED") {
|
|
656
|
+
const now = /* @__PURE__ */ new Date();
|
|
657
|
+
const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
|
|
658
|
+
this.learnPausedUntil = Math.max(this.learnPausedUntil, monthStart);
|
|
659
|
+
if (this.learnCapWarnedUntil < monthStart) {
|
|
660
|
+
this.learnCapWarnedUntil = monthStart;
|
|
661
|
+
this.logger.warn(
|
|
662
|
+
"FetchBrain monthly learning limit reached \u2014 learning is paused until the 1st (UTC); recall keeps working."
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
} else if (error.status === 429) {
|
|
666
|
+
const waitMs = Math.min(Math.max(error.retryAfterSec ?? 30, 1), 3600) * 1e3;
|
|
667
|
+
this.learnPausedUntil = Math.max(this.learnPausedUntil, Date.now() + waitMs);
|
|
668
|
+
this.logger.debug(`Learn rate-limited; pausing learns for ${waitMs / 1e3}s`);
|
|
669
|
+
}
|
|
670
|
+
throw error;
|
|
671
|
+
}
|
|
603
672
|
this.circuitBreaker.recordFailure();
|
|
604
673
|
throw error;
|
|
605
674
|
}
|
|
@@ -622,7 +691,7 @@ var FetchBrainClient = class {
|
|
|
622
691
|
if (process.env.NODE_ENV) {
|
|
623
692
|
contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
|
|
624
693
|
}
|
|
625
|
-
const nativeContext = buildNativeContext();
|
|
694
|
+
const nativeContext = buildNativeContext(process.env, this.scraperName);
|
|
626
695
|
if (nativeContext) {
|
|
627
696
|
contextHeaders["X-FB-Context"] = nativeContext;
|
|
628
697
|
}
|
|
@@ -645,12 +714,21 @@ var FetchBrainClient = class {
|
|
|
645
714
|
});
|
|
646
715
|
if (!response.ok) {
|
|
647
716
|
let serverError;
|
|
717
|
+
let code;
|
|
648
718
|
try {
|
|
649
719
|
const errBody = await response.json();
|
|
650
720
|
if (typeof errBody.error === "string") serverError = errBody.error;
|
|
721
|
+
const specific = errBody.details?.code ?? errBody.code;
|
|
722
|
+
if (typeof specific === "string") code = specific;
|
|
651
723
|
} catch {
|
|
652
724
|
}
|
|
653
|
-
throw new ApiError(
|
|
725
|
+
throw new ApiError(
|
|
726
|
+
response.status,
|
|
727
|
+
response.statusText,
|
|
728
|
+
serverError,
|
|
729
|
+
code,
|
|
730
|
+
parseRetryAfter(response.headers.get("Retry-After"))
|
|
731
|
+
);
|
|
654
732
|
}
|
|
655
733
|
return await response.json();
|
|
656
734
|
} finally {
|