@howells/fieldwork-sdk 0.4.0 → 0.5.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.
@@ -1,89 +1,20 @@
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 { 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";
4
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
5
  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
6
+ // src/adapters/perplexity/parse.ts
74
7
  const provider = "perplexity";
75
- const MAX_QUERIES = 5;
76
8
  const TERMINAL = /* @__PURE__ */ new Set([
77
9
  "completed",
78
10
  "failed",
79
11
  "incomplete",
80
12
  "cancelled"
81
13
  ]);
82
- const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
83
14
  const usDate = (name, date) => {
84
15
  if (date === void 0) return date;
85
16
  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}"`);
17
+ if (!match?.groups) throw invalidRequest(provider, `${name} must be YYYY-MM-DD, got "${date}"`);
87
18
  const { year, month, day } = match.groups;
88
19
  return `${month}/${day}/${year}`;
89
20
  };
@@ -182,13 +113,139 @@ const responseFormat = (schema) => schema ? {
182
113
  const decisionState = (context) => {
183
114
  if (typeof context === "string" || typeof context === "object" && context) return context;
184
115
  if (typeof context === "number" || typeof context === "boolean") return String(context);
185
- throw invalid("perplexity decide needs a context: a string, object or array");
116
+ throw invalidRequest(provider, "decide needs a context: a string, object or array");
117
+ };
118
+ const researchSetup = (o) => {
119
+ if (o.models && (o.models.length < 1 || o.models.length > 5)) throw invalidRequest(provider, "models takes one to five models");
120
+ const searchTool = webSearchTool(o);
121
+ if (o.effort === void 0 && (o.model !== void 0 || o.models !== void 0)) return {
122
+ max_steps: o.maxSteps ?? 10,
123
+ model: o.model,
124
+ models: o.models,
125
+ tools: [searchTool ?? { type: "web_search" }, { type: "fetch_url" }]
126
+ };
127
+ return {
128
+ effort: o.effort ?? "high",
129
+ max_steps: o.maxSteps,
130
+ model: o.model,
131
+ models: o.models,
132
+ tools: searchTool ? [searchTool] : void 0
133
+ };
134
+ };
135
+ const researchOutput = (run, reply, schema, id) => {
136
+ if (!schema) return reply;
137
+ const { status } = run.value;
138
+ try {
139
+ return parseJson(provider, reply);
140
+ } catch (error) {
141
+ if (status === "completed") throw withJob(error, id);
142
+ throw new FieldworkError("JobFailed", `perplexity research ended ${status} with output that is not valid JSON`, {
143
+ cause: run.original,
144
+ jobId: id,
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,8 @@ 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;
300
+ if (o.resume !== void 0) return o.resume;
261
301
  const created = z.parse(AgentStart, await raw.request("POST", "/v1/agent", {
262
302
  creates: true,
263
303
  ...call,
@@ -274,30 +314,15 @@ const startResearch = async (raw, question, o, call) => {
274
314
  }));
275
315
  return requireJobId(provider, created.id);
276
316
  };
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
317
  const research = async (raw, question, options) => {
292
318
  const { call, rest: o } = callSettings(options);
293
319
  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 }));
320
+ const run = await poll(provider, id, async (request) => {
321
+ const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${segment(id)}`, request));
296
322
  return TERMINAL.has(found.value.status ?? "") ? found : void 0;
297
323
  }, {
298
- interval: o.interval,
299
- signal: call.signal,
300
- timeout: call.timeout
324
+ ...call,
325
+ interval: o.interval
301
326
  });
302
327
  const { status } = run.value;
303
328
  const read = readResponse(run.value);
@@ -317,33 +342,6 @@ const research = async (raw, question, options) => {
317
342
  stopReason: status === "completed" ? void 0 : status
318
343
  });
319
344
  };
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
345
- });
346
- };
347
345
  const decide = async (raw, context, questions, options) => {
348
346
  const { call, rest: o } = callSettings(options);
349
347
  const response = await raw.request("POST", "/v1/decisions", {
@@ -371,6 +369,11 @@ const decide = async (raw, context, questions, options) => {
371
369
  raw: response
372
370
  };
373
371
  };
372
+ /**
373
+ * An adapter for Perplexity: search, answer, research and decide. Pass it to `new Fieldwork({ adapter })`.
374
+ *
375
+ * Throws `Unauthorized` when neither `apiKey` nor `PERPLEXITY_API_KEY` is set.
376
+ */
374
377
  const perplexity = (config = {}) => {
375
378
  const raw = createRawClient({
376
379
  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,220 @@
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
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";
5
+ import * as z from "zod/mini";
6
+ // src/adapters/reducto/response.ts
7
+ /** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
8
+ const FractionBox = looseObject({
9
+ height: optionalNumber,
10
+ left: optionalNumber,
11
+ original_page: optionalNumber,
12
+ page: optionalNumber,
13
+ top: optionalNumber,
14
+ width: optionalNumber
15
+ });
16
+ const Block = looseObject({
17
+ bbox: FractionBox,
18
+ content: optionalAnyString,
19
+ extra: looseObject({
20
+ cell_citations: arrayOf(looseObject({
21
+ bbox: FractionBox,
22
+ col_idx: arrayOf(z.number()),
23
+ row_idx: arrayOf(z.number()),
24
+ text: optionalAnyString
25
+ })),
26
+ word_citations: arrayOf(looseObject({
27
+ bbox: FractionBox,
28
+ text: optionalAnyString
29
+ }))
30
+ }),
31
+ type: optionalString
32
+ });
33
+ /** The parse output: in full, or, when large, a URL to fetch it from. */
34
+ const ParseOutput = looseObject({
35
+ chunks: arrayOf(looseObject({
36
+ blocks: arrayOf(Block),
37
+ content: optionalAnyString
38
+ })),
39
+ type: optionalString,
40
+ url: optionalString
41
+ });
42
+ /** `POST /upload`. */
43
+ const UploadResponse = looseObject({ file_id: withOriginal(optionalString) });
44
+ /** `POST /parse_async`. */
45
+ const ParseStart = looseObject({ job_id: withOriginal(optionalId) });
46
+ /** `GET /job/{id}`, as it arrived beside the value read from it. */
47
+ const JobResponse = withOriginal(looseObject({
48
+ error: looseObject({ message: optionalString }),
49
+ reason: optionalString,
50
+ result: looseObject({
51
+ result: ParseOutput,
52
+ usage: looseObject({
53
+ credits: optionalNumber,
54
+ num_pages: optionalNumber
55
+ })
56
+ }),
57
+ status: optionalString
58
+ }));
59
+ const boxOf = (box) => {
60
+ const { height, left, top, width } = box;
61
+ if (left === void 0 || top === void 0 || width === void 0 || height === void 0) return;
62
+ return {
63
+ height,
64
+ left,
65
+ top,
66
+ width
67
+ };
68
+ };
69
+ const cellOf = (cell) => {
70
+ const row = Math.min(...cell.row_idx);
71
+ const column = Math.min(...cell.col_idx);
72
+ if (!Number.isFinite(row) || !Number.isFinite(column)) return [];
73
+ return [compact({
74
+ box: boxOf(cell.bbox),
75
+ column,
76
+ columnSpan: cell.col_idx.length > 1 ? cell.col_idx.length : void 0,
77
+ row,
78
+ rowSpan: cell.row_idx.length > 1 ? cell.row_idx.length : void 0,
79
+ text: cell.text ?? ""
80
+ })];
81
+ };
82
+ const blockOf = (block) => {
83
+ const page = block.bbox.original_page ?? block.bbox.page;
84
+ if (page === void 0) return [];
85
+ const words = block.extra.word_citations.flatMap((word) => {
86
+ const box = boxOf(word.bbox);
87
+ return box === void 0 ? [] : [{
88
+ box,
89
+ text: word.text ?? ""
90
+ }];
91
+ });
92
+ const cells = block.extra.cell_citations.flatMap((cell) => cellOf(cell));
93
+ return [compact({
94
+ box: boxOf(block.bbox),
95
+ cells: cells.length > 0 ? cells : void 0,
96
+ page,
97
+ text: block.content ?? "",
98
+ type: block.type ?? "unknown",
99
+ words: words.length > 0 ? words : void 0
100
+ })];
101
+ };
102
+ /** Every chunk's blocks, in order, each on the file's own page number. */
103
+ const documentBlocks = (output) => output.chunks.flatMap((chunk) => chunk.blocks.flatMap((block) => blockOf(block)));
104
+ // src/adapters/reducto.ts
105
+ const provider = "reducto";
106
+ /** The largest file `/upload` takes, in megabytes. */
107
+ const MAX_UPLOAD_MB = 100;
108
+ const startParse = async (raw, document, o, call) => {
109
+ if (o.resume !== void 0) return o.resume;
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, id) => {
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
+ jobId: id,
135
+ provider
136
+ });
137
+ }
138
+ return status === "Completed" ? found : void 0;
139
+ };
140
+ /** The parse output, fetched from where Reducto put it when it was too large to return. */
141
+ const outputOf = async (found, id, options) => {
142
+ const output = found.value.result.result;
143
+ if (output.type === "full") return {
144
+ output,
145
+ stored: void 0
146
+ };
147
+ if (output.type !== "url") throw new FieldworkError("ProviderError", `reducto returned a result of type ${output.type ?? "(none)"}; Fieldwork reads "full" and "url"`, {
148
+ cause: found.original,
149
+ jobId: id,
150
+ provider
151
+ });
152
+ if (output.url === void 0) throw new FieldworkError("ProviderError", "reducto stored the result without saying where", {
153
+ cause: found.original,
154
+ jobId: id,
155
+ provider
156
+ });
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
+ }
166
+ };
167
+ const parse = async (raw, document, options, fetchImpl) => {
168
+ 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), {
171
+ ...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
+ }
197
+ });
198
+ };
199
+ /**
200
+ * An adapter for Reducto: parse. Pass it to `new Fieldwork({ adapter })`.
201
+ *
202
+ * Throws `Unauthorized` when neither `apiKey` nor `REDUCTO_API_KEY` is set.
203
+ */
204
+ const reducto = (config = {}) => {
205
+ const raw = createRawClient({
206
+ baseUrl: config.baseUrl ?? "https://platform.reducto.ai",
207
+ fetch: config.fetch,
208
+ headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "REDUCTO_API_KEY")}` },
209
+ provider,
210
+ retries: config.retries
211
+ });
212
+ return defineAdapter({
213
+ name: provider,
214
+ operations: { async parse(document, options) {
215
+ return await parse(raw, document, options, config.fetch);
216
+ } },
217
+ raw
218
+ });
219
+ };
220
+ 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 };