@howells/fieldwork-sdk 0.5.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/brave.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-Yvk42oZH.js";
3
- import { C as createRawClient, E as requireKey, N as meta, O as callSettings, P as parseJson, R as refuseTogether, a as looseObject, f as optionalNumber, h as optionalString, j as compact, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf } from "./parse-D4SMt-Ip.js";
3
+ import { C as createRawClient, F as parseJson, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf, z as refuseTogether } from "./parse-n8MmaK1x.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/brave/response.ts
6
6
  /** The `query` block every search response carries. */
@@ -1,6 +1,6 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest } from "./errors-Yvk42oZH.js";
3
- import { C as createRawClient, D as segment, E as requireKey, F as presentPage, N as meta, O as callSettings, R as refuseTogether, S as withOriginal, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as compact, m as optionalScalar, r as arrayOf, s as optionalAnyString, z as requireJobId } from "./parse-D4SMt-Ip.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, 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, m as optionalScalar, r as arrayOf, s as optionalAnyString, z as refuseTogether } from "./parse-n8MmaK1x.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/browserbase/response.ts
6
6
  /** `POST /v1/sessions`. The id keeps the value as it arrived, for the error raised when there is none. */
package/dist/exa.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
- import { A as citationsOf, B as uniqueCitations, C as createRawClient, D as segment, E as requireKey, L as record, M as hours, N as meta, O as callSettings, P as parseJson, S as withOriginal, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, j as compact, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, N as hours, P as meta, R as record, S as withOriginal, T as requireKey, V as uniqueCitations, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, j as citationsOf, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-n8MmaK1x.js";
4
+ import { t as runJob } from "./job-BGTwH3F-.js";
4
5
  import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
6
  import * as z from "zod/mini";
6
7
  const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
@@ -157,7 +158,6 @@ const researchResult = (id, entry, structured) => {
157
158
  const detail = error.message === void 0 ? stopReason : `${error.code ?? error.type ?? "error"}: ${error.message}`;
158
159
  throw new FieldworkError("JobFailed", `exa research run ${id} ended ${status}${detail === void 0 ? "" : ` (${detail})`}`, {
159
160
  cause: entry.original,
160
- jobId: id,
161
161
  provider: "exa"
162
162
  });
163
163
  }
@@ -557,29 +557,31 @@ const exa = (config = {}) => {
557
557
  async research(question, options) {
558
558
  const { call, rest: o } = callSettings(options);
559
559
  checkResearch(o);
560
- const id = o.resume ?? requireJobId("exa", z.parse(RunStart, await raw.request("POST", "/agent/runs", {
561
- creates: true,
562
- ...call,
563
- body: researchBody(question, o)
564
- })).id);
565
- const run = await poll("exa", id, async (request) => {
566
- const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request));
567
- const { status } = current.value;
568
- return status === "completed" || status === "failed" || status === "cancelled" ? current : void 0;
560
+ return await runJob("exa", {
561
+ check: async (id, request) => {
562
+ const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request));
563
+ const { status } = current.value;
564
+ return status === "completed" || status === "failed" || status === "cancelled" ? current : void 0;
565
+ },
566
+ finish: async (run, id) => {
567
+ const { outputSchema } = run.value.request;
568
+ const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
569
+ const result = researchResult(id, run, structured);
570
+ return {
571
+ ...result,
572
+ output: await checkOutput(o.schema, result.output, { provider: "exa" })
573
+ };
574
+ },
575
+ start: async () => requireJobId("exa", z.parse(RunStart, await raw.request("POST", "/agent/runs", {
576
+ creates: true,
577
+ ...call,
578
+ body: researchBody(question, o)
579
+ })).id)
569
580
  }, {
570
581
  ...call,
571
- interval: o.interval
582
+ interval: o.interval,
583
+ resume: o.resume
572
584
  });
573
- const { outputSchema } = run.value.request;
574
- const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
575
- const result = researchResult(id, run, structured);
576
- return {
577
- ...result,
578
- output: await checkOutput(o.schema, result.output, {
579
- jobId: id,
580
- provider: "exa"
581
- })
582
- };
583
585
  },
584
586
  async search(query, options) {
585
587
  const { call, rest: o } = callSettings(options);
package/dist/firecrawl.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
- import { C as createRawClient, D as segment, E as requireKey, F as presentPage, I as presentPages, N as meta, O as callSettings, R as refuseTogether, S as withOriginal, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as compact, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-n8MmaK1x.js";
4
+ import { t as runJob } from "./job-BGTwH3F-.js";
4
5
  import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
6
  import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-Dpj01mGx.js";
6
7
  import * as z from "zod/mini";
@@ -904,42 +905,43 @@ const firecrawl = (config = {}) => {
904
905
  const base = new URL(baseUrl).pathname.replace(/\/$/u, "");
905
906
  return next.pathname.slice(base.length) + next.search;
906
907
  };
907
- const finished = async (kind, id, call, interval) => {
908
- const path = `/${kind}/${segment(id)}`;
909
- const get = async (schema, to) => {
910
- try {
911
- return z.parse(schema, await raw.request("GET", to, call));
912
- } catch (error) {
913
- throw withJob(error, id);
914
- }
915
- };
916
- const first = await poll(provider, id, async (request) => {
917
- const status = z.parse(Batch, await raw.request("GET", path, request));
908
+ /**
909
+ * Runs a crawl or batch scrape: waits for it, then reads every page of its
910
+ * results and the pages that failed.
911
+ */
912
+ const batchJob = async (kind, start, settings, finish) => await runJob(provider, {
913
+ check: async (id, request) => {
914
+ const status = z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request));
918
915
  const state = status.value.status;
919
916
  if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
920
917
  cause: status.original,
921
918
  provider
922
919
  });
923
920
  return state === "completed" ? status : void 0;
924
- }, {
925
- ...call,
926
- interval
927
- });
928
- const batches = [first];
929
- let { next } = first.value;
930
- while (next !== void 0) {
931
- const batch = await get(Batch, pathOf(next));
932
- batches.push(batch);
933
- ({next} = batch.value);
934
- }
935
- const errors = await get(BatchErrors, `${path}/errors`);
936
- return {
937
- batches,
938
- errors,
939
- failed: failedPages(errors),
940
- first
941
- };
942
- };
921
+ },
922
+ finish: async (first, id) => {
923
+ const path = `/${kind}/${segment(id)}`;
924
+ const request = {
925
+ retries: settings.retries,
926
+ signal: settings.signal
927
+ };
928
+ const batches = [first];
929
+ let { next } = first.value;
930
+ while (next !== void 0) {
931
+ const batch = z.parse(Batch, await raw.request("GET", pathOf(next), request));
932
+ batches.push(batch);
933
+ ({next} = batch.value);
934
+ }
935
+ const errors = z.parse(BatchErrors, await raw.request("GET", `${path}/errors`, request));
936
+ return finish({
937
+ batches,
938
+ errors,
939
+ failed: failedPages(errors),
940
+ first
941
+ }, id);
942
+ },
943
+ start
944
+ }, settings);
943
945
  const openSession = async (o, call) => {
944
946
  const session = z.parse(Session, await raw.request("POST", "/interact", {
945
947
  body: sessionBody(o),
@@ -1015,30 +1017,34 @@ const firecrawl = (config = {}) => {
1015
1017
  },
1016
1018
  async crawl(url, options) {
1017
1019
  const { call, rest: o } = callSettings(options);
1018
- const id = o.resume ?? requireJobId("firecrawl", z.parse(CrawlStart, await raw.request("POST", "/crawl", {
1020
+ return await batchJob("crawl", async () => requireJobId(provider, z.parse(CrawlStart, await raw.request("POST", "/crawl", {
1019
1021
  creates: true,
1020
1022
  ...call,
1021
1023
  body: crawlBody(url, o)
1022
- })).id);
1023
- const job = await finished("crawl", id, call, o.interval);
1024
- const { robotsBlocked } = job.errors.value;
1025
- return compact({
1026
- failed: job.failed,
1027
- id,
1028
- meta: meta({
1029
- credits: job.first.value.creditsUsed,
1030
- requestId: id
1031
- }),
1032
- pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1033
- ...toPage(item.value, url),
1034
- raw: item.original
1035
- }))),
1036
- raw: {
1037
- batches: job.batches.map((batch) => batch.original),
1038
- errors: job.errors.original
1039
- },
1040
- robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1041
- total: job.first.value.total
1024
+ })).id), {
1025
+ ...call,
1026
+ interval: o.interval,
1027
+ resume: o.resume
1028
+ }, (job, id) => {
1029
+ const { robotsBlocked } = job.errors.value;
1030
+ return compact({
1031
+ failed: job.failed,
1032
+ id,
1033
+ meta: meta({
1034
+ credits: job.first.value.creditsUsed,
1035
+ requestId: id
1036
+ }),
1037
+ pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1038
+ ...toPage(item.value, url),
1039
+ raw: item.original
1040
+ }))),
1041
+ raw: {
1042
+ batches: job.batches.map((batch) => batch.original),
1043
+ errors: job.errors.original
1044
+ },
1045
+ robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1046
+ total: job.first.value.total
1047
+ });
1042
1048
  });
1043
1049
  },
1044
1050
  async extract(url, options) {
@@ -1175,65 +1181,77 @@ const firecrawl = (config = {}) => {
1175
1181
  async readMany(urls, options) {
1176
1182
  const { call, rest: o } = callSettings(options);
1177
1183
  const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
1178
- const started = z.parse(RunStart, resume === void 0 ? await raw.request("POST", "/batch/scrape", {
1179
- creates: true,
1184
+ let started = z.parse(RunStart, {});
1185
+ return await batchJob("batch/scrape", async () => {
1186
+ started = z.parse(RunStart, await raw.request("POST", "/batch/scrape", {
1187
+ creates: true,
1188
+ ...call,
1189
+ body: compact({
1190
+ urls,
1191
+ ...readBody(read),
1192
+ maxConcurrency,
1193
+ ignoreInvalidURLs
1194
+ })
1195
+ }));
1196
+ return requireJobId(provider, started.value.id);
1197
+ }, {
1180
1198
  ...call,
1181
- body: compact({
1182
- urls,
1183
- ...readBody(read),
1184
- maxConcurrency,
1185
- ignoreInvalidURLs
1186
- })
1187
- }) : {});
1188
- const id = resume ?? requireJobId("firecrawl", started.value.id);
1189
- const job = await finished("batch/scrape", id, call, interval);
1190
- const rejected = started.value.invalidURLs.map((url) => ({
1191
- error: "invalid URL",
1192
- url
1193
- }));
1194
- const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1195
- ...toPage(item.value, ""),
1196
- raw: item.original
1197
- }))));
1198
- return compact({
1199
- failed: [
1200
- ...job.failed,
1201
- ...rejected,
1202
- ...gone
1203
- ],
1204
- id,
1205
- meta: meta({
1206
- credits: job.first.value.creditsUsed,
1207
- requestId: id
1208
- }),
1209
- pages,
1210
- raw: {
1211
- batches: job.batches.map((batch) => batch.original),
1212
- errors: job.errors.original,
1213
- started: started.original
1214
- }
1199
+ interval,
1200
+ resume
1201
+ }, (job, id) => {
1202
+ const rejected = started.value.invalidURLs.map((url) => ({
1203
+ error: "invalid URL",
1204
+ url
1205
+ }));
1206
+ const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1207
+ ...toPage(item.value, ""),
1208
+ raw: item.original
1209
+ }))));
1210
+ return compact({
1211
+ failed: [
1212
+ ...job.failed,
1213
+ ...rejected,
1214
+ ...gone
1215
+ ],
1216
+ id,
1217
+ meta: meta({
1218
+ credits: job.first.value.creditsUsed,
1219
+ requestId: id
1220
+ }),
1221
+ pages,
1222
+ raw: {
1223
+ batches: job.batches.map((batch) => batch.original),
1224
+ errors: job.errors.original,
1225
+ started: started.original
1226
+ }
1227
+ });
1215
1228
  });
1216
1229
  },
1217
1230
  async research(question, options) {
1218
1231
  const { call, rest: o } = callSettings(options);
1219
- const started = z.parse(RunStart, o.resume === void 0 ? await raw.request("POST", "/agent", {
1220
- creates: true,
1221
- ...call,
1222
- body: researchBody(question, o)
1223
- }) : {});
1224
- const id = o.resume ?? requireJobId("firecrawl", started.value.id);
1225
- const run = await poll(provider, id, async (request) => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, request))), {
1232
+ let started = z.parse(RunStart, {});
1233
+ return await runJob(provider, {
1234
+ check: async (id, request) => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, request))),
1235
+ finish: async (run, id) => {
1236
+ const result = researchResult(id, started, run);
1237
+ return {
1238
+ ...result,
1239
+ output: await checkOutput(o.schema, result.output, { provider })
1240
+ };
1241
+ },
1242
+ start: async () => {
1243
+ started = z.parse(RunStart, await raw.request("POST", "/agent", {
1244
+ creates: true,
1245
+ ...call,
1246
+ body: researchBody(question, o)
1247
+ }));
1248
+ return requireJobId(provider, started.value.id);
1249
+ }
1250
+ }, {
1226
1251
  ...call,
1227
- interval: o.interval
1252
+ interval: o.interval,
1253
+ resume: o.resume
1228
1254
  });
1229
- const result = researchResult(id, started, run);
1230
- return {
1231
- ...result,
1232
- output: await checkOutput(o.schema, result.output, {
1233
- jobId: id,
1234
- provider
1235
- })
1236
- };
1237
1255
  },
1238
1256
  async search(query, options) {
1239
1257
  const { call, rest: o } = callSettings(options);
@@ -0,0 +1,41 @@
1
+ import { i as withJob, t as FieldworkError } from "./errors-Yvk42oZH.js";
2
+ import { D as sleep, O as stopped } from "./parse-n8MmaK1x.js";
3
+ // src/job.ts
4
+ const waitFor = async (provider, id, check, settings) => {
5
+ const interval = settings.interval ?? 2e3;
6
+ const deadline = Date.now() + (settings.timeout ?? 6e5);
7
+ const request = {
8
+ retries: settings.retries,
9
+ signal: settings.signal
10
+ };
11
+ for (;;) {
12
+ if (settings.signal?.aborted === true) throw stopped(settings.signal, `stopped waiting for ${provider} job ${id}; it may still be running`, {
13
+ jobId: id,
14
+ provider
15
+ });
16
+ const found = await check(id, request);
17
+ if (found !== void 0) return found;
18
+ if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${id} did not finish in time; it may still be running`, {
19
+ jobId: id,
20
+ provider
21
+ });
22
+ await sleep(interval, settings.signal);
23
+ }
24
+ };
25
+ /**
26
+ * Runs an asynchronous job to its result: resumes the job named by `resume`
27
+ * or starts one, checks it until it finishes, then builds the result.
28
+ *
29
+ * Every error after the job has an id carries it as `jobId`, including a
30
+ * timeout or cancellation while waiting, so the caller can resume rather than
31
+ * start a second job.
32
+ */
33
+ const runJob = async (provider, job, settings) => {
34
+ const id = settings.resume ?? await job.start();
35
+ try {
36
+ return await job.finish(await waitFor(provider, id, job.check, settings), id);
37
+ } catch (error) {
38
+ throw withJob(error, id);
39
+ }
40
+ };
41
+ export { runJob as t };
@@ -1,7 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { a as refuseLarger, n as documentPart, r as enclosing } from "./document-Dpj01mGx.js";
3
- import { i as withJob, t as FieldworkError } from "./errors-Yvk42oZH.js";
4
- import { C as createRawClient, D as segment, E as requireKey, N as meta, O as callSettings, P as parseJson, S as withOriginal, T as readSigned, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as compact, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
3
+ import { t as FieldworkError } from "./errors-Yvk42oZH.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, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-n8MmaK1x.js";
5
+ import { t as runJob } from "./job-BGTwH3F-.js";
5
6
  import * as z from "zod/mini";
6
7
  // src/adapters/llamaparse/response.ts
7
8
  /** A box in page points, from the page's top-left corner. */
@@ -156,7 +157,6 @@ const configuration = (o) => compact({
156
157
  version: o.version ?? "latest"
157
158
  });
158
159
  const startParse = async (raw, document, o, call) => {
159
- if (o.resume !== void 0) return o.resume;
160
160
  if (document === void 0) throw new FieldworkError("InvalidRequest", "parse needs a document, or resume with the id of an earlier parse", { provider });
161
161
  refuseLarger(provider, document, MAX_PARSE_MB);
162
162
  const form = new FormData();
@@ -169,28 +169,22 @@ const startParse = async (raw, document, o, call) => {
169
169
  }));
170
170
  return requireJobId(provider, created.id);
171
171
  };
172
- const finished = (found, id) => {
172
+ const finished = (found) => {
173
173
  const { error_message: message, status } = found.value.job;
174
174
  if (status === "FAILED" || status === "CANCELLED") throw new FieldworkError("JobFailed", `llamaparse job ${status.toLowerCase()}${message === void 0 ? "" : `: ${message}`}`, {
175
175
  cause: found.original,
176
- jobId: id,
177
176
  provider
178
177
  });
179
178
  return status === "COMPLETED" ? found : void 0;
180
179
  };
181
180
  /** The grounded items: one JSON line per page, each page's items with word and cell boxes. */
182
- const groundedPages = async (found, id, options) => {
181
+ const groundedPages = async (found, options) => {
183
182
  const url = found.value.result_content_metadata.grounded_items.presigned_url;
184
183
  if (url === void 0) throw new FieldworkError("ProviderError", "llamaparse finished without the word boxes it was asked for", {
185
184
  cause: found.original,
186
- jobId: id,
187
185
  provider
188
186
  });
189
- try {
190
- return (await readSigned(provider, url, options)).split("\n").filter((line) => line.trim() !== "").map((line) => parseJson(provider, line));
191
- } catch (error) {
192
- throw withJob(error, id);
193
- }
187
+ return (await readSigned(provider, url, options)).split("\n").filter((line) => line.trim() !== "").map((line) => parseJson(provider, line));
194
188
  };
195
189
  /** Each page's picture, keyed by page number, from the job's saved screenshots. */
196
190
  const pageImageAddresses = (found, id) => {
@@ -201,44 +195,23 @@ const pageImageAddresses = (found, id) => {
201
195
  }
202
196
  if (addresses.size === 0) throw new FieldworkError("ProviderError", `llamaparse job ${id} has no page pictures; only a parse started with pageImages saves them`, {
203
197
  cause: found.original,
204
- jobId: id,
205
198
  provider
206
199
  });
207
200
  return addresses;
208
201
  };
209
- const parse = async (raw, document, options, fetchImpl) => {
210
- const { call, rest: o } = callSettings(options);
211
- const id = await startParse(raw, document, o, call);
212
- const blocks = o.blocks === true || o.wordBoxes === true;
213
- const expand = [
214
- "markdown",
215
- "usage",
216
- ...blocks ? ["items"] : [],
217
- ...o.pageImages === true ? ["images_content_metadata"] : []
218
- ].join(",");
219
- const found = await poll(provider, id, async (request) => finished(z.parse(JobResult, await raw.request("GET", `/api/v2/parse/${segment(id)}`, {
220
- ...request,
221
- query: { expand }
222
- })), id), {
223
- ...call,
224
- interval: o.interval
225
- });
202
+ /** The finished job as a document, with word boxes and page pictures when they were asked for. */
203
+ const parsedDocument = async (found, id, o, read) => {
226
204
  if (found.value.markdown.pages.length === 0) throw new FieldworkError("ProviderError", `llamaparse finished job ${id} without any pages of Markdown`, {
227
205
  cause: found.original,
228
- jobId: id,
229
206
  provider
230
207
  });
231
- const grounded = o.wordBoxes === true ? await groundedPages(found, id, {
232
- fetch: fetchImpl,
233
- signal: call.signal
234
- }) : void 0;
208
+ const grounded = o.wordBoxes === true ? await groundedPages(found, read) : void 0;
235
209
  const images = o.pageImages === true ? pageImageAddresses(found, id) : void 0;
236
210
  const pages = found.value.markdown.pages.flatMap((page) => {
237
211
  if (page.page_number === void 0) return [];
238
212
  const image = images?.get(page.page_number);
239
213
  if (images !== void 0 && image === void 0) throw new FieldworkError("ProviderError", `llamaparse job ${id} has no picture of page ${page.page_number}`, {
240
214
  cause: found.original,
241
- jobId: id,
242
215
  provider
243
216
  });
244
217
  return [compact({
@@ -249,7 +222,7 @@ const parse = async (raw, document, options, fetchImpl) => {
249
222
  });
250
223
  let laidOut;
251
224
  if (grounded !== void 0) laidOut = documentBlocks(grounded.map((row) => z.parse(ItemsPage, row)));
252
- else if (blocks) laidOut = documentBlocks(found.value.items.pages);
225
+ else if (o.blocks === true) laidOut = documentBlocks(found.value.items.pages);
253
226
  return compact({
254
227
  blocks: laidOut,
255
228
  id,
@@ -262,6 +235,30 @@ const parse = async (raw, document, options, fetchImpl) => {
262
235
  }
263
236
  });
264
237
  };
238
+ const parse = async (raw, document, options, fetchImpl) => {
239
+ const { call, rest: o } = callSettings(options);
240
+ const expand = [
241
+ "markdown",
242
+ "usage",
243
+ ...o.blocks === true || o.wordBoxes === true ? ["items"] : [],
244
+ ...o.pageImages === true ? ["images_content_metadata"] : []
245
+ ].join(",");
246
+ return await runJob(provider, {
247
+ check: async (id, request) => finished(z.parse(JobResult, await raw.request("GET", `/api/v2/parse/${segment(id)}`, {
248
+ ...request,
249
+ query: { expand }
250
+ }))),
251
+ finish: async (found, id) => await parsedDocument(found, id, o, {
252
+ fetch: fetchImpl,
253
+ signal: call.signal
254
+ }),
255
+ start: async () => await startParse(raw, document, o, call)
256
+ }, {
257
+ ...call,
258
+ interval: o.interval,
259
+ resume: o.resume
260
+ });
261
+ };
265
262
  /**
266
263
  * An adapter for LlamaParse: parse. Pass it to `new Fieldwork({ adapter })`.
267
264
  *
package/dist/parallel.js CHANGED
@@ -1,6 +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-Yvk42oZH.js";
3
- import { A as citationsOf, B as uniqueCitations, C as createRawClient, D as segment, E as requireKey, N as meta, O as callSettings, P as parseJson, R as refuseTogether, S as withOriginal, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j 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, z as requireJobId } from "./parse-D4SMt-Ip.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";
4
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
@@ -155,7 +156,6 @@ const discovery = (id, entry) => {
155
156
  const stoppedEarly = state !== "completed" || reason !== void 0 && !FINISHED.has(reason);
156
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`, {
157
158
  cause: entry.original,
158
- jobId: id,
159
159
  provider
160
160
  });
161
161
  const stopReason = reason ?? state;
@@ -442,7 +442,6 @@ const stoppedRun = (id, entry) => {
442
442
  if (warnings.length > 0) message += ` (${warnings.join("; ")})`;
443
443
  return new FieldworkError("JobFailed", message, {
444
444
  cause: entry.original,
445
- jobId: id,
446
445
  provider
447
446
  });
448
447
  };
@@ -457,23 +456,22 @@ const taskResult = async (raw, id, request) => {
457
456
  throw error;
458
457
  }
459
458
  };
460
- const runTask = async (raw, body, settings) => {
461
- const { resume, ...wait } = settings;
462
- const id = resume ?? requireJobId(raw.provider, z.parse(TaskStart, await raw.request("POST", "/v1/tasks/runs", {
463
- ...wait,
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
- creates: true
466
- })).run_id);
467
- return {
468
- id,
469
- result: await poll(raw.provider, id, async (request) => {
470
- const run = z.parse(TaskRun, await raw.request("GET", `/v1/tasks/runs/${segment(id)}`, request));
471
- const { status } = run.value;
472
- if (status === "failed" || status === "cancelled" || status === "action_required") throw stoppedRun(id, run);
473
- return status === "completed" ? await taskResult(raw, id, request) : void 0;
474
- }, wait)
475
- };
476
- };
470
+ creates: true,
471
+ retries: settings.retries,
472
+ signal: settings.signal
473
+ })).run_id)
474
+ }, settings);
477
475
  const startFindAll = async (raw, objective, o, call) => {
478
476
  const created = z.parse(FindAllStart, await raw.request("POST", "/v1beta/findall/runs", {
479
477
  creates: true,
@@ -512,7 +510,6 @@ const findAllResult = async (raw, id, request) => {
512
510
  const { status } = run.value.status;
513
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`, {
514
512
  cause: run.original,
515
- jobId: id,
516
513
  provider
517
514
  });
518
515
  return status === "completed" || status === "failed" || status === "cancelled" ? z.parse(FindAllResult, await raw.request("GET", `/v1beta/findall/runs/${segment(id)}/result`, request)) : void 0;
@@ -628,31 +625,30 @@ const parallel = (config = {}) => {
628
625
  },
629
626
  async discover(objective, options) {
630
627
  const { call, rest: o } = callSettings(options);
631
- const id = o.resume ?? await startFindAll(raw, objective, o, call);
632
- const result = await poll(provider, id, async (request) => await findAllResult(raw, id, request), {
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
+ }, {
633
643
  ...call,
634
- interval: o.interval
644
+ interval: o.interval,
645
+ resume: o.resume
635
646
  });
636
- const found = discovery(id, result);
637
- const entities = await Promise.all(found.entities.map(async ({ data, ...entity }) => {
638
- if (data === void 0) return entity;
639
- return {
640
- ...entity,
641
- data: await checkOutput(o.schema, data, {
642
- jobId: id,
643
- provider
644
- })
645
- };
646
- }));
647
- return {
648
- ...found,
649
- entities
650
- };
651
647
  },
652
648
  async extract(url, options) {
653
649
  const { call, rest: o } = callSettings(options);
654
650
  const target = new URL(url);
655
- const { id, result } = await runTask(raw, compact({
651
+ return await runTask(raw, compact({
656
652
  advanced_settings: nonEmpty({ location: o.country }),
657
653
  input: {
658
654
  instructions: o.prompt ?? (o.schema ? "Extract the values in the output schema from this page only." : "Extract the main facts this page states."),
@@ -666,16 +662,14 @@ const parallel = (config = {}) => {
666
662
  ...call,
667
663
  interval: o.interval,
668
664
  resume: o.resume
669
- });
670
- const { output } = result.value;
671
- return compact({
672
- data: await checkOutput(o.schema, output.content, {
673
- jobId: id,
674
- provider
675
- }),
676
- fields: basis(output.basis),
677
- meta: taskMeta(result),
678
- 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
+ });
679
673
  });
680
674
  },
681
675
  async images(query, options) {
@@ -835,7 +829,7 @@ const parallel = (config = {}) => {
835
829
  },
836
830
  async research(question, options) {
837
831
  const { call, rest: o } = callSettings(options);
838
- const { id, result } = await runTask(raw, compact({
832
+ return await runTask(raw, compact({
839
833
  advanced_settings: nonEmpty({ location: o.country }),
840
834
  input: question,
841
835
  metadata: o.metadata,
@@ -847,21 +841,19 @@ const parallel = (config = {}) => {
847
841
  ...call,
848
842
  interval: o.interval,
849
843
  resume: o.resume
850
- });
851
- const { output, run } = result.value;
852
- const fields = basis(output.basis);
853
- return compact({
854
- continuationId: run.interaction_id,
855
- fields,
856
- id,
857
- meta: taskMeta(result),
858
- output: await checkOutput(o.schema, output.content, {
859
- jobId: id,
860
- provider
861
- }),
862
- raw: result.original,
863
- sources: citedBy(fields),
864
- 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
+ });
865
857
  });
866
858
  },
867
859
  async search(query, options) {
@@ -1,4 +1,4 @@
1
- import { i as withJob, n as codeForStatus, t as FieldworkError } from "./errors-Yvk42oZH.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);
@@ -308,38 +308,6 @@ const retryAfterSeconds = (header, now = Date.now()) => {
308
308
  const date = Date.parse(header);
309
309
  return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
310
310
  };
311
- /**
312
- * Checks a job until `check` returns its result. Each check is given the
313
- * settings for its request: the call's signal, which carries the call's whole
314
- * deadline, and its retries. A check that throws, a cancellation and a
315
- * timeout all surface with `jobId`, so the caller can resume the job.
316
- */
317
- const poll = async (provider, jobId, check, options = {}) => {
318
- const interval = options.interval ?? 2e3;
319
- const deadline = Date.now() + (options.timeout ?? 6e5);
320
- const request = {
321
- retries: options.retries,
322
- signal: options.signal
323
- };
324
- for (;;) {
325
- if (options.signal?.aborted === true) throw stopped(options.signal, `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
326
- jobId,
327
- provider
328
- });
329
- let value;
330
- try {
331
- value = await check(request);
332
- } catch (error) {
333
- throw withJob(error, jobId);
334
- }
335
- if (value !== void 0) return value;
336
- if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
337
- jobId,
338
- provider
339
- });
340
- await sleep(interval, options.signal);
341
- }
342
- };
343
311
  /** An id as one path segment, so a caller's `resume` cannot reach another endpoint. */
344
312
  const segment = (id) => encodeURIComponent(id);
345
313
  const requireKey = (provider, given, envName) => {
@@ -507,4 +475,4 @@ const optionalArrayOf = (item) => z.optional(z.union([z.pipe(z.array(z.unknown()
507
475
  const parsed = z.safeParse(item, entry);
508
476
  return parsed.success ? [parsed.data] : [];
509
477
  }))), absent]));
510
- export { citationsOf as A, uniqueCitations as B, createRawClient as C, segment as D, requireKey as E, presentPage as F, presentPages as I, record as L, hours as M, meta as N, callSettings as O, parseJson as P, refuseTogether as R, withOriginal as S, readSigned 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, compact as j, citationOf 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, requireJobId as z };
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,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
- import { B as uniqueCitations, C as createRawClient, D as segment, E as requireKey, N as meta, O as callSettings, P as parseJson, R as refuseTogether, S as withOriginal, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as compact, k as citationOf, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, w as poll, y as sourceShape, z as requireJobId } from "./parse-D4SMt-Ip.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.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-n8MmaK1x.js";
4
+ import { t as runJob } from "./job-BGTwH3F-.js";
4
5
  import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
6
  import * as z from "zod/mini";
6
7
  // src/adapters/perplexity/parse.ts
@@ -132,16 +133,15 @@ const researchSetup = (o) => {
132
133
  tools: searchTool ? [searchTool] : void 0
133
134
  };
134
135
  };
135
- const researchOutput = (run, reply, schema, id) => {
136
+ const researchOutput = (run, reply, schema) => {
136
137
  if (!schema) return reply;
137
138
  const { status } = run.value;
138
139
  try {
139
140
  return parseJson(provider, reply);
140
141
  } catch (error) {
141
- if (status === "completed") throw withJob(error, id);
142
+ if (status === "completed") throw error;
142
143
  throw new FieldworkError("JobFailed", `perplexity research ended ${status} with output that is not valid JSON`, {
143
144
  cause: run.original,
144
- jobId: id,
145
145
  provider
146
146
  });
147
147
  }
@@ -297,7 +297,6 @@ const answer = async (raw, question, options) => {
297
297
  });
298
298
  };
299
299
  const startResearch = async (raw, question, o, call) => {
300
- if (o.resume !== void 0) return o.resume;
301
300
  const created = z.parse(AgentStart, await raw.request("POST", "/v1/agent", {
302
301
  creates: true,
303
302
  ...call,
@@ -316,30 +315,32 @@ const startResearch = async (raw, question, o, call) => {
316
315
  };
317
316
  const research = async (raw, question, options) => {
318
317
  const { call, rest: o } = callSettings(options);
319
- const id = await startResearch(raw, question, o, call);
320
- const run = await poll(provider, id, async (request) => {
321
- const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${segment(id)}`, request));
322
- return TERMINAL.has(found.value.status ?? "") ? found : void 0;
318
+ return await runJob(provider, {
319
+ check: async (id, request) => {
320
+ const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${segment(id)}`, request));
321
+ return TERMINAL.has(found.value.status ?? "") ? found : void 0;
322
+ },
323
+ finish: async (run, id) => {
324
+ const { status } = run.value;
325
+ const read = readResponse(run.value);
326
+ if (status === "failed" || !read.text) throw responseError(run, id);
327
+ return compact({
328
+ continuationId: id,
329
+ id,
330
+ meta: responseMeta(run.value),
331
+ output: await checkOutput(o.schema, researchOutput(run, read.text, o.schema), { provider }),
332
+ raw: run.original,
333
+ retrieved: read.retrieved.length > 0 ? read.retrieved : void 0,
334
+ sources: read.cited,
335
+ status: status === "completed" ? "completed" : "partial",
336
+ stopReason: status === "completed" ? void 0 : status
337
+ });
338
+ },
339
+ start: async () => await startResearch(raw, question, o, call)
323
340
  }, {
324
341
  ...call,
325
- interval: o.interval
326
- });
327
- const { status } = run.value;
328
- const read = readResponse(run.value);
329
- if (status === "failed" || !read.text) throw responseError(run, id);
330
- return compact({
331
- continuationId: id,
332
- id,
333
- meta: responseMeta(run.value),
334
- output: await checkOutput(o.schema, researchOutput(run, read.text, o.schema, id), {
335
- jobId: id,
336
- provider
337
- }),
338
- raw: run.original,
339
- retrieved: read.retrieved.length > 0 ? read.retrieved : void 0,
340
- sources: read.cited,
341
- status: status === "completed" ? "completed" : "partial",
342
- stopReason: status === "completed" ? void 0 : status
342
+ interval: o.interval,
343
+ resume: o.resume
343
344
  });
344
345
  };
345
346
  const decide = async (raw, context, questions, options) => {
package/dist/reducto.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { a as refuseLarger, n as documentPart } from "./document-Dpj01mGx.js";
3
- import { i as withJob, t as FieldworkError } from "./errors-Yvk42oZH.js";
4
- import { C as createRawClient, D as segment, E as requireKey, N as meta, O as callSettings, P as parseJson, S as withOriginal, T as readSigned, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as compact, r as arrayOf, s as optionalAnyString, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
3
+ import { t as FieldworkError } from "./errors-Yvk42oZH.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-n8MmaK1x.js";
5
+ import { t as runJob } from "./job-BGTwH3F-.js";
5
6
  import * as z from "zod/mini";
6
7
  // src/adapters/reducto/response.ts
7
8
  /** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
@@ -106,7 +107,6 @@ const provider = "reducto";
106
107
  /** The largest file `/upload` takes, in megabytes. */
107
108
  const MAX_UPLOAD_MB = 100;
108
109
  const startParse = async (raw, document, o, call) => {
109
- if (o.resume !== void 0) return o.resume;
110
110
  refuseLarger(provider, document, MAX_UPLOAD_MB);
111
111
  const form = new FormData();
112
112
  form.set("file", documentPart(document), document.name);
@@ -125,20 +125,19 @@ const startParse = async (raw, document, o, call) => {
125
125
  }));
126
126
  return requireJobId(provider, started.job_id);
127
127
  };
128
- const finished = (found, id) => {
128
+ const finished = (found) => {
129
129
  const { error, reason, status } = found.value;
130
130
  if (status === "Failed") {
131
131
  const why = reason ?? error.message;
132
132
  throw new FieldworkError("JobFailed", `reducto job failed${why === void 0 ? "" : `: ${why}`}`, {
133
133
  cause: found.original,
134
- jobId: id,
135
134
  provider
136
135
  });
137
136
  }
138
137
  return status === "Completed" ? found : void 0;
139
138
  };
140
139
  /** The parse output, fetched from where Reducto put it when it was too large to return. */
141
- const outputOf = async (found, id, options) => {
140
+ const outputOf = async (found, options) => {
142
141
  const output = found.value.result.result;
143
142
  if (output.type === "full") return {
144
143
  output,
@@ -146,54 +145,52 @@ const outputOf = async (found, id, options) => {
146
145
  };
147
146
  if (output.type !== "url") throw new FieldworkError("ProviderError", `reducto returned a result of type ${output.type ?? "(none)"}; Fieldwork reads "full" and "url"`, {
148
147
  cause: found.original,
149
- jobId: id,
150
148
  provider
151
149
  });
152
150
  if (output.url === void 0) throw new FieldworkError("ProviderError", "reducto stored the result without saying where", {
153
151
  cause: found.original,
154
- jobId: id,
155
152
  provider
156
153
  });
157
- try {
158
- const stored = parseJson(provider, await readSigned(provider, output.url, options));
159
- return {
160
- output: z.parse(ParseOutput, stored),
161
- stored
162
- };
163
- } catch (error) {
164
- throw withJob(error, id);
165
- }
154
+ const stored = parseJson(provider, await readSigned(provider, output.url, options));
155
+ return {
156
+ output: z.parse(ParseOutput, stored),
157
+ stored
158
+ };
166
159
  };
167
160
  const parse = async (raw, document, options, fetchImpl) => {
168
161
  const { call, rest: o } = callSettings(options);
169
- const id = await startParse(raw, document, o, call);
170
- const found = await poll(provider, id, async (request) => finished(z.parse(JobResponse, await raw.request("GET", `/job/${segment(id)}`, request)), id), {
162
+ return await runJob(provider, {
163
+ check: async (id, request) => finished(z.parse(JobResponse, await raw.request("GET", `/job/${segment(id)}`, request))),
164
+ finish: async (found, id) => {
165
+ const { output, stored } = await outputOf(found, {
166
+ fetch: fetchImpl,
167
+ signal: call.signal
168
+ });
169
+ if (output.chunks.length === 0) throw new FieldworkError("ProviderError", `reducto finished job ${id} without any chunks of output`, {
170
+ cause: stored ?? found.original,
171
+ provider
172
+ });
173
+ const { usage } = found.value.result;
174
+ return compact({
175
+ blocks: o.blocks === true || o.wordBoxes === true ? documentBlocks(output) : void 0,
176
+ id,
177
+ markdown: output.chunks.map((chunk) => chunk.content ?? "").join("\n\n"),
178
+ meta: meta({
179
+ credits: usage.credits,
180
+ units: { pages: usage.num_pages }
181
+ }),
182
+ pageCount: usage.num_pages,
183
+ raw: stored === void 0 ? found.original : {
184
+ job: found.original,
185
+ stored
186
+ }
187
+ });
188
+ },
189
+ start: async () => await startParse(raw, document, o, call)
190
+ }, {
171
191
  ...call,
172
- interval: o.interval
173
- });
174
- const { output, stored } = await outputOf(found, id, {
175
- fetch: fetchImpl,
176
- signal: call.signal
177
- });
178
- if (output.chunks.length === 0) throw new FieldworkError("ProviderError", `reducto finished job ${id} without any chunks of output`, {
179
- cause: stored ?? found.original,
180
- jobId: id,
181
- provider
182
- });
183
- const { usage } = found.value.result;
184
- return compact({
185
- blocks: o.blocks === true || o.wordBoxes === true ? documentBlocks(output) : void 0,
186
- id,
187
- markdown: output.chunks.map((chunk) => chunk.content ?? "").join("\n\n"),
188
- meta: meta({
189
- credits: usage.credits,
190
- units: { pages: usage.num_pages }
191
- }),
192
- pageCount: usage.num_pages,
193
- raw: stored === void 0 ? found.original : {
194
- job: found.original,
195
- stored
196
- }
192
+ interval: o.interval,
193
+ resume: o.resume
197
194
  });
198
195
  };
199
196
  /**
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-Yvk42oZH.js";
3
- import { C as createRawClient, E as requireKey, N as meta, O as callSettings, R as refuseTogether, a as looseObject, f as optionalNumber, h as optionalString, j as compact, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings } from "./parse-D4SMt-Ip.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-n8MmaK1x.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/serpapi/parse.ts
6
6
  const provider = "serpapi";
package/dist/tavily.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
- import { C as createRawClient, D as segment, E as requireKey, M as hours, N as meta, O as callSettings, S as withOriginal, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as compact, m as optionalScalar, n as anything, r as arrayOf, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, M as compact, N as hours, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, n as anything, r as arrayOf } from "./parse-n8MmaK1x.js";
4
+ import { t as runJob } from "./job-BGTwH3F-.js";
4
5
  import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
6
  import * as z from "zod/mini";
6
7
  // src/adapters/tavily/countries.ts
@@ -399,58 +400,59 @@ const tavily = (config = {}) => {
399
400
  };
400
401
  });
401
402
  if (files && files.length > 5) throw invalidRequest(provider, "research takes up to 5 files");
402
- const id = o.resume ?? requireJobId("tavily", z.parse(ResearchStart, await raw.request("POST", "/research", {
403
- creates: true,
404
- ...call,
405
- body: compact({
406
- citation_format: o.citationFormat,
407
- exclude_domains: o.excludeDomains,
408
- files,
409
- include_domains: o.includeDomains,
410
- input: question,
411
- model: o.model,
412
- output_length: o.outputLength,
413
- output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
414
- stream: false
415
- })
416
- })).request_id);
417
- const { body: run, response } = await poll(provider, id, async (request) => {
418
- const current = await raw.request("GET", `/research/${segment(id)}`, {
419
- ...request,
420
- query: { include_usage: true }
421
- });
422
- const parsed = z.parse(ResearchRun, current);
423
- if (parsed.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
424
- cause: current,
425
- provider
426
- });
427
- return parsed.status === "completed" ? {
428
- body: parsed,
429
- response: current
430
- } : void 0;
403
+ return await runJob(provider, {
404
+ check: async (id, request) => {
405
+ const current = await raw.request("GET", `/research/${segment(id)}`, {
406
+ ...request,
407
+ query: { include_usage: true }
408
+ });
409
+ const parsed = z.parse(ResearchRun, current);
410
+ if (parsed.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
411
+ cause: current,
412
+ provider
413
+ });
414
+ return parsed.status === "completed" ? {
415
+ body: parsed,
416
+ response: current
417
+ } : void 0;
418
+ },
419
+ finish: async ({ body: run, response }, id) => {
420
+ const { content } = run;
421
+ if (content === void 0 || content === null || content === "") throw new FieldworkError("JobFailed", `tavily research ${id} finished without output`, {
422
+ cause: response,
423
+ provider
424
+ });
425
+ return compact({
426
+ id,
427
+ meta: responseMeta(run),
428
+ output: await checkOutput(o.schema, content, { provider }),
429
+ raw: response,
430
+ sources: run.sources.flatMap((source) => source.url === void 0 ? [] : [compact({
431
+ title: source.title,
432
+ url: source.url
433
+ })]),
434
+ status: "completed"
435
+ });
436
+ },
437
+ start: async () => requireJobId(provider, z.parse(ResearchStart, await raw.request("POST", "/research", {
438
+ creates: true,
439
+ ...call,
440
+ body: compact({
441
+ citation_format: o.citationFormat,
442
+ exclude_domains: o.excludeDomains,
443
+ files,
444
+ include_domains: o.includeDomains,
445
+ input: question,
446
+ model: o.model,
447
+ output_length: o.outputLength,
448
+ output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
449
+ stream: false
450
+ })
451
+ })).request_id)
431
452
  }, {
432
453
  ...call,
433
- interval: o.interval
434
- });
435
- const { content } = run;
436
- if (content === void 0 || content === null || content === "") throw new FieldworkError("JobFailed", `tavily research ${id} finished without output`, {
437
- cause: response,
438
- jobId: id,
439
- provider
440
- });
441
- return compact({
442
- id,
443
- meta: responseMeta(run),
444
- output: await checkOutput(o.schema, content, {
445
- jobId: id,
446
- provider
447
- }),
448
- raw: response,
449
- sources: run.sources.flatMap((source) => source.url === void 0 ? [] : [compact({
450
- title: source.title,
451
- url: source.url
452
- })]),
453
- status: "completed"
454
+ interval: o.interval,
455
+ resume: o.resume
454
456
  });
455
457
  },
456
458
  async search(query, options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "One API for web search, page reading, extraction, crawling, answers, research, browser sessions, monitoring and document parsing across Exa, Firecrawl, Tavily, Parallel, Perplexity, Brave, SerpApi, Browserbase, LlamaParse and Reducto.",
5
5
  "keywords": [
6
6
  "agents",