@howells/fieldwork-sdk 0.8.0 → 0.10.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/kernel.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as Page, a as RawClient, d as BrowserSession, p as CallOptions, t as Adapter } from "./adapter-Dqy-6BiH.js";
1
+ import { D as DownloadedFile, E as DownloadOptions, H as Page, a as RawClient, d as BrowserSession, p as CallOptions, t as Adapter } from "./adapter-DQrBP1tj.js";
2
2
  /** Settings for `kernel()`. */
3
3
  export interface KernelConfig {
4
4
  /** Defaults to the KERNEL_API_KEY environment variable. */
@@ -82,9 +82,22 @@ export interface KernelOpenOptions extends CallOptions {
82
82
  /** Start-Up and Enterprise plans only. Kernel defaults to us-east. */
83
83
  region?: "us-east" | "us-west" | "eu-west" | "ap-southeast";
84
84
  }
85
+ /**
86
+ * Options for `download`, which fetches the file with Playwright's request
87
+ * client inside a new headless Kernel browser, without rendering a page, and
88
+ * deletes the browser. The bytes never leave Kernel when the file is over
89
+ * the limit. The session bills for the seconds it ran, reported as
90
+ * `meta.usage.units.uptime_ms`. Kernel's ceiling here is 50 MiB.
91
+ */
92
+ export interface KernelDownloadOptions extends DownloadOptions {
93
+ /** Send a saved profile's cookies with the request. The download never saves to it. */
94
+ profile?: KernelProfile;
95
+ }
85
96
  /** What the Kernel adapter offers. */
86
97
  export interface KernelOperations {
87
98
  read: (url: string, options?: KernelReadOptions) => Promise<Page>;
99
+ /** Fetches a file's bytes inside a Kernel browser, up to 50 MiB. */
100
+ download: (url: string, options?: KernelDownloadOptions) => Promise<DownloadedFile>;
88
101
  browser: {
89
102
  open: (options?: KernelOpenOptions) => Promise<BrowserSession>;
90
103
  /** Deletes the session, so it stops billing. */
@@ -92,7 +105,7 @@ export interface KernelOperations {
92
105
  };
93
106
  }
94
107
  /**
95
- * An adapter for Kernel: read and browser. Pass it to `new Fieldwork({ adapter })`.
108
+ * An adapter for Kernel: read, download and browser. Pass it to `new Fieldwork({ adapter })`.
96
109
  *
97
110
  * Throws `Unauthorized` when neither `apiKey` nor `KERNEL_API_KEY` is set.
98
111
  */
package/dist/kernel.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { a as presentFile, i as header, n as byteLimit, o as tooLarge, r as checkFileUrl, t as MIB } from "./download-gyAym9vL.js";
2
3
  import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, l as optionalBoolean, n as anything, p as optionalObject, s as optionalAnyString } from "./parse-lMLcxUsG.js";
4
- import { r as runJob } from "./job-DBhGs7Ha.js";
4
+ import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, l as optionalBoolean, n as anything, p as optionalObject, s as optionalAnyString, v as recordOf } from "./parse-lMLcxUsG.js";
5
5
  import { a as compact, l as presentPage, p as requireJobId, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
6
+ import { r as runJob } from "./job-DBhGs7Ha.js";
6
7
  import * as z from "zod/mini";
7
8
  import TurndownService from "turndown";
8
9
  // src/adapters/kernel/response.ts
@@ -31,66 +32,21 @@ const RenderedPage = looseObject({
31
32
  title: optionalString,
32
33
  url: optionalString
33
34
  });
34
- // src/adapters/kernel.ts
35
- /** Seconds Kernel gives the read script, within its 300-second limit. */
36
- const READ_SCRIPT_SECONDS = 120;
35
+ /** What the download script returns: the response, and its body as Base64 unless it was over the limit or not 2xx. */
36
+ const FetchedFile = looseObject({
37
+ data: optionalAnyString,
38
+ headers: recordOf(optionalAnyString),
39
+ status: optionalNumber,
40
+ tooLarge: optionalNumber,
41
+ url: optionalString
42
+ });
43
+ // src/adapters/kernel/session.ts
37
44
  /** Seconds a read's session may sit idle before Kernel deletes it. */
38
45
  const READ_IDLE_SECONDS = 60;
39
46
  /** Milliseconds a read waits for Kernel to delete its session, apart from the call's own deadline. */
40
47
  const RELEASE_TIMEOUT = 1e4;
41
48
  /** Milliseconds a read waits for the deleted session's billed time. */
42
49
  const BILLED_TIME_WAIT = 15e3;
43
- /** The elements that hold a page's content, inside which site chrome is kept. */
44
- const CONTENT = /* @__PURE__ */ new Set(["main", "article"]);
45
- /** Site chrome: removed from the Markdown unless it is inside a main or article element. */
46
- const CHROME = /* @__PURE__ */ new Set([
47
- "nav",
48
- "header",
49
- "footer",
50
- "aside"
51
- ]);
52
- /**
53
- * The Playwright script `read` runs in the browser. It waits for the DOM and
54
- * then up to 3 seconds for the network to go quiet: pages that poll or
55
- * stream never do, and their content has rendered by then. It reads the HTML,
56
- * title and URL in one call into the page, because each call waits its turn
57
- * behind the page's own scripts, seconds on a busy page.
58
- */
59
- const readScript = (url) => `
60
- const response = await page.goto(${JSON.stringify(url)}, { waitUntil: "domcontentloaded", timeout: 90000 });
61
- await page.waitForLoadState("networkidle", { timeout: 3000 }).catch(() => undefined);
62
- const rendered = await page.evaluate(() => ({
63
- html: (document.doctype ? new XMLSerializer().serializeToString(document.doctype) : "") + document.documentElement.outerHTML,
64
- title: document.title,
65
- url: location.href,
66
- }));
67
- return { ...rendered, status: response?.status() ?? null };
68
- `;
69
- /** Whether the node has a main or article element among its ancestors. */
70
- const inContent = (node) => node.parentNode !== null && (CONTENT.has(node.parentNode.nodeName.toLowerCase()) || inContent(node.parentNode));
71
- /**
72
- * The rendered page as Markdown, without the site's navigation, header,
73
- * footer and sidebars, which on a retailer's page can be most of the text.
74
- * Those elements are kept inside a main or article element, where they are
75
- * the content's own; a page with neither loses all of them.
76
- */
77
- const markdownOf = (html) => {
78
- const service = new TurndownService({
79
- bulletListMarker: "-",
80
- codeBlockStyle: "fenced",
81
- headingStyle: "atx"
82
- });
83
- service.remove([
84
- "title",
85
- "script",
86
- "style",
87
- "noscript",
88
- "template",
89
- "iframe"
90
- ]);
91
- service.remove((node) => CHROME.has(node.nodeName.toLowerCase()) && !inContent(node));
92
- return service.turndown(html).trim();
93
- };
94
50
  /** The session's profile and proxy as Kernel's create body spells them. */
95
51
  const sessionBody = (o) => ({
96
52
  profile: o.profile ? compact({
@@ -106,15 +62,6 @@ const sessionBody = (o) => ({
106
62
  });
107
63
  /** Why a session still bills, for a warning or an error. */
108
64
  const leakText = (id, failure) => `could not delete browser ${id}, which bills until its ${READ_IDLE_SECONDS}-second idle timeout: ${failure.message}`;
109
- /**
110
- * Throws `InvalidRequest` unless the URL parses and is http or https, so no
111
- * session is created for a URL the browser should not open.
112
- */
113
- const checkUrl = (provider, url) => {
114
- const parsed = URL.parse(url);
115
- if (parsed === null) throw invalidRequest(provider, `cannot read ${url}: it is not a URL`);
116
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw invalidRequest(provider, `reads only http and https URLs, not ${parsed.protocol} (${url})`);
117
- };
118
65
  /** What the work returned, or what it threw. */
119
66
  const settle = async (work) => {
120
67
  try {
@@ -176,6 +123,135 @@ const billedTime = async (raw, id, call) => {
176
123
  }
177
124
  };
178
125
  /**
126
+ * Runs `work` in a new headless session and deletes the session whether or
127
+ * not the work succeeded. A failure whose session could not be deleted fails
128
+ * with its own error, naming the session that still bills.
129
+ */
130
+ const inSession = async (raw, o, call, work) => {
131
+ const { provider } = raw;
132
+ const created = await raw.request("POST", "/browsers", {
133
+ creates: true,
134
+ ...call,
135
+ body: compact({
136
+ headless: true,
137
+ stealth: o.stealth,
138
+ timeout_seconds: READ_IDLE_SECONDS,
139
+ ...sessionBody({
140
+ profile: o.profile,
141
+ proxy: o.proxy
142
+ })
143
+ })
144
+ });
145
+ const id = requireJobId(provider, z.parse(BrowserResponse, created).session_id);
146
+ const done = await settle(work(id));
147
+ const unreleased = await release(raw, id, call.retries);
148
+ if (!done.ok) {
149
+ const { error } = done;
150
+ if (unreleased === void 0) throw error;
151
+ const message = `${error instanceof Error ? error.message : String(error)}; also ${leakText(id, unreleased)}`;
152
+ throw error instanceof FieldworkError ? new FieldworkError(error.code, message, {
153
+ cause: error,
154
+ jobId: error.jobId,
155
+ provider: error.provider,
156
+ retryAfter: error.retryAfter,
157
+ retryable: error.retryable,
158
+ status: error.status
159
+ }) : new FieldworkError("ProviderError", message, {
160
+ cause: error,
161
+ provider
162
+ });
163
+ }
164
+ return {
165
+ billed: unreleased === void 0 ? await billedTime(raw, id, call) : { warning: leakText(id, unreleased) },
166
+ created,
167
+ id,
168
+ value: done.value
169
+ };
170
+ };
171
+ // src/adapters/kernel.ts
172
+ /** Seconds Kernel gives the read script, within its 300-second limit. */
173
+ const READ_SCRIPT_SECONDS = 120;
174
+ /** The largest file `download` returns: what Kernel's script results carry reliably. */
175
+ const DOWNLOAD_CEILING = 50 * MIB;
176
+ /** Seconds Kernel gives the download script, within its 300-second limit. */
177
+ const DOWNLOAD_SCRIPT_SECONDS = 240;
178
+ /**
179
+ * The Playwright script `download` runs in the browser's VM. It fetches with
180
+ * the context's request client (the profile's cookies, no page), follows
181
+ * redirects, and returns the body as Base64 only when the response is 2xx
182
+ * and within the limit, so an oversized file never leaves Kernel.
183
+ */
184
+ const downloadScript = (url, limit) => `
185
+ const response = await context.request.get(${JSON.stringify(url)}, { failOnStatusCode: false, maxRedirects: 20, timeout: 200000 });
186
+ const result = { headers: response.headers(), status: response.status(), url: response.url() };
187
+ if (!response.ok()) return result;
188
+ const declared = Number(result.headers["content-length"]);
189
+ if (Number.isFinite(declared) && declared > ${limit}) return { ...result, tooLarge: declared };
190
+ const body = await response.body();
191
+ if (body.length > ${limit}) return { ...result, tooLarge: body.length };
192
+ return { ...result, data: body.toString("base64") };
193
+ `;
194
+ /** The elements that hold a page's content, inside which site chrome is kept. */
195
+ const CONTENT = /* @__PURE__ */ new Set(["main", "article"]);
196
+ /** Site chrome: removed from the Markdown unless it is inside a main or article element. */
197
+ const CHROME = /* @__PURE__ */ new Set([
198
+ "nav",
199
+ "header",
200
+ "footer",
201
+ "aside"
202
+ ]);
203
+ /**
204
+ * The Playwright script `read` runs in the browser. It waits for the DOM and
205
+ * then up to 3 seconds for the network to go quiet: pages that poll or
206
+ * stream never do, and their content has rendered by then. It reads the HTML,
207
+ * title and URL in one call into the page, because each call waits its turn
208
+ * behind the page's own scripts, seconds on a busy page.
209
+ */
210
+ const readScript = (url) => `
211
+ const response = await page.goto(${JSON.stringify(url)}, { waitUntil: "domcontentloaded", timeout: 90000 });
212
+ await page.waitForLoadState("networkidle", { timeout: 3000 }).catch(() => undefined);
213
+ const rendered = await page.evaluate(() => ({
214
+ html: (document.doctype ? new XMLSerializer().serializeToString(document.doctype) : "") + document.documentElement.outerHTML,
215
+ title: document.title,
216
+ url: location.href,
217
+ }));
218
+ return { ...rendered, status: response?.status() ?? null };
219
+ `;
220
+ /** Whether the node has a main or article element among its ancestors. */
221
+ const inContent = (node) => node.parentNode !== null && (CONTENT.has(node.parentNode.nodeName.toLowerCase()) || inContent(node.parentNode));
222
+ /**
223
+ * The rendered page as Markdown, without the site's navigation, header,
224
+ * footer and sidebars, which on a retailer's page can be most of the text.
225
+ * Those elements are kept inside a main or article element, where they are
226
+ * the content's own; a page with neither loses all of them.
227
+ */
228
+ const markdownOf = (html) => {
229
+ const service = new TurndownService({
230
+ bulletListMarker: "-",
231
+ codeBlockStyle: "fenced",
232
+ headingStyle: "atx"
233
+ });
234
+ service.remove([
235
+ "title",
236
+ "script",
237
+ "style",
238
+ "noscript",
239
+ "template",
240
+ "iframe"
241
+ ]);
242
+ service.remove((node) => CHROME.has(node.nodeName.toLowerCase()) && !inContent(node));
243
+ return service.turndown(html).trim();
244
+ };
245
+ /**
246
+ * Throws `InvalidRequest` unless the URL parses and is http or https, so no
247
+ * session is created for a URL the browser should not open.
248
+ */
249
+ const checkUrl = (provider, url) => {
250
+ const parsed = URL.parse(url);
251
+ if (parsed === null) throw invalidRequest(provider, `cannot read ${url}: it is not a URL`);
252
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw invalidRequest(provider, `reads only http and https URLs, not ${parsed.protocol} (${url})`);
253
+ };
254
+ /**
179
255
  * Runs the read script in the session and returns the rendered page with its
180
256
  * HTML and Kernel's reply. Throws `ProviderError` when the script failed or
181
257
  * returned no HTML.
@@ -205,50 +281,14 @@ const render = async (raw, id, url, call) => {
205
281
  response
206
282
  };
207
283
  };
208
- /**
209
- * Loads the page in a new session, deletes the session whether or not the
210
- * script succeeded, and builds the result. A failed read whose session could
211
- * not be deleted fails with its own error, naming the session that still bills.
212
- */
284
+ /** Loads the page in a new session and builds the result. */
213
285
  const readPage = async (raw, url, options) => {
214
286
  const { provider } = raw;
215
287
  const { call, rest: o } = callSettings(options);
216
288
  checkUrl(provider, url);
217
289
  const format = o.format ?? "markdown";
218
- const created = await raw.request("POST", "/browsers", {
219
- creates: true,
220
- ...call,
221
- body: compact({
222
- headless: true,
223
- stealth: o.stealth,
224
- timeout_seconds: READ_IDLE_SECONDS,
225
- ...sessionBody({
226
- profile: o.profile,
227
- proxy: o.proxy
228
- })
229
- })
230
- });
231
- const id = requireJobId(provider, z.parse(BrowserResponse, created).session_id);
232
- const rendered = await settle(render(raw, id, url, call));
233
- const unreleased = await release(raw, id, call.retries);
234
- if (!rendered.ok) {
235
- const { error } = rendered;
236
- if (unreleased === void 0) throw error;
237
- const message = `${error instanceof Error ? error.message : String(error)}; also ${leakText(id, unreleased)}`;
238
- throw error instanceof FieldworkError ? new FieldworkError(error.code, message, {
239
- cause: error,
240
- jobId: error.jobId,
241
- provider: error.provider,
242
- retryAfter: error.retryAfter,
243
- retryable: error.retryable,
244
- status: error.status
245
- }) : new FieldworkError("ProviderError", message, {
246
- cause: error,
247
- provider
248
- });
249
- }
250
- const { html, page, response } = rendered.value;
251
- const billed = unreleased === void 0 ? await billedTime(raw, id, call) : { warning: leakText(id, unreleased) };
290
+ const { billed, created, id, value } = await inSession(raw, o, call, async (session) => await render(raw, session, url, call));
291
+ const { html, page, response } = value;
252
292
  const markdown = format === "markdown" ? markdownOf(html) : void 0;
253
293
  return presentPage(provider, compact({
254
294
  markdown,
@@ -267,8 +307,57 @@ const readPage = async (raw, url, options) => {
267
307
  url: page.url ?? url
268
308
  }));
269
309
  };
310
+ /** Fetches the file in a new session and checks it. */
311
+ const downloadFile = async (raw, url, options) => {
312
+ const { provider } = raw;
313
+ const { call, rest: o } = callSettings(options);
314
+ checkFileUrl(provider, url);
315
+ const limit = byteLimit(provider, DOWNLOAD_CEILING, o.maxBytes);
316
+ const { billed, created, id, value } = await inSession(raw, { profile: o.profile }, call, async (session) => {
317
+ const response = await raw.request("POST", `/browsers/${segment(session)}/playwright/execute`, {
318
+ ...call,
319
+ body: {
320
+ code: downloadScript(url, limit),
321
+ timeout_sec: DOWNLOAD_SCRIPT_SECONDS
322
+ }
323
+ });
324
+ const body = z.parse(ExecuteResponse, response);
325
+ if (body.success !== true) throw new FieldworkError("ProviderError", `kernel could not download ${url}: ${body.error ?? "the script failed without an error"}`, {
326
+ cause: response,
327
+ provider
328
+ });
329
+ return {
330
+ file: z.parse(FetchedFile, body.result),
331
+ response
332
+ };
333
+ });
334
+ const { file, response } = value;
335
+ if (file.tooLarge !== void 0) throw tooLarge(provider, url, file.tooLarge, limit);
336
+ if (file.status !== void 0 && file.status >= 200 && file.status <= 299 && file.data === void 0) throw new FieldworkError("ProviderError", `kernel downloaded ${url} but the script returned no bytes`, {
337
+ cause: response,
338
+ provider
339
+ });
340
+ const { headers } = file;
341
+ return presentFile(provider, {
342
+ body: { base64: file.data ?? "" },
343
+ contentType: header(headers, "content-type"),
344
+ headers,
345
+ meta: meta({
346
+ requestId: id,
347
+ units: { uptime_ms: billed.uptimeMs },
348
+ warnings: billed.warning
349
+ }),
350
+ raw: {
351
+ browser: created,
352
+ execute: response
353
+ },
354
+ requested: url,
355
+ statusCode: file.status,
356
+ url: file.url ?? url
357
+ }, limit);
358
+ };
270
359
  /**
271
- * An adapter for Kernel: read and browser. Pass it to `new Fieldwork({ adapter })`.
360
+ * An adapter for Kernel: read, download and browser. Pass it to `new Fieldwork({ adapter })`.
272
361
  *
273
362
  * Throws `Unauthorized` when neither `apiKey` nor `KERNEL_API_KEY` is set.
274
363
  */
@@ -312,6 +401,7 @@ const kernel = (config = {}) => {
312
401
  });
313
402
  }
314
403
  },
404
+ download: async (url, options) => await downloadFile(raw, url, options),
315
405
  read: async (url, options) => await readPage(raw, url, options)
316
406
  },
317
407
  raw
@@ -1,4 +1,4 @@
1
- import { C as DocumentInput, H as ParsedDocument, T as DocumentUrl, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-Dqy-6BiH.js";
1
+ import { C as DocumentInput, T as DocumentUrl, W as ParsedDocument, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-DQrBP1tj.js";
2
2
  /** Settings for `llamaparse()`. */
3
3
  export interface LlamaParseConfig {
4
4
  /** Defaults to the LLAMA_CLOUD_API_KEY environment variable. */
@@ -21,7 +21,7 @@ export interface LlamaParseParseOptions extends CallOptions {
21
21
  tier?: LlamaParseTier;
22
22
  /** The parser version: "latest" (the default) or a date such as "2026-09-28". */
23
23
  version?: string;
24
- /** Return layout blocks with positions. */
24
+ /** Return layout blocks with positions, and each page's size in points. */
25
25
  blocks?: boolean;
26
26
  /**
27
27
  * Also return where each word, line and table cell sits in each block, and
@@ -23,8 +23,12 @@ const Line = looseObject({
23
23
  span: arrayOf(z.number()),
24
24
  words: arrayOf(Word)
25
25
  });
26
+ const OneBox = z.record(z.string(), z.unknown());
27
+ const BoxList = arrayOf(PointBox);
28
+ /** A list of boxes; one box on its own reads as a list of one, and anything else as none. */
29
+ const PointBoxes = z.prefault(z.pipe(z.unknown(), z.transform((value) => z.parse(BoxList, z.safeParse(OneBox, value).success ? [value] : value))), []);
26
30
  const Cell = looseObject({
27
- bbox: arrayOf(PointBox),
31
+ bbox: PointBoxes,
28
32
  lines: arrayOf(Line)
29
33
  });
30
34
  /** An item of a page. Its own `items` (a header's, a list's) are read one level at a time. */
@@ -107,8 +111,10 @@ const tableOf = (item, size) => {
107
111
  const text = item.rows[row]?.[column];
108
112
  if (text !== void 0) {
109
113
  const inCell = grounded(cell.lines, text, size);
114
+ const boxes = cell.bbox.map((box) => fraction(box, size)).filter((box) => box !== void 0);
110
115
  cells.push(compact({
111
- box: around(cell.bbox, size),
116
+ box: enclosing(boxes),
117
+ boxes: boxes.length > 0 ? boxes : void 0,
112
118
  column,
113
119
  lines: inCell.lines.length > 0 ? inCell.lines : void 0,
114
120
  row,
@@ -124,14 +130,17 @@ const tableOf = (item, size) => {
124
130
  words
125
131
  };
126
132
  };
127
- const blocksOfItem = (item, page, size) => {
128
- if (item.items.length > 0) return item.items.flatMap((child) => blocksOfItem(z.parse(Item, child), page, size));
133
+ /** The page header or footer an item is, if it is one. */
134
+ const containerOf = (item) => item.type === "header" || item.type === "footer" ? item.type : void 0;
135
+ const blocksOfItem = (item, page, size, container) => {
136
+ if (item.items.length > 0) return item.items.flatMap((child) => blocksOfItem(z.parse(Item, child), page, size, container ?? containerOf(item)));
129
137
  const text = item.md ?? item.value ?? "";
130
- if (size === void 0) return [{
138
+ if (size === void 0) return [compact({
139
+ container,
131
140
  page,
132
141
  text,
133
142
  type: item.type ?? "unknown"
134
- }];
143
+ })];
135
144
  const table = tableOf(item, size);
136
145
  const own = grounded(item.grounding.lines, text, size);
137
146
  const lines = [...own.lines, ...table.lines];
@@ -139,6 +148,7 @@ const blocksOfItem = (item, page, size) => {
139
148
  return [compact({
140
149
  box: around(item.bbox, size),
141
150
  cells: table.cells.length > 0 ? table.cells : void 0,
151
+ container,
142
152
  lines: lines.length > 0 ? lines : void 0,
143
153
  page,
144
154
  text,
@@ -146,14 +156,25 @@ const blocksOfItem = (item, page, size) => {
146
156
  words: words.length > 0 ? words : void 0
147
157
  })];
148
158
  };
159
+ /** A page's size in points, when LlamaParse gave a usable one. */
160
+ const sizeOf = (entry) => entry.page_width !== void 0 && entry.page_height !== void 0 && entry.page_width > 0 && entry.page_height > 0 ? {
161
+ height: entry.page_height,
162
+ width: entry.page_width
163
+ } : void 0;
164
+ /** Each page's size in points, by page number. */
165
+ const pageSizes = (pages) => {
166
+ const sizes = /* @__PURE__ */ new Map();
167
+ for (const entry of pages) {
168
+ const size = sizeOf(entry);
169
+ if (entry.page_number !== void 0 && size !== void 0) sizes.set(entry.page_number, size);
170
+ }
171
+ return sizes;
172
+ };
149
173
  /** The blocks of each page, its boxes turned from points into fractions of the page. */
150
174
  const documentBlocks = (pages) => pages.flatMap((entry) => {
151
175
  const page = entry.page_number;
152
176
  if (page === void 0) return [];
153
- const size = entry.page_width !== void 0 && entry.page_height !== void 0 && entry.page_width > 0 && entry.page_height > 0 ? {
154
- height: entry.page_height,
155
- width: entry.page_width
156
- } : void 0;
177
+ const size = sizeOf(entry);
157
178
  return entry.items.flatMap((item) => blocksOfItem(item, page, size));
158
179
  });
159
180
  // src/adapters/llamaparse.ts
@@ -243,6 +264,10 @@ const parsedDocument = async (found, id, o, read) => {
243
264
  });
244
265
  const grounded = o.wordBoxes === true ? await groundedPages(found, read) : void 0;
245
266
  const images = o.pageImages === true ? pageImageAddresses(found, id) : void 0;
267
+ let laidOut;
268
+ if (grounded !== void 0) laidOut = grounded.map((row) => z.parse(ItemsPage, row));
269
+ else if (o.blocks === true) laidOut = found.value.items.pages;
270
+ const sizes = laidOut === void 0 ? void 0 : pageSizes(laidOut);
246
271
  const pages = found.value.markdown.pages.flatMap((page) => {
247
272
  if (page.page_number === void 0) return [];
248
273
  const image = images?.get(page.page_number);
@@ -250,17 +275,17 @@ const parsedDocument = async (found, id, o, read) => {
250
275
  cause: found.original,
251
276
  provider
252
277
  });
278
+ const size = sizes?.get(page.page_number);
253
279
  return [compact({
280
+ height: size?.height,
254
281
  image,
255
282
  markdown: page.markdown ?? "",
256
- pageNumber: page.page_number
283
+ pageNumber: page.page_number,
284
+ width: size?.width
257
285
  })];
258
286
  });
259
- let laidOut;
260
- if (grounded !== void 0) laidOut = documentBlocks(grounded.map((row) => z.parse(ItemsPage, row)));
261
- else if (o.blocks === true) laidOut = documentBlocks(found.value.items.pages);
262
287
  return compact({
263
- blocks: laidOut,
288
+ blocks: laidOut === void 0 ? void 0 : documentBlocks(laidOut),
264
289
  id,
265
290
  markdown: pages.map((page) => page.markdown).join("\n\n"),
266
291
  meta: meta({ credits: found.value.job.usage.credits }),
@@ -1,5 +1,5 @@
1
- import { B as Page, D as Extraction, L as MonitorEvents, M as ImageSearch, R as MonitorInfo, V as PageBatch, Y as Research, Z as SearchResponse, a as RawClient, b as Decisions, g as Condition, l as Answer, p as CallOptions, t as Adapter, x as Discovery, y as DecisionQuestion, z as MonitorSchedule } from "./adapter-Dqy-6BiH.js";
2
- import { t as OutputSchema } from "./schema-B23Z08Ds.js";
1
+ import { $ as SearchResponse, B as MonitorInfo, H as Page, P as ImageSearch, U as PageBatch, V as MonitorSchedule, Z as Research, a as RawClient, b as Decisions, g as Condition, k as Extraction, l as Answer, p as CallOptions, t as Adapter, x as Discovery, y as DecisionQuestion, z as MonitorEvents } from "./adapter-DQrBP1tj.js";
2
+ import { t as OutputSchema } from "./schema-BFjS6CSz.js";
3
3
  import "./util-DhYr1OS3.js";
4
4
  /** Settings for `parallel()`. */
5
5
  interface ParallelConfig {
@@ -1,5 +1,5 @@
1
- import { J as Recency, Y as Research, Z as SearchResponse, a as RawClient, b as Decisions, l as Answer, p as CallOptions, t as Adapter, y as DecisionQuestion } from "./adapter-Dqy-6BiH.js";
2
- import { t as OutputSchema } from "./schema-B23Z08Ds.js";
1
+ import { $ as SearchResponse, X as Recency, Z as Research, a as RawClient, b as Decisions, l as Answer, p as CallOptions, t as Adapter, y as DecisionQuestion } from "./adapter-DQrBP1tj.js";
2
+ import { t as OutputSchema } from "./schema-BFjS6CSz.js";
3
3
  /** Settings for `perplexity()`. */
4
4
  interface PerplexityConfig {
5
5
  /** Defaults to the PERPLEXITY_API_KEY environment variable. */
package/dist/reducto.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as DocumentInput, H as ParsedDocument, T as DocumentUrl, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-Dqy-6BiH.js";
1
+ import { C as DocumentInput, T as DocumentUrl, W as ParsedDocument, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-DQrBP1tj.js";
2
2
  /** Settings for `reducto()`. */
3
3
  export interface ReductoConfig {
4
4
  /** Defaults to the REDUCTO_API_KEY environment variable. */
@@ -1,4 +1,4 @@
1
- import { N as JsonSchema } from "./adapter-Dqy-6BiH.js";
1
+ import { F as JsonSchema } from "./adapter-DQrBP1tj.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. */
package/dist/serpapi.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { J as Recency, M as ImageSearch, Z as SearchResponse, a as RawClient, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-Dqy-6BiH.js";
1
+ import { $ as SearchResponse, P as ImageSearch, X as Recency, a as RawClient, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-DQrBP1tj.js";
2
2
  import "./util-DhYr1OS3.js";
3
3
  /** Settings for `serpapi()`. */
4
4
  interface SerpApiConfig {
package/dist/tavily.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { B as Page, J as Recency, M as ImageSearch, V as PageBatch, Y as Research, Z as SearchResponse, _ as Crawl, a as RawClient, et as SiteMap, l as Answer, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-Dqy-6BiH.js";
2
- import { t as OutputSchema } from "./schema-B23Z08Ds.js";
1
+ import { $ as SearchResponse, H as Page, P as ImageSearch, U as PageBatch, X as Recency, Z as Research, _ as Crawl, a as RawClient, l as Answer, nt as SiteMap, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-DQrBP1tj.js";
2
+ import { t as OutputSchema } from "./schema-BFjS6CSz.js";
3
3
  /** Settings for the Tavily adapter. */
4
4
  interface TavilyConfig {
5
5
  /** Defaults to the TAVILY_API_KEY environment variable. */
package/dist/tools.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-CAGMQ2Cu.js";
2
- import { N as JsonSchema, m as Capability, n as AnyAdapter, p as CallOptions } from "./adapter-Dqy-6BiH.js";
1
+ import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-DNwEf0Mo.js";
2
+ import { F as JsonSchema, m as Capability, n as AnyAdapter, p as CallOptions } from "./adapter-DQrBP1tj.js";
3
3
  /** Any JSON value. */
4
4
  type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
5
5
  /** A JSON object. A key may be undefined, which reads as absent and is not serialized. */
package/dist/tools.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
2
  import { f as refuseTogether } from "./util-BqeRYF2b.js";
3
3
  import { a as isNumber, i as isList, n as isFlag, o as isText, r as isJsonObject, t as joinPath } from "./path-DL5P8XH2.js";
4
- import { t as CAPABILITIES } from "./types-CnomnF-6.js";
4
+ import { t as CAPABILITIES } from "./types-rc8bl8Em.js";
5
5
  import * as z from "zod/mini";
6
6
  // src/tool-specs/schema.ts
7
7
  const described = (schema, description) => description === void 0 ? schema : {
@@ -472,6 +472,7 @@ const PARSE_OUTPUT = object({
472
472
  box,
473
473
  cells: list(object({
474
474
  box,
475
+ boxes: list(box, "Each box the cell sits in, when the provider gives them one by one; box encloses them."),
475
476
  column: whole("The column, from 0.", 0),
476
477
  columnSpan: whole("Columns the cell spans.", 1),
477
478
  lines: list(placedText),
@@ -483,6 +484,7 @@ const PARSE_OUTPUT = object({
483
484
  "column",
484
485
  "text"
485
486
  ])),
487
+ container: choice("The page header or footer the block was read out of.", ["header", "footer"]),
486
488
  lines: list(placedText),
487
489
  page: whole("The physical page number, starting at 1.", 1),
488
490
  text: str,
@@ -498,8 +500,10 @@ const PARSE_OUTPUT = object({
498
500
  meta,
499
501
  pageCount: whole("Pages in the file.", 0),
500
502
  pages: list(object({
503
+ height: number("The page's height in points."),
501
504
  markdown: str,
502
- pageNumber: whole("The physical page number, starting at 1.", 1)
505
+ pageNumber: whole("The physical page number, starting at 1.", 1),
506
+ width: number("The page's width in points.")
503
507
  }, ["pageNumber", "markdown"]))
504
508
  }, ["markdown"]);
505
509
  /** The result of `create_monitor` and `get_monitor`, a `MonitorInfo`. */
@@ -16,6 +16,7 @@ const CAPABILITIES = [
16
16
  "act",
17
17
  "browser",
18
18
  "parse",
19
+ "download",
19
20
  "monitor",
20
21
  "usage"
21
22
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
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, Kernel, LlamaParse and Reducto.",
5
5
  "keywords": [
6
6
  "agents",