@howells/fieldwork-sdk 0.5.1 → 0.6.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.d.ts CHANGED
@@ -1,9 +1,12 @@
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";
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-Bh8EIrNe.js";
2
+ import { t as OutputSchema } from "./schema-BWWiMvkg.js";
3
+ /** Settings for the Exa adapter. */
3
4
  interface ExaConfig {
4
5
  /** Defaults to the EXA_API_KEY environment variable. */
5
6
  apiKey?: string;
7
+ /** Defaults to https://api.exa.ai. */
6
8
  baseUrl?: string;
9
+ /** Sends every request instead of the global `fetch`. */
7
10
  fetch?: typeof fetch;
8
11
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
12
  retries?: number;
@@ -23,12 +26,20 @@ type ExaOutputSchema = {
23
26
  required?: string[];
24
27
  additionalProperties?: boolean;
25
28
  };
29
+ /** Steers the passages `search` returns as `snippet`. */
26
30
  interface ExaHighlightOptions {
27
31
  /** Guides which passages Exa picks. Defaults to the search query. */
28
32
  query?: string;
29
33
  /** Total highlight length per page, in characters. */
30
34
  maxCharacters?: number;
31
35
  }
36
+ /**
37
+ * Options for `search`. Combinations Exa does not accept (`lite` with the
38
+ * options it lacks, `additionalQueries` without a deep type, the `category`
39
+ * limits below) throw `InvalidRequest` before the request is sent.
40
+ *
41
+ * A result's `snippet` is its highlights and its `content` is the page text.
42
+ */
32
43
  interface ExaSearchOptions extends CallOptions {
33
44
  /** Results to return; Exa allows 1 to 100, fewer for some types. */
34
45
  limit?: number;
@@ -47,12 +58,13 @@ interface ExaSearchOptions extends CallOptions {
47
58
  category?: "company" | "publication" | "news" | "personal site" | "financial report" | "people";
48
59
  /** Hostnames, hostname plus path prefix, or `*.` wildcards; up to 1,200. */
49
60
  includeDomains?: string[];
61
+ /** Refused with `category: "people"`. */
50
62
  excludeDomains?: string[];
51
63
  /** YYYY-MM-DD, from the start of that day (UTC). */
52
64
  publishedAfter?: string;
53
65
  /** YYYY-MM-DD, to the end of that day (UTC). */
54
66
  publishedBefore?: string;
55
- /** Two-letter country code that localizes results. */
67
+ /** Two-letter country code that localizes results; sent as Exa's `userLocation`. */
56
68
  country?: string;
57
69
  /** Filter unsafe content from the results. */
58
70
  moderation?: boolean;
@@ -84,6 +96,11 @@ interface ExaSearchOptions extends CallOptions {
84
96
  /** Guides the generated answer. */
85
97
  systemPrompt?: string;
86
98
  }
99
+ /**
100
+ * Options for `read`. Exa reports a URL it could not read in its response
101
+ * rather than as an HTTP error; `read` throws for it (`NotFound`, `Timeout` or
102
+ * `ProviderError`, by Exa's reason) and `readMany` lists it in `failed`.
103
+ */
87
104
  interface ExaReadOptions extends CallOptions {
88
105
  /** Return passages that answer this query as `excerpts`. */
89
106
  query?: string;
@@ -102,7 +119,12 @@ interface ExaReadOptions extends CallOptions {
102
119
  /** Image URLs to return per page, 0 to 1,000. Defaults to 100; 0 returns none. */
103
120
  imageLimit?: number;
104
121
  }
122
+ /** Options for `readMany`, which reads 1 to 100 URLs in one call. The same as `ExaReadOptions`. */
105
123
  type ExaReadManyOptions = ExaReadOptions;
124
+ /**
125
+ * Options for `extract`. Exa has no extraction endpoint, so the adapter asks
126
+ * for a summary of the page in the shape of `schema` and returns it as `data`.
127
+ */
106
128
  interface ExaExtractOptions<T = unknown> extends CallOptions {
107
129
  /** A JSON Schema, or a Zod, Valibot or ArkType schema that types and checks `data`. */
108
130
  schema: OutputSchema<T>;
@@ -111,21 +133,31 @@ interface ExaExtractOptions<T = unknown> extends CallOptions {
111
133
  /** Seconds a cached copy may be old; 0 fetches fresh. */
112
134
  maxAge?: number;
113
135
  }
136
+ /** Options for `answer`. */
114
137
  interface ExaAnswerOptions<T = unknown> extends CallOptions {
115
- /** JSON Schema (draft 7) or a Standard Schema for the answer; the answer comes back as an object. */
138
+ /**
139
+ * JSON Schema (draft 7) or a Standard Schema for the answer. The checked
140
+ * object comes back as `output`, and `answer` holds it as JSON text.
141
+ */
116
142
  schema?: OutputSchema<T>;
117
143
  systemPrompt?: string;
118
144
  /** Two-letter country code that localizes the search. */
119
145
  country?: string;
120
146
  model?: "exa" | "exa-pro" | "exa-research" | "exa-fast";
121
147
  }
148
+ /**
149
+ * Options for `research`, which starts an Exa agent run and waits for it as an
150
+ * asynchronous job. A run that stops early with output is returned with status
151
+ * `partial`.
152
+ */
122
153
  interface ExaResearchOptions<T = unknown> extends CallOptions {
154
+ /** Output in the shape of this schema, sent as JSON Schema draft 7. Without one the output is text. */
123
155
  schema?: OutputSchema<T>;
124
156
  /** Cost and reasoning preference. Defaults to `auto`. */
125
157
  effort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "auto" | "ultra";
126
- /** Spend cap in dollars, 1 to 100. Only `auto` and `ultra` accept it. */
158
+ /** Spend cap in dollars, 1 to 100. Only `auto` and `ultra` accept it; other efforts are refused. */
127
159
  maxCostDollars?: number;
128
- /** Soft time limit in seconds, 300 to 10,800. Only `ultra` accepts it. */
160
+ /** Soft time limit in seconds, 300 to 10,800. Only `ultra` accepts it; other efforts are refused. */
129
161
  maxDurationSeconds?: number;
130
162
  systemPrompt?: string;
131
163
  /** Records for the run to enrich, and records it must not return. */
@@ -143,7 +175,9 @@ interface ExaResearchOptions<T = unknown> extends CallOptions {
143
175
  */
144
176
  resume?: string;
145
177
  }
178
+ /** An event Exa can send to a monitor's webhook. */
146
179
  type ExaWebhookEvent = "monitor.created" | "monitor.updated" | "monitor.deleted" | "monitor.run.created" | "monitor.run.completed";
180
+ /** Options for `monitor.create`. */
147
181
  interface ExaMonitorCreateOptions extends CallOptions {
148
182
  /** What to search for on every run, in plain words. */
149
183
  query: string;
@@ -151,7 +185,8 @@ interface ExaMonitorCreateOptions extends CallOptions {
151
185
  webhookUrl: string;
152
186
  /**
153
187
  * How often the monitor runs: whole hours or days, at least one hour. Exa
154
- * has no cron. Leave it out for a monitor that runs only when triggered.
188
+ * has no cron. `week` is sent as `7d`. Leave it out for a monitor that runs
189
+ * only when triggered.
155
190
  */
156
191
  schedule?: Extract<MonitorSchedule, {
157
192
  every: unknown;
@@ -170,11 +205,14 @@ interface ExaMonitorCreateOptions extends CallOptions {
170
205
  /** Defaults to what Exa chooses. */
171
206
  webhookEvents?: ExaWebhookEvent[];
172
207
  }
208
+ /** Options for `monitor.events`. Each event is one run of the monitor. */
173
209
  interface ExaMonitorEventsOptions extends CallOptions {
210
+ /** The `next` cursor of an earlier page. */
174
211
  cursor?: string;
175
212
  /** Runs per page, 1 to 100. */
176
213
  limit?: number;
177
214
  }
215
+ /** The `monitor` group: create, get, list, delete and events. `list` reads every page. */
178
216
  type ExaMonitor = {
179
217
  create: (options: ExaMonitorCreateOptions) => Promise<MonitorInfo>;
180
218
  get: (id: string, options?: CallOptions) => Promise<MonitorInfo>;
@@ -182,6 +220,10 @@ type ExaMonitor = {
182
220
  delete: (id: string, options?: CallOptions) => Promise<void>;
183
221
  events: (id: string, options?: ExaMonitorEventsOptions) => Promise<MonitorEvents>;
184
222
  };
223
+ /**
224
+ * What Exa can do: search, read, readMany, extract, answer, research and
225
+ * monitor. `research` is an asynchronous job and accepts `resume`.
226
+ */
185
227
  interface ExaOperations {
186
228
  search: (query: string, options?: ExaSearchOptions) => Promise<SearchResponse>;
187
229
  read: (url: string, options?: ExaReadOptions) => Promise<Page>;
package/dist/exa.js CHANGED
@@ -1,24 +1,32 @@
1
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";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.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-COHKvfH9.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
6
  import * as z from "zod/mini";
7
7
  const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
8
+ /** The search types that take `additionalQueries`. */
8
9
  const DEEP_TYPES = /* @__PURE__ */ new Set([
9
10
  "deep-lite",
10
11
  "deep",
11
12
  "deep-reasoning"
12
13
  ]);
14
+ /**
15
+ * A `YYYY-MM-DD` date as a UTC date-time, at the start of the day or (for an
16
+ * upper bound) its last millisecond, so the filter covers the whole day. Any
17
+ * other value passes through.
18
+ */
13
19
  const dateTime = (value, endOfDay) => {
14
20
  if (value === void 0 || !DATE_ONLY.test(value)) return value;
15
21
  return endOfDay ? `${value}T23:59:59.999Z` : `${value}T00:00:00.000Z`;
16
22
  };
23
+ /** The cost and request id Exa reports, with any warnings. */
17
24
  const responseMeta = (body, warnings) => meta({
18
25
  costUsd: body.costDollars.total,
19
26
  requestId: body.requestId,
20
27
  warnings
21
28
  });
29
+ /** Exa's `summary` content option. A schema asks for a structured summary and is sent even when `summary` is off. */
22
30
  const summaryOption = (summary, schema) => {
23
31
  if (summary === void 0 || summary === false) return schema ? compact({ schema }) : void 0;
24
32
  return compact({
@@ -26,6 +34,7 @@ const summaryOption = (summary, schema) => {
26
34
  schema
27
35
  });
28
36
  };
37
+ /** Refuses option combinations Exa does not accept, before the request is sent. */
29
38
  const checkSearch = (o) => {
30
39
  if (o.type === "lite") {
31
40
  const unsupported = [
@@ -42,10 +51,15 @@ const checkSearch = (o) => {
42
51
  if ((o.category === "company" || o.category === "people") && dated) throw invalidRequest("exa", `category "${o.category}" does not accept publishedAfter or publishedBefore`);
43
52
  if (o.category === "people" && o.excludeDomains !== void 0) throw invalidRequest("exa", "category \"people\" does not accept excludeDomains");
44
53
  };
54
+ /** Exa's `highlights` option: `true`, or the query and length limit that steer the passages. */
45
55
  const highlightsOption = (highlights) => typeof highlights === "object" ? compact({
46
56
  maxCharacters: highlights.maxCharacters,
47
57
  query: highlights.query
48
58
  }) : true;
59
+ /**
60
+ * The `contents` of a search request. Highlights are on unless `highlights` is
61
+ * false. Undefined when nothing is asked for.
62
+ */
49
63
  const searchContents = (o) => {
50
64
  const contents = compact({
51
65
  highlights: o.highlights === false ? void 0 : highlightsOption(o.highlights),
@@ -55,6 +69,10 @@ const searchContents = (o) => {
55
69
  });
56
70
  return Object.keys(contents).length > 0 ? contents : void 0;
57
71
  };
72
+ /**
73
+ * A search result. `snippet` joins the highlights with " … ". Exa's `summary`
74
+ * is not mapped; it stays in `raw`.
75
+ */
58
76
  const searchResult = (result) => compact({
59
77
  author: result.author,
60
78
  content: result.text,
@@ -66,11 +84,21 @@ const searchResult = (result) => compact({
66
84
  title: result.title,
67
85
  url: result.url ?? ""
68
86
  });
87
+ /**
88
+ * The answer Exa generated from the results: text as it is (none when empty),
89
+ * or an object serialized as JSON text. Undefined when Exa sent none; the
90
+ * object itself stays in `raw`.
91
+ */
69
92
  const generatedAnswer = (output) => {
70
93
  const { text, value } = output.content;
71
94
  if (text !== void 0) return text === "" ? void 0 : text;
72
95
  return value === void 0 || value === null ? void 0 : JSON.stringify(value);
73
96
  };
97
+ /**
98
+ * The `/contents` options for a read. Page text is always requested (capped
99
+ * when `maxCharacters` is set); `query` asks for highlights; links and image
100
+ * links default to 100 each, and `0` leaves them out.
101
+ */
74
102
  const readBody = (o) => {
75
103
  const links = o.linkLimit ?? 100;
76
104
  const images = o.imageLimit ?? 100;
@@ -87,16 +115,23 @@ const readBody = (o) => {
87
115
  text: o.maxCharacters === void 0 ? true : { maxCharacters: o.maxCharacters }
88
116
  });
89
117
  };
118
+ /**
119
+ * The error code for a URL Exa failed to read. Exa reports this per URL in the
120
+ * response, not as an HTTP error: its `tag` decides first, then the HTTP
121
+ * status it saw.
122
+ */
90
123
  const failureCode = (tag, httpStatus) => {
91
124
  if (tag === "CRAWL_NOT_FOUND" || tag === "CONTENT_NOT_CACHED") return "NotFound";
92
125
  if (tag === "CRAWL_TIMEOUT") return "Timeout";
93
126
  if (httpStatus === 404 || httpStatus === 410) return "NotFound";
94
127
  return httpStatus === 408 || httpStatus === 504 ? "Timeout" : "ProviderError";
95
128
  };
129
+ /** Why a URL failed, for an error message: Exa's tag, else its HTTP status, else the status text. */
96
130
  const statusReason = (status) => {
97
131
  const { httpStatusCode, tag } = status.error;
98
132
  return tag ?? (httpStatusCode === void 0 ? void 0 : `HTTP ${httpStatusCode}`) ?? status.status.text ?? "unknown";
99
133
  };
134
+ /** The URLs Exa reported with a status other than `success`. A status left out is not a failure. */
100
135
  const failedStatuses = (statuses) => statuses.filter(({ status }) => status.value !== void 0 && status.value !== "success");
101
136
  /** A page from a result; the caller adds `raw`. */
102
137
  const pageFrom = (url, result) => compact({
@@ -112,6 +147,7 @@ const pageFrom = (url, result) => compact({
112
147
  title: result.title,
113
148
  url: result.url ?? url
114
149
  });
150
+ /** Whether a run has the output asked for: the structured value, or the text. */
115
151
  const hasOutput = (run, structured) => structured ? run.output.structured !== void 0 && run.output.structured !== null : run.output.text !== void 0;
116
152
  const runMeta = (run) => {
117
153
  const { usage } = run;
@@ -125,11 +161,13 @@ const runMeta = (run) => {
125
161
  }
126
162
  });
127
163
  };
164
+ /** Refuses a budget the chosen `effort` does not take, before the run starts. */
128
165
  const checkResearch = (o) => {
129
166
  const effort = o.effort ?? "auto";
130
167
  if (o.maxCostDollars !== void 0 && effort !== "auto" && effort !== "ultra") throw invalidRequest("exa", `maxCostDollars needs effort "auto" or "ultra", not "${effort}"`);
131
168
  if (o.maxDurationSeconds !== void 0 && effort !== "ultra") throw invalidRequest("exa", `maxDurationSeconds needs effort "ultra", not "${effort}"`);
132
169
  };
170
+ /** The body that starts an agent run. `continueFrom` is sent as `previousRunId`. */
133
171
  const researchBody = (question, o) => {
134
172
  const budget = compact({
135
173
  maxCostDollars: o.maxCostDollars,
@@ -149,6 +187,24 @@ const researchBody = (question, o) => {
149
187
  systemPrompt: o.systemPrompt
150
188
  });
151
189
  };
190
+ const RUN_STATES = {
191
+ done: ["completed"],
192
+ failed: ["failed", "cancelled"],
193
+ running: ["queued", "running"]
194
+ };
195
+ /** The run once it has stopped, undefined while it runs. A failed or cancelled run can still carry partial output, so `researchResult` decides what it amounts to. */
196
+ const runState = (id, entry) => jobState("exa", id, RUN_STATES, {
197
+ original: entry.original,
198
+ value: entry.value.status
199
+ }) === "running" ? void 0 : entry;
200
+ /**
201
+ * The result of a finished run. A run that did not complete and has no output
202
+ * throws `JobFailed` with Exa's error, and so does a completed run without
203
+ * it. Otherwise the result is `completed`
204
+ * only when the run completed and stopped for no reason or with
205
+ * `schema_satisfied`; any other finish is `partial`, with the stop reason.
206
+ * `continuationId` is the run's id once it has completed.
207
+ */
152
208
  const researchResult = (id, entry, structured) => {
153
209
  const run = entry.value;
154
210
  const { stopReason } = run;
@@ -173,13 +229,17 @@ const researchResult = (id, entry, structured) => {
173
229
  fields: fields.length > 0 ? fields : void 0,
174
230
  id,
175
231
  meta: runMeta(run),
176
- output: structured ? output.structured : output.text,
232
+ output: requireOutput("exa", id, {
233
+ original: entry.original,
234
+ value: structured ? output.structured : output.text
235
+ }),
177
236
  raw: entry.original,
178
237
  sources: uniqueCitations(fields.flatMap((field) => field.citations)),
179
238
  status: finished ? "completed" : "partial",
180
239
  stopReason: finished ? void 0 : stopReason ?? status
181
240
  });
182
241
  };
242
+ /** Exa's trigger period for an interval schedule: `hour`, `day` and `week` become `1h`, `1d` and `7d`. Exa has no cron. */
183
243
  const intervalPeriod = (schedule) => {
184
244
  const { every } = record(schedule);
185
245
  if (typeof every !== "string") throw invalidRequest("exa", "monitors run on an interval of whole hours or days; Exa has no cron");
@@ -190,7 +250,9 @@ const intervalPeriod = (schedule) => {
190
250
  if (!/^[1-9]\d*[hd]$/u.test(value)) throw invalidRequest("exa", `monitor schedule "${every}" is not whole hours or days, at least 1h`);
191
251
  return value;
192
252
  };
253
+ /** The trigger period for a monitor's schedule; undefined for a monitor with none. */
193
254
  const period = (schedule) => schedule === void 0 ? void 0 : intervalPeriod(schedule);
255
+ /** A monitor from Exa's entry; `schedule` is its trigger period and `watch` its search query. */
194
256
  const monitorInfo = (entry) => {
195
257
  const found = entry.value;
196
258
  return compact({
@@ -203,11 +265,16 @@ const monitorInfo = (entry) => {
203
265
  webhookUrl: found.webhook.url
204
266
  });
205
267
  };
268
+ /** What a run found: its generated text, or the failure when it failed. Undefined otherwise. */
206
269
  const eventSummary = (run) => {
207
270
  const { text } = run.output.content;
208
271
  if (text !== void 0) return text === "" ? void 0 : text;
209
272
  if (run.status === "failed") return `Run failed${run.failReason === void 0 ? "" : `: ${run.failReason}`}`;
210
273
  };
274
+ /**
275
+ * One run of a monitor as an event. `output` is set only when the run's
276
+ * content is a structured value rather than text.
277
+ */
211
278
  const monitorEvent = (entry) => {
212
279
  const run = entry.value;
213
280
  const { text, value } = run.output.content;
@@ -289,6 +356,7 @@ const SearchResponse = looseObject({
289
356
  results: arrayOf(Result),
290
357
  warnings: arrayOf(warningEntry)
291
358
  });
359
+ /** The sources behind one field of a run's output, with Exa's confidence in it. */
292
360
  const Grounding = looseObject({
293
361
  citations: arrayOf(Source),
294
362
  confidence: optionalStringOrNumber,
@@ -321,6 +389,7 @@ const Run = looseObject({
321
389
  const RunEntry = withOriginal(Run);
322
390
  /** The reply to starting a run. */
323
391
  const RunStart = looseObject({ id: withOriginal(optionalId) });
392
+ /** A monitor. `trigger.period` is its schedule and `search.query` what it watches. */
324
393
  const Monitor = looseObject({
325
394
  createdAt: optionalString,
326
395
  id: withOriginal(optionalId),
@@ -337,6 +406,7 @@ const MonitorsPage = looseObject({
337
406
  hasMore: optionalBoolean,
338
407
  nextCursor: optionalString
339
408
  });
409
+ /** One run of a monitor; `output.content` is its generated report, text or a value. */
340
410
  const MonitorRun = looseObject({
341
411
  completedAt: optionalString,
342
412
  createdAt: optionalString,
@@ -368,6 +438,7 @@ const exa = (config = {}) => {
368
438
  provider: "exa",
369
439
  retries: config.retries
370
440
  });
441
+ /** Calls `/contents` for these URLs. A URL Exa could not read is in `statuses`, not an error. */
371
442
  const fetchContents = async (urls, body, call) => {
372
443
  const response = await raw.request("POST", "/contents", {
373
444
  ...call,
@@ -381,6 +452,7 @@ const exa = (config = {}) => {
381
452
  response
382
453
  };
383
454
  };
455
+ /** Reads one URL. Throws when Exa reports a failure for it or returns no result. */
384
456
  const readOne = async (url, body, call) => {
385
457
  const { body: parsed, response } = await fetchContents([url], body, call);
386
458
  const [failed] = failedStatuses(parsed.statuses);
@@ -558,11 +630,7 @@ const exa = (config = {}) => {
558
630
  const { call, rest: o } = callSettings(options);
559
631
  checkResearch(o);
560
632
  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
- },
633
+ check: async (id, request) => runState(id, z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request))),
566
634
  finish: async (run, id) => {
567
635
  const { outputSchema } = run.value.request;
568
636
  const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
@@ -572,11 +640,10 @@ const exa = (config = {}) => {
572
640
  output: await checkOutput(o.schema, result.output, { provider: "exa" })
573
641
  };
574
642
  },
575
- start: async () => requireJobId("exa", z.parse(RunStart, await raw.request("POST", "/agent/runs", {
576
- creates: true,
643
+ start: async () => await startJob(raw, "/agent/runs", {
577
644
  ...call,
578
645
  body: researchBody(question, o)
579
- })).id)
646
+ }, RunStart, (reply) => reply.id)
580
647
  }, {
581
648
  ...call,
582
649
  interval: o.interval,
@@ -1,4 +1,4 @@
1
- import { m as Capability, n as AnyAdapter } from "./adapter-BgdfLBs-.js";
1
+ import { m as Capability, n as AnyAdapter } from "./adapter-Bh8EIrNe.js";
2
2
  /** Why a call failed. Branch on this, not on the message, which can change. */
3
3
  type FieldworkErrorCode =
4
4
  /** The adapter's provider does not offer this capability. */
@@ -6,15 +6,24 @@ type FieldworkErrorCode =
6
6
  /** The API key is missing or the provider rejected it. */
7
7
  "Unauthorized" |
8
8
  /** The provider refused the request because of a rate or plan limit. */
9
- "RateLimited" | "NotFound" |
10
- /** The provider rejected the request as malformed. */
9
+ "RateLimited" |
10
+ /** A 404, or a page read that answered 404 or 410. */
11
+ "NotFound" |
12
+ /** The request is malformed or combines options the provider rejects: its 400 or 422, or Fieldwork refusing it before sending. */
11
13
  "InvalidRequest" |
12
14
  /** An asynchronous job finished without a result. */
13
- "JobFailed" | "Timeout" | "Aborted" |
15
+ "JobFailed" |
16
+ /** The call's `timeout` ran out, a job did not finish within it, or the provider answered 408. */
17
+ "Timeout" |
18
+ /** The caller's `signal` cancelled the call. */
19
+ "Aborted" |
14
20
  /** Any other provider failure. */
15
21
  "ProviderError";
22
+ /** What a `FieldworkError` carries besides its code and message. */
16
23
  interface FieldworkErrorOptions {
24
+ /** The provider the call was for, such as "exa". */
17
25
  provider?: string;
26
+ /** The HTTP status the provider answered with. */
18
27
  status?: number;
19
28
  /** Seconds the provider asked to wait before retrying. */
20
29
  retryAfter?: number;
@@ -22,14 +31,18 @@ interface FieldworkErrorOptions {
22
31
  jobId?: string;
23
32
  /** Overrides the default, which follows from the code and status. */
24
33
  retryable?: boolean;
34
+ /** What the failure came from, such as the provider's parsed error body or the underlying fetch error. */
25
35
  cause?: unknown;
26
36
  }
27
37
  /** The one error type every adapter throws, with a normalized code. */
28
38
  declare class FieldworkError extends Error {
29
39
  readonly name = "FieldworkError";
30
40
  readonly code: FieldworkErrorCode;
41
+ /** The provider the call was for, when the error came from one. */
31
42
  readonly provider?: string;
43
+ /** The HTTP status the provider answered with, when there was a response. */
32
44
  readonly status?: number;
45
+ /** Seconds the provider asked to wait before retrying, from its `Retry-After` header. */
33
46
  readonly retryAfter?: number;
34
47
  /**
35
48
  * The provider's id for an asynchronous job that was already created when
@@ -55,7 +68,9 @@ declare class FieldworkError extends Error {
55
68
  status: number | undefined;
56
69
  };
57
70
  }
71
+ /** What `new Fieldwork` takes. */
58
72
  interface FieldworkOptions<A extends AnyAdapter> {
73
+ /** The provider to call, such as `exa()`, or a `router` over several. */
59
74
  adapter: A;
60
75
  }
61
76
  interface FieldworkBase<A extends AnyAdapter> {
@@ -65,6 +80,7 @@ interface FieldworkBase<A extends AnyAdapter> {
65
80
  readonly capabilities: Readonly<Record<Capability, boolean>>;
66
81
  /** The provider's HTTP API, for anything Fieldwork does not wrap. */
67
82
  readonly raw: A["raw"];
83
+ /** Whether the capability can be called. Same as `capabilities[capability]`. */
68
84
  supports: (capability: Capability) => boolean;
69
85
  /** The provider that serves a capability, or undefined when none does. */
70
86
  providerFor: (capability: Capability) => string | undefined;