@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/dist/index.mjs CHANGED
@@ -321,16 +321,38 @@ var DENYLIST = /TOKEN|SECRET|PASSWORD|CREDENTIAL|KEY|AUTH|COOKIE/i;
321
321
  var CREDENTIAL_VALUE = /^[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$|\/\/[^/\s@]+:[^/\s@]+@/;
322
322
  var MAX_VALUE_LENGTH = 256;
323
323
  var MAX_HEADER_LENGTH = 2048;
324
- function buildNativeContext(env = process.env) {
324
+ var SCRAPER_NAME_VAR = "FETCHBRAIN_SCRAPER_ID";
325
+ var SCRAPER_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
326
+ function normalizeScraperName(raw) {
327
+ const name = raw?.trim().toLowerCase();
328
+ return name && SCRAPER_NAME.test(name) ? name : void 0;
329
+ }
330
+ function resolveScraperName(option, env = process.env) {
331
+ const rejected = [];
332
+ const candidates = [
333
+ ["option", option],
334
+ [SCRAPER_NAME_VAR, env[SCRAPER_NAME_VAR]]
335
+ ];
336
+ for (const [source, raw] of candidates) {
337
+ if (raw === void 0 || raw.trim() === "") continue;
338
+ const name = normalizeScraperName(raw);
339
+ if (name) return { name, rejected };
340
+ rejected.push(source);
341
+ }
342
+ return { rejected };
343
+ }
344
+ function buildNativeContext(env = process.env, scraper) {
325
345
  const context = {};
326
- const names = Object.keys(env).filter((name) => ALLOWED_NAME.test(name) && !DENYLIST.test(name)).sort();
327
- for (const name of names) {
328
- const value = env[name];
346
+ const name = normalizeScraperName(scraper);
347
+ if (name) context[SCRAPER_NAME_VAR] = name;
348
+ const names = Object.keys(env).filter((n) => n !== SCRAPER_NAME_VAR && ALLOWED_NAME.test(n) && !DENYLIST.test(n)).sort();
349
+ for (const varName of names) {
350
+ const value = env[varName];
329
351
  if (!value || value.length > MAX_VALUE_LENGTH) continue;
330
352
  if (CREDENTIAL_VALUE.test(value)) continue;
331
- const candidate = { ...context, [name]: value };
353
+ const candidate = { ...context, [varName]: value };
332
354
  if (JSON.stringify(candidate).length > MAX_HEADER_LENGTH) break;
333
- context[name] = value;
355
+ context[varName] = value;
334
356
  }
335
357
  if (Object.keys(context).length === 0) return void 0;
336
358
  return JSON.stringify(context);
@@ -353,13 +375,24 @@ function clampBatch(batch, cap) {
353
375
  return batch?.maxSize ? { ...batch, maxSize: Math.min(batch.maxSize, cap) } : batch;
354
376
  }
355
377
  var ApiError = class extends Error {
356
- constructor(status, statusText, serverError) {
378
+ constructor(status, statusText, serverError, code, retryAfterSec) {
357
379
  super(`API error: ${status} ${statusText}`);
358
380
  this.status = status;
359
381
  this.serverError = serverError;
382
+ this.code = code;
383
+ this.retryAfterSec = retryAfterSec;
360
384
  this.name = "ApiError";
361
385
  }
362
386
  };
387
+ function parseRetryAfter(header) {
388
+ if (!header) return void 0;
389
+ const secs = Number(header);
390
+ if (Number.isFinite(secs)) return secs > 0 ? secs : void 0;
391
+ const at = Date.parse(header);
392
+ if (Number.isNaN(at)) return void 0;
393
+ const delta = (at - Date.now()) / 1e3;
394
+ return delta > 0 ? delta : void 0;
395
+ }
363
396
  var currentContext = {};
364
397
  function setScrapeContext(ctx) {
365
398
  currentContext = ctx;
@@ -369,6 +402,13 @@ function clearScrapeContext() {
369
402
  }
370
403
  var FetchBrainClient = class {
371
404
  constructor(config) {
405
+ /**
406
+ * Epoch ms until which learns are paused after the API reported the monthly
407
+ * learn cap — the start of the next UTC month, when the cap resets. 0 = not paused.
408
+ */
409
+ this.learnPausedUntil = 0;
410
+ /** Warn about the learn cap once per pause, independent of the pause state. */
411
+ this.learnCapWarnedUntil = 0;
372
412
  this.config = {
373
413
  apiKey: config.apiKey,
374
414
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
@@ -388,10 +428,18 @@ var FetchBrainClient = class {
388
428
  // enhance-only; stored so getConfig() round-trips
389
429
  preRecall: config.preRecall,
390
430
  // enhance-only; stored so getConfig() round-trips
391
- onRecalled: config.onRecalled
431
+ onRecalled: config.onRecalled,
392
432
  // enhance-only; stored so getConfig() round-trips
433
+ scraper: config.scraper
393
434
  };
394
435
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
436
+ const scraper = resolveScraperName(config.scraper);
437
+ this.scraperName = scraper.name;
438
+ for (const source of scraper.rejected) {
439
+ this.logger.warn(
440
+ `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.")
441
+ );
442
+ }
395
443
  this.circuitBreaker = new CircuitBreaker(
396
444
  this.config.circuitBreaker,
397
445
  this.logger
@@ -462,12 +510,15 @@ var FetchBrainClient = class {
462
510
  if (!this.config.learning) {
463
511
  return { status: "rejected", learned: 0 };
464
512
  }
465
- if (this.circuitBreaker.isOpen()) {
513
+ if (Date.now() < this.learnPausedUntil || this.circuitBreaker.isOpen()) {
466
514
  return { status: "rejected", learned: 0 };
467
515
  }
468
516
  try {
469
517
  return await this.learnBatcher.learn(request, data);
470
518
  } catch (error) {
519
+ if (error instanceof ApiError && error.code === "LEARN_CAP_EXCEEDED") {
520
+ return { status: "rejected", learned: 0 };
521
+ }
471
522
  this.logger.warn("Learn failed:", error);
472
523
  return { status: "rejected", learned: 0 };
473
524
  }
@@ -492,7 +543,7 @@ var FetchBrainClient = class {
492
543
  }
493
544
  }
494
545
  /**
495
- * Ask a natural-language question against learned knowledge
546
+ * Ask a natural-language question, answered from everything the account has learned
496
547
  *
497
548
  * `model` picks the generation model for answer mode from the server's
498
549
  * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
@@ -598,6 +649,24 @@ var FetchBrainClient = class {
598
649
  this.circuitBreaker.recordSuccess();
599
650
  return response;
600
651
  } catch (error) {
652
+ if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
653
+ if (error.code === "LEARN_CAP_EXCEEDED") {
654
+ const now = /* @__PURE__ */ new Date();
655
+ const monthStart = Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1);
656
+ this.learnPausedUntil = Math.max(this.learnPausedUntil, monthStart);
657
+ if (this.learnCapWarnedUntil < monthStart) {
658
+ this.learnCapWarnedUntil = monthStart;
659
+ this.logger.warn(
660
+ "FetchBrain monthly learning limit reached \u2014 learning is paused until the 1st (UTC); recall keeps working."
661
+ );
662
+ }
663
+ } else if (error.status === 429) {
664
+ const waitMs = Math.min(Math.max(error.retryAfterSec ?? 30, 1), 3600) * 1e3;
665
+ this.learnPausedUntil = Math.max(this.learnPausedUntil, Date.now() + waitMs);
666
+ this.logger.debug(`Learn rate-limited; pausing learns for ${waitMs / 1e3}s`);
667
+ }
668
+ throw error;
669
+ }
601
670
  this.circuitBreaker.recordFailure();
602
671
  throw error;
603
672
  }
@@ -620,7 +689,7 @@ var FetchBrainClient = class {
620
689
  if (process.env.NODE_ENV) {
621
690
  contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
622
691
  }
623
- const nativeContext = buildNativeContext();
692
+ const nativeContext = buildNativeContext(process.env, this.scraperName);
624
693
  if (nativeContext) {
625
694
  contextHeaders["X-FB-Context"] = nativeContext;
626
695
  }
@@ -643,12 +712,21 @@ var FetchBrainClient = class {
643
712
  });
644
713
  if (!response.ok) {
645
714
  let serverError;
715
+ let code;
646
716
  try {
647
717
  const errBody = await response.json();
648
718
  if (typeof errBody.error === "string") serverError = errBody.error;
719
+ const specific = errBody.details?.code ?? errBody.code;
720
+ if (typeof specific === "string") code = specific;
649
721
  } catch {
650
722
  }
651
- throw new ApiError(response.status, response.statusText, serverError);
723
+ throw new ApiError(
724
+ response.status,
725
+ response.statusText,
726
+ serverError,
727
+ code,
728
+ parseRetryAfter(response.headers.get("Retry-After"))
729
+ );
652
730
  }
653
731
  return await response.json();
654
732
  } finally {