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