@howells/fieldwork-sdk 0.4.0 → 0.5.1

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,11 +1,11 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.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";
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";
5
6
  import * as z from "zod/mini";
6
7
  // src/adapters/parallel/parse.ts
7
8
  const provider = "parallel";
8
- const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
9
9
  const nonEmpty = (value) => {
10
10
  const result = compact(value);
11
11
  return Object.keys(result).length > 0 ? result : void 0;
@@ -156,7 +156,6 @@ const discovery = (id, entry) => {
156
156
  const stoppedEarly = state !== "completed" || reason !== void 0 && !FINISHED.has(reason);
157
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
158
  cause: entry.original,
159
- jobId: id,
160
159
  provider
161
160
  });
162
161
  const stopReason = reason ?? state;
@@ -186,7 +185,7 @@ const sourcePolicy = (o) => {
186
185
  });
187
186
  };
188
187
  const fetchPolicy = (maxAge) => {
189
- if (maxAge !== void 0 && maxAge < 600) throw invalid(`parallel cannot use a cached copy younger than 600 seconds (maxAge was ${maxAge}); it has no setting that always fetches fresh`);
188
+ 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`);
190
189
  return maxAge === void 0 ? void 0 : { max_age_seconds: Math.ceil(maxAge) };
191
190
  };
192
191
  const jsonOutput = (schema) => ({
@@ -200,7 +199,7 @@ const decisionQuestion = (name, question) => {
200
199
  };
201
200
  if (question.type === "choice") {
202
201
  const choices = [...new Set(question.choices)];
203
- if (choices.length < 2 || choices.length > 255) throw invalid(`parallel decisions take 2 to 255 distinct choices; question "${name}" has ${choices.length}`);
202
+ if (choices.length < 2 || choices.length > 255) throw invalidRequest(provider, `decisions take 2 to 255 distinct choices; question "${name}" has ${choices.length}`);
204
203
  return {
205
204
  criteria: Object.fromEntries(choices.map((choice) => [choice, choice])),
206
205
  instructions: question.question,
@@ -209,14 +208,14 @@ const decisionQuestion = (name, question) => {
209
208
  }
210
209
  if (question.type === "score") {
211
210
  const levels = Object.values(question.scale);
212
- if (levels.length < 2 || levels.length > 10) throw invalid(`parallel decisions take a score scale of 2 to 10 levels; question "${name}" has ${levels.length}`);
211
+ if (levels.length < 2 || levels.length > 10) throw invalidRequest(provider, `decisions take a score scale of 2 to 10 levels; question "${name}" has ${levels.length}`);
213
212
  return {
214
213
  criteria: levels,
215
214
  instructions: question.question,
216
215
  type: "score"
217
216
  };
218
217
  }
219
- throw invalid(`parallel does not know the question type "${String(question.type)}" for "${name}"`);
218
+ throw invalidRequest(provider, `does not know the question type "${String(question.type)}" for "${name}"`);
220
219
  };
221
220
  const NAMED_FREQUENCY = {
222
221
  day: "1d",
@@ -224,13 +223,13 @@ const NAMED_FREQUENCY = {
224
223
  week: "1w"
225
224
  };
226
225
  const frequency = (schedule) => {
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: ... }");
226
+ 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: ... }");
228
227
  const named = Object.entries(NAMED_FREQUENCY).find(([name]) => name === schedule.every)?.[1];
229
228
  if (named) return named;
230
229
  const match = /^(?<count>\d+)(?<unit>[hd])$/u.exec(schedule.every);
231
230
  const count = Number(match?.groups?.count);
232
231
  const limit = match?.groups?.unit === "h" ? 720 : 30;
233
- if (!match || count < 1 || count > limit) throw invalid(`parallel monitors run every 1 hour to 30 days; "${schedule.every}" is outside that`);
232
+ if (!match || count < 1 || count > limit) throw invalidRequest(provider, `monitors run every 1 hour to 30 days; "${schedule.every}" is outside that`);
234
233
  return schedule.every;
235
234
  };
236
235
  const extractBody = (urls, o) => compact({
@@ -443,39 +442,36 @@ const stoppedRun = (id, entry) => {
443
442
  if (warnings.length > 0) message += ` (${warnings.join("; ")})`;
444
443
  return new FieldworkError("JobFailed", message, {
445
444
  cause: entry.original,
446
- jobId: id,
447
445
  provider
448
446
  });
449
447
  };
450
- const taskResult = async (raw, id, signal) => {
448
+ const taskResult = async (raw, id, request) => {
451
449
  try {
452
- return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${id}/result`, { signal }));
450
+ return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${segment(id)}/result`, request));
453
451
  } catch (error) {
454
452
  if (error instanceof FieldworkError && error.code === "NotFound") {
455
- const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${id}`, { signal }));
453
+ const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
456
454
  if (run.value.status === "failed" || run.value.status === "cancelled") throw stoppedRun(id, run);
457
455
  }
458
456
  throw error;
459
457
  }
460
458
  };
461
- const runTask = async (raw, body, settings) => {
462
- const { resume, ...wait } = settings;
463
- const id = resume ?? requireJobId(raw.provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
459
+ /** Runs a task to its result, or waits for the run named by `resume`. */
460
+ const runTask = async (raw, body, settings, finish) => await runJob(provider, {
461
+ check: async (id, request) => {
462
+ 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;
466
+ },
467
+ finish,
468
+ start: async () => requireJobId(provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
464
469
  body,
465
470
  creates: true,
466
- signal: wait.signal,
467
- timeout: wait.timeout
468
- })).run_id);
469
- return {
470
- id,
471
- result: await poll(raw.provider, id, async () => {
472
- const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${id}`, { signal: wait.signal }));
473
- const { status } = run.value;
474
- if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
475
- return status === "completed" ? await taskResult(raw, id, wait.signal) : void 0;
476
- }, wait)
477
- };
478
- };
471
+ retries: settings.retries,
472
+ signal: settings.signal
473
+ })).run_id)
474
+ }, settings);
479
475
  const startFindAll = async (raw, objective, o, call) => {
480
476
  const created = z.parse(FindAllStart, await raw.request("POST", "/v1beta/findall/runs", {
481
477
  creates: true,
@@ -495,13 +491,13 @@ const startFindAll = async (raw, objective, o, call) => {
495
491
  }));
496
492
  const id = requireJobId(provider, created.findall_id);
497
493
  if (o.schema) try {
498
- await raw.request("POST", `/v1beta/findall/runs/${id}/enrich`, {
494
+ await raw.request("POST", `/v1beta/findall/runs/${segment(id)}/enrich`, {
495
+ ...call,
499
496
  body: compact({
500
497
  output_schema: jsonOutput(o.schema),
501
498
  processor: o.processor
502
499
  }),
503
- creates: true,
504
- signal: call.signal
500
+ creates: true
505
501
  });
506
502
  } catch (error) {
507
503
  throw withJob(error, id);
@@ -509,17 +505,21 @@ const startFindAll = async (raw, objective, o, call) => {
509
505
  return id;
510
506
  };
511
507
  /** The result of a FindAll run once it has stopped, or undefined while it runs. */
512
- const findAllResult = async (raw, id, signal) => {
513
- const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${id}`, { signal }));
508
+ const findAllResult = async (raw, id, request) => {
509
+ const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
514
510
  const { status } = run.value.status;
515
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`, {
516
512
  cause: run.original,
517
- jobId: id,
518
513
  provider
519
514
  });
520
- return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${id}/result`, { signal })) : void 0;
515
+ return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
521
516
  };
522
517
  // src/adapters/parallel.ts
518
+ /**
519
+ * An adapter for Parallel: search, images, read, readMany, extract, answer, research, discover, decide and monitor. Pass it to `new Fieldwork({ adapter })`.
520
+ *
521
+ * Throws `Unauthorized` when neither `apiKey` nor `PARALLEL_API_KEY` is set.
522
+ */
523
523
  const parallel = (config = {}) => {
524
524
  const raw = createRawClient({
525
525
  baseUrl: config.baseUrl ?? "https://api.parallel.ai",
@@ -593,9 +593,9 @@ const parallel = (config = {}) => {
593
593
  const { call, rest: o } = callSettings(options);
594
594
  const entries = Object.entries(questions);
595
595
  const names = entries.map(([name]) => name);
596
- if (names.length < 1 || names.length > 100) throw invalid(`parallel decisions take 1 to 100 questions; got ${names.length}`);
596
+ if (names.length < 1 || names.length > 100) throw invalidRequest(provider, `decisions take 1 to 100 questions; got ${names.length}`);
597
597
  const badName = names.find((name) => !QUESTION_NAME.test(name));
598
- if (badName !== void 0) throw invalid(`parallel question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
598
+ if (badName !== void 0) throw invalidRequest(provider, `question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
599
599
  const response = await raw.request("POST", "/v1/decisions", {
600
600
  ...call,
601
601
  body: compact({
@@ -625,31 +625,30 @@ const parallel = (config = {}) => {
625
625
  },
626
626
  async discover(objective, options) {
627
627
  const { call, rest: o } = callSettings(options);
628
- const id = o.resume ?? await startFindAll(raw, objective, o, call);
629
- const result = await poll(provider, id, async () => await findAllResult(raw, id, call.signal), {
628
+ return await runJob(provider, {
629
+ check: async (id, request) => await findAllResult(raw, id, request),
630
+ finish: async (result, id) => {
631
+ const found = discovery(id, result);
632
+ const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => data === void 0 ? entity : {
633
+ ...entity,
634
+ data: await checkOutput(o.schema, data, { provider })
635
+ }));
636
+ return {
637
+ ...found,
638
+ entities
639
+ };
640
+ },
641
+ start: async () => await startFindAll(raw, objective, o, call)
642
+ }, {
630
643
  ...call,
631
- interval: o.interval
644
+ interval: o.interval,
645
+ resume: o.resume
632
646
  });
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
- };
648
647
  },
649
648
  async extract(url, options) {
650
649
  const { call, rest: o } = callSettings(options);
651
650
  const target = new URL(url);
652
- const { id, result } = await runTask(raw, compact({
651
+ return await runTask(raw, compact({
653
652
  advanced_settings: nonEmpty({ location: o.country }),
654
653
  input: {
655
654
  instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
@@ -663,16 +662,14 @@ const parallel = (config = {}) => {
663
662
  ...call,
664
663
  interval: o.interval,
665
664
  resume: o.resume
666
- });
667
- const { output } = result.value;
668
- return compact({
669
- data: await checkOutput(o.schema, output.content, {
670
- jobId: id,
671
- provider
672
- }),
673
- fields: basis(output.basis),
674
- meta: taskMeta(result),
675
- raw: result.original
665
+ }, async (result) => {
666
+ const { output } = result.value;
667
+ return compact({
668
+ data: await checkOutput(o.schema, output.content, { provider }),
669
+ fields: basis(output.basis),
670
+ meta: taskMeta(result),
671
+ raw: result.original
672
+ });
676
673
  });
677
674
  },
678
675
  async images(query, options) {
@@ -710,8 +707,8 @@ const parallel = (config = {}) => {
710
707
  monitor: {
711
708
  async create(options) {
712
709
  const { call, rest: o } = callSettings(options);
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");
714
- if (o.taskRunId === void 0 && o.query === void 0) throw invalid("a parallel monitor needs a query or a taskRunId");
710
+ if (Object.entries(o).some(([name, value]) => name === "urls" && value !== void 0)) throw invalidRequest(provider, "monitors search the web for a query and cannot watch a list of URLs; restrict a query with includeDomains, which accepts domain/path prefixes");
711
+ if (o.taskRunId === void 0 && o.query === void 0) throw invalidRequest(provider, "a parallel monitor needs a query or a taskRunId");
715
712
  if (o.taskRunId !== void 0) for (const name of [
716
713
  "query",
717
714
  "schema",
@@ -721,7 +718,7 @@ const parallel = (config = {}) => {
721
718
  "excludeDomains",
722
719
  "publishedAfter"
723
720
  ]) refuseTogether(provider, o, "taskRunId", name);
724
- if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalid("webhookEvents needs a webhookUrl");
721
+ if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalidRequest(provider, "webhookEvents needs a webhookUrl");
725
722
  const response = await raw.request("POST", "/v1/monitors", {
726
723
  creates: true,
727
724
  ...call,
@@ -748,11 +745,11 @@ const parallel = (config = {}) => {
748
745
  return monitorInfo(z.parse(MonitorEntry, response));
749
746
  },
750
747
  async delete(id, options) {
751
- await raw.request("POST", `/v1/monitors/${encodeURIComponent(id)}/cancel`, options);
748
+ await raw.request("POST", `/v1/monitors/${segment(id)}/cancel`, options);
752
749
  },
753
750
  async events(id, options) {
754
751
  const { call, rest: o } = callSettings(options);
755
- const response = await raw.request("GET", `/v1/monitors/${encodeURIComponent(id)}/events`, {
752
+ const response = await raw.request("GET", `/v1/monitors/${segment(id)}/events`, {
756
753
  ...call,
757
754
  query: {
758
755
  cursor: o.cursor,
@@ -769,14 +766,16 @@ const parallel = (config = {}) => {
769
766
  });
770
767
  },
771
768
  async get(id, options) {
772
- return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${encodeURIComponent(id)}`, options)));
769
+ return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${segment(id)}`, options)));
773
770
  },
774
771
  async list(options) {
772
+ const { call } = callSettings(options);
775
773
  const monitors = [];
774
+ const seen = /* @__PURE__ */ new Set();
776
775
  let cursor;
777
- do {
776
+ for (;;) {
778
777
  const page = z.parse(MonitorsPage, await raw.request("GET", "/v1/monitors", {
779
- ...options,
778
+ ...call,
780
779
  query: {
781
780
  cursor,
782
781
  limit: 100
@@ -784,8 +783,9 @@ const parallel = (config = {}) => {
784
783
  }));
785
784
  monitors.push(...page.monitors.map((entry) => monitorInfo(entry)));
786
785
  cursor = page.next_cursor;
787
- } while (cursor !== void 0);
788
- return monitors;
786
+ if (cursor === void 0 || seen.has(cursor)) return monitors;
787
+ seen.add(cursor);
788
+ }
789
789
  }
790
790
  },
791
791
  async read(url, options) {
@@ -810,7 +810,7 @@ const parallel = (config = {}) => {
810
810
  },
811
811
  async readMany(urls, options) {
812
812
  const { call, rest: o } = callSettings(options);
813
- if (urls.length > 20) throw invalid(`parallel reads up to 20 URLs in one call; got ${urls.length}`);
813
+ if (urls.length > 20) throw invalidRequest(provider, `reads up to 20 URLs in one call; got ${urls.length}`);
814
814
  const response = await raw.request("POST", "/v1/extract", {
815
815
  ...call,
816
816
  body: extractBody(urls, o)
@@ -829,7 +829,7 @@ const parallel = (config = {}) => {
829
829
  },
830
830
  async research(question, options) {
831
831
  const { call, rest: o } = callSettings(options);
832
- const { id, result } = await runTask(raw, compact({
832
+ return await runTask(raw, compact({
833
833
  advanced_settings: nonEmpty({ location: o.country }),
834
834
  input: question,
835
835
  metadata: o.metadata,
@@ -841,21 +841,19 @@ const parallel = (config = {}) => {
841
841
  ...call,
842
842
  interval: o.interval,
843
843
  resume: o.resume
844
- });
845
- const { output, run } = result.value;
846
- const fields = basis(output.basis);
847
- return compact({
848
- continuationId: run.interaction_id,
849
- fields,
850
- id,
851
- meta: taskMeta(result),
852
- output: await checkOutput(o.schema, output.content, {
853
- jobId: id,
854
- provider
855
- }),
856
- raw: result.original,
857
- sources: citedBy(fields),
858
- status: "completed"
844
+ }, async (result, id) => {
845
+ const { output, run } = result.value;
846
+ const fields = basis(output.basis);
847
+ return compact({
848
+ continuationId: run.interaction_id,
849
+ fields,
850
+ id,
851
+ meta: taskMeta(result),
852
+ output: await checkOutput(o.schema, output.content, { provider }),
853
+ raw: result.original,
854
+ sources: citedBy(fields),
855
+ status: "completed"
856
+ });
859
857
  });
860
858
  },
861
859
  async search(query, options) {
@@ -1,15 +1,26 @@
1
- import { n as codeForStatus, r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
1
+ import { n as codeForStatus, t as FieldworkError } from "./errors-Yvk42oZH.js";
2
2
  import * as z from "zod/mini";
3
3
  // src/util.ts
4
4
  const isJson = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
5
  const record = (value) => isJson(value) ? value : {};
6
6
  const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
7
- const callSettings = (options) => {
7
+ /**
8
+ * Splits an operation's options into the provider's own and the call's
9
+ * settings. The call's `signal` also carries its `timeout` as a deadline, set
10
+ * now, so every request the operation makes (a start, each poll, a result
11
+ * download) shares one budget instead of restarting it. An empty `resume`
12
+ * names no job, so it is refused here, once for every adapter.
13
+ *
14
+ * `grace` extends the deadline past `timeout` for an operation that sends the
15
+ * timeout to the provider and needs a moment more to hear its report.
16
+ */
17
+ const callSettings = (options, grace = 0) => {
8
18
  const { retries, signal, timeout, ...rest } = options ?? {};
19
+ 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");
9
20
  return {
10
21
  call: {
11
22
  retries,
12
- signal,
23
+ signal: timeout === void 0 ? signal : AbortSignal.any([...signal === void 0 ? [] : [signal], AbortSignal.timeout(timeout + grace)]),
13
24
  timeout
14
25
  },
15
26
  rest
@@ -107,7 +118,7 @@ const FIRST_RETRY_WAIT = 500;
107
118
  * timed out, the failure would recur, or the request created something.
108
119
  */
109
120
  const retryDelay = (error, state) => {
110
- if (state.count >= state.retries || state.signal?.aborted === true || !error.retryable || error.code === "Timeout" || state.creates && error.code !== "RateLimited") return;
121
+ if (state.count >= state.retries || state.signal?.aborted === true || !error.retryable || error.code === "Timeout" && error.status === void 0 || state.creates && error.code !== "RateLimited") return;
111
122
  if (error.retryAfter !== void 0) {
112
123
  const asked = error.retryAfter * 1e3;
113
124
  return asked > MAX_RETRY_WAIT ? void 0 : asked;
@@ -115,6 +126,37 @@ const retryDelay = (error, state) => {
115
126
  const ceiling = Math.min(MAX_RETRY_WAIT, FIRST_RETRY_WAIT * 2 ** state.count);
116
127
  return ceiling / 2 + Math.random() * (ceiling / 2);
117
128
  };
129
+ /** Whether a stopped signal's deadline ran out, rather than its caller cancelling. */
130
+ const timedOut = (signal) => signal.reason instanceof DOMException && signal.reason.name === "TimeoutError";
131
+ /**
132
+ * The error for a call its signal stopped: `Timeout` when the signal's
133
+ * deadline ran out (a call's `timeout` is a deadline signal across all its
134
+ * requests), `Aborted` when the caller cancelled.
135
+ */
136
+ const stopped = (signal, message, options) => new FieldworkError(timedOut(signal) ? "Timeout" : "Aborted", message, options);
137
+ const transportError = (provider, error, signal) => {
138
+ if (signal?.aborted === true) return stopped(signal, `${provider} request stopped: ${timedOut(signal) ? "timed out" : "cancelled"}`, {
139
+ cause: error,
140
+ provider
141
+ });
142
+ if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
143
+ cause: error,
144
+ provider
145
+ });
146
+ return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
147
+ cause: error,
148
+ provider,
149
+ retryable: true
150
+ });
151
+ };
152
+ /** A response's body; a connection lost while it streams is a transport error like any other. */
153
+ const readText = async (provider, response, signal) => {
154
+ try {
155
+ return await response.text();
156
+ } catch (error) {
157
+ throw transportError(provider, error, signal);
158
+ }
159
+ };
118
160
  const createRawClient = (config) => {
119
161
  const doFetch = config.fetch ?? globalThis.fetch;
120
162
  return {
@@ -153,9 +195,17 @@ const createRawClient = (config) => {
153
195
  method,
154
196
  url
155
197
  });
156
- const text = await response.text();
157
- const parsed = parseBody(text);
158
- if (response.ok) return parsed;
198
+ const text = await readText(config.provider, response, signal);
199
+ const json = jsonOf(text);
200
+ const parsed = json === void 0 ? text : json.value;
201
+ if (response.ok) {
202
+ if (options.text !== true && json === void 0) throw new FieldworkError("ProviderError", `${config.provider} ${method} ${path} returned ${response.status} with a body that is not JSON: ${text.slice(0, 300)}`, {
203
+ cause: text,
204
+ provider: config.provider,
205
+ status: response.status
206
+ });
207
+ return options.text === true ? text : parsed;
208
+ }
159
209
  throw new FieldworkError(codeForStatus(response.status), `${config.provider} ${method} ${path} returned ${response.status}: ${describe(parsed, text)}`, {
160
210
  cause: parsed,
161
211
  provider: config.provider,
@@ -178,7 +228,7 @@ const createRawClient = (config) => {
178
228
  });
179
229
  if (wait === void 0 || deadline !== void 0 && Date.now() + wait >= deadline) throw error;
180
230
  await sleep(wait, signal);
181
- if (options.signal?.aborted === true) throw new FieldworkError("Aborted", `${config.provider} request was cancelled while waiting to retry`, {
231
+ if (options.signal?.aborted === true) throw stopped(options.signal, `${config.provider} request stopped while waiting to retry`, {
182
232
  cause: error,
183
233
  provider: config.provider
184
234
  });
@@ -229,27 +279,13 @@ const combineSignals = (signal, timeout) => {
229
279
  const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((value) => value !== void 0);
230
280
  return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
231
281
  };
232
- const transportError = (provider, error, signal) => {
233
- if (signal?.aborted === true) return new FieldworkError("Aborted", `${provider} request was cancelled`, {
234
- cause: error,
235
- provider
236
- });
237
- if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
238
- cause: error,
239
- provider
240
- });
241
- return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
242
- cause: error,
243
- provider,
244
- retryable: true
245
- });
246
- };
247
- const parseBody = (text) => {
248
- if (text === "") return;
282
+ /** The body's JSON, or undefined when the body is not JSON. An empty body is JSON with no value. */
283
+ const jsonOf = (text) => {
284
+ if (text === "") return { value: void 0 };
249
285
  try {
250
- return JSON.parse(text);
286
+ return { value: JSON.parse(text) };
251
287
  } catch {
252
- return text;
288
+ return;
253
289
  }
254
290
  };
255
291
  const describe = (parsed, text) => {
@@ -272,33 +308,34 @@ const retryAfterSeconds = (header, now = Date.now()) => {
272
308
  const date = Date.parse(header);
273
309
  return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
274
310
  };
275
- const poll = async (provider, jobId, check, options = {}) => {
276
- const interval = options.interval ?? 2e3;
277
- const deadline = Date.now() + (options.timeout ?? 6e5);
278
- for (;;) {
279
- if (options.signal?.aborted === true) throw new FieldworkError("Aborted", `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
280
- jobId,
281
- provider
282
- });
283
- let value;
284
- try {
285
- value = await check();
286
- } catch (error) {
287
- throw withJob(error, jobId);
288
- }
289
- if (value !== void 0) return value;
290
- if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
291
- jobId,
292
- provider
293
- });
294
- await sleep(interval, options.signal);
295
- }
296
- };
311
+ /** An id as one path segment, so a caller's `resume` cannot reach another endpoint. */
312
+ const segment = (id) => encodeURIComponent(id);
297
313
  const requireKey = (provider, given, envName) => {
298
314
  const key = given ?? process.env[envName];
299
315
  if (key === void 0 || key === "") throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
300
316
  return key;
301
317
  };
318
+ /**
319
+ * Fetches a presigned URL a provider returned, such as a large result on
320
+ * storage, and returns its body as text. Nothing of the provider's client is
321
+ * sent with it: the URL carries its own authorization, and the key must not
322
+ * reach another host.
323
+ */
324
+ const readSigned = async (provider, url, options) => {
325
+ const doFetch = options.fetch ?? globalThis.fetch;
326
+ let response;
327
+ try {
328
+ response = await doFetch(url, { signal: options.signal });
329
+ } catch (error) {
330
+ throw transportError(provider, error, options.signal);
331
+ }
332
+ const text = await readText(provider, response, options.signal);
333
+ if (!response.ok) throw new FieldworkError(codeForStatus(response.status), `${provider} result at ${new URL(url).origin} returned ${response.status}: ${text.slice(0, 300)}`, {
334
+ provider,
335
+ status: response.status
336
+ });
337
+ return text;
338
+ };
302
339
  // src/parse.ts
303
340
  /**
304
341
  * Building blocks for the schemas that parse a provider's response at the
@@ -438,4 +475,4 @@ const optionalArrayOf = (item) => z.optional(z.union([z.pipe(z.array(z.unknown()
438
475
  const parsed = z.safeParse(item, entry);
439
476
  return parsed.success ? [parsed.data] : [];
440
477
  }))), absent]));
441
- export { hours as A, createRawClient as C, citationOf as D, callSettings as E, record as F, refuseTogether as I, requireJobId as L, parseJson as M, presentPage as N, citationsOf as O, presentPages as P, uniqueCitations as R, withOriginal as S, requireKey as T, optionalStructure as _, looseObject as a, warningEntry as b, optionalArrayOf as c, optionalId as d, optionalNumber as f, optionalStringOrNumber as g, optionalString as h, both as i, meta as j, compact as k, optionalBoolean as l, optionalScalar as m, anything as n, nonEmptyString as o, optionalObject as p, arrayOf as r, optionalAnyString as s, Source as t, optionalFirstString as u, recordOf as v, poll as w, warnings as x, sourceShape as y };
478
+ export { citationOf as A, requireJobId as B, createRawClient as C, sleep as D, segment as E, parseJson as F, presentPage as I, presentPages as L, compact as M, hours as N, stopped as O, meta as P, record as R, withOriginal as S, requireKey as T, uniqueCitations as V, optionalStructure as _, looseObject as a, warningEntry as b, optionalArrayOf as c, optionalId as d, optionalNumber as f, optionalStringOrNumber as g, optionalString as h, both as i, citationsOf as j, callSettings as k, optionalBoolean as l, optionalScalar as m, anything as n, nonEmptyString as o, optionalObject as p, arrayOf as r, optionalAnyString as s, Source as t, optionalFirstString as u, recordOf as v, readSigned as w, warnings as x, sourceShape as y, refuseTogether as z };
@@ -1,6 +1,6 @@
1
- import { G as Research, W as Recency, a as RawClient, f as CallOptions, l as Answer, q as SearchResponse, t as Adapter, v as DecisionQuestion, y as Decisions } from "./adapter-CDY8qczv.js";
2
- import { t as OutputSchema } from "./schema-EZlBkY5B.js";
3
- export interface PerplexityConfig {
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-BgdfLBs-.js";
2
+ import { t as OutputSchema } from "./schema-Cupy7-7q.js";
3
+ interface PerplexityConfig {
4
4
  /** Defaults to the PERPLEXITY_API_KEY environment variable. */
5
5
  apiKey?: string;
6
6
  baseUrl?: string;
@@ -24,7 +24,7 @@ interface PerplexityFilters {
24
24
  lastUpdatedBefore?: string;
25
25
  recency?: Recency;
26
26
  }
27
- export interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
27
+ interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
28
28
  /** Results to return: up to 20, or up to 50 with `searchType: "people"`. */
29
29
  limit?: number;
30
30
  /**
@@ -45,7 +45,7 @@ export interface PerplexitySearchOptions extends CallOptions, PerplexityFilters
45
45
  }
46
46
  /** An effort level, or a name pinned to a version such as `fast@2026-10-16.0`. */
47
47
  type Pinned<Name extends string> = Name | `${Name}@${string}`;
48
- export interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
48
+ interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
49
49
  /** Defaults to "fast". Answers are synchronous, so only the quicker levels are offered. */
50
50
  effort?: Pinned<"fast" | "low" | "medium">;
51
51
  instructions?: string;
@@ -58,8 +58,8 @@ export interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
58
58
  * Perplexity's effort levels. The names change slowly, so the type is open:
59
59
  * `ultra-preview` and version pins (`high@2026-10-28.0`) are accepted too.
60
60
  */
61
- export type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
62
- export interface PerplexityResearchOptions<T = unknown> extends CallOptions, PerplexityFilters {
61
+ type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
62
+ interface PerplexityResearchOptions<T = unknown> extends CallOptions, PerplexityFilters {
63
63
  schema?: OutputSchema<T>;
64
64
  /**
65
65
  * The configuration to run: a model, tools, system prompt and step budget in
@@ -90,16 +90,21 @@ export interface PerplexityResearchOptions<T = unknown> extends CallOptions, Per
90
90
  /** Milliseconds between checks. Defaults to 2000. */
91
91
  interval?: number;
92
92
  }
93
- export type PerplexityDeciderModel = "pplx-decider-v1.2" | "pplx-decider-flash-v1.2" | "pplx-decider-latest" | "pplx-decider-flash-latest" | (string & {});
94
- export interface PerplexityDecideOptions extends CallOptions {
93
+ type PerplexityDeciderModel = "pplx-decider-v1.2" | "pplx-decider-flash-v1.2" | "pplx-decider-latest" | "pplx-decider-flash-latest" | (string & {});
94
+ interface PerplexityDecideOptions extends CallOptions {
95
95
  /** Defaults to "pplx-decider-latest". The flash models are smaller and cheaper. */
96
96
  model?: PerplexityDeciderModel;
97
97
  }
98
- export interface PerplexityOperations {
98
+ interface PerplexityOperations {
99
99
  search: (query: string, options?: PerplexitySearchOptions) => Promise<SearchResponse>;
100
100
  answer: <T = unknown>(question: string, options?: PerplexityAnswerOptions<T>) => Promise<Answer<T>>;
101
101
  research: <T = unknown>(question: string, options?: PerplexityResearchOptions<T>) => Promise<Research<T>>;
102
102
  decide: (context: unknown, questions: Record<string, DecisionQuestion>, options?: PerplexityDecideOptions) => Promise<Decisions>;
103
103
  }
104
+ /**
105
+ * An adapter for Perplexity: search, answer, research and decide. Pass it to `new Fieldwork({ adapter })`.
106
+ *
107
+ * Throws `Unauthorized` when neither `apiKey` nor `PERPLEXITY_API_KEY` is set.
108
+ */
104
109
  export declare const perplexity: (config?: PerplexityConfig) => Adapter<"perplexity", PerplexityOperations, RawClient>;
105
- export {};
110
+ export type { PerplexityAnswerOptions, PerplexityConfig, PerplexityDecideOptions, PerplexityDeciderModel, PerplexityEffort, PerplexityOperations, PerplexityResearchOptions, PerplexitySearchOptions };