@fetchbrain.com/sdk 0.1.7 → 0.3.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
@@ -106,24 +106,23 @@ var RequestBatcher = class {
106
106
  constructor(executor, config = {}, logger) {
107
107
  this.queue = [];
108
108
  this.flushTimeout = null;
109
+ this.refSeq = 0;
109
110
  this.executor = executor;
110
111
  this.config = { ...DEFAULT_CONFIG2, ...config };
111
112
  this.logger = logger;
112
113
  }
113
114
  /**
114
- * Add a URL to the batch queue
115
+ * Add a request to the batch queue
115
116
  */
116
- async query(url) {
117
+ async query(request) {
117
118
  return new Promise((resolve, reject) => {
118
- this.queue.push({ url, resolve, reject });
119
+ this.queue.push({ ref: String(this.refSeq++), request, resolve, reject });
119
120
  if (this.queue.length >= this.config.maxSize) {
120
121
  this.flush();
121
122
  return;
122
123
  }
123
124
  if (!this.flushTimeout) {
124
- this.flushTimeout = setTimeout(() => {
125
- this.flush();
126
- }, this.config.maxWait);
125
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
127
126
  }
128
127
  });
129
128
  }
@@ -139,27 +138,20 @@ var RequestBatcher = class {
139
138
  return;
140
139
  }
141
140
  const batch = this.queue.splice(0, this.config.maxSize);
142
- const urls = batch.map((r) => r.url);
143
- this.logger.debug(`Flushing batch of ${urls.length} URLs`);
141
+ const items = batch.map((r) => ({ ref: r.ref, request: r.request }));
142
+ this.logger.debug(`Flushing batch of ${items.length} requests`);
144
143
  try {
145
- const results = await this.executor(urls);
146
- for (const request of batch) {
147
- const result = results.get(request.url);
148
- if (result) {
149
- request.resolve(result);
150
- } else {
151
- request.resolve({ known: false });
152
- }
144
+ const results = await this.executor(items);
145
+ for (const r of batch) {
146
+ r.resolve(results.get(r.ref) ?? { known: false });
153
147
  }
154
148
  } catch (error) {
155
- for (const request of batch) {
156
- request.reject(error);
149
+ for (const r of batch) {
150
+ r.reject(error);
157
151
  }
158
152
  }
159
153
  if (this.queue.length > 0) {
160
- this.flushTimeout = setTimeout(() => {
161
- this.flush();
162
- }, this.config.maxWait);
154
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
163
155
  }
164
156
  }
165
157
  /**
@@ -176,8 +168,8 @@ var RequestBatcher = class {
176
168
  clearTimeout(this.flushTimeout);
177
169
  this.flushTimeout = null;
178
170
  }
179
- for (const request of this.queue) {
180
- request.resolve({ known: false, fallback: true });
171
+ for (const r of this.queue) {
172
+ r.resolve({ known: false, fallback: true });
181
173
  }
182
174
  this.queue = [];
183
175
  }
@@ -193,17 +185,15 @@ var LearnBatcher = class {
193
185
  /**
194
186
  * Add a learn entry to the batch queue
195
187
  */
196
- async learn(url, data) {
188
+ async learn(request, data) {
197
189
  return new Promise((resolve, reject) => {
198
- this.queue.push({ entry: { url, data }, resolve, reject });
190
+ this.queue.push({ entry: { request, data }, resolve, reject });
199
191
  if (this.queue.length >= this.config.maxSize) {
200
192
  this.flush();
201
193
  return;
202
194
  }
203
195
  if (!this.flushTimeout) {
204
- this.flushTimeout = setTimeout(() => {
205
- this.flush();
206
- }, this.config.maxWait);
196
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
207
197
  }
208
198
  });
209
199
  }
@@ -223,18 +213,16 @@ var LearnBatcher = class {
223
213
  this.logger.debug(`Flushing learn batch of ${entries.length} entries`);
224
214
  try {
225
215
  const result = await this.executor(entries);
226
- for (const request of batch) {
227
- request.resolve(result);
216
+ for (const r of batch) {
217
+ r.resolve(result);
228
218
  }
229
219
  } catch (error) {
230
- for (const request of batch) {
231
- request.reject(error);
220
+ for (const r of batch) {
221
+ r.reject(error);
232
222
  }
233
223
  }
234
224
  if (this.queue.length > 0) {
235
- this.flushTimeout = setTimeout(() => {
236
- this.flush();
237
- }, this.config.maxWait);
225
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
238
226
  }
239
227
  }
240
228
  /**
@@ -259,8 +247,8 @@ var LearnBatcher = class {
259
247
  clearTimeout(this.flushTimeout);
260
248
  this.flushTimeout = null;
261
249
  }
262
- for (const request of this.queue) {
263
- request.resolve({ status: "rejected", learned: 0 });
250
+ for (const r of this.queue) {
251
+ r.resolve({ status: "rejected", learned: 0 });
264
252
  }
265
253
  this.queue = [];
266
254
  }
@@ -327,10 +315,43 @@ function createLogger(minLevel = "info", enabled = true) {
327
315
  };
328
316
  }
329
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
+
330
343
  // src/client.ts
331
344
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
332
345
  var DEFAULT_TIMEOUT = 500;
333
346
  var DEFAULT_LEARN_TIMEOUT = 5e3;
347
+ var ASK_TIMEOUT = 1e4;
348
+ var ApiError = class extends Error {
349
+ constructor(status, statusText) {
350
+ super(`API error: ${status} ${statusText}`);
351
+ this.status = status;
352
+ this.name = "ApiError";
353
+ }
354
+ };
334
355
  var currentContext = {};
335
356
  function setScrapeContext(ctx) {
336
357
  currentContext = ctx;
@@ -343,7 +364,7 @@ var FetchBrainClient = class {
343
364
  this.config = {
344
365
  apiKey: config.apiKey,
345
366
  baseUrl: config.baseUrl || DEFAULT_BASE_URL,
346
- intelligence: config.intelligence || "high",
367
+ memory: config.memory || "recent",
347
368
  learning: config.learning ?? true,
348
369
  alwaysRun: config.alwaysRun ?? false,
349
370
  refreshOnRebuild: config.refreshOnRebuild ?? false,
@@ -351,7 +372,8 @@ var FetchBrainClient = class {
351
372
  debug: config.debug || false,
352
373
  extractForLearning: config.extractForLearning,
353
374
  learnUrlField: config.learnUrlField,
354
- telemetry: config.telemetry ?? { enabled: true },
375
+ telemetry: config.telemetry ?? { enabled: false },
376
+ // opt-in
355
377
  batch: config.batch,
356
378
  circuitBreaker: config.circuitBreaker
357
379
  };
@@ -361,7 +383,7 @@ var FetchBrainClient = class {
361
383
  this.logger
362
384
  );
363
385
  this.batcher = new RequestBatcher(
364
- (urls) => this.executeBatchQuery(urls),
386
+ (items) => this.executeBatchQuery(items),
365
387
  this.config.batch,
366
388
  this.logger
367
389
  );
@@ -372,56 +394,48 @@ var FetchBrainClient = class {
372
394
  );
373
395
  }
374
396
  /**
375
- * Query if FetchBrain "knows" a URL
397
+ * Recall if FetchBrain "knows" a request
376
398
  */
377
- async query(url) {
399
+ async recall(request) {
378
400
  if (this.circuitBreaker.isOpen()) {
379
- this.logger.debug(`Circuit open, skipping query for: ${url}`);
380
401
  return { known: false, fallback: true };
381
402
  }
382
403
  try {
383
- return await this.batcher.query(url);
404
+ return await this.batcher.query(request);
384
405
  } catch (error) {
385
- this.logger.debug(`Query failed for ${url}:`, error);
406
+ this.logger.debug("Recall failed:", error);
386
407
  return { known: false, fallback: true };
387
408
  }
388
409
  }
389
410
  /**
390
- * Query multiple URLs at once (bypass batcher for bulk operations)
411
+ * Recall multiple requests at once — returns ordered array matching input order
391
412
  */
392
- async queryBulk(urls) {
413
+ async recallBulk(requests) {
393
414
  if (this.circuitBreaker.isOpen()) {
394
- this.logger.debug(`Circuit open, skipping bulk query`);
395
- return new Map(
396
- urls.map((url) => [url, { known: false, fallback: true }])
397
- );
415
+ return requests.map(() => ({ known: false, fallback: true }));
398
416
  }
399
417
  try {
400
- return await this.executeBatchQuery(urls);
401
- } catch (error) {
402
- this.logger.debug(`Bulk query failed:`, error);
403
- return new Map(
404
- urls.map((url) => [url, { known: false, fallback: true }])
405
- );
418
+ const items = requests.map((request, i) => ({ ref: String(i), request }));
419
+ const results = await this.executeBatchQuery(items);
420
+ return items.map((i) => results.get(i.ref) ?? { known: false });
421
+ } catch {
422
+ return requests.map(() => ({ known: false, fallback: true }));
406
423
  }
407
424
  }
408
425
  /**
409
426
  * "Teach" FetchBrain new data (batched for high-concurrency)
410
427
  */
411
- async learn(url, data) {
428
+ async learn(request, data) {
412
429
  if (!this.config.learning) {
413
430
  return { status: "rejected", learned: 0 };
414
431
  }
415
432
  if (this.circuitBreaker.isOpen()) {
416
- this.logger.debug(`Circuit open, skipping learn for: ${url}`);
417
433
  return { status: "rejected", learned: 0 };
418
434
  }
419
435
  try {
420
- const response = await this.learnBatcher.learn(url, data);
421
- this.logger.debug(`Learned data for: ${url}`);
422
- return response;
436
+ return await this.learnBatcher.learn(request, data);
423
437
  } catch (error) {
424
- this.logger.warn(`Learn failed for ${url}:`, error);
438
+ this.logger.warn("Learn failed:", error);
425
439
  return { status: "rejected", learned: 0 };
426
440
  }
427
441
  }
@@ -444,33 +458,61 @@ var FetchBrainClient = class {
444
458
  return null;
445
459
  }
446
460
  }
461
+ /**
462
+ * Ask a natural-language question against learned knowledge
463
+ */
464
+ async ask(question, opts) {
465
+ if (this.circuitBreaker.isOpen()) {
466
+ return { sources: [], status: "unavailable" };
467
+ }
468
+ try {
469
+ const response = await this.makeRequest(
470
+ "/v1/ask",
471
+ {
472
+ method: "POST",
473
+ body: JSON.stringify({
474
+ query: question,
475
+ answer: opts?.answer,
476
+ limit: opts?.limit
477
+ })
478
+ },
479
+ ASK_TIMEOUT
480
+ );
481
+ this.circuitBreaker.recordSuccess();
482
+ return response;
483
+ } catch (error) {
484
+ const isClientError = error instanceof ApiError && error.status >= 400 && error.status < 500;
485
+ if (!isClientError) {
486
+ this.circuitBreaker.recordFailure();
487
+ }
488
+ this.logger.debug("Ask request failed:", error);
489
+ return { sources: [], status: "unavailable" };
490
+ }
491
+ }
447
492
  /**
448
493
  * Execute a batch query against the API
449
494
  */
450
- async executeBatchQuery(urls) {
495
+ async executeBatchQuery(items) {
451
496
  const results = /* @__PURE__ */ new Map();
452
497
  const request = {
453
- urls,
454
- intelligence: this.config.intelligence
498
+ items,
499
+ memory: this.config.memory
455
500
  };
456
- if (this.config.refreshOnRebuild && process.env.APIFY_ACTOR_BUILD_ID) {
457
- request.build = process.env.APIFY_ACTOR_BUILD_ID;
501
+ const platformBuildId = getPlatformBuildId();
502
+ if (this.config.refreshOnRebuild && platformBuildId) {
503
+ request.build = platformBuildId;
458
504
  }
459
505
  try {
460
- const response = await this.makeRequest("/v1/query", {
506
+ const response = await this.makeRequest("/v1/recall", {
461
507
  method: "POST",
462
508
  body: JSON.stringify(request)
463
509
  });
464
510
  this.circuitBreaker.recordSuccess();
465
511
  for (const item of response.known) {
466
- results.set(item.url, {
467
- known: true,
468
- data: item.data,
469
- confidence: item.confidence
470
- });
512
+ results.set(item.ref, { known: true, data: item.data });
471
513
  }
472
- for (const url of response.unknown) {
473
- results.set(url, { known: false });
514
+ for (const ref of response.unknown) {
515
+ results.set(ref, { known: false });
474
516
  }
475
517
  return results;
476
518
  } catch (error) {
@@ -482,23 +524,20 @@ var FetchBrainClient = class {
482
524
  * Execute a batch learn against the API
483
525
  */
484
526
  async executeBatchLearn(entries) {
485
- const processedEntries = entries.map((entry) => ({
486
- url: entry.url,
487
- data: this.config.extractForLearning ? this.config.extractForLearning(entry.data) : entry.data
527
+ const processed = entries.map((e) => ({
528
+ request: e.request,
529
+ data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
488
530
  }));
489
531
  try {
490
532
  const response = await this.makeRequest(
491
533
  "/v1/learn",
492
534
  {
493
535
  method: "POST",
494
- body: JSON.stringify({
495
- entries: processedEntries
496
- })
536
+ body: JSON.stringify({ entries: processed })
497
537
  },
498
538
  DEFAULT_LEARN_TIMEOUT
499
539
  );
500
540
  this.circuitBreaker.recordSuccess();
501
- this.logger.debug(`Batch learned ${entries.length} entries`);
502
541
  return response;
503
542
  } catch (error) {
504
543
  this.circuitBreaker.recordFailure();
@@ -523,14 +562,9 @@ var FetchBrainClient = class {
523
562
  if (process.env.NODE_ENV) {
524
563
  contextHeaders["X-FB-Env"] = process.env.NODE_ENV;
525
564
  }
526
- if (process.env.APIFY_ACTOR_ID) {
527
- contextHeaders["X-FB-Apify"] = process.env.APIFY_ACTOR_ID;
528
- }
529
- if (process.env.APIFY_ACTOR_BUILD_ID) {
530
- contextHeaders["X-FB-Build"] = process.env.APIFY_ACTOR_BUILD_ID;
531
- }
532
- if (process.env.APIFY_ACTOR_RUN_ID) {
533
- contextHeaders["X-FB-Apify-Run"] = process.env.APIFY_ACTOR_RUN_ID;
565
+ const nativeContext = buildNativeContext();
566
+ if (nativeContext) {
567
+ contextHeaders["X-FB-Context"] = nativeContext;
534
568
  }
535
569
  if (currentContext.crawler) {
536
570
  contextHeaders["X-FB-Crawler"] = currentContext.crawler;
@@ -550,7 +584,7 @@ var FetchBrainClient = class {
550
584
  signal: controller.signal
551
585
  });
552
586
  if (!response.ok) {
553
- throw new Error(`API error: ${response.status} ${response.statusText}`);
587
+ throw new ApiError(response.status, response.statusText);
554
588
  }
555
589
  return await response.json();
556
590
  } finally {
@@ -762,6 +796,36 @@ var TelemetryBuffer = class {
762
796
  };
763
797
 
764
798
  // src/enhance.ts
799
+ var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
800
+ var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainRecalled", "fetchBrainData", "__fetchBrainResult"]);
801
+ function buildRawRequest(request) {
802
+ const r = request;
803
+ let headers;
804
+ if (r.headers) {
805
+ headers = {};
806
+ for (const [k, v] of Object.entries(r.headers)) {
807
+ if (!STRIP_HEADERS.has(k.toLowerCase()) && typeof v === "string") headers[k] = v;
808
+ }
809
+ if (Object.keys(headers).length === 0) headers = void 0;
810
+ }
811
+ let userData;
812
+ if (r.userData) {
813
+ userData = {};
814
+ for (const [k, v] of Object.entries(r.userData)) if (!SDK_USERDATA_KEYS.has(k)) userData[k] = v;
815
+ if (Object.keys(userData).length === 0) userData = void 0;
816
+ }
817
+ let body;
818
+ if (typeof r.payload === "string") body = r.payload;
819
+ return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: r.label };
820
+ }
821
+ function warnDefaultUniqueKey(request, logger, warned) {
822
+ const method = (request.method ?? "GET").toUpperCase();
823
+ const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
824
+ if (method !== "GET" && isDefault && !warned.has(request.url)) {
825
+ warned.add(request.url);
826
+ 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.`);
827
+ }
828
+ }
765
829
  var asyncContext = new AsyncLocalStorage();
766
830
  function getCurrentContext() {
767
831
  return asyncContext.getStore();
@@ -777,28 +841,26 @@ function shouldRunHandler(alwaysRun, label) {
777
841
  const requestLabel = label || "default";
778
842
  return labels.includes(requestLabel);
779
843
  }
780
- var requestContextMap = /* @__PURE__ */ new WeakMap();
781
844
  var FetchBrain = class {
782
845
  constructor(config) {
783
846
  this.client = new FetchBrainClient(config);
784
847
  this.logger = createLogger(config.debug ? "debug" : "info", true);
785
848
  }
786
849
  /**
787
- * Query if FetchBrain "knows" a URL
850
+ * Recall whether FetchBrain "knows" a URL
788
851
  */
789
- async query(options) {
790
- const result = await this.client.query(options.url);
852
+ async recall(options) {
853
+ const result = await this.client.recall({ url: options.url });
791
854
  return {
792
855
  known: result.known,
793
- data: result.data,
794
- confidence: result.confidence
856
+ data: result.data
795
857
  };
796
858
  }
797
859
  /**
798
860
  * "Teach" FetchBrain new data
799
861
  */
800
862
  async learn(options) {
801
- return this.client.learn(options.url, options.data);
863
+ return this.client.learn({ url: options.url }, options.data);
802
864
  }
803
865
  /**
804
866
  * Get usage statistics
@@ -810,8 +872,8 @@ var FetchBrain = class {
810
872
  * Enhance a Crawlee crawler with FetchBrain optimization
811
873
  *
812
874
  * This wraps the crawler's request handler to:
813
- * 1. Query AI before making requests (AI knows = skip request)
814
- * 2. Teach AI after successful requests (learning)
875
+ * 1. Recall the brain before making requests (brain knows = skip request)
876
+ * 2. Teach the brain after successful requests (learning)
815
877
  *
816
878
  * @param crawler - Any Crawlee crawler (CheerioCrawler, PlaywrightCrawler, etc.)
817
879
  * @param config - FetchBrain configuration
@@ -820,11 +882,12 @@ var FetchBrain = class {
820
882
  static enhance(crawler, config) {
821
883
  const client = new FetchBrainClient(config);
822
884
  const logger = createLogger(config.debug ? "debug" : "info", true);
885
+ const telemetryConfig = config.telemetry ?? { enabled: false };
823
886
  const telemetryBuffer = new TelemetryBuffer({
824
887
  maxSize: 50,
825
888
  flushInterval: 3e4,
826
889
  onFlush: async (entries) => {
827
- if (config.telemetry?.enabled) {
890
+ if (telemetryConfig.enabled) {
828
891
  await client.sendTelemetry(entries);
829
892
  logger.debug(`Telemetry: sent ${entries.length} entries`);
830
893
  }
@@ -832,9 +895,9 @@ var FetchBrain = class {
832
895
  });
833
896
  const runStats = {
834
897
  totalRequests: 0,
835
- aiKnown: 0,
898
+ recalled: 0,
836
899
  aiSkipped: 0,
837
- // AI knew + skipped scraping
900
+ // brain knew + skipped scraping
838
901
  learned: 0,
839
902
  scraped: 0,
840
903
  // Actually ran handler
@@ -846,6 +909,7 @@ var FetchBrain = class {
846
909
  return Object.assign(crawler, { fetchBrain: client });
847
910
  }
848
911
  const crawlerType = crawler.constructor?.name || "Unknown";
912
+ const warnedKeys = /* @__PURE__ */ new Set();
849
913
  const wrappedHandler = async (context) => {
850
914
  const { request } = context;
851
915
  const url = request.url;
@@ -857,37 +921,34 @@ var FetchBrain = class {
857
921
  label,
858
922
  url
859
923
  });
924
+ const rawRequest = buildRawRequest(request);
925
+ warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
860
926
  try {
861
- const aiResult = await client.query(url);
927
+ const aiResult = await client.recall(rawRequest);
862
928
  let usedAIData = false;
863
929
  const originalPushData = context.pushData;
864
- context.ai = {
930
+ context.brain = {
865
931
  known: aiResult.known,
866
932
  data: aiResult.data,
867
- confidence: aiResult.confidence,
868
- useAIData: async () => {
933
+ use: async () => {
869
934
  if (aiResult.known && aiResult.data && originalPushData) {
870
935
  usedAIData = true;
871
936
  await originalPushData.call(context, aiResult.data);
872
- logger.info(
873
- `Used AI data: ${url} (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
874
- );
937
+ logger.info(`Used brain data: ${url}`);
875
938
  }
876
939
  }
877
940
  };
878
941
  request.userData = {
879
942
  ...request.userData,
880
- fetchBrainKnown: aiResult.known,
943
+ fetchBrainRecalled: aiResult.known,
881
944
  fetchBrainData: aiResult.data
882
945
  };
883
946
  const handlerLabel = request.label;
884
947
  const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
885
948
  if (aiResult.known && aiResult.data && !runHandler) {
886
- runStats.aiKnown++;
949
+ runStats.recalled++;
887
950
  runStats.aiSkipped++;
888
- logger.info(
889
- `AI known: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
890
- );
951
+ logger.info(`Recalled: ${url} [${handlerLabel || "default"}]`);
891
952
  if (originalPushData) {
892
953
  await originalPushData.call(context, aiResult.data);
893
954
  }
@@ -895,27 +956,25 @@ var FetchBrain = class {
895
956
  }
896
957
  runStats.scraped++;
897
958
  if (aiResult.known) {
898
- runStats.aiKnown++;
959
+ runStats.recalled++;
899
960
  logger.info(
900
- `Running handler [${handlerLabel || "default"}] with AI data available: ${url}`
961
+ `Running handler [${handlerLabel || "default"}] with recalled data available: ${url}`
901
962
  );
902
963
  } else {
903
964
  logger.debug(`Learning: ${url}`);
904
965
  }
905
- requestContextMap.set(context, url);
906
966
  if (originalPushData && config.learning !== false) {
907
967
  context.pushData = async (data) => {
908
968
  const shouldLearn = !usedAIData && !aiResult.known;
909
969
  if (shouldLearn) {
910
970
  runStats.learned++;
911
- const requestUrl = requestContextMap.get(context) || url;
912
- await client.learn(requestUrl, data);
971
+ await client.learn(rawRequest, data);
913
972
  }
914
973
  return originalPushData.call(context, data);
915
974
  };
916
975
  }
917
976
  const requestContext = {
918
- url,
977
+ request: rawRequest,
919
978
  client,
920
979
  learning: config.learning !== false,
921
980
  aiKnown: aiResult.known
@@ -923,8 +982,7 @@ var FetchBrain = class {
923
982
  await asyncContext.run(requestContext, async () => {
924
983
  await originalHandler.call(crawler, context);
925
984
  });
926
- requestContextMap.delete(context);
927
- if (config.telemetry?.enabled) {
985
+ if (telemetryConfig.enabled) {
928
986
  try {
929
987
  const telemetry = await collectTelemetry(
930
988
  {
@@ -956,7 +1014,7 @@ var FetchBrain = class {
956
1014
  responseTime: Date.now() - startTime,
957
1015
  contentSize: context.response?.body?.length
958
1016
  },
959
- config.telemetry
1017
+ telemetryConfig
960
1018
  );
961
1019
  if (telemetry) {
962
1020
  telemetryBuffer.add(telemetry);
@@ -966,7 +1024,7 @@ var FetchBrain = class {
966
1024
  }
967
1025
  }
968
1026
  } catch (err) {
969
- if (config.telemetry?.enabled) {
1027
+ if (telemetryConfig.enabled) {
970
1028
  try {
971
1029
  const telemetry = await collectTelemetry(
972
1030
  {
@@ -984,7 +1042,7 @@ var FetchBrain = class {
984
1042
  endTime: Date.now(),
985
1043
  responseTime: Date.now() - startTime
986
1044
  },
987
- config.telemetry,
1045
+ telemetryConfig,
988
1046
  err instanceof Error ? err : new Error(String(err))
989
1047
  );
990
1048
  if (telemetry) {
@@ -1015,7 +1073,7 @@ var FetchBrain = class {
1015
1073
  } finally {
1016
1074
  logger.debug("Flushing pending learn requests on crawl complete");
1017
1075
  await client.flushLearnBatch();
1018
- if (config.telemetry?.enabled) {
1076
+ if (telemetryConfig.enabled) {
1019
1077
  logger.debug("Telemetry: flushing on crawl complete");
1020
1078
  await telemetryBuffer.stop();
1021
1079
  }
@@ -1024,7 +1082,7 @@ var FetchBrain = class {
1024
1082
  );
1025
1083
  const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
1026
1084
  logger.info(
1027
- `Finished! AI known: ${runStats.aiKnown}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
1085
+ `\u{1F9E0} Finished! recalled: ${runStats.recalled}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
1028
1086
  );
1029
1087
  }
1030
1088
  };
@@ -1040,7 +1098,7 @@ async function pushData(data, dataset, datasetName) {
1040
1098
  if (ctx && ctx.learning && !ctx.aiKnown) {
1041
1099
  const items = Array.isArray(data) ? data : [data];
1042
1100
  for (const item of items) {
1043
- await ctx.client.learn(ctx.url, item);
1101
+ await ctx.client.learn(ctx.request, item);
1044
1102
  }
1045
1103
  }
1046
1104
  if (datasetName && dataset.open) {
@@ -1051,15 +1109,6 @@ async function pushData(data, dataset, datasetName) {
1051
1109
  }
1052
1110
  }
1053
1111
 
1054
- // src/types.ts
1055
- var AIMemoryDepth = /* @__PURE__ */ ((AIMemoryDepth2) => {
1056
- AIMemoryDepth2[AIMemoryDepth2["REALTIME"] = 1] = "REALTIME";
1057
- AIMemoryDepth2[AIMemoryDepth2["HIGH"] = 2] = "HIGH";
1058
- AIMemoryDepth2[AIMemoryDepth2["STANDARD"] = 3] = "STANDARD";
1059
- AIMemoryDepth2[AIMemoryDepth2["DEEP"] = 4] = "DEEP";
1060
- return AIMemoryDepth2;
1061
- })(AIMemoryDepth || {});
1062
-
1063
- export { AIMemoryDepth, CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, TelemetryBuffer, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
1112
+ export { CircuitBreaker, FetchBrain, FetchBrainClient, RequestBatcher, TelemetryBuffer, collectTelemetry, createFetchBrain, createLogger, getCurrentContext, pushData };
1064
1113
  //# sourceMappingURL=index.mjs.map
1065
1114
  //# sourceMappingURL=index.mjs.map