@howells/fieldwork-sdk 0.3.1 → 0.5.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/exa.js CHANGED
@@ -1,23 +1,21 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { S as requireKey, _ as strings, a as hours, b as createRawClient, c as num, h as requireId, i as compact, l as parseJson, o as list, p as record, r as citations, s as meta, t as callSettings, v as text, x as poll, y as uniqueCitations } from "./util-YaZYZDSk.js";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
+ import { A as citationsOf, B as uniqueCitations, C as createRawClient, D as segment, E as requireKey, L as record, M as hours, N as meta, O as callSettings, P as parseJson, S as withOriginal, _ 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 compact, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
4
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
+ import * as z from "zod/mini";
4
6
  const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
5
7
  const DEEP_TYPES = /* @__PURE__ */ new Set([
6
8
  "deep-lite",
7
9
  "deep",
8
10
  "deep-reasoning"
9
11
  ]);
10
- const invalid = (message) => {
11
- throw new FieldworkError("InvalidRequest", `exa ${message}`, { provider: "exa" });
12
- };
13
12
  const dateTime = (value, endOfDay) => {
14
13
  if (value === void 0 || !DATE_ONLY.test(value)) return value;
15
14
  return endOfDay ? `${value}T23:59:59.999Z` : `${value}T00:00:00.000Z`;
16
15
  };
17
- const costOf = (response) => num(record(response.costDollars).total);
18
- const responseMeta = (response, warnings) => meta({
19
- costUsd: costOf(response),
20
- requestId: response.requestId,
16
+ const responseMeta = (body, warnings) => meta({
17
+ costUsd: body.costDollars.total,
18
+ requestId: body.requestId,
21
19
  warnings
22
20
  });
23
21
  const summaryOption = (summary, schema) => {
@@ -36,12 +34,12 @@ const checkSearch = (o) => {
36
34
  "summary",
37
35
  "maxAge"
38
36
  ].filter((name) => o[name] !== void 0);
39
- if (unsupported.length > 0) invalid(`search type "lite" does not accept ${unsupported.join(", ")}`);
37
+ if (unsupported.length > 0) throw invalidRequest("exa", `search type "lite" does not accept ${unsupported.join(", ")}`);
40
38
  }
41
- if (o.additionalQueries !== void 0 && !DEEP_TYPES.has(o.type ?? "")) invalid("additionalQueries needs search type \"deep-lite\", \"deep\" or \"deep-reasoning\"");
39
+ if (o.additionalQueries !== void 0 && !DEEP_TYPES.has(o.type ?? "")) throw invalidRequest("exa", "additionalQueries needs search type \"deep-lite\", \"deep\" or \"deep-reasoning\"");
42
40
  const dated = o.publishedAfter !== void 0 || o.publishedBefore !== void 0;
43
- if ((o.category === "company" || o.category === "people") && dated) invalid(`category "${o.category}" does not accept publishedAfter or publishedBefore`);
44
- if (o.category === "people" && o.excludeDomains !== void 0) invalid("category \"people\" does not accept excludeDomains");
41
+ if ((o.category === "company" || o.category === "people") && dated) throw invalidRequest("exa", `category "${o.category}" does not accept publishedAfter or publishedBefore`);
42
+ if (o.category === "people" && o.excludeDomains !== void 0) throw invalidRequest("exa", "category \"people\" does not accept excludeDomains");
45
43
  };
46
44
  const highlightsOption = (highlights) => typeof highlights === "object" ? compact({
47
45
  maxCharacters: highlights.maxCharacters,
@@ -52,28 +50,25 @@ const searchContents = (o) => {
52
50
  highlights: o.highlights === false ? void 0 : highlightsOption(o.highlights),
53
51
  maxAgeHours: hours(o.maxAge),
54
52
  summary: summaryOption(o.summary),
55
- text: o.content ? true : void 0
53
+ text: o.content === true ? true : void 0
56
54
  });
57
55
  return Object.keys(contents).length > 0 ? contents : void 0;
58
56
  };
59
- const searchResult = (item) => {
60
- const result = record(item);
61
- return compact({
62
- author: text(result.author),
63
- content: text(result.text),
64
- favicon: text(result.favicon),
65
- image: text(result.image),
66
- publishedAt: text(result.publishedDate),
67
- score: num(result.score),
68
- snippet: strings(result.highlights)?.join(" … "),
69
- title: text(result.title),
70
- url: text(result.url) ?? ""
71
- });
72
- };
57
+ const searchResult = (result) => compact({
58
+ author: result.author,
59
+ content: result.text,
60
+ favicon: result.favicon,
61
+ image: result.image,
62
+ publishedAt: result.publishedDate,
63
+ score: result.score,
64
+ snippet: result.highlights.length > 0 ? result.highlights.join(" … ") : void 0,
65
+ title: result.title,
66
+ url: result.url ?? ""
67
+ });
73
68
  const generatedAnswer = (output) => {
74
- const { content } = output;
75
- if (typeof content === "string") return text(content);
76
- return content === void 0 || content === null ? void 0 : JSON.stringify(content);
69
+ const { text, value } = output.content;
70
+ if (text !== void 0) return text === "" ? void 0 : text;
71
+ return value === void 0 || value === null ? void 0 : JSON.stringify(value);
77
72
  };
78
73
  const readBody = (o) => {
79
74
  const links = o.linkLimit ?? 100;
@@ -84,7 +79,7 @@ const readBody = (o) => {
84
79
  });
85
80
  return compact({
86
81
  extras: Object.keys(extras).length > 0 ? extras : void 0,
87
- highlights: o.query ? { query: o.query } : void 0,
82
+ highlights: o.query === void 0 || o.query === "" ? void 0 : { query: o.query },
88
83
  maxAgeHours: hours(o.maxAge),
89
84
  snapshotAsOf: o.snapshotAsOf,
90
85
  summary: summaryOption(o.summary),
@@ -98,37 +93,29 @@ const failureCode = (tag, httpStatus) => {
98
93
  return httpStatus === 408 || httpStatus === 504 ? "Timeout" : "ProviderError";
99
94
  };
100
95
  const statusReason = (status) => {
101
- const error = record(status.error);
102
- const httpStatus = num(error.httpStatusCode);
103
- return text(error.tag) ?? (httpStatus === void 0 ? void 0 : `HTTP ${httpStatus}`) ?? text(status.status) ?? "unknown";
104
- };
105
- const failedStatuses = (response) => list(response.statuses).map((item) => record(item)).filter((status) => status.status !== void 0 && status.status !== "success");
106
- const pageFrom = (url, item, rawValue) => {
107
- const result = record(item);
108
- const extras = record(result.extras);
109
- return compact({
110
- author: text(result.author),
111
- excerpts: strings(result.highlights),
112
- favicon: text(result.favicon),
113
- image: text(result.image),
114
- images: strings(extras.imageLinks),
115
- links: strings(extras.links),
116
- markdown: text(result.text),
117
- publishedAt: text(result.publishedDate),
118
- raw: rawValue,
119
- summary: text(result.summary),
120
- title: text(result.title),
121
- url: text(result.url) ?? url
122
- });
123
- };
124
- const hasOutput = (run, structured) => {
125
- const output = record(run.output);
126
- return structured ? output.structured !== void 0 && output.structured !== null : text(output.text) !== void 0;
96
+ const { httpStatusCode, tag } = status.error;
97
+ return tag ?? (httpStatusCode === void 0 ? void 0 : `HTTP ${httpStatusCode}`) ?? status.status.text ?? "unknown";
127
98
  };
99
+ const failedStatuses = (statuses) => statuses.filter(({ status }) => status.value !== void 0 && status.value !== "success");
100
+ /** A page from a result; the caller adds `raw`. */
101
+ const pageFrom = (url, result) => compact({
102
+ author: result.author,
103
+ excerpts: result.highlights.length > 0 ? result.highlights : void 0,
104
+ favicon: result.favicon,
105
+ image: result.image,
106
+ images: result.extras.imageLinks.length > 0 ? result.extras.imageLinks : void 0,
107
+ links: result.extras.links.length > 0 ? result.extras.links : void 0,
108
+ markdown: result.text,
109
+ publishedAt: result.publishedDate,
110
+ summary: result.summary.text,
111
+ title: result.title,
112
+ url: result.url ?? url
113
+ });
114
+ const hasOutput = (run, structured) => structured ? run.output.structured !== void 0 && run.output.structured !== null : run.output.text !== void 0;
128
115
  const runMeta = (run) => {
129
- const usage = record(run.usage);
116
+ const { usage } = run;
130
117
  return meta({
131
- costUsd: costOf(run),
118
+ costUsd: run.costDollars.total,
132
119
  units: {
133
120
  agentComputeUnits: usage.agentComputeUnits,
134
121
  emails: usage.emails,
@@ -139,8 +126,8 @@ const runMeta = (run) => {
139
126
  };
140
127
  const checkResearch = (o) => {
141
128
  const effort = o.effort ?? "auto";
142
- if (o.maxCostDollars !== void 0 && effort !== "auto" && effort !== "ultra") invalid(`maxCostDollars needs effort "auto" or "ultra", not "${effort}"`);
143
- if (o.maxDurationSeconds !== void 0 && effort !== "ultra") invalid(`maxDurationSeconds needs effort "ultra", not "${effort}"`);
129
+ if (o.maxCostDollars !== void 0 && effort !== "auto" && effort !== "ultra") throw invalidRequest("exa", `maxCostDollars needs effort "auto" or "ultra", not "${effort}"`);
130
+ if (o.maxDurationSeconds !== void 0 && effort !== "ultra") throw invalidRequest("exa", `maxDurationSeconds needs effort "ultra", not "${effort}"`);
144
131
  };
145
132
  const researchBody = (question, o) => {
146
133
  const budget = compact({
@@ -155,34 +142,31 @@ const researchBody = (question, o) => {
155
142
  budget: Object.keys(budget).length > 0 ? budget : void 0,
156
143
  effort: o.effort,
157
144
  input: Object.keys(input).length > 0 ? input : void 0,
158
- outputSchema: o.schema,
145
+ outputSchema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema, "draft-07"),
159
146
  previousRunId: o.continueFrom,
160
147
  query: question,
161
148
  systemPrompt: o.systemPrompt
162
149
  });
163
150
  };
164
- const researchResult = (id, run, structured) => {
165
- const stopReason = text(run.stopReason);
166
- const status = text(run.status) ?? "unknown";
151
+ const researchResult = (id, entry, structured) => {
152
+ const run = entry.value;
153
+ const { stopReason } = run;
154
+ const status = run.status ?? "unknown";
167
155
  if (status !== "completed" && !hasOutput(run, structured)) {
168
- const error = record(run.error);
169
- const message = text(error.message);
170
- const detail = message ? `${text(error.code) ?? text(error.type) ?? "error"}: ${message}` : stopReason;
171
- throw new FieldworkError("JobFailed", `exa research run ${id} ended ${status}${detail ? ` (${detail})` : ""}`, {
172
- cause: run,
156
+ const { error } = run;
157
+ const detail = error.message === void 0 ? stopReason : `${error.code ?? error.type ?? "error"}: ${error.message}`;
158
+ throw new FieldworkError("JobFailed", `exa research run ${id} ended ${status}${detail === void 0 ? "" : ` (${detail})`}`, {
159
+ cause: entry.original,
173
160
  jobId: id,
174
161
  provider: "exa"
175
162
  });
176
163
  }
177
- const output = record(run.output);
178
- const fields = list(output.grounding).map((item) => {
179
- const grounding = record(item);
180
- return compact({
181
- citations: citations(grounding.citations),
182
- confidence: text(grounding.confidence) ?? num(grounding.confidence),
183
- field: text(grounding.field) ?? ""
184
- });
185
- });
164
+ const { output } = run;
165
+ const fields = output.grounding.map((grounding) => compact({
166
+ citations: citationsOf(grounding.citations),
167
+ confidence: grounding.confidence,
168
+ field: grounding.field ?? ""
169
+ }));
186
170
  const finished = status === "completed" && (stopReason === void 0 || stopReason === "schema_satisfied");
187
171
  return compact({
188
172
  continuationId: status === "completed" ? id : void 0,
@@ -190,91 +174,233 @@ const researchResult = (id, run, structured) => {
190
174
  id,
191
175
  meta: runMeta(run),
192
176
  output: structured ? output.structured : output.text,
193
- raw: run,
177
+ raw: entry.original,
194
178
  sources: uniqueCitations(fields.flatMap((field) => field.citations)),
195
179
  status: finished ? "completed" : "partial",
196
180
  stopReason: finished ? void 0 : stopReason ?? status
197
181
  });
198
182
  };
199
183
  const intervalPeriod = (schedule) => {
200
- const { every } = schedule;
201
- if (typeof every !== "string") return invalid("monitors run on an interval of whole hours or days; Exa has no cron");
184
+ const { every } = record(schedule);
185
+ if (typeof every !== "string") throw invalidRequest("exa", "monitors run on an interval of whole hours or days; Exa has no cron");
202
186
  let value = every;
203
187
  if (every === "hour") value = "1h";
204
188
  else if (every === "day") value = "1d";
205
189
  else if (every === "week") value = "7d";
206
- 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`);
207
191
  return value;
208
192
  };
209
193
  const period = (schedule) => schedule === void 0 ? void 0 : intervalPeriod(schedule);
210
- const monitorInfo = (value) => {
211
- const found = record(value);
194
+ const monitorInfo = (entry) => {
195
+ const found = entry.value;
212
196
  return compact({
213
- createdAt: text(found.createdAt),
214
- id: requireId("exa", found.id),
215
- raw: value,
216
- schedule: text(record(found.trigger).period),
217
- status: text(found.status),
218
- watch: text(record(found.search).query),
219
- webhookUrl: text(record(found.webhook).url)
197
+ createdAt: found.createdAt,
198
+ id: requireJobId("exa", found.id),
199
+ raw: entry.original,
200
+ schedule: found.trigger.period,
201
+ status: found.status,
202
+ watch: found.search.query,
203
+ webhookUrl: found.webhook.url
220
204
  });
221
205
  };
222
- const eventSummary = (run, content) => {
223
- if (typeof content === "string") return text(content);
224
- if (run.status === "failed") {
225
- const reason = text(run.failReason);
226
- return `Run failed${reason ? `: ${reason}` : ""}`;
227
- }
206
+ const eventSummary = (run) => {
207
+ const { text } = run.output.content;
208
+ if (text !== void 0) return text === "" ? void 0 : text;
209
+ if (run.status === "failed") return `Run failed${run.failReason === void 0 ? "" : `: ${run.failReason}`}`;
228
210
  };
229
- const monitorEvent = (item) => {
230
- const run = record(item);
231
- const output = record(run.output);
232
- const { content } = output;
233
- const grounded = uniqueCitations(list(output.grounding).flatMap((entry) => citations(record(entry).citations)));
234
- const structured = content !== void 0 && content !== null && typeof content !== "string";
211
+ const monitorEvent = (entry) => {
212
+ const run = entry.value;
213
+ const { text, value } = run.output.content;
214
+ const grounded = uniqueCitations(run.output.grounding.flatMap((grounding) => citationsOf(grounding.citations)));
215
+ const structured = text === void 0 && value !== void 0 && value !== null;
235
216
  return compact({
236
- at: text(run.completedAt) ?? text(run.createdAt),
217
+ at: run.completedAt ?? run.createdAt,
237
218
  citations: grounded.length > 0 ? grounded : void 0,
238
- id: text(run.id),
239
- output: structured ? content : void 0,
240
- raw: item,
241
- summary: eventSummary(run, content)
219
+ id: run.id,
220
+ output: structured ? value : void 0,
221
+ raw: entry.original,
222
+ summary: eventSummary(run)
242
223
  });
243
224
  };
225
+ // src/adapters/exa/response.ts
226
+ /** What every response reports about its cost and identity. */
227
+ const metered = {
228
+ costDollars: looseObject({ total: optionalNumber }),
229
+ requestId: optionalScalar
230
+ };
231
+ looseObject(metered);
232
+ /** A page or search result. */
233
+ const Result = looseObject({
234
+ author: optionalString,
235
+ extras: looseObject({
236
+ imageLinks: arrayOf(z.string()),
237
+ links: arrayOf(z.string())
238
+ }),
239
+ favicon: optionalString,
240
+ highlights: arrayOf(z.string()),
241
+ image: optionalString,
242
+ publishedDate: optionalString,
243
+ score: optionalNumber,
244
+ summary: z.pipe(both(optionalString, anything), z.transform(({ first, second }) => ({
245
+ text: first,
246
+ value: second
247
+ }))),
248
+ text: optionalString,
249
+ title: optionalString,
250
+ url: optionalString
251
+ });
252
+ /** The status of one URL of a `/contents` call. `status` is kept as it arrived, since anything but `success` counts as a failure. */
253
+ const UrlStatus = looseObject({
254
+ error: looseObject({
255
+ httpStatusCode: optionalNumber,
256
+ tag: optionalString
257
+ }),
258
+ id: optionalString,
259
+ status: z.pipe(both(anything, optionalString), z.transform(({ first, second }) => ({
260
+ text: second,
261
+ value: first
262
+ })))
263
+ });
264
+ /** `/contents`. Each result keeps its own entry as it arrived. */
265
+ const ContentsResponse = looseObject({
266
+ ...metered,
267
+ results: arrayOf(withOriginal(Result)),
268
+ statuses: arrayOf(UrlStatus)
269
+ });
270
+ /** A generated answer: text, or the structured value the output schema asked for. */
271
+ const AnswerResponse = looseObject({
272
+ ...metered,
273
+ answer: z.pipe(both(optionalString, optionalStructure), z.transform(({ first, second }) => ({
274
+ structure: second,
275
+ text: first
276
+ }))),
277
+ citations: arrayOf(Source)
278
+ });
279
+ /** A string, or any other value kept as it arrived. */
280
+ const Content = z.pipe(both(optionalAnyString, anything), z.transform(({ first, second }) => ({
281
+ text: first,
282
+ value: second
283
+ })));
284
+ /** `/search`. */
285
+ const SearchResponse = looseObject({
286
+ ...metered,
287
+ notices: arrayOf(warningEntry),
288
+ output: looseObject({ content: Content }),
289
+ results: arrayOf(Result),
290
+ warnings: arrayOf(warningEntry)
291
+ });
292
+ const Grounding = looseObject({
293
+ citations: arrayOf(Source),
294
+ confidence: optionalStringOrNumber,
295
+ field: optionalString
296
+ });
297
+ /** An agent run, as started, polled or resumed. */
298
+ const Run = looseObject({
299
+ ...metered,
300
+ error: looseObject({
301
+ code: optionalString,
302
+ message: optionalString,
303
+ type: optionalString
304
+ }),
305
+ output: looseObject({
306
+ grounding: arrayOf(Grounding),
307
+ structured: anything,
308
+ text: optionalString
309
+ }),
310
+ request: looseObject({ outputSchema: anything }),
311
+ status: optionalString,
312
+ stopReason: optionalString,
313
+ usage: looseObject({
314
+ agentComputeUnits: optionalNumber,
315
+ emails: optionalNumber,
316
+ phoneNumbers: optionalNumber,
317
+ searches: optionalNumber
318
+ })
319
+ });
320
+ /** A run beside the response as it arrived. */
321
+ const RunEntry = withOriginal(Run);
322
+ /** The reply to starting a run. */
323
+ const RunStart = looseObject({ id: withOriginal(optionalId) });
324
+ const Monitor = looseObject({
325
+ createdAt: optionalString,
326
+ id: withOriginal(optionalId),
327
+ search: looseObject({ query: optionalString }),
328
+ status: optionalString,
329
+ trigger: looseObject({ period: optionalString }),
330
+ webhook: looseObject({ url: optionalString })
331
+ });
332
+ /** A monitor beside the entry as it arrived. */
333
+ const MonitorEntry = withOriginal(Monitor);
334
+ /** One page of monitors. */
335
+ const MonitorsPage = looseObject({
336
+ data: arrayOf(MonitorEntry),
337
+ hasMore: optionalBoolean,
338
+ nextCursor: optionalString
339
+ });
340
+ const MonitorRun = looseObject({
341
+ completedAt: optionalString,
342
+ createdAt: optionalString,
343
+ failReason: optionalString,
344
+ id: optionalString,
345
+ output: looseObject({
346
+ content: Content,
347
+ grounding: arrayOf(looseObject({ citations: arrayOf(Source) }))
348
+ }),
349
+ status: optionalString
350
+ });
351
+ /** One page of a monitor's runs, each beside its entry as it arrived. */
352
+ const RunsPage = looseObject({
353
+ data: arrayOf(withOriginal(MonitorRun)),
354
+ hasMore: optionalBoolean,
355
+ nextCursor: optionalString
356
+ });
244
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
+ */
245
363
  const exa = (config = {}) => {
246
364
  const raw = createRawClient({
247
365
  baseUrl: config.baseUrl ?? "https://api.exa.ai",
248
366
  fetch: config.fetch,
249
367
  headers: { "x-api-key": requireKey("exa", config.apiKey, "EXA_API_KEY") },
250
- provider: "exa"
368
+ provider: "exa",
369
+ retries: config.retries
251
370
  });
252
- const fetchContents = async (urls, body, call) => record(await raw.request("POST", "/contents", {
253
- ...call,
254
- body: {
255
- urls,
256
- ...body
257
- }
258
- }));
371
+ const fetchContents = async (urls, body, call) => {
372
+ const response = await raw.request("POST", "/contents", {
373
+ ...call,
374
+ body: {
375
+ urls,
376
+ ...body
377
+ }
378
+ });
379
+ return {
380
+ body: z.parse(ContentsResponse, response),
381
+ response
382
+ };
383
+ };
259
384
  const readOne = async (url, body, call) => {
260
- const response = await fetchContents([url], body, call);
261
- const [failed] = failedStatuses(response);
385
+ const { body: parsed, response } = await fetchContents([url], body, call);
386
+ const [failed] = failedStatuses(parsed.statuses);
262
387
  if (failed) {
263
- const error = record(failed.error);
264
- throw new FieldworkError(failureCode(text(error.tag), num(error.httpStatusCode)), `exa could not read ${url}: ${statusReason(failed)}`, {
388
+ const { httpStatusCode, tag } = failed.error;
389
+ throw new FieldworkError(failureCode(tag, httpStatusCode), `exa could not read ${url}: ${statusReason(failed)}`, {
265
390
  cause: response,
266
391
  provider: "exa",
267
- status: num(error.httpStatusCode)
392
+ status: httpStatusCode
268
393
  });
269
394
  }
270
- const [result] = list(response.results);
395
+ const [result] = parsed.results;
271
396
  if (result === void 0) throw new FieldworkError("ProviderError", `exa returned no content for ${url}`, {
272
397
  cause: response,
273
398
  provider: "exa"
274
399
  });
275
400
  return {
401
+ body: parsed,
276
402
  response,
277
- result
403
+ result: result.value
278
404
  };
279
405
  };
280
406
  return defineAdapter({
@@ -282,43 +408,48 @@ const exa = (config = {}) => {
282
408
  operations: {
283
409
  async answer(question, options) {
284
410
  const { call, rest: o } = callSettings(options);
285
- const response = record(await raw.request("POST", "/answer", {
411
+ const response = await raw.request("POST", "/answer", {
286
412
  ...call,
287
413
  body: compact({
288
414
  model: o.model,
289
- outputSchema: o.schema,
415
+ outputSchema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema, "draft-07"),
290
416
  query: question,
291
417
  systemPrompt: o.systemPrompt,
292
- userLocation: o.country ? { country: o.country } : void 0
418
+ userLocation: o.country === void 0 || o.country === "" ? void 0 : { country: o.country }
293
419
  })
294
- }));
295
- const { answer: value } = response;
296
- const structured = typeof value === "object" && value !== null;
420
+ });
421
+ const body = z.parse(AnswerResponse, response);
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
+ });
297
428
  return compact({
298
- answer: structured ? JSON.stringify(value) : text(value) ?? "",
299
- citations: uniqueCitations(citations(response.citations)),
300
- meta: responseMeta(response),
301
- output: structured ? value : void 0,
429
+ answer,
430
+ citations: uniqueCitations(citationsOf(body.citations)),
431
+ meta: responseMeta(body),
432
+ output: structure === void 0 ? void 0 : await checkOutput(o.schema, structure, { provider: "exa" }),
302
433
  raw: response
303
434
  });
304
435
  },
305
436
  async extract(url, options) {
306
437
  const { call, rest: o } = callSettings(options);
307
- const { response, result } = await readOne(url, compact({
438
+ const { body, response, result } = await readOne(url, compact({
308
439
  maxAgeHours: hours(o.maxAge),
309
440
  summary: compact({
310
441
  query: o.prompt,
311
- schema: o.schema
442
+ schema: jsonSchemaOf(o.schema, "draft-07")
312
443
  })
313
444
  }), call);
314
- const { summary } = record(result);
445
+ const { value: summary } = result.summary;
315
446
  if (summary === void 0) throw new FieldworkError("ProviderError", `exa returned no structured summary for ${url}`, {
316
447
  cause: response,
317
448
  provider: "exa"
318
449
  });
319
450
  return compact({
320
- data: parseJson("exa", summary),
321
- meta: responseMeta(response),
451
+ data: await checkOutput(o.schema, parseJson("exa", summary), { provider: "exa" }),
452
+ meta: responseMeta(body),
322
453
  raw: response
323
454
  });
324
455
  },
@@ -331,48 +462,50 @@ const exa = (config = {}) => {
331
462
  name: o.name,
332
463
  outputSchema: o.outputSchema,
333
464
  search: compact({
334
- contents: o.content ? { text: true } : void 0,
465
+ contents: o.content === true ? { text: true } : void 0,
335
466
  excludeDomains: o.excludeDomains,
336
467
  includeDomains: o.includeDomains,
337
468
  numResults: o.limit,
338
469
  query: o.query
339
470
  }),
340
- trigger: every ? {
471
+ trigger: every === void 0 ? void 0 : {
341
472
  period: every,
342
473
  type: "interval"
343
- } : void 0,
474
+ },
344
475
  webhook: compact({
345
476
  events: o.webhookEvents,
346
477
  url: o.webhookUrl
347
478
  })
348
479
  });
349
- return monitorInfo(await raw.request("POST", "/monitors", {
480
+ return monitorInfo(z.parse(MonitorEntry, await raw.request("POST", "/monitors", {
481
+ creates: true,
350
482
  ...call,
351
483
  body
352
- }));
484
+ })));
353
485
  },
354
486
  async delete(id, options) {
355
487
  const { call } = callSettings(options);
356
- await raw.request("DELETE", `/monitors/${encodeURIComponent(id)}`, call);
488
+ await raw.request("DELETE", `/monitors/${segment(id)}`, call);
357
489
  },
358
490
  async events(id, options) {
359
491
  const { call, rest: o } = callSettings(options);
360
- const response = record(await raw.request("GET", `/monitors/${encodeURIComponent(id)}/runs`, {
492
+ const response = await raw.request("GET", `/monitors/${segment(id)}/runs`, {
361
493
  ...call,
362
494
  query: {
363
495
  cursor: o.cursor,
364
496
  limit: o.limit
365
497
  }
366
- }));
498
+ });
499
+ const page = z.parse(RunsPage, response);
367
500
  return compact({
368
- events: list(response.data).map((item) => monitorEvent(item)),
369
- next: response.hasMore === true ? text(response.nextCursor) : void 0,
501
+ events: page.data.map((entry) => monitorEvent(entry)),
502
+ next: page.hasMore === true ? page.nextCursor : void 0,
370
503
  raw: response
371
504
  });
372
505
  },
373
506
  async get(id, options) {
374
507
  const { call } = callSettings(options);
375
- return monitorInfo(await raw.request("GET", `/monitors/${encodeURIComponent(id)}`, call));
508
+ return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/monitors/${segment(id)}`, call)));
376
509
  },
377
510
  async list(options) {
378
511
  const { call } = callSettings(options);
@@ -380,15 +513,15 @@ const exa = (config = {}) => {
380
513
  const seen = /* @__PURE__ */ new Set();
381
514
  let cursor;
382
515
  for (;;) {
383
- const page = record(await raw.request("GET", "/monitors", {
516
+ const page = z.parse(MonitorsPage, await raw.request("GET", "/monitors", {
384
517
  ...call,
385
518
  query: {
386
519
  cursor,
387
520
  limit: 100
388
521
  }
389
522
  }));
390
- monitors.push(...list(page.data).map((item) => monitorInfo(item)));
391
- cursor = text(page.nextCursor);
523
+ monitors.push(...page.data.map((entry) => monitorInfo(entry)));
524
+ cursor = page.nextCursor;
392
525
  if (page.hasMore !== true || cursor === void 0 || seen.has(cursor)) return monitors;
393
526
  seen.add(cursor);
394
527
  }
@@ -396,49 +529,62 @@ const exa = (config = {}) => {
396
529
  },
397
530
  async read(url, options) {
398
531
  const { call, rest: o } = callSettings(options);
399
- const { response, result } = await readOne(url, readBody(o), call);
532
+ const { body, response, result } = await readOne(url, readBody(o), call);
400
533
  return compact({
401
- ...pageFrom(url, result, response),
402
- meta: responseMeta(response)
534
+ ...pageFrom(url, result),
535
+ meta: responseMeta(body),
536
+ raw: response
403
537
  });
404
538
  },
405
539
  async readMany(urls, options) {
406
540
  const { call, rest: o } = callSettings(options);
407
- if (urls.length === 0) invalid("readMany needs at least one URL");
408
- if (urls.length > 100) invalid(`readMany reads at most 100 URLs per call`);
409
- const response = await fetchContents(urls, readBody(o), 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`);
543
+ const { body, response } = await fetchContents(urls, readBody(o), call);
410
544
  return {
411
- failed: failedStatuses(response).map((status) => ({
545
+ failed: failedStatuses(body.statuses).map((status) => ({
412
546
  error: statusReason(status),
413
- url: text(status.id) ?? ""
547
+ url: status.id ?? ""
548
+ })),
549
+ meta: responseMeta(body),
550
+ pages: body.results.map((entry) => ({
551
+ ...pageFrom("", entry.value),
552
+ raw: entry.original
414
553
  })),
415
- meta: responseMeta(response),
416
- pages: list(response.results).map((item) => pageFrom("", item, item)),
417
554
  raw: response
418
555
  };
419
556
  },
420
557
  async research(question, options) {
421
558
  const { call, rest: o } = callSettings(options);
422
559
  checkResearch(o);
423
- const id = o.resume ?? requireId("exa", record(await raw.request("POST", "/agent/runs", {
560
+ const id = o.resume ?? requireJobId("exa", z.parse(RunStart, await raw.request("POST", "/agent/runs", {
561
+ creates: true,
424
562
  ...call,
425
563
  body: researchBody(question, o)
426
564
  })).id);
427
- const run = await poll("exa", id, async () => {
428
- const current = record(await raw.request("GET", `/agent/runs/${encodeURIComponent(id)}`, { signal: call.signal }));
429
- return current.status === "completed" || current.status === "failed" || current.status === "cancelled" ? current : void 0;
565
+ const run = await poll("exa", id, async (request) => {
566
+ const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request));
567
+ const { status } = current.value;
568
+ return status === "completed" || status === "failed" || status === "cancelled" ? current : void 0;
430
569
  }, {
431
570
  ...call,
432
571
  interval: o.interval
433
572
  });
434
- const { outputSchema } = record(run.request);
573
+ const { outputSchema } = run.value.request;
435
574
  const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
436
- return researchResult(id, run, structured);
575
+ const result = researchResult(id, run, structured);
576
+ return {
577
+ ...result,
578
+ output: await checkOutput(o.schema, result.output, {
579
+ jobId: id,
580
+ provider: "exa"
581
+ })
582
+ };
437
583
  },
438
584
  async search(query, options) {
439
585
  const { call, rest: o } = callSettings(options);
440
586
  checkSearch(o);
441
- const response = record(await raw.request("POST", "/search", {
587
+ const response = await raw.request("POST", "/search", {
442
588
  ...call,
443
589
  body: compact({
444
590
  additionalQueries: o.additionalQueries,
@@ -454,14 +600,15 @@ const exa = (config = {}) => {
454
600
  startPublishedDate: dateTime(o.publishedAfter, false),
455
601
  systemPrompt: o.systemPrompt,
456
602
  type: o.type,
457
- userLocation: o.country ? { country: o.country } : void 0
603
+ userLocation: o.country === void 0 || o.country === "" ? void 0 : { country: o.country }
458
604
  })
459
- }));
605
+ });
606
+ const body = z.parse(SearchResponse, response);
460
607
  return compact({
461
- answer: generatedAnswer(record(response.output)),
462
- meta: responseMeta(response, [...list(response.warnings), ...list(response.notices)]),
608
+ answer: generatedAnswer(body.output),
609
+ meta: responseMeta(body, [...body.warnings, ...body.notices].filter((note) => note !== void 0)),
463
610
  raw: response,
464
- results: list(response.results).map((item) => searchResult(item))
611
+ results: body.results.map((item) => searchResult(item))
465
612
  });
466
613
  }
467
614
  },