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