exa-js 2.24.0 → 2.26.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
@@ -4,7 +4,7 @@ import fetch2, { Headers } from "cross-fetch";
4
4
  // package.json
5
5
  var package_default = {
6
6
  name: "exa-js",
7
- version: "2.24.0",
7
+ version: "2.26.0",
8
8
  description: "Exa SDK for Node.js and the browser",
9
9
  publishConfig: {
10
10
  access: "public"
@@ -124,6 +124,99 @@ var ExaError = class extends Error {
124
124
  }
125
125
  }
126
126
  };
127
+ var ExaAbortError = class extends Error {
128
+ /**
129
+ * Create a new ExaAbortError
130
+ * @param cause The underlying fetch rejection or abort reason
131
+ */
132
+ constructor(cause) {
133
+ super("Request was aborted.");
134
+ this.name = "AbortError";
135
+ this.cause = cause;
136
+ }
137
+ };
138
+ var ExaTimeoutError = class extends ExaError {
139
+ /**
140
+ * Create a new ExaTimeoutError
141
+ * @param timeout The timeout that elapsed, in milliseconds
142
+ * @param path Path of the request that timed out
143
+ * @param cause The underlying fetch rejection
144
+ */
145
+ constructor(timeout, path, cause) {
146
+ super(
147
+ `Request timed out after ${timeout}ms.`,
148
+ 408 /* RequestTimeout */,
149
+ void 0,
150
+ path
151
+ );
152
+ this.name = "TimeoutError";
153
+ this.timeout = timeout;
154
+ this.cause = cause;
155
+ }
156
+ };
157
+
158
+ // src/error-response.ts
159
+ var NON_JSON_BODY_SNIPPET_LENGTH = 500;
160
+ async function readResponseBody(response) {
161
+ const text = await response.text();
162
+ if (!text) {
163
+ return { json: void 0, text };
164
+ }
165
+ try {
166
+ return { json: JSON.parse(text), text };
167
+ } catch {
168
+ return { json: void 0, text };
169
+ }
170
+ }
171
+ function truncateResponseBody(text) {
172
+ const collapsed = text.replace(/\s+/g, " ").trim();
173
+ return collapsed.length > NON_JSON_BODY_SNIPPET_LENGTH ? `${collapsed.slice(0, NON_JSON_BODY_SNIPPET_LENGTH)}\u2026` : collapsed;
174
+ }
175
+ async function exaErrorFromResponse(response, path) {
176
+ const { json, text } = await readResponseBody(response);
177
+ if (!json || typeof json !== "object") {
178
+ const snippet = truncateResponseBody(text);
179
+ const message2 = snippet ? `Request failed with status ${response.status}. Response body was not valid JSON: ${snippet}` : `Request failed with status ${response.status}.`;
180
+ return new ExaError(
181
+ message2,
182
+ response.status,
183
+ (/* @__PURE__ */ new Date()).toISOString(),
184
+ path
185
+ );
186
+ }
187
+ const errorData = json;
188
+ if (!errorData.statusCode) {
189
+ errorData.statusCode = response.status;
190
+ }
191
+ if (!errorData.timestamp) {
192
+ errorData.timestamp = (/* @__PURE__ */ new Date()).toISOString();
193
+ }
194
+ if (!errorData.path) {
195
+ errorData.path = path;
196
+ }
197
+ const envelope = typeof errorData.error === "object" && errorData.error !== null ? errorData.error : void 0;
198
+ let message;
199
+ if (envelope) {
200
+ message = envelope.message || errorData.message || "Unknown error";
201
+ } else {
202
+ message = errorData.error || "Unknown error";
203
+ if (errorData.message) {
204
+ message += (message.length > 0 ? ". " : "") + errorData.message;
205
+ }
206
+ }
207
+ return new ExaError(
208
+ message,
209
+ response.status,
210
+ errorData.timestamp,
211
+ errorData.path,
212
+ envelope ? {
213
+ type: envelope.type,
214
+ code: envelope.code,
215
+ detail: envelope.detail,
216
+ requestId: errorData.requestId ?? envelope.requestId
217
+ } : errorData.requestId ? { requestId: errorData.requestId } : void 0
218
+ );
219
+ }
127
220
 
128
221
  // src/zod-utils.ts
129
222
  import { ZodType } from "zod";
@@ -137,12 +230,418 @@ function zodToJsonSchema(schema) {
137
230
  });
138
231
  }
139
232
 
233
+ // src/request-options.ts
234
+ var MAX_TIMEOUT_MS = 2147483647;
235
+ function validateTimeout(timeout) {
236
+ if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT_MS) {
237
+ throw new RangeError(
238
+ `Request timeout must be an integer from 1 to ${MAX_TIMEOUT_MS} milliseconds (received ${timeout})`
239
+ );
240
+ }
241
+ return timeout;
242
+ }
243
+ var REQUEST_OPTION_KEYS = ["signal", "timeout"];
244
+ function omitRequestOptions(options) {
245
+ if (options == null) {
246
+ return void 0;
247
+ }
248
+ const rest = { ...options };
249
+ for (const key of REQUEST_OPTION_KEYS) {
250
+ delete rest[key];
251
+ }
252
+ return rest;
253
+ }
254
+ function pickRequestOptions(options) {
255
+ if (options == null) {
256
+ return void 0;
257
+ }
258
+ const picked = {};
259
+ if (options.signal !== void 0) {
260
+ picked.signal = options.signal;
261
+ }
262
+ if (options.timeout !== void 0) {
263
+ picked.timeout = options.timeout;
264
+ }
265
+ return picked.signal !== void 0 || picked.timeout !== void 0 ? picked : void 0;
266
+ }
267
+ function mergeRequestOptions(...sources) {
268
+ const merged = {};
269
+ for (const source of sources) {
270
+ if (source?.signal !== void 0) {
271
+ merged.signal = source.signal;
272
+ }
273
+ if (source?.timeout != null) {
274
+ merged.timeout = source.timeout;
275
+ }
276
+ if (source?.body !== void 0) {
277
+ merged.body = { ...merged.body, ...source.body };
278
+ }
279
+ if (source?.headers !== void 0) {
280
+ merged.headers = { ...merged.headers, ...source.headers };
281
+ }
282
+ if (source?.query !== void 0) {
283
+ merged.query = { ...merged.query, ...source.query };
284
+ }
285
+ }
286
+ return Object.keys(merged).length > 0 ? merged : void 0;
287
+ }
288
+ var BODY_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
289
+ function mergeRequestBody(method, body, extraBody) {
290
+ if (!extraBody || !BODY_METHODS.has(method.toUpperCase())) {
291
+ return body;
292
+ }
293
+ const { stream: _stream, ...extra } = extraBody;
294
+ if (body === void 0 || body === null) {
295
+ return Object.keys(extra).length > 0 ? extra : body;
296
+ }
297
+ if (typeof body !== "object" || Array.isArray(body)) {
298
+ throw new TypeError(
299
+ "Cannot merge the `body` request option into a request body that is not an object"
300
+ );
301
+ }
302
+ return { ...body, ...extra };
303
+ }
304
+ function mergeRequestQuery(query, extraQuery) {
305
+ const extra = Object.fromEntries(
306
+ Object.entries(extraQuery ?? {}).filter(
307
+ ([name, value]) => name !== "stream" && value !== void 0 && value !== null
308
+ )
309
+ );
310
+ return Object.keys(extra).length > 0 ? { ...query, ...extra } : query;
311
+ }
312
+ function acceptsEventStream(headers) {
313
+ return Object.entries(headers).some(
314
+ ([name, value]) => name.toLowerCase() === "accept" && value.toLowerCase().includes("text/event-stream")
315
+ );
316
+ }
317
+ function mergeRequestHeaders(headers, extraHeaders) {
318
+ if (!extraHeaders) {
319
+ return headers;
320
+ }
321
+ const keepsAccept = acceptsEventStream(headers);
322
+ const merged = { ...headers };
323
+ for (const [name, value] of Object.entries(extraHeaders)) {
324
+ const lowerCaseName = name.toLowerCase();
325
+ if (value === void 0 || keepsAccept && lowerCaseName === "accept") {
326
+ continue;
327
+ }
328
+ for (const existing of Object.keys(merged)) {
329
+ if (existing.toLowerCase() === lowerCaseName) {
330
+ delete merged[existing];
331
+ }
332
+ }
333
+ if (value !== null) {
334
+ merged[name] = value;
335
+ }
336
+ }
337
+ return merged;
338
+ }
339
+ var CLIENT_DEFAULTS = /* @__PURE__ */ new WeakMap();
340
+ function setClientDefaults(client, defaults) {
341
+ if (defaults === void 0) {
342
+ CLIENT_DEFAULTS.delete(client);
343
+ } else {
344
+ CLIENT_DEFAULTS.set(client, defaults);
345
+ }
346
+ }
347
+ function withClientDefaults(client, requestOptions) {
348
+ return mergeRequestOptions(CLIENT_DEFAULTS.get(client), requestOptions);
349
+ }
350
+ function streamRequestOptions(client, requestOptions) {
351
+ return asStreamRequestOptions(withClientDefaults(client, requestOptions));
352
+ }
353
+ var STREAM_REQUEST_OPTIONS = /* @__PURE__ */ new WeakSet();
354
+ function asStreamRequestOptions(options) {
355
+ const copy = mergeRequestOptions(options);
356
+ if (copy) {
357
+ STREAM_REQUEST_OPTIONS.add(copy);
358
+ }
359
+ return copy;
360
+ }
361
+ function isStreamRequestOptions(options) {
362
+ return options != null && STREAM_REQUEST_OPTIONS.has(options);
363
+ }
364
+ var NOOP_DISPOSE = () => {
365
+ };
366
+ function createTimeoutSignal(timeoutMs) {
367
+ const controller = new AbortController();
368
+ const timer = setTimeout(() => {
369
+ controller.abort(
370
+ typeof DOMException !== "undefined" ? new DOMException(
371
+ `The operation was aborted due to timeout after ${timeoutMs}ms`,
372
+ "TimeoutError"
373
+ ) : void 0
374
+ );
375
+ }, timeoutMs);
376
+ if (typeof timer.unref === "function") {
377
+ timer.unref();
378
+ }
379
+ let disposed = false;
380
+ const dispose = () => {
381
+ if (disposed) return;
382
+ disposed = true;
383
+ clearTimeout(timer);
384
+ };
385
+ controller.signal.addEventListener("abort", dispose, { once: true });
386
+ return { signal: controller.signal, dispose };
387
+ }
388
+ function anySignal(signals) {
389
+ if (signals.length === 1) {
390
+ return { signal: signals[0], dispose: NOOP_DISPOSE };
391
+ }
392
+ const controller = new AbortController();
393
+ const abortHandlers = [];
394
+ let disposed = false;
395
+ const dispose = () => {
396
+ if (disposed) return;
397
+ disposed = true;
398
+ for (const { signal, handler } of abortHandlers) {
399
+ signal.removeEventListener("abort", handler);
400
+ }
401
+ abortHandlers.length = 0;
402
+ };
403
+ for (const signal of signals) {
404
+ if (signal.aborted) {
405
+ controller.abort(signal.reason);
406
+ dispose();
407
+ return { signal: controller.signal, dispose: NOOP_DISPOSE };
408
+ }
409
+ const handler = () => {
410
+ controller.abort(signal.reason);
411
+ };
412
+ signal.addEventListener("abort", handler);
413
+ abortHandlers.push({ signal, handler });
414
+ }
415
+ controller.signal.addEventListener("abort", dispose, { once: true });
416
+ return { signal: controller.signal, dispose };
417
+ }
418
+ function resolveRequestSignal(options) {
419
+ if (options == null) {
420
+ return {
421
+ signal: void 0,
422
+ dispose: () => {
423
+ },
424
+ needsDispose: false,
425
+ stopTimeout: NOOP_DISPOSE,
426
+ toRequestError: (error) => error
427
+ };
428
+ }
429
+ const { signal, timeout } = options;
430
+ const signals = [];
431
+ const disposers = [];
432
+ let timeoutSignal;
433
+ if (signal) {
434
+ signals.push(signal);
435
+ }
436
+ if (timeout != null) {
437
+ timeoutSignal = createTimeoutSignal(validateTimeout(timeout));
438
+ signals.push(timeoutSignal.signal);
439
+ if (timeoutSignal.dispose !== NOOP_DISPOSE) {
440
+ disposers.push(timeoutSignal.dispose);
441
+ }
442
+ }
443
+ if (signals.length === 0) {
444
+ return {
445
+ signal: void 0,
446
+ dispose: () => {
447
+ },
448
+ needsDispose: false,
449
+ stopTimeout: NOOP_DISPOSE,
450
+ toRequestError: (error) => error
451
+ };
452
+ }
453
+ const combined = anySignal(signals);
454
+ if (combined.dispose !== NOOP_DISPOSE) {
455
+ disposers.push(combined.dispose);
456
+ }
457
+ let firstAbort;
458
+ if (signal && timeoutSignal) {
459
+ combined.signal.addEventListener(
460
+ "abort",
461
+ () => {
462
+ firstAbort = signal.aborted ? "signal" : "timeout";
463
+ },
464
+ { once: true }
465
+ );
466
+ }
467
+ const toRequestError = (error, path) => {
468
+ if (error instanceof ExaError || error instanceof ExaAbortError) {
469
+ return error;
470
+ }
471
+ const abortedBy = firstAbort ?? (signal?.aborted ? "signal" : timeoutSignal?.signal.aborted ? "timeout" : void 0);
472
+ if (abortedBy === "timeout") {
473
+ return new ExaTimeoutError(timeout, path, error);
474
+ }
475
+ if (abortedBy === "signal") {
476
+ return new ExaAbortError(error);
477
+ }
478
+ return error;
479
+ };
480
+ const stopTimeout = timeoutSignal?.dispose ?? NOOP_DISPOSE;
481
+ if (disposers.length === 0) {
482
+ return {
483
+ signal: combined.signal,
484
+ dispose: () => {
485
+ },
486
+ needsDispose: false,
487
+ stopTimeout,
488
+ toRequestError
489
+ };
490
+ }
491
+ let disposed = false;
492
+ return {
493
+ signal: combined.signal,
494
+ dispose: () => {
495
+ if (disposed) return;
496
+ disposed = true;
497
+ for (const dispose of disposers) {
498
+ dispose();
499
+ }
500
+ },
501
+ needsDispose: true,
502
+ stopTimeout,
503
+ toRequestError
504
+ };
505
+ }
506
+ function withDisposeOnBodySettled(response, dispose, mapError = (error) => error) {
507
+ const body = response.body;
508
+ if (!body) {
509
+ dispose();
510
+ return response;
511
+ }
512
+ if (typeof body.getReader !== "function") {
513
+ const nodeBody = body;
514
+ const settle2 = () => {
515
+ nodeBody.removeListener("end", settle2);
516
+ nodeBody.removeListener("close", settle2);
517
+ nodeBody.removeListener("error", settle2);
518
+ dispose();
519
+ };
520
+ nodeBody.once("end", settle2);
521
+ nodeBody.once("close", settle2);
522
+ nodeBody.once("error", settle2);
523
+ return response;
524
+ }
525
+ let settled = false;
526
+ const settle = () => {
527
+ if (settled) return;
528
+ settled = true;
529
+ dispose();
530
+ };
531
+ const reader = body.getReader();
532
+ const stream = new ReadableStream({
533
+ async pull(controller) {
534
+ try {
535
+ const { done, value } = await reader.read();
536
+ if (done) {
537
+ settle();
538
+ controller.close();
539
+ return;
540
+ }
541
+ controller.enqueue(value);
542
+ } catch (error) {
543
+ settle();
544
+ controller.error(mapError(error));
545
+ }
546
+ },
547
+ cancel(reason) {
548
+ settle();
549
+ return reader.cancel(reason);
550
+ }
551
+ });
552
+ const wrapped = new Response(stream, {
553
+ status: response.status,
554
+ statusText: response.statusText,
555
+ headers: response.headers
556
+ });
557
+ const preserveMetadata = (target) => {
558
+ Object.defineProperties(target, {
559
+ url: { value: response.url },
560
+ redirected: { value: response.redirected },
561
+ type: { value: response.type }
562
+ });
563
+ const clone = target.clone.bind(target);
564
+ Object.defineProperty(target, "clone", {
565
+ value: () => preserveMetadata(clone())
566
+ });
567
+ return target;
568
+ };
569
+ preserveMetadata(wrapped);
570
+ return wrapped;
571
+ }
572
+ function sleep(ms, signal) {
573
+ if (!signal) {
574
+ return new Promise((resolve) => setTimeout(resolve, ms));
575
+ }
576
+ return new Promise((resolve, reject) => {
577
+ if (signal.aborted) {
578
+ reject(new ExaAbortError(signal.reason));
579
+ return;
580
+ }
581
+ let timer;
582
+ const onAbort = () => {
583
+ clearTimeout(timer);
584
+ reject(new ExaAbortError(signal.reason));
585
+ };
586
+ signal.addEventListener("abort", onAbort, { once: true });
587
+ timer = setTimeout(() => {
588
+ signal.removeEventListener("abort", onAbort);
589
+ resolve();
590
+ }, ms);
591
+ });
592
+ }
593
+ var RequestScopedClient = class {
594
+ /**
595
+ * Returns a view of this client that sends `requestOptions` with every
596
+ * request, on top of any the client already carries. Returns the client
597
+ * itself when there is nothing to add.
598
+ */
599
+ withRequestOptions(requestOptions) {
600
+ if (mergeRequestOptions(requestOptions) === void 0) {
601
+ return this;
602
+ }
603
+ const view = Object.create(this);
604
+ view.requestOptions = mergeRequestOptions(
605
+ this.requestOptions,
606
+ requestOptions
607
+ );
608
+ return view;
609
+ }
610
+ /**
611
+ * Returns the view a listing fetches its pages with after the first: this
612
+ * one without a `cursor` in the extra `query`. A listing advances the
613
+ * cursor itself; an extra `cursor` selects where it starts and, sent again,
614
+ * would replace every later cursor and fetch that page forever.
615
+ */
616
+ forNextPage() {
617
+ const query = this.requestOptions?.query;
618
+ if (!query || !("cursor" in query)) {
619
+ return this;
620
+ }
621
+ const { cursor: _cursor, ...remaining } = query;
622
+ const view = Object.create(this);
623
+ view.requestOptions = { ...this.requestOptions, query: remaining };
624
+ return view;
625
+ }
626
+ };
627
+
140
628
  // src/agent/base.ts
141
- var AgentBaseClient = class {
629
+ var AgentBaseClient = class extends RequestScopedClient {
142
630
  constructor(client) {
631
+ super();
143
632
  this.client = client;
144
633
  }
145
634
  async request(endpoint, method = "POST", data, params, headers) {
635
+ if (this.requestOptions) {
636
+ return this.client.request(
637
+ `/agent/runs${endpoint}`,
638
+ method,
639
+ data,
640
+ params,
641
+ headers,
642
+ this.requestOptions
643
+ );
644
+ }
146
645
  return this.client.request(
147
646
  `/agent/runs${endpoint}`,
148
647
  method,
@@ -151,7 +650,22 @@ var AgentBaseClient = class {
151
650
  headers
152
651
  );
153
652
  }
653
+ /**
654
+ * Opens a streamed response. `timeout` covers the wait for the stream to
655
+ * start; the caller's `signal` can cancel it at any point.
656
+ */
154
657
  async rawRequest(endpoint, method = "POST", data, params, headers) {
658
+ const transport = streamRequestOptions(this.client, this.requestOptions);
659
+ if (transport) {
660
+ return this.client.rawRequest(
661
+ `/agent/runs${endpoint}`,
662
+ method,
663
+ data,
664
+ params,
665
+ headers,
666
+ transport
667
+ );
668
+ }
155
669
  return this.client.rawRequest(
156
670
  `/agent/runs${endpoint}`,
157
671
  method,
@@ -180,8 +694,9 @@ function headersForBetas(betas) {
180
694
  var AGENT_MONITORS_BETA_HEADER = "agent-monitors-2026-08-04";
181
695
 
182
696
  // src/agent/monitors/base.ts
183
- var AgentMonitorsBaseClient = class {
697
+ var AgentMonitorsBaseClient = class extends RequestScopedClient {
184
698
  constructor(client) {
699
+ super();
185
700
  this.client = client;
186
701
  }
187
702
  async request(endpoint, betas, method = "POST", data, params, headers) {
@@ -191,15 +706,26 @@ var AgentMonitorsBaseClient = class {
191
706
  400 /* BadRequest */
192
707
  );
193
708
  }
709
+ const requestHeaders = {
710
+ ...headersForBetas(betas),
711
+ ...headers
712
+ };
713
+ if (this.requestOptions) {
714
+ return this.client.request(
715
+ `/agent/monitors${endpoint}`,
716
+ method,
717
+ data,
718
+ params,
719
+ requestHeaders,
720
+ this.requestOptions
721
+ );
722
+ }
194
723
  return this.client.request(
195
724
  `/agent/monitors${endpoint}`,
196
725
  method,
197
726
  data,
198
727
  params,
199
- {
200
- ...headersForBetas(betas),
201
- ...headers
202
- }
728
+ requestHeaders
203
729
  );
204
730
  }
205
731
  buildPaginationParams(pagination) {
@@ -229,9 +755,10 @@ var AgentMonitorEntitiesClient = class extends AgentMonitorsBaseClient {
229
755
  * and backfilled shortly after the request completes, then update on the
230
756
  * monitor's regular refresh cadence.
231
757
  */
232
- async add(monitorId, params) {
758
+ async add(monitorId, params, requestOptions) {
759
+ const scoped = this.withRequestOptions(requestOptions);
233
760
  const { betas, ...payload } = params;
234
- return this.request(
761
+ return scoped.request(
235
762
  `/${monitorId}/entities`,
236
763
  betas,
237
764
  "POST",
@@ -242,10 +769,11 @@ var AgentMonitorEntitiesClient = class extends AgentMonitorsBaseClient {
242
769
  * Page an Agent Monitor's current entities and contents, optionally
243
770
  * filtered by update time.
244
771
  */
245
- async list(monitorId, options) {
772
+ async list(monitorId, options, requestOptions) {
773
+ const scoped = this.withRequestOptions(requestOptions);
246
774
  const { betas, ...pagination } = options;
247
775
  const params = this.buildPaginationParams(pagination);
248
- return this.request(
776
+ return scoped.request(
249
777
  `/${monitorId}/entities`,
250
778
  betas,
251
779
  "GET",
@@ -257,13 +785,14 @@ var AgentMonitorEntitiesClient = class extends AgentMonitorsBaseClient {
257
785
  * Iterate through all of a monitor's entities, handling pagination
258
786
  * automatically.
259
787
  */
260
- async *listAll(monitorId, options) {
788
+ async *listAll(monitorId, options, requestOptions) {
789
+ let scoped = this.withRequestOptions(requestOptions);
261
790
  let cursor = options.cursor;
262
791
  const { betas, ...pagination } = options;
263
792
  const pageOptions = { ...pagination };
264
793
  while (true) {
265
794
  pageOptions.cursor = cursor;
266
- const response = await this.list(monitorId, { ...pageOptions, betas });
795
+ const response = await scoped.list(monitorId, { ...pageOptions, betas });
267
796
  for (const entityView of response.data) {
268
797
  yield entityView;
269
798
  }
@@ -271,14 +800,16 @@ var AgentMonitorEntitiesClient = class extends AgentMonitorsBaseClient {
271
800
  break;
272
801
  }
273
802
  cursor = response.nextCursor;
803
+ scoped = scoped.forNextPage();
274
804
  }
275
805
  }
276
806
  /**
277
807
  * Collect all of a monitor's entities into an array.
278
808
  */
279
- async getAll(monitorId, options) {
809
+ async getAll(monitorId, options, requestOptions) {
810
+ const scoped = this.withRequestOptions(requestOptions);
280
811
  const entities = [];
281
- for await (const entityView of this.listAll(monitorId, options)) {
812
+ for await (const entityView of scoped.listAll(monitorId, options)) {
282
813
  entities.push(entityView);
283
814
  }
284
815
  return entities;
@@ -288,10 +819,11 @@ var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
288
819
  /**
289
820
  * Page an Agent Monitor's content change feed since a cursor or timestamp.
290
821
  */
291
- async list(monitorId, options) {
822
+ async list(monitorId, options, requestOptions) {
823
+ const scoped = this.withRequestOptions(requestOptions);
292
824
  const { betas, ...pagination } = options;
293
825
  const params = this.buildPaginationParams(pagination);
294
- return this.request(
826
+ return scoped.request(
295
827
  `/${monitorId}/changes`,
296
828
  betas,
297
829
  "GET",
@@ -303,13 +835,14 @@ var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
303
835
  * Iterate through a monitor's change feed, handling pagination
304
836
  * automatically.
305
837
  */
306
- async *listAll(monitorId, options) {
838
+ async *listAll(monitorId, options, requestOptions) {
839
+ let scoped = this.withRequestOptions(requestOptions);
307
840
  let cursor = options.cursor;
308
841
  const { betas, ...pagination } = options;
309
842
  const pageOptions = { ...pagination };
310
843
  while (true) {
311
844
  pageOptions.cursor = cursor;
312
- const response = await this.list(monitorId, { ...pageOptions, betas });
845
+ const response = await scoped.list(monitorId, { ...pageOptions, betas });
313
846
  for (const change of response.data) {
314
847
  yield change;
315
848
  }
@@ -317,14 +850,16 @@ var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
317
850
  break;
318
851
  }
319
852
  cursor = response.nextCursor;
853
+ scoped = scoped.forNextPage();
320
854
  }
321
855
  }
322
856
  /**
323
857
  * Collect a monitor's change feed into an array.
324
858
  */
325
- async getAll(monitorId, options) {
859
+ async getAll(monitorId, options, requestOptions) {
860
+ const scoped = this.withRequestOptions(requestOptions);
326
861
  const changes = [];
327
- for await (const change of this.listAll(monitorId, options)) {
862
+ for await (const change of scoped.listAll(monitorId, options)) {
328
863
  changes.push(change);
329
864
  }
330
865
  return changes;
@@ -333,12 +868,13 @@ var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
333
868
  var AgentMonitorBacktestsClient = class extends AgentMonitorsBaseClient {
334
869
  /**
335
870
  * Start an async backtest of entities × fields over an explicit past news
336
- * window. Returns a `running` job; poll with `get` (or use `createAndWait`)
337
- * for the result.
871
+ * window. Returns a `running` job. Poll it with `get`, or use
872
+ * `createAndWait`, for the result.
338
873
  */
339
- async create(params) {
874
+ async create(params, requestOptions) {
875
+ const scoped = this.withRequestOptions(requestOptions);
340
876
  const { betas, ...payload } = params;
341
- return this.request(
877
+ return scoped.request(
342
878
  "/backtest",
343
879
  betas,
344
880
  "POST",
@@ -349,8 +885,9 @@ var AgentMonitorBacktestsClient = class extends AgentMonitorsBaseClient {
349
885
  * Poll a backtest job for its status and, once completed, its result.
350
886
  * Jobs expire and read as 404 after `expiresAt`.
351
887
  */
352
- async get(backtestId, options) {
353
- return this.request(
888
+ async get(backtestId, options, requestOptions) {
889
+ const scoped = this.withRequestOptions(requestOptions);
890
+ return scoped.request(
354
891
  `/backtest/${backtestId}`,
355
892
  options.betas,
356
893
  "GET"
@@ -359,12 +896,13 @@ var AgentMonitorBacktestsClient = class extends AgentMonitorsBaseClient {
359
896
  /**
360
897
  * Poll a backtest job until it reaches a terminal status.
361
898
  */
362
- async pollUntilFinished(backtestId, options) {
899
+ async pollUntilFinished(backtestId, options, requestOptions) {
900
+ const scoped = this.withRequestOptions(requestOptions);
363
901
  const pollInterval = options.pollInterval ?? DEFAULT_BACKTEST_POLL_INTERVAL_MS;
364
902
  const timeoutMs = options.timeoutMs ?? DEFAULT_BACKTEST_POLL_TIMEOUT_MS;
365
903
  const startTime = Date.now();
366
904
  while (true) {
367
- const backtest = await this.get(backtestId, { betas: options.betas });
905
+ const backtest = await scoped.get(backtestId, { betas: options.betas });
368
906
  if (backtest.status !== "running") {
369
907
  return backtest;
370
908
  }
@@ -373,16 +911,17 @@ var AgentMonitorBacktestsClient = class extends AgentMonitorsBaseClient {
373
911
  `Polling timeout: Agent monitor backtest ${backtestId} did not complete within ${timeoutMs}ms`
374
912
  );
375
913
  }
376
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
914
+ await sleep(pollInterval, scoped.requestOptions?.signal);
377
915
  }
378
916
  }
379
917
  /**
380
918
  * Start a backtest and wait for its result. Throws
381
919
  * AgentMonitorBacktestFailedError if the backtest fails.
382
920
  */
383
- async createAndWait(params, options) {
384
- const backtest = await this.create(params);
385
- const terminalBacktest = backtest.status === "running" ? await this.pollUntilFinished(backtest.id, {
921
+ async createAndWait(params, options, requestOptions) {
922
+ const scoped = this.withRequestOptions(requestOptions);
923
+ const backtest = await scoped.create(params);
924
+ const terminalBacktest = backtest.status === "running" ? await scoped.pollUntilFinished(backtest.id, {
386
925
  ...options,
387
926
  betas: params.betas
388
927
  }) : backtest;
@@ -404,10 +943,11 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
404
943
  * Creation is async: the monitor is returned with status `creating` and
405
944
  * becomes `active` once its first refresh completes.
406
945
  */
407
- async create(params, options) {
946
+ async create(params, options, requestOptions) {
947
+ const scoped = this.withRequestOptions(requestOptions);
408
948
  const { betas, ...payload } = params;
409
949
  const headers = options?.idempotencyKey ? { "Idempotency-Key": options.idempotencyKey } : void 0;
410
- return this.request(
950
+ return scoped.request(
411
951
  "",
412
952
  betas,
413
953
  "POST",
@@ -419,16 +959,18 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
419
959
  /**
420
960
  * Get an Agent Monitor by ID, including refresh progress.
421
961
  */
422
- async get(monitorId, options) {
423
- return this.request(`/${monitorId}`, options.betas, "GET");
962
+ async get(monitorId, options, requestOptions) {
963
+ const scoped = this.withRequestOptions(requestOptions);
964
+ return scoped.request(`/${monitorId}`, options.betas, "GET");
424
965
  }
425
966
  /**
426
967
  * List the team's Agent Monitors.
427
968
  */
428
- async list(options) {
969
+ async list(options, requestOptions) {
970
+ const scoped = this.withRequestOptions(requestOptions);
429
971
  const { betas, ...pagination } = options;
430
972
  const params = this.buildPaginationParams(pagination);
431
- return this.request(
973
+ return scoped.request(
432
974
  "",
433
975
  betas,
434
976
  "GET",
@@ -439,13 +981,14 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
439
981
  /**
440
982
  * Iterate through all Agent Monitors, handling pagination automatically.
441
983
  */
442
- async *listAll(options) {
984
+ async *listAll(options, requestOptions) {
985
+ let scoped = this.withRequestOptions(requestOptions);
443
986
  let cursor = options.cursor;
444
987
  const { betas, ...pagination } = options;
445
988
  const pageOptions = { ...pagination };
446
989
  while (true) {
447
990
  pageOptions.cursor = cursor;
448
- const response = await this.list({ ...pageOptions, betas });
991
+ const response = await scoped.list({ ...pageOptions, betas });
449
992
  for (const monitor of response.data) {
450
993
  yield monitor;
451
994
  }
@@ -453,14 +996,16 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
453
996
  break;
454
997
  }
455
998
  cursor = response.nextCursor;
999
+ scoped = scoped.forNextPage();
456
1000
  }
457
1001
  }
458
1002
  /**
459
1003
  * Collect all Agent Monitors into an array.
460
1004
  */
461
- async getAll(options) {
1005
+ async getAll(options, requestOptions) {
1006
+ const scoped = this.withRequestOptions(requestOptions);
462
1007
  const monitors = [];
463
- for await (const monitor of this.listAll(options)) {
1008
+ for await (const monitor of scoped.listAll(options)) {
464
1009
  monitors.push(monitor);
465
1010
  }
466
1011
  return monitors;
@@ -468,8 +1013,9 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
468
1013
  /**
469
1014
  * Delete an Agent Monitor and stop its refreshes.
470
1015
  */
471
- async delete(monitorId, options) {
472
- return this.request(
1016
+ async delete(monitorId, options, requestOptions) {
1017
+ const scoped = this.withRequestOptions(requestOptions);
1018
+ return scoped.request(
473
1019
  `/${monitorId}`,
474
1020
  options.betas,
475
1021
  "DELETE"
@@ -591,9 +1137,10 @@ var AgentRunEventsClient = class extends AgentBaseClient {
591
1137
  /**
592
1138
  * List stored events for an Agent run.
593
1139
  */
594
- async list(runId, options) {
1140
+ async list(runId, options, requestOptions) {
1141
+ const scoped = this.withRequestOptions(requestOptions);
595
1142
  const params = this.buildPaginationParams(options);
596
- return this.request(
1143
+ return scoped.request(
597
1144
  `/${runId}/events`,
598
1145
  "GET",
599
1146
  void 0,
@@ -606,47 +1153,45 @@ var AgentRunsClient = class extends AgentBaseClient {
606
1153
  super(client);
607
1154
  this.events = new AgentRunEventsClient(client);
608
1155
  }
609
- async create(params) {
1156
+ async create(params, requestOptions) {
1157
+ const scoped = this.withRequestOptions(requestOptions);
610
1158
  const { stream, payload } = buildAgentRunPayload(params);
611
1159
  if (stream) {
612
- const response = await this.rawRequest("", "POST", payload, void 0, {
1160
+ const response = await scoped.rawRequest("", "POST", payload, void 0, {
613
1161
  Accept: "text/event-stream"
614
1162
  });
615
1163
  if (!response.ok) {
616
- const message = await response.text();
617
- throw new ExaError(
618
- message || `Request failed with status code ${response.status}`,
619
- response.status,
620
- (/* @__PURE__ */ new Date()).toISOString(),
621
- "/agent/runs"
622
- );
1164
+ throw await exaErrorFromResponse(response, "/agent/runs");
623
1165
  }
624
1166
  return streamAgentEvents(response);
625
1167
  }
626
- return this.request("", "POST", payload);
1168
+ return scoped.request("", "POST", payload);
627
1169
  }
628
1170
  /**
629
1171
  * Get an Agent run by ID.
630
1172
  */
631
- async get(runId) {
632
- return this.request(`/${runId}`, "GET");
1173
+ async get(runId, requestOptions) {
1174
+ const scoped = this.withRequestOptions(requestOptions);
1175
+ return scoped.request(`/${runId}`, "GET");
633
1176
  }
634
1177
  /**
635
1178
  * List Agent runs.
636
1179
  */
637
- async list(options) {
1180
+ async list(options, requestOptions) {
1181
+ const scoped = this.withRequestOptions(requestOptions);
638
1182
  const params = this.buildPaginationParams(options);
639
- return this.request("", "GET", void 0, params);
1183
+ return scoped.request("", "GET", void 0, params);
640
1184
  }
641
1185
  /**
642
1186
  * Iterate through all Agent runs, handling pagination automatically.
643
1187
  */
644
- async *listAll(options) {
1188
+ async *listAll(options, requestOptions) {
1189
+ let scoped = this.withRequestOptions(requestOptions);
645
1190
  let cursor = void 0;
646
1191
  const pageOptions = options ? { ...options } : {};
647
1192
  while (true) {
648
1193
  pageOptions.cursor = cursor;
649
- const response = await this.list(pageOptions);
1194
+ const response = await scoped.list(pageOptions);
650
1195
  for (const run of response.data) {
651
1196
  yield run;
652
1197
  }
@@ -654,14 +1199,16 @@ var AgentRunsClient = class extends AgentBaseClient {
654
1199
  break;
655
1200
  }
656
1201
  cursor = response.nextCursor;
1202
+ scoped = scoped.forNextPage();
657
1203
  }
658
1204
  }
659
1205
  /**
660
1206
  * Collect all Agent runs into an array.
661
1207
  */
662
- async getAll(options) {
1208
+ async getAll(options, requestOptions) {
1209
+ const scoped = this.withRequestOptions(requestOptions);
663
1210
  const runs = [];
664
- for await (const run of this.listAll(options)) {
1211
+ for await (const run of scoped.listAll(options)) {
665
1212
  runs.push(run);
666
1213
  }
667
1214
  return runs;
@@ -669,31 +1216,35 @@ var AgentRunsClient = class extends AgentBaseClient {
669
1216
  /**
670
1217
  * Cancel a queued or running Agent run.
671
1218
  */
672
- async cancel(runId) {
673
- return this.request(`/${runId}/cancel`, "POST");
1219
+ async cancel(runId, requestOptions) {
1220
+ const scoped = this.withRequestOptions(requestOptions);
1221
+ return scoped.request(`/${runId}/cancel`, "POST");
674
1222
  }
675
1223
  /**
676
1224
  * Stop a running Agent run, completing it early with the results
677
1225
  * gathered so far. Only supported for `ultra` effort runs.
678
1226
  */
679
- async stop(runId) {
680
- return this.request(`/${runId}/stop`, "POST");
1227
+ async stop(runId, requestOptions) {
1228
+ const scoped = this.withRequestOptions(requestOptions);
1229
+ return scoped.request(`/${runId}/stop`, "POST");
681
1230
  }
682
1231
  /**
683
1232
  * Delete a stored Agent run.
684
1233
  */
685
- async delete(runId) {
686
- return this.request(`/${runId}`, "DELETE");
1234
+ async delete(runId, requestOptions) {
1235
+ const scoped = this.withRequestOptions(requestOptions);
1236
+ return scoped.request(`/${runId}`, "DELETE");
687
1237
  }
688
1238
  /**
689
1239
  * Poll an Agent run until it reaches a terminal status.
690
1240
  */
691
- async pollUntilFinished(runId, options) {
1241
+ async pollUntilFinished(runId, options, requestOptions) {
1242
+ const scoped = this.withRequestOptions(requestOptions);
692
1243
  const pollInterval = options?.pollInterval ?? DEFAULT_AGENT_POLL_INTERVAL_MS;
693
1244
  const timeoutMs = options?.timeoutMs ?? DEFAULT_AGENT_POLL_TIMEOUT_MS;
694
1245
  const startTime = Date.now();
695
1246
  while (true) {
696
- const run = await this.get(runId);
1247
+ const run = await scoped.get(runId);
697
1248
  if (isTerminalAgentRunStatus(run.status)) {
698
1249
  return run;
699
1250
  }
@@ -702,16 +1253,17 @@ var AgentRunsClient = class extends AgentBaseClient {
702
1253
  `Polling timeout: Agent run ${runId} did not complete within ${timeoutMs}ms`
703
1254
  );
704
1255
  }
705
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1256
+ await sleep(pollInterval, scoped.requestOptions?.signal);
706
1257
  }
707
1258
  }
708
- async createAndWait(params, options) {
1259
+ async createAndWait(params, options, requestOptions) {
1260
+ const scoped = this.withRequestOptions(requestOptions);
709
1261
  const { stream: _stream, ...createParams } = params;
710
- const run = await this.create(
1262
+ const run = await scoped.create(
711
1263
  createParams
712
1264
  );
713
1265
  const runId = run.id;
714
- const terminalRun = await this.pollUntilFinished(
1266
+ const terminalRun = await scoped.pollUntilFinished(
715
1267
  runId,
716
1268
  createAndWaitPollOptions(options)
717
1269
  );
@@ -730,10 +1282,11 @@ var AgentBetaRunEventsClient = class extends AgentRunEventsClient {
730
1282
  *
731
1283
  * @deprecated Use exa.agent.runs.events instead.
732
1284
  */
733
- async list(runId, options) {
1285
+ async list(runId, options, requestOptions) {
1286
+ const scoped = this.withRequestOptions(requestOptions);
734
1287
  const { betas, ...pagination } = options ?? {};
735
1288
  const params = this.buildPaginationParams(pagination);
736
- return this.request(
1289
+ return scoped.request(
737
1290
  `/${runId}/events`,
738
1291
  "GET",
739
1292
  void 0,
@@ -747,29 +1300,24 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
747
1300
  super(client);
748
1301
  this.events = new AgentBetaRunEventsClient(client);
749
1302
  }
750
- async create(params) {
1303
+ async create(params, requestOptions) {
1304
+ const scoped = this.withRequestOptions(requestOptions);
751
1305
  const { betas, ...createParams } = params;
752
1306
  const { stream, payload } = buildAgentRunPayload(
753
1307
  createParams
754
1308
  );
755
1309
  const headers = headersForBetas(betas);
756
1310
  if (stream) {
757
- const response = await this.rawRequest("", "POST", payload, void 0, {
1311
+ const response = await scoped.rawRequest("", "POST", payload, void 0, {
758
1312
  ...headers,
759
1313
  Accept: "text/event-stream"
760
1314
  });
761
1315
  if (!response.ok) {
762
- const message = await response.text();
763
- throw new ExaError(
764
- message || `Request failed with status code ${response.status}`,
765
- response.status,
766
- (/* @__PURE__ */ new Date()).toISOString(),
767
- "/agent/runs"
768
- );
1316
+ throw await exaErrorFromResponse(response, "/agent/runs");
769
1317
  }
770
1318
  return streamAgentEvents(response);
771
1319
  }
772
- return this.request(
1320
+ return scoped.request(
773
1321
  "",
774
1322
  "POST",
775
1323
  payload,
@@ -778,7 +1326,8 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
778
1326
  );
779
1327
  }
780
1328
  async get(runId, options) {
781
- return this.request(
1329
+ const scoped = this.withRequestOptions(options);
1330
+ return scoped.request(
782
1331
  `/${runId}`,
783
1332
  "GET",
784
1333
  void 0,
@@ -786,10 +1335,11 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
786
1335
  headersForBetas(options?.betas)
787
1336
  );
788
1337
  }
789
- async list(options) {
1338
+ async list(options, requestOptions) {
1339
+ const scoped = this.withRequestOptions(requestOptions);
790
1340
  const { betas, ...pagination } = options ?? {};
791
1341
  const params = this.buildPaginationParams(pagination);
792
- return this.request(
1342
+ return scoped.request(
793
1343
  "",
794
1344
  "GET",
795
1345
  void 0,
@@ -797,13 +1347,14 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
797
1347
  headersForBetas(betas)
798
1348
  );
799
1349
  }
800
- async *listAll(options) {
1350
+ async *listAll(options, requestOptions) {
1351
+ let scoped = this.withRequestOptions(requestOptions);
801
1352
  let cursor = void 0;
802
1353
  const { betas, ...pagination } = options ?? {};
803
1354
  const pageOptions = { ...pagination };
804
1355
  while (true) {
805
1356
  pageOptions.cursor = cursor;
806
- const response = await this.list({ ...pageOptions, betas });
1357
+ const response = await scoped.list({ ...pageOptions, betas });
807
1358
  for (const run of response.data) {
808
1359
  yield run;
809
1360
  }
@@ -811,17 +1362,20 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
811
1362
  break;
812
1363
  }
813
1364
  cursor = response.nextCursor;
1365
+ scoped = scoped.forNextPage();
814
1366
  }
815
1367
  }
816
- async getAll(options) {
1368
+ async getAll(options, requestOptions) {
1369
+ const scoped = this.withRequestOptions(requestOptions);
817
1370
  const runs = [];
818
- for await (const run of this.listAll(options)) {
1371
+ for await (const run of scoped.listAll(options)) {
819
1372
  runs.push(run);
820
1373
  }
821
1374
  return runs;
822
1375
  }
823
1376
  async cancel(runId, options) {
824
- return this.request(
1377
+ const scoped = this.withRequestOptions(options);
1378
+ return scoped.request(
825
1379
  `/${runId}/cancel`,
826
1380
  "POST",
827
1381
  void 0,
@@ -834,7 +1388,8 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
834
1388
  * gathered so far. Only supported for `ultra` effort runs.
835
1389
  */
836
1390
  async stop(runId, options) {
837
- return this.request(
1391
+ const scoped = this.withRequestOptions(options);
1392
+ return scoped.request(
838
1393
  `/${runId}/stop`,
839
1394
  "POST",
840
1395
  void 0,
@@ -843,7 +1398,8 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
843
1398
  );
844
1399
  }
845
1400
  async delete(runId, options) {
846
- return this.request(
1401
+ const scoped = this.withRequestOptions(options);
1402
+ return scoped.request(
847
1403
  `/${runId}`,
848
1404
  "DELETE",
849
1405
  void 0,
@@ -851,13 +1407,14 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
851
1407
  headersForBetas(options?.betas)
852
1408
  );
853
1409
  }
854
- async pollUntilFinished(runId, options) {
1410
+ async pollUntilFinished(runId, options, requestOptions) {
1411
+ const scoped = this.withRequestOptions(requestOptions);
855
1412
  const pollInterval = options?.pollInterval ?? DEFAULT_AGENT_POLL_INTERVAL_MS;
856
1413
  const timeoutMs = options?.timeoutMs ?? DEFAULT_AGENT_POLL_TIMEOUT_MS;
857
1414
  const startTime = Date.now();
858
1415
  const headers = headersForBetas(options?.betas);
859
1416
  while (true) {
860
- const run = await this.request(
1417
+ const run = await scoped.request(
861
1418
  `/${runId}`,
862
1419
  "GET",
863
1420
  void 0,
@@ -872,21 +1429,22 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
872
1429
  `Polling timeout: Agent run ${runId} did not complete within ${timeoutMs}ms`
873
1430
  );
874
1431
  }
875
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1432
+ await sleep(pollInterval, scoped.requestOptions?.signal);
876
1433
  }
877
1434
  }
878
- async createAndWait(params, options) {
1435
+ async createAndWait(params, options, requestOptions) {
1436
+ const scoped = this.withRequestOptions(requestOptions);
879
1437
  const {
880
1438
  betas,
881
1439
  stream: _stream,
882
1440
  ...createParams
883
1441
  } = params;
884
- const run = await this.create({
1442
+ const run = await scoped.create({
885
1443
  ...createParams,
886
1444
  betas
887
1445
  });
888
1446
  const runId = run.id;
889
- const terminalRun = await this.pollUntilFinished(runId, {
1447
+ const terminalRun = await scoped.pollUntilFinished(runId, {
890
1448
  ...createAndWaitPollOptions(options),
891
1449
  betas
892
1450
  });
@@ -908,17 +1466,23 @@ var BetaClient = class {
908
1466
  };
909
1467
 
910
1468
  // src/monitors/base.ts
911
- var SearchMonitorsBaseClient = class {
1469
+ var SearchMonitorsBaseClient = class extends RequestScopedClient {
912
1470
  constructor(client) {
1471
+ super();
913
1472
  this.client = client;
914
1473
  }
915
1474
  async request(endpoint, method = "POST", data, params) {
916
- return this.client.request(
917
- `/monitors${endpoint}`,
918
- method,
919
- data,
920
- params
921
- );
1475
+ if (this.requestOptions) {
1476
+ return this.client.request(
1477
+ `/monitors${endpoint}`,
1478
+ method,
1479
+ data,
1480
+ params,
1481
+ void 0,
1482
+ this.requestOptions
1483
+ );
1484
+ }
1485
+ return this.client.request(`/monitors${endpoint}`, method, data, params);
922
1486
  }
923
1487
  buildPaginationParams(pagination) {
924
1488
  const params = {};
@@ -937,11 +1501,13 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
937
1501
  * List all runs for a Search Monitor
938
1502
  * @param monitorId The ID of the Search Monitor
939
1503
  * @param options Pagination options
1504
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
940
1505
  * @returns The list of Search Monitor runs
941
1506
  */
942
- async list(monitorId, options) {
1507
+ async list(monitorId, options, requestOptions) {
1508
+ const scoped = this.withRequestOptions(requestOptions);
943
1509
  const params = this.buildPaginationParams(options);
944
- return this.request(
1510
+ return scoped.request(
945
1511
  `/${monitorId}/runs`,
946
1512
  "GET",
947
1513
  void 0,
@@ -952,10 +1518,12 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
952
1518
  * Get a specific Search Monitor run
953
1519
  * @param monitorId The ID of the Search Monitor
954
1520
  * @param runId The ID of the run
1521
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
955
1522
  * @returns The Search Monitor run
956
1523
  */
957
- async get(monitorId, runId) {
958
- return this.request(
1524
+ async get(monitorId, runId, requestOptions) {
1525
+ const scoped = this.withRequestOptions(requestOptions);
1526
+ return scoped.request(
959
1527
  `/${monitorId}/runs/${runId}`,
960
1528
  "GET"
961
1529
  );
@@ -964,14 +1532,16 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
964
1532
  * Iterate through all runs for a Search Monitor, handling pagination automatically
965
1533
  * @param monitorId The ID of the Search Monitor
966
1534
  * @param options Pagination options
1535
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
967
1536
  * @returns Async generator of Search Monitor runs
968
1537
  */
969
- async *listAll(monitorId, options) {
1538
+ async *listAll(monitorId, options, requestOptions) {
1539
+ let scoped = this.withRequestOptions(requestOptions);
970
1540
  let cursor = void 0;
971
1541
  const pageOptions = options ? { ...options } : {};
972
1542
  while (true) {
973
1543
  pageOptions.cursor = cursor;
974
- const response = await this.list(monitorId, pageOptions);
1544
+ const response = await scoped.list(monitorId, pageOptions);
975
1545
  for (const run of response.data) {
976
1546
  yield run;
977
1547
  }
@@ -979,17 +1549,20 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
979
1549
  break;
980
1550
  }
981
1551
  cursor = response.nextCursor;
1552
+ scoped = scoped.forNextPage();
982
1553
  }
983
1554
  }
984
1555
  /**
985
1556
  * Collect all runs for a Search Monitor into an array
986
1557
  * @param monitorId The ID of the Search Monitor
987
1558
  * @param options Pagination options
1559
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
988
1560
  * @returns Promise resolving to an array of all Search Monitor runs
989
1561
  */
990
- async getAll(monitorId, options) {
1562
+ async getAll(monitorId, options, requestOptions) {
1563
+ const scoped = this.withRequestOptions(requestOptions);
991
1564
  const runs = [];
992
- for await (const run of this.listAll(monitorId, options)) {
1565
+ for await (const run of scoped.listAll(monitorId, options)) {
993
1566
  runs.push(run);
994
1567
  }
995
1568
  return runs;
@@ -1003,27 +1576,33 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1003
1576
  /**
1004
1577
  * Create a Search Monitor
1005
1578
  * @param params The monitor creation parameters
1579
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1006
1580
  * @returns The created Search Monitor with webhookSecret
1007
1581
  */
1008
- async create(params) {
1009
- return this.request("", "POST", params);
1582
+ async create(params, requestOptions) {
1583
+ const scoped = this.withRequestOptions(requestOptions);
1584
+ return scoped.request("", "POST", params);
1010
1585
  }
1011
1586
  /**
1012
1587
  * Get a Search Monitor by ID
1013
1588
  * @param id The ID of the Search Monitor
1589
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1014
1590
  * @returns The Search Monitor
1015
1591
  */
1016
- async get(id) {
1017
- return this.request(`/${id}`, "GET");
1592
+ async get(id, requestOptions) {
1593
+ const scoped = this.withRequestOptions(requestOptions);
1594
+ return scoped.request(`/${id}`, "GET");
1018
1595
  }
1019
1596
  /**
1020
1597
  * List Search Monitors
1021
1598
  * @param options Pagination and filtering options
1599
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1022
1600
  * @returns The list of Search Monitors
1023
1601
  */
1024
- async list(options) {
1602
+ async list(options, requestOptions) {
1603
+ const scoped = this.withRequestOptions(requestOptions);
1025
1604
  const params = this.buildPaginationParams(options);
1026
- return this.request(
1605
+ return scoped.request(
1027
1606
  "",
1028
1607
  "GET",
1029
1608
  void 0,
@@ -1034,26 +1613,32 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1034
1613
  * Update a Search Monitor
1035
1614
  * @param id The ID of the Search Monitor
1036
1615
  * @param params The update parameters
1616
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1037
1617
  * @returns The updated Search Monitor
1038
1618
  */
1039
- async update(id, params) {
1040
- return this.request(`/${id}`, "PATCH", params);
1619
+ async update(id, params, requestOptions) {
1620
+ const scoped = this.withRequestOptions(requestOptions);
1621
+ return scoped.request(`/${id}`, "PATCH", params);
1041
1622
  }
1042
1623
  /**
1043
1624
  * Delete a Search Monitor
1044
1625
  * @param id The ID of the Search Monitor
1626
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1045
1627
  * @returns The deleted Search Monitor
1046
1628
  */
1047
- async delete(id) {
1048
- return this.request(`/${id}`, "DELETE");
1629
+ async delete(id, requestOptions) {
1630
+ const scoped = this.withRequestOptions(requestOptions);
1631
+ return scoped.request(`/${id}`, "DELETE");
1049
1632
  }
1050
1633
  /**
1051
1634
  * Trigger a Search Monitor run immediately
1052
1635
  * @param id The ID of the Search Monitor
1636
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1053
1637
  * @returns Whether the monitor was triggered
1054
1638
  */
1055
- async trigger(id) {
1056
- return this.request(
1639
+ async trigger(id, requestOptions) {
1640
+ const scoped = this.withRequestOptions(requestOptions);
1641
+ return scoped.request(
1057
1642
  `/${id}/trigger`,
1058
1643
  "POST"
1059
1644
  );
@@ -1061,14 +1646,16 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1061
1646
  /**
1062
1647
  * Iterate through all Search Monitors, handling pagination automatically
1063
1648
  * @param options Pagination and filtering options
1649
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1064
1650
  * @returns Async generator of Search Monitors
1065
1651
  */
1066
- async *listAll(options) {
1652
+ async *listAll(options, requestOptions) {
1653
+ let scoped = this.withRequestOptions(requestOptions);
1067
1654
  let cursor = void 0;
1068
1655
  const pageOptions = options ? { ...options } : {};
1069
1656
  while (true) {
1070
1657
  pageOptions.cursor = cursor;
1071
- const response = await this.list(pageOptions);
1658
+ const response = await scoped.list(pageOptions);
1072
1659
  for (const monitor of response.data) {
1073
1660
  yield monitor;
1074
1661
  }
@@ -1076,16 +1663,19 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1076
1663
  break;
1077
1664
  }
1078
1665
  cursor = response.nextCursor;
1666
+ scoped = scoped.forNextPage();
1079
1667
  }
1080
1668
  }
1081
1669
  /**
1082
1670
  * Collect all Search Monitors into an array
1083
1671
  * @param options Pagination and filtering options
1672
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1084
1673
  * @returns Promise resolving to an array of all Search Monitors
1085
1674
  */
1086
- async getAll(options) {
1675
+ async getAll(options, requestOptions) {
1676
+ const scoped = this.withRequestOptions(requestOptions);
1087
1677
  const monitors = [];
1088
- for await (const monitor of this.listAll(options)) {
1678
+ for await (const monitor of scoped.listAll(options)) {
1089
1679
  monitors.push(monitor);
1090
1680
  }
1091
1681
  return monitors;
@@ -1093,25 +1683,22 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1093
1683
  };
1094
1684
 
1095
1685
  // src/research/base.ts
1096
- var ResearchBaseClient = class {
1686
+ var RESEARCH_RETIRED_MESSAGE = "The Exa Research API has been retired and no longer accepts requests. Use the Agent API (exa.agent.runs.create) for asynchronous, multi-step research.";
1687
+ function researchRetiredError() {
1688
+ return new ExaError(RESEARCH_RETIRED_MESSAGE, 410);
1689
+ }
1690
+ var ResearchBaseClient = class extends RequestScopedClient {
1097
1691
  constructor(client) {
1692
+ super();
1098
1693
  this.client = client;
1099
1694
  }
1100
- async request(endpoint, method = "POST", data, params) {
1101
- return this.client.request(
1102
- `/research/v1${endpoint}`,
1103
- method,
1104
- data,
1105
- params
1106
- );
1695
+ /** Rejects with `researchRetiredError()`: the Research API has been retired. */
1696
+ async request(_endpoint, _method = "POST", _data, _params) {
1697
+ throw researchRetiredError();
1107
1698
  }
1108
- async rawRequest(endpoint, method = "POST", data, params) {
1109
- return this.client.rawRequest(
1110
- `/research/v1${endpoint}`,
1111
- method,
1112
- data,
1113
- params
1114
- );
1699
+ /** Rejects with `researchRetiredError()`: the Research API has been retired. */
1700
+ async rawRequest(_endpoint, _method = "POST", _data, _params) {
1701
+ throw researchRetiredError();
1115
1702
  }
1116
1703
  buildPaginationParams(pagination) {
1117
1704
  const params = {};
@@ -1127,7 +1714,8 @@ var ResearchClient = class extends ResearchBaseClient {
1127
1714
  constructor(client) {
1128
1715
  super(client);
1129
1716
  }
1130
- async create(params) {
1717
+ async create(params, requestOptions) {
1718
+ const scoped = this.withRequestOptions(requestOptions);
1131
1719
  const { instructions, model, outputSchema } = params;
1132
1720
  let schema = outputSchema;
1133
1721
  if (schema && isZodSchema(schema)) {
@@ -1140,21 +1728,25 @@ var ResearchClient = class extends ResearchBaseClient {
1140
1728
  if (schema) {
1141
1729
  payload.outputSchema = schema;
1142
1730
  }
1143
- return this.request("", "POST", payload);
1731
+ return scoped.request("", "POST", payload);
1144
1732
  }
1145
- get(researchId, options) {
1733
+ get(researchId, options, requestOptions) {
1734
+ const scoped = this.withRequestOptions(requestOptions);
1146
1735
  if (options?.stream) {
1147
1736
  const promise = async () => {
1148
1737
  const params = { stream: "true" };
1149
1738
  if (options.events !== void 0) {
1150
1739
  params.events = options.events.toString();
1151
1740
  }
1152
- const resp = await this.rawRequest(
1741
+ const resp = await scoped.rawRequest(
1153
1742
  `/${researchId}`,
1154
1743
  "GET",
1155
1744
  void 0,
1156
1745
  params
1157
1746
  );
1747
+ if (!resp.ok) {
1748
+ throw await exaErrorFromResponse(resp, `/research/v1/${researchId}`);
1749
+ }
1158
1750
  if (!resp.body) {
1159
1751
  throw new Error("No response body for SSE stream");
1160
1752
  }
@@ -1174,23 +1766,30 @@ var ResearchClient = class extends ResearchBaseClient {
1174
1766
  }
1175
1767
  }
1176
1768
  async function* streamEvents() {
1177
- while (true) {
1178
- const { done, value } = await reader.read();
1179
- if (done) break;
1180
- buffer += decoder.decode(value, { stream: true });
1181
- let parts = buffer.split("\n\n");
1182
- buffer = parts.pop() ?? "";
1183
- for (const part of parts) {
1184
- const processed = processPart(part);
1769
+ try {
1770
+ while (true) {
1771
+ const { done, value } = await reader.read();
1772
+ if (done) break;
1773
+ buffer += decoder.decode(value, { stream: true });
1774
+ let parts = buffer.split("\n\n");
1775
+ buffer = parts.pop() ?? "";
1776
+ for (const part of parts) {
1777
+ const processed = processPart(part);
1778
+ if (processed) {
1779
+ yield processed;
1780
+ }
1781
+ }
1782
+ }
1783
+ if (buffer.trim()) {
1784
+ const processed = processPart(buffer.trim());
1185
1785
  if (processed) {
1186
1786
  yield processed;
1187
1787
  }
1188
1788
  }
1189
- }
1190
- if (buffer.trim()) {
1191
- const processed = processPart(buffer.trim());
1192
- if (processed) {
1193
- yield processed;
1789
+ } finally {
1790
+ try {
1791
+ await reader.cancel();
1792
+ } catch {
1194
1793
  }
1195
1794
  }
1196
1795
  }
@@ -1202,7 +1801,7 @@ var ResearchClient = class extends ResearchBaseClient {
1202
1801
  if (options?.events !== void 0) {
1203
1802
  params.events = options.events.toString();
1204
1803
  }
1205
- return this.request(
1804
+ return scoped.request(
1206
1805
  `/${researchId}`,
1207
1806
  "GET",
1208
1807
  void 0,
@@ -1210,50 +1809,24 @@ var ResearchClient = class extends ResearchBaseClient {
1210
1809
  );
1211
1810
  }
1212
1811
  }
1213
- async list(options) {
1812
+ async list(options, requestOptions) {
1813
+ const scoped = this.withRequestOptions(requestOptions);
1214
1814
  const params = this.buildPaginationParams(options);
1215
- return this.request("", "GET", void 0, params);
1815
+ return scoped.request("", "GET", void 0, params);
1216
1816
  }
1217
- async pollUntilFinished(researchId, options) {
1218
- const pollInterval = options?.pollInterval ?? 1e3;
1219
- const timeoutMs = options?.timeoutMs ?? 10 * 60 * 1e3;
1220
- const maxConsecutiveFailures = 5;
1221
- const startTime = Date.now();
1222
- let consecutiveFailures = 0;
1223
- while (true) {
1224
- try {
1225
- const research = await this.get(researchId, {
1226
- events: options?.events
1227
- });
1228
- consecutiveFailures = 0;
1229
- if (research.status === "completed" || research.status === "failed" || research.status === "canceled") {
1230
- return research;
1231
- }
1232
- } catch (err) {
1233
- consecutiveFailures += 1;
1234
- if (consecutiveFailures >= maxConsecutiveFailures) {
1235
- throw new Error(
1236
- `Polling failed ${maxConsecutiveFailures} times in a row for research ${researchId}: ${err}`
1237
- );
1238
- }
1239
- }
1240
- if (Date.now() - startTime > timeoutMs) {
1241
- throw new Error(
1242
- `Polling timeout: Research ${researchId} did not complete within ${timeoutMs}ms`
1243
- );
1244
- }
1245
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1246
- }
1817
+ async pollUntilFinished(_researchId, _options, _requestOptions) {
1818
+ throw researchRetiredError();
1247
1819
  }
1248
1820
  };
1249
1821
 
1250
1822
  // src/websets/base.ts
1251
- var WebsetsBaseClient = class {
1823
+ var WebsetsBaseClient = class extends RequestScopedClient {
1252
1824
  /**
1253
1825
  * Initialize a new Websets base client
1254
1826
  * @param client The Exa client instance
1255
1827
  */
1256
1828
  constructor(client) {
1829
+ super();
1257
1830
  this.client = client;
1258
1831
  }
1259
1832
  /**
@@ -1266,6 +1839,16 @@ var WebsetsBaseClient = class {
1266
1839
  * @throws ExaError with API error details if the request fails
1267
1840
  */
1268
1841
  async request(endpoint, method = "POST", data, params, headers) {
1842
+ if (this.requestOptions) {
1843
+ return this.client.request(
1844
+ `/websets${endpoint}`,
1845
+ method,
1846
+ data,
1847
+ params,
1848
+ headers,
1849
+ this.requestOptions
1850
+ );
1851
+ }
1269
1852
  return this.client.request(
1270
1853
  `/websets${endpoint}`,
1271
1854
  method,
@@ -1294,10 +1877,12 @@ var WebsetEnrichmentsClient = class extends WebsetsBaseClient {
1294
1877
  * Create an Enrichment for a Webset
1295
1878
  * @param websetId The ID of the Webset
1296
1879
  * @param params The enrichment parameters
1880
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1297
1881
  * @returns The created Webset Enrichment
1298
1882
  */
1299
- async create(websetId, params) {
1300
- return this.request(
1883
+ async create(websetId, params, requestOptions) {
1884
+ const scoped = this.withRequestOptions(requestOptions);
1885
+ return scoped.request(
1301
1886
  `/v0/websets/${websetId}/enrichments`,
1302
1887
  "POST",
1303
1888
  params
@@ -1307,10 +1892,12 @@ var WebsetEnrichmentsClient = class extends WebsetsBaseClient {
1307
1892
  * Get an Enrichment by ID
1308
1893
  * @param websetId The ID of the Webset
1309
1894
  * @param id The ID of the Enrichment
1895
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1310
1896
  * @returns The Webset Enrichment
1311
1897
  */
1312
- async get(websetId, id) {
1313
- return this.request(
1898
+ async get(websetId, id, requestOptions) {
1899
+ const scoped = this.withRequestOptions(requestOptions);
1900
+ return scoped.request(
1314
1901
  `/v0/websets/${websetId}/enrichments/${id}`,
1315
1902
  "GET"
1316
1903
  );
@@ -1319,10 +1906,12 @@ var WebsetEnrichmentsClient = class extends WebsetsBaseClient {
1319
1906
  * Delete an Enrichment
1320
1907
  * @param websetId The ID of the Webset
1321
1908
  * @param id The ID of the Enrichment
1909
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1322
1910
  * @returns The deleted Webset Enrichment
1323
1911
  */
1324
- async delete(websetId, id) {
1325
- return this.request(
1912
+ async delete(websetId, id, requestOptions) {
1913
+ const scoped = this.withRequestOptions(requestOptions);
1914
+ return scoped.request(
1326
1915
  `/v0/websets/${websetId}/enrichments/${id}`,
1327
1916
  "DELETE"
1328
1917
  );
@@ -1332,10 +1921,12 @@ var WebsetEnrichmentsClient = class extends WebsetsBaseClient {
1332
1921
  * @param websetId The ID of the Webset
1333
1922
  * @param id The ID of the Enrichment
1334
1923
  * @param params The enrichment update parameters
1924
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1335
1925
  * @returns Promise that resolves when the update is complete
1336
1926
  */
1337
- async update(websetId, id, params) {
1338
- return this.request(
1927
+ async update(websetId, id, params, requestOptions) {
1928
+ const scoped = this.withRequestOptions(requestOptions);
1929
+ return scoped.request(
1339
1930
  `/v0/websets/${websetId}/enrichments/${id}`,
1340
1931
  "PATCH",
1341
1932
  params
@@ -1345,10 +1936,12 @@ var WebsetEnrichmentsClient = class extends WebsetsBaseClient {
1345
1936
  * Cancel a running Enrichment
1346
1937
  * @param websetId The ID of the Webset
1347
1938
  * @param id The ID of the Enrichment
1939
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1348
1940
  * @returns The canceled Webset Enrichment
1349
1941
  */
1350
- async cancel(websetId, id) {
1351
- return this.request(
1942
+ async cancel(websetId, id, requestOptions) {
1943
+ const scoped = this.withRequestOptions(requestOptions);
1944
+ return scoped.request(
1352
1945
  `/v0/websets/${websetId}/enrichments/${id}/cancel`,
1353
1946
  "POST"
1354
1947
  );
@@ -1367,15 +1960,17 @@ var EventsClient = class extends WebsetsBaseClient {
1367
1960
  /**
1368
1961
  * List all Events
1369
1962
  * @param options Optional filtering and pagination options
1963
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1370
1964
  * @returns The list of Events
1371
1965
  */
1372
- async list(options) {
1966
+ async list(options, requestOptions) {
1967
+ const scoped = this.withRequestOptions(requestOptions);
1373
1968
  const params = {
1374
1969
  cursor: options?.cursor,
1375
1970
  limit: options?.limit,
1376
1971
  types: options?.types
1377
1972
  };
1378
- return this.request(
1973
+ return scoped.request(
1379
1974
  "/v0/events",
1380
1975
  "GET",
1381
1976
  void 0,
@@ -1385,22 +1980,26 @@ var EventsClient = class extends WebsetsBaseClient {
1385
1980
  /**
1386
1981
  * Get an Event by ID
1387
1982
  * @param id The ID of the Event
1983
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1388
1984
  * @returns The Event
1389
1985
  */
1390
- async get(id) {
1391
- return this.request(`/v0/events/${id}`, "GET");
1986
+ async get(id, requestOptions) {
1987
+ const scoped = this.withRequestOptions(requestOptions);
1988
+ return scoped.request(`/v0/events/${id}`, "GET");
1392
1989
  }
1393
1990
  /**
1394
1991
  * Iterate through all Events, handling pagination automatically
1395
1992
  * @param options Filtering and pagination options
1993
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1396
1994
  * @returns Async generator of Events
1397
1995
  */
1398
- async *listAll(options) {
1996
+ async *listAll(options, requestOptions) {
1997
+ let scoped = this.withRequestOptions(requestOptions);
1399
1998
  let cursor = void 0;
1400
1999
  const pageOptions = options ? { ...options } : {};
1401
2000
  while (true) {
1402
2001
  pageOptions.cursor = cursor;
1403
- const response = await this.list(pageOptions);
2002
+ const response = await scoped.list(pageOptions);
1404
2003
  for (const event of response.data) {
1405
2004
  yield event;
1406
2005
  }
@@ -1408,16 +2007,19 @@ var EventsClient = class extends WebsetsBaseClient {
1408
2007
  break;
1409
2008
  }
1410
2009
  cursor = response.nextCursor;
2010
+ scoped = scoped.forNextPage();
1411
2011
  }
1412
2012
  }
1413
2013
  /**
1414
2014
  * Collect all Events into an array
1415
2015
  * @param options Filtering and pagination options
2016
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1416
2017
  * @returns Promise resolving to an array of all Events
1417
2018
  */
1418
- async getAll(options) {
2019
+ async getAll(options, requestOptions) {
2020
+ const scoped = this.withRequestOptions(requestOptions);
1419
2021
  const events = [];
1420
- for await (const event of this.listAll(options)) {
2022
+ for await (const event of scoped.listAll(options)) {
1421
2023
  events.push(event);
1422
2024
  }
1423
2025
  return events;
@@ -1591,28 +2193,31 @@ var WebsetSearchCanceledReason = /* @__PURE__ */ ((WebsetSearchCanceledReason2)
1591
2193
 
1592
2194
  // src/websets/imports.ts
1593
2195
  var ImportsClient = class extends WebsetsBaseClient {
1594
- async create(params, csv) {
2196
+ async create(params, csv, requestOptions) {
2197
+ const scoped = this.withRequestOptions(requestOptions);
1595
2198
  if (csv === void 0) {
1596
- return this.request(
2199
+ return scoped.request(
1597
2200
  "/v0/imports",
1598
2201
  "POST",
1599
2202
  params
1600
2203
  );
1601
2204
  }
1602
- let csvBuffer;
2205
+ let csvBytes;
2206
+ let csvText;
1603
2207
  if (typeof csv === "string") {
1604
- csvBuffer = Buffer.from(csv, "utf8");
1605
- } else if (Buffer.isBuffer(csv)) {
1606
- csvBuffer = csv;
2208
+ csvBytes = new TextEncoder().encode(csv);
2209
+ csvText = csv;
2210
+ } else if (csv instanceof Uint8Array) {
2211
+ csvBytes = csv;
2212
+ csvText = new TextDecoder().decode(csv);
1607
2213
  } else {
1608
2214
  throw new ExaError(
1609
- "Invalid CSV data input. Must be string or Buffer",
2215
+ "Invalid CSV data input. Must be a string or a Uint8Array such as a Buffer",
1610
2216
  400 /* BadRequest */
1611
2217
  );
1612
2218
  }
1613
- const sizeInBytes = csvBuffer.length;
2219
+ const sizeInBytes = csvBytes.byteLength;
1614
2220
  const sizeInMB = Math.max(1, Math.ceil(sizeInBytes / (1024 * 1024)));
1615
- const csvText = csvBuffer.toString("utf8");
1616
2221
  const lines = csvText.split("\n").filter((line) => line.trim().length > 0);
1617
2222
  const recordCount = Math.max(0, lines.length - 1);
1618
2223
  if (sizeInMB > 50) {
@@ -1636,15 +2241,19 @@ var ImportsClient = class extends WebsetsBaseClient {
1636
2241
  metadata: params.metadata,
1637
2242
  csv: params.csv
1638
2243
  };
1639
- const importResponse = await this.request(
2244
+ const importResponse = await scoped.request(
1640
2245
  "/v0/imports",
1641
2246
  "POST",
1642
2247
  createParams
1643
2248
  );
2249
+ const upload = resolveRequestSignal(
2250
+ withClientDefaults(this.client, scoped.requestOptions)
2251
+ );
1644
2252
  try {
1645
2253
  const uploadResponse = await fetch(importResponse.uploadUrl, {
1646
2254
  method: "PUT",
1647
- body: csvBuffer
2255
+ body: csvBytes,
2256
+ signal: upload.signal
1648
2257
  });
1649
2258
  if (!uploadResponse.ok) {
1650
2259
  const errorText = await uploadResponse.text();
@@ -1654,32 +2263,39 @@ var ImportsClient = class extends WebsetsBaseClient {
1654
2263
  );
1655
2264
  }
1656
2265
  } catch (error) {
1657
- if (error instanceof ExaError) {
1658
- throw error;
2266
+ const requestError = upload.toRequestError(error);
2267
+ if (requestError instanceof ExaError || requestError instanceof ExaAbortError) {
2268
+ throw requestError;
1659
2269
  }
1660
2270
  throw new ExaError(
1661
2271
  `Failed to upload CSV data: ${error.message}`,
1662
2272
  400 /* BadRequest */
1663
2273
  );
2274
+ } finally {
2275
+ upload.dispose();
1664
2276
  }
1665
2277
  return importResponse;
1666
2278
  }
1667
2279
  /**
1668
2280
  * Get an Import by ID
1669
2281
  * @param id The ID of the Import
2282
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1670
2283
  * @returns The Import
1671
2284
  */
1672
- async get(id) {
1673
- return this.request(`/v0/imports/${id}`, "GET");
2285
+ async get(id, requestOptions) {
2286
+ const scoped = this.withRequestOptions(requestOptions);
2287
+ return scoped.request(`/v0/imports/${id}`, "GET");
1674
2288
  }
1675
2289
  /**
1676
2290
  * List all Imports
1677
2291
  * @param options Pagination options
2292
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1678
2293
  * @returns The list of Imports
1679
2294
  */
1680
- async list(options) {
2295
+ async list(options, requestOptions) {
2296
+ const scoped = this.withRequestOptions(requestOptions);
1681
2297
  const params = this.buildPaginationParams(options);
1682
- return this.request(
2298
+ return scoped.request(
1683
2299
  "/v0/imports",
1684
2300
  "GET",
1685
2301
  void 0,
@@ -1690,33 +2306,39 @@ var ImportsClient = class extends WebsetsBaseClient {
1690
2306
  * Update an Import
1691
2307
  * @param id The ID of the Import
1692
2308
  * @param params The import update parameters
2309
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1693
2310
  * @returns The updated Import
1694
2311
  */
1695
- async update(id, params) {
1696
- return this.request(`/v0/imports/${id}`, "PATCH", params);
2312
+ async update(id, params, requestOptions) {
2313
+ const scoped = this.withRequestOptions(requestOptions);
2314
+ return scoped.request(`/v0/imports/${id}`, "PATCH", params);
1697
2315
  }
1698
2316
  /**
1699
2317
  * Delete an Import
1700
2318
  * @param id The ID of the Import
2319
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1701
2320
  * @returns The deleted Import
1702
2321
  */
1703
- async delete(id) {
1704
- return this.request(`/v0/imports/${id}`, "DELETE");
2322
+ async delete(id, requestOptions) {
2323
+ const scoped = this.withRequestOptions(requestOptions);
2324
+ return scoped.request(`/v0/imports/${id}`, "DELETE");
1705
2325
  }
1706
2326
  /**
1707
2327
  * Wait until an Import is completed or failed
1708
2328
  * @param id The ID of the Import
1709
2329
  * @param options Configuration options for timeout and polling
2330
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1710
2331
  * @returns The Import once it reaches a final state (completed or failed)
1711
2332
  * @throws Error if the Import does not complete within the timeout or fails
1712
2333
  */
1713
- async waitUntilCompleted(id, options) {
2334
+ async waitUntilCompleted(id, options, requestOptions) {
2335
+ const scoped = this.withRequestOptions(requestOptions);
1714
2336
  const timeout = options?.timeout ?? 30 * 60 * 1e3;
1715
2337
  const pollInterval = options?.pollInterval ?? 2e3;
1716
2338
  const onPoll = options?.onPoll;
1717
2339
  const startTime = Date.now();
1718
2340
  while (true) {
1719
- const importItem = await this.get(id);
2341
+ const importItem = await scoped.get(id);
1720
2342
  if (onPoll) {
1721
2343
  onPoll(importItem.status);
1722
2344
  }
@@ -1735,20 +2357,22 @@ var ImportsClient = class extends WebsetsBaseClient {
1735
2357
  408 /* RequestTimeout */
1736
2358
  );
1737
2359
  }
1738
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
2360
+ await sleep(pollInterval, scoped.requestOptions?.signal);
1739
2361
  }
1740
2362
  }
1741
2363
  /**
1742
2364
  * Iterate through all Imports, handling pagination automatically
1743
2365
  * @param options Pagination options
2366
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1744
2367
  * @returns Async generator of Imports
1745
2368
  */
1746
- async *listAll(options) {
2369
+ async *listAll(options, requestOptions) {
2370
+ let scoped = this.withRequestOptions(requestOptions);
1747
2371
  let cursor = void 0;
1748
2372
  const pageOptions = options ? { ...options } : {};
1749
2373
  while (true) {
1750
2374
  pageOptions.cursor = cursor;
1751
- const response = await this.list(pageOptions);
2375
+ const response = await scoped.list(pageOptions);
1752
2376
  for (const importItem of response.data) {
1753
2377
  yield importItem;
1754
2378
  }
@@ -1756,16 +2380,19 @@ var ImportsClient = class extends WebsetsBaseClient {
1756
2380
  break;
1757
2381
  }
1758
2382
  cursor = response.nextCursor;
2383
+ scoped = scoped.forNextPage();
1759
2384
  }
1760
2385
  }
1761
2386
  /**
1762
2387
  * Collect all Imports into an array
1763
2388
  * @param options Pagination options
2389
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1764
2390
  * @returns Promise resolving to an array of all Imports
1765
2391
  */
1766
- async getAll(options) {
2392
+ async getAll(options, requestOptions) {
2393
+ const scoped = this.withRequestOptions(requestOptions);
1767
2394
  const imports = [];
1768
- for await (const importItem of this.listAll(options)) {
2395
+ for await (const importItem of scoped.listAll(options)) {
1769
2396
  imports.push(importItem);
1770
2397
  }
1771
2398
  return imports;
@@ -1778,14 +2405,16 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
1778
2405
  * List all Items for a Webset
1779
2406
  * @param websetId The ID of the Webset
1780
2407
  * @param params - Optional pagination and filtering parameters
2408
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1781
2409
  * @returns A promise that resolves with the list of Items
1782
2410
  */
1783
- list(websetId, params) {
2411
+ list(websetId, params, requestOptions) {
2412
+ const scoped = this.withRequestOptions(requestOptions);
1784
2413
  const queryParams = {
1785
2414
  ...this.buildPaginationParams(params),
1786
2415
  sourceId: params?.sourceId
1787
2416
  };
1788
- return this.request(
2417
+ return scoped.request(
1789
2418
  `/v0/websets/${websetId}/items`,
1790
2419
  "GET",
1791
2420
  void 0,
@@ -1796,14 +2425,16 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
1796
2425
  * Iterate through all Items in a Webset, handling pagination automatically
1797
2426
  * @param websetId The ID of the Webset
1798
2427
  * @param options Pagination options
2428
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1799
2429
  * @returns Async generator of Webset Items
1800
2430
  */
1801
- async *listAll(websetId, options) {
2431
+ async *listAll(websetId, options, requestOptions) {
2432
+ let scoped = this.withRequestOptions(requestOptions);
1802
2433
  let cursor = void 0;
1803
2434
  const pageOptions = options ? { ...options } : {};
1804
2435
  while (true) {
1805
2436
  pageOptions.cursor = cursor;
1806
- const response = await this.list(websetId, pageOptions);
2437
+ const response = await scoped.list(websetId, pageOptions);
1807
2438
  for (const item of response.data) {
1808
2439
  yield item;
1809
2440
  }
@@ -1811,17 +2442,20 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
1811
2442
  break;
1812
2443
  }
1813
2444
  cursor = response.nextCursor;
2445
+ scoped = scoped.forNextPage();
1814
2446
  }
1815
2447
  }
1816
2448
  /**
1817
2449
  * Collect all items from a Webset into an array
1818
2450
  * @param websetId The ID of the Webset
1819
2451
  * @param options Pagination options
2452
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1820
2453
  * @returns Promise resolving to an array of all Webset Items
1821
2454
  */
1822
- async getAll(websetId, options) {
2455
+ async getAll(websetId, options, requestOptions) {
2456
+ const scoped = this.withRequestOptions(requestOptions);
1823
2457
  const items = [];
1824
- for await (const item of this.listAll(websetId, options)) {
2458
+ for await (const item of scoped.listAll(websetId, options)) {
1825
2459
  items.push(item);
1826
2460
  }
1827
2461
  return items;
@@ -1830,10 +2464,12 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
1830
2464
  * Get an Item by ID
1831
2465
  * @param websetId The ID of the Webset
1832
2466
  * @param id The ID of the Item
2467
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1833
2468
  * @returns The Webset Item
1834
2469
  */
1835
- async get(websetId, id) {
1836
- return this.request(
2470
+ async get(websetId, id, requestOptions) {
2471
+ const scoped = this.withRequestOptions(requestOptions);
2472
+ return scoped.request(
1837
2473
  `/v0/websets/${websetId}/items/${id}`,
1838
2474
  "GET"
1839
2475
  );
@@ -1842,10 +2478,12 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
1842
2478
  * Delete an Item
1843
2479
  * @param websetId The ID of the Webset
1844
2480
  * @param id The ID of the Item
2481
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1845
2482
  * @returns The deleted Webset Item
1846
2483
  */
1847
- async delete(websetId, id) {
1848
- return this.request(
2484
+ async delete(websetId, id, requestOptions) {
2485
+ const scoped = this.withRequestOptions(requestOptions);
2486
+ return scoped.request(
1849
2487
  `/v0/websets/${websetId}/items/${id}`,
1850
2488
  "DELETE"
1851
2489
  );
@@ -1858,11 +2496,13 @@ var WebsetMonitorRunsClient = class extends WebsetsBaseClient {
1858
2496
  * List all runs for a Monitor
1859
2497
  * @param monitorId The ID of the Monitor
1860
2498
  * @param options Pagination options
2499
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1861
2500
  * @returns The list of Monitor runs
1862
2501
  */
1863
- async list(monitorId, options) {
2502
+ async list(monitorId, options, requestOptions) {
2503
+ const scoped = this.withRequestOptions(requestOptions);
1864
2504
  const params = this.buildPaginationParams(options);
1865
- return this.request(
2505
+ return scoped.request(
1866
2506
  `/v0/monitors/${monitorId}/runs`,
1867
2507
  "GET",
1868
2508
  void 0,
@@ -1873,10 +2513,12 @@ var WebsetMonitorRunsClient = class extends WebsetsBaseClient {
1873
2513
  * Get a specific Monitor run
1874
2514
  * @param monitorId The ID of the Monitor
1875
2515
  * @param runId The ID of the Monitor run
2516
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1876
2517
  * @returns The Monitor run
1877
2518
  */
1878
- async get(monitorId, runId) {
1879
- return this.request(
2519
+ async get(monitorId, runId, requestOptions) {
2520
+ const scoped = this.withRequestOptions(requestOptions);
2521
+ return scoped.request(
1880
2522
  `/v0/monitors/${monitorId}/runs/${runId}`,
1881
2523
  "GET"
1882
2524
  );
@@ -1890,31 +2532,37 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
1890
2532
  /**
1891
2533
  * Create a Monitor
1892
2534
  * @param params The monitor parameters
2535
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1893
2536
  * @returns The created Monitor
1894
2537
  */
1895
- async create(params) {
1896
- return this.request("/v0/monitors", "POST", params);
2538
+ async create(params, requestOptions) {
2539
+ const scoped = this.withRequestOptions(requestOptions);
2540
+ return scoped.request("/v0/monitors", "POST", params);
1897
2541
  }
1898
2542
  /**
1899
2543
  * Get a Monitor by ID
1900
2544
  * @param id The ID of the Monitor
2545
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1901
2546
  * @returns The Monitor
1902
2547
  */
1903
- async get(id) {
1904
- return this.request(`/v0/monitors/${id}`, "GET");
2548
+ async get(id, requestOptions) {
2549
+ const scoped = this.withRequestOptions(requestOptions);
2550
+ return scoped.request(`/v0/monitors/${id}`, "GET");
1905
2551
  }
1906
2552
  /**
1907
2553
  * List all Monitors
1908
2554
  * @param options Pagination and filtering options
2555
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1909
2556
  * @returns The list of Monitors
1910
2557
  */
1911
- async list(options) {
2558
+ async list(options, requestOptions) {
2559
+ const scoped = this.withRequestOptions(requestOptions);
1912
2560
  const params = {
1913
2561
  cursor: options?.cursor,
1914
2562
  limit: options?.limit,
1915
2563
  websetId: options?.websetId
1916
2564
  };
1917
- return this.request(
2565
+ return scoped.request(
1918
2566
  "/v0/monitors",
1919
2567
  "GET",
1920
2568
  void 0,
@@ -1925,30 +2573,36 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
1925
2573
  * Update a Monitor
1926
2574
  * @param id The ID of the Monitor
1927
2575
  * @param params The monitor update parameters (status, metadata)
2576
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1928
2577
  * @returns The updated Monitor
1929
2578
  */
1930
- async update(id, params) {
1931
- return this.request(`/v0/monitors/${id}`, "PATCH", params);
2579
+ async update(id, params, requestOptions) {
2580
+ const scoped = this.withRequestOptions(requestOptions);
2581
+ return scoped.request(`/v0/monitors/${id}`, "PATCH", params);
1932
2582
  }
1933
2583
  /**
1934
2584
  * Delete a Monitor
1935
2585
  * @param id The ID of the Monitor
2586
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1936
2587
  * @returns The deleted Monitor
1937
2588
  */
1938
- async delete(id) {
1939
- return this.request(`/v0/monitors/${id}`, "DELETE");
2589
+ async delete(id, requestOptions) {
2590
+ const scoped = this.withRequestOptions(requestOptions);
2591
+ return scoped.request(`/v0/monitors/${id}`, "DELETE");
1940
2592
  }
1941
2593
  /**
1942
2594
  * Iterate through all Monitors, handling pagination automatically
1943
2595
  * @param options Pagination and filtering options
2596
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1944
2597
  * @returns Async generator of Monitors
1945
2598
  */
1946
- async *listAll(options) {
2599
+ async *listAll(options, requestOptions) {
2600
+ let scoped = this.withRequestOptions(requestOptions);
1947
2601
  let cursor = void 0;
1948
2602
  const pageOptions = options ? { ...options } : {};
1949
2603
  while (true) {
1950
2604
  pageOptions.cursor = cursor;
1951
- const response = await this.list(pageOptions);
2605
+ const response = await scoped.list(pageOptions);
1952
2606
  for (const monitor of response.data) {
1953
2607
  yield monitor;
1954
2608
  }
@@ -1956,16 +2610,19 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
1956
2610
  break;
1957
2611
  }
1958
2612
  cursor = response.nextCursor;
2613
+ scoped = scoped.forNextPage();
1959
2614
  }
1960
2615
  }
1961
2616
  /**
1962
2617
  * Collect all Monitors into an array
1963
2618
  * @param options Pagination and filtering options
2619
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1964
2620
  * @returns Promise resolving to an array of all Monitors
1965
2621
  */
1966
- async getAll(options) {
2622
+ async getAll(options, requestOptions) {
2623
+ const scoped = this.withRequestOptions(requestOptions);
1967
2624
  const monitors = [];
1968
- for await (const monitor of this.listAll(options)) {
2625
+ for await (const monitor of scoped.listAll(options)) {
1969
2626
  monitors.push(monitor);
1970
2627
  }
1971
2628
  return monitors;
@@ -1978,10 +2635,12 @@ var WebsetSearchesClient = class extends WebsetsBaseClient {
1978
2635
  * Create a new Search for the Webset
1979
2636
  * @param websetId The ID of the Webset
1980
2637
  * @param params The search parameters
2638
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1981
2639
  * @returns The created Webset Search
1982
2640
  */
1983
- async create(websetId, params, options) {
1984
- return this.request(
2641
+ async create(websetId, params, options, requestOptions) {
2642
+ const scoped = this.withRequestOptions(requestOptions);
2643
+ return scoped.request(
1985
2644
  `/v0/websets/${websetId}/searches`,
1986
2645
  "POST",
1987
2646
  params,
@@ -1993,10 +2652,12 @@ var WebsetSearchesClient = class extends WebsetsBaseClient {
1993
2652
  * Get a Search by ID
1994
2653
  * @param websetId The ID of the Webset
1995
2654
  * @param id The ID of the Search
2655
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
1996
2656
  * @returns The Webset Search
1997
2657
  */
1998
- async get(websetId, id) {
1999
- return this.request(
2658
+ async get(websetId, id, requestOptions) {
2659
+ const scoped = this.withRequestOptions(requestOptions);
2660
+ return scoped.request(
2000
2661
  `/v0/websets/${websetId}/searches/${id}`,
2001
2662
  "GET"
2002
2663
  );
@@ -2005,10 +2666,12 @@ var WebsetSearchesClient = class extends WebsetsBaseClient {
2005
2666
  * Cancel a running Search
2006
2667
  * @param websetId The ID of the Webset
2007
2668
  * @param id The ID of the Search
2669
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2008
2670
  * @returns The canceled Webset Search
2009
2671
  */
2010
- async cancel(websetId, id) {
2011
- return this.request(
2672
+ async cancel(websetId, id, requestOptions) {
2673
+ const scoped = this.withRequestOptions(requestOptions);
2674
+ return scoped.request(
2012
2675
  `/v0/websets/${websetId}/searches/${id}/cancel`,
2013
2676
  "POST"
2014
2677
  );
@@ -2020,27 +2683,33 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2020
2683
  /**
2021
2684
  * Create a Webhook
2022
2685
  * @param params The webhook parameters
2686
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2023
2687
  * @returns The created Webhook
2024
2688
  */
2025
- async create(params) {
2026
- return this.request("/v0/webhooks", "POST", params);
2689
+ async create(params, requestOptions) {
2690
+ const scoped = this.withRequestOptions(requestOptions);
2691
+ return scoped.request("/v0/webhooks", "POST", params);
2027
2692
  }
2028
2693
  /**
2029
2694
  * Get a Webhook by ID
2030
2695
  * @param id The ID of the Webhook
2696
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2031
2697
  * @returns The Webhook
2032
2698
  */
2033
- async get(id) {
2034
- return this.request(`/v0/webhooks/${id}`, "GET");
2699
+ async get(id, requestOptions) {
2700
+ const scoped = this.withRequestOptions(requestOptions);
2701
+ return scoped.request(`/v0/webhooks/${id}`, "GET");
2035
2702
  }
2036
2703
  /**
2037
2704
  * List all Webhooks
2038
2705
  * @param options Pagination options
2706
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2039
2707
  * @returns The list of Webhooks
2040
2708
  */
2041
- async list(options) {
2709
+ async list(options, requestOptions) {
2710
+ const scoped = this.withRequestOptions(requestOptions);
2042
2711
  const params = this.buildPaginationParams(options);
2043
- return this.request(
2712
+ return scoped.request(
2044
2713
  "/v0/webhooks",
2045
2714
  "GET",
2046
2715
  void 0,
@@ -2050,14 +2719,16 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2050
2719
  /**
2051
2720
  * Iterate through all Webhooks, handling pagination automatically
2052
2721
  * @param options Pagination options
2722
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2053
2723
  * @returns Async generator of Webhooks
2054
2724
  */
2055
- async *listAll(options) {
2725
+ async *listAll(options, requestOptions) {
2726
+ let scoped = this.withRequestOptions(requestOptions);
2056
2727
  let cursor = void 0;
2057
2728
  const pageOptions = options ? { ...options } : {};
2058
2729
  while (true) {
2059
2730
  pageOptions.cursor = cursor;
2060
- const response = await this.list(pageOptions);
2731
+ const response = await scoped.list(pageOptions);
2061
2732
  for (const webhook of response.data) {
2062
2733
  yield webhook;
2063
2734
  }
@@ -2065,16 +2736,19 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2065
2736
  break;
2066
2737
  }
2067
2738
  cursor = response.nextCursor;
2739
+ scoped = scoped.forNextPage();
2068
2740
  }
2069
2741
  }
2070
2742
  /**
2071
2743
  * Collect all Webhooks into an array
2072
2744
  * @param options Pagination options
2745
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2073
2746
  * @returns Promise resolving to an array of all Webhooks
2074
2747
  */
2075
- async getAll(options) {
2748
+ async getAll(options, requestOptions) {
2749
+ const scoped = this.withRequestOptions(requestOptions);
2076
2750
  const webhooks = [];
2077
- for await (const webhook of this.listAll(options)) {
2751
+ for await (const webhook of scoped.listAll(options)) {
2078
2752
  webhooks.push(webhook);
2079
2753
  }
2080
2754
  return webhooks;
@@ -2083,33 +2757,39 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2083
2757
  * Update a Webhook
2084
2758
  * @param id The ID of the Webhook
2085
2759
  * @param params The webhook update parameters (events, metadata, url)
2760
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2086
2761
  * @returns The updated Webhook
2087
2762
  */
2088
- async update(id, params) {
2089
- return this.request(`/v0/webhooks/${id}`, "PATCH", params);
2763
+ async update(id, params, requestOptions) {
2764
+ const scoped = this.withRequestOptions(requestOptions);
2765
+ return scoped.request(`/v0/webhooks/${id}`, "PATCH", params);
2090
2766
  }
2091
2767
  /**
2092
2768
  * Delete a Webhook
2093
2769
  * @param id The ID of the Webhook
2770
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2094
2771
  * @returns The deleted Webhook
2095
2772
  */
2096
- async delete(id) {
2097
- return this.request(`/v0/webhooks/${id}`, "DELETE");
2773
+ async delete(id, requestOptions) {
2774
+ const scoped = this.withRequestOptions(requestOptions);
2775
+ return scoped.request(`/v0/webhooks/${id}`, "DELETE");
2098
2776
  }
2099
2777
  /**
2100
2778
  * List all attempts for a Webhook
2101
2779
  * @param id The ID of the Webhook
2102
2780
  * @param options Pagination and filtering options
2781
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2103
2782
  * @returns The list of Webhook attempts
2104
2783
  */
2105
- async listAttempts(id, options) {
2784
+ async listAttempts(id, options, requestOptions) {
2785
+ const scoped = this.withRequestOptions(requestOptions);
2106
2786
  const params = {
2107
2787
  cursor: options?.cursor,
2108
2788
  limit: options?.limit,
2109
2789
  eventType: options?.eventType,
2110
2790
  successful: options?.successful
2111
2791
  };
2112
- return this.request(
2792
+ return scoped.request(
2113
2793
  `/v0/webhooks/${id}/attempts`,
2114
2794
  "GET",
2115
2795
  void 0,
@@ -2120,14 +2800,16 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2120
2800
  * Iterate through all attempts for a Webhook, handling pagination automatically
2121
2801
  * @param id The ID of the Webhook
2122
2802
  * @param options Pagination and filtering options
2803
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2123
2804
  * @returns Async generator of Webhook attempts
2124
2805
  */
2125
- async *listAllAttempts(id, options) {
2806
+ async *listAllAttempts(id, options, requestOptions) {
2807
+ let scoped = this.withRequestOptions(requestOptions);
2126
2808
  let cursor = void 0;
2127
2809
  const pageOptions = options ? { ...options } : {};
2128
2810
  while (true) {
2129
2811
  pageOptions.cursor = cursor;
2130
- const response = await this.listAttempts(id, pageOptions);
2812
+ const response = await scoped.listAttempts(id, pageOptions);
2131
2813
  for (const attempt of response.data) {
2132
2814
  yield attempt;
2133
2815
  }
@@ -2135,17 +2817,20 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2135
2817
  break;
2136
2818
  }
2137
2819
  cursor = response.nextCursor;
2820
+ scoped = scoped.forNextPage();
2138
2821
  }
2139
2822
  }
2140
2823
  /**
2141
2824
  * Collect all attempts for a Webhook into an array
2142
2825
  * @param id The ID of the Webhook
2143
2826
  * @param options Pagination and filtering options
2827
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2144
2828
  * @returns Promise resolving to an array of all Webhook attempts
2145
2829
  */
2146
- async getAllAttempts(id, options) {
2830
+ async getAllAttempts(id, options, requestOptions) {
2831
+ const scoped = this.withRequestOptions(requestOptions);
2147
2832
  const attempts = [];
2148
- for await (const attempt of this.listAllAttempts(id, options)) {
2833
+ for await (const attempt of scoped.listAllAttempts(id, options)) {
2149
2834
  attempts.push(attempt);
2150
2835
  }
2151
2836
  return attempts;
@@ -2171,10 +2856,12 @@ var WebsetsClient = class extends WebsetsBaseClient {
2171
2856
  /**
2172
2857
  * Create a new Webset
2173
2858
  * @param params The Webset creation parameters
2859
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2174
2860
  * @returns The created Webset
2175
2861
  */
2176
- async create(params, options) {
2177
- return this.request(
2862
+ async create(params, options, requestOptions) {
2863
+ const scoped = this.withRequestOptions(requestOptions);
2864
+ return scoped.request(
2178
2865
  "/v0/websets",
2179
2866
  "POST",
2180
2867
  params,
@@ -2186,14 +2873,16 @@ var WebsetsClient = class extends WebsetsBaseClient {
2186
2873
  * Preview a webset
2187
2874
  * @param params The preview parameters
2188
2875
  * @param options Optional parameters. Search = true allows you to retrieve a preview set of items that could be returned by the webset.
2189
- * @returns The preview response showing how the query will be decomposed
2876
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2877
+ * @returns How the query will be interpreted.
2190
2878
  */
2191
- async preview(params, options) {
2879
+ async preview(params, options, requestOptions) {
2880
+ const scoped = this.withRequestOptions(requestOptions);
2192
2881
  const queryParams = {};
2193
2882
  if (options?.search !== void 0) {
2194
2883
  queryParams.search = options.search;
2195
2884
  }
2196
- return this.request(
2885
+ return scoped.request(
2197
2886
  "/v0/websets/preview",
2198
2887
  "POST",
2199
2888
  params,
@@ -2204,14 +2893,16 @@ var WebsetsClient = class extends WebsetsBaseClient {
2204
2893
  * Get a Webset by ID
2205
2894
  * @param id The ID of the Webset
2206
2895
  * @param expand Optional array of relations to expand
2896
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2207
2897
  * @returns The Webset
2208
2898
  */
2209
- async get(id, expand) {
2899
+ async get(id, expand, requestOptions) {
2900
+ const scoped = this.withRequestOptions(requestOptions);
2210
2901
  const params = {};
2211
2902
  if (expand) {
2212
2903
  params.expand = expand;
2213
2904
  }
2214
- return this.request(
2905
+ return scoped.request(
2215
2906
  `/v0/websets/${id}`,
2216
2907
  "GET",
2217
2908
  void 0,
@@ -2221,11 +2912,13 @@ var WebsetsClient = class extends WebsetsBaseClient {
2221
2912
  /**
2222
2913
  * List all Websets
2223
2914
  * @param options Pagination options (filtering by status is not supported by API)
2915
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2224
2916
  * @returns The list of Websets
2225
2917
  */
2226
- async list(options) {
2918
+ async list(options, requestOptions) {
2919
+ const scoped = this.withRequestOptions(requestOptions);
2227
2920
  const params = this.buildPaginationParams(options);
2228
- return this.request(
2921
+ return scoped.request(
2229
2922
  "/v0/websets",
2230
2923
  "GET",
2231
2924
  void 0,
@@ -2235,14 +2928,16 @@ var WebsetsClient = class extends WebsetsBaseClient {
2235
2928
  /**
2236
2929
  * Iterate through all Websets, handling pagination automatically
2237
2930
  * @param options Pagination options
2931
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2238
2932
  * @returns Async generator of Websets
2239
2933
  */
2240
- async *listAll(options) {
2934
+ async *listAll(options, requestOptions) {
2935
+ let scoped = this.withRequestOptions(requestOptions);
2241
2936
  let cursor = void 0;
2242
2937
  const pageOptions = options ? { ...options } : {};
2243
2938
  while (true) {
2244
2939
  pageOptions.cursor = cursor;
2245
- const response = await this.list(pageOptions);
2940
+ const response = await scoped.list(pageOptions);
2246
2941
  for (const webset of response.data) {
2247
2942
  yield webset;
2248
2943
  }
@@ -2250,16 +2945,19 @@ var WebsetsClient = class extends WebsetsBaseClient {
2250
2945
  break;
2251
2946
  }
2252
2947
  cursor = response.nextCursor;
2948
+ scoped = scoped.forNextPage();
2253
2949
  }
2254
2950
  }
2255
2951
  /**
2256
2952
  * Collect all Websets into an array
2257
2953
  * @param options Pagination options
2954
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2258
2955
  * @returns Promise resolving to an array of all Websets
2259
2956
  */
2260
- async getAll(options) {
2957
+ async getAll(options, requestOptions) {
2958
+ const scoped = this.withRequestOptions(requestOptions);
2261
2959
  const websets = [];
2262
- for await (const webset of this.listAll(options)) {
2960
+ for await (const webset of scoped.listAll(options)) {
2263
2961
  websets.push(webset);
2264
2962
  }
2265
2963
  return websets;
@@ -2268,35 +2966,43 @@ var WebsetsClient = class extends WebsetsBaseClient {
2268
2966
  * Update a Webset
2269
2967
  * @param id The ID of the Webset
2270
2968
  * @param params The Webset update parameters
2969
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2271
2970
  * @returns The updated Webset
2272
2971
  */
2273
- async update(id, params) {
2274
- return this.request(`/v0/websets/${id}`, "POST", params);
2972
+ async update(id, params, requestOptions) {
2973
+ const scoped = this.withRequestOptions(requestOptions);
2974
+ return scoped.request(`/v0/websets/${id}`, "POST", params);
2275
2975
  }
2276
2976
  /**
2277
2977
  * Delete a Webset
2278
2978
  * @param id The ID of the Webset
2979
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2279
2980
  * @returns The deleted Webset
2280
2981
  */
2281
- async delete(id) {
2282
- return this.request(`/v0/websets/${id}`, "DELETE");
2982
+ async delete(id, requestOptions) {
2983
+ const scoped = this.withRequestOptions(requestOptions);
2984
+ return scoped.request(`/v0/websets/${id}`, "DELETE");
2283
2985
  }
2284
2986
  /**
2285
2987
  * Cancel a running Webset
2286
2988
  * @param id The ID or external ID of the Webset
2989
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2287
2990
  * @returns The canceled Webset (as returned by the API)
2288
2991
  */
2289
- async cancel(id) {
2290
- return this.request(`/v0/websets/${id}/cancel`, "POST");
2992
+ async cancel(id, requestOptions) {
2993
+ const scoped = this.withRequestOptions(requestOptions);
2994
+ return scoped.request(`/v0/websets/${id}/cancel`, "POST");
2291
2995
  }
2292
2996
  /**
2293
2997
  * Wait until a Webset is idle
2294
2998
  * @param id The ID of the Webset
2295
2999
  * @param options Configuration options for timeout and polling
3000
+ * @param requestOptions Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`)
2296
3001
  * @returns The Webset once it becomes idle
2297
3002
  * @throws Error if the Webset does not become idle within the timeout
2298
3003
  */
2299
- async waitUntilIdle(id, options) {
3004
+ async waitUntilIdle(id, options, requestOptions) {
3005
+ const scoped = this.withRequestOptions(requestOptions);
2300
3006
  let timeout;
2301
3007
  let pollInterval = 1e3;
2302
3008
  let onPoll;
@@ -2309,7 +3015,7 @@ var WebsetsClient = class extends WebsetsBaseClient {
2309
3015
  }
2310
3016
  const startTime = Date.now();
2311
3017
  while (true) {
2312
- const webset = await this.get(id);
3018
+ const webset = await scoped.get(id);
2313
3019
  if (onPoll) {
2314
3020
  onPoll(webset.status);
2315
3021
  }
@@ -2322,7 +3028,7 @@ var WebsetsClient = class extends WebsetsBaseClient {
2322
3028
  408 /* RequestTimeout */
2323
3029
  );
2324
3030
  }
2325
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
3031
+ await sleep(pollInterval, scoped.requestOptions?.signal);
2326
3032
  }
2327
3033
  }
2328
3034
  };
@@ -2354,8 +3060,15 @@ ${result.highlights.join("\n")}`);
2354
3060
  }).join("\n\n---\n\n");
2355
3061
  return formatted || emptyMessage;
2356
3062
  }
3063
+ function formatSearchNotices(response) {
3064
+ return (response.notices ?? []).filter((notice) => typeof notice?.message === "string").map((notice) => `Note: ${notice.message}`);
3065
+ }
2357
3066
  function formatSearchResponse(response) {
2358
- return formatResults(response, "No search results found.");
3067
+ const text = formatResults(response, "No search results found.");
3068
+ const notes = formatSearchNotices(response);
3069
+ return notes.length === 0 ? text : `${notes.join("\n")}
3070
+
3071
+ ${text}`;
2359
3072
  }
2360
3073
  function formatContentsResponse(response) {
2361
3074
  return formatResults(response, "No contents found.");
@@ -2755,31 +3468,75 @@ var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : f
2755
3468
  var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : Headers;
2756
3469
  var DEFAULT_MAX_CHARACTERS = 1e4;
2757
3470
  var DYNAMIC_HIGHLIGHTS_BETA = "dynamic-highlights-2026-08-28";
2758
- var NON_JSON_BODY_SNIPPET_LENGTH = 500;
2759
- async function readResponseBody(response) {
2760
- const text = await response.text();
2761
- if (!text) {
2762
- return { json: void 0, text };
3471
+ var loggedWarnings = /* @__PURE__ */ new Set();
3472
+ function logWarningOnce(warning, context) {
3473
+ const request = `${context.method} ${context.endpoint}`;
3474
+ const key = `${request} ${warning.code} ${warning.path}`;
3475
+ if (loggedWarnings.has(key)) {
3476
+ return;
3477
+ }
3478
+ loggedWarnings.add(key);
3479
+ console.warn(
3480
+ `[exa] ${request} ${warning.code} at ${warning.path}: ${warning.message}`
3481
+ );
3482
+ }
3483
+ function warningHandlerFor(option) {
3484
+ if (option === void 0 || option === "log") {
3485
+ return logWarningOnce;
2763
3486
  }
2764
- try {
2765
- return { json: JSON.parse(text), text };
2766
- } catch {
2767
- return { json: void 0, text };
3487
+ if (option === "silent") {
3488
+ return void 0;
3489
+ }
3490
+ if (typeof option === "function") {
3491
+ return option;
2768
3492
  }
3493
+ throw new TypeError(
3494
+ `options.warnings must be "log", "silent" or a function, got ${JSON.stringify(option)}`
3495
+ );
2769
3496
  }
2770
- function truncateResponseBody(text) {
2771
- const collapsed = text.replace(/\s+/g, " ").trim();
2772
- return collapsed.length > NON_JSON_BODY_SNIPPET_LENGTH ? `${collapsed.slice(0, NON_JSON_BODY_SNIPPET_LENGTH)}\u2026` : collapsed;
3497
+ var BODY_WARNING_ENDPOINTS = /* @__PURE__ */ new Set(["/search"]);
3498
+ function isApiWarning(value) {
3499
+ if (typeof value !== "object" || value === null) {
3500
+ return false;
3501
+ }
3502
+ const { code, path, message } = value;
3503
+ return typeof code === "string" && typeof path === "string" && typeof message === "string";
3504
+ }
3505
+ function bodyWarnings(endpoint, body) {
3506
+ if (!BODY_WARNING_ENDPOINTS.has(endpoint) || typeof body !== "object" || body === null) {
3507
+ return [];
3508
+ }
3509
+ const { warnings } = body;
3510
+ return Array.isArray(warnings) ? warnings.filter(isApiWarning) : [];
3511
+ }
3512
+ function withJsonSummarySchema(contents) {
3513
+ if (typeof contents !== "object" || contents === null) return contents;
3514
+ const summary = contents.summary;
3515
+ if (typeof summary !== "object" || summary === null) return contents;
3516
+ const schema = summary.schema;
3517
+ if (!isZodSchema(schema)) return contents;
3518
+ return {
3519
+ ...contents,
3520
+ summary: { ...summary, schema: zodToJsonSchema(schema) }
3521
+ };
2773
3522
  }
2774
3523
  var Exa2 = class {
2775
3524
  /**
2776
3525
  * Constructs the Exa API client.
2777
3526
  * @param {string} apiKey - The API key for authentication.
2778
3527
  * @param {string} [baseURL] - The base URL of the Exa API.
3528
+ * @param {ExaClientOptions} [options] - Client-wide settings (`timeout`, `warnings`).
3529
+ * @throws {RangeError} When `options.timeout` is not an integer from 1 to 2147483647.
3530
+ * @throws {TypeError} When `options.warnings` is not `"log"`, `"silent"` or a function.
2779
3531
  */
2780
- constructor(apiKey, baseURL = "https://api.exa.ai") {
3532
+ constructor(apiKey, baseURL = "https://api.exa.ai", options) {
2781
3533
  this.toolRegistry = new ToolRegistry();
2782
3534
  this.baseURL = baseURL;
3535
+ this.warningHandler = warningHandlerFor(options?.warnings);
3536
+ setClientDefaults(
3537
+ this,
3538
+ options?.timeout === void 0 ? void 0 : { timeout: validateTimeout(options.timeout) }
3539
+ );
2783
3540
  if (!apiKey) {
2784
3541
  apiKey = process.env.EXA_API_KEY;
2785
3542
  if (!apiKey) {
@@ -2800,12 +3557,37 @@ var Exa2 = class {
2800
3557
  this.agent = new AgentClient(this);
2801
3558
  this.beta = new BetaClient(this.agent);
2802
3559
  this.tools = {
2803
- webSearch: (options) => createWebSearchTool(this, this.toolRegistry, options),
2804
- getContents: (options) => createGetContentsTool(this, this.toolRegistry, options)
3560
+ webSearch: (options2) => createWebSearchTool(this, this.toolRegistry, options2),
3561
+ getContents: (options2) => createGetContentsTool(this, this.toolRegistry, options2)
2805
3562
  };
2806
3563
  this.openai = new OpenAITools(this, this.toolRegistry);
2807
3564
  this.anthropic = new AnthropicTools(this, this.toolRegistry);
2808
3565
  }
3566
+ /**
3567
+ * Hands each warning in a response body or stream payload to the `warnings`
3568
+ * option's handler. `request` calls it for every JSON response and
3569
+ * `streamChatCompletions` for every stream payload, so every endpoint
3570
+ * reports through here.
3571
+ */
3572
+ reportWarnings(endpoint, method, body, requestIdHeader) {
3573
+ if (!this.warningHandler) {
3574
+ return;
3575
+ }
3576
+ const warnings = bodyWarnings(endpoint, body);
3577
+ if (warnings.length === 0) {
3578
+ return;
3579
+ }
3580
+ const bodyRequestId = body.requestId;
3581
+ const requestId = typeof bodyRequestId === "string" ? bodyRequestId : requestIdHeader ?? void 0;
3582
+ const context = {
3583
+ endpoint,
3584
+ method: method.toUpperCase(),
3585
+ ...requestId !== void 0 && { requestId }
3586
+ };
3587
+ for (const warning of warnings) {
3588
+ this.warningHandler(warning, context);
3589
+ }
3590
+ }
2809
3591
  /**
2810
3592
  * Helper method to separate out the contents-specific options from the rest.
2811
3593
  */
@@ -2821,6 +3603,7 @@ var Exa2 = class {
2821
3603
  livecrawlTimeout,
2822
3604
  maxAgeHours,
2823
3605
  snapshotAsOf,
3606
+ filterEmptyResults,
2824
3607
  // DEPRECATED FIELD: preserve legacy `context` only for backward compatibility.
2825
3608
  context,
2826
3609
  ...rest
@@ -2831,16 +3614,7 @@ var Exa2 = class {
2831
3614
  }
2832
3615
  if (text !== void 0) contentsOptions.text = text;
2833
3616
  if (highlights !== void 0) contentsOptions.highlights = highlights;
2834
- if (summary !== void 0) {
2835
- if (typeof summary === "object" && summary !== null && "schema" in summary && summary.schema && isZodSchema(summary.schema)) {
2836
- contentsOptions.summary = {
2837
- ...summary,
2838
- schema: zodToJsonSchema(summary.schema)
2839
- };
2840
- } else {
2841
- contentsOptions.summary = summary;
2842
- }
2843
- }
3617
+ if (summary !== void 0) contentsOptions.summary = summary;
2844
3618
  if (subpages !== void 0) contentsOptions.subpages = subpages;
2845
3619
  if (subpageTarget !== void 0)
2846
3620
  contentsOptions.subpageTarget = subpageTarget;
@@ -2849,30 +3623,27 @@ var Exa2 = class {
2849
3623
  if (livecrawlTimeout !== void 0)
2850
3624
  contentsOptions.livecrawlTimeout = livecrawlTimeout;
2851
3625
  if (maxAgeHours !== void 0) contentsOptions.maxAgeHours = maxAgeHours;
2852
- if (snapshotAsOf !== void 0)
2853
- contentsOptions.snapshotAsOf = snapshotAsOf;
3626
+ if (snapshotAsOf !== void 0) contentsOptions.snapshotAsOf = snapshotAsOf;
3627
+ if (filterEmptyResults !== void 0)
3628
+ contentsOptions.filterEmptyResults = filterEmptyResults;
2854
3629
  if (context !== void 0) contentsOptions.context = context;
2855
3630
  return {
2856
- contentsOptions,
3631
+ contentsOptions: withJsonSummarySchema(contentsOptions),
2857
3632
  restOptions: rest
2858
3633
  };
2859
3634
  }
2860
3635
  buildSearchRequestBody(query, options) {
2861
- const requestOptions = { ...options ?? {} };
2862
- delete requestOptions.stream;
2863
- delete requestOptions.betas;
3636
+ const body = { ...omitRequestOptions(options) };
3637
+ delete body.betas;
3638
+ delete body.stream;
2864
3639
  if (options === void 0 || !("contents" in options)) {
2865
- return {
2866
- query,
2867
- ...requestOptions,
2868
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
2869
- };
2870
- }
2871
- if (options.contents === false || options.contents === null || options.contents === void 0) {
2872
- delete requestOptions.contents;
2873
- return { query, ...requestOptions };
3640
+ body.contents = { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } };
3641
+ } else if (options.contents === false || options.contents === null || options.contents === void 0) {
3642
+ delete body.contents;
3643
+ } else {
3644
+ body.contents = withJsonSummarySchema(options.contents);
2874
3645
  }
2875
- return { query, ...requestOptions };
3646
+ return { query, ...body };
2876
3647
  }
2877
3648
  /**
2878
3649
  * Makes a request to the Exa API.
@@ -2880,10 +3651,16 @@ var Exa2 = class {
2880
3651
  * @param {string} method - The HTTP method to use.
2881
3652
  * @param {any} [body] - The request body for POST requests.
2882
3653
  * @param {Record<string, any>} [params] - The query parameters.
3654
+ * @param {Record<string, string>} [headers] - Additional request headers.
3655
+ * @param {RequestOptions} [requestOptions] - Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`).
2883
3656
  * @returns {Promise<any>} The response from the API.
2884
3657
  * @throws {ExaError} When any API request fails with structured error information
3658
+ * @throws {ExaTimeoutError} When the request exceeds its `timeout`
3659
+ * @throws {ExaAbortError} When the caller's `signal` aborts the request
2885
3660
  */
2886
- async request(endpoint, method, body, params, headers) {
3661
+ async request(endpoint, method, body, params, headers, requestOptions) {
3662
+ body = mergeRequestBody(method, body, requestOptions?.body);
3663
+ params = mergeRequestQuery(params, requestOptions?.query);
2887
3664
  let url = this.baseURL + endpoint;
2888
3665
  if (params && Object.keys(params).length > 0) {
2889
3666
  const searchParams = new URLSearchParams();
@@ -2909,72 +3686,64 @@ var Exa2 = class {
2909
3686
  if (headers) {
2910
3687
  combinedHeaders = { ...combinedHeaders, ...headers };
2911
3688
  }
2912
- const response = await fetchImpl(url, {
2913
- method,
2914
- headers: combinedHeaders,
2915
- body: body ? JSON.stringify(body) : void 0
2916
- });
2917
- if (!response.ok) {
2918
- const { json: json2, text: text2 } = await readResponseBody(response);
2919
- if (!json2 || typeof json2 !== "object") {
2920
- const snippet = truncateResponseBody(text2);
2921
- const message2 = snippet ? `Request failed with status ${response.status}. Response body was not valid JSON: ${snippet}` : `Request failed with status ${response.status}.`;
3689
+ combinedHeaders = mergeRequestHeaders(
3690
+ combinedHeaders,
3691
+ requestOptions?.headers
3692
+ );
3693
+ const { signal, dispose, toRequestError } = resolveRequestSignal(
3694
+ withClientDefaults(this, requestOptions)
3695
+ );
3696
+ try {
3697
+ const response = await fetchImpl(url, {
3698
+ method,
3699
+ headers: combinedHeaders,
3700
+ body: body ? JSON.stringify(body) : void 0,
3701
+ signal
3702
+ });
3703
+ if (!response.ok) {
3704
+ throw await exaErrorFromResponse(response, endpoint);
3705
+ }
3706
+ const contentType = response.headers.get("content-type") || "";
3707
+ if (contentType.includes("text/event-stream")) {
3708
+ return await this.parseSSEStream(response);
3709
+ }
3710
+ const { json, text } = await readResponseBody(response);
3711
+ if (json === void 0 && text) {
2922
3712
  throw new ExaError(
2923
- message2,
3713
+ `Expected a JSON response but received a non-JSON body (status ${response.status}): ${truncateResponseBody(text)}`,
2924
3714
  response.status,
2925
3715
  (/* @__PURE__ */ new Date()).toISOString(),
2926
3716
  endpoint
2927
3717
  );
2928
3718
  }
2929
- const errorData = json2;
2930
- if (!errorData.statusCode) {
2931
- errorData.statusCode = response.status;
2932
- }
2933
- if (!errorData.timestamp) {
2934
- errorData.timestamp = (/* @__PURE__ */ new Date()).toISOString();
2935
- }
2936
- if (!errorData.path) {
2937
- errorData.path = endpoint;
2938
- }
2939
- const envelope = typeof errorData.error === "object" && errorData.error !== null ? errorData.error : void 0;
2940
- let message;
2941
- if (envelope) {
2942
- message = envelope.message || errorData.message || "Unknown error";
2943
- } else {
2944
- message = errorData.error || "Unknown error";
2945
- if (errorData.message) {
2946
- message += (message.length > 0 ? ". " : "") + errorData.message;
2947
- }
2948
- }
2949
- throw new ExaError(
2950
- message,
2951
- response.status,
2952
- errorData.timestamp,
2953
- errorData.path,
2954
- envelope ? {
2955
- type: envelope.type,
2956
- code: envelope.code,
2957
- detail: envelope.detail,
2958
- requestId: errorData.requestId ?? envelope.requestId
2959
- } : errorData.requestId ? { requestId: errorData.requestId } : void 0
2960
- );
2961
- }
2962
- const contentType = response.headers.get("content-type") || "";
2963
- if (contentType.includes("text/event-stream")) {
2964
- return await this.parseSSEStream(response);
2965
- }
2966
- const { json, text } = await readResponseBody(response);
2967
- if (json === void 0 && text) {
2968
- throw new ExaError(
2969
- `Expected a JSON response but received a non-JSON body (status ${response.status}): ${truncateResponseBody(text)}`,
2970
- response.status,
2971
- (/* @__PURE__ */ new Date()).toISOString(),
2972
- endpoint
3719
+ this.reportWarnings(
3720
+ endpoint,
3721
+ method,
3722
+ json,
3723
+ response.headers.get("x-request-id")
2973
3724
  );
3725
+ return json;
3726
+ } catch (error) {
3727
+ throw toRequestError(error, endpoint);
3728
+ } finally {
3729
+ dispose();
2974
3730
  }
2975
- return json;
2976
3731
  }
2977
- async rawRequest(endpoint, method = "POST", body, queryParams, headers) {
3732
+ /**
3733
+ * Makes a request to the Exa API and returns the raw `Response`.
3734
+ *
3735
+ * `timeout` keeps running until the response body is consumed or cancelled,
3736
+ * and a body read it or the `signal` interrupts rejects with the platform's
3737
+ * own error. The SDK's streaming methods instead stop the timeout once the
3738
+ * response headers arrive. `body`, `headers` and `query` in
3739
+ * `requestOptions` are added to the request as they are in `request`.
3740
+ *
3741
+ * @throws {ExaTimeoutError} When no response arrives within `timeout`
3742
+ * @throws {ExaAbortError} When the caller's `signal` aborts before a response arrives
3743
+ */
3744
+ async rawRequest(endpoint, method = "POST", body, queryParams, headers, requestOptions) {
3745
+ body = mergeRequestBody(method, body, requestOptions?.body);
3746
+ queryParams = mergeRequestQuery(queryParams, requestOptions?.query);
2978
3747
  let url = this.baseURL + endpoint;
2979
3748
  if (queryParams) {
2980
3749
  const searchParams = new URLSearchParams();
@@ -3000,14 +3769,68 @@ var Exa2 = class {
3000
3769
  if (headers) {
3001
3770
  combinedHeaders = { ...combinedHeaders, ...headers };
3002
3771
  }
3003
- const response = await fetchImpl(url, {
3004
- method,
3005
- headers: combinedHeaders,
3006
- body: body ? JSON.stringify(body) : void 0
3007
- });
3008
- return response;
3772
+ combinedHeaders = mergeRequestHeaders(
3773
+ combinedHeaders,
3774
+ requestOptions?.headers
3775
+ );
3776
+ const { signal, dispose, needsDispose, stopTimeout, toRequestError } = resolveRequestSignal(withClientDefaults(this, requestOptions));
3777
+ try {
3778
+ const response = await fetchImpl(url, {
3779
+ method,
3780
+ headers: combinedHeaders,
3781
+ body: body ? JSON.stringify(body) : void 0,
3782
+ signal
3783
+ });
3784
+ if (isStreamRequestOptions(requestOptions)) {
3785
+ const mapError = (error) => toRequestError(error, endpoint);
3786
+ if (!response.ok) {
3787
+ return withDisposeOnBodySettled(response, dispose, mapError);
3788
+ }
3789
+ stopTimeout();
3790
+ if (!requestOptions?.signal) {
3791
+ dispose();
3792
+ return response;
3793
+ }
3794
+ return withDisposeOnBodySettled(response, dispose, mapError);
3795
+ }
3796
+ if (!needsDispose) {
3797
+ return response;
3798
+ }
3799
+ return withDisposeOnBodySettled(response, dispose);
3800
+ } catch (error) {
3801
+ dispose();
3802
+ throw toRequestError(error, endpoint);
3803
+ }
3804
+ }
3805
+ requestWithOptions(endpoint, method, body, requestOptions) {
3806
+ const transport = mergeRequestOptions(requestOptions);
3807
+ if (transport) {
3808
+ return this.request(
3809
+ endpoint,
3810
+ method,
3811
+ body,
3812
+ void 0,
3813
+ void 0,
3814
+ transport
3815
+ );
3816
+ }
3817
+ return this.request(endpoint, method, body);
3818
+ }
3819
+ streamRequestWithOptions(endpoint, method, body, requestOptions) {
3820
+ const transport = streamRequestOptions(this, requestOptions);
3821
+ if (transport) {
3822
+ return this.rawRequest(
3823
+ endpoint,
3824
+ method,
3825
+ body,
3826
+ void 0,
3827
+ void 0,
3828
+ transport
3829
+ );
3830
+ }
3831
+ return this.rawRequest(endpoint, method, body);
3009
3832
  }
3010
- async search(query, options) {
3833
+ async search(query, options, requestOptions) {
3011
3834
  if (options?.stream) {
3012
3835
  throw new ExaError(
3013
3836
  "For streaming responses, please use streamSearch() instead:\n\nfor await (const chunk of exa.streamSearch(query)) {\n // Handle chunks\n}",
@@ -3016,23 +3839,42 @@ var Exa2 = class {
3016
3839
  }
3017
3840
  const body = this.buildSearchRequestBody(query, options);
3018
3841
  const betaHeaders = headersForBetas(options?.betas);
3842
+ const transport = mergeRequestOptions(
3843
+ pickRequestOptions(options),
3844
+ requestOptions
3845
+ );
3846
+ if (transport) {
3847
+ return await this.request(
3848
+ "/search",
3849
+ "POST",
3850
+ body,
3851
+ void 0,
3852
+ betaHeaders,
3853
+ transport
3854
+ );
3855
+ }
3019
3856
  return betaHeaders ? await this.request("/search", "POST", body, void 0, betaHeaders) : await this.request("/search", "POST", body);
3020
3857
  }
3021
3858
  /**
3022
3859
  * Stream a search response as an async generator of OpenAI-style chat completion chunks.
3023
3860
  *
3024
3861
  * Each iteration yields a chunk with partial text (`content`) or new citations.
3862
+ * When the API returns `warnings` about the request, one chunk after the text
3863
+ * carries them.
3025
3864
  * Use this if you'd like to read synthesized search output incrementally.
3865
+ * The `lite` search type does not support streaming.
3866
+ * @param {RequestOptions} [requestOptions] - Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`).
3026
3867
  */
3027
- streamSearch(query, options) {
3028
- return this.streamChatCompletions("/search", {
3029
- ...this.buildSearchRequestBody(query, options),
3030
- stream: true
3031
- });
3868
+ streamSearch(query, options, requestOptions) {
3869
+ return this.streamChatCompletions(
3870
+ "/search",
3871
+ { ...this.buildSearchRequestBody(query, options), stream: true },
3872
+ mergeRequestOptions(pickRequestOptions(options), requestOptions)
3873
+ );
3032
3874
  }
3033
3875
  /**
3034
- * DEPRECATED: Use `search()` instead. This legacy wrapper will be removed in a future version.
3035
- * @deprecated Use `search()` instead. The search method now returns text contents by default.
3876
+ * @deprecated Use `search()`, which returns text contents by default. Pass
3877
+ * content options inside `contents`.
3036
3878
  *
3037
3879
  * Migration examples:
3038
3880
  * - `searchAndContents(query)` → `search(query)`
@@ -3043,41 +3885,72 @@ var Exa2 = class {
3043
3885
  *
3044
3886
  * @param {string} query - The query string.
3045
3887
  * @param {RegularSearchOptions & T} [options] - Additional search + contents options
3888
+ * @param {RequestOptions} [requestOptions] - Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`).
3046
3889
  * @returns {Promise<SearchResponse<T>>} A list of relevant search results with requested contents.
3047
3890
  */
3048
- async searchAndContents(query, options) {
3891
+ async searchAndContents(query, options, requestOptions) {
3049
3892
  const { contentsOptions, restOptions } = options === void 0 ? {
3050
3893
  contentsOptions: {
3051
3894
  text: { maxCharacters: DEFAULT_MAX_CHARACTERS }
3052
3895
  },
3053
3896
  restOptions: {}
3054
3897
  } : this.extractContentsOptions(options);
3055
- return await this.request("/search", "POST", {
3898
+ const body = {
3056
3899
  query,
3057
3900
  contents: contentsOptions,
3058
- ...restOptions
3059
- });
3901
+ ...omitRequestOptions(restOptions)
3902
+ };
3903
+ delete body.stream;
3904
+ return await this.requestWithOptions(
3905
+ "/search",
3906
+ "POST",
3907
+ body,
3908
+ mergeRequestOptions(pickRequestOptions(options), requestOptions)
3909
+ );
3060
3910
  }
3061
- async findSimilar(url, options) {
3911
+ async findSimilar(url, options, requestOptions) {
3912
+ const transport = mergeRequestOptions(
3913
+ pickRequestOptions(options),
3914
+ requestOptions
3915
+ );
3916
+ const bodyOptions = omitRequestOptions(options);
3062
3917
  if (options === void 0 || !("contents" in options)) {
3063
- return await this.request("/findSimilar", "POST", {
3064
- url,
3065
- ...options,
3066
- contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
3067
- });
3918
+ return await this.requestWithOptions(
3919
+ "/findSimilar",
3920
+ "POST",
3921
+ {
3922
+ url,
3923
+ ...bodyOptions,
3924
+ contents: { text: { maxCharacters: DEFAULT_MAX_CHARACTERS } }
3925
+ },
3926
+ transport
3927
+ );
3068
3928
  }
3069
3929
  if (options.contents === false || options.contents === null || options.contents === void 0) {
3070
- const { contents, ...restOptions } = options;
3071
- return await this.request("/findSimilar", "POST", {
3072
- url,
3073
- ...restOptions
3074
- });
3930
+ const { contents: _contents, ...restOptions } = bodyOptions ?? {};
3931
+ return await this.requestWithOptions(
3932
+ "/findSimilar",
3933
+ "POST",
3934
+ {
3935
+ url,
3936
+ ...restOptions
3937
+ },
3938
+ transport
3939
+ );
3075
3940
  }
3076
- return await this.request("/findSimilar", "POST", { url, ...options });
3941
+ return await this.requestWithOptions(
3942
+ "/findSimilar",
3943
+ "POST",
3944
+ {
3945
+ url,
3946
+ ...bodyOptions,
3947
+ contents: withJsonSummarySchema(options.contents)
3948
+ },
3949
+ transport
3950
+ );
3077
3951
  }
3078
3952
  /**
3079
- * DEPRECATED: Use `search()` for new discovery flows instead. This legacy wrapper will be removed in a future version.
3080
- * @deprecated Use `search()` for new discovery flows instead. There is no direct replacement for URL-based similarity.
3953
+ * @deprecated Use `search()` instead. There is no direct replacement for URL-based similarity.
3081
3954
  *
3082
3955
  * Migration examples:
3083
3956
  * - `findSimilarAndContents(url)` → `search(query)`
@@ -3089,26 +3962,28 @@ var Exa2 = class {
3089
3962
  * @param {FindSimilarOptions & T} [options] - Additional options for finding similar links + contents.
3090
3963
  * @returns {Promise<SearchResponse<T>>} A list of similar search results, including requested contents.
3091
3964
  */
3092
- async findSimilarAndContents(url, options) {
3965
+ async findSimilarAndContents(url, options, requestOptions) {
3093
3966
  const { contentsOptions, restOptions } = options === void 0 ? {
3094
3967
  contentsOptions: {
3095
3968
  text: { maxCharacters: DEFAULT_MAX_CHARACTERS }
3096
3969
  },
3097
3970
  restOptions: {}
3098
3971
  } : this.extractContentsOptions(options);
3099
- return await this.request("/findSimilar", "POST", {
3100
- url,
3101
- contents: contentsOptions,
3102
- ...restOptions
3103
- });
3972
+ return await this.requestWithOptions(
3973
+ "/findSimilar",
3974
+ "POST",
3975
+ { url, contents: contentsOptions, ...omitRequestOptions(restOptions) },
3976
+ mergeRequestOptions(pickRequestOptions(options), requestOptions)
3977
+ );
3104
3978
  }
3105
3979
  /**
3106
3980
  * Retrieves contents of documents based on URLs.
3107
3981
  * @param {string | string[] | SearchResult[]} urls - A URL or array of URLs, or an array of SearchResult objects.
3108
- * @param {ContentsOptions} [options] - Additional options for retrieving document contents.
3982
+ * @param {ContentsOptions & BetaOptions & UserIdentifierOptions & TransportRequestOptions} [options] - Additional options for retrieving document contents.
3983
+ * @param {RequestOptions} [requestOptions] - Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`).
3109
3984
  * @returns {Promise<SearchResponse<T>>} A list of document contents for the requested URLs.
3110
3985
  */
3111
- async getContents(urls, options) {
3986
+ async getContents(urls, options, requestOptions) {
3112
3987
  if (!urls || Array.isArray(urls) && urls.length === 0) {
3113
3988
  throw new ExaError(
3114
3989
  "Must provide at least one URL",
@@ -3126,12 +4001,26 @@ var Exa2 = class {
3126
4001
  const { betas, ...contentsOptions } = options ?? {};
3127
4002
  const payload = {
3128
4003
  urls: requestUrls,
3129
- ...contentsOptions
4004
+ ...withJsonSummarySchema(omitRequestOptions(contentsOptions))
3130
4005
  };
3131
4006
  const betaHeaders = headersForBetas(betas);
4007
+ const transport = mergeRequestOptions(
4008
+ pickRequestOptions(options),
4009
+ requestOptions
4010
+ );
4011
+ if (transport) {
4012
+ return await this.request(
4013
+ "/contents",
4014
+ "POST",
4015
+ payload,
4016
+ void 0,
4017
+ betaHeaders,
4018
+ transport
4019
+ );
4020
+ }
3132
4021
  return betaHeaders ? await this.request("/contents", "POST", payload, void 0, betaHeaders) : await this.request("/contents", "POST", payload);
3133
4022
  }
3134
- async answer(query, options) {
4023
+ async answer(query, options, requestOptions) {
3135
4024
  if (options?.stream) {
3136
4025
  throw new ExaError(
3137
4026
  "For streaming responses, please use streamAnswer() instead:\n\nfor await (const chunk of exa.streamAnswer(query)) {\n // Handle chunks\n}",
@@ -3149,11 +4038,17 @@ var Exa2 = class {
3149
4038
  model: options?.model ?? "exa",
3150
4039
  systemPrompt: options?.systemPrompt,
3151
4040
  outputSchema,
3152
- userLocation: options?.userLocation
4041
+ userLocation: options?.userLocation,
4042
+ userIdentifier: options?.userIdentifier
3153
4043
  };
3154
- return await this.request("/answer", "POST", requestBody);
4044
+ return await this.requestWithOptions(
4045
+ "/answer",
4046
+ "POST",
4047
+ requestBody,
4048
+ mergeRequestOptions(pickRequestOptions(options), requestOptions)
4049
+ );
3155
4050
  }
3156
- async *streamAnswer(query, options) {
4051
+ async *streamAnswer(query, options, requestOptions) {
3157
4052
  let outputSchema = options?.outputSchema;
3158
4053
  if (outputSchema && isZodSchema(outputSchema)) {
3159
4054
  outputSchema = zodToJsonSchema(outputSchema);
@@ -3165,16 +4060,26 @@ var Exa2 = class {
3165
4060
  model: options?.model ?? "exa",
3166
4061
  systemPrompt: options?.systemPrompt,
3167
4062
  outputSchema,
3168
- userLocation: options?.userLocation
4063
+ userLocation: options?.userLocation,
4064
+ userIdentifier: options?.userIdentifier
3169
4065
  };
3170
- yield* this.streamChatCompletions("/answer", body);
4066
+ yield* this.streamChatCompletions(
4067
+ "/answer",
4068
+ body,
4069
+ mergeRequestOptions(pickRequestOptions(options), requestOptions)
4070
+ );
3171
4071
  }
3172
- async *streamChatCompletions(endpoint, body) {
3173
- const response = await this.rawRequest(endpoint, "POST", body);
4072
+ async *streamChatCompletions(endpoint, body, requestOptions) {
4073
+ const response = await this.streamRequestWithOptions(
4074
+ endpoint,
4075
+ "POST",
4076
+ body,
4077
+ requestOptions
4078
+ );
3174
4079
  if (!response.ok) {
3175
- const message = await response.text();
3176
- throw new ExaError(message, response.status, (/* @__PURE__ */ new Date()).toISOString());
4080
+ throw await exaErrorFromResponse(response, endpoint);
3177
4081
  }
4082
+ const requestIdHeader = response.headers.get("x-request-id");
3178
4083
  const reader = response.body?.getReader();
3179
4084
  if (!reader) {
3180
4085
  throw new ExaError(
@@ -3205,7 +4110,8 @@ var Exa2 = class {
3205
4110
  continue;
3206
4111
  }
3207
4112
  const chunk = this.processChunk(chunkData);
3208
- if (chunk.content || chunk.citations) {
4113
+ this.reportWarnings(endpoint, "POST", chunkData, requestIdHeader);
4114
+ if (chunk.content || chunk.citations || chunk.warnings) {
3209
4115
  yield chunk;
3210
4116
  }
3211
4117
  }
@@ -3216,7 +4122,8 @@ var Exa2 = class {
3216
4122
  try {
3217
4123
  const chunkData = JSON.parse(leftover);
3218
4124
  const chunk = this.processChunk(chunkData);
3219
- if (chunk.content || chunk.citations) {
4125
+ this.reportWarnings(endpoint, "POST", chunkData, requestIdHeader);
4126
+ if (chunk.content || chunk.citations || chunk.warnings) {
3220
4127
  yield chunk;
3221
4128
  }
3222
4129
  } catch (e) {
@@ -3224,9 +4131,17 @@ var Exa2 = class {
3224
4131
  }
3225
4132
  }
3226
4133
  } finally {
3227
- reader.releaseLock();
4134
+ try {
4135
+ await reader.cancel();
4136
+ } catch {
4137
+ }
3228
4138
  }
3229
4139
  }
4140
+ /**
4141
+ * Parses one stream payload into a chunk. `warnings` is set only when the
4142
+ * payload carries a non-empty `warnings` array, which `/search` sends on its
4143
+ * `results` event.
4144
+ */
3230
4145
  processChunk(chunkData) {
3231
4146
  let content;
3232
4147
  let citations;
@@ -3243,6 +4158,10 @@ var Exa2 = class {
3243
4158
  text: c.text
3244
4159
  }));
3245
4160
  }
4161
+ if (Array.isArray(chunkData.warnings) && chunkData.warnings.length > 0) {
4162
+ const warnings = chunkData.warnings;
4163
+ return { content, citations, warnings };
4164
+ }
3246
4165
  return { content, citations };
3247
4166
  }
3248
4167
  async parseSSEStream(response) {
@@ -3256,65 +4175,45 @@ var Exa2 = class {
3256
4175
  }
3257
4176
  const decoder = new TextDecoder();
3258
4177
  let buffer = "";
3259
- return new Promise(async (resolve, reject) => {
3260
- try {
3261
- while (true) {
3262
- const { done, value } = await reader.read();
3263
- if (done) break;
3264
- buffer += decoder.decode(value, { stream: true });
3265
- const lines = buffer.split("\n");
3266
- buffer = lines.pop() || "";
3267
- for (const line of lines) {
3268
- if (!line.startsWith("data: ")) continue;
3269
- const jsonStr = line.replace(/^data:\s*/, "").trim();
3270
- if (!jsonStr || jsonStr === "[DONE]") {
3271
- continue;
3272
- }
3273
- let chunk;
3274
- try {
3275
- chunk = JSON.parse(jsonStr);
3276
- } catch {
3277
- continue;
3278
- }
3279
- switch (chunk.tag) {
3280
- case "complete":
3281
- reader.releaseLock();
3282
- resolve(chunk.data);
3283
- return;
3284
- case "error": {
3285
- const message = chunk.error?.message || "Unknown error";
3286
- reader.releaseLock();
3287
- reject(
3288
- new ExaError(
3289
- message,
3290
- 500 /* InternalServerError */,
3291
- (/* @__PURE__ */ new Date()).toISOString()
3292
- )
3293
- );
3294
- return;
3295
- }
3296
- // 'progress' and any other tags are ignored for the blocking variant
3297
- default:
3298
- break;
3299
- }
4178
+ try {
4179
+ while (true) {
4180
+ const { done, value } = await reader.read();
4181
+ if (done) break;
4182
+ buffer += decoder.decode(value, { stream: true });
4183
+ const lines = buffer.split("\n");
4184
+ buffer = lines.pop() || "";
4185
+ for (const line of lines) {
4186
+ if (!line.startsWith("data: ")) continue;
4187
+ const jsonStr = line.replace(/^data:\s*/, "").trim();
4188
+ if (!jsonStr || jsonStr === "[DONE]") continue;
4189
+ let chunk;
4190
+ try {
4191
+ chunk = JSON.parse(jsonStr);
4192
+ } catch {
4193
+ continue;
4194
+ }
4195
+ if (chunk.tag === "complete") return chunk.data;
4196
+ if (chunk.tag === "error") {
4197
+ throw new ExaError(
4198
+ chunk.error?.message || "Unknown error",
4199
+ 500 /* InternalServerError */,
4200
+ (/* @__PURE__ */ new Date()).toISOString()
4201
+ );
3300
4202
  }
3301
- }
3302
- reject(
3303
- new ExaError(
3304
- "Stream ended without a completion event.",
3305
- 500 /* InternalServerError */,
3306
- (/* @__PURE__ */ new Date()).toISOString()
3307
- )
3308
- );
3309
- } catch (err) {
3310
- reject(err);
3311
- } finally {
3312
- try {
3313
- reader.releaseLock();
3314
- } catch {
3315
4203
  }
3316
4204
  }
3317
- });
4205
+ throw new ExaError(
4206
+ "Stream ended without a completion event.",
4207
+ 500 /* InternalServerError */,
4208
+ (/* @__PURE__ */ new Date()).toISOString()
4209
+ );
4210
+ } finally {
4211
+ try {
4212
+ await reader.cancel();
4213
+ } catch {
4214
+ }
4215
+ reader.releaseLock();
4216
+ }
3318
4217
  }
3319
4218
  };
3320
4219
  var index_default = Exa2;
@@ -3343,7 +4242,9 @@ export {
3343
4242
  EventType,
3344
4243
  EventsClient,
3345
4244
  Exa2 as Exa,
4245
+ ExaAbortError,
3346
4246
  ExaError,
4247
+ ExaTimeoutError,
3347
4248
  HttpStatusCode,
3348
4249
  ImportFailedReason,
3349
4250
  ImportFormat,