@fetchbrain.com/sdk 0.1.6 → 0.2.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,99 @@ 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(() => {
154
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
155
+ }
156
+ }
157
+ /**
158
+ * Get current queue size
159
+ */
160
+ getQueueSize() {
161
+ return this.queue.length;
162
+ }
163
+ /**
164
+ * Clear the queue (for cleanup)
165
+ */
166
+ clear() {
167
+ if (this.flushTimeout) {
168
+ clearTimeout(this.flushTimeout);
169
+ this.flushTimeout = null;
170
+ }
171
+ for (const r of this.queue) {
172
+ r.resolve({ known: false, fallback: true });
173
+ }
174
+ this.queue = [];
175
+ }
176
+ };
177
+ var LearnBatcher = class {
178
+ constructor(executor, config = {}, logger) {
179
+ this.queue = [];
180
+ this.flushTimeout = null;
181
+ this.executor = executor;
182
+ this.config = { ...DEFAULT_CONFIG2, ...config };
183
+ this.logger = logger;
184
+ }
185
+ /**
186
+ * Add a learn entry to the batch queue
187
+ */
188
+ async learn(request, data) {
189
+ return new Promise((resolve, reject) => {
190
+ this.queue.push({ entry: { request, data }, resolve, reject });
191
+ if (this.queue.length >= this.config.maxSize) {
161
192
  this.flush();
162
- }, this.config.maxWait);
193
+ return;
194
+ }
195
+ if (!this.flushTimeout) {
196
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
197
+ }
198
+ });
199
+ }
200
+ /**
201
+ * Flush the current batch
202
+ */
203
+ async flush() {
204
+ if (this.flushTimeout) {
205
+ clearTimeout(this.flushTimeout);
206
+ this.flushTimeout = null;
207
+ }
208
+ if (this.queue.length === 0) {
209
+ return;
210
+ }
211
+ const batch = this.queue.splice(0, this.config.maxSize);
212
+ const entries = batch.map((r) => r.entry);
213
+ this.logger.debug(`Flushing learn batch of ${entries.length} entries`);
214
+ try {
215
+ const result = await this.executor(entries);
216
+ for (const r of batch) {
217
+ r.resolve(result);
218
+ }
219
+ } catch (error) {
220
+ for (const r of batch) {
221
+ r.reject(error);
222
+ }
223
+ }
224
+ if (this.queue.length > 0) {
225
+ this.flushTimeout = setTimeout(() => this.flush(), this.config.maxWait);
226
+ }
227
+ }
228
+ /**
229
+ * Force flush and wait for completion (for cleanup/shutdown)
230
+ */
231
+ async forceFlush() {
232
+ if (this.queue.length > 0) {
233
+ await this.flush();
163
234
  }
164
235
  }
165
236
  /**
@@ -176,45 +247,69 @@ var RequestBatcher = class {
176
247
  clearTimeout(this.flushTimeout);
177
248
  this.flushTimeout = null;
178
249
  }
179
- for (const request of this.queue) {
180
- request.resolve({ known: false, fallback: true });
250
+ for (const r of this.queue) {
251
+ r.resolve({ status: "rejected", learned: 0 });
181
252
  }
182
253
  this.queue = [];
183
254
  }
184
255
  };
185
256
 
186
257
  // src/logger.ts
187
- var LOG_PREFIX = "[FetchBrain]";
258
+ var COLORS = {
259
+ reset: "\x1B[0m",
260
+ cyan: "\x1B[36m",
261
+ green: "\x1B[32m",
262
+ yellow: "\x1B[33m",
263
+ red: "\x1B[31m",
264
+ gray: "\x1B[90m"
265
+ };
188
266
  var LOG_LEVELS = {
189
267
  debug: 0,
190
268
  info: 1,
191
269
  warn: 2,
192
270
  error: 3
193
271
  };
272
+ var LEVEL_COLORS = {
273
+ debug: COLORS.gray,
274
+ info: COLORS.green,
275
+ warn: COLORS.yellow,
276
+ error: COLORS.red
277
+ };
278
+ var LEVEL_LABELS = {
279
+ debug: "DEBUG",
280
+ info: "INFO ",
281
+ warn: "WARN ",
282
+ error: "ERROR"
283
+ };
194
284
  function createLogger(minLevel = "info", enabled = true) {
195
285
  const shouldLog = (level) => {
196
286
  if (!enabled) return false;
197
287
  return LOG_LEVELS[level] >= LOG_LEVELS[minLevel];
198
288
  };
289
+ const formatLog = (level, message) => {
290
+ const levelColor = LEVEL_COLORS[level];
291
+ const label = LEVEL_LABELS[level];
292
+ return `${levelColor}${label}${COLORS.reset} ${COLORS.cyan}FetchBrain:${COLORS.reset} ${message}`;
293
+ };
199
294
  return {
200
295
  debug: (message, ...args) => {
201
296
  if (shouldLog("debug")) {
202
- console.debug(`${LOG_PREFIX} ${message}`, ...args);
297
+ console.debug(formatLog("debug", message), ...args);
203
298
  }
204
299
  },
205
300
  info: (message, ...args) => {
206
301
  if (shouldLog("info")) {
207
- console.info(`${LOG_PREFIX} ${message}`, ...args);
302
+ console.info(formatLog("info", message), ...args);
208
303
  }
209
304
  },
210
305
  warn: (message, ...args) => {
211
306
  if (shouldLog("warn")) {
212
- console.warn(`${LOG_PREFIX} ${message}`, ...args);
307
+ console.warn(formatLog("warn", message), ...args);
213
308
  }
214
309
  },
215
310
  error: (message, ...args) => {
216
311
  if (shouldLog("error")) {
217
- console.error(`${LOG_PREFIX} ${message}`, ...args);
312
+ console.error(formatLog("error", message), ...args);
218
313
  }
219
314
  }
220
315
  };
@@ -223,6 +318,7 @@ function createLogger(minLevel = "info", enabled = true) {
223
318
  // src/client.ts
224
319
  var DEFAULT_BASE_URL = "https://api.fetchbrain.com";
225
320
  var DEFAULT_TIMEOUT = 500;
321
+ var DEFAULT_LEARN_TIMEOUT = 5e3;
226
322
  var currentContext = {};
227
323
  function setScrapeContext(ctx) {
228
324
  currentContext = ctx;
@@ -238,79 +334,74 @@ var FetchBrainClient = class {
238
334
  intelligence: config.intelligence || "high",
239
335
  learning: config.learning ?? true,
240
336
  alwaysRun: config.alwaysRun ?? false,
241
- strictBuildMatch: config.strictBuildMatch ?? false,
337
+ refreshOnRebuild: config.refreshOnRebuild ?? false,
242
338
  timeout: config.timeout || DEFAULT_TIMEOUT,
243
339
  debug: config.debug || false,
244
340
  extractForLearning: config.extractForLearning,
245
- telemetry: config.telemetry ?? { enabled: true }
341
+ learnUrlField: config.learnUrlField,
342
+ telemetry: config.telemetry ?? { enabled: true },
343
+ batch: config.batch,
344
+ circuitBreaker: config.circuitBreaker
246
345
  };
247
346
  this.logger = createLogger(this.config.debug ? "debug" : "info", true);
248
- this.circuitBreaker = new CircuitBreaker({}, this.logger);
347
+ this.circuitBreaker = new CircuitBreaker(
348
+ this.config.circuitBreaker,
349
+ this.logger
350
+ );
249
351
  this.batcher = new RequestBatcher(
250
- (urls) => this.executeBatchQuery(urls),
251
- {},
352
+ (items) => this.executeBatchQuery(items),
353
+ this.config.batch,
354
+ this.logger
355
+ );
356
+ this.learnBatcher = new LearnBatcher(
357
+ (entries) => this.executeBatchLearn(entries),
358
+ this.config.batch,
252
359
  this.logger
253
360
  );
254
361
  }
255
362
  /**
256
- * Query if FetchBrain "knows" a URL
363
+ * Query if FetchBrain "knows" a request
257
364
  */
258
- async query(url) {
365
+ async query(request) {
259
366
  if (this.circuitBreaker.isOpen()) {
260
- this.logger.debug(`Circuit open, skipping query for: ${url}`);
261
367
  return { known: false, fallback: true };
262
368
  }
263
369
  try {
264
- return await this.batcher.query(url);
370
+ return await this.batcher.query(request);
265
371
  } catch (error) {
266
- this.logger.debug(`Query failed for ${url}:`, error);
372
+ this.logger.debug("Query failed:", error);
267
373
  return { known: false, fallback: true };
268
374
  }
269
375
  }
270
376
  /**
271
- * Query multiple URLs at once (bypass batcher for bulk operations)
377
+ * Query multiple requests at once — returns ordered array matching input order
272
378
  */
273
- async queryBulk(urls) {
379
+ async queryBulk(requests) {
274
380
  if (this.circuitBreaker.isOpen()) {
275
- this.logger.debug(`Circuit open, skipping bulk query`);
276
- return new Map(
277
- urls.map((url) => [url, { known: false, fallback: true }])
278
- );
381
+ return requests.map(() => ({ known: false, fallback: true }));
279
382
  }
280
383
  try {
281
- return await this.executeBatchQuery(urls);
282
- } catch (error) {
283
- this.logger.debug(`Bulk query failed:`, error);
284
- return new Map(
285
- urls.map((url) => [url, { known: false, fallback: true }])
286
- );
384
+ const items = requests.map((request, i) => ({ ref: String(i), request }));
385
+ const results = await this.executeBatchQuery(items);
386
+ return items.map((i) => results.get(i.ref) ?? { known: false });
387
+ } catch {
388
+ return requests.map(() => ({ known: false, fallback: true }));
287
389
  }
288
390
  }
289
391
  /**
290
- * "Teach" FetchBrain new data
392
+ * "Teach" FetchBrain new data (batched for high-concurrency)
291
393
  */
292
- async learn(url, data) {
394
+ async learn(request, data) {
293
395
  if (!this.config.learning) {
294
396
  return { status: "rejected", learned: 0 };
295
397
  }
296
398
  if (this.circuitBreaker.isOpen()) {
297
- this.logger.debug(`Circuit open, skipping learn for: ${url}`);
298
399
  return { status: "rejected", learned: 0 };
299
400
  }
300
401
  try {
301
- const extractedData = this.config.extractForLearning ? this.config.extractForLearning(data) : data;
302
- const response = await this.makeRequest("/v1/learn", {
303
- method: "POST",
304
- body: JSON.stringify({
305
- entries: [{ url, data: extractedData }]
306
- })
307
- });
308
- this.circuitBreaker.recordSuccess();
309
- this.logger.debug(`Learned data for: ${url}`);
310
- return response;
402
+ return await this.learnBatcher.learn(request, data);
311
403
  } catch (error) {
312
- this.circuitBreaker.recordFailure();
313
- this.logger.warn(`Learn failed for ${url}:`, error);
404
+ this.logger.warn("Learn failed:", error);
314
405
  return { status: "rejected", learned: 0 };
315
406
  }
316
407
  }
@@ -336,13 +427,13 @@ var FetchBrainClient = class {
336
427
  /**
337
428
  * Execute a batch query against the API
338
429
  */
339
- async executeBatchQuery(urls) {
430
+ async executeBatchQuery(items) {
340
431
  const results = /* @__PURE__ */ new Map();
341
432
  const request = {
342
- urls,
433
+ items,
343
434
  intelligence: this.config.intelligence
344
435
  };
345
- if (this.config.strictBuildMatch && process.env.APIFY_ACTOR_BUILD_ID) {
436
+ if (this.config.refreshOnRebuild && process.env.APIFY_ACTOR_BUILD_ID) {
346
437
  request.build = process.env.APIFY_ACTOR_BUILD_ID;
347
438
  }
348
439
  try {
@@ -352,14 +443,10 @@ var FetchBrainClient = class {
352
443
  });
353
444
  this.circuitBreaker.recordSuccess();
354
445
  for (const item of response.known) {
355
- results.set(item.url, {
356
- known: true,
357
- data: item.data,
358
- confidence: item.confidence
359
- });
446
+ results.set(item.ref, { known: true, data: item.data, confidence: item.confidence });
360
447
  }
361
- for (const url of response.unknown) {
362
- results.set(url, { known: false });
448
+ for (const ref of response.unknown) {
449
+ results.set(ref, { known: false });
363
450
  }
364
451
  return results;
365
452
  } catch (error) {
@@ -367,13 +454,40 @@ var FetchBrainClient = class {
367
454
  throw error;
368
455
  }
369
456
  }
457
+ /**
458
+ * Execute a batch learn against the API
459
+ */
460
+ async executeBatchLearn(entries) {
461
+ const processed = entries.map((e) => ({
462
+ request: e.request,
463
+ data: this.config.extractForLearning ? this.config.extractForLearning(e.data) : e.data
464
+ }));
465
+ try {
466
+ const response = await this.makeRequest(
467
+ "/v1/learn",
468
+ {
469
+ method: "POST",
470
+ body: JSON.stringify({ entries: processed })
471
+ },
472
+ DEFAULT_LEARN_TIMEOUT
473
+ );
474
+ this.circuitBreaker.recordSuccess();
475
+ return response;
476
+ } catch (error) {
477
+ this.circuitBreaker.recordFailure();
478
+ throw error;
479
+ }
480
+ }
370
481
  /**
371
482
  * Make an HTTP request to the API
372
483
  */
373
- async makeRequest(path, options) {
484
+ async makeRequest(path, options, timeout) {
374
485
  const url = `${this.config.baseUrl}${path}`;
375
486
  const controller = new AbortController();
376
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
487
+ const timeoutId = setTimeout(
488
+ () => controller.abort(),
489
+ timeout ?? this.config.timeout
490
+ );
377
491
  const contextHeaders = {
378
492
  "X-FB-SDK": "js",
379
493
  "X-FB-Node": process.version || "unknown",
@@ -439,6 +553,13 @@ var FetchBrainClient = class {
439
553
  */
440
554
  clearBatch() {
441
555
  this.batcher.clear();
556
+ this.learnBatcher.clear();
557
+ }
558
+ /**
559
+ * Flush pending learn requests (call before shutdown)
560
+ */
561
+ async flushLearnBatch() {
562
+ await this.learnBatcher.forceFlush();
442
563
  }
443
564
  /**
444
565
  * Send telemetry data to the API
@@ -614,6 +735,36 @@ var TelemetryBuffer = class {
614
735
  };
615
736
 
616
737
  // src/enhance.ts
738
+ var STRIP_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "set-cookie"]);
739
+ var SDK_USERDATA_KEYS = /* @__PURE__ */ new Set(["fetchBrainKnown", "fetchBrainData", "__fetchBrainResult"]);
740
+ function buildRawRequest(request) {
741
+ const r = request;
742
+ let headers;
743
+ if (r.headers) {
744
+ headers = {};
745
+ for (const [k, v] of Object.entries(r.headers)) {
746
+ if (!STRIP_HEADERS.has(k.toLowerCase()) && typeof v === "string") headers[k] = v;
747
+ }
748
+ if (Object.keys(headers).length === 0) headers = void 0;
749
+ }
750
+ let userData;
751
+ if (r.userData) {
752
+ userData = {};
753
+ for (const [k, v] of Object.entries(r.userData)) if (!SDK_USERDATA_KEYS.has(k)) userData[k] = v;
754
+ if (Object.keys(userData).length === 0) userData = void 0;
755
+ }
756
+ let body;
757
+ if (typeof r.payload === "string") body = r.payload;
758
+ return { url: r.url, method: r.method, uniqueKey: r.uniqueKey, body, headers, userData, label: r.label };
759
+ }
760
+ function warnDefaultUniqueKey(request, logger, warned) {
761
+ const method = (request.method ?? "GET").toUpperCase();
762
+ const isDefault = !request.uniqueKey || request.uniqueKey === request.url;
763
+ if (method !== "GET" && isDefault && !warned.has(request.url)) {
764
+ 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.`);
766
+ }
767
+ }
617
768
  var asyncContext = new AsyncLocalStorage();
618
769
  function getCurrentContext() {
619
770
  return asyncContext.getStore();
@@ -629,7 +780,6 @@ function shouldRunHandler(alwaysRun, label) {
629
780
  const requestLabel = label || "default";
630
781
  return labels.includes(requestLabel);
631
782
  }
632
- var requestContextMap = /* @__PURE__ */ new WeakMap();
633
783
  var FetchBrain = class {
634
784
  constructor(config) {
635
785
  this.client = new FetchBrainClient(config);
@@ -639,7 +789,7 @@ var FetchBrain = class {
639
789
  * Query if FetchBrain "knows" a URL
640
790
  */
641
791
  async query(options) {
642
- const result = await this.client.query(options.url);
792
+ const result = await this.client.query({ url: options.url });
643
793
  return {
644
794
  known: result.known,
645
795
  data: result.data,
@@ -650,7 +800,7 @@ var FetchBrain = class {
650
800
  * "Teach" FetchBrain new data
651
801
  */
652
802
  async learn(options) {
653
- return this.client.learn(options.url, options.data);
803
+ return this.client.learn({ url: options.url }, options.data);
654
804
  }
655
805
  /**
656
806
  * Get usage statistics
@@ -682,24 +832,38 @@ var FetchBrain = class {
682
832
  }
683
833
  }
684
834
  });
835
+ const runStats = {
836
+ totalRequests: 0,
837
+ aiKnown: 0,
838
+ aiSkipped: 0,
839
+ // AI knew + skipped scraping
840
+ learned: 0,
841
+ scraped: 0,
842
+ // Actually ran handler
843
+ startTime: 0
844
+ };
685
845
  const originalHandler = crawler.requestHandler || crawler.userDefinedRequestHandler;
686
846
  if (!originalHandler) {
687
847
  logger.warn("No request handler found on crawler, returning unmodified");
688
848
  return Object.assign(crawler, { fetchBrain: client });
689
849
  }
690
850
  const crawlerType = crawler.constructor?.name || "Unknown";
851
+ const warnedKeys = /* @__PURE__ */ new Set();
691
852
  const wrappedHandler = async (context) => {
692
853
  const { request } = context;
693
854
  const url = request.url;
694
855
  const label = request.label;
695
856
  const startTime = Date.now();
857
+ runStats.totalRequests++;
696
858
  setScrapeContext({
697
859
  crawler: crawlerType,
698
860
  label,
699
861
  url
700
862
  });
863
+ const rawRequest = buildRawRequest(request);
864
+ warnDefaultUniqueKey(rawRequest, logger, warnedKeys);
701
865
  try {
702
- const aiResult = await client.query(url);
866
+ const aiResult = await client.query(rawRequest);
703
867
  let usedAIData = false;
704
868
  const originalPushData = context.pushData;
705
869
  context.ai = {
@@ -724,34 +888,37 @@ var FetchBrain = class {
724
888
  const handlerLabel = request.label;
725
889
  const runHandler = shouldRunHandler(config.alwaysRun, handlerLabel);
726
890
  if (aiResult.known && aiResult.data && !runHandler) {
891
+ runStats.aiKnown++;
892
+ runStats.aiSkipped++;
727
893
  logger.info(
728
- `Optimized: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
894
+ `AI known: ${url} [${handlerLabel || "default"}] (confidence: ${aiResult.confidence?.toFixed(2) || "N/A"})`
729
895
  );
730
896
  if (originalPushData) {
731
897
  await originalPushData.call(context, aiResult.data);
732
898
  }
733
899
  return;
734
900
  }
901
+ runStats.scraped++;
735
902
  if (aiResult.known) {
903
+ runStats.aiKnown++;
736
904
  logger.info(
737
905
  `Running handler [${handlerLabel || "default"}] with AI data available: ${url}`
738
906
  );
739
907
  } else {
740
908
  logger.debug(`Learning: ${url}`);
741
909
  }
742
- requestContextMap.set(context, url);
743
910
  if (originalPushData && config.learning !== false) {
744
911
  context.pushData = async (data) => {
745
912
  const shouldLearn = !usedAIData && !aiResult.known;
746
913
  if (shouldLearn) {
747
- const currentUrl = requestContextMap.get(context) || url;
748
- await client.learn(currentUrl, data);
914
+ runStats.learned++;
915
+ await client.learn(rawRequest, data);
749
916
  }
750
917
  return originalPushData.call(context, data);
751
918
  };
752
919
  }
753
920
  const requestContext = {
754
- url,
921
+ request: rawRequest,
755
922
  client,
756
923
  learning: config.learning !== false,
757
924
  aiKnown: aiResult.known
@@ -759,7 +926,6 @@ var FetchBrain = class {
759
926
  await asyncContext.run(requestContext, async () => {
760
927
  await originalHandler.call(crawler, context);
761
928
  });
762
- requestContextMap.delete(context);
763
929
  if (config.telemetry?.enabled) {
764
930
  try {
765
931
  const telemetry = await collectTelemetry(
@@ -844,14 +1010,24 @@ var FetchBrain = class {
844
1010
  if (typeof crawlerAny.run === "function") {
845
1011
  const originalRun = crawlerAny.run.bind(crawlerAny);
846
1012
  crawlerAny.run = async (...args) => {
1013
+ runStats.startTime = Date.now();
847
1014
  try {
848
1015
  const result = await originalRun(...args);
849
1016
  return result;
850
1017
  } finally {
1018
+ logger.debug("Flushing pending learn requests on crawl complete");
1019
+ await client.flushLearnBatch();
851
1020
  if (config.telemetry?.enabled) {
852
1021
  logger.debug("Telemetry: flushing on crawl complete");
853
1022
  await telemetryBuffer.stop();
854
1023
  }
1024
+ const duration = ((Date.now() - runStats.startTime) / 1e3).toFixed(
1025
+ 1
1026
+ );
1027
+ const savingsPercent = runStats.totalRequests > 0 ? (runStats.aiSkipped / runStats.totalRequests * 100).toFixed(1) : "0";
1028
+ logger.info(
1029
+ `Finished! AI known: ${runStats.aiKnown}/${runStats.totalRequests} (${savingsPercent}%), learned: ${runStats.learned}, scraped: ${runStats.scraped}, duration: ${duration}s`
1030
+ );
855
1031
  }
856
1032
  };
857
1033
  }
@@ -866,7 +1042,7 @@ async function pushData(data, dataset, datasetName) {
866
1042
  if (ctx && ctx.learning && !ctx.aiKnown) {
867
1043
  const items = Array.isArray(data) ? data : [data];
868
1044
  for (const item of items) {
869
- await ctx.client.learn(ctx.url, item);
1045
+ await ctx.client.learn(ctx.request, item);
870
1046
  }
871
1047
  }
872
1048
  if (datasetName && dataset.open) {