exa-js 2.27.0 → 2.29.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.27.0",
7
+ version: "2.29.0",
8
8
  description: "Exa SDK for Node.js and the browser",
9
9
  publishConfig: {
10
10
  access: "public"
@@ -42,7 +42,6 @@ var package_default = {
42
42
  "generate:types:websets": "openapi-typescript https://raw.githubusercontent.com/exa-labs/openapi-spec/refs/heads/master/exa-websets-spec.yaml --enum --root-types --alphabetize --root-types-no-schema-prefix --output ./src/websets/openapi.ts && npm run format:websets",
43
43
  format: 'prettier --write "src/**/*.ts"',
44
44
  "format:websets": "prettier --write src/websets/openapi.ts",
45
- "generate-docs": "npx tsx scripts/generate-docs.ts",
46
45
  "build:beta": "cross-env NPM_CONFIG_TAG=beta npm run build",
47
46
  "version:beta": "npm version prerelease --preid=beta",
48
47
  "version:stable": "npm version patch",
@@ -53,23 +52,19 @@ var package_default = {
53
52
  license: "MIT",
54
53
  devDependencies: {
55
54
  "@anthropic-ai/sdk": "^0.115.0",
56
- "@types/node": "~22.14.0",
55
+ "@types/node": "~22.14.1",
57
56
  "cross-env": "~7.0.3",
57
+ openai: "^6.49.0",
58
58
  "openapi-typescript": "~7.6.1",
59
59
  prettier: "~3.5.3",
60
- "ts-morph": "^27.0.2",
61
- "ts-node": "~10.9.2",
62
60
  tsup: "~8.4.0",
63
- tsx: "^4.21.0",
64
61
  typescript: "~5.8.3",
65
- vitest: "~3.1.1"
62
+ vitest: "~4.1.12"
66
63
  },
67
64
  dependencies: {
68
65
  "cross-fetch": "~4.1.0",
69
- dotenv: "~16.4.7",
70
- openai: "^5.0.1",
71
- zod: "^3.22.0",
72
- "zod-to-json-schema": "^3.20.0"
66
+ zod: "^3.25.28 || ^4.6.6",
67
+ "zod-to-json-schema": "^3.25.2"
73
68
  },
74
69
  directories: {
75
70
  test: "test"
@@ -128,6 +123,7 @@ var ExaError = class extends Error {
128
123
  this.code = envelope.code;
129
124
  this.detail = envelope.detail;
130
125
  this.requestId = envelope.requestId;
126
+ this.tag = envelope.tag;
131
127
  }
132
128
  }
133
129
  };
@@ -227,6 +223,7 @@ async function exaErrorFromResponse(response, path) {
227
223
  message += (message.length > 0 ? ". " : "") + errorData.message;
228
224
  }
229
225
  }
226
+ const tag = typeof errorData.tag === "string" ? errorData.tag : void 0;
230
227
  return new ExaError(
231
228
  message,
232
229
  response.status,
@@ -236,13 +233,14 @@ async function exaErrorFromResponse(response, path) {
236
233
  type: envelope.type,
237
234
  code: envelope.code,
238
235
  detail: envelope.detail,
239
- requestId: errorData.requestId ?? envelope.requestId
240
- } : errorData.requestId ? { requestId: errorData.requestId } : void 0
236
+ requestId: errorData.requestId ?? envelope.requestId,
237
+ tag
238
+ } : errorData.requestId || tag ? { requestId: errorData.requestId, tag } : void 0
241
239
  );
242
240
  }
243
241
 
244
242
  // src/zod-utils.ts
245
- import { ZodType } from "zod";
243
+ import { ZodType } from "zod/v3";
246
244
  import { zodToJsonSchema as convertZodToJsonSchema } from "zod-to-json-schema";
247
245
  function isZodSchema(obj) {
248
246
  return obj instanceof ZodType;
@@ -359,6 +357,12 @@ function mergeRequestHeaders(headers, extraHeaders) {
359
357
  }
360
358
  return merged;
361
359
  }
360
+ function setsHeader(headers, name) {
361
+ const lowerCaseName = name.toLowerCase();
362
+ return Object.entries(headers ?? {}).some(
363
+ ([key, value]) => key.toLowerCase() === lowerCaseName && value !== void 0
364
+ );
365
+ }
362
366
  var CLIENT_DEFAULTS = /* @__PURE__ */ new WeakMap();
363
367
  function setClientDefaults(client, defaults) {
364
368
  if (defaults === void 0) {
@@ -613,6 +617,26 @@ function sleep(ms, signal) {
613
617
  }, ms);
614
618
  });
615
619
  }
620
+ function untilAborted(promise, signal) {
621
+ return new Promise((resolve, reject) => {
622
+ const onAbort = () => reject(signal.reason);
623
+ if (signal.aborted) {
624
+ onAbort();
625
+ } else {
626
+ signal.addEventListener("abort", onAbort, { once: true });
627
+ }
628
+ promise.then(
629
+ (value) => {
630
+ signal.removeEventListener("abort", onAbort);
631
+ resolve(value);
632
+ },
633
+ (error) => {
634
+ signal.removeEventListener("abort", onAbort);
635
+ reject(error);
636
+ }
637
+ );
638
+ });
639
+ }
616
640
  var RequestScopedClient = class {
617
641
  /**
618
642
  * Returns a view of this client that sends `requestOptions` with every
@@ -646,7 +670,35 @@ var RequestScopedClient = class {
646
670
  view.requestOptions = { ...this.requestOptions, query: remaining };
647
671
  return view;
648
672
  }
673
+ /**
674
+ * Yields every item of a cursor-paginated listing. `fetchPage` fetches the
675
+ * page at `cursor` with the view it is given: this one for the first page,
676
+ * `forNextPage()` for the rest. Stops after a page without `hasMore` or
677
+ * without a `nextCursor`.
678
+ */
679
+ async *paginate(firstCursor, fetchPage) {
680
+ let view = this;
681
+ let cursor = firstCursor;
682
+ while (true) {
683
+ const page = await fetchPage(view, cursor);
684
+ for (const item of page.data) {
685
+ yield item;
686
+ }
687
+ if (!page.hasMore || !page.nextCursor) {
688
+ return;
689
+ }
690
+ cursor = page.nextCursor;
691
+ view = view.forNextPage();
692
+ }
693
+ }
649
694
  };
695
+ async function collectAll(items) {
696
+ const all = [];
697
+ for await (const item of items) {
698
+ all.push(item);
699
+ }
700
+ return all;
701
+ }
650
702
 
651
703
  // src/agent/base.ts
652
704
  var AgentBaseClient = class extends RequestScopedClient {
@@ -809,33 +861,19 @@ var AgentMonitorEntitiesClient = class extends AgentMonitorsBaseClient {
809
861
  * automatically.
810
862
  */
811
863
  async *listAll(monitorId, options, requestOptions) {
812
- let scoped = this.withRequestOptions(requestOptions);
813
- let cursor = options.cursor;
814
864
  const { betas, ...pagination } = options;
815
- const pageOptions = { ...pagination };
816
- while (true) {
817
- pageOptions.cursor = cursor;
818
- const response = await scoped.list(monitorId, { ...pageOptions, betas });
819
- for (const entityView of response.data) {
820
- yield entityView;
821
- }
822
- if (!response.hasMore || !response.nextCursor) {
823
- break;
824
- }
825
- cursor = response.nextCursor;
826
- scoped = scoped.forNextPage();
827
- }
865
+ yield* this.withRequestOptions(requestOptions).paginate(
866
+ options.cursor,
867
+ (view, cursor) => view.list(monitorId, { ...pagination, cursor, betas })
868
+ );
828
869
  }
829
870
  /**
830
871
  * Collect all of a monitor's entities into an array.
831
872
  */
832
873
  async getAll(monitorId, options, requestOptions) {
833
- const scoped = this.withRequestOptions(requestOptions);
834
- const entities = [];
835
- for await (const entityView of scoped.listAll(monitorId, options)) {
836
- entities.push(entityView);
837
- }
838
- return entities;
874
+ return collectAll(
875
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
876
+ );
839
877
  }
840
878
  };
841
879
  var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
@@ -859,33 +897,19 @@ var AgentMonitorChangesClient = class extends AgentMonitorsBaseClient {
859
897
  * automatically.
860
898
  */
861
899
  async *listAll(monitorId, options, requestOptions) {
862
- let scoped = this.withRequestOptions(requestOptions);
863
- let cursor = options.cursor;
864
900
  const { betas, ...pagination } = options;
865
- const pageOptions = { ...pagination };
866
- while (true) {
867
- pageOptions.cursor = cursor;
868
- const response = await scoped.list(monitorId, { ...pageOptions, betas });
869
- for (const change of response.data) {
870
- yield change;
871
- }
872
- if (!response.hasMore || !response.nextCursor) {
873
- break;
874
- }
875
- cursor = response.nextCursor;
876
- scoped = scoped.forNextPage();
877
- }
901
+ yield* this.withRequestOptions(requestOptions).paginate(
902
+ options.cursor,
903
+ (view, cursor) => view.list(monitorId, { ...pagination, cursor, betas })
904
+ );
878
905
  }
879
906
  /**
880
907
  * Collect a monitor's change feed into an array.
881
908
  */
882
909
  async getAll(monitorId, options, requestOptions) {
883
- const scoped = this.withRequestOptions(requestOptions);
884
- const changes = [];
885
- for await (const change of scoped.listAll(monitorId, options)) {
886
- changes.push(change);
887
- }
888
- return changes;
910
+ return collectAll(
911
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
912
+ );
889
913
  }
890
914
  };
891
915
  var AgentMonitorBacktestsClient = class extends AgentMonitorsBaseClient {
@@ -1005,33 +1029,19 @@ var AgentMonitorsClient = class extends AgentMonitorsBaseClient {
1005
1029
  * Iterate through all Agent Monitors, handling pagination automatically.
1006
1030
  */
1007
1031
  async *listAll(options, requestOptions) {
1008
- let scoped = this.withRequestOptions(requestOptions);
1009
- let cursor = options.cursor;
1010
1032
  const { betas, ...pagination } = options;
1011
- const pageOptions = { ...pagination };
1012
- while (true) {
1013
- pageOptions.cursor = cursor;
1014
- const response = await scoped.list({ ...pageOptions, betas });
1015
- for (const monitor of response.data) {
1016
- yield monitor;
1017
- }
1018
- if (!response.hasMore || !response.nextCursor) {
1019
- break;
1020
- }
1021
- cursor = response.nextCursor;
1022
- scoped = scoped.forNextPage();
1023
- }
1033
+ yield* this.withRequestOptions(requestOptions).paginate(
1034
+ options.cursor,
1035
+ (view, cursor) => view.list({ ...pagination, cursor, betas })
1036
+ );
1024
1037
  }
1025
1038
  /**
1026
1039
  * Collect all Agent Monitors into an array.
1027
1040
  */
1028
1041
  async getAll(options, requestOptions) {
1029
- const scoped = this.withRequestOptions(requestOptions);
1030
- const monitors = [];
1031
- for await (const monitor of scoped.listAll(options)) {
1032
- monitors.push(monitor);
1033
- }
1034
- return monitors;
1042
+ return collectAll(
1043
+ this.withRequestOptions(requestOptions).listAll(options)
1044
+ );
1035
1045
  }
1036
1046
  /**
1037
1047
  * Delete an Agent Monitor and stop its refreshes.
@@ -1209,32 +1219,18 @@ var AgentRunsClient = class extends AgentBaseClient {
1209
1219
  * Iterate through all Agent runs, handling pagination automatically.
1210
1220
  */
1211
1221
  async *listAll(options, requestOptions) {
1212
- let scoped = this.withRequestOptions(requestOptions);
1213
- let cursor = void 0;
1214
- const pageOptions = options ? { ...options } : {};
1215
- while (true) {
1216
- pageOptions.cursor = cursor;
1217
- const response = await scoped.list(pageOptions);
1218
- for (const run of response.data) {
1219
- yield run;
1220
- }
1221
- if (!response.hasMore || !response.nextCursor) {
1222
- break;
1223
- }
1224
- cursor = response.nextCursor;
1225
- scoped = scoped.forNextPage();
1226
- }
1222
+ yield* this.withRequestOptions(requestOptions).paginate(
1223
+ options?.cursor,
1224
+ (view, cursor) => view.list({ ...options, cursor })
1225
+ );
1227
1226
  }
1228
1227
  /**
1229
1228
  * Collect all Agent runs into an array.
1230
1229
  */
1231
1230
  async getAll(options, requestOptions) {
1232
- const scoped = this.withRequestOptions(requestOptions);
1233
- const runs = [];
1234
- for await (const run of scoped.listAll(options)) {
1235
- runs.push(run);
1236
- }
1237
- return runs;
1231
+ return collectAll(
1232
+ this.withRequestOptions(requestOptions).listAll(options)
1233
+ );
1238
1234
  }
1239
1235
  /**
1240
1236
  * Cancel a queued or running Agent run.
@@ -1371,30 +1367,16 @@ var AgentBetaRunsClient = class extends AgentRunsClient {
1371
1367
  );
1372
1368
  }
1373
1369
  async *listAll(options, requestOptions) {
1374
- let scoped = this.withRequestOptions(requestOptions);
1375
- let cursor = void 0;
1376
1370
  const { betas, ...pagination } = options ?? {};
1377
- const pageOptions = { ...pagination };
1378
- while (true) {
1379
- pageOptions.cursor = cursor;
1380
- const response = await scoped.list({ ...pageOptions, betas });
1381
- for (const run of response.data) {
1382
- yield run;
1383
- }
1384
- if (!response.hasMore || !response.nextCursor) {
1385
- break;
1386
- }
1387
- cursor = response.nextCursor;
1388
- scoped = scoped.forNextPage();
1389
- }
1371
+ yield* this.withRequestOptions(requestOptions).paginate(
1372
+ pagination?.cursor,
1373
+ (view, cursor) => view.list({ ...pagination, cursor, betas })
1374
+ );
1390
1375
  }
1391
1376
  async getAll(options, requestOptions) {
1392
- const scoped = this.withRequestOptions(requestOptions);
1393
- const runs = [];
1394
- for await (const run of scoped.listAll(options)) {
1395
- runs.push(run);
1396
- }
1397
- return runs;
1377
+ return collectAll(
1378
+ this.withRequestOptions(requestOptions).listAll(options)
1379
+ );
1398
1380
  }
1399
1381
  async cancel(runId, options) {
1400
1382
  const scoped = this.withRequestOptions(options);
@@ -1559,21 +1541,10 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
1559
1541
  * @returns Async generator of Search Monitor runs
1560
1542
  */
1561
1543
  async *listAll(monitorId, options, requestOptions) {
1562
- let scoped = this.withRequestOptions(requestOptions);
1563
- let cursor = void 0;
1564
- const pageOptions = options ? { ...options } : {};
1565
- while (true) {
1566
- pageOptions.cursor = cursor;
1567
- const response = await scoped.list(monitorId, pageOptions);
1568
- for (const run of response.data) {
1569
- yield run;
1570
- }
1571
- if (!response.hasMore || !response.nextCursor) {
1572
- break;
1573
- }
1574
- cursor = response.nextCursor;
1575
- scoped = scoped.forNextPage();
1576
- }
1544
+ yield* this.withRequestOptions(requestOptions).paginate(
1545
+ options?.cursor,
1546
+ (view, cursor) => view.list(monitorId, { ...options, cursor })
1547
+ );
1577
1548
  }
1578
1549
  /**
1579
1550
  * Collect all runs for a Search Monitor into an array
@@ -1583,12 +1554,9 @@ var SearchMonitorRunsClient = class extends SearchMonitorsBaseClient {
1583
1554
  * @returns Promise resolving to an array of all Search Monitor runs
1584
1555
  */
1585
1556
  async getAll(monitorId, options, requestOptions) {
1586
- const scoped = this.withRequestOptions(requestOptions);
1587
- const runs = [];
1588
- for await (const run of scoped.listAll(monitorId, options)) {
1589
- runs.push(run);
1590
- }
1591
- return runs;
1557
+ return collectAll(
1558
+ this.withRequestOptions(requestOptions).listAll(monitorId, options)
1559
+ );
1592
1560
  }
1593
1561
  };
1594
1562
  var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
@@ -1673,21 +1641,10 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1673
1641
  * @returns Async generator of Search Monitors
1674
1642
  */
1675
1643
  async *listAll(options, requestOptions) {
1676
- let scoped = this.withRequestOptions(requestOptions);
1677
- let cursor = void 0;
1678
- const pageOptions = options ? { ...options } : {};
1679
- while (true) {
1680
- pageOptions.cursor = cursor;
1681
- const response = await scoped.list(pageOptions);
1682
- for (const monitor of response.data) {
1683
- yield monitor;
1684
- }
1685
- if (!response.hasMore || !response.nextCursor) {
1686
- break;
1687
- }
1688
- cursor = response.nextCursor;
1689
- scoped = scoped.forNextPage();
1690
- }
1644
+ yield* this.withRequestOptions(requestOptions).paginate(
1645
+ options?.cursor,
1646
+ (view, cursor) => view.list({ ...options, cursor })
1647
+ );
1691
1648
  }
1692
1649
  /**
1693
1650
  * Collect all Search Monitors into an array
@@ -1696,12 +1653,9 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
1696
1653
  * @returns Promise resolving to an array of all Search Monitors
1697
1654
  */
1698
1655
  async getAll(options, requestOptions) {
1699
- const scoped = this.withRequestOptions(requestOptions);
1700
- const monitors = [];
1701
- for await (const monitor of scoped.listAll(options)) {
1702
- monitors.push(monitor);
1703
- }
1704
- return monitors;
1656
+ return collectAll(
1657
+ this.withRequestOptions(requestOptions).listAll(options)
1658
+ );
1705
1659
  }
1706
1660
  };
1707
1661
 
@@ -1715,21 +1669,6 @@ var ResearchBaseClient = class extends RequestScopedClient {
1715
1669
  super();
1716
1670
  this.client = client;
1717
1671
  }
1718
- /** Rejects with `researchRetiredError()`: the Research API has been retired. */
1719
- async request(_endpoint, _method = "POST", _data, _params) {
1720
- throw researchRetiredError();
1721
- }
1722
- /** Rejects with `researchRetiredError()`: the Research API has been retired. */
1723
- async rawRequest(_endpoint, _method = "POST", _data, _params) {
1724
- throw researchRetiredError();
1725
- }
1726
- buildPaginationParams(pagination) {
1727
- const params = {};
1728
- if (!pagination) return params;
1729
- if (pagination.cursor) params.cursor = pagination.cursor;
1730
- if (pagination.limit) params.limit = pagination.limit;
1731
- return params;
1732
- }
1733
1672
  };
1734
1673
 
1735
1674
  // src/research/client.ts
@@ -1737,105 +1676,14 @@ var ResearchClient = class extends ResearchBaseClient {
1737
1676
  constructor(client) {
1738
1677
  super(client);
1739
1678
  }
1740
- async create(params, requestOptions) {
1741
- const scoped = this.withRequestOptions(requestOptions);
1742
- const { instructions, model, outputSchema } = params;
1743
- let schema = outputSchema;
1744
- if (schema && isZodSchema(schema)) {
1745
- schema = zodToJsonSchema(schema);
1746
- }
1747
- const payload = {
1748
- instructions,
1749
- model: model ?? "exa-research-fast"
1750
- };
1751
- if (schema) {
1752
- payload.outputSchema = schema;
1753
- }
1754
- return scoped.request("", "POST", payload);
1679
+ async create(_params, _requestOptions) {
1680
+ throw researchRetiredError();
1755
1681
  }
1756
- get(researchId, options, requestOptions) {
1757
- const scoped = this.withRequestOptions(requestOptions);
1758
- if (options?.stream) {
1759
- const promise = async () => {
1760
- const params = { stream: "true" };
1761
- if (options.events !== void 0) {
1762
- params.events = options.events.toString();
1763
- }
1764
- const resp = await scoped.rawRequest(
1765
- `/${researchId}`,
1766
- "GET",
1767
- void 0,
1768
- params
1769
- );
1770
- if (!resp.ok) {
1771
- throw await exaErrorFromResponse(resp, `/research/v1/${researchId}`);
1772
- }
1773
- if (!resp.body) {
1774
- throw new Error("No response body for SSE stream");
1775
- }
1776
- const reader = resp.body.getReader();
1777
- const decoder = new TextDecoder();
1778
- let buffer = "";
1779
- function processPart(part) {
1780
- const lines = part.split("\n");
1781
- let data = lines.slice(1).join("\n");
1782
- if (data.startsWith("data:")) {
1783
- data = data.slice(5).trimStart();
1784
- }
1785
- try {
1786
- return JSON.parse(data);
1787
- } catch (e) {
1788
- return null;
1789
- }
1790
- }
1791
- async function* streamEvents() {
1792
- try {
1793
- while (true) {
1794
- const { done, value } = await reader.read();
1795
- if (done) break;
1796
- buffer += decoder.decode(value, { stream: true });
1797
- let parts = buffer.split("\n\n");
1798
- buffer = parts.pop() ?? "";
1799
- for (const part of parts) {
1800
- const processed = processPart(part);
1801
- if (processed) {
1802
- yield processed;
1803
- }
1804
- }
1805
- }
1806
- if (buffer.trim()) {
1807
- const processed = processPart(buffer.trim());
1808
- if (processed) {
1809
- yield processed;
1810
- }
1811
- }
1812
- } finally {
1813
- try {
1814
- await reader.cancel();
1815
- } catch {
1816
- }
1817
- }
1818
- }
1819
- return streamEvents();
1820
- };
1821
- return promise();
1822
- } else {
1823
- const params = { stream: "false" };
1824
- if (options?.events !== void 0) {
1825
- params.events = options.events.toString();
1826
- }
1827
- return scoped.request(
1828
- `/${researchId}`,
1829
- "GET",
1830
- void 0,
1831
- params
1832
- );
1833
- }
1682
+ get(_researchId, _options, _requestOptions) {
1683
+ return Promise.reject(researchRetiredError());
1834
1684
  }
1835
- async list(options, requestOptions) {
1836
- const scoped = this.withRequestOptions(requestOptions);
1837
- const params = this.buildPaginationParams(options);
1838
- return scoped.request("", "GET", void 0, params);
1685
+ async list(_options, _requestOptions) {
1686
+ throw researchRetiredError();
1839
1687
  }
1840
1688
  async pollUntilFinished(_researchId, _options, _requestOptions) {
1841
1689
  throw researchRetiredError();
@@ -2017,21 +1865,10 @@ var EventsClient = class extends WebsetsBaseClient {
2017
1865
  * @returns Async generator of Events
2018
1866
  */
2019
1867
  async *listAll(options, requestOptions) {
2020
- let scoped = this.withRequestOptions(requestOptions);
2021
- let cursor = void 0;
2022
- const pageOptions = options ? { ...options } : {};
2023
- while (true) {
2024
- pageOptions.cursor = cursor;
2025
- const response = await scoped.list(pageOptions);
2026
- for (const event of response.data) {
2027
- yield event;
2028
- }
2029
- if (!response.hasMore || !response.nextCursor) {
2030
- break;
2031
- }
2032
- cursor = response.nextCursor;
2033
- scoped = scoped.forNextPage();
2034
- }
1868
+ yield* this.withRequestOptions(requestOptions).paginate(
1869
+ options?.cursor,
1870
+ (view, cursor) => view.list({ ...options, cursor })
1871
+ );
2035
1872
  }
2036
1873
  /**
2037
1874
  * Collect all Events into an array
@@ -2040,12 +1877,9 @@ var EventsClient = class extends WebsetsBaseClient {
2040
1877
  * @returns Promise resolving to an array of all Events
2041
1878
  */
2042
1879
  async getAll(options, requestOptions) {
2043
- const scoped = this.withRequestOptions(requestOptions);
2044
- const events = [];
2045
- for await (const event of scoped.listAll(options)) {
2046
- events.push(event);
2047
- }
2048
- return events;
1880
+ return collectAll(
1881
+ this.withRequestOptions(requestOptions).listAll(options)
1882
+ );
2049
1883
  }
2050
1884
  };
2051
1885
 
@@ -2390,21 +2224,10 @@ var ImportsClient = class extends WebsetsBaseClient {
2390
2224
  * @returns Async generator of Imports
2391
2225
  */
2392
2226
  async *listAll(options, requestOptions) {
2393
- let scoped = this.withRequestOptions(requestOptions);
2394
- let cursor = void 0;
2395
- const pageOptions = options ? { ...options } : {};
2396
- while (true) {
2397
- pageOptions.cursor = cursor;
2398
- const response = await scoped.list(pageOptions);
2399
- for (const importItem of response.data) {
2400
- yield importItem;
2401
- }
2402
- if (!response.hasMore || !response.nextCursor) {
2403
- break;
2404
- }
2405
- cursor = response.nextCursor;
2406
- scoped = scoped.forNextPage();
2407
- }
2227
+ yield* this.withRequestOptions(requestOptions).paginate(
2228
+ options?.cursor,
2229
+ (view, cursor) => view.list({ ...options, cursor })
2230
+ );
2408
2231
  }
2409
2232
  /**
2410
2233
  * Collect all Imports into an array
@@ -2413,12 +2236,9 @@ var ImportsClient = class extends WebsetsBaseClient {
2413
2236
  * @returns Promise resolving to an array of all Imports
2414
2237
  */
2415
2238
  async getAll(options, requestOptions) {
2416
- const scoped = this.withRequestOptions(requestOptions);
2417
- const imports = [];
2418
- for await (const importItem of scoped.listAll(options)) {
2419
- imports.push(importItem);
2420
- }
2421
- return imports;
2239
+ return collectAll(
2240
+ this.withRequestOptions(requestOptions).listAll(options)
2241
+ );
2422
2242
  }
2423
2243
  };
2424
2244
 
@@ -2452,21 +2272,10 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
2452
2272
  * @returns Async generator of Webset Items
2453
2273
  */
2454
2274
  async *listAll(websetId, options, requestOptions) {
2455
- let scoped = this.withRequestOptions(requestOptions);
2456
- let cursor = void 0;
2457
- const pageOptions = options ? { ...options } : {};
2458
- while (true) {
2459
- pageOptions.cursor = cursor;
2460
- const response = await scoped.list(websetId, pageOptions);
2461
- for (const item of response.data) {
2462
- yield item;
2463
- }
2464
- if (!response.hasMore || !response.nextCursor) {
2465
- break;
2466
- }
2467
- cursor = response.nextCursor;
2468
- scoped = scoped.forNextPage();
2469
- }
2275
+ yield* this.withRequestOptions(requestOptions).paginate(
2276
+ options?.cursor,
2277
+ (view, cursor) => view.list(websetId, { ...options, cursor })
2278
+ );
2470
2279
  }
2471
2280
  /**
2472
2281
  * Collect all items from a Webset into an array
@@ -2476,12 +2285,9 @@ var WebsetItemsClient = class extends WebsetsBaseClient {
2476
2285
  * @returns Promise resolving to an array of all Webset Items
2477
2286
  */
2478
2287
  async getAll(websetId, options, requestOptions) {
2479
- const scoped = this.withRequestOptions(requestOptions);
2480
- const items = [];
2481
- for await (const item of scoped.listAll(websetId, options)) {
2482
- items.push(item);
2483
- }
2484
- return items;
2288
+ return collectAll(
2289
+ this.withRequestOptions(requestOptions).listAll(websetId, options)
2290
+ );
2485
2291
  }
2486
2292
  /**
2487
2293
  * Get an Item by ID
@@ -2620,21 +2426,10 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
2620
2426
  * @returns Async generator of Monitors
2621
2427
  */
2622
2428
  async *listAll(options, requestOptions) {
2623
- let scoped = this.withRequestOptions(requestOptions);
2624
- let cursor = void 0;
2625
- const pageOptions = options ? { ...options } : {};
2626
- while (true) {
2627
- pageOptions.cursor = cursor;
2628
- const response = await scoped.list(pageOptions);
2629
- for (const monitor of response.data) {
2630
- yield monitor;
2631
- }
2632
- if (!response.hasMore || !response.nextCursor) {
2633
- break;
2634
- }
2635
- cursor = response.nextCursor;
2636
- scoped = scoped.forNextPage();
2637
- }
2429
+ yield* this.withRequestOptions(requestOptions).paginate(
2430
+ options?.cursor,
2431
+ (view, cursor) => view.list({ ...options, cursor })
2432
+ );
2638
2433
  }
2639
2434
  /**
2640
2435
  * Collect all Monitors into an array
@@ -2643,12 +2438,9 @@ var WebsetMonitorsClient = class extends WebsetsBaseClient {
2643
2438
  * @returns Promise resolving to an array of all Monitors
2644
2439
  */
2645
2440
  async getAll(options, requestOptions) {
2646
- const scoped = this.withRequestOptions(requestOptions);
2647
- const monitors = [];
2648
- for await (const monitor of scoped.listAll(options)) {
2649
- monitors.push(monitor);
2650
- }
2651
- return monitors;
2441
+ return collectAll(
2442
+ this.withRequestOptions(requestOptions).listAll(options)
2443
+ );
2652
2444
  }
2653
2445
  };
2654
2446
 
@@ -2746,21 +2538,10 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2746
2538
  * @returns Async generator of Webhooks
2747
2539
  */
2748
2540
  async *listAll(options, requestOptions) {
2749
- let scoped = this.withRequestOptions(requestOptions);
2750
- let cursor = void 0;
2751
- const pageOptions = options ? { ...options } : {};
2752
- while (true) {
2753
- pageOptions.cursor = cursor;
2754
- const response = await scoped.list(pageOptions);
2755
- for (const webhook of response.data) {
2756
- yield webhook;
2757
- }
2758
- if (!response.hasMore || !response.nextCursor) {
2759
- break;
2760
- }
2761
- cursor = response.nextCursor;
2762
- scoped = scoped.forNextPage();
2763
- }
2541
+ yield* this.withRequestOptions(requestOptions).paginate(
2542
+ options?.cursor,
2543
+ (view, cursor) => view.list({ ...options, cursor })
2544
+ );
2764
2545
  }
2765
2546
  /**
2766
2547
  * Collect all Webhooks into an array
@@ -2769,12 +2550,9 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2769
2550
  * @returns Promise resolving to an array of all Webhooks
2770
2551
  */
2771
2552
  async getAll(options, requestOptions) {
2772
- const scoped = this.withRequestOptions(requestOptions);
2773
- const webhooks = [];
2774
- for await (const webhook of scoped.listAll(options)) {
2775
- webhooks.push(webhook);
2776
- }
2777
- return webhooks;
2553
+ return collectAll(
2554
+ this.withRequestOptions(requestOptions).listAll(options)
2555
+ );
2778
2556
  }
2779
2557
  /**
2780
2558
  * Update a Webhook
@@ -2827,21 +2605,10 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2827
2605
  * @returns Async generator of Webhook attempts
2828
2606
  */
2829
2607
  async *listAllAttempts(id, options, requestOptions) {
2830
- let scoped = this.withRequestOptions(requestOptions);
2831
- let cursor = void 0;
2832
- const pageOptions = options ? { ...options } : {};
2833
- while (true) {
2834
- pageOptions.cursor = cursor;
2835
- const response = await scoped.listAttempts(id, pageOptions);
2836
- for (const attempt of response.data) {
2837
- yield attempt;
2838
- }
2839
- if (!response.hasMore || !response.nextCursor) {
2840
- break;
2841
- }
2842
- cursor = response.nextCursor;
2843
- scoped = scoped.forNextPage();
2844
- }
2608
+ yield* this.withRequestOptions(requestOptions).paginate(
2609
+ options?.cursor,
2610
+ (view, cursor) => view.listAttempts(id, { ...options, cursor })
2611
+ );
2845
2612
  }
2846
2613
  /**
2847
2614
  * Collect all attempts for a Webhook into an array
@@ -2851,12 +2618,9 @@ var WebsetWebhooksClient = class extends WebsetsBaseClient {
2851
2618
  * @returns Promise resolving to an array of all Webhook attempts
2852
2619
  */
2853
2620
  async getAllAttempts(id, options, requestOptions) {
2854
- const scoped = this.withRequestOptions(requestOptions);
2855
- const attempts = [];
2856
- for await (const attempt of scoped.listAllAttempts(id, options)) {
2857
- attempts.push(attempt);
2858
- }
2859
- return attempts;
2621
+ return collectAll(
2622
+ this.withRequestOptions(requestOptions).listAllAttempts(id, options)
2623
+ );
2860
2624
  }
2861
2625
  };
2862
2626
 
@@ -2955,21 +2719,10 @@ var WebsetsClient = class extends WebsetsBaseClient {
2955
2719
  * @returns Async generator of Websets
2956
2720
  */
2957
2721
  async *listAll(options, requestOptions) {
2958
- let scoped = this.withRequestOptions(requestOptions);
2959
- let cursor = void 0;
2960
- const pageOptions = options ? { ...options } : {};
2961
- while (true) {
2962
- pageOptions.cursor = cursor;
2963
- const response = await scoped.list(pageOptions);
2964
- for (const webset of response.data) {
2965
- yield webset;
2966
- }
2967
- if (!response.hasMore || !response.nextCursor) {
2968
- break;
2969
- }
2970
- cursor = response.nextCursor;
2971
- scoped = scoped.forNextPage();
2972
- }
2722
+ yield* this.withRequestOptions(requestOptions).paginate(
2723
+ options?.cursor,
2724
+ (view, cursor) => view.list({ ...options, cursor })
2725
+ );
2973
2726
  }
2974
2727
  /**
2975
2728
  * Collect all Websets into an array
@@ -2978,12 +2731,9 @@ var WebsetsClient = class extends WebsetsBaseClient {
2978
2731
  * @returns Promise resolving to an array of all Websets
2979
2732
  */
2980
2733
  async getAll(options, requestOptions) {
2981
- const scoped = this.withRequestOptions(requestOptions);
2982
- const websets = [];
2983
- for await (const webset of scoped.listAll(options)) {
2984
- websets.push(webset);
2985
- }
2986
- return websets;
2734
+ return collectAll(
2735
+ this.withRequestOptions(requestOptions).listAll(options)
2736
+ );
2987
2737
  }
2988
2738
  /**
2989
2739
  * Update a Webset
@@ -3057,7 +2807,7 @@ var WebsetsClient = class extends WebsetsBaseClient {
3057
2807
  };
3058
2808
 
3059
2809
  // src/tools/core.ts
3060
- import { z } from "zod";
2810
+ import { z } from "zod/v3";
3061
2811
  var DEFAULT_WEB_SEARCH_TOOL_DESCRIPTION = "Search the web for up-to-date, relevant information. Describe the ideal page rather than listing keywords.";
3062
2812
  var DEFAULT_GET_CONTENTS_TOOL_DESCRIPTION = "Read the full contents of web pages you already have URLs for, such as pages returned by a search or mentioned by the user.";
3063
2813
  var SEARCH_OBJECTIVE_TOOL_DESCRIPTION = "Goal for this search turn; say which documents should rank first, which should be excluded, and what specific facts or figures to pull from them.";
@@ -3490,7 +3240,47 @@ function isResponsesInput(value) {
3490
3240
  var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : fetch2;
3491
3241
  var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : Headers;
3492
3242
  var DEFAULT_MAX_CHARACTERS = 1e4;
3243
+ var DEFAULT_BASE_URL = "https://api.exa.ai";
3244
+ function resolveBaseURL(baseURL) {
3245
+ if (baseURL === void 0) {
3246
+ const fromEnvironment = typeof process === "undefined" ? void 0 : process.env?.EXA_BASE_URL?.trim();
3247
+ baseURL = fromEnvironment || DEFAULT_BASE_URL;
3248
+ }
3249
+ return baseURL.replace(/\/+$/, "");
3250
+ }
3251
+ function clientArguments(second, third) {
3252
+ if (typeof URL !== "undefined" && second instanceof URL) {
3253
+ second = String(second);
3254
+ }
3255
+ if (typeof second === "object" && second !== null) {
3256
+ if (third !== void 0) {
3257
+ throw new TypeError(
3258
+ "Pass the client options once, as the second argument or as the third after a base URL"
3259
+ );
3260
+ }
3261
+ return { baseURL: second.baseURL, options: second };
3262
+ }
3263
+ if (second != null && third?.baseURL !== void 0) {
3264
+ throw new TypeError(
3265
+ "Pass the base URL once, as the second argument or as options.baseURL"
3266
+ );
3267
+ }
3268
+ return { baseURL: second ?? third?.baseURL, options: third };
3269
+ }
3493
3270
  var DYNAMIC_HIGHLIGHTS_BETA = "dynamic-highlights-2026-08-28";
3271
+ async function resolveApiKey(apiKey, signal) {
3272
+ if (signal?.aborted) {
3273
+ throw signal.reason;
3274
+ }
3275
+ const pending = Promise.resolve(apiKey({ signal }));
3276
+ const key = await (signal ? untilAborted(pending, signal) : pending);
3277
+ if (typeof key !== "string" || !/^[\x21-\x7E]+$/.test(key)) {
3278
+ throw new TypeError(
3279
+ "apiKey must return a non-empty string of visible ASCII characters"
3280
+ );
3281
+ }
3282
+ return key;
3283
+ }
3494
3284
  var loggedWarnings = /* @__PURE__ */ new Set();
3495
3285
  function logWarningOnce(warning, context) {
3496
3286
  const request = `${context.method} ${context.endpoint}`;
@@ -3542,6 +3332,24 @@ function costDollarsOf(payload) {
3542
3332
  }
3543
3333
  return costDollars;
3544
3334
  }
3335
+ function streamErrorOf(payload, path, requestIdHeader) {
3336
+ const event = payload?.type === "error" ? payload : payload?.tag === "ERROR" ? payload.payload : void 0;
3337
+ if (typeof event !== "object" || event === null) {
3338
+ return void 0;
3339
+ }
3340
+ const { code, message, tag } = event.error ?? {};
3341
+ const requestId = typeof event.requestId === "string" ? event.requestId : requestIdHeader;
3342
+ return new ExaError(
3343
+ typeof message === "string" && message ? message : "Unknown error",
3344
+ typeof code === "number" ? code : 500 /* InternalServerError */,
3345
+ void 0,
3346
+ path,
3347
+ {
3348
+ requestId: requestId ?? void 0,
3349
+ tag: typeof tag === "string" ? tag : void 0
3350
+ }
3351
+ );
3352
+ }
3545
3353
  function citationsFromResults(results) {
3546
3354
  if (!Array.isArray(results)) {
3547
3355
  return void 0;
@@ -3568,36 +3376,47 @@ function withJsonSummarySchema(contents) {
3568
3376
  };
3569
3377
  }
3570
3378
  var Exa2 = class {
3571
- /**
3572
- * Constructs the Exa API client.
3573
- * @param {string} apiKey - The API key for authentication.
3574
- * @param {string} [baseURL] - The base URL of the Exa API.
3575
- * @param {ExaClientOptions} [options] - Client-wide settings (`timeout`, `warnings`).
3576
- * @throws {RangeError} When `options.timeout` is not an integer from 1 to 2147483647.
3577
- * @throws {TypeError} When `options.warnings` is not `"log"`, `"silent"` or a function.
3578
- */
3579
- constructor(apiKey, baseURL = "https://api.exa.ai", options) {
3379
+ constructor(apiKey, baseURLOrOptions, maybeOptions) {
3580
3380
  this.toolRegistry = new ToolRegistry();
3581
- this.baseURL = baseURL;
3381
+ const { baseURL, options } = clientArguments(
3382
+ baseURLOrOptions,
3383
+ maybeOptions
3384
+ );
3385
+ this.baseURL = resolveBaseURL(baseURL);
3582
3386
  this.warningHandler = warningHandlerFor(options?.warnings);
3583
3387
  setClientDefaults(
3584
3388
  this,
3585
3389
  options?.timeout === void 0 ? void 0 : { timeout: validateTimeout(options.timeout) }
3586
3390
  );
3587
- if (!apiKey) {
3588
- apiKey = process.env.EXA_API_KEY;
3391
+ const customFetch = options?.fetch;
3392
+ if (customFetch !== void 0 && typeof customFetch !== "function") {
3393
+ throw new TypeError("options.fetch must be a function");
3394
+ }
3395
+ const send = customFetch ?? fetchImpl;
3396
+ this.fetcher = (input, init) => send(input, init);
3397
+ if (typeof apiKey === "function") {
3398
+ this.apiKeySource = apiKey;
3399
+ this.headers = new HeadersImpl({
3400
+ "Content-Type": "application/json",
3401
+ "User-Agent": `exa-node ${package_default.version}`
3402
+ });
3403
+ } else {
3404
+ this.apiKeySource = void 0;
3589
3405
  if (!apiKey) {
3590
- throw new ExaError(
3591
- "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
3592
- 401 /* Unauthorized */
3593
- );
3406
+ apiKey = process.env.EXA_API_KEY;
3407
+ if (!apiKey) {
3408
+ throw new ExaError(
3409
+ "API key must be provided as an argument or as an environment variable (EXA_API_KEY)",
3410
+ 401 /* Unauthorized */
3411
+ );
3412
+ }
3594
3413
  }
3414
+ this.headers = new HeadersImpl({
3415
+ "x-api-key": apiKey,
3416
+ "Content-Type": "application/json",
3417
+ "User-Agent": `exa-node ${package_default.version}`
3418
+ });
3595
3419
  }
3596
- this.headers = new HeadersImpl({
3597
- "x-api-key": apiKey,
3598
- "Content-Type": "application/json",
3599
- "User-Agent": `exa-node ${package_default.version}`
3600
- });
3601
3420
  this.websets = new WebsetsClient(this);
3602
3421
  this.research = new ResearchClient(this);
3603
3422
  this.monitors = new SearchMonitorsClient(this);
@@ -3692,6 +3511,22 @@ var Exa2 = class {
3692
3511
  }
3693
3512
  return { query, ...body };
3694
3513
  }
3514
+ /**
3515
+ * Returns the headers a request sends, which are `headers` with the call's
3516
+ * `extraHeaders` on top and, when `apiKey` is a function, the key it returns
3517
+ * as `x-api-key` beneath them. The function is called only when neither
3518
+ * sets `x-api-key` nor removes it with `null`, whatever its case. Called
3519
+ * inside each request's lifecycle, so the request's `signal` and `timeout`
3520
+ * also bound the wait for the key.
3521
+ */
3522
+ async requestHeaders(headers, extraHeaders, signal) {
3523
+ const merged = mergeRequestHeaders(headers, extraHeaders);
3524
+ if (!this.apiKeySource || setsHeader(headers, "x-api-key") || setsHeader(extraHeaders, "x-api-key")) {
3525
+ return merged;
3526
+ }
3527
+ const apiKey = await resolveApiKey(this.apiKeySource, signal);
3528
+ return mergeRequestHeaders({ "x-api-key": apiKey }, merged);
3529
+ }
3695
3530
  /**
3696
3531
  * Makes a request to the Exa API.
3697
3532
  * @param {string} endpoint - The API endpoint to call.
@@ -3733,17 +3568,17 @@ var Exa2 = class {
3733
3568
  if (headers) {
3734
3569
  combinedHeaders = { ...combinedHeaders, ...headers };
3735
3570
  }
3736
- combinedHeaders = mergeRequestHeaders(
3737
- combinedHeaders,
3738
- requestOptions?.headers
3739
- );
3740
3571
  const { signal, dispose, toRequestError } = resolveRequestSignal(
3741
3572
  withClientDefaults(this, requestOptions)
3742
3573
  );
3743
3574
  try {
3744
- const response = await fetchImpl(url, {
3575
+ const response = await this.fetcher(url, {
3745
3576
  method,
3746
- headers: combinedHeaders,
3577
+ headers: await this.requestHeaders(
3578
+ combinedHeaders,
3579
+ requestOptions?.headers,
3580
+ signal
3581
+ ),
3747
3582
  body: body ? JSON.stringify(body) : void 0,
3748
3583
  signal
3749
3584
  });
@@ -3808,15 +3643,15 @@ var Exa2 = class {
3808
3643
  if (headers) {
3809
3644
  combinedHeaders = { ...combinedHeaders, ...headers };
3810
3645
  }
3811
- combinedHeaders = mergeRequestHeaders(
3812
- combinedHeaders,
3813
- requestOptions?.headers
3814
- );
3815
3646
  const { signal, dispose, needsDispose, stopTimeout, toRequestError } = resolveRequestSignal(withClientDefaults(this, requestOptions));
3816
3647
  try {
3817
- const response = await fetchImpl(url, {
3648
+ const response = await this.fetcher(url, {
3818
3649
  method,
3819
- headers: combinedHeaders,
3650
+ headers: await this.requestHeaders(
3651
+ combinedHeaders,
3652
+ requestOptions?.headers,
3653
+ signal
3654
+ ),
3820
3655
  body: body ? JSON.stringify(body) : void 0,
3821
3656
  signal
3822
3657
  });
@@ -3907,6 +3742,9 @@ var Exa2 = class {
3907
3742
  * A search without `outputSchema` has no text to stream. Its stream yields
3908
3743
  * one chunk with the results as `citations`, then the warnings chunk when
3909
3744
  * the API returns warnings. Call `search()` for every field of the results.
3745
+ *
3746
+ * If the API reports an error partway through, the stream yields the chunks
3747
+ * before it and then rejects with an `ExaError`.
3910
3748
  * @param {RequestOptions} [requestOptions] - Per-call request options (`signal`, `timeout`, `body`, `headers`, `query`).
3911
3749
  */
3912
3750
  streamSearch(query, options, requestOptions) {
@@ -4160,18 +3998,29 @@ var Exa2 = class {
4160
3998
  continue;
4161
3999
  }
4162
4000
  this.reportWarnings(endpoint, "POST", chunkData, requestIdHeader);
4001
+ const error = streamErrorOf(chunkData, endpoint, requestIdHeader);
4002
+ if (error) {
4003
+ throw error;
4004
+ }
4163
4005
  yield* this.payloadChunks(chunkData);
4164
4006
  }
4165
4007
  }
4166
4008
  if (buffer.startsWith("data: ")) {
4167
4009
  const leftover = buffer.replace(/^data:\s*/, "").trim();
4168
4010
  if (leftover && leftover !== "[DONE]") {
4011
+ let error;
4169
4012
  try {
4170
4013
  const chunkData = JSON.parse(leftover);
4171
4014
  this.reportWarnings(endpoint, "POST", chunkData, requestIdHeader);
4172
- yield* this.payloadChunks(chunkData);
4015
+ error = streamErrorOf(chunkData, endpoint, requestIdHeader);
4016
+ if (!error) {
4017
+ yield* this.payloadChunks(chunkData);
4018
+ }
4173
4019
  } catch (e) {
4174
4020
  }
4021
+ if (error) {
4022
+ throw error;
4023
+ }
4175
4024
  }
4176
4025
  }
4177
4026
  } finally {
@@ -4362,4 +4211,3 @@ export {
4362
4211
  createWebSearchTool,
4363
4212
  index_default as default
4364
4213
  };
4365
- //# sourceMappingURL=index.mjs.map