@howells/fieldwork-sdk 0.10.0 → 0.10.2

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/README.md CHANGED
@@ -108,7 +108,7 @@ Every result is normalized and keeps the provider's response in `raw`. Most also
108
108
  - `research` returns `{ id, status, output, sources, fields, continuationId }`. `output` follows your schema when you pass one, otherwise it is the report text.
109
109
  - `crawl` returns `{ pages, failed, robotsBlocked, total }`.
110
110
  - `download` returns `{ url, bytes, contentType, size, statusCode, etag, lastModified }`: `url` is the final URL, `bytes` a `Uint8Array` exactly as served, `contentType` the server's header unchanged. `etag` and `lastModified` come back from Browserbase and Kernel, which pass headers through.
111
- - `parse` returns `{ id, markdown, pages, blocks, pageCount }`. With `blocks: true`, `blocks` lists the layout in reading order: each block's `page`, `type` (the provider's own word), `text` and `box`. With `wordBoxes: true` (LlamaParse and Reducto), blocks also carry `words` and table `cells`, each with its own box. LlamaParse also places each line: a block's `lines` and a cell's `lines` are `{ text, box }`, the text being the line's part of the block's or cell's text, Markdown included. A table's `words` and `lines` are its cells', in reading order. Reducto places no lines. LlamaParse also gives a cell that sits in several boxes each of them as `boxes`, with `box` enclosing them; marks a block read out of a page header or footer with `container: "header"` or `"footer"`; and, with `blocks` or `wordBoxes`, gives each page its `width` and `height` in points. With `pageImages: true` (LlamaParse), each page carries `image`, an address for a picture of the page that expires after about an hour; `parse({ resume: id, pageImages: true })` collects fresh addresses without the file: one request that reads the finished job, in under a second, with no new parse and no credits charged. LlamaParse does not publish how long it keeps a job's result; plan for 48 hours (its retention for parse caches and uploaded files) and treat `NotFound` on resume as a job that must be parsed again. Every box is `{ left, top, width, height }` in fractions of the page from its top-left corner, whatever units the provider used, so boxes from different providers line up.
111
+ - `parse` returns `{ id, markdown, pages, blocks, pageCount }`. With `blocks: true`, `blocks` lists the layout in reading order: each block's `page`, `type` (the provider's own word), `text` and `box`. With `wordBoxes: true` (LlamaParse and Reducto), blocks also carry `words` and table `cells`, each with its own box. LlamaParse also places each line: a block's `lines` and a cell's `lines` are `{ text, box }`, the text being the line's part of the block's or cell's text, Markdown included. A table's `words` and `lines` are its cells', in reading order. Reducto places no lines. LlamaParse also gives a cell that sits in several boxes each of them as `boxes`, with `box` enclosing them; marks a block read out of a page header or footer with `container: "header"` or `"footer"`; and, with `blocks` or `wordBoxes`, gives each page its `width` and `height` in points. With `pageImages: true` (LlamaParse), each page carries `image`, an address for a picture of the page that expires after about an hour; `parse({ resume: id, pageImages: true })` collects fresh addresses without the file: one request that reads the finished job, in under a second, with no new parse and no credits charged. LlamaParse draws no pictures of a spreadsheet (xlsx, xls, csv, ods and the like), so a spreadsheet's pages come back without `image`. LlamaParse does not publish how long it keeps a job's result; plan for 48 hours (its retention for parse caches and uploaded files) and treat `NotFound` on resume as a job that must be parsed again. Every box is `{ left, top, width, height }` in fractions of the page from its top-left corner, whatever units the provider used, so boxes from different providers line up.
112
112
 
113
113
  A job that stopped early but produced output, for example on a credit or step limit, returns `status: "partial"` with `stopReason`. A job with no usable output throws `JobFailed`.
114
114
 
@@ -203,9 +203,10 @@ Every failure is a `FieldworkError`. It carries:
203
203
  - `retryable`: whether repeating the same call can succeed;
204
204
  - `retryAfter`, in seconds, when the provider sent one;
205
205
  - `jobId`, when a job had already started;
206
+ - `meta`, when the provider billed the call before it failed: the usage it reported, in the shape a result's `meta` has, such as `meta.usage.credits` for a Firecrawl download that reached a web page;
206
207
  - the provider's response, as `cause`.
207
208
 
208
- `error.toJSON()` returns these fields without the provider's response.
209
+ `error.toJSON()` returns these fields without the provider's response or `meta`.
209
210
 
210
211
  | Code | What happened | What to do |
211
212
  | --- | --- | --- |
package/dist/brave.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { C as createRawClient, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf } from "./parse-lMLcxUsG.js";
4
- import { a as compact, c as parseJson, f as refuseTogether, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
+ import { C as createRawClient, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf } from "./parse-Q7H4mrnO.js";
4
+ import { a as compact, c as parseJson, f as refuseTogether, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
5
5
  import * as z from "zod/mini";
6
6
  // src/adapters/brave/response.ts
7
7
  /** The `query` block every search response carries. */
@@ -1,8 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- 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, m as optionalScalar, r as arrayOf, s as optionalAnyString, v as recordOf } from "./parse-lMLcxUsG.js";
4
- import { a as compact, f as refuseTogether, l as presentPage, p as requireJobId, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
5
- import { a as presentFile, i as header, n as byteLimit, o as tooLarge, r as checkFileUrl, t as MIB } from "./download-gyAym9vL.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.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, m as optionalScalar, r as arrayOf, s as optionalAnyString, v as recordOf } from "./parse-Q7H4mrnO.js";
4
+ import { a as compact, f as refuseTogether, l as presentPage, p as requireJobId, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
5
+ import { a as presentFile, i as header, n as byteLimit, o as tooLarge, r as checkFileUrl, t as MIB } from "./download-CP8noBdX.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/browserbase/response.ts
8
8
  /** `POST /v1/sessions`. The id keeps the value as it arrived, for the error raised when there is none. */
@@ -1,5 +1,5 @@
1
- import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
2
- import { f as refuseTogether } from "./util-BqeRYF2b.js";
1
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
2
+ import { f as refuseTogether } from "./util-DFUXQX6v.js";
3
3
  import * as z from "zod/mini";
4
4
  // src/document.ts
5
5
  /** Content types of the document files parsers commonly take, by extension. */
@@ -1,4 +1,4 @@
1
- import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
1
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
2
2
  // src/download.ts
3
3
  /** One mebibyte, the unit the providers' ceilings are stated in. */
4
4
  const MIB = 1048576;
@@ -22,8 +22,11 @@ const byteLimit = (provider, ceiling, maxBytes) => {
22
22
  if (maxBytes > ceiling) throw invalidRequest(provider, `downloads at most ${ceiling} bytes; maxBytes ${maxBytes} is larger`);
23
23
  return maxBytes;
24
24
  };
25
- /** The error for a file over the limit. */
26
- const tooLarge = (provider, url, size, limit) => new FieldworkError("TooLarge", `${provider} could not download ${url}: the file is ${size === void 0 ? "larger than" : `${size} bytes, over`} the limit of ${limit} bytes`, { provider });
25
+ /** The error for a file over the limit, with what the provider billed for the fetch when it billed one. */
26
+ const tooLarge = (provider, url, size, limit, meta) => new FieldworkError("TooLarge", `${provider} could not download ${url}: the file is ${size === void 0 ? "larger than" : `${size} bytes, over`} the limit of ${limit} bytes`, {
27
+ meta,
28
+ provider
29
+ });
27
30
  /** Content types that are web pages rather than files. */
28
31
  const PAGE_TYPES = /* @__PURE__ */ new Set(["text/html", "application/xhtml+xml"]);
29
32
  /** Statuses that mean the file is not there. */
@@ -32,14 +35,16 @@ const GONE = /* @__PURE__ */ new Set([404, 410]);
32
35
  const header = (headers, name) => Object.entries(headers ?? {}).find(([key]) => key.toLowerCase() === name)?.[1];
33
36
  /** Throws `NotFound` for a 404 or 410 and `ProviderError` for any other status that is not 2xx. */
34
37
  const checkStatus = (provider, fetched) => {
35
- const { requested, statusCode } = fetched;
38
+ const { meta, requested, statusCode } = fetched;
36
39
  if (statusCode === void 0) return;
37
40
  if (GONE.has(statusCode)) throw new FieldworkError("NotFound", `${provider} could not download ${requested}: it answered ${statusCode}`, {
41
+ meta,
38
42
  provider,
39
43
  status: statusCode
40
44
  });
41
45
  if (statusCode < 200 || statusCode > 299) throw new FieldworkError("ProviderError", `${provider} could not download ${requested}: it answered ${statusCode}`, {
42
46
  cause: fetched.raw,
47
+ meta,
43
48
  provider,
44
49
  status: statusCode
45
50
  });
@@ -48,19 +53,24 @@ const checkStatus = (provider, fetched) => {
48
53
  * The checked file. Throws `NotFound` for a 404 or 410, `ProviderError` for
49
54
  * any other status that is not 2xx or a reply with no content type,
50
55
  * `NotAFile` for an HTML page, and `TooLarge` for more bytes than `limit`.
56
+ * Each error carries the fetch's `meta`: the provider billed it.
51
57
  */
52
58
  const presentFile = (provider, fetched, limit) => {
53
- const { requested, statusCode } = fetched;
59
+ const { meta, requested, statusCode } = fetched;
54
60
  checkStatus(provider, fetched);
55
61
  const { contentType } = fetched;
56
62
  if (contentType === void 0 || contentType === "") throw new FieldworkError("ProviderError", `${provider} downloaded ${requested} but reported no content type`, {
57
63
  cause: fetched.raw,
64
+ meta,
58
65
  provider
59
66
  });
60
67
  const mediaType = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
61
- if (PAGE_TYPES.has(mediaType)) throw new FieldworkError("NotAFile", `${provider} could not download ${requested}: it is a web page (${contentType}), not a file`, { provider });
68
+ if (PAGE_TYPES.has(mediaType)) throw new FieldworkError("NotAFile", `${provider} could not download ${requested}: it is a web page (${contentType}), not a file`, {
69
+ meta,
70
+ provider
71
+ });
62
72
  const bytes = "base64" in fetched.body ? new Uint8Array(Buffer.from(fetched.body.base64, "base64")) : new TextEncoder().encode(fetched.body.utf8);
63
- if (bytes.byteLength > limit) throw tooLarge(provider, requested, bytes.byteLength, limit);
73
+ if (bytes.byteLength > limit) throw tooLarge(provider, requested, bytes.byteLength, limit, meta);
64
74
  return {
65
75
  bytes,
66
76
  contentType,
@@ -68,7 +78,7 @@ const presentFile = (provider, fetched, limit) => {
68
78
  etag: header(fetched.headers, "etag"),
69
79
  lastModified: header(fetched.headers, "last-modified")
70
80
  },
71
- ...fetched.meta && { meta: fetched.meta },
81
+ ...meta && { meta },
72
82
  raw: fetched.raw,
73
83
  size: bytes.byteLength,
74
84
  ...statusCode !== void 0 && { statusCode },
@@ -20,6 +20,13 @@ var FieldworkError = class extends Error {
20
20
  * set, because repeating the call would start a second job; resume it.
21
21
  */
22
22
  retryable;
23
+ /**
24
+ * What the provider reported for a call it billed before the failure, in
25
+ * the shape a result's `meta` has: `meta.usage.credits` for Firecrawl's
26
+ * scrape, `meta.usage.units.uptime_ms` for a Kernel session. Absent when
27
+ * the call failed before the provider billed anything.
28
+ */
29
+ meta;
23
30
  constructor(code, message, options = {}) {
24
31
  super(message, { cause: options.cause });
25
32
  this.code = code;
@@ -27,6 +34,7 @@ var FieldworkError = class extends Error {
27
34
  this.status = options.status;
28
35
  this.retryAfter = options.retryAfter;
29
36
  this.jobId = options.jobId;
37
+ this.meta = options.meta;
30
38
  this.retryable = options.jobId === void 0 && (options.retryable ?? isRetryable(code, options.status));
31
39
  }
32
40
  /** The fields an agent or a log needs, without the provider's response. */
@@ -58,6 +66,7 @@ const withJob = (error, jobId) => {
58
66
  return new FieldworkError(error.code, error.message, {
59
67
  cause: error.cause,
60
68
  jobId,
69
+ meta: error.meta,
61
70
  provider: error.provider,
62
71
  retryAfter: error.retryAfter,
63
72
  status: error.status
package/dist/exa.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- 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, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-lMLcxUsG.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-COAaWnZB.js";
6
- import { a as compact, c as parseJson, d as record, i as citationsOf, m as uniqueCitations, o as hours, p as requireJobId, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
+ import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-Q7H4mrnO.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
+ import { a as compact, c as parseJson, d as record, i as citationsOf, m as uniqueCitations, o as hours, p as requireJobId, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
7
  import * as z from "zod/mini";
8
8
  const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
9
9
  /** The search types that take `additionalQueries`. */
@@ -1,4 +1,4 @@
1
- import { m as Capability, n as AnyAdapter } from "./adapter-DQrBP1tj.js";
1
+ import { L as Meta, m as Capability, n as AnyAdapter } from "./adapter-DQrBP1tj.js";
2
2
  /** Why a call failed. Branch on this, not on the message, which can change. */
3
3
  type FieldworkErrorCode =
4
4
  /** The adapter's provider does not offer this capability. */
@@ -37,6 +37,8 @@ interface FieldworkErrorOptions {
37
37
  retryable?: boolean;
38
38
  /** What the failure came from, such as the provider's parsed error body or the underlying fetch error. */
39
39
  cause?: unknown;
40
+ /** What the provider reported for a call it billed before the failure. */
41
+ meta?: Meta;
40
42
  }
41
43
  /** The one error type every adapter throws, with a normalized code. */
42
44
  declare class FieldworkError extends Error {
@@ -59,6 +61,13 @@ declare class FieldworkError extends Error {
59
61
  * set, because repeating the call would start a second job; resume it.
60
62
  */
61
63
  readonly retryable: boolean;
64
+ /**
65
+ * What the provider reported for a call it billed before the failure, in
66
+ * the shape a result's `meta` has: `meta.usage.credits` for Firecrawl's
67
+ * scrape, `meta.usage.units.uptime_ms` for a Kernel session. Absent when
68
+ * the call failed before the provider billed anything.
69
+ */
70
+ readonly meta?: Meta;
62
71
  constructor(code: FieldworkErrorCode, message: string, options?: FieldworkErrorOptions);
63
72
  /** The fields an agent or a log needs, without the provider's response. */
64
73
  toJSON(): {
package/dist/firecrawl.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- 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, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf } from "./parse-lMLcxUsG.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-COAaWnZB.js";
6
- import { a as compact, f as refuseTogether, l as presentPage, p as requireJobId, s as meta, t as callSettings, u as presentPages } from "./util-BqeRYF2b.js";
7
- import { a as presentFile, n as byteLimit, o as tooLarge, r as checkFileUrl, t as MIB } from "./download-gyAym9vL.js";
8
- import { a as mediaTypeOf, n as documentPart, o as refuseLarger, t as MEDIA_TYPES } from "./document-DOzhDFFt.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
+ import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf } from "./parse-Q7H4mrnO.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
+ import { a as compact, f as refuseTogether, l as presentPage, p as requireJobId, s as meta, t as callSettings, u as presentPages } from "./util-DFUXQX6v.js";
7
+ import { a as presentFile, n as byteLimit, o as tooLarge, r as checkFileUrl, t as MIB } from "./download-CP8noBdX.js";
8
+ import { a as mediaTypeOf, n as documentPart, o as refuseLarger, t as MEDIA_TYPES } from "./document-DMIUCoDA.js";
9
9
  import * as z from "zod/mini";
10
10
  // src/adapters/firecrawl/shared.ts
11
11
  const provider = "firecrawl";
@@ -1035,14 +1035,16 @@ const downloadFile = async (raw, url, options) => {
1035
1035
  }
1036
1036
  const { data, warning } = z.parse(ScrapeResponse, response);
1037
1037
  const { metadata } = data;
1038
+ const meta = pageMeta(data, warning.notes);
1038
1039
  if (data.rawBase64 === void 0) throw new FieldworkError("ProviderError", `firecrawl downloaded ${url} but returned no rawBase64 content`, {
1039
1040
  cause: response,
1041
+ meta,
1040
1042
  provider
1041
1043
  });
1042
1044
  return presentFile(provider, {
1043
1045
  body: { base64: data.rawBase64 },
1044
1046
  contentType: metadata.contentType,
1045
- meta: pageMeta(data, warning.notes),
1047
+ meta,
1046
1048
  raw: response,
1047
1049
  requested: url,
1048
1050
  statusCode: metadata.statusCode,
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { $ as SearchResponse, A as FailedUrl, B as MonitorInfo, C as DocumentInput, D as DownloadedFile, E as DownloadOptions, F as JsonSchema, G as Place, H as Page, I as LineBox, J as ProductImage, K as Price, L as Meta, M as GROUP_CAPABILITIES, N as ImageResult, O as Entity, P as ImageSearch, Q as RunStatus, R as MonitorEvent, S as DocumentBlock, T as DocumentUrl, U as PageBatch, V as MonitorSchedule, W as ParsedDocument, X as Recency, Y as ProductVariant, Z as Research, _ as Crawl, a as RawClient, at as WordBox, b as Decisions, c as ActResult, d as BrowserSession, et as SearchResult, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, it as Usage, j as FieldSource, k as Extraction, l as Answer, m as Capability, n as AnyAdapter, nt as SiteMap, o as RequestOptions, p as CallOptions, q as Product, r as Operations, rt as TableCell, s as AccountUsage, t as Adapter, tt as SiteLink, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as MonitorEvents } from "./adapter-DQrBP1tj.js";
2
- import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-DNwEf0Mo.js";
2
+ import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-JCfyw58T.js";
3
3
  import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-BFjS6CSz.js";
4
4
  /** Which adapter serves each capability, for `router`. */
5
5
  type Routes = Partial<Record<Capability, AnyAdapter>>;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
+ import { t as FieldworkError } from "./errors-DkFJysIM.js";
3
3
  import { n as GROUP_CAPABILITIES, t as CAPABILITIES } from "./types-rc8bl8Em.js";
4
4
  // src/fieldwork.ts
5
5
  /**
@@ -1,6 +1,6 @@
1
- import { i as withJob, t as FieldworkError } from "./errors-DROZyb9T.js";
2
- import { D as sleep, O as stopped } from "./parse-lMLcxUsG.js";
3
- import { p as requireJobId } from "./util-BqeRYF2b.js";
1
+ import { i as withJob, t as FieldworkError } from "./errors-DkFJysIM.js";
2
+ import { D as sleep, O as stopped } from "./parse-Q7H4mrnO.js";
3
+ import { p as requireJobId } from "./util-DFUXQX6v.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/job.ts
6
6
  /** The first wait between checks when `interval` is unset, and the longest. */
package/dist/kernel.js CHANGED
@@ -1,9 +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";
3
- import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.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
- 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";
2
+ import { a as presentFile, i as header, n as byteLimit, o as tooLarge, r as checkFileUrl, t as MIB } from "./download-CP8noBdX.js";
3
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.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-Q7H4mrnO.js";
5
+ import { a as compact, l as presentPage, p as requireJobId, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
6
+ import { r as runJob } from "./job-DnavRq_s.js";
7
7
  import * as z from "zod/mini";
8
8
  import TurndownService from "turndown";
9
9
  // src/adapters/kernel/response.ts
@@ -122,10 +122,17 @@ const billedTime = async (raw, id, call) => {
122
122
  return { warning: error instanceof FieldworkError && error.code === "Timeout" && error.status === void 0 && call.signal?.aborted !== true ? `kernel did not report the session's billed time within ${BILLED_TIME_WAIT / 1e3} seconds` : `could not get the session's billed time: ${error instanceof Error ? error.message : String(error)}` };
123
123
  }
124
124
  };
125
+ /** A session's billed time as `meta`: `usage.units.uptime_ms`, or a warning saying why it is missing. */
126
+ const sessionMeta = (id, billed) => meta({
127
+ requestId: id,
128
+ units: { uptime_ms: billed.uptimeMs },
129
+ warnings: billed.warning
130
+ });
125
131
  /**
126
132
  * Runs `work` in a new headless session and deletes the session whether or
127
133
  * not the work succeeded. A failure whose session could not be deleted fails
128
- * with its own error, naming the session that still bills.
134
+ * with its own error, naming the session that still bills; one whose session
135
+ * was deleted carries the session's billed time as `meta`.
129
136
  */
130
137
  const inSession = async (raw, o, call, work) => {
131
138
  const { provider } = raw;
@@ -147,7 +154,18 @@ const inSession = async (raw, o, call, work) => {
147
154
  const unreleased = await release(raw, id, call.retries);
148
155
  if (!done.ok) {
149
156
  const { error } = done;
150
- if (unreleased === void 0) throw error;
157
+ if (unreleased === void 0) {
158
+ if (!(error instanceof FieldworkError)) throw error;
159
+ throw new FieldworkError(error.code, error.message, {
160
+ cause: error.cause,
161
+ jobId: error.jobId,
162
+ meta: sessionMeta(id, await billedTime(raw, id, call)),
163
+ provider: error.provider,
164
+ retryAfter: error.retryAfter,
165
+ retryable: error.retryable,
166
+ status: error.status
167
+ });
168
+ }
151
169
  const message = `${error instanceof Error ? error.message : String(error)}; also ${leakText(id, unreleased)}`;
152
170
  throw error instanceof FieldworkError ? new FieldworkError(error.code, message, {
153
171
  cause: error,
@@ -332,9 +350,11 @@ const downloadFile = async (raw, url, options) => {
332
350
  };
333
351
  });
334
352
  const { file, response } = value;
335
- if (file.tooLarge !== void 0) throw tooLarge(provider, url, file.tooLarge, limit);
353
+ const billedMeta = sessionMeta(id, billed);
354
+ if (file.tooLarge !== void 0) throw tooLarge(provider, url, file.tooLarge, limit, billedMeta);
336
355
  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
356
  cause: response,
357
+ meta: billedMeta,
338
358
  provider
339
359
  });
340
360
  const { headers } = file;
@@ -342,11 +362,7 @@ const downloadFile = async (raw, url, options) => {
342
362
  body: { base64: file.data ?? "" },
343
363
  contentType: header(headers, "content-type"),
344
364
  headers,
345
- meta: meta({
346
- requestId: id,
347
- units: { uptime_ms: billed.uptimeMs },
348
- warnings: billed.warning
349
- }),
365
+ meta: billedMeta,
350
366
  raw: {
351
367
  browser: created,
352
368
  execute: response
@@ -35,6 +35,8 @@ export interface LlamaParseParseOptions extends CallOptions {
35
35
  * expires after about an hour. Collect fresh addresses with
36
36
  * `parse({ resume: id, pageImages: true })`; a parse started without
37
37
  * `pageImages` saved no pictures, so resuming it with them throws.
38
+ * LlamaParse draws no pictures of a spreadsheet, so its pages come back
39
+ * without `image`.
38
40
  */
39
41
  pageImages?: boolean;
40
42
  /** The id of a job from an error's `jobId`; waits for it instead of starting another. */
@@ -1,9 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { i as enclosing, n as documentPart, o as refuseLarger, r as documentUrl } from "./document-DOzhDFFt.js";
3
- import { t as FieldworkError } from "./errors-DROZyb9T.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, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-lMLcxUsG.js";
5
- import { i as startJob, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
6
- import { a as compact, c as parseJson, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
2
+ import { i as enclosing, n as documentPart, o as refuseLarger, r as documentUrl } from "./document-DMIUCoDA.js";
3
+ import { t as FieldworkError } from "./errors-DkFJysIM.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, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-Q7H4mrnO.js";
5
+ import { i as startJob, r as runJob, t as jobState } from "./job-DnavRq_s.js";
6
+ import { a as compact, c as parseJson, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
7
  import * as z from "zod/mini";
8
8
  // src/adapters/llamaparse/response.ts
9
9
  /** A box in page points, from the page's top-left corner. */
@@ -63,6 +63,8 @@ const JobResult = withOriginal(looseObject({
63
63
  items: looseObject({ pages: arrayOf(ItemsPage) }),
64
64
  job: looseObject({
65
65
  error_message: optionalString,
66
+ /** The file's name as uploaded, or as read from its address. */
67
+ name: optionalString,
66
68
  status: optionalString,
67
69
  usage: looseObject({ credits: optionalNumber })
68
70
  }),
@@ -243,27 +245,41 @@ const groundedPages = async (found, options) => {
243
245
  });
244
246
  return (await readSigned(provider, url, options)).split("\n").filter((line) => line.trim() !== "").map((line) => parseJson(provider, line));
245
247
  };
246
- /** Each page's picture, keyed by page number, from the job's saved screenshots. */
247
- const pageImageAddresses = (found, id) => {
248
+ /**
249
+ * Spreadsheet files, which LlamaParse reads sheet by sheet into tables and
250
+ * never draws, so it saves no page pictures for them: the inputs its
251
+ * Spreadsheets page lists, by extension.
252
+ */
253
+ const SPREADSHEET = /\.(?:csv|dbf|dif|numbers|ods|slk|tsv|xls|xlsb|xlsm|xlsx)$/iu;
254
+ /**
255
+ * Each page's picture, keyed by page number, from the job's saved
256
+ * screenshots; empty when LlamaParse drew none for a job that asked.
257
+ * LlamaParse does not say what a job asked for, so a job counts as having
258
+ * asked when this call started it with `pageImages`, or when its file is a
259
+ * spreadsheet, which has no pictures whatever it asked. A resumed job with
260
+ * no pictures otherwise was started without `pageImages`, and throws.
261
+ */
262
+ const pageImageAddresses = (found, id, started) => {
248
263
  const addresses = /* @__PURE__ */ new Map();
249
264
  for (const image of found.value.images_content_metadata.images) {
250
265
  const page = PAGE_IMAGE.exec(image.filename ?? "")?.groups?.page;
251
266
  if (page !== void 0 && image.presigned_url !== void 0) addresses.set(Number(page), image.presigned_url);
252
267
  }
253
- if (addresses.size === 0) throw new FieldworkError("ProviderError", `llamaparse job ${id} has no page pictures; only a parse started with pageImages saves them`, {
268
+ const asked = started || SPREADSHEET.test(found.value.job.name ?? "");
269
+ if (addresses.size === 0 && !asked) throw new FieldworkError("ProviderError", `llamaparse job ${id} has no page pictures; only a parse started with pageImages saves them`, {
254
270
  cause: found.original,
255
271
  provider
256
272
  });
257
273
  return addresses;
258
274
  };
259
275
  /** The finished job as a document, with word boxes and page pictures when they were asked for. */
260
- const parsedDocument = async (found, id, o, read) => {
276
+ const parsedDocument = async (found, id, o, read, started) => {
261
277
  if (found.value.markdown.pages.length === 0) throw new FieldworkError("ProviderError", `llamaparse finished job ${id} without any pages of Markdown`, {
262
278
  cause: found.original,
263
279
  provider
264
280
  });
265
281
  const grounded = o.wordBoxes === true ? await groundedPages(found, read) : void 0;
266
- const images = o.pageImages === true ? pageImageAddresses(found, id) : void 0;
282
+ const images = o.pageImages === true ? pageImageAddresses(found, id, started) : void 0;
267
283
  let laidOut;
268
284
  if (grounded !== void 0) laidOut = grounded.map((row) => z.parse(ItemsPage, row));
269
285
  else if (o.blocks === true) laidOut = found.value.items.pages;
@@ -271,7 +287,7 @@ const parsedDocument = async (found, id, o, read) => {
271
287
  const pages = found.value.markdown.pages.flatMap((page) => {
272
288
  if (page.page_number === void 0) return [];
273
289
  const image = images?.get(page.page_number);
274
- if (images !== void 0 && image === void 0) throw new FieldworkError("ProviderError", `llamaparse job ${id} has no picture of page ${page.page_number}`, {
290
+ if (images !== void 0 && images.size > 0 && image === void 0) throw new FieldworkError("ProviderError", `llamaparse job ${id} has no picture of page ${page.page_number}`, {
275
291
  cause: found.original,
276
292
  provider
277
293
  });
@@ -299,10 +315,12 @@ const parsedDocument = async (found, id, o, read) => {
299
315
  /** Runs the job. `expand` names the sections of the result to include; blocks, word boxes and page images each add one. */
300
316
  const parse = async (raw, document, options, fetchImpl) => {
301
317
  const { call, rest: o } = callSettings(options);
318
+ const blocks = o.blocks === true || o.wordBoxes === true;
319
+ let started = false;
302
320
  const expand = [
303
321
  "markdown",
304
322
  "usage",
305
- ...o.blocks === true || o.wordBoxes === true ? ["items"] : [],
323
+ ...blocks ? ["items"] : [],
306
324
  ...o.pageImages === true ? ["images_content_metadata"] : []
307
325
  ].join(",");
308
326
  return await runJob(provider, {
@@ -313,8 +331,11 @@ const parse = async (raw, document, options, fetchImpl) => {
313
331
  finish: async (found, id) => await parsedDocument(found, id, o, {
314
332
  fetch: fetchImpl,
315
333
  signal: call.signal
316
- }),
317
- start: async () => await startParse(raw, document, o, call)
334
+ }, started),
335
+ start: async () => {
336
+ started = true;
337
+ return await startParse(raw, document, o, call);
338
+ }
318
339
  }, {
319
340
  ...call,
320
341
  interval: o.interval,
package/dist/parallel.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, v as recordOf, x as warnings, y as sourceShape } from "./parse-lMLcxUsG.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-COAaWnZB.js";
6
- import { a as compact, c as parseJson, f as refuseTogether, i as citationsOf, m as uniqueCitations, p as requireJobId, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
2
+ import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
+ import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, _ as optionalStructure, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, v as recordOf, x as warnings, y as sourceShape } from "./parse-Q7H4mrnO.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
+ import { a as compact, c as parseJson, f as refuseTogether, i as citationsOf, m as uniqueCitations, p as requireJobId, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
7
  import * as z from "zod/mini";
8
8
  // src/adapters/parallel/parse.ts
9
9
  /** The name this adapter reports in errors and results. */
@@ -1,5 +1,5 @@
1
- import { n as codeForStatus, t as FieldworkError } from "./errors-DROZyb9T.js";
2
- import { d as record, n as checkCallSettings } from "./util-BqeRYF2b.js";
1
+ import { n as codeForStatus, t as FieldworkError } from "./errors-DkFJysIM.js";
2
+ import { d as record, n as checkCallSettings } from "./util-DFUXQX6v.js";
3
3
  import * as z from "zod/mini";
4
4
  /**
5
5
  * Waits `ms`. When `signal` aborts it resolves early rather than rejecting, so
@@ -1,9 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- 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, i as both, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, y as sourceShape } from "./parse-lMLcxUsG.js";
4
- import { i as startJob, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-COAaWnZB.js";
6
- import { a as compact, c as parseJson, f as refuseTogether, m as uniqueCitations, r as citationOf, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.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, i as both, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, y as sourceShape } from "./parse-Q7H4mrnO.js";
4
+ import { i as startJob, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
+ import { a as compact, c as parseJson, f as refuseTogether, m as uniqueCitations, r as citationOf, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
7
  import * as z from "zod/mini";
8
8
  // src/adapters/perplexity/parse.ts
9
9
  /** The name this adapter reports in errors and results. */
package/dist/reducto.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { n as documentPart, o as refuseLarger, r as documentUrl } from "./document-DOzhDFFt.js";
3
- import { t as FieldworkError } from "./errors-DROZyb9T.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, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-lMLcxUsG.js";
5
- import { i as startJob, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
6
- import { a as compact, c as parseJson, p as requireJobId, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
2
+ import { n as documentPart, o as refuseLarger, r as documentUrl } from "./document-DMIUCoDA.js";
3
+ import { t as FieldworkError } from "./errors-DkFJysIM.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, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-Q7H4mrnO.js";
5
+ import { i as startJob, r as runJob, t as jobState } from "./job-DnavRq_s.js";
6
+ import { a as compact, c as parseJson, p as requireJobId, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
7
  import * as z from "zod/mini";
8
8
  // src/adapters/reducto/response.ts
9
9
  /** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
@@ -1,4 +1,4 @@
1
- import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
1
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
2
2
  import { o as isText, r as isJsonObject, t as joinPath } from "./path-DL5P8XH2.js";
3
3
  // src/schema-subset.ts
4
4
  const MAPS = /* @__PURE__ */ new Set([
package/dist/serpapi.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { C as createRawClient, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings } from "./parse-lMLcxUsG.js";
4
- import { a as compact, f as refuseTogether, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.js";
3
+ import { C as createRawClient, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings } from "./parse-Q7H4mrnO.js";
4
+ import { a as compact, f as refuseTogether, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
5
5
  import * as z from "zod/mini";
6
6
  // src/adapters/serpapi/parse.ts
7
7
  /** The name this adapter reports in errors and results. */
package/dist/tavily.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- 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, m as optionalScalar, n as anything, r as arrayOf } from "./parse-lMLcxUsG.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-COAaWnZB.js";
6
- import { a as compact, o as hours, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DkFJysIM.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, m as optionalScalar, n as anything, r as arrayOf } from "./parse-Q7H4mrnO.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DnavRq_s.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema--iU4AXSM.js";
6
+ import { a as compact, o as hours, s as meta, t as callSettings } from "./util-DFUXQX6v.js";
7
7
  import * as z from "zod/mini";
8
8
  // src/adapters/tavily/countries.ts
9
9
  /** Tavily's country names, by ISO 3166-1 alpha-2 code. */
package/dist/tools.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-DNwEf0Mo.js";
1
+ import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-JCfyw58T.js";
2
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;
package/dist/tools.js CHANGED
@@ -1,5 +1,5 @@
1
- import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
- import { f as refuseTogether } from "./util-BqeRYF2b.js";
1
+ import { t as FieldworkError } from "./errors-DkFJysIM.js";
2
+ import { f as refuseTogether } from "./util-DFUXQX6v.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
4
  import { t as CAPABILITIES } from "./types-rc8bl8Em.js";
5
5
  import * as z from "zod/mini";
@@ -1,4 +1,4 @@
1
- import { t as FieldworkError } from "./errors-DROZyb9T.js";
1
+ import { t as FieldworkError } from "./errors-DkFJysIM.js";
2
2
  // src/util.ts
3
3
  const isJson = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
4
  /** The value as an object, or an empty one when it is null, an array or not an object, so a read of a missing body needs no guard. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
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",