@howells/fieldwork-sdk 0.11.0 → 0.12.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.
Files changed (47) hide show
  1. package/README.md +72 -15
  2. package/dist/{adapter-DWYJys20.js → adapter-CBSAfErv.js} +1 -1
  3. package/dist/adapter-J2yatZJ0.d.ts +73 -0
  4. package/dist/best-CO9liYDa.js +1436 -0
  5. package/dist/brave.d.ts +7 -6
  6. package/dist/brave.js +180 -173
  7. package/dist/browserbase.d.ts +4 -3
  8. package/dist/browserbase.js +185 -170
  9. package/dist/{document-DMIUCoDA.js → document-BSCwJgBM.js} +4 -4
  10. package/dist/{download-CP8noBdX.js → download-kuTqNnuZ.js} +1 -1
  11. package/dist/{adapter-B8kAAAgF.d.ts → errors-gMtejKHc.d.ts} +87 -69
  12. package/dist/exa.d.ts +18 -11
  13. package/dist/exa.js +306 -275
  14. package/dist/fieldwork-D7npPoUf.d.ts +35 -0
  15. package/dist/firecrawl.d.ts +4 -3
  16. package/dist/firecrawl.js +450 -417
  17. package/dist/{parse-Q7H4mrnO.js → http-CJcvTPnE.js} +223 -225
  18. package/dist/image.d.ts +253 -0
  19. package/dist/image.js +1 -0
  20. package/dist/index.d.ts +6 -7
  21. package/dist/index.js +66 -82
  22. package/dist/{job-DnavRq_s.js → job-JLEpszjr.js} +9 -9
  23. package/dist/kernel.d.ts +20 -2
  24. package/dist/kernel.js +65 -19
  25. package/dist/llamaparse.d.ts +3 -2
  26. package/dist/llamaparse.js +16 -16
  27. package/dist/parallel.d.ts +8 -8
  28. package/dist/parallel.js +423 -389
  29. package/dist/path-DO2llIdp.js +10 -0
  30. package/dist/perplexity.d.ts +6 -5
  31. package/dist/perplexity.js +21 -21
  32. package/dist/reducto.d.ts +3 -2
  33. package/dist/reducto.js +14 -14
  34. package/dist/{schema-CAPSX7yQ.d.ts → schema-C9xzRkKJ.d.ts} +17 -6
  35. package/dist/{schema--iU4AXSM.js → schema-CJXFAZ-x.js} +12 -3
  36. package/dist/serpapi.d.ts +3 -3
  37. package/dist/serpapi.js +176 -171
  38. package/dist/tavily.d.ts +4 -3
  39. package/dist/tavily.js +247 -234
  40. package/dist/tools.d.ts +76 -15
  41. package/dist/tools.js +351 -33
  42. package/dist/{util-DFUXQX6v.js → util-LvME_uOj.js} +35 -11
  43. package/package.json +6 -1
  44. package/dist/fieldwork-BrfoehvG.d.ts +0 -113
  45. package/dist/path-DL5P8XH2.js +0 -17
  46. package/dist/util-DhYr1OS3.d.ts +0 -1
  47. package/dist/{errors-DkFJysIM.js → errors-gpxg6Tnh.js} +5 -5
package/dist/parallel.js CHANGED
@@ -1,10 +1,10 @@
1
- import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
- import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, v as recordOf, x as warnings, y as sourceShape } from "./parse-Q7H4mrnO.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
- import { a as compact, c as parseJson, f as refuseTogether, i as citationsOf, m as uniqueCitations, p as requireJobId, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
- import * as z from "zod/mini";
1
+ import { t as defineAdapter } from "./adapter-CBSAfErv.js";
2
+ import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-gpxg6Tnh.js";
3
+ import { C as optionalStructure, D as warnings, O as withOriginal, T as sourceShape, _ as optionalId, b as optionalScalar, c as anything, d as looseObject, i as segment, l as arrayOf, p as optionalAnyString, r as requireKey, s as Source, t as createRawClient, u as both, v as optionalNumber, w as recordOf, x as optionalString } from "./http-CJcvTPnE.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-JLEpszjr.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-CJXFAZ-x.js";
6
+ import { a as compact, c as parseJson, d as refuseTogether, f as requireJobId, i as citationsOf, p as uniqueCitations, s as meta, t as callSettings } from "./util-LvME_uOj.js";
7
+ import * as z$1 from "zod/mini";
8
8
  // src/adapters/parallel/parse.ts
9
9
  /** The name this adapter reports in errors and results. */
10
10
  const provider = "parallel";
@@ -262,6 +262,8 @@ const jsonOutput = (schema) => ({
262
262
  json_schema: jsonSchemaOf(schema),
263
263
  type: "json"
264
264
  });
265
+ /** A question of a type the checks do not know: only its `type`, as it arrived. */
266
+ const UntypedQuestion = looseObject({ type: anything });
265
267
  /**
266
268
  * Parallel's form of a normalized decision question: `yesno` is `noul`, `choice`
267
269
  * keeps its type and `score` takes the scale's labels, in order, as criteria.
@@ -290,7 +292,8 @@ const decisionQuestion = (name, question) => {
290
292
  type: "score"
291
293
  };
292
294
  }
293
- throw invalidRequest(provider, `does not know the question type "${String(question.type)}" for "${name}"`);
295
+ const { type } = z$1.parse(UntypedQuestion, question);
296
+ throw invalidRequest(provider, `does not know the question type ${JSON.stringify(type)} for "${name}"`);
294
297
  };
295
298
  /** Parallel's short form of each named schedule. */
296
299
  const NAMED_FREQUENCY = {
@@ -342,14 +345,14 @@ const Usage = arrayOf(looseObject({
342
345
  name: optionalString
343
346
  }));
344
347
  /** A string, an object or an array as it arrived, told apart. */
345
- const Content = z.pipe(both(optionalAnyString, optionalStructure), z.transform(({ first, second }) => ({
348
+ const Content = z$1.pipe(both(optionalAnyString, optionalStructure), z$1.transform(({ first, second }) => ({
346
349
  structure: second,
347
350
  text: first
348
351
  })));
349
352
  /** `/v1/search`. */
350
353
  const SearchResponse = looseObject({
351
354
  results: arrayOf(looseObject({
352
- excerpts: arrayOf(z.string()),
355
+ excerpts: arrayOf(z$1.string()),
353
356
  publish_date: optionalString,
354
357
  title: optionalString,
355
358
  url: optionalString
@@ -373,7 +376,7 @@ const ImagesResponse = looseObject({
373
376
  });
374
377
  /** One URL's result in an Extract response. */
375
378
  const ExtractResult = looseObject({
376
- excerpts: arrayOf(z.string()),
379
+ excerpts: arrayOf(z$1.string()),
377
380
  full_content: optionalString,
378
381
  publish_date: optionalString,
379
382
  title: optionalString,
@@ -390,7 +393,7 @@ const ExtractResponse = looseObject({
390
393
  http_status_code: optionalNumber,
391
394
  url: optionalString
392
395
  })),
393
- extract_id: z.pipe(both(optionalString, optionalScalar), z.transform(({ first, second }) => ({
396
+ extract_id: z$1.pipe(both(optionalString, optionalScalar), z$1.transform(({ first, second }) => ({
394
397
  id: second,
395
398
  text: first
396
399
  }))),
@@ -401,7 +404,7 @@ const ExtractResponse = looseObject({
401
404
  /** `/v1/responses`: the ids are read as text (a continuation id) and as a request id. */
402
405
  const AnswerResponse = looseObject({
403
406
  error: looseObject({ message: optionalString }),
404
- id: z.pipe(both(optionalString, optionalScalar), z.transform(({ first, second }) => ({
407
+ id: z$1.pipe(both(optionalString, optionalScalar), z$1.transform(({ first, second }) => ({
405
408
  request: second,
406
409
  text: first
407
410
  }))),
@@ -577,10 +580,10 @@ const stoppedRun = (id, entry) => {
577
580
  */
578
581
  const taskResult = async (raw, id, request) => {
579
582
  try {
580
- return z.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${segment(id)}/result`, request));
583
+ return z$1.parse(TaskResult, await raw.request("GET", `/v1/tasks/runs/${segment(id)}/result`, request));
581
584
  } catch (error) {
582
585
  if (error instanceof FieldworkError && error.code === "NotFound") {
583
- const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
586
+ const run = z$1.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
584
587
  if (run.value.status === "failed" || run.value.status === "cancelled") throw stoppedRun(id, run);
585
588
  }
586
589
  throw error;
@@ -594,7 +597,7 @@ const taskResult = async (raw, id, request) => {
594
597
  */
595
598
  const runTask = async (raw, body, settings, finish) => await runJob(provider, {
596
599
  check: async (id, request) => {
597
- const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
600
+ const run = z$1.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
598
601
  const state = jobState(provider, id, TASK_STATES, {
599
602
  original: run.original,
600
603
  value: run.value.status
@@ -656,7 +659,7 @@ const startFindAll = async (raw, objective, o, call) => {
656
659
  * and a status Parallel does not document throws `ProviderError`.
657
660
  */
658
661
  const findAllResult = async (raw, id, request) => {
659
- const run = z.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
662
+ const run = z$1.parse(FindAllRun, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}`, request));
660
663
  const state = jobState(provider, id, FINDALL_STATES, {
661
664
  original: run.original,
662
665
  value: run.value.status.status
@@ -665,11 +668,403 @@ const findAllResult = async (raw, id, request) => {
665
668
  cause: run.original,
666
669
  provider
667
670
  });
668
- return state === "done" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
671
+ return state === "done" ? z$1.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
669
672
  };
673
+ // src/adapters/parallel/monitor.ts
674
+ /** Refuses a monitor Parallel cannot run, before anything is sent. */
675
+ const checkMonitor = (o) => {
676
+ 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");
677
+ if (o.taskRunId === void 0 && o.query === void 0) throw invalidRequest(provider, "a parallel monitor needs a query or a taskRunId");
678
+ if (o.taskRunId !== void 0) for (const name of [
679
+ "query",
680
+ "schema",
681
+ "includeBackfill",
682
+ "country",
683
+ "includeDomains",
684
+ "excludeDomains",
685
+ "publishedAfter"
686
+ ]) refuseTogether(provider, o, "taskRunId", name);
687
+ if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalidRequest(provider, "webhookEvents needs a webhookUrl");
688
+ };
689
+ /** The body that creates a monitor: a query to search, or a Task run to repeat. */
690
+ const monitorBody = (o) => compact({
691
+ frequency: frequency(o.schedule),
692
+ metadata: o.metadata,
693
+ processor: o.processor,
694
+ settings: o.taskRunId === void 0 ? compact({
695
+ advanced_settings: nonEmpty({
696
+ location: o.country,
697
+ source_policy: sourcePolicy(o)
698
+ }),
699
+ include_backfill: o.includeBackfill,
700
+ output_schema: o.schema ? jsonOutput(o.schema) : void 0,
701
+ query: o.query
702
+ }) : { task_run_id: o.taskRunId },
703
+ type: o.taskRunId === void 0 ? "event_stream" : "snapshot",
704
+ webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : compact({
705
+ event_types: o.webhookEvents,
706
+ url: o.webhookUrl
707
+ })
708
+ });
709
+ /**
710
+ * Every monitor from `cursor` on, one page after another: the next page is
711
+ * requested only once this one names its cursor. A cursor seen before would
712
+ * page forever, so it ends the listing.
713
+ */
714
+ const listMonitors = async (raw, call, cursor, seen) => {
715
+ const page = z$1.parse(MonitorsPage, await raw.request("GET", "/v1/monitors", {
716
+ ...call,
717
+ query: {
718
+ cursor,
719
+ limit: 100
720
+ }
721
+ }));
722
+ const monitors = page.monitors.map((entry) => monitorInfo(entry));
723
+ const next = page.next_cursor;
724
+ if (next === void 0 || seen.has(next)) return monitors;
725
+ return [...monitors, ...await listMonitors(raw, call, next, /* @__PURE__ */ new Set([...seen, next]))];
726
+ };
727
+ /** Parallel's monitor methods, calling through `raw`. */
728
+ const parallelMonitor = (raw) => ({
729
+ async create(options) {
730
+ const { call, rest: o } = callSettings(options);
731
+ checkMonitor(o);
732
+ const response = await raw.request("POST", "/v1/monitors", {
733
+ creates: true,
734
+ ...call,
735
+ body: monitorBody(o)
736
+ });
737
+ return monitorInfo(z$1.parse(MonitorEntry, response));
738
+ },
739
+ async delete(id, options) {
740
+ await raw.request("POST", `/v1/monitors/${segment(id)}/cancel`, options);
741
+ },
742
+ async events(id, options = {}) {
743
+ const { call, rest: o } = callSettings(options);
744
+ const response = await raw.request("GET", `/v1/monitors/${segment(id)}/events`, {
745
+ ...call,
746
+ query: {
747
+ cursor: o.cursor,
748
+ event_group_id: o.eventGroupId,
749
+ include_completions: o.includeCompletions,
750
+ limit: o.limit
751
+ }
752
+ });
753
+ const page = z$1.parse(EventsPage, response);
754
+ return compact({
755
+ events: page.events.map((entry) => monitorEvent(entry)),
756
+ next: page.next_cursor,
757
+ raw: response
758
+ });
759
+ },
760
+ async get(id, options) {
761
+ return monitorInfo(z$1.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${segment(id)}`, options)));
762
+ },
763
+ async list(options = {}) {
764
+ const { call } = callSettings(options);
765
+ return await listMonitors(raw, call, void 0, /* @__PURE__ */ new Set());
766
+ }
767
+ });
670
768
  // src/adapters/parallel.ts
769
+ /** `answer`: one response from Parallel's model, with web search. */
770
+ const answering = (raw) => ({ async answer(question, options = {}) {
771
+ const { call, rest: o } = callSettings(options);
772
+ refuseTogether(provider, o, "includeDomains", "excludeDomains");
773
+ const filters = nonEmpty({
774
+ allowed_domains: o.includeDomains,
775
+ blocked_domains: o.excludeDomains
776
+ });
777
+ const response = await raw.request("POST", "/v1/responses", {
778
+ ...call,
779
+ body: compact({
780
+ input: question,
781
+ instructions: o.instructions,
782
+ metadata: o.metadata,
783
+ model: "parallel",
784
+ previous_response_id: o.continueFrom,
785
+ reasoning: o.effort ? { effort: o.effort } : void 0,
786
+ text: o.schema ? { format: {
787
+ name: "answer",
788
+ schema: jsonSchemaOf(o.schema),
789
+ type: "json_schema"
790
+ } } : void 0,
791
+ tools: filters ? [{
792
+ filters,
793
+ type: "web_search"
794
+ }] : void 0
795
+ })
796
+ });
797
+ const body = z$1.parse(AnswerResponse, response);
798
+ const failure = body.error.message;
799
+ if (body.status === "failed" || failure !== void 0) throw new FieldworkError("ProviderError", `parallel could not answer: ${failure ?? "the response failed"}`, {
800
+ cause: response,
801
+ provider
802
+ });
803
+ const parts = responseMessages(body).flatMap((message) => message.content.filter((part) => part.type === "output_text"));
804
+ const answer = parts.map((part) => part.text).filter((part) => part !== void 0).join("\n\n");
805
+ if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${body.status ?? "unknown"})`, {
806
+ cause: response,
807
+ provider
808
+ });
809
+ const { usage } = body;
810
+ const incomplete = body.incomplete_details.reason;
811
+ return compact({
812
+ answer,
813
+ citations: uniqueCitations(citationsOf(parts.flatMap((part) => part.annotations).filter((item) => item.type === "url_citation"))),
814
+ continuationId: body.id.text,
815
+ meta: meta({
816
+ requestId: body.id.request,
817
+ units: {
818
+ input_tokens: usage.input_tokens,
819
+ output_tokens: usage.output_tokens,
820
+ total_tokens: usage.total_tokens
821
+ },
822
+ warnings: incomplete === void 0 ? void 0 : [`the answer is incomplete: ${incomplete}`]
823
+ }),
824
+ output: o.schema ? await checkOutput(o.schema, parseJson(provider, answer), { provider }) : void 0,
825
+ raw: response
826
+ });
827
+ } });
828
+ /** `decide` and `discover`: questions answered about the web, and the entities a FindAll run turns up. */
829
+ const judging = (raw) => ({
830
+ async decide(context, questions, options = {}) {
831
+ const { call, rest: o } = callSettings(options);
832
+ const entries = Object.entries(questions);
833
+ const names = entries.map(([name]) => name);
834
+ if (names.length < 1 || names.length > 100) throw invalidRequest(provider, `decisions take 1 to 100 questions; got ${names.length}`);
835
+ const badName = names.find((name) => !QUESTION_NAME.test(name));
836
+ if (badName !== void 0) throw invalidRequest(provider, `question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
837
+ const response = await raw.request("POST", "/v1/decisions", {
838
+ ...call,
839
+ body: compact({
840
+ advanced_settings: nonEmpty({
841
+ include_excerpts: o.includeExcerpts,
842
+ location: o.country
843
+ }),
844
+ questions: Object.fromEntries(entries.map(([name, question]) => [name, decisionQuestion(name, question)])),
845
+ state: context ?? null
846
+ })
847
+ });
848
+ const body = z$1.parse(DecisionsResponse, response);
849
+ const result = {};
850
+ const unanswered = [];
851
+ for (const [name, question] of entries) {
852
+ const found = Object.hasOwn(body.answers, name) ? body.answers[name] : void 0;
853
+ const answer = found && decisionAnswer(question, found);
854
+ if (answer === void 0) unanswered.push(name);
855
+ else result[name] = answer;
856
+ }
857
+ if (unanswered.length > 0) throw new FieldworkError("ProviderError", `parallel returned no complete answer for ${unanswered.join(", ")}`, {
858
+ cause: response,
859
+ provider
860
+ });
861
+ return compact({
862
+ answers: result,
863
+ citations: citationsOf(body.citations),
864
+ meta: meta({
865
+ requestId: body.decision_id,
866
+ units: { input_tokens: body.usage.input_tokens }
867
+ }),
868
+ raw: response
869
+ });
870
+ },
871
+ async discover(objective, options) {
872
+ const { call, rest: o } = callSettings(options);
873
+ return await runJob(provider, {
874
+ check: async (id, request) => await findAllResult(raw, id, request),
875
+ finish: async (result, id) => {
876
+ const found = discovery(id, result);
877
+ const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => data === void 0 ? entity : {
878
+ ...entity,
879
+ data: await checkOutput(o.schema, data, { provider })
880
+ }));
881
+ return {
882
+ ...found,
883
+ entities
884
+ };
885
+ },
886
+ start: async () => await startFindAll(raw, objective, o, call)
887
+ }, {
888
+ ...call,
889
+ interval: o.interval,
890
+ resume: o.resume
891
+ });
892
+ }
893
+ });
894
+ /** `extract` and `research`: Task runs, polled to their result. */
895
+ const tasking = (raw) => ({
896
+ async extract(url, options = {}) {
897
+ const { call, rest: o } = callSettings(options);
898
+ if (!URL.canParse(url)) throw invalidRequest(provider, `cannot extract ${url}: it is not a URL`);
899
+ const target = new URL(url);
900
+ return await runTask(raw, compact({
901
+ advanced_settings: nonEmpty({ location: o.country }),
902
+ input: {
903
+ instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
904
+ url
905
+ },
906
+ metadata: o.metadata,
907
+ processor: o.processor ?? "base",
908
+ source_policy: { include_domains: [`${target.hostname}${target.pathname}`.replace(/\/$/u, "")] },
909
+ task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "auto" } }
910
+ }), {
911
+ ...call,
912
+ interval: o.interval,
913
+ resume: o.resume
914
+ }, async (result) => {
915
+ const { output } = result.value;
916
+ return compact({
917
+ data: await checkOutput(o.schema, output.content, { provider }),
918
+ fields: basis(output.basis),
919
+ meta: taskMeta(result),
920
+ raw: result.original
921
+ });
922
+ });
923
+ },
924
+ async research(question, options = {}) {
925
+ const { call, rest: o } = callSettings(options);
926
+ return await runTask(raw, compact({
927
+ advanced_settings: nonEmpty({ location: o.country }),
928
+ input: question,
929
+ metadata: o.metadata,
930
+ previous_interaction_id: o.continueFrom,
931
+ processor: o.processor ?? "base",
932
+ source_policy: sourcePolicy(o),
933
+ task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "text" } }
934
+ }), {
935
+ ...call,
936
+ interval: o.interval,
937
+ resume: o.resume
938
+ }, async (result, id) => {
939
+ const { output, run } = result.value;
940
+ const fields = basis(output.basis);
941
+ return compact({
942
+ continuationId: run.interaction_id,
943
+ fields,
944
+ id,
945
+ meta: taskMeta(result),
946
+ output: await checkOutput(o.schema, output.content, { provider }),
947
+ raw: result.original,
948
+ sources: citedBy(fields),
949
+ status: "completed"
950
+ });
951
+ });
952
+ }
953
+ });
954
+ /** `read` and `readMany`, through `/v1/extract`. */
955
+ const reading = (raw) => ({
956
+ async read(url, options = {}) {
957
+ const { call, rest: o } = callSettings(options);
958
+ const response = await raw.request("POST", "/v1/extract", {
959
+ ...call,
960
+ body: extractBody([url], o)
961
+ });
962
+ const body = z$1.parse(ExtractResponse, response);
963
+ const [result] = body.results;
964
+ if (result?.value.url === void 0) {
965
+ const [failure] = body.errors;
966
+ throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${failure !== void 0 && Object.keys(failure).length > 0 ? extractFailure(failure) : "no content returned"}`, {
967
+ cause: response,
968
+ provider
969
+ });
970
+ }
971
+ return pageFrom(result, {
972
+ meta: extractMeta(body),
973
+ raw: response
974
+ });
975
+ },
976
+ async readMany(urls, options = {}) {
977
+ const { call, rest: o } = callSettings(options);
978
+ if (urls.length > 20) throw invalidRequest(provider, `reads up to 20 URLs in one call; got ${urls.length}`);
979
+ const response = await raw.request("POST", "/v1/extract", {
980
+ ...call,
981
+ body: extractBody(urls, o)
982
+ });
983
+ const body = z$1.parse(ExtractResponse, response);
984
+ return compact({
985
+ failed: body.errors.map((failure) => ({
986
+ error: extractFailure(failure),
987
+ url: failure.url ?? ""
988
+ })),
989
+ id: body.extract_id.text,
990
+ meta: extractMeta(body),
991
+ pages: body.results.map((entry) => pageFrom(entry)),
992
+ raw: response
993
+ });
994
+ }
995
+ });
996
+ /** `search` and `images`: one request each. */
997
+ const searching = (raw) => ({
998
+ async images(query, options = {}) {
999
+ const { call, rest: o } = callSettings(options);
1000
+ const response = await raw.request("POST", "/v1/images/search", {
1001
+ ...call,
1002
+ body: compact({
1003
+ advanced_settings: nonEmpty({
1004
+ location: o.country,
1005
+ max_results: o.limit
1006
+ }),
1007
+ mode: o.mode,
1008
+ objective: o.objective ?? query,
1009
+ search_queries: o.queries ?? [query],
1010
+ session_id: o.sessionId
1011
+ })
1012
+ });
1013
+ const body = z$1.parse(ImagesResponse, response);
1014
+ return compact({
1015
+ meta: meta({
1016
+ requestId: body.search_id,
1017
+ units: usageUnits(body.usage),
1018
+ warnings: body.warnings
1019
+ }),
1020
+ raw: response,
1021
+ results: body.results.map((image) => compact({
1022
+ height: image.height,
1023
+ sourceUrl: image.source_page_url,
1024
+ title: image.title,
1025
+ url: image.image_url ?? "",
1026
+ width: image.width
1027
+ }))
1028
+ });
1029
+ },
1030
+ async search(query, options = {}) {
1031
+ const { call, rest: o } = callSettings(options);
1032
+ const response = await raw.request("POST", "/v1/search", {
1033
+ ...call,
1034
+ body: compact({
1035
+ advanced_settings: nonEmpty({
1036
+ excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
1037
+ fetch_policy: fetchPolicy(o.maxAge),
1038
+ location: o.country,
1039
+ max_results: o.limit,
1040
+ source_policy: sourcePolicy(o)
1041
+ }),
1042
+ max_chars_total: o.maxCharsTotal,
1043
+ mode: o.mode,
1044
+ objective: o.objective ?? query,
1045
+ search_queries: o.queries ?? [query],
1046
+ session_id: o.sessionId
1047
+ })
1048
+ });
1049
+ const body = z$1.parse(SearchResponse, response);
1050
+ return compact({
1051
+ meta: meta({
1052
+ requestId: body.search_id,
1053
+ units: usageUnits(body.usage),
1054
+ warnings: body.warnings
1055
+ }),
1056
+ raw: response,
1057
+ results: body.results.map((result) => compact({
1058
+ publishedAt: result.publish_date,
1059
+ snippet: result.excerpts.length > 0 ? result.excerpts.join(" … ") : void 0,
1060
+ title: result.title,
1061
+ url: result.url ?? ""
1062
+ }))
1063
+ });
1064
+ }
1065
+ });
671
1066
  /**
672
- * An adapter for Parallel: search, images, read, readMany, extract, answer, research, discover, decide and monitor. Pass it to `new Fieldwork({ adapter })`.
1067
+ * An adapter for Parallel: search, images, read, readMany, extract, answer, research, discover, decide and monitor. Pass it to `fieldwork({ adapter })`.
673
1068
  *
674
1069
  * Throws `Unauthorized` when neither `apiKey` nor `PARALLEL_API_KEY` is set.
675
1070
  */
@@ -681,378 +1076,17 @@ const parallel = (config = {}) => {
681
1076
  provider,
682
1077
  retries: config.retries
683
1078
  });
1079
+ const operations = {
1080
+ ...answering(raw),
1081
+ ...judging(raw),
1082
+ ...reading(raw),
1083
+ ...searching(raw),
1084
+ ...tasking(raw),
1085
+ monitor: parallelMonitor(raw)
1086
+ };
684
1087
  return defineAdapter({
685
1088
  name: provider,
686
- operations: {
687
- async answer(question, options) {
688
- const { call, rest: o } = callSettings(options);
689
- refuseTogether(provider, o, "includeDomains", "excludeDomains");
690
- const filters = nonEmpty({
691
- allowed_domains: o.includeDomains,
692
- blocked_domains: o.excludeDomains
693
- });
694
- const response = await raw.request("POST", "/v1/responses", {
695
- ...call,
696
- body: compact({
697
- input: question,
698
- instructions: o.instructions,
699
- metadata: o.metadata,
700
- model: "parallel",
701
- previous_response_id: o.continueFrom,
702
- reasoning: o.effort ? { effort: o.effort } : void 0,
703
- text: o.schema ? { format: {
704
- name: "answer",
705
- schema: jsonSchemaOf(o.schema),
706
- type: "json_schema"
707
- } } : void 0,
708
- tools: filters ? [{
709
- filters,
710
- type: "web_search"
711
- }] : void 0
712
- })
713
- });
714
- const body = z.parse(AnswerResponse, response);
715
- const failure = body.error.message;
716
- if (body.status === "failed" || failure !== void 0) throw new FieldworkError("ProviderError", `parallel could not answer: ${failure ?? "the response failed"}`, {
717
- cause: response,
718
- provider
719
- });
720
- const parts = responseMessages(body).flatMap((message) => message.content.filter((part) => part.type === "output_text"));
721
- const answer = parts.map((part) => part.text).filter((part) => part !== void 0).join("\n\n");
722
- if (answer === "") throw new FieldworkError("ProviderError", `parallel returned no answer text (status ${body.status ?? "unknown"})`, {
723
- cause: response,
724
- provider
725
- });
726
- const { usage } = body;
727
- const incomplete = body.incomplete_details.reason;
728
- return compact({
729
- answer,
730
- citations: uniqueCitations(citationsOf(parts.flatMap((part) => part.annotations).filter((item) => item.type === "url_citation"))),
731
- continuationId: body.id.text,
732
- meta: meta({
733
- requestId: body.id.request,
734
- units: {
735
- input_tokens: usage.input_tokens,
736
- output_tokens: usage.output_tokens,
737
- total_tokens: usage.total_tokens
738
- },
739
- warnings: incomplete === void 0 ? void 0 : [`the answer is incomplete: ${incomplete}`]
740
- }),
741
- output: o.schema ? await checkOutput(o.schema, parseJson(provider, answer), { provider }) : void 0,
742
- raw: response
743
- });
744
- },
745
- async decide(context, questions, options) {
746
- const { call, rest: o } = callSettings(options);
747
- const entries = Object.entries(questions);
748
- const names = entries.map(([name]) => name);
749
- if (names.length < 1 || names.length > 100) throw invalidRequest(provider, `decisions take 1 to 100 questions; got ${names.length}`);
750
- const badName = names.find((name) => !QUESTION_NAME.test(name));
751
- if (badName !== void 0) throw invalidRequest(provider, `question names use only letters, numbers, underscores and hyphens; "${badName}" does not`);
752
- const response = await raw.request("POST", "/v1/decisions", {
753
- ...call,
754
- body: compact({
755
- advanced_settings: nonEmpty({
756
- include_excerpts: o.includeExcerpts,
757
- location: o.country
758
- }),
759
- questions: Object.fromEntries(entries.map(([name, question]) => [name, decisionQuestion(name, question)])),
760
- state: context ?? null
761
- })
762
- });
763
- const body = z.parse(DecisionsResponse, response);
764
- const result = {};
765
- const unanswered = [];
766
- for (const [name, question] of entries) {
767
- const found = Object.hasOwn(body.answers, name) ? body.answers[name] : void 0;
768
- const answer = found && decisionAnswer(question, found);
769
- if (answer === void 0) unanswered.push(name);
770
- else result[name] = answer;
771
- }
772
- if (unanswered.length > 0) throw new FieldworkError("ProviderError", `parallel returned no complete answer for ${unanswered.join(", ")}`, {
773
- cause: response,
774
- provider
775
- });
776
- return compact({
777
- answers: result,
778
- citations: citationsOf(body.citations),
779
- meta: meta({
780
- requestId: body.decision_id,
781
- units: { input_tokens: body.usage.input_tokens }
782
- }),
783
- raw: response
784
- });
785
- },
786
- async discover(objective, options) {
787
- const { call, rest: o } = callSettings(options);
788
- return await runJob(provider, {
789
- check: async (id, request) => await findAllResult(raw, id, request),
790
- finish: async (result, id) => {
791
- const found = discovery(id, result);
792
- const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => data === void 0 ? entity : {
793
- ...entity,
794
- data: await checkOutput(o.schema, data, { provider })
795
- }));
796
- return {
797
- ...found,
798
- entities
799
- };
800
- },
801
- start: async () => await startFindAll(raw, objective, o, call)
802
- }, {
803
- ...call,
804
- interval: o.interval,
805
- resume: o.resume
806
- });
807
- },
808
- async extract(url, options) {
809
- const { call, rest: o } = callSettings(options);
810
- if (!URL.canParse(url)) throw invalidRequest(provider, `cannot extract ${url}: it is not a URL`);
811
- const target = new URL(url);
812
- return await runTask(raw, compact({
813
- advanced_settings: nonEmpty({ location: o.country }),
814
- input: {
815
- instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
816
- url
817
- },
818
- metadata: o.metadata,
819
- processor: o.processor ?? "base",
820
- source_policy: { include_domains: [`${target.hostname}${target.pathname}`.replace(/\/$/u, "")] },
821
- task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "auto" } }
822
- }), {
823
- ...call,
824
- interval: o.interval,
825
- resume: o.resume
826
- }, async (result) => {
827
- const { output } = result.value;
828
- return compact({
829
- data: await checkOutput(o.schema, output.content, { provider }),
830
- fields: basis(output.basis),
831
- meta: taskMeta(result),
832
- raw: result.original
833
- });
834
- });
835
- },
836
- async images(query, options) {
837
- const { call, rest: o } = callSettings(options);
838
- const response = await raw.request("POST", "/v1/images/search", {
839
- ...call,
840
- body: compact({
841
- advanced_settings: nonEmpty({
842
- location: o.country,
843
- max_results: o.limit
844
- }),
845
- mode: o.mode,
846
- objective: o.objective ?? query,
847
- search_queries: o.queries ?? [query],
848
- session_id: o.sessionId
849
- })
850
- });
851
- const body = z.parse(ImagesResponse, response);
852
- return compact({
853
- meta: meta({
854
- requestId: body.search_id,
855
- units: usageUnits(body.usage),
856
- warnings: body.warnings
857
- }),
858
- raw: response,
859
- results: body.results.map((image) => compact({
860
- height: image.height,
861
- sourceUrl: image.source_page_url,
862
- title: image.title,
863
- url: image.image_url ?? "",
864
- width: image.width
865
- }))
866
- });
867
- },
868
- monitor: {
869
- async create(options) {
870
- const { call, rest: o } = callSettings(options);
871
- 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");
872
- if (o.taskRunId === void 0 && o.query === void 0) throw invalidRequest(provider, "a parallel monitor needs a query or a taskRunId");
873
- if (o.taskRunId !== void 0) for (const name of [
874
- "query",
875
- "schema",
876
- "includeBackfill",
877
- "country",
878
- "includeDomains",
879
- "excludeDomains",
880
- "publishedAfter"
881
- ]) refuseTogether(provider, o, "taskRunId", name);
882
- if (o.webhookEvents && (o.webhookUrl === void 0 || o.webhookUrl === "")) throw invalidRequest(provider, "webhookEvents needs a webhookUrl");
883
- const response = await raw.request("POST", "/v1/monitors", {
884
- creates: true,
885
- ...call,
886
- body: compact({
887
- frequency: frequency(o.schedule),
888
- metadata: o.metadata,
889
- processor: o.processor,
890
- settings: o.taskRunId === void 0 ? compact({
891
- advanced_settings: nonEmpty({
892
- location: o.country,
893
- source_policy: sourcePolicy(o)
894
- }),
895
- include_backfill: o.includeBackfill,
896
- output_schema: o.schema ? jsonOutput(o.schema) : void 0,
897
- query: o.query
898
- }) : { task_run_id: o.taskRunId },
899
- type: o.taskRunId === void 0 ? "event_stream" : "snapshot",
900
- webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : compact({
901
- event_types: o.webhookEvents,
902
- url: o.webhookUrl
903
- })
904
- })
905
- });
906
- return monitorInfo(z.parse(MonitorEntry, response));
907
- },
908
- async delete(id, options) {
909
- await raw.request("POST", `/v1/monitors/${segment(id)}/cancel`, options);
910
- },
911
- async events(id, options) {
912
- const { call, rest: o } = callSettings(options);
913
- const response = await raw.request("GET", `/v1/monitors/${segment(id)}/events`, {
914
- ...call,
915
- query: {
916
- cursor: o.cursor,
917
- event_group_id: o.eventGroupId,
918
- include_completions: o.includeCompletions,
919
- limit: o.limit
920
- }
921
- });
922
- const page = z.parse(EventsPage, response);
923
- return compact({
924
- events: page.events.map((entry) => monitorEvent(entry)),
925
- next: page.next_cursor,
926
- raw: response
927
- });
928
- },
929
- async get(id, options) {
930
- return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/v1/monitors/${segment(id)}`, options)));
931
- },
932
- async list(options) {
933
- const { call } = callSettings(options);
934
- const monitors = [];
935
- const seen = /* @__PURE__ */ new Set();
936
- let cursor;
937
- for (;;) {
938
- const page = z.parse(MonitorsPage, await raw.request("GET", "/v1/monitors", {
939
- ...call,
940
- query: {
941
- cursor,
942
- limit: 100
943
- }
944
- }));
945
- monitors.push(...page.monitors.map((entry) => monitorInfo(entry)));
946
- cursor = page.next_cursor;
947
- if (cursor === void 0 || seen.has(cursor)) return monitors;
948
- seen.add(cursor);
949
- }
950
- }
951
- },
952
- async read(url, options) {
953
- const { call, rest: o } = callSettings(options);
954
- const response = await raw.request("POST", "/v1/extract", {
955
- ...call,
956
- body: extractBody([url], o)
957
- });
958
- const body = z.parse(ExtractResponse, response);
959
- const [result] = body.results;
960
- if (result?.value.url === void 0) {
961
- const [failure] = body.errors;
962
- throw new FieldworkError("ProviderError", `parallel could not read ${url}: ${failure !== void 0 && Object.keys(failure).length > 0 ? extractFailure(failure) : "no content returned"}`, {
963
- cause: response,
964
- provider
965
- });
966
- }
967
- return pageFrom(result, {
968
- meta: extractMeta(body),
969
- raw: response
970
- });
971
- },
972
- async readMany(urls, options) {
973
- const { call, rest: o } = callSettings(options);
974
- if (urls.length > 20) throw invalidRequest(provider, `reads up to 20 URLs in one call; got ${urls.length}`);
975
- const response = await raw.request("POST", "/v1/extract", {
976
- ...call,
977
- body: extractBody(urls, o)
978
- });
979
- const body = z.parse(ExtractResponse, response);
980
- return compact({
981
- failed: body.errors.map((failure) => ({
982
- error: extractFailure(failure),
983
- url: failure.url ?? ""
984
- })),
985
- id: body.extract_id.text,
986
- meta: extractMeta(body),
987
- pages: body.results.map((entry) => pageFrom(entry)),
988
- raw: response
989
- });
990
- },
991
- async research(question, options) {
992
- const { call, rest: o } = callSettings(options);
993
- return await runTask(raw, compact({
994
- advanced_settings: nonEmpty({ location: o.country }),
995
- input: question,
996
- metadata: o.metadata,
997
- previous_interaction_id: o.continueFrom,
998
- processor: o.processor ?? "base",
999
- source_policy: sourcePolicy(o),
1000
- task_spec: { output_schema: o.schema ? jsonOutput(o.schema) : { type: "text" } }
1001
- }), {
1002
- ...call,
1003
- interval: o.interval,
1004
- resume: o.resume
1005
- }, async (result, id) => {
1006
- const { output, run } = result.value;
1007
- const fields = basis(output.basis);
1008
- return compact({
1009
- continuationId: run.interaction_id,
1010
- fields,
1011
- id,
1012
- meta: taskMeta(result),
1013
- output: await checkOutput(o.schema, output.content, { provider }),
1014
- raw: result.original,
1015
- sources: citedBy(fields),
1016
- status: "completed"
1017
- });
1018
- });
1019
- },
1020
- async search(query, options) {
1021
- const { call, rest: o } = callSettings(options);
1022
- const response = await raw.request("POST", "/v1/search", {
1023
- ...call,
1024
- body: compact({
1025
- advanced_settings: nonEmpty({
1026
- excerpt_settings: nonEmpty({ max_chars_per_result: o.maxCharsPerResult }),
1027
- fetch_policy: fetchPolicy(o.maxAge),
1028
- location: o.country,
1029
- max_results: o.limit,
1030
- source_policy: sourcePolicy(o)
1031
- }),
1032
- max_chars_total: o.maxCharsTotal,
1033
- mode: o.mode,
1034
- objective: o.objective ?? query,
1035
- search_queries: o.queries ?? [query],
1036
- session_id: o.sessionId
1037
- })
1038
- });
1039
- const body = z.parse(SearchResponse, response);
1040
- return compact({
1041
- meta: meta({
1042
- requestId: body.search_id,
1043
- units: usageUnits(body.usage),
1044
- warnings: body.warnings
1045
- }),
1046
- raw: response,
1047
- results: body.results.map((result) => compact({
1048
- publishedAt: result.publish_date,
1049
- snippet: result.excerpts.length > 0 ? result.excerpts.join(" … ") : void 0,
1050
- title: result.title,
1051
- url: result.url ?? ""
1052
- }))
1053
- });
1054
- }
1055
- },
1089
+ operations,
1056
1090
  raw
1057
1091
  });
1058
1092
  };