@howells/fieldwork-sdk 0.11.0 → 0.12.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.
Files changed (47) hide show
  1. package/README.md +72 -15
  2. package/dist/{adapter-DWYJys20.js → adapter-CBSAfErv.js} +1 -1
  3. package/dist/adapter-J2yatZJ0.d.ts +73 -0
  4. package/dist/best-CO9liYDa.js +1436 -0
  5. package/dist/brave.d.ts +7 -6
  6. package/dist/brave.js +180 -173
  7. package/dist/browserbase.d.ts +4 -3
  8. package/dist/browserbase.js +185 -170
  9. package/dist/{document-DMIUCoDA.js → document-BSCwJgBM.js} +4 -4
  10. package/dist/{download-CP8noBdX.js → download-kuTqNnuZ.js} +1 -1
  11. package/dist/{adapter-B8kAAAgF.d.ts → errors-gMtejKHc.d.ts} +87 -69
  12. package/dist/exa.d.ts +18 -11
  13. package/dist/exa.js +306 -275
  14. package/dist/fieldwork-D7npPoUf.d.ts +35 -0
  15. package/dist/firecrawl.d.ts +4 -3
  16. package/dist/firecrawl.js +450 -417
  17. package/dist/{parse-Q7H4mrnO.js → http-CJcvTPnE.js} +223 -225
  18. package/dist/image.d.ts +253 -0
  19. package/dist/image.js +1 -0
  20. package/dist/index.d.ts +6 -7
  21. package/dist/index.js +66 -82
  22. package/dist/{job-DnavRq_s.js → job-JLEpszjr.js} +9 -9
  23. package/dist/kernel.d.ts +20 -2
  24. package/dist/kernel.js +65 -19
  25. package/dist/llamaparse.d.ts +3 -2
  26. package/dist/llamaparse.js +16 -16
  27. package/dist/parallel.d.ts +8 -8
  28. package/dist/parallel.js +423 -389
  29. package/dist/path-DO2llIdp.js +10 -0
  30. package/dist/perplexity.d.ts +6 -5
  31. package/dist/perplexity.js +21 -21
  32. package/dist/reducto.d.ts +3 -2
  33. package/dist/reducto.js +14 -14
  34. package/dist/{schema-CAPSX7yQ.d.ts → schema-C9xzRkKJ.d.ts} +17 -6
  35. package/dist/{schema--iU4AXSM.js → schema-CJXFAZ-x.js} +12 -3
  36. package/dist/serpapi.d.ts +3 -3
  37. package/dist/serpapi.js +176 -171
  38. package/dist/tavily.d.ts +4 -3
  39. package/dist/tavily.js +247 -234
  40. package/dist/tools.d.ts +76 -15
  41. package/dist/tools.js +351 -33
  42. package/dist/{util-DFUXQX6v.js → util-LvME_uOj.js} +35 -11
  43. package/package.json +6 -1
  44. package/dist/fieldwork-BrfoehvG.d.ts +0 -113
  45. package/dist/path-DL5P8XH2.js +0 -17
  46. package/dist/util-DhYr1OS3.d.ts +0 -1
  47. package/dist/{errors-DkFJysIM.js → errors-gpxg6Tnh.js} +5 -5
package/dist/tools.js CHANGED
@@ -1,9 +1,34 @@
1
- import { t as FieldworkError } from "./errors-DkFJysIM.js";
2
- import { f as refuseTogether } from "./util-DFUXQX6v.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";
1
+ import { t as FieldworkError } from "./errors-gpxg6Tnh.js";
2
+ import { _ as isNumber, a as compact, d as refuseTogether, g as isList, h as isJsonObject, m as isFlag, v as isText, y as jsonValue } from "./util-LvME_uOj.js";
3
+ import { n as bestImages, t as RENDERERS } from "./best-CO9liYDa.js";
4
4
  import { t as CAPABILITIES } from "./types-mq6d6YOK.js";
5
- import * as z from "zod/mini";
5
+ import { t as joinPath } from "./path-DO2llIdp.js";
6
+ import * as z$1 from "zod/mini";
7
+ // src/tools/budget.ts
8
+ const DEFAULT_MAX_CHARACTERS = 2e4;
9
+ /** Checks configured and per-call budgets against the same optional cap. */
10
+ const checkMaxCharacters = (value, limit = Number.MAX_SAFE_INTEGER) => {
11
+ const parsed = z$1.safeParse(z$1.number().check(z$1.int(), z$1.minimum(1), z$1.maximum(limit)), value);
12
+ if (!parsed.success) throw new FieldworkError("InvalidRequest", `maxCharacters must be an integer from 1 to ${limit}`);
13
+ return parsed.data;
14
+ };
6
15
  // src/tool-specs/schema.ts
16
+ /** The schema as a JSON object, to advertise it. Keywords that are absent stay absent. */
17
+ const jsonOf = (schema) => compact({
18
+ additionalProperties: schema.additionalProperties instanceof Object ? jsonOf(schema.additionalProperties) : schema.additionalProperties,
19
+ description: schema.description,
20
+ enum: schema.enum,
21
+ format: schema.format,
22
+ items: schema.items === void 0 ? void 0 : jsonOf(schema.items),
23
+ maximum: schema.maximum,
24
+ minItems: schema.minItems,
25
+ minimum: schema.minimum,
26
+ oneOf: schema.oneOf?.map((item) => jsonOf(item)),
27
+ pattern: schema.pattern,
28
+ properties: schema.properties === void 0 ? void 0 : Object.fromEntries(Object.entries(schema.properties).map(([name, item]) => [name, jsonOf(item)])),
29
+ required: schema.required,
30
+ type: schema.type
31
+ });
7
32
  const described = (schema, description) => description === void 0 ? schema : {
8
33
  ...schema,
9
34
  description
@@ -205,6 +230,50 @@ const stealth = (providers) => ({
205
230
  providers,
206
231
  schema: flag("Use a stealth browser that hides automation and solves CAPTCHAs. Use when a site blocks or challenges the plain browser.")
207
232
  });
233
+ /** Total passage token budget across all results, split where bounds and prerequisites differ. */
234
+ const maxTokens = () => [{
235
+ name: "maxTokens",
236
+ providers: ["brave"],
237
+ schema: whole("Total token budget for all results' passages, 1024 to 32768. Requires content: true.", 1024, 32768)
238
+ }, {
239
+ name: "maxTokens",
240
+ providers: ["perplexity"],
241
+ schema: whole("Total token budget for page content across all results.", 1)
242
+ }];
243
+ /** Per-result passage token cap, split where bounds and prerequisites differ. */
244
+ const maxTokensPerResult = () => [{
245
+ name: "maxTokensPerResult",
246
+ providers: ["brave"],
247
+ schema: whole("Token cap for one result's passages, 512 to 8192. Requires content: true.", 512, 8192)
248
+ }, {
249
+ name: "maxTokensPerResult",
250
+ providers: ["perplexity"],
251
+ schema: whole("Token cap for each result's page content.", 1)
252
+ }];
253
+ /** Per-result excerpt/passage character cap. */
254
+ const maxCharsPerResult = (providers) => ({
255
+ name: "maxCharsPerResult",
256
+ providers,
257
+ schema: whole("Cap on the characters of passages or excerpts returned for each result.", 1)
258
+ });
259
+ /** Total excerpt/passage character cap across all results. */
260
+ const maxCharsTotal = (providers) => ({
261
+ name: "maxCharsTotal",
262
+ providers,
263
+ schema: whole("Cap on the characters of passages or excerpts returned across all results.", 1)
264
+ });
265
+ /** Per-page full text (`markdown`) character cap. */
266
+ const maxContentChars = (providers) => ({
267
+ name: "maxContentChars",
268
+ providers,
269
+ schema: whole("Cap on the characters of full page text returned as markdown for each page.", 1)
270
+ });
271
+ /** Tavily's passage count cap per source page. */
272
+ const chunksPerSource = (maximum, note = "") => ({
273
+ name: "chunksPerSource",
274
+ providers: ["tavily"],
275
+ schema: whole(`Passages to return per page, 1 to ${maximum}. ${note}`.trim(), 1, maximum)
276
+ });
208
277
  const meta = object({
209
278
  requestId: str,
210
279
  usage: object({
@@ -355,6 +424,32 @@ const IMAGE_MATCHES_OUTPUT = object({
355
424
  meta,
356
425
  results: list(imageMatch)
357
426
  }, ["results"]);
427
+ /** The result of `find_images`, a `BestImages`. */
428
+ const BEST_IMAGES_OUTPUT = object({
429
+ images: list(object({
430
+ height: number(),
431
+ measured: flag("True when width and height were measured from loaded pixels; false when the page declared them or the CDN's URL names them."),
432
+ score: number("How good the image is; higher is better."),
433
+ sources: texts("Where the page names the image, such as og:image, img or srcset, and lcp when it was the rendered page's largest contentful paint."),
434
+ url: str,
435
+ variants: texts("The image's other URLs, such as the page's own and smaller sizes."),
436
+ verified: flag("False when a CDN pattern built url and nothing loaded it; the page's own URL is then first in variants."),
437
+ width: number()
438
+ }, [
439
+ "url",
440
+ "verified",
441
+ "variants",
442
+ "measured",
443
+ "sources",
444
+ "score"
445
+ ]), "The page's images, best first."),
446
+ meta,
447
+ renderError: object({
448
+ code: str,
449
+ message: str
450
+ }, ["code", "message"], "Why the render failed, when render was auto and the images are the read's instead."),
451
+ rendered: flag("Whether the page was rendered in a browser.")
452
+ }, ["images", "rendered"]);
358
453
  /** The result of `read_page`, a `Page`. */
359
454
  const PAGE_OUTPUT = page;
360
455
  /** The result of `read_pages`, a `PageBatch`: the pages read, and `failed` for URLs that could not be. */
@@ -744,19 +839,23 @@ const BROWSER_SPECS = [
744
839
  capability: "act",
745
840
  description: "Run a script in a new remote browser session and return what it printed and returned; the session closes afterwards. The script can visit sites, click, type and submit forms, and its effects on those sites are real. Use only when a page needs interaction that reading cannot do. Do not use to read or search pages.",
746
841
  destructive: true,
747
- fields: [{
748
- name: "code",
749
- required: true,
750
- schema: text("The script to run.")
751
- }, {
752
- name: "language",
753
- providers: ["firecrawl"],
754
- schema: choice("The script's language. Defaults to node.", [
755
- "node",
756
- "python",
757
- "bash"
758
- ])
759
- }],
842
+ fields: [
843
+ {
844
+ name: "code",
845
+ required: true,
846
+ schema: text("The script to run.")
847
+ },
848
+ {
849
+ name: "language",
850
+ providers: ["firecrawl"],
851
+ schema: choice("The script's language. Defaults to node.", [
852
+ "node",
853
+ "python",
854
+ "bash"
855
+ ])
856
+ },
857
+ stealth(["kernel"])
858
+ ],
760
859
  idempotent: false,
761
860
  name: "run_browser_script",
762
861
  output: ACT_OUTPUT,
@@ -1035,6 +1134,43 @@ const MONITOR_SPECS = [
1035
1134
  title: "Check usage"
1036
1135
  }
1037
1136
  ];
1137
+ // src/tools/images.ts
1138
+ /** Providers whose `read` returns a page's HTML, with `format: "raw"`. */
1139
+ const HTML_READERS = ["browserbase", "kernel"];
1140
+ const Arguments = z$1.tuple([z$1.string(), z$1.object({
1141
+ limit: z$1.optional(z$1.number()),
1142
+ render: z$1.optional(z$1.enum([
1143
+ "auto",
1144
+ "never",
1145
+ "always"
1146
+ ])),
1147
+ retries: z$1.optional(z$1.number()),
1148
+ signal: z$1.optional(z$1.instanceof(AbortSignal)),
1149
+ timeout: z$1.optional(z$1.number())
1150
+ })]);
1151
+ const isOneOf = (names, name) => names.some((candidate) => candidate === name);
1152
+ const isImageRouter = (web) => isOneOf(HTML_READERS, web.providerFor("read")) && isOneOf(RENDERERS, web.providerFor("act"));
1153
+ /**
1154
+ * `bestImages` as a tool operation, or undefined unless the instance reads
1155
+ * HTML with a provider in `HTML_READERS` and acts with one in `RENDERERS`.
1156
+ * The tool's input is already checked. The call's `signal` and `retries` go
1157
+ * through, and its `timeout` stops the read and the render as one deadline.
1158
+ */
1159
+ const findImages = (web) => {
1160
+ if (!isImageRouter(web)) return;
1161
+ const router = web;
1162
+ return async (...args) => {
1163
+ const [url, options] = z$1.parse(Arguments, args);
1164
+ const { raw: _raw, renderError, ...found } = await bestImages(router, url, options);
1165
+ return z$1.parse(jsonValue, {
1166
+ ...found,
1167
+ ...renderError && { renderError: {
1168
+ code: renderError.code,
1169
+ message: renderError.message
1170
+ } }
1171
+ });
1172
+ };
1173
+ };
1038
1174
  // src/tool-specs/read.ts
1039
1175
  const query = {
1040
1176
  name: "query",
@@ -1059,6 +1195,10 @@ const READ_SPECS = [
1059
1195
  fields: [
1060
1196
  urlField(PAGE_URL),
1061
1197
  query,
1198
+ maxCharsPerResult(["exa", "parallel"]),
1199
+ maxCharsTotal(["parallel"]),
1200
+ maxContentChars(["exa", "parallel"]),
1201
+ chunksPerSource(5, "Requires query."),
1062
1202
  maxAge(["exa", "firecrawl"]),
1063
1203
  maxAgeAtLeast600(),
1064
1204
  country(["browserbase"], "Fetch the page through a proxy in"),
@@ -1082,6 +1222,10 @@ const READ_SPECS = [
1082
1222
  schema: list(url("A page's full URL, including https://."), "The pages' full URLs, including https://.", { minItems: 1 })
1083
1223
  },
1084
1224
  query,
1225
+ maxCharsPerResult(["exa", "parallel"]),
1226
+ maxCharsTotal(["parallel"]),
1227
+ maxContentChars(["exa", "parallel"]),
1228
+ chunksPerSource(5, "Requires query."),
1085
1229
  maxAge(["exa", "firecrawl"]),
1086
1230
  maxAgeAtLeast600(),
1087
1231
  resume(["firecrawl"])
@@ -1127,6 +1271,33 @@ const READ_SPECS = [
1127
1271
  readOnly: true,
1128
1272
  title: "Read a product page"
1129
1273
  },
1274
+ {
1275
+ capability: "read",
1276
+ description: "Find a page's images, best first: the largest, most prominent content images, each at its largest known original URL, with its size when known. Leaves out SVGs, images in the site's header, nav or footer, and images known to be under 100 pixels on a side, such as icons and tracking pixels. Use when you need a page's main image or its photos. Do not use to find pictures of a subject across the web (use search_images), or for where an image appears (use search_by_image).",
1277
+ destructive: false,
1278
+ fields: [
1279
+ urlField(PAGE_URL),
1280
+ {
1281
+ name: "limit",
1282
+ schema: whole("The most images to return. Leave out for every image found.", 1)
1283
+ },
1284
+ {
1285
+ name: "render",
1286
+ schema: choice("auto (the default) reads the page's HTML and renders it in a browser only when that leaves no image or no clear best one; never only reads the HTML; always renders, which finds images JavaScript loads and measures real sizes, and is slower.", [
1287
+ "auto",
1288
+ "never",
1289
+ "always"
1290
+ ])
1291
+ }
1292
+ ],
1293
+ idempotent: true,
1294
+ name: "find_images",
1295
+ operation: findImages,
1296
+ output: BEST_IMAGES_OUTPUT,
1297
+ positional: ["url"],
1298
+ readOnly: true,
1299
+ title: "Find a page's images"
1300
+ },
1130
1301
  {
1131
1302
  capability: "map",
1132
1303
  description: "List the URLs of a website without reading the pages. Use to find which pages a site has before reading some of them. Do not use when you need page text (use read_page or crawl_site).",
@@ -1244,6 +1415,11 @@ const SPECS = [
1244
1415
  ],
1245
1416
  schema: flag("Include each result's page text. Slower and longer; leave out to get snippets only.")
1246
1417
  },
1418
+ ...maxTokens(),
1419
+ ...maxTokensPerResult(),
1420
+ maxCharsPerResult(["exa", "parallel"]),
1421
+ maxCharsTotal(["parallel"]),
1422
+ chunksPerSource(3),
1247
1423
  maxAge(["exa", "tavily"]),
1248
1424
  maxAgeAtLeast600()
1249
1425
  ],
@@ -1325,14 +1501,6 @@ const SPECS = [
1325
1501
  ...BROWSER_SPECS,
1326
1502
  ...MONITOR_SPECS
1327
1503
  ];
1328
- // src/tools/budget.ts
1329
- const DEFAULT_MAX_CHARACTERS = 2e4;
1330
- /** Checks configured and per-call budgets against the same optional cap. */
1331
- const checkMaxCharacters = (value, limit = Number.MAX_SAFE_INTEGER) => {
1332
- const parsed = z.safeParse(z.number().check(z.int(), z.minimum(1), z.maximum(limit)), value);
1333
- if (!parsed.success) throw new FieldworkError("InvalidRequest", `maxCharacters must be an integer from 1 to ${limit}`);
1334
- return parsed.data;
1335
- };
1336
1504
  // src/tools/dispatch.ts
1337
1505
  const isOperation = (value) => typeof value === "function";
1338
1506
  const isGroup = (value) => isJsonObject(value);
@@ -1400,10 +1568,12 @@ const VERBATIM = /* @__PURE__ */ new Set([
1400
1568
  const SPEND_FIRST = [
1401
1569
  "answer",
1402
1570
  "output",
1571
+ "excerpts",
1572
+ "snippet",
1573
+ "summary",
1403
1574
  "markdown",
1404
1575
  "content",
1405
- "text",
1406
- "summary"
1576
+ "text"
1407
1577
  ];
1408
1578
  const SPEND_LAST = ["html", "rawHtml"];
1409
1579
  const rank = (key) => {
@@ -1521,7 +1691,7 @@ const problem = (schema, value, name) => {
1521
1691
  }
1522
1692
  return typeProblem(schema, value, name, problem);
1523
1693
  };
1524
- // src/tools.ts
1694
+ // src/tools/build.ts
1525
1695
  /**
1526
1696
  * Capabilities that start remote browsers or create lasting or billed
1527
1697
  * resources. `toolsFor` leaves them out unless they are named in `allow` or
@@ -1577,7 +1747,7 @@ const resultObject = (spec, values, result) => {
1577
1747
  const inputSchema = (fields, provider, budget, limit) => {
1578
1748
  const schema = {
1579
1749
  additionalProperties: false,
1580
- 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) }]]),
1750
+ properties: Object.fromEntries([...fields.map((field) => [field.name, jsonOf(field.schema)]), ["maxCharacters", jsonOf(whole(`Shared long-text budget for this call; defaults to ${budget}. Never sent to the provider.`, 1, limit))]]),
1581
1751
  required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1582
1752
  type: "object"
1583
1753
  };
@@ -1613,7 +1783,7 @@ const toolFor = (spec, provider, operation, budget, limit) => {
1613
1783
  inputSchema: inputSchema(fields, provider, budget, limit),
1614
1784
  method: spec.method,
1615
1785
  name: spec.name,
1616
- outputSchema: {
1786
+ outputSchema: jsonOf({
1617
1787
  ...spec.output,
1618
1788
  properties: {
1619
1789
  ...spec.output.properties,
@@ -1627,7 +1797,7 @@ const toolFor = (spec, provider, operation, budget, limit) => {
1627
1797
  "length"
1628
1798
  ]), "One entry for each cut text field; absent when nothing was cut.")
1629
1799
  }
1630
- },
1800
+ }),
1631
1801
  provider
1632
1802
  };
1633
1803
  };
@@ -1643,7 +1813,7 @@ const toolsFor = (web, options = {}) => {
1643
1813
  const dispatcher = web;
1644
1814
  return SPECS.flatMap((spec) => {
1645
1815
  const provider = web.providerFor(spec.capability);
1646
- const operation = operationFor(dispatcher, spec);
1816
+ const operation = spec.operation === void 0 ? operationFor(dispatcher, spec) : spec.operation(web);
1647
1817
  return wanted.has(spec.capability) && provider !== void 0 && operation !== void 0 ? [toolFor(spec, provider, operation, budget, limit)] : [];
1648
1818
  });
1649
1819
  };
@@ -1662,4 +1832,152 @@ const toolError = (cause) => {
1662
1832
  retryable: false
1663
1833
  };
1664
1834
  };
1665
- export { DEFAULT_MAX_CHARACTERS, EXCLUDED_BY_DEFAULT, checkMaxCharacters, toolError, toolsFor };
1835
+ // src/tools/catalog.ts
1836
+ /** Retrieval-style notes for `search_web` when more than one search provider is offered. */
1837
+ const SEARCH_PROVIDER_ROLES = /* @__PURE__ */ new Map([
1838
+ ["brave", "brave for lexical/keyword queries, search operators and token-budgeted passages (content: true)"],
1839
+ ["browserbase", "browserbase for managed web search"],
1840
+ ["exa", "exa for neural/semantic queries and capped highlights"],
1841
+ ["firecrawl", "firecrawl for web search with full-page Markdown"],
1842
+ ["parallel", "parallel for objective-driven semantic search and char-budgeted excerpts"],
1843
+ ["perplexity", "perplexity for hybrid lexical+semantic search with token-budgeted snippets"],
1844
+ ["serpapi", "serpapi for Google/Bing SERPs and exact keyword queries"],
1845
+ ["tavily", "tavily for hybrid search with chunked passages"]
1846
+ ]);
1847
+ /**
1848
+ * Retrieval-style guidance naming only the search providers present, or an
1849
+ * empty string when fewer than two providers are offered.
1850
+ */
1851
+ const searchProviderGuidance = (providers) => {
1852
+ if (providers.length < 2) return "";
1853
+ const notes = providers.flatMap((provider) => {
1854
+ const role = SEARCH_PROVIDER_ROLES.get(provider);
1855
+ return role === void 0 ? [] : [role];
1856
+ });
1857
+ return notes.length === 0 ? "" : ` Choose provider by query style: ${notes.join("; ")}.`;
1858
+ };
1859
+ const InputSchema = z$1.object({
1860
+ oneOf: z$1.optional(z$1.array(z$1.json())),
1861
+ properties: z$1.record(z$1.string(), z$1.json()),
1862
+ required: z$1.optional(z$1.array(z$1.string()))
1863
+ });
1864
+ /**
1865
+ * One provider's schema branch for a multi-provider tool. `explicit` fixes and
1866
+ * requires `provider`; `extraProperties` adds transport-level fields such as
1867
+ * the gateway's `timeout`.
1868
+ */
1869
+ const providerBranchSchema = (tool, explicit, extraProperties = {}) => {
1870
+ const schema = z$1.parse(InputSchema, tool.inputSchema);
1871
+ const properties = {
1872
+ ...schema.properties,
1873
+ ...extraProperties
1874
+ };
1875
+ if (explicit) properties.provider = {
1876
+ const: tool.provider,
1877
+ type: "string"
1878
+ };
1879
+ const input = {
1880
+ additionalProperties: false,
1881
+ properties,
1882
+ required: [...schema.required ?? [], ...explicit ? ["provider"] : []],
1883
+ type: "object"
1884
+ };
1885
+ if (schema.oneOf !== void 0) input.oneOf = schema.oneOf;
1886
+ return input;
1887
+ };
1888
+ const resolveDefaultTool = (variants, first, configured) => {
1889
+ if (configured === void 0) return variants.size === 1 ? first : void 0;
1890
+ return variants.get(configured);
1891
+ };
1892
+ const multiProviderSchema = (variants, defaultTool, providers) => ({
1893
+ oneOf: [...defaultTool === void 0 ? [] : [providerBranchSchema(defaultTool, false)], ...variants.map((tool) => providerBranchSchema(tool, true))],
1894
+ properties: { provider: {
1895
+ enum: [...providers],
1896
+ type: "string"
1897
+ } },
1898
+ type: "object"
1899
+ });
1900
+ /** Describes a tool across its providers, including search retrieval-style guidance when several serve `search_web`. */
1901
+ const describeMultiProviderTool = (first, providers, defaultProvider) => {
1902
+ const guidance = first.name === "search_web" ? searchProviderGuidance(providers) : "";
1903
+ const routing = defaultProvider === void 0 ? "Name a provider explicitly." : `Defaults to ${defaultProvider}.`;
1904
+ return `${first.description}${guidance} ${routing} Set provider to choose another supported provider; Fieldwork never switches providers after an error.`;
1905
+ };
1906
+ /**
1907
+ * Collects every client's tools grouped by tool name and provider. Throws when
1908
+ * two clients serve the same tool through the same provider.
1909
+ */
1910
+ const collectToolVariants = (clients, options = {}) => {
1911
+ const entries = /* @__PURE__ */ new Map();
1912
+ for (const client of clients) for (const tool of toolsFor(client, options)) {
1913
+ const variants = entries.get(tool.name) ?? /* @__PURE__ */ new Map();
1914
+ if (variants.has(tool.provider)) throw new Error(`Duplicate provider ${tool.provider} for ${tool.name}`);
1915
+ variants.set(tool.provider, tool);
1916
+ entries.set(tool.name, variants);
1917
+ }
1918
+ return entries;
1919
+ };
1920
+ /**
1921
+ * Builds one tool per capability name across several Fieldwork clients. Each
1922
+ * provider keeps its own input schema branch and executor; no options are
1923
+ * merged and no call falls back to another provider.
1924
+ *
1925
+ * When a tool has one provider and no conflicting default was configured, it
1926
+ * uses that provider's plain schema without a `provider` field. When several
1927
+ * providers serve a tool (such as `search_web` over Brave and Exa), the tool
1928
+ * exposes a `provider` enum with per-provider `oneOf` branches and retrieval
1929
+ * guidance in its description.
1930
+ */
1931
+ const toolCatalog = (clients, options = {}) => {
1932
+ const { defaults, toolDefaults, ...toolOptions } = options;
1933
+ const entries = collectToolVariants(clients, toolOptions);
1934
+ const defaultByTool = /* @__PURE__ */ new Map();
1935
+ const providersByTool = /* @__PURE__ */ new Map();
1936
+ const select = (name, provider) => {
1937
+ const variants = entries.get(name);
1938
+ if (variants === void 0) throw new FieldworkError("NotFound", `${name} is not a tool in this catalog`);
1939
+ const selected = provider ?? defaultByTool.get(name);
1940
+ const tool = selected === void 0 ? void 0 : variants.get(selected);
1941
+ if (tool === void 0) {
1942
+ const available = providersByTool.get(name)?.join(", ") ?? "none";
1943
+ throw new FieldworkError("Unsupported", `${name} needs a supported provider; available: ${available}`, { provider: selected });
1944
+ }
1945
+ return tool;
1946
+ };
1947
+ const tools = [];
1948
+ for (const variants of entries.values()) {
1949
+ const list = [...variants.values()];
1950
+ const [first] = list;
1951
+ if (first === void 0) continue;
1952
+ const providers = list.map((tool) => tool.provider);
1953
+ const configured = toolDefaults?.[first.name] ?? defaults?.[first.capability];
1954
+ const defaultTool = resolveDefaultTool(variants, first, configured);
1955
+ const defaultProvider = defaultTool?.provider;
1956
+ defaultByTool.set(first.name, defaultProvider);
1957
+ providersByTool.set(first.name, providers);
1958
+ const single = list.length === 1 && defaultTool !== void 0;
1959
+ tools.push({
1960
+ annotations: first.annotations,
1961
+ capability: first.capability,
1962
+ ...defaultProvider !== void 0 && { defaultProvider },
1963
+ description: single ? first.description : describeMultiProviderTool(first, providers, defaultProvider),
1964
+ execute: async (input, call = {}) => {
1965
+ if (!isJsonObject(input)) throw new FieldworkError("InvalidRequest", `${first.name}: input must be an object`);
1966
+ if (single) return await defaultTool.execute(input, call);
1967
+ const { provider, ...args } = input;
1968
+ if (provider !== void 0 && !isText(provider)) throw new FieldworkError("InvalidRequest", `${first.name}: provider must be a string`);
1969
+ return await select(first.name, provider).execute(args, call);
1970
+ },
1971
+ inputSchema: single ? first.inputSchema : multiProviderSchema(list, defaultTool, providers),
1972
+ ...first.method !== void 0 && { method: first.method },
1973
+ name: first.name,
1974
+ outputSchema: first.outputSchema,
1975
+ providers
1976
+ });
1977
+ }
1978
+ return {
1979
+ select,
1980
+ tools
1981
+ };
1982
+ };
1983
+ export { DEFAULT_MAX_CHARACTERS, EXCLUDED_BY_DEFAULT, checkMaxCharacters, collectToolVariants, describeMultiProviderTool, providerBranchSchema, searchProviderGuidance, toolCatalog, toolError, toolsFor };
@@ -1,10 +1,31 @@
1
- import { t as FieldworkError } from "./errors-DkFJysIM.js";
1
+ import { t as FieldworkError } from "./errors-gpxg6Tnh.js";
2
+ import * as z$1 from "zod/mini";
3
+ // src/json.ts
4
+ const isText = (value) => typeof value === "string";
5
+ /** A finite number: JSON has no NaN or Infinity. */
6
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
7
+ const isFlag = (value) => typeof value === "boolean";
8
+ const isList = (value) => Array.isArray(value);
9
+ /** Checks a value is JSON all the way down, for a body or field that arrives untyped. */
10
+ const jsonValue = z$1.json();
11
+ /** Parses JSON text. Throws `SyntaxError` when the text is not JSON. */
12
+ const parseJsonText = (text) => {
13
+ const parsed = JSON.parse(text);
14
+ return z$1.parse(jsonValue, parsed);
15
+ };
16
+ /** Narrows anything, such as a value a transport hands over, to a JSON object. */
17
+ const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
18
  // 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));
19
+ /**
20
+ * Drops the keys whose value is undefined, so a request body or result carries
21
+ * only what was set. Shallow: nested objects are not touched. Every key left
22
+ * keeps the type T gives it, and a dropped key reads as undefined, as before.
23
+ */
24
+ const compact = (value) => {
25
+ const result = { ...value };
26
+ for (const [key, item] of Object.entries(result)) if (item === void 0) Reflect.deleteProperty(result, key);
27
+ return result;
28
+ };
8
29
  /** The longest `timeout` a timer holds, in milliseconds: about 24.8 days. */
9
30
  const MAX_TIMEOUT = 2147483647;
10
31
  /**
@@ -30,7 +51,7 @@ const checkCallSettings = (settings) => {
30
51
  * timeout to the provider and needs a moment more to hear its report.
31
52
  */
32
53
  const callSettings = (options, grace = 0) => {
33
- const { retries, signal, timeout, ...rest } = options ?? {};
54
+ const { retries, signal, timeout, ...rest } = options;
34
55
  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
56
  checkCallSettings({
36
57
  retries,
@@ -53,9 +74,9 @@ const callSettings = (options, grace = 0) => {
53
74
  * not valid JSON.
54
75
  */
55
76
  const parseJson = (provider, value) => {
56
- if (typeof value !== "string") return value;
77
+ if (!isText(value)) return value;
57
78
  try {
58
- return JSON.parse(value);
79
+ return parseJsonText(value);
59
80
  } catch (error) {
60
81
  throw new FieldworkError("ProviderError", `${provider} returned output that is not valid JSON`, {
61
82
  cause: error,
@@ -122,7 +143,10 @@ const refuseTogether = (provider, options, ...names) => {
122
143
  * up, so 1 second is 1 hour and 0 stays 0 (always fetch fresh). A negative age
123
144
  * (read only the cache) becomes -1. Undefined stays undefined.
124
145
  */
125
- const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
146
+ const hours = (seconds) => {
147
+ if (seconds === void 0) return;
148
+ return seconds < 0 ? -1 : Math.ceil(seconds / 3600);
149
+ };
126
150
  /** Statuses that mean the page is not there, so a read of it has no page to return. */
127
151
  const GONE = /* @__PURE__ */ new Set([404, 410]);
128
152
  /**
@@ -145,4 +169,4 @@ const presentPages = (pages) => ({
145
169
  })),
146
170
  pages: pages.filter((page) => page.statusCode === void 0 || !GONE.has(page.statusCode))
147
171
  });
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 };
172
+ export { isNumber as _, compact as a, parseJsonText as b, parseJson as c, refuseTogether as d, requireJobId as f, isList as g, isJsonObject as h, citationsOf as i, presentPage as l, isFlag as m, checkCallSettings as n, hours as o, uniqueCitations as p, citationOf as r, meta as s, callSettings as t, presentPages as u, isText as v, jsonValue as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "One API for web search, reverse image 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",
@@ -88,6 +88,10 @@
88
88
  "types": "./dist/reducto.d.ts",
89
89
  "import": "./dist/reducto.js"
90
90
  },
91
+ "./image": {
92
+ "types": "./dist/image.d.ts",
93
+ "import": "./dist/image.js"
94
+ },
91
95
  "./tools": {
92
96
  "types": "./dist/tools.d.ts",
93
97
  "import": "./dist/tools.js"
@@ -97,6 +101,7 @@
97
101
  "access": "public"
98
102
  },
99
103
  "dependencies": {
104
+ "@mixmark-io/domino": "2.2.0",
100
105
  "turndown": "7.2.5",
101
106
  "zod": "^4.6.7"
102
107
  },