@howells/fieldwork-sdk 0.11.0 → 0.13.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 +73 -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-DiKYwLdC.js +1436 -0
  5. package/dist/brave.d.ts +7 -6
  6. package/dist/brave.js +175 -168
  7. package/dist/browserbase.d.ts +4 -3
  8. package/dist/browserbase.js +182 -167
  9. package/dist/{document-DMIUCoDA.js → document-x9fWsQ1W.js} +2 -2
  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 +301 -267
  14. package/dist/fieldwork-D7npPoUf.d.ts +35 -0
  15. package/dist/firecrawl.d.ts +4 -3
  16. package/dist/firecrawl.js +432 -399
  17. package/dist/{parse-Q7H4mrnO.js → http-Bg0h3D-t.js} +222 -224
  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-BsrOrrO1.js} +7 -7
  23. package/dist/kernel.d.ts +20 -2
  24. package/dist/kernel.js +58 -12
  25. package/dist/llamaparse.d.ts +3 -2
  26. package/dist/llamaparse.js +8 -8
  27. package/dist/parallel.d.ts +10 -10
  28. package/dist/parallel.js +432 -391
  29. package/dist/path-tDCyAKK9.js +10 -0
  30. package/dist/perplexity.d.ts +6 -5
  31. package/dist/perplexity.js +16 -16
  32. package/dist/reducto.d.ts +3 -2
  33. package/dist/reducto.js +8 -8
  34. package/dist/{schema--iU4AXSM.js → schema-Bfd2E8u2.js} +12 -3
  35. package/dist/{schema-CAPSX7yQ.d.ts → schema-C9xzRkKJ.d.ts} +17 -6
  36. package/dist/serpapi.d.ts +3 -3
  37. package/dist/serpapi.js +170 -165
  38. package/dist/tavily.d.ts +4 -3
  39. package/dist/tavily.js +242 -229
  40. package/dist/tools.d.ts +79 -15
  41. package/dist/tools.js +431 -77
  42. package/dist/{util-DFUXQX6v.js → util-BOqd71Om.js} +44 -12
  43. package/package.json +11 -6
  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";
4
- import { t as CAPABILITIES } from "./types-mq6d6YOK.js";
5
1
  import * as z from "zod/mini";
2
+ import { t as FieldworkError } from "./errors-gpxg6Tnh.js";
3
+ import { _ as isList, a as compact, b as jsonValue, f as refuseTogether, g as isJsonObject, h as isFlag, v as isNumber, y as isText } from "./util-BOqd71Om.js";
4
+ import { n as bestImages, t as RENDERERS } from "./best-DiKYwLdC.js";
5
+ import { t as CAPABILITIES } from "./types-mq6d6YOK.js";
6
+ import { t as joinPath } from "./path-tDCyAKK9.js";
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.safeParse(z.number().check(z.int(), z.minimum(1), z.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.tuple([z.string(), z.object({
1141
+ limit: z.optional(z.number()),
1142
+ render: z.optional(z.enum([
1143
+ "auto",
1144
+ "never",
1145
+ "always"
1146
+ ])),
1147
+ retries: z.optional(z.number()),
1148
+ signal: z.optional(z.instanceof(AbortSignal)),
1149
+ timeout: z.optional(z.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.parse(Arguments, args);
1164
+ const { raw: _raw, renderError, ...found } = await bestImages(router, url, options);
1165
+ return z.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);
@@ -1393,65 +1561,101 @@ const VERBATIM = /* @__PURE__ */ new Set([
1393
1561
  "values"
1394
1562
  ]);
1395
1563
  /**
1396
- * The order an object's fields spend the shared budget in: the readable
1397
- * answer or page text first, other renderings of the same page last, and
1398
- * everything else between, as it appears. The result keeps its own key order.
1564
+ * Priority tier for spending the shared budget across the whole result tree.
1565
+ * Answers and focused passages (excerpts, snippets, summaries) are budgeted
1566
+ * across every result before full page bodies (markdown, content, text) and
1567
+ * alternate renderings (html, rawHtml).
1399
1568
  */
1400
- const SPEND_FIRST = [
1401
- "answer",
1402
- "output",
1403
- "markdown",
1404
- "content",
1405
- "text",
1406
- "summary"
1569
+ const TIERS = [
1570
+ /* @__PURE__ */ new Set(["answer", "output"]),
1571
+ /* @__PURE__ */ new Set([
1572
+ "excerpts",
1573
+ "snippet",
1574
+ "summary"
1575
+ ]),
1576
+ /* @__PURE__ */ new Set([
1577
+ "markdown",
1578
+ "content",
1579
+ "text"
1580
+ ])
1407
1581
  ];
1408
- const SPEND_LAST = ["html", "rawHtml"];
1409
- const rank = (key) => {
1410
- if (SPEND_FIRST.includes(key)) return SPEND_FIRST.indexOf(key);
1411
- return SPEND_LAST.includes(key) ? SPEND_FIRST.length + 1 + SPEND_LAST.indexOf(key) : SPEND_FIRST.length;
1582
+ const LAST_TIER_KEYS = /* @__PURE__ */ new Set(["html", "rawHtml"]);
1583
+ const OTHER_TIER = TIERS.length;
1584
+ const LAST_TIER = TIERS.length + 1;
1585
+ const tierOf = (key) => {
1586
+ if (key === void 0) return OTHER_TIER;
1587
+ const index = TIERS.findIndex((keys) => keys.has(key));
1588
+ if (index !== -1) return index;
1589
+ return LAST_TIER_KEYS.has(key) ? LAST_TIER : OTHER_TIER;
1412
1590
  };
1413
- /** 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. */
1414
- const cut = (value, budget, path) => {
1415
- if (value.length <= SHORT_TEXT) return value;
1416
- const kept = Math.min(value.length, budget.remaining);
1417
- budget.remaining -= kept;
1418
- if (kept === value.length) return value;
1419
- budget.truncated.push({
1420
- length: value.length,
1421
- path: joinPath(path),
1422
- shown: kept
1423
- });
1424
- return `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
1591
+ /** Pass 1: collects every long string slot in tree order, skipping non-verbatim `raw` keys. */
1592
+ const collect = (value, verbatim, key, slots) => {
1593
+ if (isText(value)) {
1594
+ if (value.length > SHORT_TEXT) slots.push({
1595
+ kept: value.length,
1596
+ length: value.length,
1597
+ tier: tierOf(key)
1598
+ });
1599
+ return;
1600
+ }
1601
+ if (isList(value)) {
1602
+ for (const item of value) collect(item, verbatim, key, slots);
1603
+ return;
1604
+ }
1605
+ if (!isJsonObject(value)) return;
1606
+ for (const [entryKey, item] of Object.entries(value)) {
1607
+ if (!verbatim && entryKey === "raw") continue;
1608
+ collect(item, verbatim || VERBATIM.has(entryKey), entryKey, slots);
1609
+ }
1425
1610
  };
1426
- /**
1427
- * Applies `cut` and the `raw` rule through a value. Fields are visited in
1428
- * `rank` order so the answer or page text gets the budget first, but each
1429
- * object keeps its own key order. `verbatim` is set inside `VERBATIM` keys and
1430
- * stays set below them.
1431
- */
1432
- const shape = (value, verbatim, budget, path) => {
1433
- if (isText(value)) return cut(value, budget, path);
1434
- if (isList(value)) return value.map((item, index) => shape(item, verbatim, budget, [...path, index]) ?? null);
1611
+ /** Allocates `budget` across `slots` in priority-tier order, preserving tree order within each tier. */
1612
+ const allocate = (slots, budget) => {
1613
+ let remaining = budget;
1614
+ for (const slot of slots.toSorted((a, b) => a.tier - b.tier)) {
1615
+ const kept = Math.min(slot.length, remaining);
1616
+ slot.kept = kept;
1617
+ remaining -= kept;
1618
+ }
1619
+ };
1620
+ /** Pass 2: rebuilds the value without `raw`, applying each slot's allocated length. */
1621
+ const render = (value, verbatim, state, path) => {
1622
+ if (isText(value)) {
1623
+ if (value.length <= SHORT_TEXT) return value;
1624
+ const slot = state.slots[state.index];
1625
+ state.index += 1;
1626
+ const kept = slot?.kept ?? value.length;
1627
+ if (kept === value.length) return value;
1628
+ state.truncated.push({
1629
+ length: value.length,
1630
+ path: joinPath(path),
1631
+ shown: kept
1632
+ });
1633
+ return `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
1634
+ }
1635
+ if (isList(value)) return value.map((item, index) => render(item, verbatim, state, [...path, index]) ?? null);
1435
1636
  if (!isJsonObject(value)) return value;
1436
1637
  const entries = Object.entries(value).filter(([key]) => verbatim || key !== "raw");
1437
- const shaped = /* @__PURE__ */ new Map();
1438
- 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]));
1439
- return Object.fromEntries(entries.map(([key]) => [key, shaped.get(key)]));
1638
+ return Object.fromEntries(entries.map(([key, item]) => [key, render(item, verbatim || VERBATIM.has(key), state, [...path, key])]));
1440
1639
  };
1441
1640
  /**
1442
1641
  * A result as a model should see it: the provider's `raw` response dropped at
1443
1642
  * every depth except inside extracted values, and long text cut to one budget
1444
- * shared across the result. Within each object the answer or page text is
1445
- * served first and alternate renderings such as HTML last.
1643
+ * shared across the result. Answers and focused passages (excerpts, snippets,
1644
+ * summaries) spend the budget across every item before full page bodies and
1645
+ * alternate renderings such as HTML.
1446
1646
  */
1447
1647
  const forModel = (result, budget) => {
1448
- const truncated = [];
1449
- const shaped = shape(result, false, {
1450
- remaining: budget,
1451
- truncated
1452
- }, []);
1648
+ const slots = [];
1649
+ collect(result, false, void 0, slots);
1650
+ allocate(slots, budget);
1651
+ const state = {
1652
+ index: 0,
1653
+ slots,
1654
+ truncated: []
1655
+ };
1656
+ const shaped = render(result, false, state, []);
1453
1657
  const output = isJsonObject(shaped) ? shaped : {};
1454
- if (truncated.length > 0) output.truncated = truncated;
1658
+ if (state.truncated.length > 0) output.truncated = state.truncated;
1455
1659
  return output;
1456
1660
  };
1457
1661
  // src/tools/validate.ts
@@ -1521,7 +1725,7 @@ const problem = (schema, value, name) => {
1521
1725
  }
1522
1726
  return typeProblem(schema, value, name, problem);
1523
1727
  };
1524
- // src/tools.ts
1728
+ // src/tools/build.ts
1525
1729
  /**
1526
1730
  * Capabilities that start remote browsers or create lasting or billed
1527
1731
  * resources. `toolsFor` leaves them out unless they are named in `allow` or
@@ -1577,7 +1781,7 @@ const resultObject = (spec, values, result) => {
1577
1781
  const inputSchema = (fields, provider, budget, limit) => {
1578
1782
  const schema = {
1579
1783
  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) }]]),
1784
+ 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
1785
  required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1582
1786
  type: "object"
1583
1787
  };
@@ -1613,7 +1817,7 @@ const toolFor = (spec, provider, operation, budget, limit) => {
1613
1817
  inputSchema: inputSchema(fields, provider, budget, limit),
1614
1818
  method: spec.method,
1615
1819
  name: spec.name,
1616
- outputSchema: {
1820
+ outputSchema: jsonOf({
1617
1821
  ...spec.output,
1618
1822
  properties: {
1619
1823
  ...spec.output.properties,
@@ -1627,7 +1831,7 @@ const toolFor = (spec, provider, operation, budget, limit) => {
1627
1831
  "length"
1628
1832
  ]), "One entry for each cut text field; absent when nothing was cut.")
1629
1833
  }
1630
- },
1834
+ }),
1631
1835
  provider
1632
1836
  };
1633
1837
  };
@@ -1643,7 +1847,7 @@ const toolsFor = (web, options = {}) => {
1643
1847
  const dispatcher = web;
1644
1848
  return SPECS.flatMap((spec) => {
1645
1849
  const provider = web.providerFor(spec.capability);
1646
- const operation = operationFor(dispatcher, spec);
1850
+ const operation = spec.operation === void 0 ? operationFor(dispatcher, spec) : spec.operation(web);
1647
1851
  return wanted.has(spec.capability) && provider !== void 0 && operation !== void 0 ? [toolFor(spec, provider, operation, budget, limit)] : [];
1648
1852
  });
1649
1853
  };
@@ -1662,4 +1866,154 @@ const toolError = (cause) => {
1662
1866
  retryable: false
1663
1867
  };
1664
1868
  };
1665
- export { DEFAULT_MAX_CHARACTERS, EXCLUDED_BY_DEFAULT, checkMaxCharacters, toolError, toolsFor };
1869
+ // src/tools/catalog.ts
1870
+ /** Retrieval-style notes for `search_web` when more than one search provider is offered. */
1871
+ const SEARCH_PROVIDER_ROLES = /* @__PURE__ */ new Map([
1872
+ ["brave", "brave for lexical/keyword queries, search operators and token-budgeted passages (content: true)"],
1873
+ ["browserbase", "browserbase for managed web search"],
1874
+ ["exa", "exa for neural/semantic queries and capped highlights"],
1875
+ ["firecrawl", "firecrawl for web search with full-page Markdown"],
1876
+ ["parallel", "parallel for objective-driven semantic search and char-budgeted excerpts"],
1877
+ ["perplexity", "perplexity for hybrid lexical+semantic search with token-budgeted snippets"],
1878
+ ["serpapi", "serpapi for Google/Bing SERPs and exact keyword queries"],
1879
+ ["tavily", "tavily for hybrid search with chunked passages"]
1880
+ ]);
1881
+ const searchProviderGuidance = (providers) => {
1882
+ if (providers.length < 2) return "";
1883
+ const notes = providers.flatMap((provider) => {
1884
+ const role = SEARCH_PROVIDER_ROLES.get(provider);
1885
+ return role === void 0 ? [] : [role];
1886
+ });
1887
+ return notes.length === 0 ? "" : ` Choose provider by query style: ${notes.join("; ")}.`;
1888
+ };
1889
+ const InputSchema = z.object({
1890
+ oneOf: z.optional(z.array(z.json())),
1891
+ properties: z.record(z.string(), z.json()),
1892
+ required: z.optional(z.array(z.string()))
1893
+ });
1894
+ const providerBranchSchema = (tool, explicit, extraProperties = {}) => {
1895
+ const schema = z.parse(InputSchema, tool.inputSchema);
1896
+ const properties = {
1897
+ ...schema.properties,
1898
+ ...extraProperties
1899
+ };
1900
+ if (explicit) properties.provider = {
1901
+ const: tool.provider,
1902
+ type: "string"
1903
+ };
1904
+ const input = {
1905
+ additionalProperties: false,
1906
+ properties,
1907
+ required: [...schema.required ?? [], ...explicit ? ["provider"] : []],
1908
+ type: "object"
1909
+ };
1910
+ if (schema.oneOf !== void 0) input.oneOf = schema.oneOf;
1911
+ return input;
1912
+ };
1913
+ const resolveDefaultTool = (variants, first, configured, alwaysSelect) => {
1914
+ if (configured === void 0) {
1915
+ if (alwaysSelect || variants.size !== 1) return;
1916
+ return first;
1917
+ }
1918
+ if (isText(configured)) return variants.get(configured);
1919
+ for (const candidate of configured) {
1920
+ const found = variants.get(candidate);
1921
+ if (found !== void 0) return found;
1922
+ }
1923
+ };
1924
+ const multiProviderSchema = (variants, defaultTool, providers, extraProperties) => ({
1925
+ oneOf: [...defaultTool === void 0 ? [] : [providerBranchSchema(defaultTool, false, extraProperties)], ...variants.map((tool) => providerBranchSchema(tool, true, extraProperties))],
1926
+ properties: {
1927
+ provider: {
1928
+ enum: [...providers],
1929
+ type: "string"
1930
+ },
1931
+ ...extraProperties
1932
+ },
1933
+ type: "object"
1934
+ });
1935
+ const describeMultiProviderTool = (first, providers, defaultProvider) => {
1936
+ const guidance = first.name === "search_web" ? searchProviderGuidance(providers) : "";
1937
+ const routing = defaultProvider === void 0 ? "Name a provider explicitly." : `Defaults to ${defaultProvider}.`;
1938
+ return `${first.description}${guidance} ${routing} Set provider to choose another supported provider; Fieldwork never switches providers after an error.`;
1939
+ };
1940
+ const collectToolVariants = (clients, options = {}) => {
1941
+ const entries = /* @__PURE__ */ new Map();
1942
+ for (const client of clients) for (const tool of toolsFor(client, options)) {
1943
+ const variants = entries.get(tool.name) ?? /* @__PURE__ */ new Map();
1944
+ if (variants.has(tool.provider)) throw new FieldworkError("InvalidRequest", `Duplicate provider ${tool.provider} for ${tool.name}`, { provider: tool.provider });
1945
+ variants.set(tool.provider, tool);
1946
+ entries.set(tool.name, variants);
1947
+ }
1948
+ return entries;
1949
+ };
1950
+ const catalogToolFor = (first, list, defaultTool, providers, single, extraProperties, select) => {
1951
+ const defaultProvider = defaultTool?.provider;
1952
+ const singleSchema = Object.keys(extraProperties).length > 0 ? providerBranchSchema(first, false, extraProperties) : first.inputSchema;
1953
+ return {
1954
+ annotations: first.annotations,
1955
+ capability: first.capability,
1956
+ ...defaultProvider !== void 0 && { defaultProvider },
1957
+ description: single ? first.description : describeMultiProviderTool(first, providers, defaultProvider),
1958
+ execute: async (input, call = {}) => {
1959
+ if (!isJsonObject(input)) throw new FieldworkError("InvalidRequest", `${first.name}: input must be an object`);
1960
+ if (single && defaultTool !== void 0) return await defaultTool.execute(input, call);
1961
+ const { provider, ...args } = input;
1962
+ if (provider !== void 0 && !isText(provider)) throw new FieldworkError("InvalidRequest", `${first.name}: provider must be a string`);
1963
+ return await select(first.name, provider).execute(args, call);
1964
+ },
1965
+ inputSchema: single ? singleSchema : multiProviderSchema(list, defaultTool, providers, extraProperties),
1966
+ ...first.method !== void 0 && { method: first.method },
1967
+ name: first.name,
1968
+ outputSchema: first.outputSchema,
1969
+ providers,
1970
+ single
1971
+ };
1972
+ };
1973
+ /**
1974
+ * Builds one tool per capability name across several Fieldwork clients. Each
1975
+ * provider keeps its own input schema branch and executor; no options are
1976
+ * merged and no call falls back to another provider after an error.
1977
+ *
1978
+ * Under the default `providerSelection: "multi"`, a single-provider tool with
1979
+ * a default keeps its plain schema (`single: true`, no `provider` field). When
1980
+ * several providers serve a tool (such as `search_web` over Brave and Exa), the
1981
+ * tool exposes a `provider` enum with per-provider `oneOf` branches and
1982
+ * query-style guidance in `search_web`'s description.
1983
+ */
1984
+ const toolCatalog = (clients, options = {}) => {
1985
+ const { defaults, extraProperties = {}, providerSelection = "multi", toolDefaults, ...toolOptions } = options;
1986
+ const alwaysSelect = providerSelection === "always";
1987
+ const entries = collectToolVariants(clients, toolOptions);
1988
+ const defaultByTool = /* @__PURE__ */ new Map();
1989
+ const providersByTool = /* @__PURE__ */ new Map();
1990
+ const select = (name, provider) => {
1991
+ const variants = entries.get(name);
1992
+ if (variants === void 0) throw new FieldworkError("NotFound", `${name} is not a tool in this catalog`);
1993
+ const selected = provider ?? defaultByTool.get(name);
1994
+ const tool = selected === void 0 ? void 0 : variants.get(selected);
1995
+ if (tool === void 0) {
1996
+ const available = providersByTool.get(name)?.join(", ") ?? "none";
1997
+ throw new FieldworkError("Unsupported", `${name} needs a supported provider; available: ${available}`, { provider: selected });
1998
+ }
1999
+ return tool;
2000
+ };
2001
+ const tools = [];
2002
+ for (const variants of entries.values()) {
2003
+ const list = [...variants.values()];
2004
+ const [first] = list;
2005
+ if (first === void 0) continue;
2006
+ const providers = list.map((tool) => tool.provider);
2007
+ const configured = toolDefaults?.[first.name] ?? defaults?.[first.capability];
2008
+ const defaultTool = resolveDefaultTool(variants, first, configured, alwaysSelect);
2009
+ defaultByTool.set(first.name, defaultTool?.provider);
2010
+ providersByTool.set(first.name, providers);
2011
+ const single = providerSelection === "multi" && list.length === 1 && defaultTool !== void 0;
2012
+ tools.push(catalogToolFor(first, list, defaultTool, providers, single, extraProperties, select));
2013
+ }
2014
+ return {
2015
+ select,
2016
+ tools
2017
+ };
2018
+ };
2019
+ export { DEFAULT_MAX_CHARACTERS, EXCLUDED_BY_DEFAULT, checkMaxCharacters, toolCatalog, toolError, toolsFor };