@howells/fieldwork-sdk 0.4.0 → 0.5.1

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.
@@ -0,0 +1,51 @@
1
+ import { t as FieldworkError } from "./errors-Yvk42oZH.js";
2
+ // src/document.ts
3
+ /** Content types of the document files parsers commonly take, by extension. */
4
+ const MEDIA_TYPES = new Map(Object.entries({
5
+ csv: "text/csv",
6
+ doc: "application/msword",
7
+ docm: "application/vnd.ms-word.document.macroEnabled.12",
8
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
9
+ epub: "application/epub+zip",
10
+ htm: "text/html",
11
+ html: "text/html",
12
+ odp: "application/vnd.oasis.opendocument.presentation",
13
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
14
+ odt: "application/vnd.oasis.opendocument.text",
15
+ pdf: "application/pdf",
16
+ ppt: "application/vnd.ms-powerpoint",
17
+ pptm: "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
18
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
19
+ rtf: "application/rtf",
20
+ xhtml: "application/xhtml+xml",
21
+ xls: "application/vnd.ms-excel",
22
+ xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
23
+ xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12",
24
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
25
+ }));
26
+ /** The content type the file's extension names, or undefined for one not listed. */
27
+ const mediaTypeOf = (name) => MEDIA_TYPES.get(name.split(".").pop()?.toLowerCase() ?? "");
28
+ /** Refuses a file larger than the provider takes, before it is sent. */
29
+ const refuseLarger = (provider, document, maxMegabytes) => {
30
+ const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
31
+ if (size > maxMegabytes * 1024 * 1024) throw new FieldworkError("InvalidRequest", `${provider} parses files up to ${maxMegabytes} MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`, { provider });
32
+ };
33
+ /** The file's bytes as a multipart part, with the content type its extension names. */
34
+ const documentPart = (document) => {
35
+ const part = document.data instanceof Uint8Array ? new Uint8Array(document.data) : document.data;
36
+ return new Blob([part], { type: mediaTypeOf(document.name) ?? "application/octet-stream" });
37
+ };
38
+ /** The smallest box that holds every one of `boxes`, or undefined when there are none. */
39
+ const enclosing = (boxes) => {
40
+ if (boxes.length <= 1) return boxes[0];
41
+ const left = Math.min(...boxes.map((box) => box.left));
42
+ const top = Math.min(...boxes.map((box) => box.top));
43
+ const right = Math.max(...boxes.map((box) => box.left + box.width));
44
+ return {
45
+ height: Math.max(...boxes.map((box) => box.top + box.height)) - top,
46
+ left,
47
+ top,
48
+ width: right - left
49
+ };
50
+ };
51
+ export { refuseLarger as a, mediaTypeOf as i, documentPart as n, enclosing as r, MEDIA_TYPES as t };
@@ -62,4 +62,6 @@ const codeForStatus = (status) => {
62
62
  if (status === 400 || status === 422) return "InvalidRequest";
63
63
  return "ProviderError";
64
64
  };
65
- export { codeForStatus as n, withJob as r, FieldworkError as t };
65
+ /** A request refused before it is sent, with the provider's name leading the message. */
66
+ const invalidRequest = (provider, message) => new FieldworkError("InvalidRequest", `${provider} ${message}`, { provider });
67
+ export { withJob as i, codeForStatus as n, invalidRequest as r, FieldworkError as t };
package/dist/exa.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { F as MonitorSchedule, G as Research, I as Page, L as PageBatch, N as MonitorEvents, P as MonitorInfo, a as RawClient, f as CallOptions, l as Answer, q as SearchResponse, t as Adapter, w as Extraction } from "./adapter-CDY8qczv.js";
2
- import { t as OutputSchema } from "./schema-EZlBkY5B.js";
1
+ import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, l as Answer, p as CallOptions, q as Research, t as Adapter, z as PageBatch } from "./adapter-BgdfLBs-.js";
2
+ import { t as OutputSchema } from "./schema-Cupy7-7q.js";
3
3
  interface ExaConfig {
4
4
  /** Defaults to the EXA_API_KEY environment variable. */
5
5
  apiKey?: string;
@@ -191,5 +191,10 @@ interface ExaOperations {
191
191
  research: <T = unknown>(question: string, options?: ExaResearchOptions<T>) => Promise<Research<T>>;
192
192
  monitor: ExaMonitor;
193
193
  }
194
+ /**
195
+ * An adapter for Exa: search, read, readMany, extract, answer, research and monitor. Pass it to `new Fieldwork({ adapter })`.
196
+ *
197
+ * Throws `Unauthorized` when neither `apiKey` nor `EXA_API_KEY` is set.
198
+ */
194
199
  export declare const exa: (config?: ExaConfig) => Adapter<"exa", ExaOperations, RawClient>;
195
200
  export type { ExaAnswerOptions, ExaConfig, ExaExtractOptions, ExaHighlightOptions, ExaMonitor, ExaMonitorCreateOptions, ExaMonitorEventsOptions, ExaOperations, ExaOutputSchema, ExaReadManyOptions, ExaReadOptions, ExaResearchOptions, ExaSearchOptions, ExaWebhookEvent };
package/dist/exa.js CHANGED
@@ -1,7 +1,8 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { A as hours, C as createRawClient, E as callSettings, F as record, L as requireJobId, M as parseJson, O as citationsOf, R as uniqueCitations, 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, j as meta, k as compact, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, w as poll } from "./parse-CxOri73y.js";
4
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-teOy7Od-.js";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, N as hours, P as meta, R as record, S as withOriginal, T as requireKey, V as uniqueCitations, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, j as citationsOf, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-n8MmaK1x.js";
4
+ import { t as runJob } from "./job-BGTwH3F-.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
6
  import * as z from "zod/mini";
6
7
  const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
7
8
  const DEEP_TYPES = /* @__PURE__ */ new Set([
@@ -9,9 +10,6 @@ const DEEP_TYPES = /* @__PURE__ */ new Set([
9
10
  "deep",
10
11
  "deep-reasoning"
11
12
  ]);
12
- const invalid = (message) => {
13
- throw new FieldworkError("InvalidRequest", `exa ${message}`, { provider: "exa" });
14
- };
15
13
  const dateTime = (value, endOfDay) => {
16
14
  if (value === void 0 || !DATE_ONLY.test(value)) return value;
17
15
  return endOfDay ? `${value}T23:59:59.999Z` : `${value}T00:00:00.000Z`;
@@ -37,12 +35,12 @@ const checkSearch = (o) => {
37
35
  "summary",
38
36
  "maxAge"
39
37
  ].filter((name) => o[name] !== void 0);
40
- if (unsupported.length > 0) invalid(`search type "lite" does not accept ${unsupported.join(", ")}`);
38
+ if (unsupported.length > 0) throw invalidRequest("exa", `search type "lite" does not accept ${unsupported.join(", ")}`);
41
39
  }
42
- if (o.additionalQueries !== void 0 && !DEEP_TYPES.has(o.type ?? "")) invalid("additionalQueries needs search type \"deep-lite\", \"deep\" or \"deep-reasoning\"");
40
+ if (o.additionalQueries !== void 0 && !DEEP_TYPES.has(o.type ?? "")) throw invalidRequest("exa", "additionalQueries needs search type \"deep-lite\", \"deep\" or \"deep-reasoning\"");
43
41
  const dated = o.publishedAfter !== void 0 || o.publishedBefore !== void 0;
44
- if ((o.category === "company" || o.category === "people") && dated) invalid(`category "${o.category}" does not accept publishedAfter or publishedBefore`);
45
- if (o.category === "people" && o.excludeDomains !== void 0) invalid("category \"people\" does not accept excludeDomains");
42
+ if ((o.category === "company" || o.category === "people") && dated) throw invalidRequest("exa", `category "${o.category}" does not accept publishedAfter or publishedBefore`);
43
+ if (o.category === "people" && o.excludeDomains !== void 0) throw invalidRequest("exa", "category \"people\" does not accept excludeDomains");
46
44
  };
47
45
  const highlightsOption = (highlights) => typeof highlights === "object" ? compact({
48
46
  maxCharacters: highlights.maxCharacters,
@@ -129,8 +127,8 @@ const runMeta = (run) => {
129
127
  };
130
128
  const checkResearch = (o) => {
131
129
  const effort = o.effort ?? "auto";
132
- if (o.maxCostDollars !== void 0 && effort !== "auto" && effort !== "ultra") invalid(`maxCostDollars needs effort "auto" or "ultra", not "${effort}"`);
133
- if (o.maxDurationSeconds !== void 0 && effort !== "ultra") invalid(`maxDurationSeconds needs effort "ultra", not "${effort}"`);
130
+ if (o.maxCostDollars !== void 0 && effort !== "auto" && effort !== "ultra") throw invalidRequest("exa", `maxCostDollars needs effort "auto" or "ultra", not "${effort}"`);
131
+ if (o.maxDurationSeconds !== void 0 && effort !== "ultra") throw invalidRequest("exa", `maxDurationSeconds needs effort "ultra", not "${effort}"`);
134
132
  };
135
133
  const researchBody = (question, o) => {
136
134
  const budget = compact({
@@ -160,7 +158,6 @@ const researchResult = (id, entry, structured) => {
160
158
  const detail = error.message === void 0 ? stopReason : `${error.code ?? error.type ?? "error"}: ${error.message}`;
161
159
  throw new FieldworkError("JobFailed", `exa research run ${id} ended ${status}${detail === void 0 ? "" : ` (${detail})`}`, {
162
160
  cause: entry.original,
163
- jobId: id,
164
161
  provider: "exa"
165
162
  });
166
163
  }
@@ -185,12 +182,12 @@ const researchResult = (id, entry, structured) => {
185
182
  };
186
183
  const intervalPeriod = (schedule) => {
187
184
  const { every } = record(schedule);
188
- if (typeof every !== "string") return invalid("monitors run on an interval of whole hours or days; Exa has no cron");
185
+ if (typeof every !== "string") throw invalidRequest("exa", "monitors run on an interval of whole hours or days; Exa has no cron");
189
186
  let value = every;
190
187
  if (every === "hour") value = "1h";
191
188
  else if (every === "day") value = "1d";
192
189
  else if (every === "week") value = "7d";
193
- if (!/^[1-9]\d*[hd]$/u.test(value)) return invalid(`monitor schedule "${every}" is not whole hours or days, at least 1h`);
190
+ if (!/^[1-9]\d*[hd]$/u.test(value)) throw invalidRequest("exa", `monitor schedule "${every}" is not whole hours or days, at least 1h`);
194
191
  return value;
195
192
  };
196
193
  const period = (schedule) => schedule === void 0 ? void 0 : intervalPeriod(schedule);
@@ -358,6 +355,11 @@ const RunsPage = looseObject({
358
355
  nextCursor: optionalString
359
356
  });
360
357
  // src/adapters/exa.ts
358
+ /**
359
+ * An adapter for Exa: search, read, readMany, extract, answer, research and monitor. Pass it to `new Fieldwork({ adapter })`.
360
+ *
361
+ * Throws `Unauthorized` when neither `apiKey` nor `EXA_API_KEY` is set.
362
+ */
361
363
  const exa = (config = {}) => {
362
364
  const raw = createRawClient({
363
365
  baseUrl: config.baseUrl ?? "https://api.exa.ai",
@@ -417,9 +419,14 @@ const exa = (config = {}) => {
417
419
  })
418
420
  });
419
421
  const body = z.parse(AnswerResponse, response);
420
- const { structure } = body.answer;
422
+ const { structure, text } = body.answer;
423
+ const answer = structure === void 0 ? text : JSON.stringify(structure);
424
+ if (answer === void 0 || answer === "") throw new FieldworkError("ProviderError", "exa returned no answer text", {
425
+ cause: response,
426
+ provider: "exa"
427
+ });
421
428
  return compact({
422
- answer: structure === void 0 ? body.answer.text ?? "" : JSON.stringify(structure),
429
+ answer,
423
430
  citations: uniqueCitations(citationsOf(body.citations)),
424
431
  meta: responseMeta(body),
425
432
  output: structure === void 0 ? void 0 : await checkOutput(o.schema, structure, { provider: "exa" }),
@@ -478,11 +485,11 @@ const exa = (config = {}) => {
478
485
  },
479
486
  async delete(id, options) {
480
487
  const { call } = callSettings(options);
481
- await raw.request("DELETE", `/monitors/${encodeURIComponent(id)}`, call);
488
+ await raw.request("DELETE", `/monitors/${segment(id)}`, call);
482
489
  },
483
490
  async events(id, options) {
484
491
  const { call, rest: o } = callSettings(options);
485
- const response = await raw.request("GET", `/monitors/${encodeURIComponent(id)}/runs`, {
492
+ const response = await raw.request("GET", `/monitors/${segment(id)}/runs`, {
486
493
  ...call,
487
494
  query: {
488
495
  cursor: o.cursor,
@@ -498,7 +505,7 @@ const exa = (config = {}) => {
498
505
  },
499
506
  async get(id, options) {
500
507
  const { call } = callSettings(options);
501
- return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/monitors/${encodeURIComponent(id)}`, call)));
508
+ return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/monitors/${segment(id)}`, call)));
502
509
  },
503
510
  async list(options) {
504
511
  const { call } = callSettings(options);
@@ -531,8 +538,8 @@ const exa = (config = {}) => {
531
538
  },
532
539
  async readMany(urls, options) {
533
540
  const { call, rest: o } = callSettings(options);
534
- if (urls.length === 0) invalid("readMany needs at least one URL");
535
- if (urls.length > 100) invalid(`readMany reads at most 100 URLs per call`);
541
+ if (urls.length === 0) throw invalidRequest("exa", "readMany needs at least one URL");
542
+ if (urls.length > 100) throw invalidRequest("exa", `readMany reads at most 100 URLs per call`);
536
543
  const { body, response } = await fetchContents(urls, readBody(o), call);
537
544
  return {
538
545
  failed: failedStatuses(body.statuses).map((status) => ({
@@ -550,29 +557,31 @@ const exa = (config = {}) => {
550
557
  async research(question, options) {
551
558
  const { call, rest: o } = callSettings(options);
552
559
  checkResearch(o);
553
- const id = o.resume ?? requireJobId("exa", z.parse(RunStart, await raw.request("POST", "/agent/runs", {
554
- creates: true,
555
- ...call,
556
- body: researchBody(question, o)
557
- })).id);
558
- const run = await poll("exa", id, async () => {
559
- const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${encodeURIComponent(id)}`, { signal: call.signal }));
560
- const { status } = current.value;
561
- return status === "completed" || status === "failed" || status === "cancelled" ? current : void 0;
560
+ return await runJob("exa", {
561
+ check: async (id, request) => {
562
+ const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request));
563
+ const { status } = current.value;
564
+ return status === "completed" || status === "failed" || status === "cancelled" ? current : void 0;
565
+ },
566
+ finish: async (run, id) => {
567
+ const { outputSchema } = run.value.request;
568
+ const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
569
+ const result = researchResult(id, run, structured);
570
+ return {
571
+ ...result,
572
+ output: await checkOutput(o.schema, result.output, { provider: "exa" })
573
+ };
574
+ },
575
+ start: async () => requireJobId("exa", z.parse(RunStart, await raw.request("POST", "/agent/runs", {
576
+ creates: true,
577
+ ...call,
578
+ body: researchBody(question, o)
579
+ })).id)
562
580
  }, {
563
581
  ...call,
564
- interval: o.interval
582
+ interval: o.interval,
583
+ resume: o.resume
565
584
  });
566
- const { outputSchema } = run.value.request;
567
- const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
568
- const result = researchResult(id, run, structured);
569
- return {
570
- ...result,
571
- output: await checkOutput(o.schema, result.output, {
572
- jobId: id,
573
- provider: "exa"
574
- })
575
- };
576
585
  },
577
586
  async search(query, options) {
578
587
  const { call, rest: o } = callSettings(options);
@@ -1,4 +1,5 @@
1
- import { n as AnyAdapter, p as Capability } from "./adapter-CDY8qczv.js";
1
+ import { m as Capability, n as AnyAdapter } from "./adapter-BgdfLBs-.js";
2
+ /** Why a call failed. Branch on this, not on the message, which can change. */
2
3
  type FieldworkErrorCode =
3
4
  /** The adapter's provider does not offer this capability. */
4
5
  "Unsupported" |
@@ -74,5 +75,10 @@ interface FieldworkBase<A extends AnyAdapter> {
74
75
  * Tavily has no browser.
75
76
  */
76
77
  type Fieldwork<A extends AnyAdapter> = FieldworkBase<A> & Readonly<A["operations"]>;
78
+ /**
79
+ * The client: `new Fieldwork({ adapter })` has exactly the methods its adapter offers.
80
+ *
81
+ * Check `supports` or `capabilities` before calling dynamically; a capability the provider lacks throws `Unsupported`.
82
+ */
77
83
  declare const Fieldwork: new <A extends AnyAdapter>(options: FieldworkOptions<A>) => Fieldwork<A>;
78
84
  export { FieldworkErrorCode as i, FieldworkOptions as n, FieldworkError as r, Fieldwork as t };
@@ -1,5 +1,5 @@
1
- import { F as MonitorSchedule, G as Research, I as Page, L as PageBatch, N as MonitorEvents, P as MonitorInfo, R as ParsedDocument, V as Product, W as Recency, X as SiteMap, a as RawClient, c as ActResult, f as CallOptions, g as Crawl, k as ImageSearch, q as SearchResponse, s as AccountUsage, t as Adapter, u as BrowserSession, w as Extraction, x as DocumentInput } from "./adapter-CDY8qczv.js";
2
- import { t as OutputSchema } from "./schema-EZlBkY5B.js";
1
+ import { B as ParsedDocument, C as DocumentInput, E as Extraction, F as MonitorEvents, I as MonitorInfo, K as Recency, L as MonitorSchedule, Q as SiteMap, R as Page, U as Product, Y as SearchResponse, _ as Crawl, a as RawClient, c as ActResult, d as BrowserSession, j as ImageSearch, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-BgdfLBs-.js";
2
+ import { t as OutputSchema } from "./schema-Cupy7-7q.js";
3
3
  interface FirecrawlConfig {
4
4
  /** Defaults to the FIRECRAWL_API_KEY environment variable. */
5
5
  apiKey?: string;
@@ -321,5 +321,10 @@ interface FirecrawlOperations {
321
321
  };
322
322
  usage: (options?: CallOptions) => Promise<AccountUsage>;
323
323
  }
324
+ /**
325
+ * An adapter for Firecrawl: search, images, read, readMany, extract, product, map, crawl, research, act, browser, parse, monitor and usage. Pass it to `new Fieldwork({ adapter })`.
326
+ *
327
+ * Throws `Unauthorized` when neither `apiKey` nor `FIRECRAWL_API_KEY` is set.
328
+ */
324
329
  export declare const firecrawl: (config?: FirecrawlConfig) => Adapter<"firecrawl", FirecrawlOperations, RawClient>;
325
330
  export type { FirecrawlActOptions, FirecrawlAction, FirecrawlBrowserOptions, FirecrawlConfig, FirecrawlCrawlOptions, FirecrawlExtractOptions, FirecrawlFormat, FirecrawlImagesOptions, FirecrawlMapOptions, FirecrawlMonitorOptions, FirecrawlOperations, FirecrawlPageOptions, FirecrawlPageSettings, FirecrawlParseOptions, FirecrawlParser, FirecrawlPdfParser, FirecrawlReadManyOptions, FirecrawlReadOptions, FirecrawlReadSettings, FirecrawlResearchOptions, FirecrawlSearchOptions, FirecrawlSessionSettings };