exa-js 2.12.1 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -30,6 +30,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AGENT_BETA_HEADER: () => AGENT_BETA_HEADER,
34
+ AgentBetaClient: () => AgentBetaClient,
35
+ AgentClient: () => AgentClient,
36
+ AgentRunEventsClient: () => AgentRunEventsClient,
37
+ AgentRunsClient: () => AgentRunsClient,
38
+ BetaClient: () => BetaClient,
33
39
  CreateEnrichmentParametersFormat: () => CreateEnrichmentParametersFormat,
34
40
  CreateImportParametersFormat: () => CreateImportParametersFormat,
35
41
  EventType: () => EventType,
@@ -76,7 +82,7 @@ var import_cross_fetch = __toESM(require("cross-fetch"));
76
82
  // package.json
77
83
  var package_default = {
78
84
  name: "exa-js",
79
- version: "2.12.1",
85
+ version: "2.14.0",
80
86
  description: "Exa SDK for Node.js and the browser",
81
87
  publishConfig: {
82
88
  access: "public"
@@ -189,6 +195,391 @@ var ExaError = class extends Error {
189
195
  }
190
196
  };
191
197
 
198
+ // src/zod-utils.ts
199
+ var import_zod = require("zod");
200
+ var import_zod_to_json_schema = require("zod-to-json-schema");
201
+ function isZodSchema(obj) {
202
+ return obj instanceof import_zod.ZodType;
203
+ }
204
+ function zodToJsonSchema(schema) {
205
+ return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
206
+ $refStrategy: "none"
207
+ });
208
+ }
209
+
210
+ // src/agent/base.ts
211
+ var AgentBaseClient = class {
212
+ constructor(client) {
213
+ this.client = client;
214
+ }
215
+ async request(endpoint, method = "POST", data, params, headers) {
216
+ return this.client.request(
217
+ `/agent/runs${endpoint}`,
218
+ method,
219
+ data,
220
+ params,
221
+ headers
222
+ );
223
+ }
224
+ async rawRequest(endpoint, method = "POST", data, params, headers) {
225
+ return this.client.rawRequest(
226
+ `/agent/runs${endpoint}`,
227
+ method,
228
+ data,
229
+ params,
230
+ headers
231
+ );
232
+ }
233
+ buildPaginationParams(pagination) {
234
+ const params = {};
235
+ if (!pagination) return params;
236
+ if (pagination.cursor) params.cursor = pagination.cursor;
237
+ if (pagination.limit) params.limit = pagination.limit;
238
+ return params;
239
+ }
240
+ };
241
+
242
+ // src/agent/client.ts
243
+ function headersForBetas(betas) {
244
+ const betaValues = betas?.filter(Boolean);
245
+ if (!betaValues?.length) return void 0;
246
+ return { "Exa-Beta": betaValues.join(",") };
247
+ }
248
+ function buildAgentRunPayload(params) {
249
+ const { stream, outputSchema, ...rest } = params;
250
+ let schema = outputSchema;
251
+ if (schema && isZodSchema(schema)) {
252
+ schema = zodToJsonSchema(schema);
253
+ }
254
+ const payload = { ...rest };
255
+ if (schema) {
256
+ payload.outputSchema = schema;
257
+ }
258
+ return { stream, payload };
259
+ }
260
+ async function* streamAgentEvents(response) {
261
+ if (!response.body) {
262
+ throw new Error("No response body for SSE stream");
263
+ }
264
+ const reader = response.body.getReader();
265
+ const decoder = new TextDecoder();
266
+ let buffer = "";
267
+ let doneReading = false;
268
+ const processPart = (part) => {
269
+ const event = {};
270
+ const dataLines = [];
271
+ for (const line of part.split("\n")) {
272
+ if (!line || !line.includes(":")) continue;
273
+ const [field, ...rest] = line.split(":");
274
+ const value = rest.join(":").replace(/^ /, "");
275
+ if (field === "id") event.id = value;
276
+ if (field === "event") event.event = value;
277
+ if (field === "data") dataLines.push(value);
278
+ }
279
+ if (!event.event || dataLines.length === 0) return null;
280
+ try {
281
+ event.data = JSON.parse(dataLines.join("\n"));
282
+ } catch {
283
+ event.data = { value: dataLines.join("\n") };
284
+ }
285
+ return event;
286
+ };
287
+ try {
288
+ while (true) {
289
+ const { done, value } = await reader.read();
290
+ if (done) {
291
+ doneReading = true;
292
+ break;
293
+ }
294
+ buffer += decoder.decode(value, { stream: true });
295
+ const parts = buffer.split("\n\n");
296
+ buffer = parts.pop() ?? "";
297
+ for (const part of parts) {
298
+ const event = processPart(part);
299
+ if (event) yield event;
300
+ }
301
+ }
302
+ if (buffer.trim()) {
303
+ const event = processPart(buffer.trim());
304
+ if (event) yield event;
305
+ }
306
+ } finally {
307
+ if (!doneReading) {
308
+ await reader.cancel();
309
+ }
310
+ reader.releaseLock();
311
+ }
312
+ }
313
+ var AgentRunEventsClient = class extends AgentBaseClient {
314
+ /**
315
+ * List stored events for an Agent run.
316
+ */
317
+ async list(runId, options) {
318
+ const params = this.buildPaginationParams(options);
319
+ return this.request(
320
+ `/${runId}/events`,
321
+ "GET",
322
+ void 0,
323
+ params
324
+ );
325
+ }
326
+ };
327
+ var AgentRunsClient = class extends AgentBaseClient {
328
+ constructor(client) {
329
+ super(client);
330
+ this.events = new AgentRunEventsClient(client);
331
+ }
332
+ async create(params) {
333
+ const { stream, payload } = buildAgentRunPayload(params);
334
+ if (stream) {
335
+ const response = await this.rawRequest("", "POST", payload, void 0, {
336
+ Accept: "text/event-stream"
337
+ });
338
+ if (!response.ok) {
339
+ const message = await response.text();
340
+ throw new ExaError(
341
+ message || `Request failed with status code ${response.status}`,
342
+ response.status,
343
+ (/* @__PURE__ */ new Date()).toISOString(),
344
+ "/agent/runs"
345
+ );
346
+ }
347
+ return streamAgentEvents(response);
348
+ }
349
+ return this.request("", "POST", payload);
350
+ }
351
+ /**
352
+ * Get an Agent run by ID.
353
+ */
354
+ async get(runId) {
355
+ return this.request(`/${runId}`, "GET");
356
+ }
357
+ /**
358
+ * List Agent runs.
359
+ */
360
+ async list(options) {
361
+ const params = this.buildPaginationParams(options);
362
+ return this.request("", "GET", void 0, params);
363
+ }
364
+ /**
365
+ * Iterate through all Agent runs, handling pagination automatically.
366
+ */
367
+ async *listAll(options) {
368
+ let cursor = void 0;
369
+ const pageOptions = options ? { ...options } : {};
370
+ while (true) {
371
+ pageOptions.cursor = cursor;
372
+ const response = await this.list(pageOptions);
373
+ for (const run of response.data) {
374
+ yield run;
375
+ }
376
+ if (!response.hasMore || !response.nextCursor) {
377
+ break;
378
+ }
379
+ cursor = response.nextCursor;
380
+ }
381
+ }
382
+ /**
383
+ * Collect all Agent runs into an array.
384
+ */
385
+ async getAll(options) {
386
+ const runs = [];
387
+ for await (const run of this.listAll(options)) {
388
+ runs.push(run);
389
+ }
390
+ return runs;
391
+ }
392
+ /**
393
+ * Cancel a queued or running Agent run.
394
+ */
395
+ async cancel(runId) {
396
+ return this.request(`/${runId}/cancel`, "POST");
397
+ }
398
+ /**
399
+ * Delete a stored Agent run.
400
+ */
401
+ async delete(runId) {
402
+ return this.request(`/${runId}`, "DELETE");
403
+ }
404
+ /**
405
+ * Poll an Agent run until it reaches a terminal status.
406
+ */
407
+ async pollUntilFinished(runId, options) {
408
+ const pollInterval = options?.pollInterval ?? 1e3;
409
+ const timeoutMs = options?.timeoutMs ?? 60 * 60 * 1e3;
410
+ const startTime = Date.now();
411
+ while (true) {
412
+ const run = await this.get(runId);
413
+ if (run.status === "completed" || run.status === "failed" || run.status === "cancelled") {
414
+ return run;
415
+ }
416
+ if (Date.now() - startTime > timeoutMs) {
417
+ throw new Error(
418
+ `Polling timeout: Agent run ${runId} did not complete within ${timeoutMs}ms`
419
+ );
420
+ }
421
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
422
+ }
423
+ }
424
+ };
425
+ var AgentClient = class {
426
+ constructor(client) {
427
+ this.client = client;
428
+ this.runs = new AgentRunsClient(client);
429
+ }
430
+ };
431
+ var AgentBetaRunEventsClient = class extends AgentRunEventsClient {
432
+ /**
433
+ * List stored events for an Agent run.
434
+ *
435
+ * @deprecated Use exa.agent.runs.events instead.
436
+ */
437
+ async list(runId, options) {
438
+ const { betas, ...pagination } = options ?? {};
439
+ const params = this.buildPaginationParams(pagination);
440
+ return this.request(
441
+ `/${runId}/events`,
442
+ "GET",
443
+ void 0,
444
+ params,
445
+ headersForBetas(betas)
446
+ );
447
+ }
448
+ };
449
+ var AgentBetaRunsClient = class extends AgentRunsClient {
450
+ constructor(client) {
451
+ super(client);
452
+ this.events = new AgentBetaRunEventsClient(client);
453
+ }
454
+ async create(params) {
455
+ const { betas, ...createParams } = params;
456
+ const { stream, payload } = buildAgentRunPayload(
457
+ createParams
458
+ );
459
+ const headers = headersForBetas(betas);
460
+ if (stream) {
461
+ const response = await this.rawRequest("", "POST", payload, void 0, {
462
+ ...headers,
463
+ Accept: "text/event-stream"
464
+ });
465
+ if (!response.ok) {
466
+ const message = await response.text();
467
+ throw new ExaError(
468
+ message || `Request failed with status code ${response.status}`,
469
+ response.status,
470
+ (/* @__PURE__ */ new Date()).toISOString(),
471
+ "/agent/runs"
472
+ );
473
+ }
474
+ return streamAgentEvents(response);
475
+ }
476
+ return this.request(
477
+ "",
478
+ "POST",
479
+ payload,
480
+ void 0,
481
+ headers
482
+ );
483
+ }
484
+ async get(runId, options) {
485
+ return this.request(
486
+ `/${runId}`,
487
+ "GET",
488
+ void 0,
489
+ void 0,
490
+ headersForBetas(options?.betas)
491
+ );
492
+ }
493
+ async list(options) {
494
+ const { betas, ...pagination } = options ?? {};
495
+ const params = this.buildPaginationParams(pagination);
496
+ return this.request(
497
+ "",
498
+ "GET",
499
+ void 0,
500
+ params,
501
+ headersForBetas(betas)
502
+ );
503
+ }
504
+ async *listAll(options) {
505
+ let cursor = void 0;
506
+ const { betas, ...pagination } = options ?? {};
507
+ const pageOptions = { ...pagination };
508
+ while (true) {
509
+ pageOptions.cursor = cursor;
510
+ const response = await this.list({ ...pageOptions, betas });
511
+ for (const run of response.data) {
512
+ yield run;
513
+ }
514
+ if (!response.hasMore || !response.nextCursor) {
515
+ break;
516
+ }
517
+ cursor = response.nextCursor;
518
+ }
519
+ }
520
+ async getAll(options) {
521
+ const runs = [];
522
+ for await (const run of this.listAll(options)) {
523
+ runs.push(run);
524
+ }
525
+ return runs;
526
+ }
527
+ async cancel(runId, options) {
528
+ return this.request(
529
+ `/${runId}/cancel`,
530
+ "POST",
531
+ void 0,
532
+ void 0,
533
+ headersForBetas(options?.betas)
534
+ );
535
+ }
536
+ async delete(runId, options) {
537
+ return this.request(
538
+ `/${runId}`,
539
+ "DELETE",
540
+ void 0,
541
+ void 0,
542
+ headersForBetas(options?.betas)
543
+ );
544
+ }
545
+ async pollUntilFinished(runId, options) {
546
+ const pollInterval = options?.pollInterval ?? 1e3;
547
+ const timeoutMs = options?.timeoutMs ?? 60 * 60 * 1e3;
548
+ const startTime = Date.now();
549
+ const headers = headersForBetas(options?.betas);
550
+ while (true) {
551
+ const run = await this.request(
552
+ `/${runId}`,
553
+ "GET",
554
+ void 0,
555
+ void 0,
556
+ headers
557
+ );
558
+ if (run.status === "completed" || run.status === "failed" || run.status === "cancelled") {
559
+ return run;
560
+ }
561
+ if (Date.now() - startTime > timeoutMs) {
562
+ throw new Error(
563
+ `Polling timeout: Agent run ${runId} did not complete within ${timeoutMs}ms`
564
+ );
565
+ }
566
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
567
+ }
568
+ }
569
+ };
570
+ var AgentBetaClient = class extends AgentClient {
571
+ constructor(clientOrAgent) {
572
+ const client = clientOrAgent instanceof AgentClient ? clientOrAgent.client : clientOrAgent;
573
+ super(client);
574
+ this.runs = new AgentBetaRunsClient(client);
575
+ }
576
+ };
577
+ var BetaClient = class {
578
+ constructor(clientOrAgent) {
579
+ this.agent = new AgentBetaClient(clientOrAgent);
580
+ }
581
+ };
582
+
192
583
  // src/monitors/base.ts
193
584
  var SearchMonitorsBaseClient = class {
194
585
  constructor(client) {
@@ -374,18 +765,6 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
374
765
  }
375
766
  };
376
767
 
377
- // src/zod-utils.ts
378
- var import_zod = require("zod");
379
- var import_zod_to_json_schema = require("zod-to-json-schema");
380
- function isZodSchema(obj) {
381
- return obj instanceof import_zod.ZodType;
382
- }
383
- function zodToJsonSchema(schema) {
384
- return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
385
- $refStrategy: "none"
386
- });
387
- }
388
-
389
768
  // src/research/base.ts
390
769
  var ResearchBaseClient = class {
391
770
  constructor(client) {
@@ -1619,10 +1998,29 @@ var WebsetsClient = class extends WebsetsBaseClient {
1619
1998
  }
1620
1999
  };
1621
2000
 
2001
+ // src/agent/types.ts
2002
+ var AGENT_BETA_HEADER = "agent-2026-05-07";
2003
+
1622
2004
  // src/index.ts
1623
2005
  var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : import_cross_fetch.default;
1624
2006
  var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : import_cross_fetch.Headers;
1625
2007
  var DEFAULT_MAX_CHARACTERS = 1e4;
2008
+ var NON_JSON_BODY_SNIPPET_LENGTH = 500;
2009
+ async function readResponseBody(response) {
2010
+ const text = await response.text();
2011
+ if (!text) {
2012
+ return { json: void 0, text };
2013
+ }
2014
+ try {
2015
+ return { json: JSON.parse(text), text };
2016
+ } catch {
2017
+ return { json: void 0, text };
2018
+ }
2019
+ }
2020
+ function truncateResponseBody(text) {
2021
+ const collapsed = text.replace(/\s+/g, " ").trim();
2022
+ return collapsed.length > NON_JSON_BODY_SNIPPET_LENGTH ? `${collapsed.slice(0, NON_JSON_BODY_SNIPPET_LENGTH)}\u2026` : collapsed;
2023
+ }
1626
2024
  var Exa2 = class {
1627
2025
  /**
1628
2026
  * Helper method to separate out the contents-specific options from the rest.
@@ -1638,6 +2036,7 @@ var Exa2 = class {
1638
2036
  livecrawl,
1639
2037
  livecrawlTimeout,
1640
2038
  maxAgeHours,
2039
+ // DEPRECATED FIELD: preserve legacy `context` only for backward compatibility.
1641
2040
  context,
1642
2041
  ...rest
1643
2042
  } = options;
@@ -1711,6 +2110,8 @@ var Exa2 = class {
1711
2110
  this.websets = new WebsetsClient(this);
1712
2111
  this.research = new ResearchClient(this);
1713
2112
  this.monitors = new SearchMonitorsClient(this);
2113
+ this.agent = new AgentClient(this);
2114
+ this.beta = new BetaClient(this.agent);
1714
2115
  }
1715
2116
  /**
1716
2117
  * Makes a request to the Exa API.
@@ -1753,7 +2154,18 @@ var Exa2 = class {
1753
2154
  body: body ? JSON.stringify(body) : void 0
1754
2155
  });
1755
2156
  if (!response.ok) {
1756
- const errorData = await response.json();
2157
+ const { json: json2, text: text2 } = await readResponseBody(response);
2158
+ if (!json2 || typeof json2 !== "object") {
2159
+ const snippet = truncateResponseBody(text2);
2160
+ const message2 = snippet ? `Request failed with status ${response.status}. Response body was not valid JSON: ${snippet}` : `Request failed with status ${response.status}.`;
2161
+ throw new ExaError(
2162
+ message2,
2163
+ response.status,
2164
+ (/* @__PURE__ */ new Date()).toISOString(),
2165
+ endpoint
2166
+ );
2167
+ }
2168
+ const errorData = json2;
1757
2169
  if (!errorData.statusCode) {
1758
2170
  errorData.statusCode = response.status;
1759
2171
  }
@@ -1778,9 +2190,18 @@ var Exa2 = class {
1778
2190
  if (contentType.includes("text/event-stream")) {
1779
2191
  return await this.parseSSEStream(response);
1780
2192
  }
1781
- return await response.json();
2193
+ const { json, text } = await readResponseBody(response);
2194
+ if (json === void 0 && text) {
2195
+ throw new ExaError(
2196
+ `Expected a JSON response but received a non-JSON body (status ${response.status}): ${truncateResponseBody(text)}`,
2197
+ response.status,
2198
+ (/* @__PURE__ */ new Date()).toISOString(),
2199
+ endpoint
2200
+ );
2201
+ }
2202
+ return json;
1782
2203
  }
1783
- async rawRequest(endpoint, method = "POST", body, queryParams) {
2204
+ async rawRequest(endpoint, method = "POST", body, queryParams, headers) {
1784
2205
  let url = this.baseURL + endpoint;
1785
2206
  if (queryParams) {
1786
2207
  const searchParams = new URLSearchParams();
@@ -1795,9 +2216,20 @@ var Exa2 = class {
1795
2216
  }
1796
2217
  url += `?${searchParams.toString()}`;
1797
2218
  }
2219
+ let combinedHeaders = {};
2220
+ if (this.headers instanceof HeadersImpl) {
2221
+ this.headers.forEach((value, key) => {
2222
+ combinedHeaders[key] = value;
2223
+ });
2224
+ } else {
2225
+ combinedHeaders = { ...this.headers };
2226
+ }
2227
+ if (headers) {
2228
+ combinedHeaders = { ...combinedHeaders, ...headers };
2229
+ }
1798
2230
  const response = await fetchImpl(url, {
1799
2231
  method,
1800
- headers: this.headers,
2232
+ headers: combinedHeaders,
1801
2233
  body: body ? JSON.stringify(body) : void 0
1802
2234
  });
1803
2235
  return response;
@@ -1828,6 +2260,7 @@ var Exa2 = class {
1828
2260
  });
1829
2261
  }
1830
2262
  /**
2263
+ * DEPRECATED: Use `search()` instead. This legacy wrapper will be removed in a future version.
1831
2264
  * @deprecated Use `search()` instead. The search method now returns text contents by default.
1832
2265
  *
1833
2266
  * Migration examples:
@@ -1835,7 +2268,7 @@ var Exa2 = class {
1835
2268
  * - `searchAndContents(query, { text: true })` → `search(query, { contents: { text: true } })`
1836
2269
  * - `searchAndContents(query, { summary: true })` → `search(query, { contents: { summary: true } })`
1837
2270
  *
1838
- * Performs a search with an Exa prompt-engineered query and returns the contents of the documents.
2271
+ * Compatibility wrapper for the legacy top-level contents options shape.
1839
2272
  *
1840
2273
  * @param {string} query - The query string.
1841
2274
  * @param {RegularSearchOptions & T} [options] - Additional search + contents options
@@ -1872,14 +2305,15 @@ var Exa2 = class {
1872
2305
  return await this.request("/findSimilar", "POST", { url, ...options });
1873
2306
  }
1874
2307
  /**
1875
- * @deprecated Use `findSimilar()` instead. The findSimilar method now returns text contents by default.
2308
+ * DEPRECATED: Use `search()` for new discovery flows instead. This legacy wrapper will be removed in a future version.
2309
+ * @deprecated Use `search()` for new discovery flows instead. There is no direct replacement for URL-based similarity.
1876
2310
  *
1877
2311
  * Migration examples:
1878
- * - `findSimilarAndContents(url)` → `findSimilar(url)`
1879
- * - `findSimilarAndContents(url, { text: true })` → `findSimilar(url, { contents: { text: true } })`
1880
- * - `findSimilarAndContents(url, { summary: true })` → `findSimilar(url, { contents: { summary: true } })`
2312
+ * - `findSimilarAndContents(url)` → `search(query)`
2313
+ * - `findSimilarAndContents(url, { text: true })` → `search(query, { contents: { text: true } })`
2314
+ * - `findSimilarAndContents(url, { summary: true })` → `search(query, { contents: { summary: true } })`
1881
2315
  *
1882
- * Finds similar links to the provided URL and returns the contents of the documents.
2316
+ * Compatibility wrapper for the legacy top-level contents options shape.
1883
2317
  * @param {string} url - The URL for which to find similar links.
1884
2318
  * @param {FindSimilarOptions & T} [options] - Additional options for finding similar links + contents.
1885
2319
  * @returns {Promise<SearchResponse<T>>} A list of similar search results, including requested contents.
@@ -2113,6 +2547,12 @@ var Exa2 = class {
2113
2547
  var index_default = Exa2;
2114
2548
  // Annotate the CommonJS export names for ESM import in node:
2115
2549
  0 && (module.exports = {
2550
+ AGENT_BETA_HEADER,
2551
+ AgentBetaClient,
2552
+ AgentClient,
2553
+ AgentRunEventsClient,
2554
+ AgentRunsClient,
2555
+ BetaClient,
2116
2556
  CreateEnrichmentParametersFormat,
2117
2557
  CreateImportParametersFormat,
2118
2558
  EventType,