exa-js 2.12.1 → 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.js CHANGED
@@ -30,6 +30,11 @@ 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
+ AgentRunEventsClient: () => AgentRunEventsClient,
36
+ AgentRunsClient: () => AgentRunsClient,
37
+ BetaClient: () => BetaClient,
33
38
  CreateEnrichmentParametersFormat: () => CreateEnrichmentParametersFormat,
34
39
  CreateImportParametersFormat: () => CreateImportParametersFormat,
35
40
  EventType: () => EventType,
@@ -76,7 +81,7 @@ var import_cross_fetch = __toESM(require("cross-fetch"));
76
81
  // package.json
77
82
  var package_default = {
78
83
  name: "exa-js",
79
- version: "2.12.1",
84
+ version: "2.13.0",
80
85
  description: "Exa SDK for Node.js and the browser",
81
86
  publishConfig: {
82
87
  access: "public"
@@ -189,6 +194,261 @@ var ExaError = class extends Error {
189
194
  }
190
195
  };
191
196
 
197
+ // src/zod-utils.ts
198
+ var import_zod = require("zod");
199
+ var import_zod_to_json_schema = require("zod-to-json-schema");
200
+ function isZodSchema(obj) {
201
+ return obj instanceof import_zod.ZodType;
202
+ }
203
+ function zodToJsonSchema(schema) {
204
+ return (0, import_zod_to_json_schema.zodToJsonSchema)(schema, {
205
+ $refStrategy: "none"
206
+ });
207
+ }
208
+
209
+ // src/agent/base.ts
210
+ var AgentBaseClient = class {
211
+ constructor(client) {
212
+ this.client = client;
213
+ }
214
+ async request(endpoint, betas, method = "POST", data, params, headers) {
215
+ if (!betas?.length) {
216
+ throw new Error("betas must include the Agent API beta identifier");
217
+ }
218
+ return this.client.request(
219
+ `/agent/runs${endpoint}`,
220
+ method,
221
+ data,
222
+ params,
223
+ {
224
+ "Exa-Beta": betas.join(","),
225
+ ...headers
226
+ }
227
+ );
228
+ }
229
+ async rawRequest(endpoint, betas, method = "POST", data, params, headers) {
230
+ if (!betas?.length) {
231
+ throw new Error("betas must include the Agent API beta identifier");
232
+ }
233
+ return this.client.rawRequest(
234
+ `/agent/runs${endpoint}`,
235
+ method,
236
+ data,
237
+ params,
238
+ {
239
+ "Exa-Beta": betas.join(","),
240
+ ...headers
241
+ }
242
+ );
243
+ }
244
+ buildPaginationParams(pagination) {
245
+ const params = {};
246
+ if (!pagination) return params;
247
+ if (pagination.cursor) params.cursor = pagination.cursor;
248
+ if (pagination.limit) params.limit = pagination.limit;
249
+ return params;
250
+ }
251
+ };
252
+
253
+ // src/agent/client.ts
254
+ async function* streamAgentEvents(response) {
255
+ if (!response.body) {
256
+ throw new Error("No response body for SSE stream");
257
+ }
258
+ const reader = response.body.getReader();
259
+ const decoder = new TextDecoder();
260
+ let buffer = "";
261
+ let doneReading = false;
262
+ const processPart = (part) => {
263
+ const event = {};
264
+ const dataLines = [];
265
+ for (const line of part.split("\n")) {
266
+ if (!line || !line.includes(":")) continue;
267
+ const [field, ...rest] = line.split(":");
268
+ const value = rest.join(":").replace(/^ /, "");
269
+ if (field === "id") event.id = value;
270
+ if (field === "event") event.event = value;
271
+ if (field === "data") dataLines.push(value);
272
+ }
273
+ if (!event.event || dataLines.length === 0) return null;
274
+ try {
275
+ event.data = JSON.parse(dataLines.join("\n"));
276
+ } catch {
277
+ event.data = { value: dataLines.join("\n") };
278
+ }
279
+ return event;
280
+ };
281
+ try {
282
+ while (true) {
283
+ const { done, value } = await reader.read();
284
+ if (done) {
285
+ doneReading = true;
286
+ break;
287
+ }
288
+ buffer += decoder.decode(value, { stream: true });
289
+ const parts = buffer.split("\n\n");
290
+ buffer = parts.pop() ?? "";
291
+ for (const part of parts) {
292
+ const event = processPart(part);
293
+ if (event) yield event;
294
+ }
295
+ }
296
+ if (buffer.trim()) {
297
+ const event = processPart(buffer.trim());
298
+ if (event) yield event;
299
+ }
300
+ } finally {
301
+ if (!doneReading) {
302
+ await reader.cancel();
303
+ }
304
+ reader.releaseLock();
305
+ }
306
+ }
307
+ var AgentRunEventsClient = class extends AgentBaseClient {
308
+ /**
309
+ * List stored events for an Agent run.
310
+ */
311
+ async list(runId, options) {
312
+ const params = this.buildPaginationParams(options);
313
+ return this.request(
314
+ `/${runId}/events`,
315
+ options.betas,
316
+ "GET",
317
+ void 0,
318
+ params
319
+ );
320
+ }
321
+ };
322
+ var AgentRunsClient = class extends AgentBaseClient {
323
+ constructor(client) {
324
+ super(client);
325
+ this.events = new AgentRunEventsClient(client);
326
+ }
327
+ async create(params) {
328
+ const { stream, outputSchema, betas, ...rest } = params;
329
+ let schema = outputSchema;
330
+ if (schema && isZodSchema(schema)) {
331
+ schema = zodToJsonSchema(schema);
332
+ }
333
+ const payload = { ...rest };
334
+ if (schema) {
335
+ payload.outputSchema = schema;
336
+ }
337
+ if (stream) {
338
+ const response = await this.rawRequest(
339
+ "",
340
+ betas,
341
+ "POST",
342
+ payload,
343
+ void 0,
344
+ {
345
+ Accept: "text/event-stream"
346
+ }
347
+ );
348
+ if (!response.ok) {
349
+ const message = await response.text();
350
+ throw new ExaError(
351
+ message || `Request failed with status code ${response.status}`,
352
+ response.status,
353
+ (/* @__PURE__ */ new Date()).toISOString(),
354
+ "/agent/runs"
355
+ );
356
+ }
357
+ return streamAgentEvents(response);
358
+ }
359
+ return this.request("", betas, "POST", payload);
360
+ }
361
+ /**
362
+ * Get an Agent run by ID.
363
+ */
364
+ async get(runId, options) {
365
+ return this.request(`/${runId}`, options.betas, "GET");
366
+ }
367
+ /**
368
+ * List Agent runs.
369
+ */
370
+ async list(options) {
371
+ const params = this.buildPaginationParams(options);
372
+ return this.request(
373
+ "",
374
+ options.betas,
375
+ "GET",
376
+ void 0,
377
+ params
378
+ );
379
+ }
380
+ /**
381
+ * Iterate through all Agent runs, handling pagination automatically.
382
+ */
383
+ async *listAll(options) {
384
+ let cursor = void 0;
385
+ const pageOptions = { ...options };
386
+ while (true) {
387
+ pageOptions.cursor = cursor;
388
+ const response = await this.list(pageOptions);
389
+ for (const run of response.data) {
390
+ yield run;
391
+ }
392
+ if (!response.hasMore || !response.nextCursor) {
393
+ break;
394
+ }
395
+ cursor = response.nextCursor;
396
+ }
397
+ }
398
+ /**
399
+ * Collect all Agent runs into an array.
400
+ */
401
+ async getAll(options) {
402
+ const runs = [];
403
+ for await (const run of this.listAll(options)) {
404
+ runs.push(run);
405
+ }
406
+ return runs;
407
+ }
408
+ /**
409
+ * Cancel a queued or running Agent run.
410
+ */
411
+ async cancel(runId, options) {
412
+ return this.request(`/${runId}/cancel`, options.betas, "POST");
413
+ }
414
+ /**
415
+ * Delete a stored Agent run.
416
+ */
417
+ async delete(runId, options) {
418
+ return this.request(`/${runId}`, options.betas, "DELETE");
419
+ }
420
+ /**
421
+ * Poll an Agent run until it reaches a terminal status.
422
+ */
423
+ async pollUntilFinished(runId, options) {
424
+ const pollInterval = options?.pollInterval ?? 1e3;
425
+ const timeoutMs = options?.timeoutMs ?? 60 * 60 * 1e3;
426
+ const startTime = Date.now();
427
+ while (true) {
428
+ const run = await this.get(runId, { betas: options.betas });
429
+ if (run.status === "completed" || run.status === "failed" || run.status === "cancelled") {
430
+ return run;
431
+ }
432
+ if (Date.now() - startTime > timeoutMs) {
433
+ throw new Error(
434
+ `Polling timeout: Agent run ${runId} did not complete within ${timeoutMs}ms`
435
+ );
436
+ }
437
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
438
+ }
439
+ }
440
+ };
441
+ var AgentBetaClient = class {
442
+ constructor(client) {
443
+ this.runs = new AgentRunsClient(client);
444
+ }
445
+ };
446
+ var BetaClient = class {
447
+ constructor(client) {
448
+ this.agent = new AgentBetaClient(client);
449
+ }
450
+ };
451
+
192
452
  // src/monitors/base.ts
193
453
  var SearchMonitorsBaseClient = class {
194
454
  constructor(client) {
@@ -374,18 +634,6 @@ var SearchMonitorsClient = class extends SearchMonitorsBaseClient {
374
634
  }
375
635
  };
376
636
 
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
637
  // src/research/base.ts
390
638
  var ResearchBaseClient = class {
391
639
  constructor(client) {
@@ -1619,6 +1867,9 @@ var WebsetsClient = class extends WebsetsBaseClient {
1619
1867
  }
1620
1868
  };
1621
1869
 
1870
+ // src/agent/types.ts
1871
+ var AGENT_BETA_HEADER = "agent-2026-05-07";
1872
+
1622
1873
  // src/index.ts
1623
1874
  var fetchImpl = typeof global !== "undefined" && global.fetch ? global.fetch : import_cross_fetch.default;
1624
1875
  var HeadersImpl = typeof global !== "undefined" && global.Headers ? global.Headers : import_cross_fetch.Headers;
@@ -1638,6 +1889,7 @@ var Exa2 = class {
1638
1889
  livecrawl,
1639
1890
  livecrawlTimeout,
1640
1891
  maxAgeHours,
1892
+ // DEPRECATED FIELD: preserve legacy `context` only for backward compatibility.
1641
1893
  context,
1642
1894
  ...rest
1643
1895
  } = options;
@@ -1711,6 +1963,7 @@ var Exa2 = class {
1711
1963
  this.websets = new WebsetsClient(this);
1712
1964
  this.research = new ResearchClient(this);
1713
1965
  this.monitors = new SearchMonitorsClient(this);
1966
+ this.beta = new BetaClient(this);
1714
1967
  }
1715
1968
  /**
1716
1969
  * Makes a request to the Exa API.
@@ -1780,7 +2033,7 @@ var Exa2 = class {
1780
2033
  }
1781
2034
  return await response.json();
1782
2035
  }
1783
- async rawRequest(endpoint, method = "POST", body, queryParams) {
2036
+ async rawRequest(endpoint, method = "POST", body, queryParams, headers) {
1784
2037
  let url = this.baseURL + endpoint;
1785
2038
  if (queryParams) {
1786
2039
  const searchParams = new URLSearchParams();
@@ -1795,9 +2048,20 @@ var Exa2 = class {
1795
2048
  }
1796
2049
  url += `?${searchParams.toString()}`;
1797
2050
  }
2051
+ let combinedHeaders = {};
2052
+ if (this.headers instanceof HeadersImpl) {
2053
+ this.headers.forEach((value, key) => {
2054
+ combinedHeaders[key] = value;
2055
+ });
2056
+ } else {
2057
+ combinedHeaders = { ...this.headers };
2058
+ }
2059
+ if (headers) {
2060
+ combinedHeaders = { ...combinedHeaders, ...headers };
2061
+ }
1798
2062
  const response = await fetchImpl(url, {
1799
2063
  method,
1800
- headers: this.headers,
2064
+ headers: combinedHeaders,
1801
2065
  body: body ? JSON.stringify(body) : void 0
1802
2066
  });
1803
2067
  return response;
@@ -1828,6 +2092,7 @@ var Exa2 = class {
1828
2092
  });
1829
2093
  }
1830
2094
  /**
2095
+ * DEPRECATED: Use `search()` instead. This legacy wrapper will be removed in a future version.
1831
2096
  * @deprecated Use `search()` instead. The search method now returns text contents by default.
1832
2097
  *
1833
2098
  * Migration examples:
@@ -1835,7 +2100,7 @@ var Exa2 = class {
1835
2100
  * - `searchAndContents(query, { text: true })` → `search(query, { contents: { text: true } })`
1836
2101
  * - `searchAndContents(query, { summary: true })` → `search(query, { contents: { summary: true } })`
1837
2102
  *
1838
- * Performs a search with an Exa prompt-engineered query and returns the contents of the documents.
2103
+ * Compatibility wrapper for the legacy top-level contents options shape.
1839
2104
  *
1840
2105
  * @param {string} query - The query string.
1841
2106
  * @param {RegularSearchOptions & T} [options] - Additional search + contents options
@@ -1872,14 +2137,15 @@ var Exa2 = class {
1872
2137
  return await this.request("/findSimilar", "POST", { url, ...options });
1873
2138
  }
1874
2139
  /**
1875
- * @deprecated Use `findSimilar()` instead. The findSimilar method now returns text contents by default.
2140
+ * DEPRECATED: Use `search()` for new discovery flows instead. This legacy wrapper will be removed in a future version.
2141
+ * @deprecated Use `search()` for new discovery flows instead. There is no direct replacement for URL-based similarity.
1876
2142
  *
1877
2143
  * 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 } })`
2144
+ * - `findSimilarAndContents(url)` → `search(query)`
2145
+ * - `findSimilarAndContents(url, { text: true })` → `search(query, { contents: { text: true } })`
2146
+ * - `findSimilarAndContents(url, { summary: true })` → `search(query, { contents: { summary: true } })`
1881
2147
  *
1882
- * Finds similar links to the provided URL and returns the contents of the documents.
2148
+ * Compatibility wrapper for the legacy top-level contents options shape.
1883
2149
  * @param {string} url - The URL for which to find similar links.
1884
2150
  * @param {FindSimilarOptions & T} [options] - Additional options for finding similar links + contents.
1885
2151
  * @returns {Promise<SearchResponse<T>>} A list of similar search results, including requested contents.
@@ -2113,6 +2379,11 @@ var Exa2 = class {
2113
2379
  var index_default = Exa2;
2114
2380
  // Annotate the CommonJS export names for ESM import in node:
2115
2381
  0 && (module.exports = {
2382
+ AGENT_BETA_HEADER,
2383
+ AgentBetaClient,
2384
+ AgentRunEventsClient,
2385
+ AgentRunsClient,
2386
+ BetaClient,
2116
2387
  CreateEnrichmentParametersFormat,
2117
2388
  CreateImportParametersFormat,
2118
2389
  EventType,