@howells/fieldwork-sdk 0.6.1 → 0.8.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,5 +1,8 @@
1
1
  import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
+ import { f as refuseTogether } from "./util-BqeRYF2b.js";
3
+ import { a as isNumber, i as isList, n as isFlag, o as isText, r as isJsonObject, t as joinPath } from "./path-DL5P8XH2.js";
2
4
  import { t as CAPABILITIES } from "./types-CnomnF-6.js";
5
+ import * as z from "zod/mini";
3
6
  // src/tool-specs/schema.ts
4
7
  const described = (schema, description) => description === void 0 ? schema : {
5
8
  ...schema,
@@ -458,6 +461,11 @@ const box = object({
458
461
  "width",
459
462
  "height"
460
463
  ], "Where it sits on the page, as fractions of the page's width and height from its top-left corner.");
464
+ /** A word or a line: its text and where it sits. */
465
+ const placedText = object({
466
+ box,
467
+ text: str
468
+ }, ["text", "box"]);
461
469
  /** The result of `parse_document`, a `ParsedDocument`. */
462
470
  const PARSE_OUTPUT = object({
463
471
  blocks: list(object({
@@ -466,6 +474,7 @@ const PARSE_OUTPUT = object({
466
474
  box,
467
475
  column: whole("The column, from 0.", 0),
468
476
  columnSpan: whole("Columns the cell spans.", 1),
477
+ lines: list(placedText),
469
478
  row: whole("The row, from 0.", 0),
470
479
  rowSpan: whole("Rows the cell spans.", 1),
471
480
  text: str
@@ -474,13 +483,11 @@ const PARSE_OUTPUT = object({
474
483
  "column",
475
484
  "text"
476
485
  ])),
486
+ lines: list(placedText),
477
487
  page: whole("The physical page number, starting at 1.", 1),
478
488
  text: str,
479
489
  type: str,
480
- words: list(object({
481
- box,
482
- text: str
483
- }, ["text", "box"]))
490
+ words: list(placedText)
484
491
  }, [
485
492
  "page",
486
493
  "type",
@@ -708,8 +715,8 @@ const ANSWER_SPECS = [
708
715
  * The tools that drive a browser or convert a file: `run_browser_script`,
709
716
  * `open_browser`, `close_browser` and `parse_document`. `toolsFor` leaves out
710
717
  * the first three unless asked, since they start billed sessions with real
711
- * effects; `parse_document` is a normal tool. Its `name` and `contentBase64`
712
- * become the one file argument `parse` takes.
718
+ * effects; `parse_document` is a normal tool. Its URL or name and bytes
719
+ * become the one document argument `parse` takes.
713
720
  */
714
721
  const BROWSER_SPECS = [
715
722
  {
@@ -787,19 +794,24 @@ const BROWSER_SPECS = [
787
794
  },
788
795
  {
789
796
  capability: "parse",
790
- description: "Convert a document file (PDF, DOCX, XLSX, PPTX, HTML or CSV) to Markdown. Use when you have the file's bytes. Do not use for a document at a public URL (use read_page).",
797
+ description: "Convert a document file (PDF, DOCX, XLSX, PPTX, HTML or CSV) to Markdown. Use name and contentBase64 for bytes, or a public url with LlamaParse or Reducto. Firecrawl accepts bytes here; use read_page for a public URL.",
791
798
  destructive: false,
792
799
  fields: [
793
800
  {
794
801
  name: "name",
795
- required: true,
802
+ requiredFor: ["firecrawl"],
796
803
  schema: text("The file name with its extension, such as spec-sheet.pdf. The extension tells the provider the type.")
797
804
  },
798
805
  {
799
806
  name: "contentBase64",
800
- required: true,
807
+ requiredFor: ["firecrawl"],
801
808
  schema: text("The file's bytes, base64-encoded.")
802
809
  },
810
+ {
811
+ name: "url",
812
+ providers: ["llamaparse", "reducto"],
813
+ schema: url("Public HTTP or HTTPS document URL; the provider fetches it. Use instead of name and contentBase64 for large files.")
814
+ },
803
815
  {
804
816
  name: "pages",
805
817
  providers: ["firecrawl"],
@@ -810,7 +822,11 @@ const BROWSER_SPECS = [
810
822
  idempotent: true,
811
823
  name: "parse_document",
812
824
  output: PARSE_OUTPUT,
813
- positional: ["name", "contentBase64"],
825
+ positional: [
826
+ "name",
827
+ "contentBase64",
828
+ "url"
829
+ ],
814
830
  readOnly: true,
815
831
  title: "Convert a document to Markdown"
816
832
  }
@@ -1255,14 +1271,14 @@ const SPECS = [
1255
1271
  ...BROWSER_SPECS,
1256
1272
  ...MONITOR_SPECS
1257
1273
  ];
1258
- // src/tools/json.ts
1259
- const isText = (value) => typeof value === "string";
1260
- /** A finite number: JSON has no NaN or Infinity. */
1261
- const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
1262
- const isFlag = (value) => typeof value === "boolean";
1263
- const isList = (value) => Array.isArray(value);
1264
- /** Narrows anything, such as a value a transport hands over, to a JSON object. */
1265
- const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1274
+ // src/tools/budget.ts
1275
+ const DEFAULT_MAX_CHARACTERS = 2e4;
1276
+ /** Checks configured and per-call budgets against the same optional cap. */
1277
+ const checkMaxCharacters = (value, limit = Number.MAX_SAFE_INTEGER) => {
1278
+ const parsed = z.safeParse(z.number().check(z.int(), z.minimum(1), z.maximum(limit)), value);
1279
+ if (!parsed.success) throw new FieldworkError("InvalidRequest", `maxCharacters must be an integer from 1 to ${limit}`);
1280
+ return parsed.data;
1281
+ };
1266
1282
  // src/tools/dispatch.ts
1267
1283
  const isOperation = (value) => typeof value === "function";
1268
1284
  const isGroup = (value) => isJsonObject(value);
@@ -1280,8 +1296,12 @@ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/u;
1280
1296
  * Throws `InvalidRequest` when either is not a string or the content is not
1281
1297
  * well-formed base64 (standard alphabet, padded to a multiple of 4).
1282
1298
  */
1283
- const documentFrom = (name, content) => {
1284
- if (!isText(name) || !isText(content)) throw new FieldworkError("InvalidRequest", "parse_document needs name and contentBase64");
1299
+ const documentFrom = (provider, values) => {
1300
+ refuseTogether(provider, values, "url", "contentBase64");
1301
+ refuseTogether(provider, values, "url", "name");
1302
+ const { contentBase64: content, name, url } = values;
1303
+ if (isText(url)) return { url };
1304
+ if (!isText(name) || !isText(content)) throw new FieldworkError("InvalidRequest", "parse_document needs name and contentBase64, or a public url with llamaparse or reducto");
1285
1305
  if (content.length % 4 !== 0 || !BASE64.test(content)) throw new FieldworkError("InvalidRequest", `parse_document: contentBase64 must be standard base64 padded to a multiple of 4 characters${content.startsWith("data:") ? "; remove the data: prefix" : ""}`);
1286
1306
  return {
1287
1307
  data: new Uint8Array(Buffer.from(content, "base64")),
@@ -1292,15 +1312,15 @@ const documentFrom = (name, content) => {
1292
1312
  * The arguments for the spec's method, from validated input and the call
1293
1313
  * settings: the `positional` fields in order, then one options object of the
1294
1314
  * other fields and the call settings (`signal`, `timeout`, `retries`). `parse`
1295
- * is the exception: its two positional fields become one `DocumentArgument`.
1315
+ * is the exception: its source fields become one `DocumentArgument`.
1296
1316
  */
1297
- const argumentsFor = (spec, values, call) => {
1317
+ const argumentsFor = (spec, values, call, provider) => {
1298
1318
  const options = {
1299
1319
  ...Object.fromEntries(Object.entries(values).filter(([key]) => !spec.positional.includes(key))),
1300
1320
  ...call
1301
1321
  };
1302
1322
  const positional = spec.positional.map((name) => values[name]);
1303
- if (spec.capability === "parse") return [documentFrom(positional[0], positional[1]), options];
1323
+ if (spec.capability === "parse") return [documentFrom(provider, values), options];
1304
1324
  return [...positional, options];
1305
1325
  };
1306
1326
  // src/tools/model.ts
@@ -1337,11 +1357,17 @@ const rank = (key) => {
1337
1357
  return SPEND_LAST.includes(key) ? SPEND_FIRST.length + 1 + SPEND_LAST.indexOf(key) : SPEND_FIRST.length;
1338
1358
  };
1339
1359
  /** The text whole if it is short or the budget covers it; otherwise cut to what is left of the budget, with a note of how much was shown. Short text spends nothing. */
1340
- const cut = (value, budget) => {
1360
+ const cut = (value, budget, path) => {
1341
1361
  if (value.length <= SHORT_TEXT) return value;
1342
1362
  const kept = Math.min(value.length, budget.remaining);
1343
1363
  budget.remaining -= kept;
1344
- return kept === value.length ? value : `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
1364
+ if (kept === value.length) return value;
1365
+ budget.truncated.push({
1366
+ length: value.length,
1367
+ path: joinPath(path),
1368
+ shown: kept
1369
+ });
1370
+ return `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
1345
1371
  };
1346
1372
  /**
1347
1373
  * Applies `cut` and the `raw` rule through a value. Fields are visited in
@@ -1349,13 +1375,13 @@ const cut = (value, budget) => {
1349
1375
  * object keeps its own key order. `verbatim` is set inside `VERBATIM` keys and
1350
1376
  * stays set below them.
1351
1377
  */
1352
- const shape = (value, verbatim, budget) => {
1353
- if (isText(value)) return cut(value, budget);
1354
- if (isList(value)) return value.map((item) => shape(item, verbatim, budget) ?? null);
1378
+ const shape = (value, verbatim, budget, path) => {
1379
+ if (isText(value)) return cut(value, budget, path);
1380
+ if (isList(value)) return value.map((item, index) => shape(item, verbatim, budget, [...path, index]) ?? null);
1355
1381
  if (!isJsonObject(value)) return value;
1356
1382
  const entries = Object.entries(value).filter(([key]) => verbatim || key !== "raw");
1357
1383
  const shaped = /* @__PURE__ */ new Map();
1358
- for (const [key, item] of entries.toSorted(([a], [b]) => rank(a) - rank(b))) shaped.set(key, shape(item, verbatim || VERBATIM.has(key), budget));
1384
+ for (const [key, item] of entries.toSorted(([a], [b]) => rank(a) - rank(b))) shaped.set(key, shape(item, verbatim || VERBATIM.has(key), budget, [...path, key]));
1359
1385
  return Object.fromEntries(entries.map(([key]) => [key, shaped.get(key)]));
1360
1386
  };
1361
1387
  /**
@@ -1365,8 +1391,14 @@ const shape = (value, verbatim, budget) => {
1365
1391
  * served first and alternate renderings such as HTML last.
1366
1392
  */
1367
1393
  const forModel = (result, budget) => {
1368
- const shaped = shape(result, false, { remaining: budget });
1369
- return isJsonObject(shaped) ? shaped : {};
1394
+ const truncated = [];
1395
+ const shaped = shape(result, false, {
1396
+ remaining: budget,
1397
+ truncated
1398
+ }, []);
1399
+ const output = isJsonObject(shaped) ? shaped : {};
1400
+ if (truncated.length > 0) output.truncated = truncated;
1401
+ return output;
1370
1402
  };
1371
1403
  // src/tools/validate.ts
1372
1404
  /** The shape only: 2026-02-31 passes and is the provider's to refuse. */
@@ -1488,13 +1520,23 @@ const resultObject = (spec, values, result) => {
1488
1520
  throw new FieldworkError("ProviderError", `${spec.name} got a result that is not an object`);
1489
1521
  };
1490
1522
  /** The JSON Schema advertised for the tool's input: closed to other keys, requiring what `needs` says. */
1491
- const inputSchema = (fields, provider) => ({
1492
- additionalProperties: false,
1493
- properties: Object.fromEntries(fields.map((field) => [field.name, { ...field.schema }])),
1494
- required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1495
- type: "object"
1496
- });
1497
- const toolFor = (spec, provider, operation, budget) => {
1523
+ const inputSchema = (fields, provider, budget, limit) => {
1524
+ const schema = {
1525
+ additionalProperties: false,
1526
+ properties: Object.fromEntries([...fields.map((field) => [field.name, { ...field.schema }]), ["maxCharacters", { ...whole(`Shared long-text budget for this call; defaults to ${budget}. Never sent to the provider.`, 1, limit) }]]),
1527
+ required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1528
+ type: "object"
1529
+ };
1530
+ if (fields.some((field) => field.name === "contentBase64") && fields.some((field) => field.name === "url")) schema.oneOf = [{
1531
+ not: { anyOf: [{ required: ["name"] }, { required: ["contentBase64"] }] },
1532
+ required: ["url"]
1533
+ }, {
1534
+ not: { required: ["url"] },
1535
+ required: ["name", "contentBase64"]
1536
+ }];
1537
+ return schema;
1538
+ };
1539
+ const toolFor = (spec, provider, operation, budget, limit) => {
1498
1540
  const fields = spec.fields.filter((field) => offers(field, provider));
1499
1541
  return {
1500
1542
  annotations: {
@@ -1507,14 +1549,31 @@ const toolFor = (spec, provider, operation, budget) => {
1507
1549
  capability: spec.capability,
1508
1550
  description: spec.description,
1509
1551
  execute: async (input, call = {}) => {
1510
- const values = readInput(spec.name, provider, fields, input);
1511
- const result = await operation(...argumentsFor(spec, values, call));
1512
- return forModel(resultObject(spec, values, result), budget);
1552
+ if (!isJsonObject(input)) throw invalid(spec.name, provider, "input must be an object");
1553
+ const { maxCharacters, ...args } = input;
1554
+ const values = readInput(spec.name, provider, fields, args);
1555
+ const callBudget = maxCharacters === void 0 ? budget : checkMaxCharacters(maxCharacters, limit);
1556
+ const result = await operation(...argumentsFor(spec, values, call, provider));
1557
+ return forModel(resultObject(spec, values, result), callBudget);
1513
1558
  },
1514
- inputSchema: inputSchema(fields, provider),
1559
+ inputSchema: inputSchema(fields, provider, budget, limit),
1515
1560
  method: spec.method,
1516
1561
  name: spec.name,
1517
- outputSchema: { ...spec.output },
1562
+ outputSchema: {
1563
+ ...spec.output,
1564
+ properties: {
1565
+ ...spec.output.properties,
1566
+ truncated: list(object({
1567
+ length: whole("Original character length.", 0),
1568
+ path: str,
1569
+ shown: whole("Characters shown before the inline cut note.", 0)
1570
+ }, [
1571
+ "path",
1572
+ "shown",
1573
+ "length"
1574
+ ]), "One entry for each cut text field; absent when nothing was cut.")
1575
+ }
1576
+ },
1518
1577
  provider
1519
1578
  };
1520
1579
  };
@@ -1525,12 +1584,13 @@ const toolFor = (spec, provider, operation, budget) => {
1525
1584
  */
1526
1585
  const toolsFor = (web, options = {}) => {
1527
1586
  const wanted = /* @__PURE__ */ new Set([...options.capabilities ?? CAPABILITIES.filter((capability) => !EXCLUDED_BY_DEFAULT.includes(capability)), ...options.allow ?? []]);
1528
- const budget = options.maxCharacters ?? 2e4;
1587
+ const limit = options.maxCharactersLimit === void 0 ? void 0 : checkMaxCharacters(options.maxCharactersLimit);
1588
+ const budget = checkMaxCharacters(options.maxCharacters ?? 2e4, limit);
1529
1589
  const dispatcher = web;
1530
1590
  return SPECS.flatMap((spec) => {
1531
1591
  const provider = web.providerFor(spec.capability);
1532
1592
  const operation = operationFor(dispatcher, spec);
1533
- return wanted.has(spec.capability) && provider !== void 0 && operation !== void 0 ? [toolFor(spec, provider, operation, budget)] : [];
1593
+ return wanted.has(spec.capability) && provider !== void 0 && operation !== void 0 ? [toolFor(spec, provider, operation, budget, limit)] : [];
1534
1594
  });
1535
1595
  };
1536
1596
  /**
@@ -1548,4 +1608,4 @@ const toolError = (cause) => {
1548
1608
  retryable: false
1549
1609
  };
1550
1610
  };
1551
- export { EXCLUDED_BY_DEFAULT, toolError, toolsFor };
1611
+ export { DEFAULT_MAX_CHARACTERS, EXCLUDED_BY_DEFAULT, checkMaxCharacters, toolError, toolsFor };
@@ -0,0 +1,148 @@
1
+ import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
+ // src/util.ts
3
+ const isJson = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
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. */
5
+ const record = (value) => isJson(value) ? value : {};
6
+ /** Drops the keys whose value is undefined, so a request body or result carries only what was set. Shallow: nested objects are not touched. */
7
+ const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
8
+ /** The longest `timeout` a timer holds, in milliseconds: about 24.8 days. */
9
+ const MAX_TIMEOUT = 2147483647;
10
+ /**
11
+ * Refuses a `timeout` or `retries` that no timer or retry count can hold,
12
+ * before anything is sent.
13
+ *
14
+ * Throws `InvalidRequest` naming the accepted range.
15
+ */
16
+ const checkCallSettings = (settings) => {
17
+ const { retries, timeout } = settings;
18
+ if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 0 && timeout <= MAX_TIMEOUT)) throw new FieldworkError("InvalidRequest", `timeout is ${timeout}: pass a whole number of milliseconds from 0 to ${MAX_TIMEOUT}`);
19
+ if (retries !== void 0 && !(Number.isInteger(retries) && retries >= 0)) throw new FieldworkError("InvalidRequest", `retries is ${retries}: pass a whole number from 0 up`);
20
+ };
21
+ /**
22
+ * Splits an operation's options into the provider's own and the call's
23
+ * settings. The call's `signal` also carries its `timeout` as a deadline, set
24
+ * now, so every request the operation makes (a start, each poll, a result
25
+ * download) shares one budget instead of restarting it. An empty `resume`
26
+ * names no job, and a `timeout` or `retries` out of range holds no deadline or
27
+ * count, so both are refused here, once for every adapter.
28
+ *
29
+ * `grace` extends the deadline past `timeout` for an operation that sends the
30
+ * timeout to the provider and needs a moment more to hear its report.
31
+ */
32
+ const callSettings = (options, grace = 0) => {
33
+ const { retries, signal, timeout, ...rest } = options ?? {};
34
+ if ("resume" in rest && rest.resume === "") throw new FieldworkError("InvalidRequest", "resume is empty: pass the jobId an earlier call returned, or leave resume out to start a job");
35
+ checkCallSettings({
36
+ retries,
37
+ timeout
38
+ });
39
+ return {
40
+ call: {
41
+ retries,
42
+ signal: timeout === void 0 ? signal : AbortSignal.any([...signal === void 0 ? [] : [signal], AbortSignal.timeout(Math.min(timeout + grace, MAX_TIMEOUT))]),
43
+ timeout
44
+ },
45
+ rest
46
+ };
47
+ };
48
+ /**
49
+ * Reads a provider field that holds JSON text. A value that is not a string
50
+ * is returned as it is, already parsed.
51
+ *
52
+ * Throws `ProviderError` carrying the parse error as `cause` when the text is
53
+ * not valid JSON.
54
+ */
55
+ const parseJson = (provider, value) => {
56
+ if (typeof value !== "string") return value;
57
+ try {
58
+ return JSON.parse(value);
59
+ } catch (error) {
60
+ throw new FieldworkError("ProviderError", `${provider} returned output that is not valid JSON`, {
61
+ cause: error,
62
+ provider
63
+ });
64
+ }
65
+ };
66
+ /** The citations with repeated URLs removed: the first of each URL stays, in order. */
67
+ const uniqueCitations = (all) => {
68
+ const seen = /* @__PURE__ */ new Map();
69
+ for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
70
+ return [...seen.values()];
71
+ };
72
+ /** The citation a parsed source amounts to, or undefined when it has no URL. */
73
+ const citationOf = (source) => source.url === void 0 ? void 0 : compact({
74
+ excerpts: source.excerpts,
75
+ title: source.title,
76
+ url: source.url
77
+ });
78
+ /** The citations the parsed sources amount to; a source without a URL is left out. */
79
+ const citationsOf = (sources) => sources.map((source) => citationOf(source)).filter((item) => item !== void 0);
80
+ /** The job id a start call returned, or a ProviderError carrying the value as it arrived. */
81
+ const requireJobId = (provider, id) => {
82
+ if (id.value === void 0) throw new FieldworkError("ProviderError", `${provider} did not return a job id`, {
83
+ cause: id.original,
84
+ provider
85
+ });
86
+ return id.value;
87
+ };
88
+ /**
89
+ * Builds a result's `meta`, leaving out whatever is absent: `units` with an
90
+ * undefined count, an empty `usage`, no `warnings`. A single warning string
91
+ * becomes a one-item list. Returns undefined when nothing is left, so a result
92
+ * has no `meta` at all rather than an empty one.
93
+ */
94
+ const meta = (parts) => {
95
+ const units = Object.fromEntries(Object.entries(parts.units ?? {}).filter((entry) => entry[1] !== void 0));
96
+ const usage = compact({
97
+ costUsd: parts.costUsd,
98
+ credits: parts.credits,
99
+ units: Object.keys(units).length > 0 ? units : void 0
100
+ });
101
+ const warnings = [parts.warnings ?? []].flat();
102
+ const result = compact({
103
+ requestId: parts.requestId,
104
+ usage: Object.keys(usage).length > 0 ? usage : void 0,
105
+ warnings: warnings.length > 0 ? warnings : void 0
106
+ });
107
+ return Object.keys(result).length > 0 ? result : void 0;
108
+ };
109
+ /**
110
+ * Refuses a request that sets more than one of `names` (a name counts as set
111
+ * unless its value is undefined), for options the provider rejects or ignores
112
+ * when combined. Throws before anything is sent.
113
+ *
114
+ * Throws `InvalidRequest` naming the options that were set.
115
+ */
116
+ const refuseTogether = (provider, options, ...names) => {
117
+ const set = names.filter((name) => options[name] !== void 0);
118
+ if (set.length > 1) throw new FieldworkError("InvalidRequest", `${provider} does not accept ${set.join(" and ")} together; pass one`, { provider });
119
+ };
120
+ /**
121
+ * A `maxAge` in seconds as the whole hours Exa and Tavily count in, rounded
122
+ * up, so 1 second is 1 hour and 0 stays 0 (always fetch fresh). A negative age
123
+ * (read only the cache) becomes -1. Undefined stays undefined.
124
+ */
125
+ const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
126
+ /** Statuses that mean the page is not there, so a read of it has no page to return. */
127
+ const GONE = /* @__PURE__ */ new Set([404, 410]);
128
+ /**
129
+ * A read whose page answered 404 or 410 fails as NotFound, as it does on
130
+ * providers that return no page at all, instead of returning the error page
131
+ * as if it were the content.
132
+ */
133
+ const presentPage = (provider, page) => {
134
+ if (page.statusCode !== void 0 && GONE.has(page.statusCode)) throw new FieldworkError("NotFound", `${provider} could not read ${page.url}: the page returned ${page.statusCode}`, {
135
+ provider,
136
+ status: page.statusCode
137
+ });
138
+ return page;
139
+ };
140
+ /** Splits a batch's pages into those present and those that answered 404 or 410. */
141
+ const presentPages = (pages) => ({
142
+ gone: pages.filter((page) => page.statusCode !== void 0 && GONE.has(page.statusCode)).map((page) => ({
143
+ error: `the page returned ${page.statusCode}`,
144
+ url: page.url
145
+ })),
146
+ pages: pages.filter((page) => page.statusCode === void 0 || !GONE.has(page.statusCode))
147
+ });
148
+ export { compact as a, parseJson as c, record as d, refuseTogether as f, citationsOf as i, presentPage as l, uniqueCitations as m, checkCallSettings as n, hours as o, requireJobId as p, citationOf as r, meta as s, callSettings as t, presentPages as u };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.6.1",
3
+ "version": "0.8.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",
@@ -1,49 +0,0 @@
1
- import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
- // src/schema.ts
3
- const isStandard = (schema) => "~standard" in schema;
4
- /**
5
- * The JSON Schema to send to a provider. A plain JSON Schema passes through as
6
- * given; a Standard Schema is converted to `target`, without its `$schema` key,
7
- * because the provider's docs, not the library, say which dialect it reads.
8
- *
9
- * Throws `InvalidRequest`, with the library's error as `cause`, when the
10
- * library cannot write the schema as `target`.
11
- */
12
- const jsonSchemaOf = (schema, target = "draft-2020-12") => {
13
- if (!isStandard(schema)) return schema;
14
- try {
15
- const converted = schema["~standard"].jsonSchema.input({ target });
16
- return Object.fromEntries(Object.entries(converted).filter(([key]) => key !== "$schema"));
17
- } catch (error) {
18
- throw new FieldworkError("InvalidRequest", `the ${schema["~standard"].vendor} schema cannot be written as ${target} JSON Schema: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
19
- }
20
- };
21
- const MAX_ISSUES = 3;
22
- const pathOf = (issue) => {
23
- const segments = (issue.path ?? []).map((segment) => String(segment instanceof Object ? segment.key : segment));
24
- return segments.length > 0 ? segments.join(".") : "(root)";
25
- };
26
- const describeIssues = (issues) => {
27
- const shown = issues.slice(0, MAX_ISSUES).map((issue) => `${pathOf(issue)}: ${issue.message}`);
28
- const more = issues.length - shown.length;
29
- return `${shown.join("; ")}${more > 0 ? `; and ${more} more` : ""}`;
30
- };
31
- /**
32
- * The provider's structured output as the caller's type. A Standard Schema
33
- * checks it and throws `ProviderError` listing the first three issues with
34
- * their paths, not `retryable` and carrying the context's `jobId`; the value
35
- * returned is the schema's own output, so transforms and defaults apply. A
36
- * plain JSON Schema, or no schema, leaves it unchecked.
37
- */
38
- const checkOutput = async (schema, value, context) => {
39
- if (schema === void 0 || !isStandard(schema)) return value;
40
- const result = await schema["~standard"].validate(value);
41
- if (result.issues !== void 0) throw new FieldworkError("ProviderError", `${context.provider} returned output that does not match the schema: ${describeIssues(result.issues)}`, {
42
- cause: result.issues,
43
- jobId: context.jobId,
44
- provider: context.provider,
45
- retryable: false
46
- });
47
- return result.value;
48
- };
49
- export { jsonSchemaOf as n, checkOutput as t };