@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/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-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
  // 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,27 +50,41 @@ 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, or undefined when
69
+ * Parallel left out the part the question needs: a `yesno` answer's `noul`, a
70
+ * `choice` answer's `choice`, a `score` answer's probabilities. A `refusal`
71
+ * answer becomes `{ refusal }`. A `yesno` answer keeps only `probability`. A
72
+ * `score` answer's probabilities are keyed by the scale's own keys and its
73
+ * `choice` is the most likely of them; Parallel's numeric `score` stays in `raw`.
74
+ */
47
75
  const decisionAnswer = (question, answer) => {
48
76
  if (answer.type === "refusal") return { refusal: "Parallel declined to answer this question" };
49
77
  const { confidence } = answer;
50
- if (question.type === "yesno") return compact({ probability: answer.noul });
51
- if (question.type === "choice") return compact({
78
+ if (question.type === "yesno") return answer.noul === void 0 ? void 0 : { probability: answer.noul };
79
+ if (question.type === "choice") return answer.choice === void 0 ? void 0 : compact({
52
80
  choice: answer.choice,
53
81
  confidence,
54
82
  probabilities: probabilities(answer.probabilities)
55
83
  });
56
84
  const keys = Object.keys(question.scale);
57
85
  const byLevel = probabilities(answer.probabilities);
58
- const byKey = byLevel && Object.fromEntries(Object.entries(byLevel).map(([level, chance]) => [keys[Number(level)] ?? level, chance]));
86
+ if (byLevel === void 0) return;
87
+ const byKey = Object.fromEntries(Object.entries(byLevel).map(([level, chance]) => [keys[Number(level)] ?? level, chance]));
59
88
  return compact({
60
89
  choice: mostLikely(byKey),
61
90
  confidence,
@@ -64,6 +93,11 @@ const decisionAnswer = (question, answer) => {
64
93
  };
65
94
  /** Termination reasons that mean the run found everything it could. */
66
95
  const FINISHED = /* @__PURE__ */ new Set(["match_limit_met", "candidates_exhausted"]);
96
+ /**
97
+ * A FindAll candidate as an entity, or undefined when Parallel discarded it.
98
+ * `matched` is true or false for the `matched` and `unmatched` statuses and unset
99
+ * for any other. Only `enrichment` outputs reach `data`; the rest stay in `raw`.
100
+ */
67
101
  const candidate = (item) => {
68
102
  const status = item.match_status;
69
103
  if (status === "discarded") return;
@@ -84,6 +118,10 @@ const candidate = (item) => {
84
118
  url: item.url
85
119
  });
86
120
  };
121
+ /**
122
+ * A monitor from Parallel's entry. `watch` is the monitor's `settings.query` and
123
+ * `schedule` is Parallel's frequency string. A missing id throws.
124
+ */
87
125
  const monitorInfo = (entry) => {
88
126
  const monitor = entry.value;
89
127
  return compact({
@@ -96,6 +134,12 @@ const monitorInfo = (entry) => {
96
134
  webhookUrl: monitor.webhook.url
97
135
  });
98
136
  };
137
+ /**
138
+ * A monitor event by `event_type`. A `completion` is a run that found no change,
139
+ * with a fixed summary. An `error` takes its message as the summary. A `snapshot`
140
+ * reads `changed_output`; any other type reads `output`. Completions and errors
141
+ * are dated by `timestamp`, changes by `event_date`.
142
+ */
99
143
  const monitorEvent = (entry) => {
100
144
  const event = entry.value;
101
145
  const type = event.event_type;
@@ -134,6 +178,10 @@ const pageFrom = (entry, extra = {}) => {
134
178
  ...extra
135
179
  });
136
180
  };
181
+ /**
182
+ * Why one URL failed, as `type: HTTP status: content`. A missing type reads as
183
+ * "error"; missing parts are left out.
184
+ */
137
185
  const extractFailure = (error) => {
138
186
  const status = error.http_status_code;
139
187
  return [
@@ -142,11 +190,18 @@ const extractFailure = (error) => {
142
190
  error.content
143
191
  ].filter((part) => part !== void 0).join(": ");
144
192
  };
193
+ /** Meta for an Extract response: its id as `requestId`, usage units and warnings. */
145
194
  const extractMeta = (body) => meta({
146
195
  requestId: body.extract_id.id,
147
196
  units: usageUnits(body.usage),
148
197
  warnings: body.warnings
149
198
  });
199
+ /**
200
+ * A finished FindAll run as a discovery. The run counts as stopped early when its
201
+ * status is not `completed` or its termination reason is not in `FINISHED`. Stopped
202
+ * early with at least one matched entity, it is `partial` with a `stopReason` and
203
+ * a warning; with none, it throws `JobFailed`. Discarded candidates are left out.
204
+ */
150
205
  const discovery = (id, entry) => {
151
206
  const run = entry.value.run.status;
152
207
  const { metrics } = run;
@@ -175,7 +230,13 @@ const discovery = (id, entry) => {
175
230
  stopReason: stoppedEarly ? stopReason : void 0
176
231
  });
177
232
  };
233
+ /** The characters Parallel allows in a decision question's name. */
178
234
  const QUESTION_NAME = /^[A-Za-z0-9_-]+$/u;
235
+ /**
236
+ * Parallel's `source_policy`, or undefined when no filter is set. Refuses both
237
+ * domain lists together, since Parallel ignores the exclude list when an include
238
+ * list is present.
239
+ */
179
240
  const sourcePolicy = (o) => {
180
241
  refuseTogether(provider, o, "includeDomains", "excludeDomains");
181
242
  return nonEmpty({
@@ -184,14 +245,27 @@ const sourcePolicy = (o) => {
184
245
  include_domains: o.includeDomains
185
246
  });
186
247
  };
248
+ /**
249
+ * Parallel's `fetch_policy` for a `maxAge`, rounded up to whole seconds. Refuses a
250
+ * value under the minimum: Parallel has no setting that always fetches fresh.
251
+ */
187
252
  const fetchPolicy = (maxAge) => {
188
253
  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
254
  return maxAge === void 0 ? void 0 : { max_age_seconds: Math.ceil(maxAge) };
190
255
  };
256
+ /**
257
+ * Parallel's JSON output spec (`type: "json"`) for a schema, as Tasks and monitors
258
+ * take it.
259
+ */
191
260
  const jsonOutput = (schema) => ({
192
261
  json_schema: jsonSchemaOf(schema),
193
262
  type: "json"
194
263
  });
264
+ /**
265
+ * Parallel's form of a normalized decision question: `yesno` is `noul`, `choice`
266
+ * keeps its type and `score` takes the scale's labels, in order, as criteria.
267
+ * Refuses a choice or score count outside Parallel's limits.
268
+ */
195
269
  const decisionQuestion = (name, question) => {
196
270
  if (question.type === "yesno") return {
197
271
  instructions: question.question,
@@ -217,11 +291,16 @@ const decisionQuestion = (name, question) => {
217
291
  }
218
292
  throw invalidRequest(provider, `does not know the question type "${String(question.type)}" for "${name}"`);
219
293
  };
294
+ /** Parallel's short form of each named schedule. */
220
295
  const NAMED_FREQUENCY = {
221
296
  day: "1d",
222
297
  hour: "1h",
223
298
  week: "1w"
224
299
  };
300
+ /**
301
+ * Parallel's `frequency` string for a schedule: a named interval, or `<n>h` up to
302
+ * 720 or `<n>d` up to 30. Refuses cron and anything outside 1 hour to 30 days.
303
+ */
225
304
  const frequency = (schedule) => {
226
305
  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
306
  const named = Object.entries(NAMED_FREQUENCY).find(([name]) => name === schedule.every)?.[1];
@@ -232,6 +311,10 @@ const frequency = (schedule) => {
232
311
  if (!match || count < 1 || count > limit) throw invalidRequest(provider, `monitors run every 1 hour to 30 days; "${schedule.every}" is outside that`);
233
312
  return schedule.every;
234
313
  };
314
+ /**
315
+ * The `/v1/extract` body that `read` and `readMany` share. It always asks for
316
+ * `full_content`, capped only when `maxContentChars` is a non-zero number.
317
+ */
235
318
  const extractBody = (urls, o) => compact({
236
319
  advanced_settings: compact({
237
320
  excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
@@ -287,6 +370,7 @@ const ImagesResponse = looseObject({
287
370
  usage: Usage,
288
371
  warnings
289
372
  });
373
+ /** One URL's result in an Extract response. */
290
374
  const ExtractResult = looseObject({
291
375
  excerpts: arrayOf(z.string()),
292
376
  full_content: optionalString,
@@ -294,7 +378,10 @@ const ExtractResult = looseObject({
294
378
  title: optionalString,
295
379
  url: optionalString
296
380
  });
297
- /** `/v1/extract`. Each result keeps its own entry as it arrived. */
381
+ /**
382
+ * `/v1/extract`. Each result keeps its own entry as it arrived. `extract_id` is
383
+ * read as text (the batch id) and as a request id (a string, number or boolean).
384
+ */
298
385
  const ExtractResponse = looseObject({
299
386
  errors: arrayOf(looseObject({
300
387
  content: optionalString,
@@ -337,6 +424,10 @@ const AnswerResponse = looseObject({
337
424
  total_tokens: optionalNumber
338
425
  })
339
426
  });
427
+ /**
428
+ * One decision answer. `noul` is a yes/no probability; `probabilities` is keyed by
429
+ * choice, or by zero-based score level.
430
+ */
340
431
  const Decision = looseObject({
341
432
  choice: optionalString,
342
433
  confidence: optionalNumber,
@@ -375,6 +466,7 @@ const TaskResult = withOriginal(looseObject({
375
466
  const FindAllStart = looseObject({ findall_id: withOriginal(optionalId) });
376
467
  /** A FindAll run while it is polled. */
377
468
  const FindAllRun = withOriginal(looseObject({ status: looseObject({ status: optionalString }) }));
469
+ /** A FindAll candidate. `output` holds its enrichment values among other outputs. */
378
470
  const Candidate = looseObject({
379
471
  basis: arrayOf(Basis),
380
472
  description: optionalString,
@@ -412,6 +504,10 @@ const MonitorsPage = looseObject({
412
504
  monitors: arrayOf(MonitorEntry),
413
505
  next_cursor: optionalString
414
506
  });
507
+ /**
508
+ * The output of a monitor event: the evidence and the content, read as text and as
509
+ * a structure.
510
+ */
415
511
  const EventOutput = looseObject({
416
512
  basis: arrayOf(Basis),
417
513
  content: Content
@@ -430,6 +526,34 @@ const EventsPage = looseObject({
430
526
  next_cursor: optionalString
431
527
  });
432
528
  // src/adapters/parallel/jobs.ts
529
+ const RUNNING = [
530
+ "queued",
531
+ "running",
532
+ "cancelling"
533
+ ];
534
+ const TASK_STATES = {
535
+ done: ["completed"],
536
+ failed: [
537
+ "failed",
538
+ "cancelled",
539
+ "action_required"
540
+ ],
541
+ running: RUNNING
542
+ };
543
+ const FINDALL_STATES = {
544
+ done: [
545
+ "completed",
546
+ "failed",
547
+ "cancelled"
548
+ ],
549
+ failed: ["action_required"],
550
+ running: RUNNING
551
+ };
552
+ /**
553
+ * The `JobFailed` error for a Task run that ended without a result: cancelled,
554
+ * failed with Parallel's message, or `action_required`, which waits on something
555
+ * Fieldwork cannot do and so never finishes. The run's warnings are appended.
556
+ */
433
557
  const stoppedRun = (id, entry) => {
434
558
  const run = entry.value;
435
559
  const status = run.status ?? "unknown";
@@ -445,6 +569,11 @@ const stoppedRun = (id, entry) => {
445
569
  provider
446
570
  });
447
571
  };
572
+ /**
573
+ * A completed run's result. When the result endpoint answers `NotFound` for a run
574
+ * that failed or was cancelled, this raises that run's `JobFailed` instead; any
575
+ * other error passes through.
576
+ */
448
577
  const taskResult = async (raw, id, request) => {
449
578
  try {
450
579
  return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${segment(id)}/result`, request));
@@ -456,25 +585,42 @@ const taskResult = async (raw, id, request) => {
456
585
  throw error;
457
586
  }
458
587
  };
459
- /** Runs a task to its result, or waits for the run named by `resume`. */
588
+ /**
589
+ * Runs a task to its result, or waits for the run named by `resume`. A failed,
590
+ * cancelled or `action_required` run throws at once; queued, running and
591
+ * cancelling runs are polled again; any other status throws `ProviderError`.
592
+ * A completed run whose result has no `output.content` throws `JobFailed`.
593
+ */
460
594
  const runTask = async (raw, body, settings, finish) => await runJob(provider, {
461
595
  check: async (id, request) => {
462
596
  const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
463
- const { status } = run.value;
464
- if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
465
- return status === "completed" ? await taskResult(raw, id, request) : void 0;
597
+ const state = jobState(provider, id, TASK_STATES, {
598
+ original: run.original,
599
+ value: run.value.status
600
+ });
601
+ if (state === "failed") throw stoppedRun(id, run);
602
+ return state === "done" ? await taskResult(raw, id, request) : void 0;
466
603
  },
467
- finish,
468
- start: async () => requireJobId(provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
604
+ finish: async (result, id) => {
605
+ requireOutput(provider, id, {
606
+ original: result.original,
607
+ value: result.value.output.content
608
+ });
609
+ return await finish(result, id);
610
+ },
611
+ start: async () => await startJob(raw, "/v1/tasks/runs", {
469
612
  body,
470
- creates: true,
471
613
  retries: settings.retries,
472
614
  signal: settings.signal
473
- })).run_id)
615
+ }, TaskStart, (reply) => reply.run_id)
474
616
  }, settings);
617
+ /**
618
+ * Starts a FindAll run and returns its id. With a `schema` it then adds the
619
+ * enrichment; if that request fails, the error carries the run's id, since the run
620
+ * already exists.
621
+ */
475
622
  const startFindAll = async (raw, objective, o, call) => {
476
- const created = z.parse(FindAllStart, await raw.request("POST", "/v1beta/findall/runs", {
477
- creates: true,
623
+ const id = await startJob(raw, "/v1beta/findall/runs", {
478
624
  ...call,
479
625
  body: compact({
480
626
  entity_type: o.entityType,
@@ -488,8 +634,7 @@ const startFindAll = async (raw, objective, o, call) => {
488
634
  metadata: o.metadata,
489
635
  objective
490
636
  })
491
- }));
492
- const id = requireJobId(provider, created.findall_id);
637
+ }, FindAllStart, (reply) => reply.findall_id);
493
638
  if (o.schema) try {
494
639
  await raw.request("POST", `/v1beta/findall/runs/${segment(id)}/enrich`, {
495
640
  ...call,
@@ -504,15 +649,22 @@ const startFindAll = async (raw, objective, o, call) => {
504
649
  }
505
650
  return id;
506
651
  };
507
- /** The result of a FindAll run once it has stopped, or undefined while it runs. */
652
+ /**
653
+ * The result of a FindAll run once it has stopped (completed, failed or
654
+ * cancelled), or undefined while it runs. `action_required` throws `JobFailed`,
655
+ * and a status Parallel does not document throws `ProviderError`.
656
+ */
508
657
  const findAllResult = async (raw, id, request) => {
509
658
  const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
510
- const { status } = run.value.status;
511
- 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`, {
659
+ const state = jobState(provider, id, FINDALL_STATES, {
660
+ original: run.original,
661
+ value: run.value.status.status
662
+ });
663
+ if (state === "failed") 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`, {
512
664
  cause: run.original,
513
665
  provider
514
666
  });
515
- return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
667
+ return state === "done" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
516
668
  };
517
669
  // src/adapters/parallel.ts
518
670
  /**
@@ -609,10 +761,17 @@ const parallel = (config = {}) => {
609
761
  });
610
762
  const body = z.parse(DecisionsResponse, response);
611
763
  const result = {};
764
+ const unanswered = [];
612
765
  for (const [name, question] of entries) {
613
- const answer = body.answers[name];
614
- if (answer !== void 0) result[name] = decisionAnswer(question, answer);
766
+ const found = Object.hasOwn(body.answers, name) ? body.answers[name] : void 0;
767
+ const answer = found && decisionAnswer(question, found);
768
+ if (answer === void 0) unanswered.push(name);
769
+ else result[name] = answer;
615
770
  }
771
+ if (unanswered.length > 0) throw new FieldworkError("ProviderError", `parallel returned no complete answer for ${unanswered.join(", ")}`, {
772
+ cause: response,
773
+ provider
774
+ });
616
775
  return compact({
617
776
  answers: result,
618
777
  citations: citationsOf(body.citations),
@@ -647,6 +806,7 @@ const parallel = (config = {}) => {
647
806
  },
648
807
  async extract(url, options) {
649
808
  const { call, rest: o } = callSettings(options);
809
+ if (!URL.canParse(url)) throw invalidRequest(provider, `cannot extract ${url}: it is not a URL`);
650
810
  const target = new URL(url);
651
811
  return await runTask(raw, compact({
652
812
  advanced_settings: nonEmpty({ location: o.country }),