@howells/fieldwork-sdk 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,89 +1,21 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { C as createRawClient, D as citationOf, E as callSettings, I as refuseTogether, L as requireJobId, M as parseJson, R as uniqueCitations, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as meta, k as compact, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, w as poll, y as sourceShape } from "./parse-CxOri73y.js";
4
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-teOy7Od-.js";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { 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";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
6
  import * as z from "zod/mini";
6
- // src/adapters/perplexity/response.ts
7
- /** `/search`. */
8
- const SearchResponse = looseObject({
9
- id: optionalScalar,
10
- results: arrayOf(looseObject({
11
- date: optionalString,
12
- last_updated: optionalString,
13
- snippet: optionalString,
14
- title: optionalString,
15
- url: optionalString
16
- }))
17
- });
18
- /** An annotation on message text. Its `type` is kept as it arrived, since only an absent one or `url_citation` counts as a citation. */
19
- const Annotation = looseObject({
20
- ...sourceShape,
21
- type: anything
22
- });
23
- const MessagePart = looseObject({
24
- annotations: arrayOf(Annotation),
25
- text: optionalString
26
- });
27
- const OutputEntry = looseObject({
28
- content: arrayOf(MessagePart),
29
- contents: arrayOf(Source),
30
- results: arrayOf(Source),
31
- type: optionalString
32
- });
33
- /** A response of the Agent API, whole. Its `id` is read as a continuation id (a non-empty string) and as a request id (a string, number or boolean). */
34
- const Agent = looseObject({
35
- error: looseObject({
36
- message: optionalString,
37
- type: optionalString
38
- }),
39
- id: both(optionalString, optionalScalar),
40
- output: arrayOf(OutputEntry),
41
- status: optionalString,
42
- usage: looseObject({
43
- cost: looseObject({ total_cost: optionalNumber }),
44
- input_tokens: optionalNumber,
45
- input_tokens_details: looseObject({
46
- cache_creation_input_tokens: optionalNumber,
47
- cache_read_input_tokens: optionalNumber
48
- }),
49
- output_tokens: optionalNumber,
50
- output_tokens_details: looseObject({ reasoning_tokens: optionalNumber }),
51
- total_tokens: optionalNumber
52
- })
53
- });
54
- /** An Agent API response beside the response as it arrived. */
55
- const AgentRun = withOriginal(Agent);
56
- /** The reply to starting a run: its id as a string, and as it arrived. */
57
- const AgentStart = looseObject({ id: withOriginal(optionalId) });
58
- const DecisionAnswer = looseObject({
59
- choice: optionalString,
60
- confidence: optionalNumber,
61
- noul: optionalNumber,
62
- probabilities: recordOf(optionalNumber),
63
- type: optionalString
64
- });
65
- /** `/v1/decisions`. */
66
- const DecisionsResponse = looseObject({
67
- answers: recordOf(DecisionAnswer),
68
- usage: looseObject({
69
- input_tokens: optionalNumber,
70
- output_tokens: optionalNumber
71
- })
72
- });
73
- // src/adapters/perplexity.ts
7
+ // src/adapters/perplexity/parse.ts
74
8
  const provider = "perplexity";
75
- const MAX_QUERIES = 5;
76
9
  const TERMINAL = /* @__PURE__ */ new Set([
77
10
  "completed",
78
11
  "failed",
79
12
  "incomplete",
80
13
  "cancelled"
81
14
  ]);
82
- const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
83
15
  const usDate = (name, date) => {
84
16
  if (date === void 0) return date;
85
17
  const match = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u.exec(date);
86
- if (!match?.groups) throw invalid(`${name} must be YYYY-MM-DD, got "${date}"`);
18
+ if (!match?.groups) throw invalidRequest(provider, `${name} must be YYYY-MM-DD, got "${date}"`);
87
19
  const { year, month, day } = match.groups;
88
20
  return `${month}/${day}/${year}`;
89
21
  };
@@ -182,13 +114,138 @@ const responseFormat = (schema) => schema ? {
182
114
  const decisionState = (context) => {
183
115
  if (typeof context === "string" || typeof context === "object" && context) return context;
184
116
  if (typeof context === "number" || typeof context === "boolean") return String(context);
185
- throw invalid("perplexity decide needs a context: a string, object or array");
117
+ throw invalidRequest(provider, "decide needs a context: a string, object or array");
118
+ };
119
+ const researchSetup = (o) => {
120
+ if (o.models && (o.models.length < 1 || o.models.length > 5)) throw invalidRequest(provider, "models takes one to five models");
121
+ const searchTool = webSearchTool(o);
122
+ if (o.effort === void 0 && (o.model !== void 0 || o.models !== void 0)) return {
123
+ max_steps: o.maxSteps ?? 10,
124
+ model: o.model,
125
+ models: o.models,
126
+ tools: [searchTool ?? { type: "web_search" }, { type: "fetch_url" }]
127
+ };
128
+ return {
129
+ effort: o.effort ?? "high",
130
+ max_steps: o.maxSteps,
131
+ model: o.model,
132
+ models: o.models,
133
+ tools: searchTool ? [searchTool] : void 0
134
+ };
135
+ };
136
+ const researchOutput = (run, reply, schema) => {
137
+ if (!schema) return reply;
138
+ const { status } = run.value;
139
+ try {
140
+ return parseJson(provider, reply);
141
+ } catch (error) {
142
+ if (status === "completed") throw error;
143
+ throw new FieldworkError("JobFailed", `perplexity research ended ${status} with output that is not valid JSON`, {
144
+ cause: run.original,
145
+ provider
146
+ });
147
+ }
186
148
  };
149
+ const decisionQuestion = (question) => {
150
+ if (question.type === "yesno") return {
151
+ instructions: question.question,
152
+ type: "noul"
153
+ };
154
+ if (question.type === "choice") return {
155
+ criteria: Object.fromEntries(question.choices.map((choice) => [choice, null])),
156
+ instructions: question.question,
157
+ type: "choice"
158
+ };
159
+ return {
160
+ criteria: Object.values(question.scale),
161
+ instructions: question.question,
162
+ type: "score"
163
+ };
164
+ };
165
+ const decisionAnswer = (found, scores) => {
166
+ if (found.type === "noul") return compact({ probability: found.noul });
167
+ let probabilities = Object.fromEntries(Object.entries(found.probabilities).filter((entry) => entry[1] !== void 0));
168
+ if (found.type === "score") probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores?.[Number(index)] ?? index, probability]));
169
+ const top = Object.entries(probabilities).toSorted((a, b) => b[1] - a[1])[0]?.[0];
170
+ return compact({
171
+ choice: found.choice ?? top,
172
+ confidence: found.confidence,
173
+ probabilities
174
+ });
175
+ };
176
+ // src/adapters/perplexity/response.ts
177
+ /** `/search`. */
178
+ const SearchResponse = looseObject({
179
+ id: optionalScalar,
180
+ results: arrayOf(looseObject({
181
+ date: optionalString,
182
+ last_updated: optionalString,
183
+ snippet: optionalString,
184
+ title: optionalString,
185
+ url: optionalString
186
+ }))
187
+ });
188
+ /** An annotation on message text. Its `type` is kept as it arrived, since only an absent one or `url_citation` counts as a citation. */
189
+ const Annotation = looseObject({
190
+ ...sourceShape,
191
+ type: anything
192
+ });
193
+ const MessagePart = looseObject({
194
+ annotations: arrayOf(Annotation),
195
+ text: optionalString
196
+ });
197
+ const OutputEntry = looseObject({
198
+ content: arrayOf(MessagePart),
199
+ contents: arrayOf(Source),
200
+ results: arrayOf(Source),
201
+ type: optionalString
202
+ });
203
+ /** A response of the Agent API, whole. Its `id` is read as a continuation id (a non-empty string) and as a request id (a string, number or boolean). */
204
+ const Agent = looseObject({
205
+ error: looseObject({
206
+ message: optionalString,
207
+ type: optionalString
208
+ }),
209
+ id: both(optionalString, optionalScalar),
210
+ output: arrayOf(OutputEntry),
211
+ status: optionalString,
212
+ usage: looseObject({
213
+ cost: looseObject({ total_cost: optionalNumber }),
214
+ input_tokens: optionalNumber,
215
+ input_tokens_details: looseObject({
216
+ cache_creation_input_tokens: optionalNumber,
217
+ cache_read_input_tokens: optionalNumber
218
+ }),
219
+ output_tokens: optionalNumber,
220
+ output_tokens_details: looseObject({ reasoning_tokens: optionalNumber }),
221
+ total_tokens: optionalNumber
222
+ })
223
+ });
224
+ /** An Agent API response beside the response as it arrived. */
225
+ const AgentRun = withOriginal(Agent);
226
+ /** The reply to starting a run: its id as a string, and as it arrived. */
227
+ const AgentStart = looseObject({ id: withOriginal(optionalId) });
228
+ const DecisionAnswer = looseObject({
229
+ choice: optionalString,
230
+ confidence: optionalNumber,
231
+ noul: optionalNumber,
232
+ probabilities: recordOf(optionalNumber),
233
+ type: optionalString
234
+ });
235
+ /** `/v1/decisions`. */
236
+ const DecisionsResponse = looseObject({
237
+ answers: recordOf(DecisionAnswer),
238
+ usage: looseObject({
239
+ input_tokens: optionalNumber,
240
+ output_tokens: optionalNumber
241
+ })
242
+ });
243
+ // src/adapters/perplexity.ts
187
244
  const search = async (raw, query, options) => {
188
245
  const { call, rest: o } = callSettings(options);
189
246
  const queries = [query, ...o.queries ?? []];
190
- if (queries.length > MAX_QUERIES) throw invalid(`perplexity search takes at most ${MAX_QUERIES} queries in one request, got ${queries.length}`);
191
- if (o.limit !== void 0 && o.limit > 20 && o.searchType !== "people") throw invalid("perplexity search returns at most 20 results unless searchType is \"people\"");
247
+ if (queries.length > 5) throw invalidRequest(provider, `search takes at most 5 queries in one request, got ${queries.length}`);
248
+ if (o.limit !== void 0 && o.limit > 20 && o.searchType !== "people") throw invalidRequest(provider, "search returns at most 20 results unless searchType is \"people\"");
192
249
  const response = await raw.request("POST", "/search", {
193
250
  ...call,
194
251
  body: compact({
@@ -239,25 +296,7 @@ const answer = async (raw, question, options) => {
239
296
  raw: run.original
240
297
  });
241
298
  };
242
- const researchSetup = (o) => {
243
- if (o.models && (o.models.length < 1 || o.models.length > 5)) throw invalid("perplexity models takes one to five models");
244
- const searchTool = webSearchTool(o);
245
- if (o.effort === void 0 && (o.model !== void 0 || o.models !== void 0)) return {
246
- max_steps: o.maxSteps ?? 10,
247
- model: o.model,
248
- models: o.models,
249
- tools: [searchTool ?? { type: "web_search" }, { type: "fetch_url" }]
250
- };
251
- return {
252
- effort: o.effort ?? "high",
253
- max_steps: o.maxSteps,
254
- model: o.model,
255
- models: o.models,
256
- tools: searchTool ? [searchTool] : void 0
257
- };
258
- };
259
299
  const startResearch = async (raw, question, o, call) => {
260
- if (o.resume !== void 0 && o.resume !== "") return o.resume;
261
300
  const created = z.parse(AgentStart, await raw.request("POST", "/v1/agent", {
262
301
  creates: true,
263
302
  ...call,
@@ -274,74 +313,34 @@ const startResearch = async (raw, question, o, call) => {
274
313
  }));
275
314
  return requireJobId(provider, created.id);
276
315
  };
277
- const researchOutput = (run, reply, schema, id) => {
278
- if (!schema) return reply;
279
- const { status } = run.value;
280
- try {
281
- return parseJson(provider, reply);
282
- } catch (error) {
283
- if (status === "completed") throw error;
284
- throw new FieldworkError("JobFailed", `perplexity research ended ${status} with output that is not valid JSON`, {
285
- cause: run.original,
286
- jobId: id,
287
- provider
288
- });
289
- }
290
- };
291
316
  const research = async (raw, question, options) => {
292
317
  const { call, rest: o } = callSettings(options);
293
- const id = await startResearch(raw, question, o, call);
294
- const run = await poll(provider, id, async () => {
295
- const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${encodeURIComponent(id)}`, { signal: call.signal }));
296
- 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)
297
340
  }, {
341
+ ...call,
298
342
  interval: o.interval,
299
- signal: call.signal,
300
- timeout: call.timeout
301
- });
302
- const { status } = run.value;
303
- const read = readResponse(run.value);
304
- if (status === "failed" || !read.text) throw responseError(run, id);
305
- return compact({
306
- continuationId: id,
307
- id,
308
- meta: responseMeta(run.value),
309
- output: await checkOutput(o.schema, researchOutput(run, read.text, o.schema, id), {
310
- jobId: id,
311
- provider
312
- }),
313
- raw: run.original,
314
- retrieved: read.retrieved.length > 0 ? read.retrieved : void 0,
315
- sources: read.cited,
316
- status: status === "completed" ? "completed" : "partial",
317
- stopReason: status === "completed" ? void 0 : status
318
- });
319
- };
320
- const decisionQuestion = (question) => {
321
- if (question.type === "yesno") return {
322
- instructions: question.question,
323
- type: "noul"
324
- };
325
- if (question.type === "choice") return {
326
- criteria: Object.fromEntries(question.choices.map((choice) => [choice, null])),
327
- instructions: question.question,
328
- type: "choice"
329
- };
330
- return {
331
- criteria: Object.values(question.scale),
332
- instructions: question.question,
333
- type: "score"
334
- };
335
- };
336
- const decisionAnswer = (found, scores) => {
337
- if (found.type === "noul") return compact({ probability: found.noul });
338
- let probabilities = Object.fromEntries(Object.entries(found.probabilities).filter((entry) => entry[1] !== void 0));
339
- if (found.type === "score") probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores?.[Number(index)] ?? index, probability]));
340
- const top = Object.entries(probabilities).toSorted((a, b) => b[1] - a[1])[0]?.[0];
341
- return compact({
342
- choice: found.choice ?? top,
343
- confidence: found.confidence,
344
- probabilities
343
+ resume: o.resume
345
344
  });
346
345
  };
347
346
  const decide = async (raw, context, questions, options) => {
@@ -371,6 +370,11 @@ const decide = async (raw, context, questions, options) => {
371
370
  raw: response
372
371
  };
373
372
  };
373
+ /**
374
+ * An adapter for Perplexity: search, answer, research and decide. Pass it to `new Fieldwork({ adapter })`.
375
+ *
376
+ * Throws `Unauthorized` when neither `apiKey` nor `PERPLEXITY_API_KEY` is set.
377
+ */
374
378
  const perplexity = (config = {}) => {
375
379
  const raw = createRawClient({
376
380
  baseUrl: config.baseUrl ?? "https://api.perplexity.ai",
@@ -0,0 +1,31 @@
1
+ import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-BgdfLBs-.js";
2
+ export interface ReductoConfig {
3
+ /** Defaults to the REDUCTO_API_KEY environment variable. */
4
+ apiKey?: string;
5
+ baseUrl?: string;
6
+ fetch?: typeof fetch;
7
+ /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
8
+ retries?: number;
9
+ }
10
+ export interface ReductoParseOptions extends CallOptions {
11
+ /** Return layout blocks with positions. */
12
+ blocks?: boolean;
13
+ /** Also return where each word and table cell sits in each block. Returns blocks too. */
14
+ wordBoxes?: boolean;
15
+ /**
16
+ * The id of a job from an error's `jobId`; waits for it instead of starting
17
+ * another. Reducto keeps a job's result for about 12 hours.
18
+ */
19
+ resume?: string;
20
+ /** Milliseconds between checks. Defaults to 2000. */
21
+ interval?: number;
22
+ }
23
+ export interface ReductoOperations {
24
+ parse: (document: DocumentInput, options?: ReductoParseOptions) => Promise<ParsedDocument>;
25
+ }
26
+ /**
27
+ * An adapter for Reducto: parse. Pass it to `new Fieldwork({ adapter })`.
28
+ *
29
+ * Throws `Unauthorized` when neither `apiKey` nor `REDUCTO_API_KEY` is set.
30
+ */
31
+ export declare const reducto: (config?: ReductoConfig) => Adapter<"reducto", ReductoOperations, RawClient>;
@@ -0,0 +1,217 @@
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { a as refuseLarger, n as documentPart } from "./document-Dpj01mGx.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";
6
+ import * as z from "zod/mini";
7
+ // src/adapters/reducto/response.ts
8
+ /** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
9
+ const FractionBox = looseObject({
10
+ height: optionalNumber,
11
+ left: optionalNumber,
12
+ original_page: optionalNumber,
13
+ page: optionalNumber,
14
+ top: optionalNumber,
15
+ width: optionalNumber
16
+ });
17
+ const Block = looseObject({
18
+ bbox: FractionBox,
19
+ content: optionalAnyString,
20
+ extra: looseObject({
21
+ cell_citations: arrayOf(looseObject({
22
+ bbox: FractionBox,
23
+ col_idx: arrayOf(z.number()),
24
+ row_idx: arrayOf(z.number()),
25
+ text: optionalAnyString
26
+ })),
27
+ word_citations: arrayOf(looseObject({
28
+ bbox: FractionBox,
29
+ text: optionalAnyString
30
+ }))
31
+ }),
32
+ type: optionalString
33
+ });
34
+ /** The parse output: in full, or, when large, a URL to fetch it from. */
35
+ const ParseOutput = looseObject({
36
+ chunks: arrayOf(looseObject({
37
+ blocks: arrayOf(Block),
38
+ content: optionalAnyString
39
+ })),
40
+ type: optionalString,
41
+ url: optionalString
42
+ });
43
+ /** `POST /upload`. */
44
+ const UploadResponse = looseObject({ file_id: withOriginal(optionalString) });
45
+ /** `POST /parse_async`. */
46
+ const ParseStart = looseObject({ job_id: withOriginal(optionalId) });
47
+ /** `GET /job/{id}`, as it arrived beside the value read from it. */
48
+ const JobResponse = withOriginal(looseObject({
49
+ error: looseObject({ message: optionalString }),
50
+ reason: optionalString,
51
+ result: looseObject({
52
+ result: ParseOutput,
53
+ usage: looseObject({
54
+ credits: optionalNumber,
55
+ num_pages: optionalNumber
56
+ })
57
+ }),
58
+ status: optionalString
59
+ }));
60
+ const boxOf = (box) => {
61
+ const { height, left, top, width } = box;
62
+ if (left === void 0 || top === void 0 || width === void 0 || height === void 0) return;
63
+ return {
64
+ height,
65
+ left,
66
+ top,
67
+ width
68
+ };
69
+ };
70
+ const cellOf = (cell) => {
71
+ const row = Math.min(...cell.row_idx);
72
+ const column = Math.min(...cell.col_idx);
73
+ if (!Number.isFinite(row) || !Number.isFinite(column)) return [];
74
+ return [compact({
75
+ box: boxOf(cell.bbox),
76
+ column,
77
+ columnSpan: cell.col_idx.length > 1 ? cell.col_idx.length : void 0,
78
+ row,
79
+ rowSpan: cell.row_idx.length > 1 ? cell.row_idx.length : void 0,
80
+ text: cell.text ?? ""
81
+ })];
82
+ };
83
+ const blockOf = (block) => {
84
+ const page = block.bbox.original_page ?? block.bbox.page;
85
+ if (page === void 0) return [];
86
+ const words = block.extra.word_citations.flatMap((word) => {
87
+ const box = boxOf(word.bbox);
88
+ return box === void 0 ? [] : [{
89
+ box,
90
+ text: word.text ?? ""
91
+ }];
92
+ });
93
+ const cells = block.extra.cell_citations.flatMap((cell) => cellOf(cell));
94
+ return [compact({
95
+ box: boxOf(block.bbox),
96
+ cells: cells.length > 0 ? cells : void 0,
97
+ page,
98
+ text: block.content ?? "",
99
+ type: block.type ?? "unknown",
100
+ words: words.length > 0 ? words : void 0
101
+ })];
102
+ };
103
+ /** Every chunk's blocks, in order, each on the file's own page number. */
104
+ const documentBlocks = (output) => output.chunks.flatMap((chunk) => chunk.blocks.flatMap((block) => blockOf(block)));
105
+ // src/adapters/reducto.ts
106
+ const provider = "reducto";
107
+ /** The largest file `/upload` takes, in megabytes. */
108
+ const MAX_UPLOAD_MB = 100;
109
+ const startParse = async (raw, document, o, call) => {
110
+ refuseLarger(provider, document, MAX_UPLOAD_MB);
111
+ const form = new FormData();
112
+ form.set("file", documentPart(document), document.name);
113
+ const uploaded = z.parse(UploadResponse, await raw.request("POST", "/upload", {
114
+ creates: true,
115
+ ...call,
116
+ form
117
+ }));
118
+ const started = z.parse(ParseStart, await raw.request("POST", "/parse_async", {
119
+ creates: true,
120
+ ...call,
121
+ body: compact({
122
+ input: requireJobId(provider, uploaded.file_id),
123
+ settings: o.wordBoxes === true ? { return_citations: true } : void 0
124
+ })
125
+ }));
126
+ return requireJobId(provider, started.job_id);
127
+ };
128
+ const finished = (found) => {
129
+ const { error, reason, status } = found.value;
130
+ if (status === "Failed") {
131
+ const why = reason ?? error.message;
132
+ throw new FieldworkError("JobFailed", `reducto job failed${why === void 0 ? "" : `: ${why}`}`, {
133
+ cause: found.original,
134
+ provider
135
+ });
136
+ }
137
+ return status === "Completed" ? found : void 0;
138
+ };
139
+ /** The parse output, fetched from where Reducto put it when it was too large to return. */
140
+ const outputOf = async (found, options) => {
141
+ const output = found.value.result.result;
142
+ if (output.type === "full") return {
143
+ output,
144
+ stored: void 0
145
+ };
146
+ if (output.type !== "url") throw new FieldworkError("ProviderError", `reducto returned a result of type ${output.type ?? "(none)"}; Fieldwork reads "full" and "url"`, {
147
+ cause: found.original,
148
+ provider
149
+ });
150
+ if (output.url === void 0) throw new FieldworkError("ProviderError", "reducto stored the result without saying where", {
151
+ cause: found.original,
152
+ provider
153
+ });
154
+ const stored = parseJson(provider, await readSigned(provider, output.url, options));
155
+ return {
156
+ output: z.parse(ParseOutput, stored),
157
+ stored
158
+ };
159
+ };
160
+ const parse = async (raw, document, options, fetchImpl) => {
161
+ const { call, rest: o } = callSettings(options);
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
+ }, {
191
+ ...call,
192
+ interval: o.interval,
193
+ resume: o.resume
194
+ });
195
+ };
196
+ /**
197
+ * An adapter for Reducto: parse. Pass it to `new Fieldwork({ adapter })`.
198
+ *
199
+ * Throws `Unauthorized` when neither `apiKey` nor `REDUCTO_API_KEY` is set.
200
+ */
201
+ const reducto = (config = {}) => {
202
+ const raw = createRawClient({
203
+ baseUrl: config.baseUrl ?? "https://platform.reducto.ai",
204
+ fetch: config.fetch,
205
+ headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "REDUCTO_API_KEY")}` },
206
+ provider,
207
+ retries: config.retries
208
+ });
209
+ return defineAdapter({
210
+ name: provider,
211
+ operations: { async parse(document, options) {
212
+ return await parse(raw, document, options, config.fetch);
213
+ } },
214
+ raw
215
+ });
216
+ };
217
+ export { reducto };
@@ -1,4 +1,4 @@
1
- import { A as JsonSchema } from "./adapter-CDY8qczv.js";
1
+ import { M as JsonSchema } from "./adapter-BgdfLBs-.js";
2
2
  /** Vendor-specific parameters a schema library may accept. */
3
3
  type LibraryOptions = JsonSchema;
4
4
  /** The path segment interface of an issue. */
@@ -1,4 +1,4 @@
1
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
1
+ import { t as FieldworkError } from "./errors-Yvk42oZH.js";
2
2
  // src/schema.ts
3
3
  const isStandard = (schema) => "~standard" in schema;
4
4
  /**
package/dist/serpapi.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { W as Recency, a as RawClient, f as CallOptions, k as ImageSearch, q as SearchResponse, s as AccountUsage, t as Adapter } from "./adapter-CDY8qczv.js";
1
+ import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-BgdfLBs-.js";
2
2
  import "./util-DhYr1OS3.js";
3
3
  interface SerpApiConfig {
4
4
  /** Defaults to the SERPAPI_API_KEY environment variable. */
@@ -171,5 +171,10 @@ interface SerpApiOperations {
171
171
  images: (query: string, options?: SerpApiImagesOptions) => Promise<ImageSearch>;
172
172
  usage: (options?: CallOptions) => Promise<AccountUsage>;
173
173
  }
174
+ /**
175
+ * An adapter for SerpApi: search, images and usage. Pass it to `new Fieldwork({ adapter })`.
176
+ *
177
+ * Throws `Unauthorized` when neither `apiKey` nor `SERPAPI_API_KEY` is set.
178
+ */
174
179
  export declare const serpapi: (config?: SerpApiConfig) => Adapter<"serpapi", SerpApiOperations, RawClient>;
175
180
  export type { SerpApiBingOptions, SerpApiConfig, SerpApiDuckDuckGoOptions, SerpApiEngine, SerpApiGoogleOptions, SerpApiImagesOptions, SerpApiMapsOptions, SerpApiNewsOptions, SerpApiOperations, SerpApiPatentsOptions, SerpApiScholarOptions, SerpApiSearchOptions, SerpApiShoppingOptions };