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.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.12.1",
7
+ version: "2.14.0",
8
8
  description: "Exa SDK for Node.js and the browser",
9
9
  publishConfig: {
10
10
  access: "public"
@@ -117,6 +117,391 @@ 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, method = "POST", data, params, headers) {
138
+ return this.client.request(
139
+ `/agent/runs${endpoint}`,
140
+ method,
141
+ data,
142
+ params,
143
+ headers
144
+ );
145
+ }
146
+ async rawRequest(endpoint, method = "POST", data, params, headers) {
147
+ return this.client.rawRequest(
148
+ `/agent/runs${endpoint}`,
149
+ method,
150
+ data,
151
+ params,
152
+ headers
153
+ );
154
+ }
155
+ buildPaginationParams(pagination) {
156
+ const params = {};
157
+ if (!pagination) return params;
158
+ if (pagination.cursor) params.cursor = pagination.cursor;
159
+ if (pagination.limit) params.limit = pagination.limit;
160
+ return params;
161
+ }
162
+ };
163
+
164
+ // src/agent/client.ts
165
+ function headersForBetas(betas) {
166
+ const betaValues = betas?.filter(Boolean);
167
+ if (!betaValues?.length) return void 0;
168
+ return { "Exa-Beta": betaValues.join(",") };
169
+ }
170
+ function buildAgentRunPayload(params) {
171
+ const { stream, outputSchema, ...rest } = params;
172
+ let schema = outputSchema;
173
+ if (schema && isZodSchema(schema)) {
174
+ schema = zodToJsonSchema(schema);
175
+ }
176
+ const payload = { ...rest };
177
+ if (schema) {
178
+ payload.outputSchema = schema;
179
+ }
180
+ return { stream, payload };
181
+ }
182
+ async function* streamAgentEvents(response) {
183
+ if (!response.body) {
184
+ throw new Error("No response body for SSE stream");
185
+ }
186
+ const reader = response.body.getReader();
187
+ const decoder = new TextDecoder();
188
+ let buffer = "";
189
+ let doneReading = false;
190
+ const processPart = (part) => {
191
+ const event = {};
192
+ const dataLines = [];
193
+ for (const line of part.split("\n")) {
194
+ if (!line || !line.includes(":")) continue;
195
+ const [field, ...rest] = line.split(":");
196
+ const value = rest.join(":").replace(/^ /, "");
197
+ if (field === "id") event.id = value;
198
+ if (field === "event") event.event = value;
199
+ if (field === "data") dataLines.push(value);
200
+ }
201
+ if (!event.event || dataLines.length === 0) return null;
202
+ try {
203
+ event.data = JSON.parse(dataLines.join("\n"));
204
+ } catch {
205
+ event.data = { value: dataLines.join("\n") };
206
+ }
207
+ return event;
208
+ };
209
+ try {
210
+ while (true) {
211
+ const { done, value } = await reader.read();
212
+ if (done) {
213
+ doneReading = true;
214
+ break;
215
+ }
216
+ buffer += decoder.decode(value, { stream: true });
217
+ const parts = buffer.split("\n\n");
218
+ buffer = parts.pop() ?? "";
219
+ for (const part of parts) {
220
+ const event = processPart(part);
221
+ if (event) yield event;
222
+ }
223
+ }
224
+ if (buffer.trim()) {
225
+ const event = processPart(buffer.trim());
226
+ if (event) yield event;
227
+ }
228
+ } finally {
229
+ if (!doneReading) {
230
+ await reader.cancel();
231
+ }
232
+ reader.releaseLock();
233
+ }
234
+ }
235
+ var AgentRunEventsClient = class extends AgentBaseClient {
236
+ /**
237
+ * List stored events for an Agent run.
238
+ */
239
+ async list(runId, options) {
240
+ const params = this.buildPaginationParams(options);
241
+ return this.request(
242
+ `/${runId}/events`,
243
+ "GET",
244
+ void 0,
245
+ params
246
+ );
247
+ }
248
+ };
249
+ var AgentRunsClient = class extends AgentBaseClient {
250
+ constructor(client) {
251
+ super(client);
252
+ this.events = new AgentRunEventsClient(client);
253
+ }
254
+ async create(params) {
255
+ const { stream, payload } = buildAgentRunPayload(params);
256
+ if (stream) {
257
+ const response = await this.rawRequest("", "POST", payload, void 0, {
258
+ Accept: "text/event-stream"
259
+ });
260
+ if (!response.ok) {
261
+ const message = await response.text();
262
+ throw new ExaError(
263
+ message || `Request failed with status code ${response.status}`,
264
+ response.status,
265
+ (/* @__PURE__ */ new Date()).toISOString(),
266
+ "/agent/runs"
267
+ );
268
+ }
269
+ return streamAgentEvents(response);
270
+ }
271
+ return this.request("", "POST", payload);
272
+ }
273
+ /**
274
+ * Get an Agent run by ID.
275
+ */
276
+ async get(runId) {
277
+ return this.request(`/${runId}`, "GET");
278
+ }
279
+ /**
280
+ * List Agent runs.
281
+ */
282
+ async list(options) {
283
+ const params = this.buildPaginationParams(options);
284
+ return this.request("", "GET", void 0, params);
285
+ }
286
+ /**
287
+ * Iterate through all Agent runs, handling pagination automatically.
288
+ */
289
+ async *listAll(options) {
290
+ let cursor = void 0;
291
+ const pageOptions = options ? { ...options } : {};
292
+ while (true) {
293
+ pageOptions.cursor = cursor;
294
+ const response = await this.list(pageOptions);
295
+ for (const run of response.data) {
296
+ yield run;
297
+ }
298
+ if (!response.hasMore || !response.nextCursor) {
299
+ break;
300
+ }
301
+ cursor = response.nextCursor;
302
+ }
303
+ }
304
+ /**
305
+ * Collect all Agent runs into an array.
306
+ */
307
+ async getAll(options) {
308
+ const runs = [];
309
+ for await (const run of this.listAll(options)) {
310
+ runs.push(run);
311
+ }
312
+ return runs;
313
+ }
314
+ /**
315
+ * Cancel a queued or running Agent run.
316
+ */
317
+ async cancel(runId) {
318
+ return this.request(`/${runId}/cancel`, "POST");
319
+ }
320
+ /**
321
+ * Delete a stored Agent run.
322
+ */
323
+ async delete(runId) {
324
+ return this.request(`/${runId}`, "DELETE");
325
+ }
326
+ /**
327
+ * Poll an Agent run until it reaches a terminal status.
328
+ */
329
+ async pollUntilFinished(runId, options) {
330
+ const pollInterval = options?.pollInterval ?? 1e3;
331
+ const timeoutMs = options?.timeoutMs ?? 60 * 60 * 1e3;
332
+ const startTime = Date.now();
333
+ while (true) {
334
+ const run = await this.get(runId);
335
+ if (run.status === "completed" || run.status === "failed" || run.status === "cancelled") {
336
+ return run;
337
+ }
338
+ if (Date.now() - startTime > timeoutMs) {
339
+ throw new Error(
340
+ `Polling timeout: Agent run ${runId} did not complete within ${timeoutMs}ms`
341
+ );
342
+ }
343
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
344
+ }
345
+ }
346
+ };
347
+ var AgentClient = class {
348
+ constructor(client) {
349
+ this.client = client;
350
+ this.runs = new AgentRunsClient(client);
351
+ }
352
+ };
353
+ var AgentBetaRunEventsClient = class extends AgentRunEventsClient {
354
+ /**
355
+ * List stored events for an Agent run.
356
+ *
357
+ * @deprecated Use exa.agent.runs.events instead.
358
+ */
359
+ async list(runId, options) {
360
+ const { betas, ...pagination } = options ?? {};
361
+ const params = this.buildPaginationParams(pagination);
362
+ return this.request(
363
+ `/${runId}/events`,
364
+ "GET",
365
+ void 0,
366
+ params,
367
+ headersForBetas(betas)
368
+ );
369
+ }
370
+ };
371
+ var AgentBetaRunsClient = class extends AgentRunsClient {
372
+ constructor(client) {
373
+ super(client);
374
+ this.events = new AgentBetaRunEventsClient(client);
375
+ }
376
+ async create(params) {
377
+ const { betas, ...createParams } = params;
378
+ const { stream, payload } = buildAgentRunPayload(
379
+ createParams
380
+ );
381
+ const headers = headersForBetas(betas);
382
+ if (stream) {
383
+ const response = await this.rawRequest("", "POST", payload, void 0, {
384
+ ...headers,
385
+ Accept: "text/event-stream"
386
+ });
387
+ if (!response.ok) {
388
+ const message = await response.text();
389
+ throw new ExaError(
390
+ message || `Request failed with status code ${response.status}`,
391
+ response.status,
392
+ (/* @__PURE__ */ new Date()).toISOString(),
393
+ "/agent/runs"
394
+ );
395
+ }
396
+ return streamAgentEvents(response);
397
+ }
398
+ return this.request(
399
+ "",
400
+ "POST",
401
+ payload,
402
+ void 0,
403
+ headers
404
+ );
405
+ }
406
+ async get(runId, options) {
407
+ return this.request(
408
+ `/${runId}`,
409
+ "GET",
410
+ void 0,
411
+ void 0,
412
+ headersForBetas(options?.betas)
413
+ );
414
+ }
415
+ async list(options) {
416
+ const { betas, ...pagination } = options ?? {};
417
+ const params = this.buildPaginationParams(pagination);
418
+ return this.request(
419
+ "",
420
+ "GET",
421
+ void 0,
422
+ params,
423
+ headersForBetas(betas)
424
+ );
425
+ }
426
+ async *listAll(options) {
427
+ let cursor = void 0;
428
+ const { betas, ...pagination } = options ?? {};
429
+ const pageOptions = { ...pagination };
430
+ while (true) {
431
+ pageOptions.cursor = cursor;
432
+ const response = await this.list({ ...pageOptions, betas });
433
+ for (const run of response.data) {
434
+ yield run;
435
+ }
436
+ if (!response.hasMore || !response.nextCursor) {
437
+ break;
438
+ }
439
+ cursor = response.nextCursor;
440
+ }
441
+ }
442
+ async getAll(options) {
443
+ const runs = [];
444
+ for await (const run of this.listAll(options)) {
445
+ runs.push(run);
446
+ }
447
+ return runs;
448
+ }
449
+ async cancel(runId, options) {
450
+ return this.request(
451
+ `/${runId}/cancel`,
452
+ "POST",
453
+ void 0,
454
+ void 0,
455
+ headersForBetas(options?.betas)
456
+ );
457
+ }
458
+ async delete(runId, options) {
459
+ return this.request(
460
+ `/${runId}`,
461
+ "DELETE",
462
+ void 0,
463
+ void 0,
464
+ headersForBetas(options?.betas)
465
+ );
466
+ }
467
+ async pollUntilFinished(runId, options) {
468
+ const pollInterval = options?.pollInterval ?? 1e3;
469
+ const timeoutMs = options?.timeoutMs ?? 60 * 60 * 1e3;
470
+ const startTime = Date.now();
471
+ const headers = headersForBetas(options?.betas);
472
+ while (true) {
473
+ const run = await this.request(
474
+ `/${runId}`,
475
+ "GET",
476
+ void 0,
477
+ void 0,
478
+ headers
479
+ );
480
+ if (run.status === "completed" || run.status === "failed" || run.status === "cancelled") {
481
+ return run;
482
+ }
483
+ if (Date.now() - startTime > timeoutMs) {
484
+ throw new Error(
485
+ `Polling timeout: Agent run ${runId} did not complete within ${timeoutMs}ms`
486
+ );
487
+ }
488
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
489
+ }
490
+ }
491
+ };
492
+ var AgentBetaClient = class extends AgentClient {
493
+ constructor(clientOrAgent) {
494
+ const client = clientOrAgent instanceof AgentClient ? clientOrAgent.client : clientOrAgent;
495
+ super(client);
496
+ this.runs = new AgentBetaRunsClient(client);
497
+ }
498
+ };
499
+ var BetaClient = class {
500
+ constructor(clientOrAgent) {
501
+ this.agent = new AgentBetaClient(clientOrAgent);
502
+ }
503
+ };
504
+
120
505
  // src/monitors/base.ts
121
506
  var SearchMonitorsBaseClient = class {
122
507
  constructor(client) {
@@ -302,18 +687,6 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
302
687
  }
303
688
  };
304
689
 
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
690
  // src/research/base.ts
318
691
  var ResearchBaseClient = class {
319
692
  constructor(client) {
@@ -1547,10 +1920,29 @@ var WebsetsClient = class extends WebsetsBaseClient {
1547
1920
  }
1548
1921
  };
1549
1922
 
1923
+ // src/agent/types.ts
1924
+ var AGENT_BETA_HEADER = "agent-2026-05-07";
1925
+
1550
1926
  // src/index.ts
1551
1927
  var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : fetch2;
1552
1928
  var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : Headers;
1553
1929
  var DEFAULT_MAX_CHARACTERS = 1e4;
1930
+ var NON_JSON_BODY_SNIPPET_LENGTH = 500;
1931
+ async function readResponseBody(response) {
1932
+ const text = await response.text();
1933
+ if (!text) {
1934
+ return { json: void 0, text };
1935
+ }
1936
+ try {
1937
+ return { json: JSON.parse(text), text };
1938
+ } catch {
1939
+ return { json: void 0, text };
1940
+ }
1941
+ }
1942
+ function truncateResponseBody(text) {
1943
+ const collapsed = text.replace(/\s+/g, " ").trim();
1944
+ return collapsed.length > NON_JSON_BODY_SNIPPET_LENGTH ? `${collapsed.slice(0, NON_JSON_BODY_SNIPPET_LENGTH)}\u2026` : collapsed;
1945
+ }
1554
1946
  var Exa2 = class {
1555
1947
  /**
1556
1948
  * Helper method to separate out the contents-specific options from the rest.
@@ -1566,6 +1958,7 @@ var Exa2 = class {
1566
1958
  livecrawl,
1567
1959
  livecrawlTimeout,
1568
1960
  maxAgeHours,
1961
+ // DEPRECATED FIELD: preserve legacy `context` only for backward compatibility.
1569
1962
  context,
1570
1963
  ...rest
1571
1964
  } = options;
@@ -1639,6 +2032,8 @@ var Exa2 = class {
1639
2032
  this.websets = new WebsetsClient(this);
1640
2033
  this.research = new ResearchClient(this);
1641
2034
  this.monitors = new SearchMonitorsClient(this);
2035
+ this.agent = new AgentClient(this);
2036
+ this.beta = new BetaClient(this.agent);
1642
2037
  }
1643
2038
  /**
1644
2039
  * Makes a request to the Exa API.
@@ -1681,7 +2076,18 @@ var Exa2 = class {
1681
2076
  body: body ? JSON.stringify(body) : void 0
1682
2077
  });
1683
2078
  if (!response.ok) {
1684
- const errorData = await response.json();
2079
+ const { json: json2, text: text2 } = await readResponseBody(response);
2080
+ if (!json2 || typeof json2 !== "object") {
2081
+ const snippet = truncateResponseBody(text2);
2082
+ const message2 = snippet ? `Request failed with status ${response.status}. Response body was not valid JSON: ${snippet}` : `Request failed with status ${response.status}.`;
2083
+ throw new ExaError(
2084
+ message2,
2085
+ response.status,
2086
+ (/* @__PURE__ */ new Date()).toISOString(),
2087
+ endpoint
2088
+ );
2089
+ }
2090
+ const errorData = json2;
1685
2091
  if (!errorData.statusCode) {
1686
2092
  errorData.statusCode = response.status;
1687
2093
  }
@@ -1706,9 +2112,18 @@ var Exa2 = class {
1706
2112
  if (contentType.includes("text/event-stream")) {
1707
2113
  return await this.parseSSEStream(response);
1708
2114
  }
1709
- return await response.json();
2115
+ const { json, text } = await readResponseBody(response);
2116
+ if (json === void 0 && text) {
2117
+ throw new ExaError(
2118
+ `Expected a JSON response but received a non-JSON body (status ${response.status}): ${truncateResponseBody(text)}`,
2119
+ response.status,
2120
+ (/* @__PURE__ */ new Date()).toISOString(),
2121
+ endpoint
2122
+ );
2123
+ }
2124
+ return json;
1710
2125
  }
1711
- async rawRequest(endpoint, method = "POST", body, queryParams) {
2126
+ async rawRequest(endpoint, method = "POST", body, queryParams, headers) {
1712
2127
  let url = this.baseURL + endpoint;
1713
2128
  if (queryParams) {
1714
2129
  const searchParams = new URLSearchParams();
@@ -1723,9 +2138,20 @@ var Exa2 = class {
1723
2138
  }
1724
2139
  url += `?${searchParams.toString()}`;
1725
2140
  }
2141
+ let combinedHeaders = {};
2142
+ if (this.headers instanceof HeadersImpl) {
2143
+ this.headers.forEach((value, key) => {
2144
+ combinedHeaders[key] = value;
2145
+ });
2146
+ } else {
2147
+ combinedHeaders = { ...this.headers };
2148
+ }
2149
+ if (headers) {
2150
+ combinedHeaders = { ...combinedHeaders, ...headers };
2151
+ }
1726
2152
  const response = await fetchImpl(url, {
1727
2153
  method,
1728
- headers: this.headers,
2154
+ headers: combinedHeaders,
1729
2155
  body: body ? JSON.stringify(body) : void 0
1730
2156
  });
1731
2157
  return response;
@@ -1756,6 +2182,7 @@ var Exa2 = class {
1756
2182
  });
1757
2183
  }
1758
2184
  /**
2185
+ * DEPRECATED: Use `search()` instead. This legacy wrapper will be removed in a future version.
1759
2186
  * @deprecated Use `search()` instead. The search method now returns text contents by default.
1760
2187
  *
1761
2188
  * Migration examples:
@@ -1763,7 +2190,7 @@ var Exa2 = class {
1763
2190
  * - `searchAndContents(query, { text: true })` → `search(query, { contents: { text: true } })`
1764
2191
  * - `searchAndContents(query, { summary: true })` → `search(query, { contents: { summary: true } })`
1765
2192
  *
1766
- * Performs a search with an Exa prompt-engineered query and returns the contents of the documents.
2193
+ * Compatibility wrapper for the legacy top-level contents options shape.
1767
2194
  *
1768
2195
  * @param {string} query - The query string.
1769
2196
  * @param {RegularSearchOptions & T} [options] - Additional search + contents options
@@ -1800,14 +2227,15 @@ var Exa2 = class {
1800
2227
  return await this.request("/findSimilar", "POST", { url, ...options });
1801
2228
  }
1802
2229
  /**
1803
- * @deprecated Use `findSimilar()` instead. The findSimilar method now returns text contents by default.
2230
+ * DEPRECATED: Use `search()` for new discovery flows instead. This legacy wrapper will be removed in a future version.
2231
+ * @deprecated Use `search()` for new discovery flows instead. There is no direct replacement for URL-based similarity.
1804
2232
  *
1805
2233
  * 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 } })`
2234
+ * - `findSimilarAndContents(url)` → `search(query)`
2235
+ * - `findSimilarAndContents(url, { text: true })` → `search(query, { contents: { text: true } })`
2236
+ * - `findSimilarAndContents(url, { summary: true })` → `search(query, { contents: { summary: true } })`
1809
2237
  *
1810
- * Finds similar links to the provided URL and returns the contents of the documents.
2238
+ * Compatibility wrapper for the legacy top-level contents options shape.
1811
2239
  * @param {string} url - The URL for which to find similar links.
1812
2240
  * @param {FindSimilarOptions & T} [options] - Additional options for finding similar links + contents.
1813
2241
  * @returns {Promise<SearchResponse<T>>} A list of similar search results, including requested contents.
@@ -2040,6 +2468,12 @@ var Exa2 = class {
2040
2468
  };
2041
2469
  var index_default = Exa2;
2042
2470
  export {
2471
+ AGENT_BETA_HEADER,
2472
+ AgentBetaClient,
2473
+ AgentClient,
2474
+ AgentRunEventsClient,
2475
+ AgentRunsClient,
2476
+ BetaClient,
2043
2477
  CreateEnrichmentParametersFormat,
2044
2478
  CreateImportParametersFormat,
2045
2479
  EventType,