@howells/fieldwork-sdk 0.3.1 → 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.
package/dist/tools.js CHANGED
@@ -1,8 +1,6 @@
1
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
1
+ import { t as FieldworkError } from "./errors-Yvk42oZH.js";
2
2
  import { t as CAPABILITIES } from "./types-CnomnF-6.js";
3
3
  // src/tool-specs/schema.ts
4
- /** A schema as plain JSON Schema, for clients. */
5
- const toJsonSchema = (schema) => ({ ...schema });
6
4
  const described = (schema, description) => description === void 0 ? schema : {
7
5
  ...schema,
8
6
  description
@@ -92,7 +90,21 @@ const publishedBefore = (providers) => ({
92
90
  providers,
93
91
  schema: date("Only pages published before this date, YYYY-MM-DD.")
94
92
  });
95
- const RECENCY_NOTE = "Not together with publishedAfter or publishedBefore.";
93
+ /** The providers whose adapters refuse recency with a date bound, as each one's API does. */
94
+ const RECENCY_REFUSERS = /* @__PURE__ */ new Map([
95
+ ["brave", "Brave"],
96
+ ["firecrawl", "Firecrawl"],
97
+ ["serpapi", "SerpApi"]
98
+ ]);
99
+ /** Names the refusers among `providers`, so a model is told only what applies. */
100
+ const recencyNote = (providers) => {
101
+ const names = providers.flatMap((name) => {
102
+ const label = RECENCY_REFUSERS.get(name);
103
+ return label === void 0 ? [] : [label];
104
+ });
105
+ if (names.length === 0) return "";
106
+ return ` ${names.length === 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1) ?? ""}`} refuse it together with publishedAfter or publishedBefore.`;
107
+ };
96
108
  /**
97
109
  * `withHour` providers accept all five windows; `fromDay` providers have no
98
110
  * hour window. Two fields with one name, because the accepted values differ.
@@ -100,7 +112,7 @@ const RECENCY_NOTE = "Not together with publishedAfter or publishedBefore.";
100
112
  const recency = (withHour, fromDay) => [{
101
113
  name: "recency",
102
114
  providers: withHour,
103
- schema: choice(`Only pages from the last hour, day, week, month or year. ${RECENCY_NOTE}`, [
115
+ schema: choice(`Only pages from the last hour, day, week, month or year.${recencyNote(withHour)}`, [
104
116
  "hour",
105
117
  "day",
106
118
  "week",
@@ -110,7 +122,7 @@ const recency = (withHour, fromDay) => [{
110
122
  }, {
111
123
  name: "recency",
112
124
  providers: fromDay,
113
- schema: choice(`Only pages from the last day, week, month or year. ${RECENCY_NOTE}`, [
125
+ schema: choice(`Only pages from the last day, week, month or year.${recencyNote(fromDay)}`, [
114
126
  "day",
115
127
  "week",
116
128
  "month",
@@ -393,8 +405,45 @@ const CLOSE_BROWSER_OUTPUT = object({
393
405
  closed: flag(),
394
406
  id: str
395
407
  }, ["closed", "id"]);
408
+ const box = object({
409
+ height: number(),
410
+ left: number(),
411
+ top: number(),
412
+ width: number()
413
+ }, [
414
+ "left",
415
+ "top",
416
+ "width",
417
+ "height"
418
+ ], "Where it sits on the page, as fractions of the page's width and height from its top-left corner.");
396
419
  const PARSE_OUTPUT = object({
397
- blocks: list(anything()),
420
+ blocks: list(object({
421
+ box,
422
+ cells: list(object({
423
+ box,
424
+ column: whole("The column, from 0.", 0),
425
+ columnSpan: whole("Columns the cell spans.", 1),
426
+ row: whole("The row, from 0.", 0),
427
+ rowSpan: whole("Rows the cell spans.", 1),
428
+ text: str
429
+ }, [
430
+ "row",
431
+ "column",
432
+ "text"
433
+ ])),
434
+ page: whole("The physical page number, starting at 1.", 1),
435
+ text: str,
436
+ type: str,
437
+ words: list(object({
438
+ box,
439
+ text: str
440
+ }, ["text", "box"]))
441
+ }, [
442
+ "page",
443
+ "type",
444
+ "text"
445
+ ])),
446
+ id: str,
398
447
  markdown: str,
399
448
  meta,
400
449
  pageCount: whole("Pages in the file.", 0),
@@ -687,7 +736,8 @@ const BROWSER_SPECS = [
687
736
  name: "pages",
688
737
  providers: ["firecrawl"],
689
738
  schema: flag("Also return the Markdown of each page separately.")
690
- }
739
+ },
740
+ resume(["llamaparse", "reducto"])
691
741
  ],
692
742
  idempotent: true,
693
743
  name: "parse_document",
@@ -1282,8 +1332,8 @@ const EXCLUDED_BY_DEFAULT = [
1282
1332
  "browser",
1283
1333
  "monitor"
1284
1334
  ];
1285
- const offers = (field, provider) => field.providers === void 0 || field.providers.includes(provider);
1286
- const needs = (field, provider) => field.required === true || field.requiredFor?.includes(provider) === true;
1335
+ const offers = (field, provider) => field.providers === void 0 || field.providers.some((name) => name === provider);
1336
+ const needs = (field, provider) => field.required === true || field.requiredFor?.some((name) => name === provider) === true;
1287
1337
  const invalid = (tool, provider, message) => new FieldworkError("InvalidRequest", `${tool}: ${message}`, { provider });
1288
1338
  const readInput = (tool, provider, fields, input) => {
1289
1339
  if (!isJsonObject(input)) throw invalid(tool, provider, "input must be an object");
@@ -1312,7 +1362,7 @@ const resultObject = (spec, values, result) => {
1312
1362
  };
1313
1363
  const inputSchema = (fields, provider) => ({
1314
1364
  additionalProperties: false,
1315
- properties: Object.fromEntries(fields.map((field) => [field.name, toJsonSchema(field.schema)])),
1365
+ properties: Object.fromEntries(fields.map((field) => [field.name, { ...field.schema }])),
1316
1366
  required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1317
1367
  type: "object"
1318
1368
  });
@@ -1336,7 +1386,7 @@ const toolFor = (spec, provider, operation, budget) => {
1336
1386
  inputSchema: inputSchema(fields, provider),
1337
1387
  method: spec.method,
1338
1388
  name: spec.name,
1339
- outputSchema: toJsonSchema(spec.output),
1389
+ outputSchema: { ...spec.output },
1340
1390
  provider
1341
1391
  };
1342
1392
  };
@@ -0,0 +1 @@
1
+ import "zod/mini";
package/package.json CHANGED
@@ -1,17 +1,21 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.3.1",
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 and Browserbase.",
3
+ "version": "0.5.0",
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",
7
7
  "brave",
8
8
  "browserbase",
9
+ "document-parsing",
9
10
  "exa",
10
11
  "extraction",
11
12
  "firecrawl",
13
+ "llamaparse",
12
14
  "monitoring",
13
15
  "parallel",
16
+ "pdf",
14
17
  "perplexity",
18
+ "reducto",
15
19
  "research",
16
20
  "scraping",
17
21
  "sdk",
@@ -71,6 +75,14 @@
71
75
  "types": "./dist/browserbase.d.ts",
72
76
  "import": "./dist/browserbase.js"
73
77
  },
78
+ "./llamaparse": {
79
+ "types": "./dist/llamaparse.d.ts",
80
+ "import": "./dist/llamaparse.js"
81
+ },
82
+ "./reducto": {
83
+ "types": "./dist/reducto.d.ts",
84
+ "import": "./dist/reducto.js"
85
+ },
74
86
  "./tools": {
75
87
  "types": "./dist/tools.d.ts",
76
88
  "import": "./dist/tools.js"
@@ -79,6 +91,9 @@
79
91
  "publishConfig": {
80
92
  "access": "public"
81
93
  },
94
+ "dependencies": {
95
+ "zod": "^4.6.7"
96
+ },
82
97
  "devDependencies": {
83
98
  "@howells/lint": "^3.9.1",
84
99
  "@howells/typescript-config": "^0.1.8",
@@ -1,3 +0,0 @@
1
- // src/adapter.ts
2
- const defineAdapter = (adapter) => adapter;
3
- export { defineAdapter as t };
@@ -1,287 +0,0 @@
1
- import { n as codeForStatus, r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
2
- // src/http.ts
3
- const createRawClient = (config) => {
4
- const doFetch = config.fetch ?? globalThis.fetch;
5
- return {
6
- baseUrl: config.baseUrl,
7
- provider: config.provider,
8
- async request(method, path, options = {}) {
9
- const url = new URL(config.baseUrl.replace(/\/$/u, "") + path);
10
- for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
11
- const headers = new Headers({
12
- accept: "application/json",
13
- ...config.headers
14
- });
15
- let body;
16
- if (options.form) body = options.form;
17
- else if (options.body !== void 0) {
18
- headers.set("content-type", "application/json");
19
- body = JSON.stringify(options.body);
20
- }
21
- const signal = combineSignals(options.signal, options.timeout);
22
- const send = async (request) => {
23
- try {
24
- return await doFetch(request.url, {
25
- body: request.body,
26
- headers,
27
- method: request.method,
28
- redirect: "manual",
29
- signal
30
- });
31
- } catch (error) {
32
- throw transportError(config.provider, error, options.signal);
33
- }
34
- };
35
- const response = await followRedirects(config.provider, send, {
36
- body,
37
- method,
38
- url
39
- });
40
- const text = await response.text();
41
- const parsed = parseBody(text);
42
- if (!response.ok) throw new FieldworkError(codeForStatus(response.status), `${config.provider} ${method} ${path} returned ${response.status}: ${describe(parsed, text)}`, {
43
- cause: parsed,
44
- provider: config.provider,
45
- retryAfter: retryAfterSeconds(response.headers.get("retry-after")),
46
- status: response.status
47
- });
48
- return parsed;
49
- }
50
- };
51
- };
52
- const REDIRECTS = /* @__PURE__ */ new Set([
53
- 301,
54
- 302,
55
- 303,
56
- 307,
57
- 308
58
- ]);
59
- const MAX_REDIRECTS = 5;
60
- /**
61
- * Follows a provider's redirects only within its own origin, so the key in
62
- * the request's headers or query never reaches another host. A redirect to
63
- * another origin, scheme or port fails before anything is sent there.
64
- */
65
- const followRedirects = async (provider, send, first) => {
66
- let hop = first;
67
- for (let count = 0; count <= MAX_REDIRECTS; count += 1) {
68
- const response = await send(hop);
69
- if (response.type === "opaqueredirect") throw new FieldworkError("ProviderError", `${provider} redirected the request, and this runtime hides where to; Fieldwork does not follow it`, { provider });
70
- const location = response.headers.get("location");
71
- if (!REDIRECTS.has(response.status) || location === null) return response;
72
- const target = new URL(location, hop.url);
73
- if (target.origin !== first.url.origin) throw new FieldworkError("ProviderError", `${provider} redirected the request to ${target.origin}; Fieldwork follows redirects only within ${first.url.origin}, so the key was not sent`, {
74
- provider,
75
- status: response.status
76
- });
77
- hop = response.status === 303 || (response.status === 301 || response.status === 302) && hop.method === "POST" ? {
78
- body: void 0,
79
- method: "GET",
80
- url: target
81
- } : {
82
- ...hop,
83
- url: target
84
- };
85
- }
86
- throw new FieldworkError("ProviderError", `${provider} redirected the request more than ${MAX_REDIRECTS} times`, { provider });
87
- };
88
- const combineSignals = (signal, timeout) => {
89
- const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((value) => value !== void 0);
90
- return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
91
- };
92
- const transportError = (provider, error, signal) => {
93
- if (signal?.aborted) return new FieldworkError("Aborted", `${provider} request was cancelled`, {
94
- cause: error,
95
- provider
96
- });
97
- if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
98
- cause: error,
99
- provider
100
- });
101
- return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
102
- cause: error,
103
- provider,
104
- retryable: true
105
- });
106
- };
107
- const parseBody = (text) => {
108
- if (text === "") return;
109
- try {
110
- return JSON.parse(text);
111
- } catch {
112
- return text;
113
- }
114
- };
115
- const describe = (parsed, text) => {
116
- if (parsed && typeof parsed === "object") {
117
- const record = parsed;
118
- for (const key of [
119
- "error",
120
- "message",
121
- "detail"
122
- ]) {
123
- const value = record[key];
124
- if (typeof value === "string") return value;
125
- if (value && typeof value === "object") return JSON.stringify(value).slice(0, 300);
126
- }
127
- }
128
- return text.slice(0, 300);
129
- };
130
- const retryAfterSeconds = (header, now = Date.now()) => {
131
- if (!header) return;
132
- const seconds = Number(header);
133
- if (Number.isFinite(seconds)) return seconds;
134
- const date = Date.parse(header);
135
- return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
136
- };
137
- const poll = async (provider, jobId, check, options = {}) => {
138
- const interval = options.interval ?? 2e3;
139
- const deadline = Date.now() + (options.timeout ?? 6e5);
140
- for (;;) {
141
- if (options.signal?.aborted) throw new FieldworkError("Aborted", `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
142
- jobId,
143
- provider
144
- });
145
- let value;
146
- try {
147
- value = await check();
148
- } catch (error) {
149
- throw withJob(error, jobId);
150
- }
151
- if (value !== void 0) return value;
152
- if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
153
- jobId,
154
- provider
155
- });
156
- await sleep(interval, options.signal);
157
- }
158
- };
159
- const sleep = async (ms, signal) => {
160
- await new Promise((resolve) => {
161
- const timer = setTimeout(resolve, ms);
162
- signal?.addEventListener("abort", () => {
163
- clearTimeout(timer);
164
- resolve();
165
- }, { once: true });
166
- });
167
- };
168
- const requireKey = (provider, given, envName) => {
169
- const key = given ?? process.env[envName];
170
- if (!key) throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
171
- return key;
172
- };
173
- // src/util.ts
174
- const record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
175
- const list = (value) => Array.isArray(value) ? value : [];
176
- const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
177
- const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
178
- const strings = (value) => {
179
- const items = list(value).filter((item) => typeof item === "string");
180
- return items.length > 0 ? items : void 0;
181
- };
182
- const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
183
- const callSettings = (options) => {
184
- const { signal, timeout, ...rest } = options ?? {};
185
- return {
186
- call: {
187
- signal,
188
- timeout
189
- },
190
- rest
191
- };
192
- };
193
- const parseJson = (provider, value) => {
194
- if (typeof value !== "string") return value;
195
- try {
196
- return JSON.parse(value);
197
- } catch (error) {
198
- throw new FieldworkError("ProviderError", `${provider} returned output that is not valid JSON`, {
199
- cause: error,
200
- provider
201
- });
202
- }
203
- };
204
- const uniqueCitations = (all) => {
205
- const seen = /* @__PURE__ */ new Map();
206
- for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
207
- return [...seen.values()];
208
- };
209
- const citation = (value) => {
210
- const item = record(value);
211
- const url = text(item.url);
212
- if (!url) return;
213
- const excerpts = typeof item.excerpts === "string" ? [item.excerpts] : strings(item.excerpts);
214
- return compact({
215
- excerpts,
216
- title: text(item.title),
217
- url
218
- });
219
- };
220
- const citations = (value) => list(value).map((item) => citation(item)).filter((item) => item !== void 0);
221
- const requireId = (provider, value) => {
222
- const id = typeof value === "number" ? String(value) : text(value);
223
- if (id === void 0) throw new FieldworkError("ProviderError", `${provider} did not return a job id`, {
224
- cause: value,
225
- provider
226
- });
227
- return id;
228
- };
229
- const scalar = (value) => {
230
- if (typeof value === "string") return value;
231
- return typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
232
- };
233
- const meta = (parts) => {
234
- const units = Object.fromEntries(Object.entries(parts.units ?? {}).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])));
235
- const usage = compact({
236
- costUsd: num(parts.costUsd),
237
- credits: num(parts.credits),
238
- units: Object.keys(units).length > 0 ? units : void 0
239
- });
240
- const warnings = typeof parts.warnings === "string" ? [parts.warnings] : list(parts.warnings).map((item) => typeof item === "string" ? item : text(record(item).message) ?? text(record(item).detail)).filter((item) => item !== void 0);
241
- const result = compact({
242
- requestId: scalar(parts.requestId),
243
- usage: Object.keys(usage).length > 0 ? usage : void 0,
244
- warnings: warnings.length > 0 ? warnings : void 0
245
- });
246
- return Object.keys(result).length > 0 ? result : void 0;
247
- };
248
- const productImages = (value) => {
249
- const items = list(value).map((item) => {
250
- if (typeof item === "string") return item === "" ? void 0 : { url: item };
251
- const image = record(item);
252
- const url = text(image.url) ?? text(image.src);
253
- return url ? compact({
254
- alt: text(image.alt),
255
- url
256
- }) : void 0;
257
- }).filter((item) => item !== void 0);
258
- return items.length > 0 ? items : void 0;
259
- };
260
- const refuseTogether = (provider, options, ...names) => {
261
- const set = names.filter((name) => options[name] !== void 0);
262
- if (set.length > 1) throw new FieldworkError("InvalidRequest", `${provider} does not accept ${set.join(" and ")} together; pass one`, { provider });
263
- };
264
- const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
265
- /** Statuses that mean the page is not there, so a read of it has no page to return. */
266
- const GONE = /* @__PURE__ */ new Set([404, 410]);
267
- /**
268
- * A read whose page answered 404 or 410 fails as NotFound, as it does on
269
- * providers that return no page at all, instead of returning the error page
270
- * as if it were the content.
271
- */
272
- const presentPage = (provider, page) => {
273
- if (page.statusCode !== void 0 && GONE.has(page.statusCode)) throw new FieldworkError("NotFound", `${provider} could not read ${page.url}: the page returned ${page.statusCode}`, {
274
- provider,
275
- status: page.statusCode
276
- });
277
- return page;
278
- };
279
- /** Splits a batch's pages into those present and those that answered 404 or 410. */
280
- const presentPages = (pages) => ({
281
- gone: pages.filter((page) => page.statusCode !== void 0 && GONE.has(page.statusCode)).map((page) => ({
282
- error: `the page returned ${page.statusCode}`,
283
- url: page.url
284
- })),
285
- pages: pages.filter((page) => page.statusCode === void 0 || !GONE.has(page.statusCode))
286
- });
287
- export { requireKey as S, strings as _, hours as a, createRawClient as b, num as c, presentPages as d, productImages as f, scalar as g, requireId as h, compact as i, parseJson as l, refuseTogether as m, citation as n, list as o, record as p, citations as r, meta as s, callSettings as t, presentPage as u, text as v, poll as x, uniqueCitations as y };