@howells/fieldwork-sdk 0.11.0 → 0.12.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.
Files changed (47) hide show
  1. package/README.md +72 -15
  2. package/dist/{adapter-DWYJys20.js → adapter-CBSAfErv.js} +1 -1
  3. package/dist/adapter-J2yatZJ0.d.ts +73 -0
  4. package/dist/best-CO9liYDa.js +1436 -0
  5. package/dist/brave.d.ts +7 -6
  6. package/dist/brave.js +180 -173
  7. package/dist/browserbase.d.ts +4 -3
  8. package/dist/browserbase.js +185 -170
  9. package/dist/{document-DMIUCoDA.js → document-BSCwJgBM.js} +4 -4
  10. package/dist/{download-CP8noBdX.js → download-kuTqNnuZ.js} +1 -1
  11. package/dist/{adapter-B8kAAAgF.d.ts → errors-gMtejKHc.d.ts} +87 -69
  12. package/dist/exa.d.ts +18 -11
  13. package/dist/exa.js +306 -275
  14. package/dist/fieldwork-D7npPoUf.d.ts +35 -0
  15. package/dist/firecrawl.d.ts +4 -3
  16. package/dist/firecrawl.js +450 -417
  17. package/dist/{parse-Q7H4mrnO.js → http-CJcvTPnE.js} +223 -225
  18. package/dist/image.d.ts +253 -0
  19. package/dist/image.js +1 -0
  20. package/dist/index.d.ts +6 -7
  21. package/dist/index.js +66 -82
  22. package/dist/{job-DnavRq_s.js → job-JLEpszjr.js} +9 -9
  23. package/dist/kernel.d.ts +20 -2
  24. package/dist/kernel.js +65 -19
  25. package/dist/llamaparse.d.ts +3 -2
  26. package/dist/llamaparse.js +16 -16
  27. package/dist/parallel.d.ts +8 -8
  28. package/dist/parallel.js +423 -389
  29. package/dist/path-DO2llIdp.js +10 -0
  30. package/dist/perplexity.d.ts +6 -5
  31. package/dist/perplexity.js +21 -21
  32. package/dist/reducto.d.ts +3 -2
  33. package/dist/reducto.js +14 -14
  34. package/dist/{schema-CAPSX7yQ.d.ts → schema-C9xzRkKJ.d.ts} +17 -6
  35. package/dist/{schema--iU4AXSM.js → schema-CJXFAZ-x.js} +12 -3
  36. package/dist/serpapi.d.ts +3 -3
  37. package/dist/serpapi.js +176 -171
  38. package/dist/tavily.d.ts +4 -3
  39. package/dist/tavily.js +247 -234
  40. package/dist/tools.d.ts +76 -15
  41. package/dist/tools.js +351 -33
  42. package/dist/{util-DFUXQX6v.js → util-LvME_uOj.js} +35 -11
  43. package/package.json +6 -1
  44. package/dist/fieldwork-BrfoehvG.d.ts +0 -113
  45. package/dist/path-DL5P8XH2.js +0 -17
  46. package/dist/util-DhYr1OS3.d.ts +0 -1
  47. package/dist/{errors-DkFJysIM.js → errors-gpxg6Tnh.js} +5 -5
package/dist/exa.js CHANGED
@@ -1,10 +1,10 @@
1
- import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
- import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-Q7H4mrnO.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
- import { a as compact, c as parseJson, d as record, i as citationsOf, m as uniqueCitations, o as hours, p as requireJobId, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
- import * as z from "zod/mini";
1
+ import { t as defineAdapter } from "./adapter-CBSAfErv.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-gpxg6Tnh.js";
3
+ import { C as optionalStructure, E as warningEntry, O as withOriginal, S as optionalStringOrNumber, _ as optionalId, b as optionalScalar, c as anything, d as looseObject, h as optionalBoolean, i as segment, l as arrayOf, p as optionalAnyString, r as requireKey, s as Source, t as createRawClient, u as both, v as optionalNumber, x as optionalString } from "./http-CJcvTPnE.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-JLEpszjr.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-CJXFAZ-x.js";
6
+ import { a as compact, c as parseJson, f as requireJobId, i as citationsOf, o as hours, p as uniqueCitations, s as meta, t as callSettings } from "./util-LvME_uOj.js";
7
+ import * as z$1 from "zod/mini";
8
8
  const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
9
9
  /** The search types that take `additionalQueries`. */
10
10
  const DEEP_TYPES = /* @__PURE__ */ new Set([
@@ -31,7 +31,7 @@ const responseMeta = (body, warnings) => meta({
31
31
  const summaryOption = (summary, schema) => {
32
32
  if (summary === void 0 || summary === false) return schema ? compact({ schema }) : void 0;
33
33
  return compact({
34
- query: typeof summary === "object" ? summary.query : void 0,
34
+ query: summary === true ? void 0 : summary.query,
35
35
  schema
36
36
  });
37
37
  };
@@ -51,19 +51,24 @@ const checkSearch = (o) => {
51
51
  const dated = o.publishedAfter !== void 0 || o.publishedBefore !== void 0;
52
52
  if ((o.category === "company" || o.category === "people") && dated) throw invalidRequest("exa", `category "${o.category}" does not accept publishedAfter or publishedBefore`);
53
53
  if (o.category === "people" && o.excludeDomains !== void 0) throw invalidRequest("exa", "category \"people\" does not accept excludeDomains");
54
+ if (o.highlights === false && o.maxCharsPerResult !== void 0) throw invalidRequest("exa", "maxCharsPerResult cannot be used with highlights: false");
54
55
  };
55
56
  /** Exa's `highlights` option: `true`, or the query and length limit that steer the passages. */
56
- const highlightsOption = (highlights) => typeof highlights === "object" ? compact({
57
- maxCharacters: highlights.maxCharacters,
58
- query: highlights.query
59
- }) : true;
57
+ const highlightsOption = (highlights, maxCharsPerResult) => {
58
+ const query = highlights === true || highlights === void 0 ? void 0 : highlights.query;
59
+ const options = compact({
60
+ maxCharacters: maxCharsPerResult,
61
+ query
62
+ });
63
+ return Object.keys(options).length > 0 ? options : true;
64
+ };
60
65
  /**
61
66
  * The `contents` of a search request. Highlights are on unless `highlights` is
62
67
  * false. Undefined when nothing is asked for.
63
68
  */
64
69
  const searchContents = (o) => {
65
70
  const contents = compact({
66
- highlights: o.highlights === false ? void 0 : highlightsOption(o.highlights),
71
+ highlights: o.highlights === false ? void 0 : highlightsOption(o.highlights, o.maxCharsPerResult),
67
72
  maxAgeHours: hours(o.maxAge),
68
73
  summary: summaryOption(o.summary),
69
74
  text: o.content === true ? true : void 0
@@ -97,8 +102,9 @@ const generatedAnswer = (output) => {
97
102
  };
98
103
  /**
99
104
  * The `/contents` options for a read. Page text is always requested (capped
100
- * when `maxCharacters` is set); `query` asks for highlights; links and image
101
- * links default to 100 each, and `0` leaves them out.
105
+ * when `maxContentChars` is set); `query` or `maxCharsPerResult` asks for
106
+ * highlights; links and image links default to 100 each, and `0` leaves them
107
+ * out.
102
108
  */
103
109
  const readBody = (o) => {
104
110
  const links = o.linkLimit ?? 100;
@@ -107,15 +113,27 @@ const readBody = (o) => {
107
113
  imageLinks: images > 0 ? images : void 0,
108
114
  links: links > 0 ? links : void 0
109
115
  });
116
+ const highlights = compact({
117
+ maxCharacters: o.maxCharsPerResult,
118
+ query: o.query === void 0 || o.query === "" ? void 0 : o.query
119
+ });
110
120
  return compact({
111
121
  extras: Object.keys(extras).length > 0 ? extras : void 0,
112
- highlights: o.query === void 0 || o.query === "" ? void 0 : { query: o.query },
122
+ highlights: Object.keys(highlights).length > 0 ? highlights : void 0,
113
123
  maxAgeHours: hours(o.maxAge),
114
124
  snapshotAsOf: o.snapshotAsOf,
115
125
  summary: summaryOption(o.summary),
116
- text: o.maxCharacters === void 0 ? true : { maxCharacters: o.maxCharacters }
126
+ text: o.maxContentChars === void 0 ? true : { maxCharacters: o.maxContentChars }
117
127
  });
118
128
  };
129
+ /** The `/contents` options for `extract`: a structured summary of the page, and its cache age. */
130
+ const extractBody = (o) => compact({
131
+ maxAgeHours: hours(o.maxAge),
132
+ summary: compact({
133
+ query: o.prompt,
134
+ schema: jsonSchemaOf(o.schema, "draft-07", "exa")
135
+ })
136
+ });
119
137
  /**
120
138
  * The error code for a URL Exa failed to read. Exa reports this per URL in the
121
139
  * response, not as an HTTP error: its `tag` decides first, then the HTTP
@@ -198,6 +216,15 @@ const runState = (id, entry) => jobState("exa", id, RUN_STATES, {
198
216
  original: entry.original,
199
217
  value: entry.value.status
200
218
  }) === "running" ? void 0 : entry;
219
+ /** The `JobFailed` error for a run that ended without output: Exa's error, else its stop reason. */
220
+ const runFailure = (id, entry, status) => {
221
+ const { error, stopReason } = entry.value;
222
+ const detail = error.message === void 0 ? stopReason : `${error.code ?? error.type ?? "error"}: ${error.message}`;
223
+ return new FieldworkError("JobFailed", `exa research run ${id} ended ${status}${detail === void 0 ? "" : ` (${detail})`}`, {
224
+ cause: entry.original,
225
+ provider: "exa"
226
+ });
227
+ };
201
228
  /**
202
229
  * The result of a finished run. A run that did not complete and has no output
203
230
  * throws `JobFailed` with Exa's error, and so does a completed run without
@@ -210,14 +237,7 @@ const researchResult = (id, entry, structured) => {
210
237
  const run = entry.value;
211
238
  const { stopReason } = run;
212
239
  const status = run.status ?? "unknown";
213
- if (status !== "completed" && !hasOutput(run, structured)) {
214
- const { error } = run;
215
- const detail = error.message === void 0 ? stopReason : `${error.code ?? error.type ?? "error"}: ${error.message}`;
216
- throw new FieldworkError("JobFailed", `exa research run ${id} ended ${status}${detail === void 0 ? "" : ` (${detail})`}`, {
217
- cause: entry.original,
218
- provider: "exa"
219
- });
220
- }
240
+ if (status !== "completed" && !hasOutput(run, structured)) throw runFailure(id, entry, status);
221
241
  const { output } = run;
222
242
  const fields = output.grounding.map((grounding) => compact({
223
243
  citations: citationsOf(grounding.citations),
@@ -242,8 +262,9 @@ const researchResult = (id, entry, structured) => {
242
262
  };
243
263
  /** Exa's trigger period for an interval schedule: `hour`, `day` and `week` become `1h`, `1d` and `7d`. Exa has no cron. */
244
264
  const intervalPeriod = (schedule) => {
245
- const { every } = record(schedule);
246
- if (typeof every !== "string") throw invalidRequest("exa", "monitors run on an interval of whole hours or days; Exa has no cron");
265
+ const parsed = z$1.safeParse(z$1.string(), schedule.every);
266
+ if (!parsed.success) throw invalidRequest("exa", "monitors run on an interval of whole hours or days; Exa has no cron");
267
+ const every = parsed.data;
247
268
  let value = every;
248
269
  if (every === "hour") value = "1h";
249
270
  else if (every === "day") value = "1d";
@@ -301,15 +322,15 @@ looseObject(metered);
301
322
  const Result = looseObject({
302
323
  author: optionalString,
303
324
  extras: looseObject({
304
- imageLinks: arrayOf(z.string()),
305
- links: arrayOf(z.string())
325
+ imageLinks: arrayOf(z$1.string()),
326
+ links: arrayOf(z$1.string())
306
327
  }),
307
328
  favicon: optionalString,
308
- highlights: arrayOf(z.string()),
329
+ highlights: arrayOf(z$1.string()),
309
330
  image: optionalString,
310
331
  publishedDate: optionalString,
311
332
  score: optionalNumber,
312
- summary: z.pipe(both(optionalString, anything), z.transform(({ first, second }) => ({
333
+ summary: z$1.pipe(both(optionalString, anything), z$1.transform(({ first, second }) => ({
313
334
  text: first,
314
335
  value: second
315
336
  }))),
@@ -324,7 +345,7 @@ const UrlStatus = looseObject({
324
345
  tag: optionalString
325
346
  }),
326
347
  id: optionalString,
327
- status: z.pipe(both(anything, optionalString), z.transform(({ first, second }) => ({
348
+ status: z$1.pipe(both(anything, optionalString), z$1.transform(({ first, second }) => ({
328
349
  text: second,
329
350
  value: first
330
351
  })))
@@ -338,14 +359,14 @@ const ContentsResponse = looseObject({
338
359
  /** A generated answer: text, or the structured value the output schema asked for. */
339
360
  const AnswerResponse = looseObject({
340
361
  ...metered,
341
- answer: z.pipe(both(optionalString, optionalStructure), z.transform(({ first, second }) => ({
362
+ answer: z$1.pipe(both(optionalString, optionalStructure), z$1.transform(({ first, second }) => ({
342
363
  structure: second,
343
364
  text: first
344
365
  }))),
345
366
  citations: arrayOf(Source)
346
367
  });
347
368
  /** A string, or any other value kept as it arrived. */
348
- const Content = z.pipe(both(optionalAnyString, anything), z.transform(({ first, second }) => ({
369
+ const Content = z$1.pipe(both(optionalAnyString, anything), z$1.transform(({ first, second }) => ({
349
370
  text: first,
350
371
  value: second
351
372
  })));
@@ -425,9 +446,253 @@ const RunsPage = looseObject({
425
446
  hasMore: optionalBoolean,
426
447
  nextCursor: optionalString
427
448
  });
449
+ // src/adapters/exa/monitor.ts
450
+ /**
451
+ * Every monitor, one page after another: each page is requested only once the
452
+ * one before it names its cursor. A cursor seen before ends the listing.
453
+ */
454
+ const listMonitors = async (raw, call, cursor, seen) => {
455
+ const page = z$1.parse(MonitorsPage, await raw.request("GET", "/monitors", {
456
+ ...call,
457
+ query: {
458
+ cursor,
459
+ limit: 100
460
+ }
461
+ }));
462
+ const monitors = page.data.map((entry) => monitorInfo(entry));
463
+ const next = page.nextCursor;
464
+ if (page.hasMore !== true || next === void 0 || seen.has(next)) return monitors;
465
+ return [...monitors, ...await listMonitors(raw, call, next, /* @__PURE__ */ new Set([...seen, next]))];
466
+ };
467
+ /** Exa's monitor methods, calling through `raw`. */
468
+ const exaMonitor = (raw) => ({
469
+ async create(options) {
470
+ const { call, rest: o } = callSettings(options);
471
+ const every = period(o.schedule);
472
+ const body = compact({
473
+ metadata: o.metadata,
474
+ name: o.name,
475
+ outputSchema: o.outputSchema,
476
+ search: compact({
477
+ contents: o.content === true ? { text: true } : void 0,
478
+ excludeDomains: o.excludeDomains,
479
+ includeDomains: o.includeDomains,
480
+ numResults: o.limit,
481
+ query: o.query
482
+ }),
483
+ trigger: every === void 0 ? void 0 : {
484
+ period: every,
485
+ type: "interval"
486
+ },
487
+ webhook: compact({
488
+ events: o.webhookEvents,
489
+ url: o.webhookUrl
490
+ })
491
+ });
492
+ return monitorInfo(z$1.parse(MonitorEntry, await raw.request("POST", "/monitors", {
493
+ creates: true,
494
+ ...call,
495
+ body
496
+ })));
497
+ },
498
+ async delete(id, options = {}) {
499
+ const { call } = callSettings(options);
500
+ await raw.request("DELETE", `/monitors/${segment(id)}`, call);
501
+ },
502
+ async events(id, options = {}) {
503
+ const { call, rest: o } = callSettings(options);
504
+ const response = await raw.request("GET", `/monitors/${segment(id)}/runs`, {
505
+ ...call,
506
+ query: {
507
+ cursor: o.cursor,
508
+ limit: o.limit
509
+ }
510
+ });
511
+ const page = z$1.parse(RunsPage, response);
512
+ return compact({
513
+ events: page.data.map((entry) => monitorEvent(entry)),
514
+ next: page.hasMore === true ? page.nextCursor : void 0,
515
+ raw: response
516
+ });
517
+ },
518
+ async get(id, options = {}) {
519
+ const { call } = callSettings(options);
520
+ return monitorInfo(z$1.parse(MonitorEntry, await raw.request("GET", `/monitors/${segment(id)}`, call)));
521
+ },
522
+ async list(options = {}) {
523
+ const { call } = callSettings(options);
524
+ return await listMonitors(raw, call, void 0, /* @__PURE__ */ new Set());
525
+ }
526
+ });
428
527
  // src/adapters/exa.ts
528
+ /** Calls `/contents` for these URLs. A URL Exa could not read is in `statuses`, not an error. */
529
+ const fetchContents = async (raw, urls, body, call) => {
530
+ const response = await raw.request("POST", "/contents", {
531
+ ...call,
532
+ body: {
533
+ urls,
534
+ ...body
535
+ }
536
+ });
537
+ return {
538
+ body: z$1.parse(ContentsResponse, response),
539
+ response
540
+ };
541
+ };
542
+ /** Reads one URL. Throws when Exa reports a failure for it or returns no result. */
543
+ const readOne = async (raw, url, body, call) => {
544
+ const { body: parsed, response } = await fetchContents(raw, [url], body, call);
545
+ const [failed] = failedStatuses(parsed.statuses);
546
+ if (failed) {
547
+ const { httpStatusCode, tag } = failed.error;
548
+ throw new FieldworkError(failureCode(tag, httpStatusCode), `exa could not read ${url}: ${statusReason(failed)}`, {
549
+ cause: response,
550
+ provider: "exa",
551
+ status: httpStatusCode
552
+ });
553
+ }
554
+ const [result] = parsed.results;
555
+ if (result === void 0) throw new FieldworkError("ProviderError", `exa returned no content for ${url}`, {
556
+ cause: response,
557
+ provider: "exa"
558
+ });
559
+ return {
560
+ body: parsed,
561
+ response,
562
+ result: result.value
563
+ };
564
+ };
565
+ /** Search and answer: one request each. */
566
+ const searching = (raw) => ({
567
+ async answer(question, options = {}) {
568
+ const { call, rest: o } = callSettings(options);
569
+ const response = await raw.request("POST", "/answer", {
570
+ ...call,
571
+ body: compact({
572
+ model: o.model,
573
+ outputSchema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema, "draft-07"),
574
+ query: question,
575
+ systemPrompt: o.systemPrompt,
576
+ userLocation: o.country === void 0 || o.country === "" ? void 0 : { country: o.country }
577
+ })
578
+ });
579
+ const body = z$1.parse(AnswerResponse, response);
580
+ const { structure, text } = body.answer;
581
+ const answer = structure === void 0 ? text : JSON.stringify(structure);
582
+ if (answer === void 0 || answer === "") throw new FieldworkError("ProviderError", "exa returned no answer text", {
583
+ cause: response,
584
+ provider: "exa"
585
+ });
586
+ return compact({
587
+ answer,
588
+ citations: uniqueCitations(citationsOf(body.citations)),
589
+ meta: responseMeta(body),
590
+ output: structure === void 0 ? void 0 : await checkOutput(o.schema, structure, { provider: "exa" }),
591
+ raw: response
592
+ });
593
+ },
594
+ async search(query, options = {}) {
595
+ const { call, rest: o } = callSettings(options);
596
+ checkSearch(o);
597
+ const response = await raw.request("POST", "/search", {
598
+ ...call,
599
+ body: compact({
600
+ additionalQueries: o.additionalQueries,
601
+ category: o.category,
602
+ contents: searchContents(o),
603
+ endPublishedDate: dateTime(o.publishedBefore, true),
604
+ excludeDomains: o.excludeDomains,
605
+ includeDomains: o.includeDomains,
606
+ moderation: o.moderation,
607
+ numResults: o.limit,
608
+ outputSchema: o.outputSchema,
609
+ query,
610
+ startPublishedDate: dateTime(o.publishedAfter, false),
611
+ systemPrompt: o.systemPrompt,
612
+ type: o.type,
613
+ userLocation: o.country === void 0 || o.country === "" ? void 0 : { country: o.country }
614
+ })
615
+ });
616
+ const body = z$1.parse(SearchResponse, response);
617
+ return compact({
618
+ answer: generatedAnswer(body.output),
619
+ meta: responseMeta(body, [...body.warnings, ...body.notices].filter((note) => note !== void 0)),
620
+ raw: response,
621
+ results: body.results.map((item) => searchResult(item))
622
+ });
623
+ }
624
+ });
625
+ /** Read, readMany and extract, all through `/contents`. */
626
+ const reading = (raw) => ({
627
+ async extract(url, options) {
628
+ const { call, rest: o } = callSettings(options);
629
+ const { body, response, result } = await readOne(raw, url, extractBody(o), call);
630
+ const { value: summary } = result.summary;
631
+ if (summary === void 0) throw new FieldworkError("ProviderError", `exa returned no structured summary for ${url}`, {
632
+ cause: response,
633
+ provider: "exa"
634
+ });
635
+ return compact({
636
+ data: await checkOutput(o.schema, parseJson("exa", summary), { provider: "exa" }),
637
+ meta: responseMeta(body),
638
+ raw: response
639
+ });
640
+ },
641
+ async read(url, options = {}) {
642
+ const { call, rest: o } = callSettings(options);
643
+ const { body, response, result } = await readOne(raw, url, readBody(o), call);
644
+ return compact({
645
+ ...pageFrom(url, result),
646
+ meta: responseMeta(body),
647
+ raw: response
648
+ });
649
+ },
650
+ async readMany(urls, options = {}) {
651
+ const { call, rest: o } = callSettings(options);
652
+ if (urls.length === 0) throw invalidRequest("exa", "readMany needs at least one URL");
653
+ if (urls.length > 100) throw invalidRequest("exa", `readMany reads at most 100 URLs per call`);
654
+ const { body, response } = await fetchContents(raw, urls, readBody(o), call);
655
+ return {
656
+ failed: failedStatuses(body.statuses).map((status) => ({
657
+ error: statusReason(status),
658
+ url: status.id ?? ""
659
+ })),
660
+ meta: responseMeta(body),
661
+ pages: body.results.map((entry) => ({
662
+ ...pageFrom("", entry.value),
663
+ raw: entry.original
664
+ })),
665
+ raw: response
666
+ };
667
+ }
668
+ });
669
+ /** Research: a run Exa's agent works through, polled to its result. */
670
+ const researching = (raw) => ({ async research(question, options = {}) {
671
+ const { call, rest: o } = callSettings(options);
672
+ checkResearch(o);
673
+ return await runJob("exa", {
674
+ check: async (id, request) => runState(id, z$1.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request))),
675
+ finish: async (run, id) => {
676
+ const { outputSchema } = run.value.request;
677
+ const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
678
+ const result = researchResult(id, run, structured);
679
+ return {
680
+ ...result,
681
+ output: await checkOutput(o.schema, result.output, { provider: "exa" })
682
+ };
683
+ },
684
+ start: async () => await startJob(raw, "/agent/runs", {
685
+ ...call,
686
+ body: researchBody(question, o)
687
+ }, RunStart, (reply) => reply.id)
688
+ }, {
689
+ ...call,
690
+ interval: o.interval,
691
+ resume: o.resume
692
+ });
693
+ } });
429
694
  /**
430
- * An adapter for Exa: search, read, readMany, extract, answer, research and monitor. Pass it to `new Fieldwork({ adapter })`.
695
+ * An adapter for Exa: search, read, readMany, extract, answer, research and monitor. Pass it to `fieldwork({ adapter })`.
431
696
  *
432
697
  * Throws `Unauthorized` when neither `apiKey` nor `EXA_API_KEY` is set.
433
698
  */
@@ -439,249 +704,15 @@ const exa = (config = {}) => {
439
704
  provider: "exa",
440
705
  retries: config.retries
441
706
  });
442
- /** Calls `/contents` for these URLs. A URL Exa could not read is in `statuses`, not an error. */
443
- const fetchContents = async (urls, body, call) => {
444
- const response = await raw.request("POST", "/contents", {
445
- ...call,
446
- body: {
447
- urls,
448
- ...body
449
- }
450
- });
451
- return {
452
- body: z.parse(ContentsResponse, response),
453
- response
454
- };
455
- };
456
- /** Reads one URL. Throws when Exa reports a failure for it or returns no result. */
457
- const readOne = async (url, body, call) => {
458
- const { body: parsed, response } = await fetchContents([url], body, call);
459
- const [failed] = failedStatuses(parsed.statuses);
460
- if (failed) {
461
- const { httpStatusCode, tag } = failed.error;
462
- throw new FieldworkError(failureCode(tag, httpStatusCode), `exa could not read ${url}: ${statusReason(failed)}`, {
463
- cause: response,
464
- provider: "exa",
465
- status: httpStatusCode
466
- });
467
- }
468
- const [result] = parsed.results;
469
- if (result === void 0) throw new FieldworkError("ProviderError", `exa returned no content for ${url}`, {
470
- cause: response,
471
- provider: "exa"
472
- });
473
- return {
474
- body: parsed,
475
- response,
476
- result: result.value
477
- };
707
+ const operations = {
708
+ ...searching(raw),
709
+ ...reading(raw),
710
+ ...researching(raw),
711
+ monitor: exaMonitor(raw)
478
712
  };
479
713
  return defineAdapter({
480
714
  name: "exa",
481
- operations: {
482
- async answer(question, options) {
483
- const { call, rest: o } = callSettings(options);
484
- const response = await raw.request("POST", "/answer", {
485
- ...call,
486
- body: compact({
487
- model: o.model,
488
- outputSchema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema, "draft-07"),
489
- query: question,
490
- systemPrompt: o.systemPrompt,
491
- userLocation: o.country === void 0 || o.country === "" ? void 0 : { country: o.country }
492
- })
493
- });
494
- const body = z.parse(AnswerResponse, response);
495
- const { structure, text } = body.answer;
496
- const answer = structure === void 0 ? text : JSON.stringify(structure);
497
- if (answer === void 0 || answer === "") throw new FieldworkError("ProviderError", "exa returned no answer text", {
498
- cause: response,
499
- provider: "exa"
500
- });
501
- return compact({
502
- answer,
503
- citations: uniqueCitations(citationsOf(body.citations)),
504
- meta: responseMeta(body),
505
- output: structure === void 0 ? void 0 : await checkOutput(o.schema, structure, { provider: "exa" }),
506
- raw: response
507
- });
508
- },
509
- async extract(url, options) {
510
- const { call, rest: o } = callSettings(options);
511
- const { body, response, result } = await readOne(url, compact({
512
- maxAgeHours: hours(o.maxAge),
513
- summary: compact({
514
- query: o.prompt,
515
- schema: jsonSchemaOf(o.schema, "draft-07", "exa")
516
- })
517
- }), call);
518
- const { value: summary } = result.summary;
519
- if (summary === void 0) throw new FieldworkError("ProviderError", `exa returned no structured summary for ${url}`, {
520
- cause: response,
521
- provider: "exa"
522
- });
523
- return compact({
524
- data: await checkOutput(o.schema, parseJson("exa", summary), { provider: "exa" }),
525
- meta: responseMeta(body),
526
- raw: response
527
- });
528
- },
529
- monitor: {
530
- async create(options) {
531
- const { call, rest: o } = callSettings(options);
532
- const every = period(o.schedule);
533
- const body = compact({
534
- metadata: o.metadata,
535
- name: o.name,
536
- outputSchema: o.outputSchema,
537
- search: compact({
538
- contents: o.content === true ? { text: true } : void 0,
539
- excludeDomains: o.excludeDomains,
540
- includeDomains: o.includeDomains,
541
- numResults: o.limit,
542
- query: o.query
543
- }),
544
- trigger: every === void 0 ? void 0 : {
545
- period: every,
546
- type: "interval"
547
- },
548
- webhook: compact({
549
- events: o.webhookEvents,
550
- url: o.webhookUrl
551
- })
552
- });
553
- return monitorInfo(z.parse(MonitorEntry, await raw.request("POST", "/monitors", {
554
- creates: true,
555
- ...call,
556
- body
557
- })));
558
- },
559
- async delete(id, options) {
560
- const { call } = callSettings(options);
561
- await raw.request("DELETE", `/monitors/${segment(id)}`, call);
562
- },
563
- async events(id, options) {
564
- const { call, rest: o } = callSettings(options);
565
- const response = await raw.request("GET", `/monitors/${segment(id)}/runs`, {
566
- ...call,
567
- query: {
568
- cursor: o.cursor,
569
- limit: o.limit
570
- }
571
- });
572
- const page = z.parse(RunsPage, response);
573
- return compact({
574
- events: page.data.map((entry) => monitorEvent(entry)),
575
- next: page.hasMore === true ? page.nextCursor : void 0,
576
- raw: response
577
- });
578
- },
579
- async get(id, options) {
580
- const { call } = callSettings(options);
581
- return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/monitors/${segment(id)}`, call)));
582
- },
583
- async list(options) {
584
- const { call } = callSettings(options);
585
- const monitors = [];
586
- const seen = /* @__PURE__ */ new Set();
587
- let cursor;
588
- for (;;) {
589
- const page = z.parse(MonitorsPage, await raw.request("GET", "/monitors", {
590
- ...call,
591
- query: {
592
- cursor,
593
- limit: 100
594
- }
595
- }));
596
- monitors.push(...page.data.map((entry) => monitorInfo(entry)));
597
- cursor = page.nextCursor;
598
- if (page.hasMore !== true || cursor === void 0 || seen.has(cursor)) return monitors;
599
- seen.add(cursor);
600
- }
601
- }
602
- },
603
- async read(url, options) {
604
- const { call, rest: o } = callSettings(options);
605
- const { body, response, result } = await readOne(url, readBody(o), call);
606
- return compact({
607
- ...pageFrom(url, result),
608
- meta: responseMeta(body),
609
- raw: response
610
- });
611
- },
612
- async readMany(urls, options) {
613
- const { call, rest: o } = callSettings(options);
614
- if (urls.length === 0) throw invalidRequest("exa", "readMany needs at least one URL");
615
- if (urls.length > 100) throw invalidRequest("exa", `readMany reads at most 100 URLs per call`);
616
- const { body, response } = await fetchContents(urls, readBody(o), call);
617
- return {
618
- failed: failedStatuses(body.statuses).map((status) => ({
619
- error: statusReason(status),
620
- url: status.id ?? ""
621
- })),
622
- meta: responseMeta(body),
623
- pages: body.results.map((entry) => ({
624
- ...pageFrom("", entry.value),
625
- raw: entry.original
626
- })),
627
- raw: response
628
- };
629
- },
630
- async research(question, options) {
631
- const { call, rest: o } = callSettings(options);
632
- checkResearch(o);
633
- return await runJob("exa", {
634
- check: async (id, request) => runState(id, z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request))),
635
- finish: async (run, id) => {
636
- const { outputSchema } = run.value.request;
637
- const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
638
- const result = researchResult(id, run, structured);
639
- return {
640
- ...result,
641
- output: await checkOutput(o.schema, result.output, { provider: "exa" })
642
- };
643
- },
644
- start: async () => await startJob(raw, "/agent/runs", {
645
- ...call,
646
- body: researchBody(question, o)
647
- }, RunStart, (reply) => reply.id)
648
- }, {
649
- ...call,
650
- interval: o.interval,
651
- resume: o.resume
652
- });
653
- },
654
- async search(query, options) {
655
- const { call, rest: o } = callSettings(options);
656
- checkSearch(o);
657
- const response = await raw.request("POST", "/search", {
658
- ...call,
659
- body: compact({
660
- additionalQueries: o.additionalQueries,
661
- category: o.category,
662
- contents: searchContents(o),
663
- endPublishedDate: dateTime(o.publishedBefore, true),
664
- excludeDomains: o.excludeDomains,
665
- includeDomains: o.includeDomains,
666
- moderation: o.moderation,
667
- numResults: o.limit,
668
- outputSchema: o.outputSchema,
669
- query,
670
- startPublishedDate: dateTime(o.publishedAfter, false),
671
- systemPrompt: o.systemPrompt,
672
- type: o.type,
673
- userLocation: o.country === void 0 || o.country === "" ? void 0 : { country: o.country }
674
- })
675
- });
676
- const body = z.parse(SearchResponse, response);
677
- return compact({
678
- answer: generatedAnswer(body.output),
679
- meta: responseMeta(body, [...body.warnings, ...body.notices].filter((note) => note !== void 0)),
680
- raw: response,
681
- results: body.results.map((item) => searchResult(item))
682
- });
683
- }
684
- },
715
+ operations,
685
716
  raw
686
717
  });
687
718
  };