@howells/fieldwork-sdk 0.5.2 → 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,7 +1,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
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";
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
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
@@ -65,23 +65,26 @@ const mostLikely = (chances) => {
65
65
  return best;
66
66
  };
67
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`.
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`.
72
74
  */
73
75
  const decisionAnswer = (question, answer) => {
74
76
  if (answer.type === "refusal") return { refusal: "Parallel declined to answer this question" };
75
77
  const { confidence } = answer;
76
- if (question.type === "yesno") return compact({ probability: answer.noul });
77
- 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({
78
80
  choice: answer.choice,
79
81
  confidence,
80
82
  probabilities: probabilities(answer.probabilities)
81
83
  });
82
84
  const keys = Object.keys(question.scale);
83
85
  const byLevel = probabilities(answer.probabilities);
84
- 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]));
85
88
  return compact({
86
89
  choice: mostLikely(byKey),
87
90
  confidence,
@@ -523,6 +526,29 @@ const EventsPage = looseObject({
523
526
  next_cursor: optionalString
524
527
  });
525
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
+ };
526
552
  /**
527
553
  * The `JobFailed` error for a Task run that ended without a result: cancelled,
528
554
  * failed with Parallel's message, or `action_required`, which waits on something
@@ -562,22 +588,31 @@ const taskResult = async (raw, id, request) => {
562
588
  /**
563
589
  * Runs a task to its result, or waits for the run named by `resume`. A failed,
564
590
  * cancelled or `action_required` run throws at once; queued, running and
565
- * cancelling runs are polled again.
591
+ * cancelling runs are polled again; any other status throws `ProviderError`.
592
+ * A completed run whose result has no `output.content` throws `JobFailed`.
566
593
  */
567
594
  const runTask = async (raw, body, settings, finish) => await runJob(provider, {
568
595
  check: async (id, request) => {
569
596
  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;
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;
603
+ },
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);
573
610
  },
574
- finish,
575
- start: async () => requireJobId(provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
611
+ start: async () => await startJob(raw, "/v1/tasks/runs", {
576
612
  body,
577
- creates: true,
578
613
  retries: settings.retries,
579
614
  signal: settings.signal
580
- })).run_id)
615
+ }, TaskStart, (reply) => reply.run_id)
581
616
  }, settings);
582
617
  /**
583
618
  * Starts a FindAll run and returns its id. With a `schema` it then adds the
@@ -585,8 +620,7 @@ const runTask = async (raw, body, settings, finish) => await runJob(provider, {
585
620
  * already exists.
586
621
  */
587
622
  const startFindAll = async (raw, objective, o, call) => {
588
- const created = z.parse(FindAllStart, await raw.request("POST", "/v1beta/findall/runs", {
589
- creates: true,
623
+ const id = await startJob(raw, "/v1beta/findall/runs", {
590
624
  ...call,
591
625
  body: compact({
592
626
  entity_type: o.entityType,
@@ -600,8 +634,7 @@ const startFindAll = async (raw, objective, o, call) => {
600
634
  metadata: o.metadata,
601
635
  objective
602
636
  })
603
- }));
604
- const id = requireJobId(provider, created.findall_id);
637
+ }, FindAllStart, (reply) => reply.findall_id);
605
638
  if (o.schema) try {
606
639
  await raw.request("POST", `/v1beta/findall/runs/${segment(id)}/enrich`, {
607
640
  ...call,
@@ -618,16 +651,20 @@ const startFindAll = async (raw, objective, o, call) => {
618
651
  };
619
652
  /**
620
653
  * The result of a FindAll run once it has stopped (completed, failed or
621
- * cancelled), or undefined while it runs. `action_required` throws `JobFailed`.
654
+ * cancelled), or undefined while it runs. `action_required` throws `JobFailed`,
655
+ * and a status Parallel does not document throws `ProviderError`.
622
656
  */
623
657
  const findAllResult = async (raw, id, request) => {
624
658
  const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
625
- const { status } = run.value.status;
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`, {
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`, {
627
664
  cause: run.original,
628
665
  provider
629
666
  });
630
- 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;
631
668
  };
632
669
  // src/adapters/parallel.ts
633
670
  /**
@@ -724,10 +761,17 @@ const parallel = (config = {}) => {
724
761
  });
725
762
  const body = z.parse(DecisionsResponse, response);
726
763
  const result = {};
764
+ const unanswered = [];
727
765
  for (const [name, question] of entries) {
728
- const answer = body.answers[name];
729
- 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;
730
770
  }
771
+ if (unanswered.length > 0) throw new FieldworkError("ProviderError", `parallel returned no complete answer for ${unanswered.join(", ")}`, {
772
+ cause: response,
773
+ provider
774
+ });
731
775
  return compact({
732
776
  answers: result,
733
777
  citations: citationsOf(body.citations),
@@ -762,6 +806,7 @@ const parallel = (config = {}) => {
762
806
  },
763
807
  async extract(url, options) {
764
808
  const { call, rest: o } = callSettings(options);
809
+ if (!URL.canParse(url)) throw invalidRequest(provider, `cannot extract ${url}: it is not a URL`);
765
810
  const target = new URL(url);
766
811
  return await runTask(raw, compact({
767
812
  advanced_settings: nonEmpty({ location: o.country }),
@@ -6,12 +6,26 @@ const isJson = (value) => typeof value === "object" && value !== null && !Array.
6
6
  const record = (value) => isJson(value) ? value : {};
7
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. */
8
8
  const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
9
+ /** The longest `timeout` a timer holds, in milliseconds: about 24.8 days. */
10
+ const MAX_TIMEOUT = 2147483647;
11
+ /**
12
+ * Refuses a `timeout` or `retries` that no timer or retry count can hold,
13
+ * before anything is sent.
14
+ *
15
+ * Throws `InvalidRequest` naming the accepted range.
16
+ */
17
+ const checkCallSettings = (settings) => {
18
+ const { retries, timeout } = settings;
19
+ if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 0 && timeout <= MAX_TIMEOUT)) throw new FieldworkError("InvalidRequest", `timeout is ${timeout}: pass a whole number of milliseconds from 0 to ${MAX_TIMEOUT}`);
20
+ if (retries !== void 0 && !(Number.isInteger(retries) && retries >= 0)) throw new FieldworkError("InvalidRequest", `retries is ${retries}: pass a whole number from 0 up`);
21
+ };
9
22
  /**
10
23
  * Splits an operation's options into the provider's own and the call's
11
24
  * settings. The call's `signal` also carries its `timeout` as a deadline, set
12
25
  * now, so every request the operation makes (a start, each poll, a result
13
26
  * download) shares one budget instead of restarting it. An empty `resume`
14
- * names no job, so it is refused here, once for every adapter.
27
+ * names no job, and a `timeout` or `retries` out of range holds no deadline or
28
+ * count, so both are refused here, once for every adapter.
15
29
  *
16
30
  * `grace` extends the deadline past `timeout` for an operation that sends the
17
31
  * timeout to the provider and needs a moment more to hear its report.
@@ -19,10 +33,14 @@ const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, i
19
33
  const callSettings = (options, grace = 0) => {
20
34
  const { retries, signal, timeout, ...rest } = options ?? {};
21
35
  if ("resume" in rest && rest.resume === "") throw new FieldworkError("InvalidRequest", "resume is empty: pass the jobId an earlier call returned, or leave resume out to start a job");
36
+ checkCallSettings({
37
+ retries,
38
+ timeout
39
+ });
22
40
  return {
23
41
  call: {
24
42
  retries,
25
- signal: timeout === void 0 ? signal : AbortSignal.any([...signal === void 0 ? [] : [signal], AbortSignal.timeout(timeout + grace)]),
43
+ signal: timeout === void 0 ? signal : AbortSignal.any([...signal === void 0 ? [] : [signal], AbortSignal.timeout(Math.min(timeout + grace, MAX_TIMEOUT))]),
26
44
  timeout
27
45
  },
28
46
  rest
@@ -131,17 +149,23 @@ const presentPages = (pages) => ({
131
149
  /**
132
150
  * Waits `ms`. When `signal` aborts it resolves early rather than rejecting, so
133
151
  * the caller checks the signal afterwards. A signal already aborted on entry
134
- * returns at once.
152
+ * returns at once. The abort listener is removed when the wait ends, so a
153
+ * signal shared by many polls does not collect them.
135
154
  */
136
155
  const sleep = async (ms, signal) => {
137
156
  if (signal?.aborted === true) return;
157
+ const cleanup = new AbortController();
138
158
  await new Promise((resolve) => {
139
159
  const timer = setTimeout(resolve, ms);
140
160
  signal?.addEventListener("abort", () => {
141
161
  clearTimeout(timer);
142
162
  resolve();
143
- }, { once: true });
163
+ }, {
164
+ once: true,
165
+ signal: cleanup.signal
166
+ });
144
167
  });
168
+ cleanup.abort();
145
169
  };
146
170
  /** The longest wait between attempts; a provider asking for longer gets the error instead. */
147
171
  const MAX_RETRY_WAIT = 3e4;
@@ -168,6 +192,22 @@ const timedOut = (signal) => signal.reason instanceof DOMException && signal.rea
168
192
  * requests), `Aborted` when the caller cancelled.
169
193
  */
170
194
  const stopped = (signal, message, options) => new FieldworkError(timedOut(signal) ? "Timeout" : "Aborted", message, options);
195
+ /**
196
+ * The error a request that creates something throws. After anything but a
197
+ * rate limit the provider may already have created it, and the error carries
198
+ * no `jobId` to resume, so it is not `retryable`: repeating the call could
199
+ * start and charge for a second one.
200
+ */
201
+ const createFailure = (error) => {
202
+ if (!error.retryable || error.code === "RateLimited") return error;
203
+ return new FieldworkError(error.code, `${error.message}; ${error.provider ?? "the provider"} may already have created it, so check before repeating the call`, {
204
+ cause: error.cause,
205
+ provider: error.provider,
206
+ retryAfter: error.retryAfter,
207
+ retryable: false,
208
+ status: error.status
209
+ });
210
+ };
171
211
  /** 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. */
172
212
  const transportError = (provider, error, signal) => {
173
213
  if (signal?.aborted === true) return stopped(signal, `${provider} request stopped: ${timedOut(signal) ? "timed out" : "cancelled"}`, {
@@ -206,6 +246,11 @@ const createRawClient = (config) => {
206
246
  baseUrl: config.baseUrl,
207
247
  provider: config.provider,
208
248
  async request(method, path, options = {}) {
249
+ const retries = options.retries ?? config.retries ?? 2;
250
+ checkCallSettings({
251
+ retries,
252
+ timeout: options.timeout
253
+ });
209
254
  const url = new URL(config.baseUrl.replace(/\/$/u, "") + path);
210
255
  for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
211
256
  const headers = new Headers({
@@ -256,7 +301,6 @@ const createRawClient = (config) => {
256
301
  status: response.status
257
302
  });
258
303
  };
259
- const retries = options.retries ?? config.retries ?? 2;
260
304
  const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
261
305
  const attempt = async (count) => {
262
306
  try {
@@ -269,7 +313,7 @@ const createRawClient = (config) => {
269
313
  retries,
270
314
  signal
271
315
  });
272
- if (wait === void 0 || deadline !== void 0 && Date.now() + wait >= deadline) throw error;
316
+ if (wait === void 0 || deadline !== void 0 && Date.now() + wait >= deadline) throw options.creates === true ? createFailure(error) : error;
273
317
  await sleep(wait, signal);
274
318
  if (options.signal?.aborted === true) throw stopped(options.signal, `${config.provider} request stopped while waiting to retry`, {
275
319
  cause: error,
@@ -356,8 +400,17 @@ const retryAfterSeconds = (header, now = Date.now()) => {
356
400
  const date = Date.parse(header);
357
401
  return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
358
402
  };
359
- /** An id as one path segment, so a caller's `resume` cannot reach another endpoint. */
360
- const segment = (id) => encodeURIComponent(id);
403
+ /**
404
+ * An id as one path segment, so a caller's `resume` cannot reach another
405
+ * endpoint.
406
+ *
407
+ * Throws `InvalidRequest` for an empty id, "." or "..", which survive encoding
408
+ * and which the URL parser would resolve to another path.
409
+ */
410
+ const segment = (id) => {
411
+ if (id === "" || id === "." || id === "..") throw new FieldworkError("InvalidRequest", `${JSON.stringify(id)} is not an id: pass the id the provider returned`);
412
+ return encodeURIComponent(id);
413
+ };
361
414
  /**
362
415
  * The API key: `given`, else the environment variable. An empty `given` is
363
416
  * not replaced by the variable.
@@ -1,5 +1,5 @@
1
- import { K as Recency, Y as SearchResponse, a as RawClient, b as Decisions, l as Answer, p as CallOptions, q as Research, t as Adapter, y as DecisionQuestion } from "./adapter-BhTK51Yj.js";
2
- import { t as OutputSchema } from "./schema-CNd51xdD.js";
1
+ import { K as Recency, Y as SearchResponse, a as RawClient, b as Decisions, l as Answer, p as CallOptions, q as Research, t as Adapter, y as DecisionQuestion } from "./adapter-Bh8EIrNe.js";
2
+ import { t as OutputSchema } from "./schema-BWWiMvkg.js";
3
3
  /** Settings for `perplexity()`. */
4
4
  interface PerplexityConfig {
5
5
  /** Defaults to the PERPLEXITY_API_KEY environment variable. */
@@ -1,19 +1,12 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { A as citationOf, 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, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, y as sourceShape, z as refuseTogether } from "./parse-BY3R0oWO.js";
4
- import { t as runJob } from "./job-DVsmQMKP.js";
3
+ import { A as citationOf, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, V as uniqueCitations, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, y as sourceShape, z as refuseTogether } from "./parse-COHKvfH9.js";
4
+ import { i as startJob, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
5
5
  import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/perplexity/parse.ts
8
8
  /** The name this adapter reports in errors and results. */
9
9
  const provider = "perplexity";
10
- /** The Agent run statuses after which a run no longer changes. */
11
- const TERMINAL = /* @__PURE__ */ new Set([
12
- "completed",
13
- "failed",
14
- "incomplete",
15
- "cancelled"
16
- ]);
17
10
  /** Perplexity's MM/DD/YYYY form of a YYYY-MM-DD date. Refuses any other format. */
18
11
  const usDate = (name, date) => {
19
12
  if (date === void 0) return date;
@@ -217,17 +210,24 @@ const decisionQuestion = (question) => {
217
210
  };
218
211
  };
219
212
  /**
220
- * One decision answer. `noul` gives a `probability`. Otherwise the probabilities
221
- * without undefined entries; for a score, Perplexity's level indexes are renamed to
222
- * the scale's keys (`scores`). `choice` is Perplexity's, else the most likely.
213
+ * One decision answer in the shape its question asks for, or undefined when
214
+ * Perplexity left out the part the question needs: a `yesno` answer's `noul`,
215
+ * or a `choice` or `score` answer's choice. `noul` gives a `probability`.
216
+ * Otherwise the probabilities without undefined entries; for a score,
217
+ * Perplexity's level indexes are renamed to the scale's keys. `choice` is
218
+ * Perplexity's, else the most likely.
223
219
  */
224
- const decisionAnswer = (found, scores) => {
225
- if (found.type === "noul") return compact({ probability: found.noul });
220
+ const decisionAnswer = (found, question) => {
221
+ if (question.type === "yesno") return found.noul === void 0 ? void 0 : { probability: found.noul };
226
222
  let probabilities = Object.fromEntries(Object.entries(found.probabilities).filter((entry) => entry[1] !== void 0));
227
- if (found.type === "score") probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores?.[Number(index)] ?? index, probability]));
223
+ if (question.type === "score") {
224
+ const scores = Object.keys(question.scale);
225
+ probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores[Number(index)] ?? index, probability]));
226
+ }
228
227
  const top = Object.entries(probabilities).toSorted((a, b) => b[1] - a[1])[0]?.[0];
229
- return compact({
230
- choice: found.choice ?? top,
228
+ const choice = found.choice ?? top;
229
+ return choice === void 0 ? void 0 : compact({
230
+ choice,
231
231
  confidence: found.confidence,
232
232
  probabilities
233
233
  });
@@ -375,24 +375,34 @@ const answer = async (raw, question, options) => {
375
375
  raw: run.original
376
376
  });
377
377
  };
378
- /** Starts a background Agent API run and returns its id. */
379
- const startResearch = async (raw, question, o, call) => {
380
- const created = z.parse(AgentStart, await raw.request("POST", "/v1/agent", {
381
- creates: true,
382
- ...call,
383
- body: compact({
384
- ...researchSetup(o),
385
- background: true,
386
- input: question,
387
- instructions: o.instructions,
388
- language_preference: o.languagePreference,
389
- max_output_tokens: o.maxOutputTokens,
390
- previous_response_id: o.continueFrom,
391
- response_format: responseFormat(o.schema)
392
- })
393
- }));
394
- return requireJobId(provider, created.id);
378
+ /**
379
+ * Perplexity's run statuses, always sent (docs.perplexity.ai/api-reference/agent-get).
380
+ * An incomplete or cancelled run can still carry text, so it counts as
381
+ * finished and `research` decides what it amounts to.
382
+ */
383
+ const RESEARCH_STATES = {
384
+ done: [
385
+ "completed",
386
+ "incomplete",
387
+ "cancelled"
388
+ ],
389
+ failed: ["failed"],
390
+ running: ["queued", "in_progress"]
395
391
  };
392
+ /** Starts a background Agent API run and returns its id. */
393
+ const startResearch = async (raw, question, o, call) => await startJob(raw, "/v1/agent", {
394
+ ...call,
395
+ body: compact({
396
+ ...researchSetup(o),
397
+ background: true,
398
+ input: question,
399
+ instructions: o.instructions,
400
+ language_preference: o.languagePreference,
401
+ max_output_tokens: o.maxOutputTokens,
402
+ previous_response_id: o.continueFrom,
403
+ response_format: responseFormat(o.schema)
404
+ })
405
+ }, AgentStart, (reply) => reply.id);
396
406
  /**
397
407
  * Polls a research run until it reaches a terminal status. A `completed` run
398
408
  * returns `completed`. An `incomplete` or `cancelled` one that left text returns
@@ -404,7 +414,10 @@ const research = async (raw, question, options) => {
404
414
  return await runJob(provider, {
405
415
  check: async (id, request) => {
406
416
  const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${segment(id)}`, request));
407
- return TERMINAL.has(found.value.status ?? "") ? found : void 0;
417
+ return jobState("perplexity", id, RESEARCH_STATES, {
418
+ original: found.original,
419
+ value: found.value.status
420
+ }) === "running" ? void 0 : found;
408
421
  },
409
422
  finish: async (run, id) => {
410
423
  const { status } = run.value;
@@ -445,10 +458,17 @@ const decide = async (raw, context, questions, options) => {
445
458
  });
446
459
  const body = z.parse(DecisionsResponse, response);
447
460
  const answers = {};
448
- for (const [name, value] of Object.entries(body.answers)) {
449
- const question = questions[name];
450
- answers[name] = decisionAnswer(value, question?.type === "score" ? Object.keys(question.scale) : void 0);
461
+ const unanswered = [];
462
+ for (const [name, question] of Object.entries(questions)) {
463
+ const found = Object.hasOwn(body.answers, name) ? body.answers[name] : void 0;
464
+ const decided = found && decisionAnswer(found, question);
465
+ if (decided === void 0) unanswered.push(name);
466
+ else answers[name] = decided;
451
467
  }
468
+ if (unanswered.length > 0) throw new FieldworkError("ProviderError", `perplexity returned no complete answer for ${unanswered.join(", ")}`, {
469
+ cause: response,
470
+ provider
471
+ });
452
472
  const { usage } = body;
453
473
  return {
454
474
  answers,
package/dist/reducto.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-BhTK51Yj.js";
1
+ import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-Bh8EIrNe.js";
2
2
  /** Settings for `reducto()`. */
3
3
  export interface ReductoConfig {
4
4
  /** Defaults to the REDUCTO_API_KEY environment variable. */
package/dist/reducto.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { a as refuseLarger, n as documentPart } from "./document-CjMeBtV5.js";
2
+ import { a as refuseLarger, n as documentPart } from "./document-Clmi51Sf.js";
3
3
  import { t as FieldworkError } from "./errors-DROZyb9T.js";
4
- 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, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-BY3R0oWO.js";
5
- import { t as runJob } from "./job-DVsmQMKP.js";
4
+ 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, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-COHKvfH9.js";
5
+ import { i as startJob, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/reducto/response.ts
8
8
  /** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
@@ -117,27 +117,34 @@ const startParse = async (raw, document, o, call) => {
117
117
  ...call,
118
118
  form
119
119
  }));
120
- const started = z.parse(ParseStart, await raw.request("POST", "/parse_async", {
121
- creates: true,
120
+ return await startJob(raw, "/parse_async", {
122
121
  ...call,
123
122
  body: compact({
124
123
  input: requireJobId(provider, uploaded.file_id),
125
124
  settings: o.wordBoxes === true ? { return_citations: true } : void 0
126
125
  })
127
- }));
128
- return requireJobId(provider, started.job_id);
126
+ }, ParseStart, (reply) => reply.job_id);
127
+ };
128
+ const JOB_STATES = {
129
+ done: ["Completed"],
130
+ failed: ["Failed"],
131
+ running: ["Pending", "Idle"]
129
132
  };
130
133
  /** The result once the job has completed, undefined while it runs; throws `JobFailed` when Reducto reports a failure. */
131
- const finished = (found) => {
134
+ const finished = (id, found) => {
132
135
  const { error, reason, status } = found.value;
133
- if (status === "Failed") {
136
+ const state = jobState(provider, id, JOB_STATES, {
137
+ original: found.original,
138
+ value: status
139
+ });
140
+ if (state === "failed") {
134
141
  const why = reason ?? error.message;
135
142
  throw new FieldworkError("JobFailed", `reducto job failed${why === void 0 ? "" : `: ${why}`}`, {
136
143
  cause: found.original,
137
144
  provider
138
145
  });
139
146
  }
140
- return status === "Completed" ? found : void 0;
147
+ return state === "done" ? found : void 0;
141
148
  };
142
149
  /** The parse output, fetched from where Reducto put it when it was too large to return. */
143
150
  const outputOf = async (found, options) => {
@@ -163,7 +170,7 @@ const outputOf = async (found, options) => {
163
170
  const parse = async (raw, document, options, fetchImpl) => {
164
171
  const { call, rest: o } = callSettings(options);
165
172
  return await runJob(provider, {
166
- check: async (id, request) => finished(z.parse(JobResponse, await raw.request("GET", `/job/${segment(id)}`, request))),
173
+ check: async (id, request) => finished(id, z.parse(JobResponse, await raw.request("GET", `/job/${segment(id)}`, request))),
167
174
  finish: async (found, id) => {
168
175
  const { output, stored } = await outputOf(found, {
169
176
  fetch: fetchImpl,
@@ -1,4 +1,4 @@
1
- import { M as JsonSchema } from "./adapter-BhTK51Yj.js";
1
+ import { M as JsonSchema } from "./adapter-Bh8EIrNe.js";
2
2
  /** Vendor-specific parameters a schema library may accept. */
3
3
  type LibraryOptions = JsonSchema;
4
4
  /** The path segment interface of an issue. */
package/dist/serpapi.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-BhTK51Yj.js";
1
+ import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-Bh8EIrNe.js";
2
2
  import "./util-DhYr1OS3.js";
3
3
  /** Settings for `serpapi()`. */
4
4
  interface SerpApiConfig {
package/dist/serpapi.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { C as createRawClient, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings, z as refuseTogether } from "./parse-BY3R0oWO.js";
3
+ import { C as createRawClient, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings, z as refuseTogether } from "./parse-COHKvfH9.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/serpapi/parse.ts
6
6
  /** The name this adapter reports in errors and results. */
package/dist/tavily.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { K as Recency, Q as SiteMap, R as Page, Y as SearchResponse, _ as Crawl, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-BhTK51Yj.js";
2
- import { t as OutputSchema } from "./schema-CNd51xdD.js";
1
+ import { K as Recency, Q as SiteMap, R as Page, Y as SearchResponse, _ as Crawl, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-Bh8EIrNe.js";
2
+ import { t as OutputSchema } from "./schema-BWWiMvkg.js";
3
3
  /** Settings for the Tavily adapter. */
4
4
  interface TavilyConfig {
5
5
  /** Defaults to the TAVILY_API_KEY environment variable. */