@howells/fieldwork-sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/parallel.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
2
  import { r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { _ as uniqueCitations, b as requireKey, c as num, d as record, f as refuseTogether, g as text, h as strings, i as compact, l as parseJson, o as list, p as requireId, r as citations, s as meta, t as callSettings, v as createRawClient, y as poll } from "./util-CYenIQQT.js";
3
+ import { C as createRawClient, E as callSettings, I as refuseTogether, L as requireJobId, M as parseJson, O as citationsOf, R as uniqueCitations, S as withOriginal, T as requireKey, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as meta, k 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 } from "./parse-CxOri73y.js";
4
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-teOy7Od-.js";
5
+ import * as z from "zod/mini";
4
6
  // src/adapters/parallel/parse.ts
5
7
  const provider = "parallel";
6
8
  const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
@@ -8,40 +10,33 @@ const nonEmpty = (value) => {
8
10
  const result = compact(value);
9
11
  return Object.keys(result).length > 0 ? result : void 0;
10
12
  };
11
- const usageUnits = (value) => {
13
+ const usageUnits = (entries) => {
12
14
  const units = /* @__PURE__ */ new Map();
13
- for (const item of list(value)) {
14
- const entry = record(item);
15
- const name = text(entry.name);
16
- const count = num(entry.count);
17
- if (name && count !== void 0) units.set(name, (units.get(name) ?? 0) + count);
18
- }
15
+ for (const { count, name } of entries) if (name !== void 0 && count !== void 0) units.set(name, (units.get(name) ?? 0) + count);
19
16
  return Object.fromEntries(units);
20
17
  };
21
- const basis = (entries) => list(entries).map((item) => {
22
- const entry = record(item);
23
- return compact({
24
- citations: citations(entry.citations),
25
- confidence: text(entry.confidence),
26
- field: text(entry.field) ?? "",
27
- reasoning: text(entry.reasoning)
28
- });
29
- });
18
+ const basis = (entries) => entries.map((entry) => compact({
19
+ citations: citationsOf(entry.citations),
20
+ confidence: entry.confidence,
21
+ field: entry.field ?? "",
22
+ reasoning: entry.reasoning
23
+ }));
30
24
  const citedBy = (fields) => uniqueCitations(fields.flatMap((field) => field.citations));
31
25
  const taskMeta = (result) => {
32
- const run = record(result.run);
26
+ const { run } = result.value;
33
27
  return meta({
34
28
  requestId: run.run_id,
35
29
  warnings: run.warnings
36
30
  });
37
31
  };
38
- const responseMessages = (response) => {
39
- const messages = list(response.output).map((item) => record(item)).filter((item) => item.type === "message");
32
+ /** The messages of a response; only the final answer's when it marks one. */
33
+ const responseMessages = (body) => {
34
+ const messages = body.output.filter((item) => item.type === "message");
40
35
  const final = messages.filter((item) => item.phase === "final_answer");
41
36
  return final.length > 0 ? final : messages;
42
37
  };
43
- const probabilities = (value) => {
44
- const entries = Object.entries(record(value)).filter((entry) => num(entry[1]) !== void 0);
38
+ const probabilities = (chances) => {
39
+ const entries = Object.entries(chances).filter((entry) => entry[1] !== void 0);
45
40
  return entries.length > 0 ? Object.fromEntries(entries) : void 0;
46
41
  };
47
42
  const mostLikely = (chances) => {
@@ -49,13 +44,12 @@ const mostLikely = (chances) => {
49
44
  for (const [key, chance] of Object.entries(chances ?? {})) if (best === void 0 || chance > (chances?.[best] ?? 0)) best = key;
50
45
  return best;
51
46
  };
52
- const decisionAnswer = (question, value) => {
53
- const answer = record(value);
47
+ const decisionAnswer = (question, answer) => {
54
48
  if (answer.type === "refusal") return { refusal: "Parallel declined to answer this question" };
55
- const confidence = num(answer.confidence);
56
- if (question.type === "yesno") return compact({ probability: num(answer.noul) });
49
+ const { confidence } = answer;
50
+ if (question.type === "yesno") return compact({ probability: answer.noul });
57
51
  if (question.type === "choice") return compact({
58
- choice: text(answer.choice),
52
+ choice: answer.choice,
59
53
  confidence,
60
54
  probabilities: probabilities(answer.probabilities)
61
55
  });
@@ -70,15 +64,11 @@ const decisionAnswer = (question, value) => {
70
64
  };
71
65
  /** Termination reasons that mean the run found everything it could. */
72
66
  const FINISHED = /* @__PURE__ */ new Set(["match_limit_met", "candidates_exhausted"]);
73
- const candidate = (value) => {
74
- const item = record(value);
75
- const status = text(item.match_status);
67
+ const candidate = (item) => {
68
+ const status = item.match_status;
76
69
  if (status === "discarded") return;
77
70
  const data = {};
78
- for (const [key, output] of Object.entries(record(item.output))) {
79
- const entry = record(output);
80
- if (entry.type === "enrichment") data[key] = entry.value;
81
- }
71
+ for (const [key, output] of Object.entries(item.output)) if (output.type === "enrichment") data[key] = output.value;
82
72
  const fields = basis(item.basis);
83
73
  const sources = citedBy(fields);
84
74
  let matched;
@@ -87,82 +77,85 @@ const candidate = (value) => {
87
77
  return compact({
88
78
  citations: sources.length > 0 ? sources : void 0,
89
79
  data: nonEmpty(data),
90
- description: text(item.description),
80
+ description: item.description,
91
81
  fields: fields.length > 0 ? fields : void 0,
92
82
  matched,
93
- name: text(item.name) ?? "",
94
- url: text(item.url)
83
+ name: item.name ?? "",
84
+ url: item.url
95
85
  });
96
86
  };
97
- const monitorInfo = (value) => {
98
- const monitor = record(value);
87
+ const monitorInfo = (entry) => {
88
+ const monitor = entry.value;
99
89
  return compact({
100
- createdAt: text(monitor.created_at),
101
- id: requireId(provider, monitor.monitor_id),
102
- raw: monitor,
103
- schedule: text(monitor.frequency),
104
- status: text(monitor.status),
105
- watch: text(record(monitor.settings).query),
106
- webhookUrl: text(record(monitor.webhook).url)
90
+ createdAt: monitor.created_at,
91
+ id: requireJobId(provider, monitor.monitor_id),
92
+ raw: entry.original,
93
+ schedule: monitor.frequency,
94
+ status: monitor.status,
95
+ watch: monitor.settings.query,
96
+ webhookUrl: monitor.webhook.url
107
97
  });
108
98
  };
109
- const monitorEvent = (value) => {
110
- const event = record(value);
111
- const type = text(event.event_type);
99
+ const monitorEvent = (entry) => {
100
+ const event = entry.value;
101
+ const type = event.event_type;
112
102
  if (type === "completion") return {
113
- at: text(event.timestamp),
114
- raw: event,
103
+ at: event.timestamp,
104
+ raw: entry.original,
115
105
  summary: "Run finished with no material change."
116
106
  };
117
107
  if (type === "error") return compact({
118
- at: text(event.timestamp),
119
- raw: event,
120
- summary: text(event.error_message)
108
+ at: event.timestamp,
109
+ raw: entry.original,
110
+ summary: event.error_message
121
111
  });
122
- const output = record(type === "snapshot" ? event.changed_output : event.output);
123
- const { content } = output;
112
+ const output = type === "snapshot" ? event.changed_output : event.output;
113
+ const { structure, text } = output.content;
124
114
  const sources = citedBy(basis(output.basis));
125
115
  return compact({
126
- at: text(event.event_date),
116
+ at: event.event_date,
127
117
  citations: sources.length > 0 ? sources : void 0,
128
- id: text(event.event_id),
129
- output: content && typeof content === "object" ? content : void 0,
130
- raw: event,
131
- summary: typeof content === "string" ? content : void 0
118
+ id: event.event_id,
119
+ output: structure,
120
+ raw: entry.original,
121
+ summary: text
122
+ });
123
+ };
124
+ /** A page from an extracted result; `raw` is the entry as it arrived unless `extra` sets it. */
125
+ const pageFrom = (entry, extra = {}) => {
126
+ const result = entry.value;
127
+ return compact({
128
+ excerpts: result.excerpts.length > 0 ? result.excerpts : void 0,
129
+ markdown: result.full_content,
130
+ publishedAt: result.publish_date,
131
+ raw: entry.original,
132
+ title: result.title,
133
+ url: result.url ?? "",
134
+ ...extra
132
135
  });
133
136
  };
134
- const pageFrom = (result, extra = {}) => compact({
135
- excerpts: strings(result.excerpts),
136
- markdown: text(result.full_content),
137
- publishedAt: text(result.publish_date),
138
- raw: result,
139
- title: text(result.title),
140
- url: text(result.url) ?? "",
141
- ...extra
142
- });
143
137
  const extractFailure = (error) => {
144
- const status = num(error.http_status_code);
145
- const detail = text(error.content);
138
+ const status = error.http_status_code;
146
139
  return [
147
- text(error.error_type) ?? "error",
140
+ error.error_type ?? "error",
148
141
  status === void 0 ? void 0 : `HTTP ${status}`,
149
- detail
142
+ error.content
150
143
  ].filter((part) => part !== void 0).join(": ");
151
144
  };
152
- const extractMeta = (response) => meta({
153
- requestId: response.extract_id,
154
- units: usageUnits(response.usage),
155
- warnings: response.warnings
145
+ const extractMeta = (body) => meta({
146
+ requestId: body.extract_id.id,
147
+ units: usageUnits(body.usage),
148
+ warnings: body.warnings
156
149
  });
157
- const discovery = (id, result) => {
158
- const run = record(record(result.run).status);
159
- const metrics = record(run.metrics);
160
- const reason = text(run.termination_reason);
161
- const state = text(run.status) ?? "unknown";
162
- const entities = list(result.candidates).map((item) => candidate(item)).filter((item) => item !== void 0);
150
+ const discovery = (id, entry) => {
151
+ const run = entry.value.run.status;
152
+ const { metrics } = run;
153
+ const reason = run.termination_reason;
154
+ const state = run.status ?? "unknown";
155
+ const entities = entry.value.candidates.map((item) => candidate(item)).filter((item) => item !== void 0);
163
156
  const stoppedEarly = state !== "completed" || reason !== void 0 && !FINISHED.has(reason);
164
- if (stoppedEarly && !entities.some((entity) => entity.matched)) throw new FieldworkError("JobFailed", `parallel FindAll run ${id} ended as ${state}${reason ? ` (${reason})` : ""} without a match`, {
165
- cause: result,
157
+ 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`, {
158
+ cause: entry.original,
166
159
  jobId: id,
167
160
  provider
168
161
  });
@@ -178,7 +171,7 @@ const discovery = (id, result) => {
178
171
  },
179
172
  warnings: stoppedEarly ? [`the run stopped before it finished: ${stopReason}`] : void 0
180
173
  }),
181
- raw: result,
174
+ raw: entry.original,
182
175
  status: stoppedEarly ? "partial" : "completed",
183
176
  stopReason: stoppedEarly ? stopReason : void 0
184
177
  });
@@ -197,7 +190,7 @@ const fetchPolicy = (maxAge) => {
197
190
  return maxAge === void 0 ? void 0 : { max_age_seconds: Math.ceil(maxAge) };
198
191
  };
199
192
  const jsonOutput = (schema) => ({
200
- json_schema: schema,
193
+ json_schema: jsonSchemaOf(schema),
201
194
  type: "json"
202
195
  });
203
196
  const decisionQuestion = (name, question) => {
@@ -232,7 +225,7 @@ const NAMED_FREQUENCY = {
232
225
  };
233
226
  const frequency = (schedule) => {
234
227
  if ("cron" in schedule) throw invalid("parallel monitors run at a fixed interval from 1 hour to 30 days and cannot follow a cron expression; pass { every: ... }");
235
- const named = NAMED_FREQUENCY[schedule.every];
228
+ const named = Object.entries(NAMED_FREQUENCY).find(([name]) => name === schedule.every)?.[1];
236
229
  if (named) return named;
237
230
  const match = /^(?<count>\d+)(?<unit>[hd])$/u.exec(schedule.every);
238
231
  const count = Number(match?.groups?.count);
@@ -244,7 +237,7 @@ const extractBody = (urls, o) => compact({
244
237
  advanced_settings: compact({
245
238
  excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
246
239
  fetch_policy: fetchPolicy(o.maxAge),
247
- full_content: o.maxContentChars ? { max_chars_per_result: o.maxContentChars } : true
240
+ full_content: o.maxContentChars !== void 0 && o.maxContentChars !== 0 ? { max_chars_per_result: o.maxContentChars } : true
248
241
  }),
249
242
  max_chars_total: o.maxCharsTotal,
250
243
  objective: o.query,
@@ -252,52 +245,240 @@ const extractBody = (urls, o) => compact({
252
245
  session_id: o.sessionId,
253
246
  urls
254
247
  });
248
+ // src/adapters/parallel/response.ts
249
+ /** What a result says about the evidence for a field. */
250
+ const Basis = looseObject({
251
+ citations: arrayOf(Source),
252
+ confidence: optionalString,
253
+ field: optionalString,
254
+ reasoning: optionalString
255
+ });
256
+ /** The units a call used, one entry per kind. */
257
+ const Usage = arrayOf(looseObject({
258
+ count: optionalNumber,
259
+ name: optionalString
260
+ }));
261
+ /** A string, an object or an array as it arrived, told apart. */
262
+ const Content = z.pipe(both(optionalAnyString, optionalStructure), z.transform(({ first, second }) => ({
263
+ structure: second,
264
+ text: first
265
+ })));
266
+ /** `/v1/search`. */
267
+ const SearchResponse = looseObject({
268
+ results: arrayOf(looseObject({
269
+ excerpts: arrayOf(z.string()),
270
+ publish_date: optionalString,
271
+ title: optionalString,
272
+ url: optionalString
273
+ })),
274
+ search_id: optionalScalar,
275
+ usage: Usage,
276
+ warnings
277
+ });
278
+ /** `/v1/images/search`. */
279
+ const ImagesResponse = looseObject({
280
+ results: arrayOf(looseObject({
281
+ height: optionalNumber,
282
+ image_url: optionalString,
283
+ source_page_url: optionalString,
284
+ title: optionalString,
285
+ width: optionalNumber
286
+ })),
287
+ search_id: optionalScalar,
288
+ usage: Usage,
289
+ warnings
290
+ });
291
+ const ExtractResult = looseObject({
292
+ excerpts: arrayOf(z.string()),
293
+ full_content: optionalString,
294
+ publish_date: optionalString,
295
+ title: optionalString,
296
+ url: optionalString
297
+ });
298
+ /** `/v1/extract`. Each result keeps its own entry as it arrived. */
299
+ const ExtractResponse = looseObject({
300
+ errors: arrayOf(looseObject({
301
+ content: optionalString,
302
+ error_type: optionalString,
303
+ http_status_code: optionalNumber,
304
+ url: optionalString
305
+ })),
306
+ extract_id: z.pipe(both(optionalString, optionalScalar), z.transform(({ first, second }) => ({
307
+ id: second,
308
+ text: first
309
+ }))),
310
+ results: arrayOf(withOriginal(ExtractResult)),
311
+ usage: Usage,
312
+ warnings
313
+ });
314
+ /** `/v1/responses`: the ids are read as text (a continuation id) and as a request id. */
315
+ const AnswerResponse = looseObject({
316
+ error: looseObject({ message: optionalString }),
317
+ id: z.pipe(both(optionalString, optionalScalar), z.transform(({ first, second }) => ({
318
+ request: second,
319
+ text: first
320
+ }))),
321
+ incomplete_details: looseObject({ reason: optionalString }),
322
+ output: arrayOf(looseObject({
323
+ content: arrayOf(looseObject({
324
+ annotations: arrayOf(looseObject({
325
+ ...sourceShape,
326
+ type: optionalString
327
+ })),
328
+ text: optionalString,
329
+ type: optionalString
330
+ })),
331
+ phase: optionalString,
332
+ type: optionalString
333
+ })),
334
+ status: optionalString,
335
+ usage: looseObject({
336
+ input_tokens: optionalNumber,
337
+ output_tokens: optionalNumber,
338
+ total_tokens: optionalNumber
339
+ })
340
+ });
341
+ const Decision = looseObject({
342
+ choice: optionalString,
343
+ confidence: optionalNumber,
344
+ noul: optionalNumber,
345
+ probabilities: recordOf(optionalNumber),
346
+ type: optionalString
347
+ });
348
+ /** `/v1/decisions`. */
349
+ const DecisionsResponse = looseObject({
350
+ answers: recordOf(Decision),
351
+ citations: arrayOf(Source),
352
+ decision_id: optionalScalar,
353
+ usage: looseObject({ input_tokens: optionalNumber })
354
+ });
355
+ /** The reply to starting a task run. */
356
+ const TaskStart = looseObject({ run_id: withOriginal(optionalId) });
357
+ /** A task run while it is polled. */
358
+ const TaskRun = withOriginal(looseObject({
359
+ error: looseObject({ message: optionalString }),
360
+ status: optionalString,
361
+ warnings: arrayOf(looseObject({ message: optionalString }))
362
+ }));
363
+ /** A finished task run's result, beside the response as it arrived. */
364
+ const TaskResult = withOriginal(looseObject({
365
+ output: looseObject({
366
+ basis: arrayOf(Basis),
367
+ content: anything
368
+ }),
369
+ run: looseObject({
370
+ interaction_id: optionalString,
371
+ run_id: optionalScalar,
372
+ warnings
373
+ })
374
+ }));
375
+ /** The reply to starting a FindAll run. */
376
+ const FindAllStart = looseObject({ findall_id: withOriginal(optionalId) });
377
+ /** A FindAll run while it is polled. */
378
+ const FindAllRun = withOriginal(looseObject({ status: looseObject({ status: optionalString }) }));
379
+ const Candidate = looseObject({
380
+ basis: arrayOf(Basis),
381
+ description: optionalString,
382
+ match_status: optionalString,
383
+ name: optionalString,
384
+ output: recordOf(looseObject({
385
+ type: optionalString,
386
+ value: anything
387
+ })),
388
+ url: optionalString
389
+ });
390
+ /** A finished FindAll run's result, beside the response as it arrived. */
391
+ const FindAllResult = withOriginal(looseObject({
392
+ candidates: arrayOf(Candidate),
393
+ run: looseObject({ status: looseObject({
394
+ metrics: looseObject({
395
+ generated_candidates_count: optionalNumber,
396
+ matched_candidates_count: optionalNumber
397
+ }),
398
+ status: optionalString,
399
+ termination_reason: optionalString
400
+ }) })
401
+ }));
402
+ /** A monitor beside the entry as it arrived. */
403
+ const MonitorEntry = withOriginal(looseObject({
404
+ created_at: optionalString,
405
+ frequency: optionalString,
406
+ monitor_id: withOriginal(optionalId),
407
+ settings: looseObject({ query: optionalString }),
408
+ status: optionalString,
409
+ webhook: looseObject({ url: optionalString })
410
+ }));
411
+ /** One page of monitors. */
412
+ const MonitorsPage = looseObject({
413
+ monitors: arrayOf(MonitorEntry),
414
+ next_cursor: optionalString
415
+ });
416
+ const EventOutput = looseObject({
417
+ basis: arrayOf(Basis),
418
+ content: Content
419
+ });
420
+ /** One page of a monitor's events, each beside its entry as it arrived. */
421
+ const EventsPage = looseObject({
422
+ events: arrayOf(withOriginal(looseObject({
423
+ changed_output: EventOutput,
424
+ error_message: optionalString,
425
+ event_date: optionalString,
426
+ event_id: optionalString,
427
+ event_type: optionalString,
428
+ output: EventOutput,
429
+ timestamp: optionalString
430
+ }))),
431
+ next_cursor: optionalString
432
+ });
255
433
  // src/adapters/parallel/jobs.ts
256
- const stoppedRun = (id, run) => {
257
- const status = text(run.status) ?? "unknown";
258
- const reason = text(record(run.error).message);
259
- const warnings = list(run.warnings).map((item) => text(record(item).message)).filter((item) => item !== void 0);
434
+ const stoppedRun = (id, entry) => {
435
+ const run = entry.value;
436
+ const status = run.status ?? "unknown";
437
+ const reason = run.error.message;
438
+ const warnings = run.warnings.map((item) => item.message).filter((item) => item !== void 0);
260
439
  let message;
261
440
  if (status === "action_required") message = `parallel task 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`;
262
441
  else if (status === "cancelled") message = `parallel task run ${id} was cancelled`;
263
442
  else message = `parallel task run ${id} failed: ${reason ?? "no reason given"}`;
264
443
  if (warnings.length > 0) message += ` (${warnings.join("; ")})`;
265
444
  return new FieldworkError("JobFailed", message, {
266
- cause: run,
445
+ cause: entry.original,
267
446
  jobId: id,
268
447
  provider
269
448
  });
270
449
  };
271
450
  const taskResult = async (raw, id, signal) => {
272
451
  try {
273
- return record(await raw.request("GET", `/v1/tasks/runs/${id}/result`, { signal }));
452
+ return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${id}/result`, { signal }));
274
453
  } catch (error) {
275
454
  if (error instanceof FieldworkError && error.code === "NotFound") {
276
- const run = record(await raw.request("GET", `/v1/tasks/runs/${id}`, { signal }));
277
- if (text(run.status) === "failed" || text(run.status) === "cancelled") throw stoppedRun(id, run);
455
+ const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${id}`, { signal }));
456
+ if (run.value.status === "failed" || run.value.status === "cancelled") throw stoppedRun(id, run);
278
457
  }
279
458
  throw error;
280
459
  }
281
460
  };
282
461
  const runTask = async (raw, body, settings) => {
283
462
  const { resume, ...wait } = settings;
284
- const id = resume ?? requireId(raw.provider, record(await raw.request("POST", "/v1/tasks/runs", {
463
+ const id = resume ?? requireJobId(raw.provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
285
464
  body,
465
+ creates: true,
286
466
  signal: wait.signal,
287
467
  timeout: wait.timeout
288
468
  })).run_id);
289
469
  return {
290
470
  id,
291
471
  result: await poll(raw.provider, id, async () => {
292
- const run = record(await raw.request("GET", `/v1/tasks/runs/${id}`, { signal: wait.signal }));
293
- const status = text(run.status);
472
+ const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${id}`, { signal: wait.signal }));
473
+ const { status } = run.value;
294
474
  if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
295
475
  return status === "completed" ? await taskResult(raw, id, wait.signal) : void 0;
296
476
  }, wait)
297
477
  };
298
478
  };
299
479
  const startFindAll = async (raw, objective, o, call) => {
300
- const created = record(await raw.request("POST", "/v1beta/findall/runs", {
480
+ const created = z.parse(FindAllStart, await raw.request("POST", "/v1beta/findall/runs", {
481
+ creates: true,
301
482
  ...call,
302
483
  body: compact({
303
484
  entity_type: o.entityType,
@@ -312,13 +493,14 @@ const startFindAll = async (raw, objective, o, call) => {
312
493
  objective
313
494
  })
314
495
  }));
315
- const id = requireId(provider, created.findall_id);
496
+ const id = requireJobId(provider, created.findall_id);
316
497
  if (o.schema) try {
317
498
  await raw.request("POST", `/v1beta/findall/runs/${id}/enrich`, {
318
499
  body: compact({
319
500
  output_schema: jsonOutput(o.schema),
320
501
  processor: o.processor
321
502
  }),
503
+ creates: true,
322
504
  signal: call.signal
323
505
  });
324
506
  } catch (error) {
@@ -326,15 +508,16 @@ const startFindAll = async (raw, objective, o, call) => {
326
508
  }
327
509
  return id;
328
510
  };
511
+ /** The result of a FindAll run once it has stopped, or undefined while it runs. */
329
512
  const findAllResult = async (raw, id, signal) => {
330
- const run = record(await raw.request("GET", `/v1beta/findall/runs/${id}`, { signal }));
331
- const status = text(record(run.status).status);
513
+ const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${id}`, { signal }));
514
+ const { status } = run.value.status;
332
515
  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`, {
333
- cause: run,
516
+ cause: run.original,
334
517
  jobId: id,
335
518
  provider
336
519
  });
337
- return status === "completed" || status === "failed" || status === "cancelled" ? record(await raw.request("GET", `/v1beta/findall/runs/${id}/result`, { signal })) : void 0;
520
+ return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${id}/result`, { signal })) : void 0;
338
521
  };
339
522
  // src/adapters/parallel.ts
340
523
  const parallel = (config = {}) => {
@@ -342,7 +525,8 @@ const parallel = (config = {}) => {
342
525
  baseUrl: config.baseUrl ?? "https://api.parallel.ai",
343
526
  fetch: config.fetch,
344
527
  headers: { "x-api-key": requireKey(provider, config.apiKey, "PARALLEL_API_KEY") },
345
- provider
528
+ provider,
529
+ retries: config.retries
346
530
  });
347
531
  return defineAdapter({
348
532
  name: provider,
@@ -354,7 +538,7 @@ const parallel = (config = {}) => {
354
538
  allowed_domains: o.includeDomains,
355
539
  blocked_domains: o.excludeDomains
356
540
  });
357
- const response = record(await raw.request("POST", "/v1/responses", {
541
+ const response = await raw.request("POST", "/v1/responses", {
358
542
  ...call,
359
543
  body: compact({
360
544
  input: question,
@@ -365,7 +549,7 @@ const parallel = (config = {}) => {
365
549
  reasoning: o.effort ? { effort: o.effort } : void 0,
366
550
  text: o.schema ? { format: {
367
551
  name: "answer",
368
- schema: o.schema,
552
+ schema: jsonSchemaOf(o.schema),
369
553
  type: "json_schema"
370
554
  } } : void 0,
371
555
  tools: filters ? [{
@@ -373,34 +557,35 @@ const parallel = (config = {}) => {
373
557
  type: "web_search"
374
558
  }] : void 0
375
559
  })
376
- }));
377
- const failure = record(response.error);
378
- if (response.status === "failed" || text(failure.message)) throw new FieldworkError("ProviderError", `parallel could not answer: ${text(failure.message) ?? "the response failed"}`, {
560
+ });
561
+ const body = z.parse(AnswerResponse, response);
562
+ const failure = body.error.message;
563
+ if (body.status === "failed" || failure !== void 0) throw new FieldworkError("ProviderError", `parallel could not answer: ${failure ?? "the response failed"}`, {
379
564
  cause: response,
380
565
  provider
381
566
  });
382
- const parts = responseMessages(response).flatMap((message) => list(message.content).map((part) => record(part)).filter((part) => part.type === "output_text"));
383
- const answer = parts.map((part) => text(part.text)).filter((part) => part !== void 0).join("\n\n");
384
- if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${text(response.status) ?? "unknown"})`, {
567
+ const parts = responseMessages(body).flatMap((message) => message.content.filter((part) => part.type === "output_text"));
568
+ const answer = parts.map((part) => part.text).filter((part) => part !== void 0).join("\n\n");
569
+ if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${body.status ?? "unknown"})`, {
385
570
  cause: response,
386
571
  provider
387
572
  });
388
- const usage = record(response.usage);
389
- const incomplete = text(record(response.incomplete_details).reason);
573
+ const { usage } = body;
574
+ const incomplete = body.incomplete_details.reason;
390
575
  return compact({
391
576
  answer,
392
- citations: uniqueCitations(citations(parts.flatMap((part) => list(part.annotations)).filter((item) => record(item).type === "url_citation"))),
393
- continuationId: text(response.id),
577
+ citations: uniqueCitations(citationsOf(parts.flatMap((part) => part.annotations).filter((item) => item.type === "url_citation"))),
578
+ continuationId: body.id.text,
394
579
  meta: meta({
395
- requestId: response.id,
580
+ requestId: body.id.request,
396
581
  units: {
397
582
  input_tokens: usage.input_tokens,
398
583
  output_tokens: usage.output_tokens,
399
584
  total_tokens: usage.total_tokens
400
585
  },
401
- warnings: incomplete ? [`the answer is incomplete: ${incomplete}`] : void 0
586
+ warnings: incomplete === void 0 ? void 0 : [`the answer is incomplete: ${incomplete}`]
402
587
  }),
403
- output: o.schema ? parseJson(provider, answer) : void 0,
588
+ output: o.schema ? await checkOutput(o.schema, parseJson(provider, answer), { provider }) : void 0,
404
589
  raw: response
405
590
  });
406
591
  },
@@ -411,7 +596,7 @@ const parallel = (config = {}) => {
411
596
  if (names.length < 1 || names.length > 100) throw invalid(`parallel decisions take 1 to 100 questions; got ${names.length}`);
412
597
  const badName = names.find((name) => !QUESTION_NAME.test(name));
413
598
  if (badName !== void 0) throw invalid(`parallel question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
414
- const response = record(await raw.request("POST", "/v1/decisions", {
599
+ const response = await raw.request("POST", "/v1/decisions", {
415
600
  ...call,
416
601
  body: compact({
417
602
  advanced_settings: nonEmpty({
@@ -421,16 +606,19 @@ const parallel = (config = {}) => {
421
606
  questions: Object.fromEntries(entries.map(([name, question]) => [name, decisionQuestion(name, question)])),
422
607
  state: context ?? null
423
608
  })
424
- }));
425
- const answers = record(response.answers);
609
+ });
610
+ const body = z.parse(DecisionsResponse, response);
426
611
  const result = {};
427
- for (const [name, question] of entries) if (answers[name] !== void 0) result[name] = decisionAnswer(question, answers[name]);
612
+ for (const [name, question] of entries) {
613
+ const answer = body.answers[name];
614
+ if (answer !== void 0) result[name] = decisionAnswer(question, answer);
615
+ }
428
616
  return compact({
429
617
  answers: result,
430
- citations: citations(response.citations),
618
+ citations: citationsOf(body.citations),
431
619
  meta: meta({
432
- requestId: response.decision_id,
433
- units: { input_tokens: record(response.usage).input_tokens }
620
+ requestId: body.decision_id,
621
+ units: { input_tokens: body.usage.input_tokens }
434
622
  }),
435
623
  raw: response
436
624
  });
@@ -442,12 +630,26 @@ const parallel = (config = {}) => {
442
630
  ...call,
443
631
  interval: o.interval
444
632
  });
445
- return discovery(id, result);
633
+ const found = discovery(id, result);
634
+ const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => {
635
+ if (data === void 0) return entity;
636
+ return {
637
+ ...entity,
638
+ data: await checkOutput(o.schema, data, {
639
+ jobId: id,
640
+ provider
641
+ })
642
+ };
643
+ }));
644
+ return {
645
+ ...found,
646
+ entities
647
+ };
446
648
  },
447
649
  async extract(url, options) {
448
650
  const { call, rest: o } = callSettings(options);
449
651
  const target = new URL(url);
450
- const { result } = await runTask(raw, compact({
652
+ const { id, result } = await runTask(raw, compact({
451
653
  advanced_settings: nonEmpty({ location: o.country }),
452
654
  input: {
453
655
  instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
@@ -462,17 +664,20 @@ const parallel = (config = {}) => {
462
664
  interval: o.interval,
463
665
  resume: o.resume
464
666
  });
465
- const output = record(result.output);
667
+ const { output } = result.value;
466
668
  return compact({
467
- data: output.content,
669
+ data: await checkOutput(o.schema, output.content, {
670
+ jobId: id,
671
+ provider
672
+ }),
468
673
  fields: basis(output.basis),
469
674
  meta: taskMeta(result),
470
- raw: result
675
+ raw: result.original
471
676
  });
472
677
  },
473
678
  async images(query, options) {
474
679
  const { call, rest: o } = callSettings(options);
475
- const response = record(await raw.request("POST", "/v1/images/search", {
680
+ const response = await raw.request("POST", "/v1/images/search", {
476
681
  ...call,
477
682
  body: compact({
478
683
  advanced_settings: nonEmpty({
@@ -484,31 +689,28 @@ const parallel = (config = {}) => {
484
689
  search_queries: o.queries ?? [query],
485
690
  session_id: o.sessionId
486
691
  })
487
- }));
692
+ });
693
+ const body = z.parse(ImagesResponse, response);
488
694
  return compact({
489
695
  meta: meta({
490
- requestId: response.search_id,
491
- units: usageUnits(response.usage),
492
- warnings: response.warnings
696
+ requestId: body.search_id,
697
+ units: usageUnits(body.usage),
698
+ warnings: body.warnings
493
699
  }),
494
700
  raw: response,
495
- results: list(response.results).map((item) => {
496
- const image = record(item);
497
- return compact({
498
- height: num(image.height),
499
- sourceUrl: text(image.source_page_url),
500
- title: text(image.title),
501
- url: text(image.image_url) ?? "",
502
- width: num(image.width)
503
- });
504
- })
701
+ results: body.results.map((image) => compact({
702
+ height: image.height,
703
+ sourceUrl: image.source_page_url,
704
+ title: image.title,
705
+ url: image.image_url ?? "",
706
+ width: image.width
707
+ }))
505
708
  });
506
709
  },
507
710
  monitor: {
508
711
  async create(options) {
509
712
  const { call, rest: o } = callSettings(options);
510
- const { urls } = o;
511
- if (urls !== void 0) throw invalid("parallel monitors search the web for a query and cannot watch a list of URLs; restrict a query with includeDomains, which accepts domain/path prefixes");
713
+ if (Object.entries(o).some(([name, value]) => name === "urls" && value !== void 0)) throw invalid("parallel monitors search the web for a query and cannot watch a list of URLs; restrict a query with includeDomains, which accepts domain/path prefixes");
512
714
  if (o.taskRunId === void 0 && o.query === void 0) throw invalid("a parallel monitor needs a query or a taskRunId");
513
715
  if (o.taskRunId !== void 0) for (const name of [
514
716
  "query",
@@ -519,8 +721,9 @@ const parallel = (config = {}) => {
519
721
  "excludeDomains",
520
722
  "publishedAfter"
521
723
  ]) refuseTogether(provider, o, "taskRunId", name);
522
- if (o.webhookEvents && !o.webhookUrl) throw invalid("webhookEvents needs a webhookUrl");
724
+ if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalid("webhookEvents needs a webhookUrl");
523
725
  const response = await raw.request("POST", "/v1/monitors", {
726
+ creates: true,
524
727
  ...call,
525
728
  body: compact({
526
729
  frequency: frequency(o.schedule),
@@ -528,28 +731,28 @@ const parallel = (config = {}) => {
528
731
  processor: o.processor,
529
732
  settings: o.taskRunId === void 0 ? compact({
530
733
  advanced_settings: nonEmpty({
531
- source_policy: sourcePolicy(o),
532
- location: o.country
734
+ location: o.country,
735
+ source_policy: sourcePolicy(o)
533
736
  }),
534
737
  include_backfill: o.includeBackfill,
535
738
  output_schema: o.schema ? jsonOutput(o.schema) : void 0,
536
739
  query: o.query
537
740
  }) : { task_run_id: o.taskRunId },
538
741
  type: o.taskRunId === void 0 ? "event_stream" : "snapshot",
539
- webhook: o.webhookUrl ? compact({
742
+ webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : compact({
540
743
  event_types: o.webhookEvents,
541
744
  url: o.webhookUrl
542
- }) : void 0
745
+ })
543
746
  })
544
747
  });
545
- return monitorInfo(response);
748
+ return monitorInfo(z.parse(MonitorEntry, response));
546
749
  },
547
750
  async delete(id, options) {
548
751
  await raw.request("POST", `/v1/monitors/${encodeURIComponent(id)}/cancel`, options);
549
752
  },
550
753
  async events(id, options) {
551
754
  const { call, rest: o } = callSettings(options);
552
- const response = record(await raw.request("GET", `/v1/monitors/${encodeURIComponent(id)}/events`, {
755
+ const response = await raw.request("GET", `/v1/monitors/${encodeURIComponent(id)}/events`, {
553
756
  ...call,
554
757
  query: {
555
758
  cursor: o.cursor,
@@ -557,70 +760,70 @@ const parallel = (config = {}) => {
557
760
  include_completions: o.includeCompletions,
558
761
  limit: o.limit
559
762
  }
560
- }));
763
+ });
764
+ const page = z.parse(EventsPage, response);
561
765
  return compact({
562
- events: list(response.events).map((item) => monitorEvent(item)),
563
- next: text(response.next_cursor),
766
+ events: page.events.map((entry) => monitorEvent(entry)),
767
+ next: page.next_cursor,
564
768
  raw: response
565
769
  });
566
770
  },
567
771
  async get(id, options) {
568
- return monitorInfo(await raw.request("GET", `/v1/monitors/${encodeURIComponent(id)}`, options));
772
+ return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${encodeURIComponent(id)}`, options)));
569
773
  },
570
774
  async list(options) {
571
775
  const monitors = [];
572
776
  let cursor;
573
777
  do {
574
- const page = record(await raw.request("GET", "/v1/monitors", {
778
+ const page = z.parse(MonitorsPage, await raw.request("GET", "/v1/monitors", {
575
779
  ...options,
576
780
  query: {
577
781
  cursor,
578
782
  limit: 100
579
783
  }
580
784
  }));
581
- monitors.push(...list(page.monitors).map((item) => monitorInfo(item)));
582
- cursor = text(page.next_cursor);
785
+ monitors.push(...page.monitors.map((entry) => monitorInfo(entry)));
786
+ cursor = page.next_cursor;
583
787
  } while (cursor !== void 0);
584
788
  return monitors;
585
789
  }
586
790
  },
587
791
  async read(url, options) {
588
792
  const { call, rest: o } = callSettings(options);
589
- const response = record(await raw.request("POST", "/v1/extract", {
793
+ const response = await raw.request("POST", "/v1/extract", {
590
794
  ...call,
591
795
  body: extractBody([url], o)
592
- }));
593
- const result = record(list(response.results)[0]);
594
- if (!result.url) {
595
- const failure = record(list(response.errors)[0]);
596
- throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${Object.keys(failure).length > 0 ? extractFailure(failure) : "no content returned"}`, {
796
+ });
797
+ const body = z.parse(ExtractResponse, response);
798
+ const [result] = body.results;
799
+ if (result?.value.url === void 0) {
800
+ const [failure] = body.errors;
801
+ throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${failure !== void 0 && Object.keys(failure).length > 0 ? extractFailure(failure) : "no content returned"}`, {
597
802
  cause: response,
598
803
  provider
599
804
  });
600
805
  }
601
806
  return pageFrom(result, {
602
- meta: extractMeta(response),
807
+ meta: extractMeta(body),
603
808
  raw: response
604
809
  });
605
810
  },
606
811
  async readMany(urls, options) {
607
812
  const { call, rest: o } = callSettings(options);
608
813
  if (urls.length > 20) throw invalid(`parallel reads up to 20 URLs in one call; got ${urls.length}`);
609
- const response = record(await raw.request("POST", "/v1/extract", {
814
+ const response = await raw.request("POST", "/v1/extract", {
610
815
  ...call,
611
816
  body: extractBody(urls, o)
612
- }));
817
+ });
818
+ const body = z.parse(ExtractResponse, response);
613
819
  return compact({
614
- failed: list(response.errors).map((item) => {
615
- const failure = record(item);
616
- return {
617
- error: extractFailure(failure),
618
- url: text(failure.url) ?? ""
619
- };
620
- }),
621
- id: text(response.extract_id),
622
- meta: extractMeta(response),
623
- pages: list(response.results).map((item) => pageFrom(record(item))),
820
+ failed: body.errors.map((failure) => ({
821
+ error: extractFailure(failure),
822
+ url: failure.url ?? ""
823
+ })),
824
+ id: body.extract_id.text,
825
+ meta: extractMeta(body),
826
+ pages: body.results.map((entry) => pageFrom(entry)),
624
827
  raw: response
625
828
  });
626
829
  },
@@ -639,22 +842,25 @@ const parallel = (config = {}) => {
639
842
  interval: o.interval,
640
843
  resume: o.resume
641
844
  });
642
- const output = record(result.output);
845
+ const { output, run } = result.value;
643
846
  const fields = basis(output.basis);
644
847
  return compact({
645
- continuationId: text(record(result.run).interaction_id),
848
+ continuationId: run.interaction_id,
646
849
  fields,
647
850
  id,
648
851
  meta: taskMeta(result),
649
- output: output.content,
650
- raw: result,
852
+ output: await checkOutput(o.schema, output.content, {
853
+ jobId: id,
854
+ provider
855
+ }),
856
+ raw: result.original,
651
857
  sources: citedBy(fields),
652
858
  status: "completed"
653
859
  });
654
860
  },
655
861
  async search(query, options) {
656
862
  const { call, rest: o } = callSettings(options);
657
- const response = record(await raw.request("POST", "/v1/search", {
863
+ const response = await raw.request("POST", "/v1/search", {
658
864
  ...call,
659
865
  body: compact({
660
866
  advanced_settings: nonEmpty({
@@ -670,23 +876,21 @@ const parallel = (config = {}) => {
670
876
  search_queries: o.queries ?? [query],
671
877
  session_id: o.sessionId
672
878
  })
673
- }));
879
+ });
880
+ const body = z.parse(SearchResponse, response);
674
881
  return compact({
675
882
  meta: meta({
676
- requestId: response.search_id,
677
- units: usageUnits(response.usage),
678
- warnings: response.warnings
883
+ requestId: body.search_id,
884
+ units: usageUnits(body.usage),
885
+ warnings: body.warnings
679
886
  }),
680
887
  raw: response,
681
- results: list(response.results).map((item) => {
682
- const result = record(item);
683
- return compact({
684
- publishedAt: text(result.publish_date),
685
- snippet: strings(result.excerpts)?.join(" … "),
686
- title: text(result.title),
687
- url: text(result.url) ?? ""
688
- });
689
- })
888
+ results: body.results.map((result) => compact({
889
+ publishedAt: result.publish_date,
890
+ snippet: result.excerpts.length > 0 ? result.excerpts.join(" … ") : void 0,
891
+ title: result.title,
892
+ url: result.url ?? ""
893
+ }))
690
894
  });
691
895
  }
692
896
  },