@fetchbrain.com/sdk 0.2.0 → 0.3.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/dist/index.mjs CHANGED
@@ -315,10 +315,44 @@ function createLogger(minLevel = "info", enabled = true) {
315
315
  };
316
316
  }
317
317
 
318
+ // src/native-context.ts
319
+ var ALLOWED_NAME = /_ID$|^(NODE_ENV|REGION|CI)$/;
320
+ var DENYLIST = /TOKEN|SECRET|PASSWORD|CREDENTIAL|KEY|AUTH|COOKIE/i;
321
+ var CREDENTIAL_VALUE = /^[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}$|\/\/[^/\s@]+:[^/\s@]+@/;
322
+ var MAX_VALUE_LENGTH = 256;
323
+ var MAX_HEADER_LENGTH = 2048;
324
+ function buildNativeContext(env = process.env) {
325
+ 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];
329
+ if (!value || value.length > MAX_VALUE_LENGTH) continue;
330
+ if (CREDENTIAL_VALUE.test(value)) continue;
331
+ const candidate = { ...context, [name]: value };
332
+ if (JSON.stringify(candidate).length > MAX_HEADER_LENGTH) break;
333
+ context[name] = value;
334
+ }
335
+ if (Object.keys(context).length === 0) return void 0;
336
+ return JSON.stringify(context);
337
+ }
338
+ function getPlatformBuildId(env = process.env) {
339
+ const key = Object.keys(env).find((name) => name.endsWith("BUILD_ID"));
340
+ return key ? env[key] || void 0 : void 0;
341
+ }
342
+
318
343
  // src/client.ts
319
344
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
320
345
  var DEFAULT_TIMEOUT = 500;
321
346
  var DEFAULT_LEARN_TIMEOUT = 5e3;
347
+ var ASK_TIMEOUT = 1e4;
348
+ var ApiError = class extends Error {
349
+ constructor(status, statusText, serverError) {
350
+ super(`API error: ${status} ${statusText}`);
351
+ this.status = status;
352
+ this.serverError = serverError;
353
+ this.name = "ApiError";
354
+ }
355
+ };
322
356
  var currentContext = {};
323
357
  function setScrapeContext(ctx) {
324
358
  currentContext = ctx;
@@ -331,7 +365,7 @@ var FetchBrainClient = class {
331
365
  this.config = {
332
366
  apiKey: config.apiKey,
333
367
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
334
- intelligence: config.intelligence || "high",
368
+ memory: config.memory || "recent",
335
369
  learning: config.learning ?? true,
336
370
  alwaysRun: config.alwaysRun ?? false,
337
371
  refreshOnRebuild: config.refreshOnRebuild ?? false,
@@ -339,7 +373,8 @@ var FetchBrainClient = class {
339
373
  debug: config.debug || false,
340
374
  extractForLearning: config.extractForLearning,
341
375
  learnUrlField: config.learnUrlField,
342
- telemetry: config.telemetry ?? { enabled: true },
376
+ telemetry: config.telemetry ?? { enabled: false },
377
+ // opt-in
343
378
  batch: config.batch,
344
379
  circuitBreaker: config.circuitBreaker
345
380
  };
@@ -360,23 +395,23 @@ var FetchBrainClient = class {
360
395
  );
361
396
  }
362
397
  /**
363
- * Query if FetchBrain "knows" a request
398
+ * Recall if FetchBrain "knows" a request
364
399
  */
365
- async query(request) {
400
+ async recall(request) {
366
401
  if (this.circuitBreaker.isOpen()) {
367
402
  return { known: false, fallback: true };
368
403
  }
369
404
  try {
370
405
  return await this.batcher.query(request);
371
406
  } catch (error) {
372
- this.logger.debug("Query failed:", error);
407
+ this.logger.debug("Recall failed:", error);
373
408
  return { known: false, fallback: true };
374
409
  }
375
410
  }
376
411
  /**
377
- * Query multiple requests at once — returns ordered array matching input order
412
+ * Recall multiple requests at once — returns ordered array matching input order
378
413
  */
379
- async queryBulk(requests) {
414
+ async recallBulk(requests) {
380
415
  if (this.circuitBreaker.isOpen()) {
381
416
  return requests.map(() => ({ known: false, fallback: true }));
382
417
  }
@@ -424,6 +459,53 @@ var FetchBrainClient = class {
424
459
  return null;
425
460
  }
426
461
  }
462
+ /**
463
+ * Ask a natural-language question against learned knowledge
464
+ *
465
+ * `model` picks the generation model for answer mode from the server's
466
+ * menu (e.g. "llama-3.3-70b", "kimi-k2.5" — premium models cost extra ask
467
+ * credits), or "byok" to answer with your own linked provider model.
468
+ * Omit it for the default model.
469
+ */
470
+ async ask(question, opts) {
471
+ if (this.circuitBreaker.isOpen()) {
472
+ return { sources: [], status: "unavailable" };
473
+ }
474
+ const askBody = {
475
+ query: question,
476
+ answer: opts?.answer,
477
+ limit: opts?.limit,
478
+ model: opts?.model
479
+ };
480
+ const platformBuildId = getPlatformBuildId();
481
+ if (this.config.refreshOnRebuild && platformBuildId) {
482
+ askBody.build = platformBuildId;
483
+ }
484
+ try {
485
+ const response = await this.makeRequest(
486
+ "/v1/ask",
487
+ {
488
+ method: "POST",
489
+ body: JSON.stringify(askBody)
490
+ },
491
+ ASK_TIMEOUT
492
+ );
493
+ this.circuitBreaker.recordSuccess();
494
+ return response;
495
+ } catch (error) {
496
+ if (error instanceof ApiError && error.status >= 400 && error.status < 500) {
497
+ this.logger.debug("Ask rejected:", error);
498
+ return {
499
+ sources: [],
500
+ status: "rejected",
501
+ error: error.serverError ?? error.message
502
+ };
503
+ }
504
+ this.circuitBreaker.recordFailure();
505
+ this.logger.debug("Ask request failed:", error);
506
+ return { sources: [], status: "unavailable" };
507
+ }
508
+ }
427
509
  /**
428
510
  * Execute a batch query against the API
429
511
  */
@@ -431,19 +513,20 @@ var FetchBrainClient = class {
431
513
  const results = /* @__PURE__ */ new Map();
432
514
  const request = {
433
515
  items,
434
- intelligence: this.config.intelligence
516
+ memory: this.config.memory
435
517
  };
436
- if (this.config.refreshOnRebuild && process.env.APIFY_ACTOR_BUILD_ID) {
437
- request.build = process.env.APIFY_ACTOR_BUILD_ID;
518
+ const platformBuildId = getPlatformBuildId();
519
+ if (this.config.refreshOnRebuild && platformBuildId) {
520
+ request.build = platformBuildId;
438
521
  }
439
522
  try {
440
- const response = await this.makeRequest("/v1/query", {
523
+ const response = await this.makeRequest("/v1/recall", {
441
524
  method: "POST",
442
525
  body: JSON.stringify(request)
443
526
  });
444
527
  this.circuitBreaker.recordSuccess();
445
528
  for (const item of response.known) {
446
- results.set(item.ref, { known: true, data: item.data, confidence: item.confidence });
529
+ results.set(item.ref, { known: true, data: item.data });
447
530
  }
448
531
  for (const ref of response.unknown) {
449
532
  results.set(ref, { known: false });
@@ -462,12 +545,17 @@ var FetchBrainClient = class {
462
545
  request: e.request,
463
546
  data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
464
547
  }));
548
+ const request = { entries: processed };
549
+ const platformBuildId = getPlatformBuildId();
550
+ if (this.config.refreshOnRebuild && platformBuildId) {
551
+ request.build = platformBuildId;
552
+ }
465
553
  try {
466
554
  const response = await this.makeRequest(
467
555
  "/v1/learn",
468
556
  {
469
557
  method: "POST",
470
- body: JSON.stringify({ entries: processed })
558
+ body: JSON.stringify(request)
471
559
  },
472
560
  DEFAULT_LEARN_TIMEOUT
473
561
  );
@@ -496,14 +584,9 @@ var FetchBrainClient = class {
496
584
  if (process.env.NODE_ENV) {
497
585
  contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
498
586
  }
499
- if (process.env.APIFY_ACTOR_ID) {
500
- contextHeaders["X-FB-Apify"] = process.env.APIFY_ACTOR_ID;
501
- }
502
- if (process.env.APIFY_ACTOR_BUILD_ID) {
503
- contextHeaders["X-FB-Build"] = process.env.APIFY_ACTOR_BUILD_ID;
504
- }
505
- if (process.env.APIFY_ACTOR_RUN_ID) {
506
- contextHeaders["X-FB-Apify-Run"] = process.env.APIFY_ACTOR_RUN_ID;
587
+ const nativeContext = buildNativeContext();
588
+ if (nativeContext) {
589
+ contextHeaders["X-FB-Context"] = nativeContext;
507
590
  }
508
591
  if (currentContext.crawler) {
509
592
  contextHeaders["X-FB-Crawler"] = currentContext.crawler;
@@ -523,7 +606,13 @@ var FetchBrainClient = class {
523
606
  signal: controller.signal
524
607
  });
525
608
  if (!response.ok) {
526
- throw new Error(`API error: ${response.status} ${response.statusText}`);
609
+ let serverError;
610
+ try {
611
+ const errBody = await response.json();
612
+ if (typeof errBody.error === "string") serverError = errBody.error;
613
+ } catch {
614
+ }
615
+ throw new ApiError(response.status, response.statusText, serverError);
527
616
  }
528
617
  return await response.json();
529
618
  } finally {
@@ -736,7 +825,7 @@ var TelemetryBuffer = class {
736
825
 
737
826
  // src/enhance.ts
738
827
  var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
739
- var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainKnown", "fetchBrainData", "__fetchBrainResult"]);
828
+ var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
740
829
  function buildRawRequest(request) {
741
830
  const r = request;
742
831
  let headers;
@@ -762,7 +851,7 @@ function warnDefaultUniqueKey(request, logger, warned) {
762
851
  const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
763
852
  if (method !== "GET" && isDefault && !warned.has(request.url)) {
764
853
  warned.add(request.url);
765
- logger.warn(`FetchBrain: ${method} ${request.url} has a default uniqueKey \u2014 set request.uniqueKey to your stable identity, or these requests won't be cached separately.`);
854
+ 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.`);
766
855
  }
767
856
  }
768
857
  var asyncContext = new AsyncLocalStorage();
@@ -786,14 +875,13 @@ var FetchBrain = class {
786
875
  this.logger = createLogger(config.debug ? "debug" : "info", true);
787
876
  }
788
877
  /**
789
- * Query if FetchBrain "knows" a URL
878
+ * Recall whether FetchBrain "knows" a URL
790
879
  */
791
- async query(options) {
792
- const result = await this.client.query({ url: options.url });
880
+ async recall(options) {
881
+ const result = await this.client.recall({ url: options.url });
793
882
  return {
794
883
  known: result.known,
795
- data: result.data,
796
- confidence: result.confidence
884
+ data: result.data
797
885
  };
798
886
  }
799
887
  /**
@@ -812,8 +900,8 @@ var FetchBrain = class {
812
900
  * Enhance a Crawlee crawler with FetchBrain optimization
813
901
  *
814
902
  * This wraps the crawler's request handler to:
815
- * 1. Query AI before making requests (AI knows = skip request)
816
- * 2. Teach AI after successful requests (learning)
903
+ * 1. Recall the brain before making requests (brain knows = skip request)
904
+ * 2. Teach the brain after successful requests (learning)
817
905
  *
818
906
  * @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
819
907
  * @param config - FetchBrain configuration
@@ -822,11 +910,12 @@ var FetchBrain = class {
822
910
  static enhance(crawler, config) {
823
911
  const client = new FetchBrainClient(config);
824
912
  const logger = createLogger(config.debug ? "debug" : "info", true);
913
+ const telemetryConfig = config.telemetry ?? { enabled: false };
825
914
  const telemetryBuffer = new TelemetryBuffer({
826
915
  maxSize: 50,
827
916
  flushInterval: 3e4,
828
917
  onFlush: async (entries) => {
829
- if (config.telemetry?.enabled) {
918
+ if (telemetryConfig.enabled) {
830
919
  await client.sendTelemetry(entries);
831
920
  logger.debug(`Telemetry: sent ${entries.length} entries`);
832
921
  }
@@ -834,9 +923,9 @@ var FetchBrain = class {
834
923
  });
835
924
  const runStats = {
836
925
  totalRequests: 0,
837
- aiKnown: 0,
926
+ recalled: 0,
838
927
  aiSkipped: 0,
839
- // AI knew + skipped scraping
928
+ // brain knew + skipped scraping
840
929
  learned: 0,
841
930
  scraped: 0,
842
931
  // Actually ran handler
@@ -863,36 +952,31 @@ var FetchBrain = class {
863
952
  const rawRequest = buildRawRequest(request);
864
953
  warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
865
954
  try {
866
- const aiResult = await client.query(rawRequest);
955
+ const aiResult = await client.recall(rawRequest);
867
956
  let usedAIData = false;
868
957
  const originalPushData = context.pushData;
869
- context.ai = {
958
+ context.brain = {
870
959
  known: aiResult.known,
871
960
  data: aiResult.data,
872
- confidence: aiResult.confidence,
873
- useAIData: async () => {
961
+ use: async () => {
874
962
  if (aiResult.known && aiResult.data && originalPushData) {
875
963
  usedAIData = true;
876
964
  await originalPushData.call(context, aiResult.data);
877
- logger.info(
878
- `Used AI data: ${url} (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
879
- );
965
+ logger.info(`Used brain data: ${url}`);
880
966
  }
881
967
  }
882
968
  };
883
969
  request.userData = {
884
970
  ...request.userData,
885
- fetchBrainKnown: aiResult.known,
971
+ fetchBrainRecalled: aiResult.known,
886
972
  fetchBrainData: aiResult.data
887
973
  };
888
974
  const handlerLabel = request.label;
889
975
  const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
890
976
  if (aiResult.known && aiResult.data && !runHandler) {
891
- runStats.aiKnown++;
977
+ runStats.recalled++;
892
978
  runStats.aiSkipped++;
893
- logger.info(
894
- `AI known: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
895
- );
979
+ logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
896
980
  if (originalPushData) {
897
981
  await originalPushData.call(context, aiResult.data);
898
982
  }
@@ -900,9 +984,9 @@ var FetchBrain = class {
900
984
  }
901
985
  runStats.scraped++;
902
986
  if (aiResult.known) {
903
- runStats.aiKnown++;
987
+ runStats.recalled++;
904
988
  logger.info(
905
- `Running handler [${handlerLabel || "default"}] with AI data available: ${url}`
989
+ `Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
906
990
  );
907
991
  } else {
908
992
  logger.debug(`Learning: ${url}`);
@@ -926,7 +1010,7 @@ var FetchBrain = class {
926
1010
  await asyncContext.run(requestContext, async () => {
927
1011
  await originalHandler.call(crawler, context);
928
1012
  });
929
- if (config.telemetry?.enabled) {
1013
+ if (telemetryConfig.enabled) {
930
1014
  try {
931
1015
  const telemetry = await collectTelemetry(
932
1016
  {
@@ -958,7 +1042,7 @@ var FetchBrain = class {
958
1042
  responseTime: Date.now() - startTime,
959
1043
  contentSize: context.response?.body?.length
960
1044
  },
961
- config.telemetry
1045
+ telemetryConfig
962
1046
  );
963
1047
  if (telemetry) {
964
1048
  telemetryBuffer.add(telemetry);
@@ -968,7 +1052,7 @@ var FetchBrain = class {
968
1052
  }
969
1053
  }
970
1054
  } catch (err) {
971
- if (config.telemetry?.enabled) {
1055
+ if (telemetryConfig.enabled) {
972
1056
  try {
973
1057
  const telemetry = await collectTelemetry(
974
1058
  {
@@ -986,7 +1070,7 @@ var FetchBrain = class {
986
1070
  endTime: Date.now(),
987
1071
  responseTime: Date.now() - startTime
988
1072
  },
989
- config.telemetry,
1073
+ telemetryConfig,
990
1074
  err instanceof Error ? err : new Error(String(err))
991
1075
  );
992
1076
  if (telemetry) {
@@ -1017,7 +1101,7 @@ var FetchBrain = class {
1017
1101
  } finally {
1018
1102
  logger.debug("Flushing pending learn requests on crawl complete");
1019
1103
  await client.flushLearnBatch();
1020
- if (config.telemetry?.enabled) {
1104
+ if (telemetryConfig.enabled) {
1021
1105
  logger.debug("Telemetry: flushing on crawl complete");
1022
1106
  await telemetryBuffer.stop();
1023
1107
  }
@@ -1026,7 +1110,7 @@ var FetchBrain = class {
1026
1110
  );
1027
1111
  const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
1028
1112
  logger.info(
1029
- `Finished! AI known: ${runStats.aiKnown}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
1113
+ `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
1030
1114
  );
1031
1115
  }
1032
1116
  };
@@ -1053,15 +1137,6 @@ async function pushData(data, dataset, datasetName) {
1053
1137
  }
1054
1138
  }
1055
1139
 
1056
- // src/types.ts
1057
- var AIMemoryDepth = /* @__PURE__ */ ((AIMemoryDepth2) => {
1058
- AIMemoryDepth2[AIMemoryDepth2["REALTIME"] = 1] = "REALTIME";
1059
- AIMemoryDepth2[AIMemoryDepth2["HIGH"] = 2] = "HIGH";
1060
- AIMemoryDepth2[AIMemoryDepth2["STANDARD"] = 3] = "STANDARD";
1061
- AIMemoryDepth2[AIMemoryDepth2["DEEP"] = 4] = "DEEP";
1062
- return AIMemoryDepth2;
1063
- })(AIMemoryDepth || {});
1064
-
1065
- export { AIMemoryDepth, CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, TelemetryBuffer, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
1140
+ export { CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, TelemetryBuffer, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
1066
1141
  //# sourceMappingURL=index.mjs.map
1067
1142
  //# sourceMappingURL=index.mjs.map