@howells/fieldwork-sdk 0.5.0 → 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.
package/dist/parallel.js CHANGED
@@ -1,26 +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 { A as citationsOf, B as uniqueCitations, C as createRawClient, D as segment, E as requireKey, N as meta, O as callSettings, P as parseJson, R as refuseTogether, S as withOriginal, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as compact, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, v as recordOf, w as poll, x as warnings, y as sourceShape, z as requireJobId } from "./parse-D4SMt-Ip.js";
4
- 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";
5
6
  import * as z from "zod/mini";
6
7
  // src/adapters/parallel/parse.ts
8
+ /** The name this adapter reports in errors and results. */
7
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
+ */
8
14
  const nonEmpty = (value) => {
9
15
  const result = compact(value);
10
16
  return Object.keys(result).length > 0 ? result : void 0;
11
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
+ */
12
22
  const usageUnits = (entries) => {
13
23
  const units = /* @__PURE__ */ new Map();
14
24
  for (const { count, name } of entries) if (name !== void 0 && count !== void 0) units.set(name, (units.get(name) ?? 0) + count);
15
25
  return Object.fromEntries(units);
16
26
  };
27
+ /**
28
+ * The evidence Parallel gives for each field, as field sources. A missing `field`
29
+ * becomes an empty string.
30
+ */
17
31
  const basis = (entries) => entries.map((entry) => compact({
18
32
  citations: citationsOf(entry.citations),
19
33
  confidence: entry.confidence,
20
34
  field: entry.field ?? "",
21
35
  reasoning: entry.reasoning
22
36
  }));
37
+ /** The unique citations across the fields' sources. */
23
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. */
24
40
  const taskMeta = (result) => {
25
41
  const { run } = result.value;
26
42
  return meta({
@@ -34,15 +50,26 @@ const responseMessages = (body) => {
34
50
  const final = messages.filter((item) => item.phase === "final_answer");
35
51
  return final.length > 0 ? final : messages;
36
52
  };
53
+ /**
54
+ * A decision's probabilities without the entries Parallel left undefined, or
55
+ * undefined when none remain.
56
+ */
37
57
  const probabilities = (chances) => {
38
58
  const entries = Object.entries(chances).filter((entry) => entry[1] !== void 0);
39
59
  return entries.length > 0 ? Object.fromEntries(entries) : void 0;
40
60
  };
61
+ /** The key with the highest probability; the first one wins a tie. */
41
62
  const mostLikely = (chances) => {
42
63
  let best;
43
64
  for (const [key, chance] of Object.entries(chances ?? {})) if (best === void 0 || chance > (chances?.[best] ?? 0)) best = key;
44
65
  return best;
45
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
+ */
46
73
  const decisionAnswer = (question, answer) => {
47
74
  if (answer.type === "refusal") return { refusal: "Parallel declined to answer this question" };
48
75
  const { confidence } = answer;
@@ -63,6 +90,11 @@ const decisionAnswer = (question, answer) => {
63
90
  };
64
91
  /** Termination reasons that mean the run found everything it could. */
65
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
+ */
66
98
  const candidate = (item) => {
67
99
  const status = item.match_status;
68
100
  if (status === "discarded") return;
@@ -83,6 +115,10 @@ const candidate = (item) => {
83
115
  url: item.url
84
116
  });
85
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
+ */
86
122
  const monitorInfo = (entry) => {
87
123
  const monitor = entry.value;
88
124
  return compact({
@@ -95,6 +131,12 @@ const monitorInfo = (entry) => {
95
131
  webhookUrl: monitor.webhook.url
96
132
  });
97
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
+ */
98
140
  const monitorEvent = (entry) => {
99
141
  const event = entry.value;
100
142
  const type = event.event_type;
@@ -133,6 +175,10 @@ const pageFrom = (entry, extra = {}) => {
133
175
  ...extra
134
176
  });
135
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
+ */
136
182
  const extractFailure = (error) => {
137
183
  const status = error.http_status_code;
138
184
  return [
@@ -141,11 +187,18 @@ const extractFailure = (error) => {
141
187
  error.content
142
188
  ].filter((part) => part !== void 0).join(": ");
143
189
  };
190
+ /** Meta for an Extract response: its id as `requestId`, usage units and warnings. */
144
191
  const extractMeta = (body) => meta({
145
192
  requestId: body.extract_id.id,
146
193
  units: usageUnits(body.usage),
147
194
  warnings: body.warnings
148
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
+ */
149
202
  const discovery = (id, entry) => {
150
203
  const run = entry.value.run.status;
151
204
  const { metrics } = run;
@@ -155,7 +208,6 @@ const discovery = (id, entry) => {
155
208
  const stoppedEarly = state !== "completed" || reason !== void 0 && !FINISHED.has(reason);
156
209
  if (stoppedEarly && !entities.some((entity) => entity.matched === true)) throw new FieldworkError("JobFailed", `parallel FindAll run ${id} ended as ${state}${reason === void 0 ? "" : ` (${reason})`} without a match`, {
157
210
  cause: entry.original,
158
- jobId: id,
159
211
  provider
160
212
  });
161
213
  const stopReason = reason ?? state;
@@ -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";
@@ -442,10 +540,14 @@ const stoppedRun = (id, entry) => {
442
540
  if (warnings.length > 0) message += ` (${warnings.join("; ")})`;
443
541
  return new FieldworkError("JobFailed", message, {
444
542
  cause: entry.original,
445
- jobId: id,
446
543
  provider
447
544
  });
448
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
+ */
449
551
  const taskResult = async (raw, id, request) => {
450
552
  try {
451
553
  return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${segment(id)}/result`, request));
@@ -457,23 +559,31 @@ const taskResult = async (raw, id, request) => {
457
559
  throw error;
458
560
  }
459
561
  };
460
- const runTask = async (raw, body, settings) => {
461
- const { resume, ...wait } = settings;
462
- const id = resume ?? requireJobId(raw.provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
463
- ...wait,
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
+ */
567
+ const runTask = async (raw, body, settings, finish) => await runJob(provider, {
568
+ check: async (id, request) => {
569
+ const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
570
+ const { status } = run.value;
571
+ if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
572
+ return status === "completed" ? await taskResult(raw, id, request) : void 0;
573
+ },
574
+ finish,
575
+ start: async () => requireJobId(provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
464
576
  body,
465
- creates: true
466
- })).run_id);
467
- return {
468
- id,
469
- result: await poll(raw.provider, id, async (request) => {
470
- const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
471
- const { status } = run.value;
472
- if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
473
- return status === "completed" ? await taskResult(raw, id, request) : void 0;
474
- }, wait)
475
- };
476
- };
577
+ creates: true,
578
+ retries: settings.retries,
579
+ signal: settings.signal
580
+ })).run_id)
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
+ */
477
587
  const startFindAll = async (raw, objective, o, call) => {
478
588
  const created = z.parse(FindAllStart, await raw.request("POST", "/v1beta/findall/runs", {
479
589
  creates: true,
@@ -506,13 +616,15 @@ const startFindAll = async (raw, objective, o, call) => {
506
616
  }
507
617
  return id;
508
618
  };
509
- /** 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
+ */
510
623
  const findAllResult = async (raw, id, request) => {
511
624
  const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
512
625
  const { status } = run.value.status;
513
626
  if (status === "action_required") throw new FieldworkError("JobFailed", `parallel FindAll run ${id} stopped with status action_required: it is waiting for an action Fieldwork cannot take, so it will not finish on its own. Open the run in the Parallel console to see what it needs`, {
514
627
  cause: run.original,
515
- jobId: id,
516
628
  provider
517
629
  });
518
630
  return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
@@ -628,31 +740,30 @@ const parallel = (config = {}) => {
628
740
  },
629
741
  async discover(objective, options) {
630
742
  const { call, rest: o } = callSettings(options);
631
- const id = o.resume ?? await startFindAll(raw, objective, o, call);
632
- const result = await poll(provider, id, async (request) => await findAllResult(raw, id, request), {
743
+ return await runJob(provider, {
744
+ check: async (id, request) => await findAllResult(raw, id, request),
745
+ finish: async (result, id) => {
746
+ const found = discovery(id, result);
747
+ const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => data === void 0 ? entity : {
748
+ ...entity,
749
+ data: await checkOutput(o.schema, data, { provider })
750
+ }));
751
+ return {
752
+ ...found,
753
+ entities
754
+ };
755
+ },
756
+ start: async () => await startFindAll(raw, objective, o, call)
757
+ }, {
633
758
  ...call,
634
- interval: o.interval
759
+ interval: o.interval,
760
+ resume: o.resume
635
761
  });
636
- const found = discovery(id, result);
637
- const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => {
638
- if (data === void 0) return entity;
639
- return {
640
- ...entity,
641
- data: await checkOutput(o.schema, data, {
642
- jobId: id,
643
- provider
644
- })
645
- };
646
- }));
647
- return {
648
- ...found,
649
- entities
650
- };
651
762
  },
652
763
  async extract(url, options) {
653
764
  const { call, rest: o } = callSettings(options);
654
765
  const target = new URL(url);
655
- const { id, result } = await runTask(raw, compact({
766
+ return await runTask(raw, compact({
656
767
  advanced_settings: nonEmpty({ location: o.country }),
657
768
  input: {
658
769
  instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
@@ -666,16 +777,14 @@ const parallel = (config = {}) => {
666
777
  ...call,
667
778
  interval: o.interval,
668
779
  resume: o.resume
669
- });
670
- const { output } = result.value;
671
- return compact({
672
- data: await checkOutput(o.schema, output.content, {
673
- jobId: id,
674
- provider
675
- }),
676
- fields: basis(output.basis),
677
- meta: taskMeta(result),
678
- raw: result.original
780
+ }, async (result) => {
781
+ const { output } = result.value;
782
+ return compact({
783
+ data: await checkOutput(o.schema, output.content, { provider }),
784
+ fields: basis(output.basis),
785
+ meta: taskMeta(result),
786
+ raw: result.original
787
+ });
679
788
  });
680
789
  },
681
790
  async images(query, options) {
@@ -835,7 +944,7 @@ const parallel = (config = {}) => {
835
944
  },
836
945
  async research(question, options) {
837
946
  const { call, rest: o } = callSettings(options);
838
- const { id, result } = await runTask(raw, compact({
947
+ return await runTask(raw, compact({
839
948
  advanced_settings: nonEmpty({ location: o.country }),
840
949
  input: question,
841
950
  metadata: o.metadata,
@@ -847,21 +956,19 @@ const parallel = (config = {}) => {
847
956
  ...call,
848
957
  interval: o.interval,
849
958
  resume: o.resume
850
- });
851
- const { output, run } = result.value;
852
- const fields = basis(output.basis);
853
- return compact({
854
- continuationId: run.interaction_id,
855
- fields,
856
- id,
857
- meta: taskMeta(result),
858
- output: await checkOutput(o.schema, output.content, {
859
- jobId: id,
860
- provider
861
- }),
862
- raw: result.original,
863
- sources: citedBy(fields),
864
- status: "completed"
959
+ }, async (result, id) => {
960
+ const { output, run } = result.value;
961
+ const fields = basis(output.basis);
962
+ return compact({
963
+ continuationId: run.interaction_id,
964
+ fields,
965
+ id,
966
+ meta: taskMeta(result),
967
+ output: await checkOutput(o.schema, output.content, { provider }),
968
+ raw: result.original,
969
+ sources: citedBy(fields),
970
+ status: "completed"
971
+ });
865
972
  });
866
973
  },
867
974
  async search(query, options) {
@@ -1,8 +1,10 @@
1
- import { i as withJob, 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);
@@ -308,40 +356,14 @@ const retryAfterSeconds = (header, now = Date.now()) => {
308
356
  const date = Date.parse(header);
309
357
  return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
310
358
  };
311
- /**
312
- * Checks a job until `check` returns its result. Each check is given the
313
- * settings for its request: the call's signal, which carries the call's whole
314
- * deadline, and its retries. A check that throws, a cancellation and a
315
- * timeout all surface with `jobId`, so the caller can resume the job.
316
- */
317
- const poll = async (provider, jobId, check, options = {}) => {
318
- const interval = options.interval ?? 2e3;
319
- const deadline = Date.now() + (options.timeout ?? 6e5);
320
- const request = {
321
- retries: options.retries,
322
- signal: options.signal
323
- };
324
- for (;;) {
325
- if (options.signal?.aborted === true) throw stopped(options.signal, `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
326
- jobId,
327
- provider
328
- });
329
- let value;
330
- try {
331
- value = await check(request);
332
- } catch (error) {
333
- throw withJob(error, jobId);
334
- }
335
- if (value !== void 0) return value;
336
- if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
337
- jobId,
338
- provider
339
- });
340
- await sleep(interval, options.signal);
341
- }
342
- };
343
359
  /** An id as one path segment, so a caller's `resume` cannot reach another endpoint. */
344
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
+ */
345
367
  const requireKey = (provider, given, envName) => {
346
368
  const key = given ?? process.env[envName];
347
369
  if (key === void 0 || key === "") throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
@@ -369,15 +391,6 @@ const readSigned = async (provider, url, options) => {
369
391
  return text;
370
392
  };
371
393
  // src/parse.ts
372
- /**
373
- * Building blocks for the schemas that parse a provider's response at the
374
- * boundary. Every block is lenient: it never fails, so a provider that adds,
375
- * removes or retypes a field cannot make a working call throw. A field of the
376
- * wrong type reads as absent, and unknown keys pass through. Build each
377
- * adapter's response schema only from these, then `z.parse` the response once.
378
- * The provider's untouched response still goes in `raw`; the parsed value is
379
- * for reading only.
380
- */
381
394
  /** The result of a field that is absent or of the wrong type. */
382
395
  const nothing = () => void 0;
383
396
  /** Reads any value as absent. A union's last member, so a value of the wrong type does not fail. */
@@ -507,4 +520,4 @@ const optionalArrayOf = (item) => z.optional(z.union([z.pipe(z.array(z.unknown()
507
520
  const parsed = z.safeParse(item, entry);
508
521
  return parsed.success ? [parsed.data] : [];
509
522
  }))), absent]));
510
- export { citationsOf as A, uniqueCitations as B, createRawClient as C, segment as D, requireKey as E, presentPage as F, presentPages as I, record as L, hours as M, meta as N, callSettings as O, parseJson as P, refuseTogether as R, withOriginal as S, readSigned as T, optionalStructure as _, looseObject as a, warningEntry as b, optionalArrayOf as c, optionalId as d, optionalNumber as f, optionalStringOrNumber as g, optionalString as h, both as i, compact as j, citationOf as k, optionalBoolean as l, optionalScalar as m, anything as n, nonEmptyString as o, optionalObject as p, arrayOf as r, optionalAnyString as s, Source as t, optionalFirstString as u, recordOf as v, poll as w, warnings as x, sourceShape as y, requireJobId as z };
523
+ export { citationOf as A, requireJobId as B, createRawClient as C, sleep as D, segment as E, parseJson as F, presentPage as I, presentPages as L, compact as M, hours as N, stopped as O, meta as P, record as R, withOriginal as S, requireKey as T, uniqueCitations as V, optionalStructure as _, looseObject as a, warningEntry as b, optionalArrayOf as c, optionalId as d, optionalNumber as f, optionalStringOrNumber as g, optionalString as h, both as i, citationsOf as j, callSettings as k, optionalBoolean as l, optionalScalar as m, anything as n, nonEmptyString as o, optionalObject as p, arrayOf as r, optionalAnyString as s, Source as t, optionalFirstString as u, recordOf as v, readSigned as w, warnings as x, sourceShape as y, refuseTogether as z };