exa-js 2.11.0 → 2.13.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.11.0",
7
+ version: "2.13.0",
8
8
  description: "Exa SDK for Node.js and the browser",
9
9
  publishConfig: {
10
10
  access: "public"
@@ -117,6 +117,261 @@ var ExaError = class extends Error {
117
117
  }
118
118
  };
119
119
 
120
+ // src/zod-utils.ts
121
+ import { ZodType } from "zod";
122
+ import { zodToJsonSchema as convertZodToJsonSchema } from "zod-to-json-schema";
123
+ function isZodSchema(obj) {
124
+ return obj instanceof ZodType;
125
+ }
126
+ function zodToJsonSchema(schema) {
127
+ return convertZodToJsonSchema(schema, {
128
+ $refStrategy: "none"
129
+ });
130
+ }
131
+
132
+ // src/agent/base.ts
133
+ var AgentBaseClient = class {
134
+ constructor(client) {
135
+ this.client = client;
136
+ }
137
+ async request(endpoint, betas, method = "POST", data, params, headers) {
138
+ if (!betas?.length) {
139
+ throw new Error("betas must include the Agent API beta identifier");
140
+ }
141
+ return this.client.request(
142
+ `/agent/runs${endpoint}`,
143
+ method,
144
+ data,
145
+ params,
146
+ {
147
+ "Exa-Beta": betas.join(","),
148
+ ...headers
149
+ }
150
+ );
151
+ }
152
+ async rawRequest(endpoint, betas, method = "POST", data, params, headers) {
153
+ if (!betas?.length) {
154
+ throw new Error("betas must include the Agent API beta identifier");
155
+ }
156
+ return this.client.rawRequest(
157
+ `/agent/runs${endpoint}`,
158
+ method,
159
+ data,
160
+ params,
161
+ {
162
+ "Exa-Beta": betas.join(","),
163
+ ...headers
164
+ }
165
+ );
166
+ }
167
+ buildPaginationParams(pagination) {
168
+ const params = {};
169
+ if (!pagination) return params;
170
+ if (pagination.cursor) params.cursor = pagination.cursor;
171
+ if (pagination.limit) params.limit = pagination.limit;
172
+ return params;
173
+ }
174
+ };
175
+
176
+ // src/agent/client.ts
177
+ async function* streamAgentEvents(response) {
178
+ if (!response.body) {
179
+ throw new Error("No response body for SSE stream");
180
+ }
181
+ const reader = response.body.getReader();
182
+ const decoder = new TextDecoder();
183
+ let buffer = "";
184
+ let doneReading = false;
185
+ const processPart = (part) => {
186
+ const event = {};
187
+ const dataLines = [];
188
+ for (const line of part.split("\n")) {
189
+ if (!line || !line.includes(":")) continue;
190
+ const [field, ...rest] = line.split(":");
191
+ const value = rest.join(":").replace(/^ /, "");
192
+ if (field === "id") event.id = value;
193
+ if (field === "event") event.event = value;
194
+ if (field === "data") dataLines.push(value);
195
+ }
196
+ if (!event.event || dataLines.length === 0) return null;
197
+ try {
198
+ event.data = JSON.parse(dataLines.join("\n"));
199
+ } catch {
200
+ event.data = { value: dataLines.join("\n") };
201
+ }
202
+ return event;
203
+ };
204
+ try {
205
+ while (true) {
206
+ const { done, value } = await reader.read();
207
+ if (done) {
208
+ doneReading = true;
209
+ break;
210
+ }
211
+ buffer += decoder.decode(value, { stream: true });
212
+ const parts = buffer.split("\n\n");
213
+ buffer = parts.pop() ?? "";
214
+ for (const part of parts) {
215
+ const event = processPart(part);
216
+ if (event) yield event;
217
+ }
218
+ }
219
+ if (buffer.trim()) {
220
+ const event = processPart(buffer.trim());
221
+ if (event) yield event;
222
+ }
223
+ } finally {
224
+ if (!doneReading) {
225
+ await reader.cancel();
226
+ }
227
+ reader.releaseLock();
228
+ }
229
+ }
230
+ var AgentRunEventsClient = class extends AgentBaseClient {
231
+ /**
232
+ * List stored events for an Agent run.
233
+ */
234
+ async list(runId, options) {
235
+ const params = this.buildPaginationParams(options);
236
+ return this.request(
237
+ `/${runId}/events`,
238
+ options.betas,
239
+ "GET",
240
+ void 0,
241
+ params
242
+ );
243
+ }
244
+ };
245
+ var AgentRunsClient = class extends AgentBaseClient {
246
+ constructor(client) {
247
+ super(client);
248
+ this.events = new AgentRunEventsClient(client);
249
+ }
250
+ async create(params) {
251
+ const { stream, outputSchema, betas, ...rest } = params;
252
+ let schema = outputSchema;
253
+ if (schema && isZodSchema(schema)) {
254
+ schema = zodToJsonSchema(schema);
255
+ }
256
+ const payload = { ...rest };
257
+ if (schema) {
258
+ payload.outputSchema = schema;
259
+ }
260
+ if (stream) {
261
+ const response = await this.rawRequest(
262
+ "",
263
+ betas,
264
+ "POST",
265
+ payload,
266
+ void 0,
267
+ {
268
+ Accept: "text/event-stream"
269
+ }
270
+ );
271
+ if (!response.ok) {
272
+ const message = await response.text();
273
+ throw new ExaError(
274
+ message || `Request failed with status code ${response.status}`,
275
+ response.status,
276
+ (/* @__PURE__ */ new Date()).toISOString(),
277
+ "/agent/runs"
278
+ );
279
+ }
280
+ return streamAgentEvents(response);
281
+ }
282
+ return this.request("", betas, "POST", payload);
283
+ }
284
+ /**
285
+ * Get an Agent run by ID.
286
+ */
287
+ async get(runId, options) {
288
+ return this.request(`/${runId}`, options.betas, "GET");
289
+ }
290
+ /**
291
+ * List Agent runs.
292
+ */
293
+ async list(options) {
294
+ const params = this.buildPaginationParams(options);
295
+ return this.request(
296
+ "",
297
+ options.betas,
298
+ "GET",
299
+ void 0,
300
+ params
301
+ );
302
+ }
303
+ /**
304
+ * Iterate through all Agent runs, handling pagination automatically.
305
+ */
306
+ async *listAll(options) {
307
+ let cursor = void 0;
308
+ const pageOptions = { ...options };
309
+ while (true) {
310
+ pageOptions.cursor = cursor;
311
+ const response = await this.list(pageOptions);
312
+ for (const run of response.data) {
313
+ yield run;
314
+ }
315
+ if (!response.hasMore || !response.nextCursor) {
316
+ break;
317
+ }
318
+ cursor = response.nextCursor;
319
+ }
320
+ }
321
+ /**
322
+ * Collect all Agent runs into an array.
323
+ */
324
+ async getAll(options) {
325
+ const runs = [];
326
+ for await (const run of this.listAll(options)) {
327
+ runs.push(run);
328
+ }
329
+ return runs;
330
+ }
331
+ /**
332
+ * Cancel a queued or running Agent run.
333
+ */
334
+ async cancel(runId, options) {
335
+ return this.request(`/${runId}/cancel`, options.betas, "POST");
336
+ }
337
+ /**
338
+ * Delete a stored Agent run.
339
+ */
340
+ async delete(runId, options) {
341
+ return this.request(`/${runId}`, options.betas, "DELETE");
342
+ }
343
+ /**
344
+ * Poll an Agent run until it reaches a terminal status.
345
+ */
346
+ async pollUntilFinished(runId, options) {
347
+ const pollInterval = options?.pollInterval ?? 1e3;
348
+ const timeoutMs = options?.timeoutMs ?? 60 * 60 * 1e3;
349
+ const startTime = Date.now();
350
+ while (true) {
351
+ const run = await this.get(runId, { betas: options.betas });
352
+ if (run.status === "completed" || run.status === "failed" || run.status === "cancelled") {
353
+ return run;
354
+ }
355
+ if (Date.now() - startTime > timeoutMs) {
356
+ throw new Error(
357
+ `Polling timeout: Agent run ${runId} did not complete within ${timeoutMs}ms`
358
+ );
359
+ }
360
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
361
+ }
362
+ }
363
+ };
364
+ var AgentBetaClient = class {
365
+ constructor(client) {
366
+ this.runs = new AgentRunsClient(client);
367
+ }
368
+ };
369
+ var BetaClient = class {
370
+ constructor(client) {
371
+ this.agent = new AgentBetaClient(client);
372
+ }
373
+ };
374
+
120
375
  // src/monitors/base.ts
121
376
  var SearchMonitorsBaseClient = class {
122
377
  constructor(client) {
@@ -302,18 +557,6 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
302
557
  }
303
558
  };
304
559
 
305
- // src/zod-utils.ts
306
- import { ZodType } from "zod";
307
- import { zodToJsonSchema as convertZodToJsonSchema } from "zod-to-json-schema";
308
- function isZodSchema(obj) {
309
- return obj instanceof ZodType;
310
- }
311
- function zodToJsonSchema(schema) {
312
- return convertZodToJsonSchema(schema, {
313
- $refStrategy: "none"
314
- });
315
- }
316
-
317
560
  // src/research/base.ts
318
561
  var ResearchBaseClient = class {
319
562
  constructor(client) {
@@ -1547,6 +1790,9 @@ var WebsetsClient = class extends WebsetsBaseClient {
1547
1790
  }
1548
1791
  };
1549
1792
 
1793
+ // src/agent/types.ts
1794
+ var AGENT_BETA_HEADER = "agent-2026-05-07";
1795
+
1550
1796
  // src/index.ts
1551
1797
  var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : fetch2;
1552
1798
  var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : Headers;
@@ -1566,6 +1812,7 @@ var Exa2 = class {
1566
1812
  livecrawl,
1567
1813
  livecrawlTimeout,
1568
1814
  maxAgeHours,
1815
+ // DEPRECATED FIELD: preserve legacy `context` only for backward compatibility.
1569
1816
  context,
1570
1817
  ...rest
1571
1818
  } = options;
@@ -1639,6 +1886,7 @@ var Exa2 = class {
1639
1886
  this.websets = new WebsetsClient(this);
1640
1887
  this.research = new ResearchClient(this);
1641
1888
  this.monitors = new SearchMonitorsClient(this);
1889
+ this.beta = new BetaClient(this);
1642
1890
  }
1643
1891
  /**
1644
1892
  * Makes a request to the Exa API.
@@ -1708,7 +1956,7 @@ var Exa2 = class {
1708
1956
  }
1709
1957
  return await response.json();
1710
1958
  }
1711
- async rawRequest(endpoint, method = "POST", body, queryParams) {
1959
+ async rawRequest(endpoint, method = "POST", body, queryParams, headers) {
1712
1960
  let url = this.baseURL + endpoint;
1713
1961
  if (queryParams) {
1714
1962
  const searchParams = new URLSearchParams();
@@ -1723,9 +1971,20 @@ var Exa2 = class {
1723
1971
  }
1724
1972
  url += `?${searchParams.toString()}`;
1725
1973
  }
1974
+ let combinedHeaders = {};
1975
+ if (this.headers instanceof HeadersImpl) {
1976
+ this.headers.forEach((value, key) => {
1977
+ combinedHeaders[key] = value;
1978
+ });
1979
+ } else {
1980
+ combinedHeaders = { ...this.headers };
1981
+ }
1982
+ if (headers) {
1983
+ combinedHeaders = { ...combinedHeaders, ...headers };
1984
+ }
1726
1985
  const response = await fetchImpl(url, {
1727
1986
  method,
1728
- headers: this.headers,
1987
+ headers: combinedHeaders,
1729
1988
  body: body ? JSON.stringify(body) : void 0
1730
1989
  });
1731
1990
  return response;
@@ -1756,6 +2015,7 @@ var Exa2 = class {
1756
2015
  });
1757
2016
  }
1758
2017
  /**
2018
+ * DEPRECATED: Use `search()` instead. This legacy wrapper will be removed in a future version.
1759
2019
  * @deprecated Use `search()` instead. The search method now returns text contents by default.
1760
2020
  *
1761
2021
  * Migration examples:
@@ -1763,7 +2023,7 @@ var Exa2 = class {
1763
2023
  * - `searchAndContents(query, { text: true })` → `search(query, { contents: { text: true } })`
1764
2024
  * - `searchAndContents(query, { summary: true })` → `search(query, { contents: { summary: true } })`
1765
2025
  *
1766
- * Performs a search with an Exa prompt-engineered query and returns the contents of the documents.
2026
+ * Compatibility wrapper for the legacy top-level contents options shape.
1767
2027
  *
1768
2028
  * @param {string} query - The query string.
1769
2029
  * @param {RegularSearchOptions & T} [options] - Additional search + contents options
@@ -1800,14 +2060,15 @@ var Exa2 = class {
1800
2060
  return await this.request("/findSimilar", "POST", { url, ...options });
1801
2061
  }
1802
2062
  /**
1803
- * @deprecated Use `findSimilar()` instead. The findSimilar method now returns text contents by default.
2063
+ * DEPRECATED: Use `search()` for new discovery flows instead. This legacy wrapper will be removed in a future version.
2064
+ * @deprecated Use `search()` for new discovery flows instead. There is no direct replacement for URL-based similarity.
1804
2065
  *
1805
2066
  * Migration examples:
1806
- * - `findSimilarAndContents(url)` → `findSimilar(url)`
1807
- * - `findSimilarAndContents(url, { text: true })` → `findSimilar(url, { contents: { text: true } })`
1808
- * - `findSimilarAndContents(url, { summary: true })` → `findSimilar(url, { contents: { summary: true } })`
2067
+ * - `findSimilarAndContents(url)` → `search(query)`
2068
+ * - `findSimilarAndContents(url, { text: true })` → `search(query, { contents: { text: true } })`
2069
+ * - `findSimilarAndContents(url, { summary: true })` → `search(query, { contents: { summary: true } })`
1809
2070
  *
1810
- * Finds similar links to the provided URL and returns the contents of the documents.
2071
+ * Compatibility wrapper for the legacy top-level contents options shape.
1811
2072
  * @param {string} url - The URL for which to find similar links.
1812
2073
  * @param {FindSimilarOptions & T} [options] - Additional options for finding similar links + contents.
1813
2074
  * @returns {Promise<SearchResponse<T>>} A list of similar search results, including requested contents.
@@ -2040,6 +2301,11 @@ var Exa2 = class {
2040
2301
  };
2041
2302
  var index_default = Exa2;
2042
2303
  export {
2304
+ AGENT_BETA_HEADER,
2305
+ AgentBetaClient,
2306
+ AgentRunEventsClient,
2307
+ AgentRunsClient,
2308
+ BetaClient,
2043
2309
  CreateEnrichmentParametersFormat,
2044
2310
  CreateImportParametersFormat,
2045
2311
  EventType,