@howells/fieldwork-sdk 0.5.1 → 0.5.2

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.
@@ -1,10 +1,13 @@
1
- import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, b as Decisions, g as Condition, j as ImageSearch, l as Answer, p as CallOptions, q as Research, t as Adapter, x as Discovery, y as DecisionQuestion, 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, b as Decisions, g as Condition, j as ImageSearch, l as Answer, p as CallOptions, q as Research, t as Adapter, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-BhTK51Yj.js";
2
+ import { t as OutputSchema } from "./schema-CNd51xdD.js";
3
3
  import "./util-DhYr1OS3.js";
4
+ /** Settings for `parallel()`. */
4
5
  interface ParallelConfig {
5
6
  /** Defaults to the PARALLEL_API_KEY environment variable. */
6
7
  apiKey?: string;
8
+ /** Defaults to https://api.parallel.ai. */
7
9
  baseUrl?: string;
10
+ /** Used in place of the global `fetch`. */
8
11
  fetch?: typeof fetch;
9
12
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
10
13
  retries?: number;
@@ -22,12 +25,17 @@ interface ParallelSources {
22
25
  * Parallel ignores `excludeDomains`, so passing both is refused.
23
26
  */
24
27
  includeDomains?: string[];
28
+ /** Same forms as `includeDomains`. Not combinable with it. */
25
29
  excludeDomains?: string[];
26
- /** YYYY-MM-DD. */
30
+ /** YYYY-MM-DD. Sent as `after_date`; there is no `publishedBefore`. */
27
31
  publishedAfter?: string;
28
32
  }
29
33
  /** Task metadata: keys up to 16 characters, values up to 512. */
30
34
  type ParallelMetadata = Record<string, string | number | boolean>;
35
+ /**
36
+ * Options for `search` (`POST /v1/search`). A `maxAge` under 600 is refused. There
37
+ * is no `recency` or `publishedBefore`; use `publishedAfter`.
38
+ */
31
39
  interface ParallelSearchOptions extends CallOptions, ParallelSources {
32
40
  /** What the search is for, in plain words. Defaults to the query. */
33
41
  objective?: string;
@@ -38,6 +46,7 @@ interface ParallelSearchOptions extends CallOptions, ParallelSources {
38
46
  * `basic` or `advanced` (the default, richer retrieval).
39
47
  */
40
48
  mode?: "turbo" | "fast" | "basic" | "advanced";
49
+ /** Sent as `max_results`. */
41
50
  limit?: number;
42
51
  /** ISO 3166-1 alpha-2 code such as "GB", for geo-targeted results. */
43
52
  country?: string;
@@ -50,16 +59,23 @@ interface ParallelSearchOptions extends CallOptions, ParallelSources {
50
59
  /** Groups calls made for one larger task; Parallel may use it to improve later results. */
51
60
  sessionId?: string;
52
61
  }
62
+ /** Options for `images` (`POST /v1/images/search`). */
53
63
  interface ParallelImagesOptions extends CallOptions {
54
64
  /** The images wanted, in plain words, up to 5,000 characters. Defaults to the query. */
55
65
  objective?: string;
56
66
  /** Up to 5 image queries; defaults to the query alone. */
57
67
  queries?: string[];
58
68
  mode?: "fast" | "advanced";
69
+ /** Sent as `max_results`. */
59
70
  limit?: number;
71
+ /** ISO 3166-1 alpha-2 code such as "GB", for geo-targeted results. */
60
72
  country?: string;
61
73
  sessionId?: string;
62
74
  }
75
+ /**
76
+ * Options for `read` (`POST /v1/extract`). The page text comes back as `markdown`;
77
+ * `query` and `queries` add focused `excerpts`. A `maxAge` under 600 is refused.
78
+ */
63
79
  interface ParallelReadOptions extends CallOptions {
64
80
  /** Return passages that answer this as `excerpts`. Sent as Parallel's `objective`. */
65
81
  query?: string;
@@ -67,7 +83,10 @@ interface ParallelReadOptions extends CallOptions {
67
83
  queries?: string[];
68
84
  /** Seconds a cached copy may be old. Parallel's minimum is 600; lower values are refused. */
69
85
  maxAge?: number;
70
- /** Cap on the characters of the page text returned for each URL. */
86
+ /**
87
+ * Cap on the characters of the page text returned for each URL. Without it,
88
+ * or at 0, the full content is requested with no cap.
89
+ */
71
90
  maxContentChars?: number;
72
91
  /** Cap on the characters of excerpts returned for each URL. */
73
92
  maxCharsPerResult?: number;
@@ -75,7 +94,15 @@ interface ParallelReadOptions extends CallOptions {
75
94
  maxCharsTotal?: number;
76
95
  sessionId?: string;
77
96
  }
97
+ /**
98
+ * Options for `readMany`: the same as `read`, applied to every URL. Parallel takes
99
+ * at most 20 URLs in one call.
100
+ */
78
101
  type ParallelReadManyOptions = ParallelReadOptions;
102
+ /**
103
+ * Options for `extract`: a Task run limited to the page's own URL, polled to
104
+ * completion. `resume` waits for an earlier run instead of starting another.
105
+ */
79
106
  interface ParallelExtractOptions<T = unknown> extends CallOptions {
80
107
  /**
81
108
  * The values to extract. Without one, Parallel picks the fields itself (its
@@ -84,6 +111,10 @@ interface ParallelExtractOptions<T = unknown> extends CallOptions {
84
111
  * checks `data`.
85
112
  */
86
113
  schema?: OutputSchema<T>;
114
+ /**
115
+ * Instructions for the run. Defaults to one that asks for the values in `schema`
116
+ * from this page only, or for the page's main facts when there is no schema.
117
+ */
87
118
  prompt?: string;
88
119
  /** Defaults to "base". */
89
120
  processor?: ParallelProcessor;
@@ -98,6 +129,10 @@ interface ParallelExtractOptions<T = unknown> extends CallOptions {
98
129
  */
99
130
  resume?: string;
100
131
  }
132
+ /**
133
+ * Options for `answer` (`POST /v1/responses`, synchronous). `includeDomains` and
134
+ * `excludeDomains` are refused together.
135
+ */
101
136
  interface ParallelAnswerOptions<T = unknown> extends CallOptions {
102
137
  /** The answer in the shape of this schema, in `output`. */
103
138
  schema?: OutputSchema<T>;
@@ -109,10 +144,15 @@ interface ParallelAnswerOptions<T = unknown> extends CallOptions {
109
144
  continueFrom?: string;
110
145
  /** Only these domains are searched. Parallel allows one of the two lists. */
111
146
  includeDomains?: string[];
147
+ /** These domains are not searched. Not combinable with `includeDomains`. */
112
148
  excludeDomains?: string[];
113
149
  /** Up to 16 keys, keys up to 64 characters, values up to 512. */
114
150
  metadata?: Record<string, string>;
115
151
  }
152
+ /**
153
+ * Options for `research`: a Task run polled to completion. `includeDomains` and
154
+ * `excludeDomains` are refused together.
155
+ */
116
156
  interface ParallelResearchOptions<T = unknown> extends CallOptions, ParallelSources {
117
157
  /** Structured output in the shape of this schema; without one the output is report text. */
118
158
  schema?: OutputSchema<T>;
@@ -131,6 +171,12 @@ interface ParallelResearchOptions<T = unknown> extends CallOptions, ParallelSour
131
171
  */
132
172
  resume?: string;
133
173
  }
174
+ /**
175
+ * Options for `discover`: a FindAll run (`/v1beta/findall`) that finds entities
176
+ * matching every condition, polled to completion. A run that stops early with at
177
+ * least one match returns `status: "partial"`; one that ends with no match throws
178
+ * `JobFailed`.
179
+ */
134
180
  interface ParallelDiscoverOptions<T = unknown> extends CallOptions {
135
181
  /** What kind of entity to find, such as "companies" or "people". */
136
182
  entityType: string;
@@ -162,13 +208,25 @@ interface ParallelDiscoverOptions<T = unknown> extends CallOptions {
162
208
  */
163
209
  resume?: string;
164
210
  }
211
+ /**
212
+ * Options for `decide` (`POST /v1/decisions`, synchronous). Parallel takes 1 to 100
213
+ * questions named with letters, numbers, underscores and hyphens. A choice
214
+ * question needs 2 to 255 distinct choices and a score scale 2 to 10 levels. All
215
+ * three are refused before sending.
216
+ */
165
217
  interface ParallelDecideOptions extends CallOptions {
166
218
  /** ISO 3166-1 alpha-2 code for geo-targeted search. */
167
219
  country?: string;
168
220
  /** Keep the passages each citation was taken from. Parallel defaults to true. */
169
221
  includeExcerpts?: boolean;
170
222
  }
223
+ /** The event types a monitor webhook can subscribe to. */
171
224
  type ParallelWebhookEvent = "monitor.event.detected" | "monitor.execution.completed" | "monitor.execution.failed";
225
+ /**
226
+ * Options for `monitor.create`. A `query` makes an event-stream monitor that
227
+ * searches the web on each run; a `taskRunId` makes a snapshot monitor of that
228
+ * Task run's output. Pass one of the two. `webhookEvents` needs a `webhookUrl`.
229
+ */
172
230
  interface ParallelMonitorCreateOptions extends CallOptions, ParallelSources {
173
231
  /**
174
232
  * What to watch for, in plain words. Parallel searches the web for it on
@@ -177,17 +235,22 @@ interface ParallelMonitorCreateOptions extends CallOptions, ParallelSources {
177
235
  query?: string;
178
236
  /**
179
237
  * Watch the output of an earlier Task run for changes instead of a query.
180
- * Cannot be combined with `query`, `schema`, `includeBackfill`, `country` or
181
- * the domain filters.
238
+ * Cannot be combined with `query`, `schema`, `includeBackfill`, `country`,
239
+ * `includeDomains`, `excludeDomains` or `publishedAfter`.
182
240
  */
183
241
  taskRunId?: string;
184
- /** Parallel runs at a fixed interval from 1 hour to 30 days; cron is refused. */
242
+ /**
243
+ * Parallel runs at a fixed interval from 1 hour to 30 days; cron is refused.
244
+ * `every` is "hour", "day", "week", or a count such as "6h" (up to 720h) or
245
+ * "3d" (up to 30d).
246
+ */
185
247
  schedule: MonitorSchedule;
186
248
  /** Events come back in the shape of this schema. Events are not checked against a Standard Schema. */
187
249
  schema?: OutputSchema<unknown>;
188
250
  /** The first run returns a sample of recent events (a preview, not exhaustive). */
189
251
  includeBackfill?: boolean;
190
252
  country?: string;
253
+ /** Where Parallel sends webhook events. */
191
254
  webhookUrl?: string;
192
255
  /** Needs `webhookUrl`. Parallel sends every event type when omitted. */
193
256
  webhookEvents?: ParallelWebhookEvent[];
@@ -196,6 +259,10 @@ interface ParallelMonitorCreateOptions extends CallOptions, ParallelSources {
196
259
  /** Keys up to 16 characters, values up to 512. */
197
260
  metadata?: Record<string, string>;
198
261
  }
262
+ /**
263
+ * Options for `monitor.events`: one page of a monitor's events. Pass the result's
264
+ * `next` as `cursor` for the following page.
265
+ */
199
266
  interface ParallelMonitorEventsOptions extends CallOptions {
200
267
  cursor?: string;
201
268
  /** 1 to 100. Parallel defaults to 20. */
@@ -212,6 +279,11 @@ interface ParallelMonitorEventsOptions extends CallOptions {
212
279
  type ParallelDiscovery<T> = Discovery<T> & {
213
280
  stopReason?: string;
214
281
  };
282
+ /**
283
+ * What Parallel offers: search, images, read, readMany, extract, answer, research,
284
+ * discover, decide and monitor. `extract`, `research` and `discover` run as jobs
285
+ * and accept `resume`.
286
+ */
215
287
  interface ParallelOperations {
216
288
  search: (query: string, options?: ParallelSearchOptions) => Promise<SearchResponse>;
217
289
  images: (query: string, options?: ParallelImagesOptions) => Promise<ImageSearch>;
package/dist/parallel.js CHANGED
@@ -1,27 +1,42 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { i as withJob, 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, P as meta, S as withOriginal, T as requireKey, V as uniqueCitations, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as citationsOf, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, v as recordOf, x as warnings, y as sourceShape, z as refuseTogether } 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 { i as withJob, 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, P as meta, S as withOriginal, T as requireKey, V as uniqueCitations, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as citationsOf, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, v as recordOf, x as warnings, y as sourceShape, z as refuseTogether } from "./parse-BY3R0oWO.js";
4
+ import { t as runJob } from "./job-DVsmQMKP.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/parallel/parse.ts
8
+ /** The name this adapter reports in errors and results. */
8
9
  const provider = "parallel";
10
+ /**
11
+ * The object with undefined fields removed, or undefined when none is left, so an
12
+ * empty settings block is not sent.
13
+ */
9
14
  const nonEmpty = (value) => {
10
15
  const result = compact(value);
11
16
  return Object.keys(result).length > 0 ? result : void 0;
12
17
  };
18
+ /**
19
+ * Parallel's usage entries as a map of unit name to count, summing repeated names.
20
+ * An entry without a name or count is skipped.
21
+ */
13
22
  const usageUnits = (entries) => {
14
23
  const units = /* @__PURE__ */ new Map();
15
24
  for (const { count, name } of entries) if (name !== void 0 && count !== void 0) units.set(name, (units.get(name) ?? 0) + count);
16
25
  return Object.fromEntries(units);
17
26
  };
27
+ /**
28
+ * The evidence Parallel gives for each field, as field sources. A missing `field`
29
+ * becomes an empty string.
30
+ */
18
31
  const basis = (entries) => entries.map((entry) => compact({
19
32
  citations: citationsOf(entry.citations),
20
33
  confidence: entry.confidence,
21
34
  field: entry.field ?? "",
22
35
  reasoning: entry.reasoning
23
36
  }));
37
+ /** The unique citations across the fields' sources. */
24
38
  const citedBy = (fields) => uniqueCitations(fields.flatMap((field) => field.citations));
39
+ /** Meta for a Task result: the run id as `requestId`, and the run's warnings. */
25
40
  const taskMeta = (result) => {
26
41
  const { run } = result.value;
27
42
  return meta({
@@ -35,15 +50,26 @@ const responseMessages = (body) => {
35
50
  const final = messages.filter((item) => item.phase === "final_answer");
36
51
  return final.length > 0 ? final : messages;
37
52
  };
53
+ /**
54
+ * A decision's probabilities without the entries Parallel left undefined, or
55
+ * undefined when none remain.
56
+ */
38
57
  const probabilities = (chances) => {
39
58
  const entries = Object.entries(chances).filter((entry) => entry[1] !== void 0);
40
59
  return entries.length > 0 ? Object.fromEntries(entries) : void 0;
41
60
  };
61
+ /** The key with the highest probability; the first one wins a tie. */
42
62
  const mostLikely = (chances) => {
43
63
  let best;
44
64
  for (const [key, chance] of Object.entries(chances ?? {})) if (best === void 0 || chance > (chances?.[best] ?? 0)) best = key;
45
65
  return best;
46
66
  };
67
+ /**
68
+ * One decision answer in the shape its question asks for. A `refusal` answer
69
+ * becomes `{ refusal }`. A `yesno` answer keeps only `probability`. A `score`
70
+ * answer's probabilities are keyed by the scale's own keys and its `choice` is the
71
+ * most likely of them; Parallel's numeric `score` stays in `raw`.
72
+ */
47
73
  const decisionAnswer = (question, answer) => {
48
74
  if (answer.type === "refusal") return { refusal: "Parallel declined to answer this question" };
49
75
  const { confidence } = answer;
@@ -64,6 +90,11 @@ const decisionAnswer = (question, answer) => {
64
90
  };
65
91
  /** Termination reasons that mean the run found everything it could. */
66
92
  const FINISHED = /* @__PURE__ */ new Set(["match_limit_met", "candidates_exhausted"]);
93
+ /**
94
+ * A FindAll candidate as an entity, or undefined when Parallel discarded it.
95
+ * `matched` is true or false for the `matched` and `unmatched` statuses and unset
96
+ * for any other. Only `enrichment` outputs reach `data`; the rest stay in `raw`.
97
+ */
67
98
  const candidate = (item) => {
68
99
  const status = item.match_status;
69
100
  if (status === "discarded") return;
@@ -84,6 +115,10 @@ const candidate = (item) => {
84
115
  url: item.url
85
116
  });
86
117
  };
118
+ /**
119
+ * A monitor from Parallel's entry. `watch` is the monitor's `settings.query` and
120
+ * `schedule` is Parallel's frequency string. A missing id throws.
121
+ */
87
122
  const monitorInfo = (entry) => {
88
123
  const monitor = entry.value;
89
124
  return compact({
@@ -96,6 +131,12 @@ const monitorInfo = (entry) => {
96
131
  webhookUrl: monitor.webhook.url
97
132
  });
98
133
  };
134
+ /**
135
+ * A monitor event by `event_type`. A `completion` is a run that found no change,
136
+ * with a fixed summary. An `error` takes its message as the summary. A `snapshot`
137
+ * reads `changed_output`; any other type reads `output`. Completions and errors
138
+ * are dated by `timestamp`, changes by `event_date`.
139
+ */
99
140
  const monitorEvent = (entry) => {
100
141
  const event = entry.value;
101
142
  const type = event.event_type;
@@ -134,6 +175,10 @@ const pageFrom = (entry, extra = {}) => {
134
175
  ...extra
135
176
  });
136
177
  };
178
+ /**
179
+ * Why one URL failed, as `type: HTTP status: content`. A missing type reads as
180
+ * "error"; missing parts are left out.
181
+ */
137
182
  const extractFailure = (error) => {
138
183
  const status = error.http_status_code;
139
184
  return [
@@ -142,11 +187,18 @@ const extractFailure = (error) => {
142
187
  error.content
143
188
  ].filter((part) => part !== void 0).join(": ");
144
189
  };
190
+ /** Meta for an Extract response: its id as `requestId`, usage units and warnings. */
145
191
  const extractMeta = (body) => meta({
146
192
  requestId: body.extract_id.id,
147
193
  units: usageUnits(body.usage),
148
194
  warnings: body.warnings
149
195
  });
196
+ /**
197
+ * A finished FindAll run as a discovery. The run counts as stopped early when its
198
+ * status is not `completed` or its termination reason is not in `FINISHED`. Stopped
199
+ * early with at least one matched entity, it is `partial` with a `stopReason` and
200
+ * a warning; with none, it throws `JobFailed`. Discarded candidates are left out.
201
+ */
150
202
  const discovery = (id, entry) => {
151
203
  const run = entry.value.run.status;
152
204
  const { metrics } = run;
@@ -175,7 +227,13 @@ const discovery = (id, entry) => {
175
227
  stopReason: stoppedEarly ? stopReason : void 0
176
228
  });
177
229
  };
230
+ /** The characters Parallel allows in a decision question's name. */
178
231
  const QUESTION_NAME = /^[A-Za-z0-9_-]+$/u;
232
+ /**
233
+ * Parallel's `source_policy`, or undefined when no filter is set. Refuses both
234
+ * domain lists together, since Parallel ignores the exclude list when an include
235
+ * list is present.
236
+ */
179
237
  const sourcePolicy = (o) => {
180
238
  refuseTogether(provider, o, "includeDomains", "excludeDomains");
181
239
  return nonEmpty({
@@ -184,14 +242,27 @@ const sourcePolicy = (o) => {
184
242
  include_domains: o.includeDomains
185
243
  });
186
244
  };
245
+ /**
246
+ * Parallel's `fetch_policy` for a `maxAge`, rounded up to whole seconds. Refuses a
247
+ * value under the minimum: Parallel has no setting that always fetches fresh.
248
+ */
187
249
  const fetchPolicy = (maxAge) => {
188
250
  if (maxAge !== void 0 && maxAge < 600) throw invalidRequest(provider, `cannot use a cached copy younger than 600 seconds (maxAge was ${maxAge}); it has no setting that always fetches fresh`);
189
251
  return maxAge === void 0 ? void 0 : { max_age_seconds: Math.ceil(maxAge) };
190
252
  };
253
+ /**
254
+ * Parallel's JSON output spec (`type: "json"`) for a schema, as Tasks and monitors
255
+ * take it.
256
+ */
191
257
  const jsonOutput = (schema) => ({
192
258
  json_schema: jsonSchemaOf(schema),
193
259
  type: "json"
194
260
  });
261
+ /**
262
+ * Parallel's form of a normalized decision question: `yesno` is `noul`, `choice`
263
+ * keeps its type and `score` takes the scale's labels, in order, as criteria.
264
+ * Refuses a choice or score count outside Parallel's limits.
265
+ */
195
266
  const decisionQuestion = (name, question) => {
196
267
  if (question.type === "yesno") return {
197
268
  instructions: question.question,
@@ -217,11 +288,16 @@ const decisionQuestion = (name, question) => {
217
288
  }
218
289
  throw invalidRequest(provider, `does not know the question type "${String(question.type)}" for "${name}"`);
219
290
  };
291
+ /** Parallel's short form of each named schedule. */
220
292
  const NAMED_FREQUENCY = {
221
293
  day: "1d",
222
294
  hour: "1h",
223
295
  week: "1w"
224
296
  };
297
+ /**
298
+ * Parallel's `frequency` string for a schedule: a named interval, or `<n>h` up to
299
+ * 720 or `<n>d` up to 30. Refuses cron and anything outside 1 hour to 30 days.
300
+ */
225
301
  const frequency = (schedule) => {
226
302
  if ("cron" in schedule) throw invalidRequest(provider, "monitors run at a fixed interval from 1 hour to 30 days and cannot follow a cron expression; pass { every: ... }");
227
303
  const named = Object.entries(NAMED_FREQUENCY).find(([name]) => name === schedule.every)?.[1];
@@ -232,6 +308,10 @@ const frequency = (schedule) => {
232
308
  if (!match || count < 1 || count > limit) throw invalidRequest(provider, `monitors run every 1 hour to 30 days; "${schedule.every}" is outside that`);
233
309
  return schedule.every;
234
310
  };
311
+ /**
312
+ * The `/v1/extract` body that `read` and `readMany` share. It always asks for
313
+ * `full_content`, capped only when `maxContentChars` is a non-zero number.
314
+ */
235
315
  const extractBody = (urls, o) => compact({
236
316
  advanced_settings: compact({
237
317
  excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
@@ -287,6 +367,7 @@ const ImagesResponse = looseObject({
287
367
  usage: Usage,
288
368
  warnings
289
369
  });
370
+ /** One URL's result in an Extract response. */
290
371
  const ExtractResult = looseObject({
291
372
  excerpts: arrayOf(z.string()),
292
373
  full_content: optionalString,
@@ -294,7 +375,10 @@ const ExtractResult = looseObject({
294
375
  title: optionalString,
295
376
  url: optionalString
296
377
  });
297
- /** `/v1/extract`. Each result keeps its own entry as it arrived. */
378
+ /**
379
+ * `/v1/extract`. Each result keeps its own entry as it arrived. `extract_id` is
380
+ * read as text (the batch id) and as a request id (a string, number or boolean).
381
+ */
298
382
  const ExtractResponse = looseObject({
299
383
  errors: arrayOf(looseObject({
300
384
  content: optionalString,
@@ -337,6 +421,10 @@ const AnswerResponse = looseObject({
337
421
  total_tokens: optionalNumber
338
422
  })
339
423
  });
424
+ /**
425
+ * One decision answer. `noul` is a yes/no probability; `probabilities` is keyed by
426
+ * choice, or by zero-based score level.
427
+ */
340
428
  const Decision = looseObject({
341
429
  choice: optionalString,
342
430
  confidence: optionalNumber,
@@ -375,6 +463,7 @@ const TaskResult = withOriginal(looseObject({
375
463
  const FindAllStart = looseObject({ findall_id: withOriginal(optionalId) });
376
464
  /** A FindAll run while it is polled. */
377
465
  const FindAllRun = withOriginal(looseObject({ status: looseObject({ status: optionalString }) }));
466
+ /** A FindAll candidate. `output` holds its enrichment values among other outputs. */
378
467
  const Candidate = looseObject({
379
468
  basis: arrayOf(Basis),
380
469
  description: optionalString,
@@ -412,6 +501,10 @@ const MonitorsPage = looseObject({
412
501
  monitors: arrayOf(MonitorEntry),
413
502
  next_cursor: optionalString
414
503
  });
504
+ /**
505
+ * The output of a monitor event: the evidence and the content, read as text and as
506
+ * a structure.
507
+ */
415
508
  const EventOutput = looseObject({
416
509
  basis: arrayOf(Basis),
417
510
  content: Content
@@ -430,6 +523,11 @@ const EventsPage = looseObject({
430
523
  next_cursor: optionalString
431
524
  });
432
525
  // src/adapters/parallel/jobs.ts
526
+ /**
527
+ * The `JobFailed` error for a Task run that ended without a result: cancelled,
528
+ * failed with Parallel's message, or `action_required`, which waits on something
529
+ * Fieldwork cannot do and so never finishes. The run's warnings are appended.
530
+ */
433
531
  const stoppedRun = (id, entry) => {
434
532
  const run = entry.value;
435
533
  const status = run.status ?? "unknown";
@@ -445,6 +543,11 @@ const stoppedRun = (id, entry) => {
445
543
  provider
446
544
  });
447
545
  };
546
+ /**
547
+ * A completed run's result. When the result endpoint answers `NotFound` for a run
548
+ * that failed or was cancelled, this raises that run's `JobFailed` instead; any
549
+ * other error passes through.
550
+ */
448
551
  const taskResult = async (raw, id, request) => {
449
552
  try {
450
553
  return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${segment(id)}/result`, request));
@@ -456,7 +559,11 @@ const taskResult = async (raw, id, request) => {
456
559
  throw error;
457
560
  }
458
561
  };
459
- /** Runs a task to its result, or waits for the run named by `resume`. */
562
+ /**
563
+ * Runs a task to its result, or waits for the run named by `resume`. A failed,
564
+ * cancelled or `action_required` run throws at once; queued, running and
565
+ * cancelling runs are polled again.
566
+ */
460
567
  const runTask = async (raw, body, settings, finish) => await runJob(provider, {
461
568
  check: async (id, request) => {
462
569
  const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
@@ -472,6 +579,11 @@ const runTask = async (raw, body, settings, finish) => await runJob(provider, {
472
579
  signal: settings.signal
473
580
  })).run_id)
474
581
  }, settings);
582
+ /**
583
+ * Starts a FindAll run and returns its id. With a `schema` it then adds the
584
+ * enrichment; if that request fails, the error carries the run's id, since the run
585
+ * already exists.
586
+ */
475
587
  const startFindAll = async (raw, objective, o, call) => {
476
588
  const created = z.parse(FindAllStart, await raw.request("POST", "/v1beta/findall/runs", {
477
589
  creates: true,
@@ -504,7 +616,10 @@ const startFindAll = async (raw, objective, o, call) => {
504
616
  }
505
617
  return id;
506
618
  };
507
- /** The result of a FindAll run once it has stopped, or undefined while it runs. */
619
+ /**
620
+ * The result of a FindAll run once it has stopped (completed, failed or
621
+ * cancelled), or undefined while it runs. `action_required` throws `JobFailed`.
622
+ */
508
623
  const findAllResult = async (raw, id, request) => {
509
624
  const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
510
625
  const { status } = run.value.status;
@@ -1,8 +1,10 @@
1
- import { n as codeForStatus, t as FieldworkError } from "./errors-Yvk42oZH.js";
1
+ import { n as codeForStatus, t as FieldworkError } from "./errors-DROZyb9T.js";
2
2
  import * as z from "zod/mini";
3
3
  // src/util.ts
4
4
  const isJson = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
+ /** The value as an object, or an empty one when it is null, an array or not an object, so a read of a missing body needs no guard. */
5
6
  const record = (value) => isJson(value) ? value : {};
7
+ /** Drops the keys whose value is undefined, so a request body or result carries only what was set. Shallow: nested objects are not touched. */
6
8
  const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
7
9
  /**
8
10
  * Splits an operation's options into the provider's own and the call's
@@ -26,6 +28,13 @@ const callSettings = (options, grace = 0) => {
26
28
  rest
27
29
  };
28
30
  };
31
+ /**
32
+ * Reads a provider field that holds JSON text. A value that is not a string
33
+ * is returned as it is, already parsed.
34
+ *
35
+ * Throws `ProviderError` carrying the parse error as `cause` when the text is
36
+ * not valid JSON.
37
+ */
29
38
  const parseJson = (provider, value) => {
30
39
  if (typeof value !== "string") return value;
31
40
  try {
@@ -37,6 +46,7 @@ const parseJson = (provider, value) => {
37
46
  });
38
47
  }
39
48
  };
49
+ /** The citations with repeated URLs removed: the first of each URL stays, in order. */
40
50
  const uniqueCitations = (all) => {
41
51
  const seen = /* @__PURE__ */ new Map();
42
52
  for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
@@ -58,6 +68,12 @@ const requireJobId = (provider, id) => {
58
68
  });
59
69
  return id.value;
60
70
  };
71
+ /**
72
+ * Builds a result's `meta`, leaving out whatever is absent: `units` with an
73
+ * undefined count, an empty `usage`, no `warnings`. A single warning string
74
+ * becomes a one-item list. Returns undefined when nothing is left, so a result
75
+ * has no `meta` at all rather than an empty one.
76
+ */
61
77
  const meta = (parts) => {
62
78
  const units = Object.fromEntries(Object.entries(parts.units ?? {}).filter((entry) => entry[1] !== void 0));
63
79
  const usage = compact({
@@ -73,10 +89,22 @@ const meta = (parts) => {
73
89
  });
74
90
  return Object.keys(result).length > 0 ? result : void 0;
75
91
  };
92
+ /**
93
+ * Refuses a request that sets more than one of `names` (a name counts as set
94
+ * unless its value is undefined), for options the provider rejects or ignores
95
+ * when combined. Throws before anything is sent.
96
+ *
97
+ * Throws `InvalidRequest` naming the options that were set.
98
+ */
76
99
  const refuseTogether = (provider, options, ...names) => {
77
100
  const set = names.filter((name) => options[name] !== void 0);
78
101
  if (set.length > 1) throw new FieldworkError("InvalidRequest", `${provider} does not accept ${set.join(" and ")} together; pass one`, { provider });
79
102
  };
103
+ /**
104
+ * A `maxAge` in seconds as the whole hours Exa and Tavily count in, rounded
105
+ * up, so 1 second is 1 hour and 0 stays 0 (always fetch fresh). A negative age
106
+ * (read only the cache) becomes -1. Undefined stays undefined.
107
+ */
80
108
  const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
81
109
  /** Statuses that mean the page is not there, so a read of it has no page to return. */
82
110
  const GONE = /* @__PURE__ */ new Set([404, 410]);
@@ -100,7 +128,13 @@ const presentPages = (pages) => ({
100
128
  })),
101
129
  pages: pages.filter((page) => page.statusCode === void 0 || !GONE.has(page.statusCode))
102
130
  });
131
+ /**
132
+ * Waits `ms`. When `signal` aborts it resolves early rather than rejecting, so
133
+ * the caller checks the signal afterwards. A signal already aborted on entry
134
+ * returns at once.
135
+ */
103
136
  const sleep = async (ms, signal) => {
137
+ if (signal?.aborted === true) return;
104
138
  await new Promise((resolve) => {
105
139
  const timer = setTimeout(resolve, ms);
106
140
  signal?.addEventListener("abort", () => {
@@ -134,6 +168,7 @@ const timedOut = (signal) => signal.reason instanceof DOMException && signal.rea
134
168
  * requests), `Aborted` when the caller cancelled.
135
169
  */
136
170
  const stopped = (signal, message, options) => new FieldworkError(timedOut(signal) ? "Timeout" : "Aborted", message, options);
171
+ /** The error for a fetch that threw: stopped by the signal (`Timeout` or `Aborted`), timed out on its own, or a lost connection, which can succeed on repeat. */
137
172
  const transportError = (provider, error, signal) => {
138
173
  if (signal?.aborted === true) return stopped(signal, `${provider} request stopped: ${timedOut(signal) ? "timed out" : "cancelled"}`, {
139
174
  cause: error,
@@ -157,6 +192,14 @@ const readText = async (provider, response, signal) => {
157
192
  throw transportError(provider, error, signal);
158
193
  }
159
194
  };
195
+ /**
196
+ * Builds the client for one provider. A request is sent to `baseUrl` plus its
197
+ * path, with JSON bodies and the config's headers, and `timeout` and `signal`
198
+ * stop it. A failed request is repeated as `CallOptions.retries` says, waiting
199
+ * as long as the provider's `Retry-After` or backing off exponentially, and
200
+ * never past the call's `timeout`. A request marked `creates` is repeated only
201
+ * after a rate limit.
202
+ */
160
203
  const createRawClient = (config) => {
161
204
  const doFetch = config.fetch ?? globalThis.fetch;
162
205
  return {
@@ -301,6 +344,11 @@ const describe = (parsed, text) => {
301
344
  }
302
345
  return text.slice(0, 300);
303
346
  };
347
+ /**
348
+ * Seconds to wait from a `Retry-After` header, which is a number of seconds or
349
+ * an HTTP date. Undefined when the header is absent, empty or neither. `now`
350
+ * is for tests.
351
+ */
304
352
  const retryAfterSeconds = (header, now = Date.now()) => {
305
353
  if (header === null || header === "") return;
306
354
  const seconds = Number(header);
@@ -310,6 +358,12 @@ const retryAfterSeconds = (header, now = Date.now()) => {
310
358
  };
311
359
  /** An id as one path segment, so a caller's `resume` cannot reach another endpoint. */
312
360
  const segment = (id) => encodeURIComponent(id);
361
+ /**
362
+ * The API key: `given`, else the environment variable. An empty `given` is
363
+ * not replaced by the variable.
364
+ *
365
+ * Throws `Unauthorized` when there is no key or it is empty.
366
+ */
313
367
  const requireKey = (provider, given, envName) => {
314
368
  const key = given ?? process.env[envName];
315
369
  if (key === void 0 || key === "") throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
@@ -337,15 +391,6 @@ const readSigned = async (provider, url, options) => {
337
391
  return text;
338
392
  };
339
393
  // src/parse.ts
340
- /**
341
- * Building blocks for the schemas that parse a provider's response at the
342
- * boundary. Every block is lenient: it never fails, so a provider that adds,
343
- * removes or retypes a field cannot make a working call throw. A field of the
344
- * wrong type reads as absent, and unknown keys pass through. Build each
345
- * adapter's response schema only from these, then `z.parse` the response once.
346
- * The provider's untouched response still goes in `raw`; the parsed value is
347
- * for reading only.
348
- */
349
394
  /** The result of a field that is absent or of the wrong type. */
350
395
  const nothing = () => void 0;
351
396
  /** Reads any value as absent. A union's last member, so a value of the wrong type does not fail. */