@howells/fieldwork-sdk 0.5.1 → 0.6.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.d.ts CHANGED
@@ -1,21 +1,11 @@
1
- import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-CXNIcqSN.js";
2
- import { M as JsonSchema, m as Capability, n as AnyAdapter, p as CallOptions } from "./adapter-BgdfLBs-.js";
3
- /**
4
- * The JSON values that cross the tool boundary: what a model sends in, what a
5
- * tool sends back. Tools take and return these types, and the guards below are
6
- * the one place untyped data becomes one of them.
7
- */
1
+ import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-BaWqUNI3.js";
2
+ import { M as JsonSchema, m as Capability, n as AnyAdapter, p as CallOptions } from "./adapter-Bh8EIrNe.js";
3
+ /** Any JSON value. */
8
4
  type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
5
+ /** A JSON object. A key may be undefined, which reads as absent and is not serialized. */
9
6
  interface JsonObject {
10
7
  [key: string]: JsonValue | undefined;
11
8
  }
12
- /**
13
- * Tool definitions for agents, built from a Fieldwork instance. Each tool's
14
- * input schema lists only the options its provider supports, so a model is
15
- * never offered an option that would be ignored. The definitions are plain
16
- * JSON Schema with MCP-style annotations, so they work with the AI SDK, MCP
17
- * servers and any framework that accepts JSON Schema tools.
18
- */
19
9
  /** What a model sends a tool: a parsed JSON value, which must be an object. */
20
10
  export type ToolInput = JsonValue;
21
11
  /** The arguments a tool accepts, once they are known to be an object. */
@@ -31,13 +21,14 @@ export interface ToolAnnotations {
31
21
  destructiveHint: boolean;
32
22
  /** True when repeating a call with the same input has no further effect. */
33
23
  idempotentHint: boolean;
34
- /** True when the tool reaches the open web. */
24
+ /** True when the tool reaches outside Fieldwork. `toolsFor` sets it on every tool. */
35
25
  openWorldHint: boolean;
36
26
  }
37
27
  /** One agent tool, ready to register with an MCP server or a model's tool API. */
38
28
  export interface FieldworkTool {
39
29
  /** A verb_noun name, such as `search_web`. */
40
30
  name: string;
31
+ /** The capability this tool calls on the instance. */
41
32
  capability: Capability;
42
33
  /** For a group capability, the method this tool calls, such as `create` for `monitor`. */
43
34
  method?: string;
@@ -53,7 +44,8 @@ export interface FieldworkTool {
53
44
  /**
54
45
  * Checks the input against `inputSchema`, calls the capability and returns
55
46
  * the result shaped for a model: without the provider's `raw` response and
56
- * with long text cut to the `maxCharacters` budget. Throws a
47
+ * with long text cut to the `maxCharacters` budget. `options` are the call's
48
+ * `signal`, `timeout` and `retries`, passed through. Throws a
57
49
  * `FieldworkError`; bad input is `InvalidRequest`.
58
50
  */
59
51
  execute: (input: ToolInput, options?: CallOptions) => Promise<ToolOutput>;
@@ -83,11 +75,17 @@ export interface ToolsOptions {
83
75
  */
84
76
  maxCharacters?: number;
85
77
  }
86
- /** Makes one tool per capability, or per method of a group, the instance supports. */
78
+ /**
79
+ * Makes one tool per capability, or per method of a group, the instance
80
+ * supports, in the order of `SPECS`. A router gives each tool the inputs of
81
+ * the provider that serves its capability, and `provider` names it.
82
+ */
87
83
  export declare const toolsFor: (web: Fieldwork<AnyAdapter>, options?: ToolsOptions) => FieldworkTool[];
88
84
  /**
89
85
  * An error as a model or an MCP client should see it: the code, the message
90
- * and what to do next, without the provider's response.
86
+ * and what to do next (`retryable`, `retryAfter`, `jobId`), without the
87
+ * provider's response. An error that is not a `FieldworkError` becomes a
88
+ * `ProviderError` that is not retryable.
91
89
  */
92
90
  export declare const toolError: (cause: unknown) => {
93
91
  code: FieldworkErrorCode;
package/dist/tools.js CHANGED
@@ -1,18 +1,23 @@
1
- import { t as FieldworkError } from "./errors-Yvk42oZH.js";
1
+ import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
2
  import { t as CAPABILITIES } from "./types-CnomnF-6.js";
3
3
  // src/tool-specs/schema.ts
4
4
  const described = (schema, description) => description === void 0 ? schema : {
5
5
  ...schema,
6
6
  description
7
7
  };
8
+ /** A string, with any extra keywords such as `pattern`. */
8
9
  const text = (description, extra = {}) => ({
9
10
  ...extra,
10
11
  description,
11
12
  type: "string"
12
13
  });
14
+ /** A string that must parse as a full URL. */
13
15
  const url = (description) => text(description, { format: "uri" });
16
+ /** A string in the form YYYY-MM-DD. */
14
17
  const date = (description) => text(description, { format: "date" });
18
+ /** A string that is one of `values`. */
15
19
  const choice = (description, values) => text(description, { enum: values });
20
+ /** An integer from `minimum`, up to `maximum` when given. */
16
21
  const whole = (description, minimum, maximum) => maximum === void 0 ? {
17
22
  description,
18
23
  minimum,
@@ -23,14 +28,19 @@ const whole = (description, minimum, maximum) => maximum === void 0 ? {
23
28
  minimum,
24
29
  type: "integer"
25
30
  };
31
+ /** Any number. */
26
32
  const number = (description) => described({ type: "number" }, description);
33
+ /** A boolean. */
27
34
  const flag = (description) => described({ type: "boolean" }, description);
35
+ /** An array of `items`, with any extra keywords such as `minItems`. */
28
36
  const list = (items, description, extra = {}) => described({
29
37
  ...extra,
30
38
  items,
31
39
  type: "array"
32
40
  }, description);
41
+ /** An array of strings. */
33
42
  const texts = (description) => list({ type: "string" }, description);
43
+ /** An object with the given properties; `required` lists the keys that must be present. Other keys are allowed. */
34
44
  const object = (properties, required = [], description) => described(required.length === 0 ? {
35
45
  properties,
36
46
  type: "object"
@@ -46,45 +56,50 @@ const keyed = (values, description) => described({
46
56
  }, description);
47
57
  /** Any JSON value. */
48
58
  const anything = (description) => described({}, description);
59
+ /** A bare string, for properties that need no description. */
49
60
  const str = { type: "string" };
50
61
  // src/tool-specs/fields.ts
51
- /**
52
- * Inputs that several tools share. Each helper takes the providers whose
53
- * options type has the option with this meaning.
54
- */
55
62
  const RESUME_DESCRIPTION = "The jobId from an earlier call's error, when that call timed out or was cancelled. Waits for that job instead of starting and paying for a new one.";
63
+ /** The required `url` input. */
56
64
  const urlField = (description) => ({
57
65
  name: "url",
58
66
  required: true,
59
67
  schema: url(description)
60
68
  });
69
+ /** The description of a `url` input that names a page. */
61
70
  const PAGE_URL = "The page's full URL, including https://.";
71
+ /** The `resume` input, for providers whose method accepts it: a `jobId` from an earlier error, to wait for that job again (see `runJob`). */
62
72
  const resume = (providers) => ({
63
73
  name: "resume",
64
74
  providers,
65
75
  schema: text(RESUME_DESCRIPTION)
66
76
  });
77
+ /** The `limit` input: a whole number from 1 to `maximum`. */
67
78
  const limit = (description, maximum, providers) => ({
68
79
  name: "limit",
69
80
  providers,
70
81
  schema: whole(description, 1, maximum)
71
82
  });
72
83
  const NOT_TOGETHER = "Firecrawl, Parallel and Perplexity refuse includeDomains and excludeDomains together.";
84
+ /** The `includeDomains` input. `noun` names what is restricted ("results", "sources"); `note` adds a provider-specific caveat. */
73
85
  const includeDomains = (noun, providers, note = "") => ({
74
86
  name: "includeDomains",
75
87
  providers,
76
88
  schema: texts(`Only use ${noun} from these domains, such as example.com. ${NOT_TOGETHER} ${note}`.trim())
77
89
  });
90
+ /** The `excludeDomains` input, worded as `includeDomains` is. */
78
91
  const excludeDomains = (noun, providers, note = "") => ({
79
92
  name: "excludeDomains",
80
93
  providers,
81
94
  schema: texts(`Leave out ${noun} from these domains, such as example.com. ${NOT_TOGETHER} ${note}`.trim())
82
95
  });
96
+ /** The `publishedAfter` input, a date. */
83
97
  const publishedAfter = (providers) => ({
84
98
  name: "publishedAfter",
85
99
  providers,
86
100
  schema: date("Only pages published on or after this date, YYYY-MM-DD.")
87
101
  });
102
+ /** The `publishedBefore` input, a date. */
88
103
  const publishedBefore = (providers) => ({
89
104
  name: "publishedBefore",
90
105
  providers,
@@ -129,21 +144,25 @@ const recency = (withHour, fromDay) => [{
129
144
  "year"
130
145
  ])
131
146
  }].filter((field) => field.providers.length > 0);
147
+ /** The `country` input, a two-letter ISO code. `what` is the sentence's lead, such as "Search from". */
132
148
  const country = (providers, what = "Prefer results for") => ({
133
149
  name: "country",
134
150
  providers,
135
151
  schema: text(`${what} this country, as a two-letter ISO code such as GB.`, { pattern: "^[A-Za-z]{2}$" })
136
152
  });
153
+ /** The `language` input, an ISO 639-1 code. */
137
154
  const language = (providers) => ({
138
155
  name: "language",
139
156
  providers,
140
157
  schema: text("Prefer pages in this language, as an ISO 639-1 code such as en.")
141
158
  });
159
+ /** The `continueFrom` input: the `continuationId` of an earlier result. */
142
160
  const continueFrom = (providers) => ({
143
161
  name: "continueFrom",
144
162
  providers,
145
163
  schema: text("The continuationId of an earlier result, to ask a follow-up in the same thread instead of starting over.")
146
164
  });
165
+ /** The `schema` input, a JSON Schema object. Optional unless `required` is true. */
147
166
  const schemaField = (description, providers, required = false) => ({
148
167
  name: "schema",
149
168
  providers,
@@ -166,15 +185,23 @@ const maxAgeAtLeast600 = () => ({
166
185
  providers: ["parallel"],
167
186
  schema: whole(`${CACHE} At least 600: Parallel cannot always fetch fresh.`, 600)
168
187
  });
188
+ /** The `id` input of a monitor, required. */
169
189
  const monitorId = {
170
190
  name: "id",
171
191
  required: true,
172
192
  schema: text("The monitor's id, from create_monitor or list_monitors.")
173
193
  };
194
+ /** A condition for `find_entities`: a name and a description, as the `Condition` type has. */
174
195
  const condition = object({
175
196
  description: text("The condition in plain words."),
176
197
  name: text("A short name for the condition.")
177
198
  }, ["name", "description"]);
199
+ /** The `stealth` input: a browser that hides automation and solves CAPTCHAs, for sites that block bots. */
200
+ const stealth = (providers) => ({
201
+ name: "stealth",
202
+ providers,
203
+ schema: flag("Use a stealth browser that hides automation and solves CAPTCHAs. Use when a site blocks or challenges the plain browser.")
204
+ });
178
205
  const meta = object({
179
206
  requestId: str,
180
207
  usage: object({
@@ -296,28 +323,34 @@ const monitorInfo = object({
296
323
  watch: str,
297
324
  webhookUrl: str
298
325
  }, ["id"]);
326
+ /** The result of `search_web`, a `SearchResponse`. */
299
327
  const SEARCH_OUTPUT = object({
300
328
  answer: str,
301
329
  images: list(imageResult),
302
330
  meta,
303
331
  results: list(searchResult)
304
332
  }, ["results"]);
333
+ /** The result of `search_images`, an `ImageSearch`. */
305
334
  const IMAGES_OUTPUT = object({
306
335
  meta,
307
336
  results: list(imageResult)
308
337
  }, ["results"]);
338
+ /** The result of `read_page`, a `Page`. */
309
339
  const PAGE_OUTPUT = page;
340
+ /** The result of `read_pages`, a `PageBatch`: the pages read, and `failed` for URLs that could not be. */
310
341
  const PAGES_OUTPUT = object({
311
342
  failed: failedUrls,
312
343
  id: str,
313
344
  meta,
314
345
  pages: list(page)
315
346
  }, ["pages", "failed"]);
347
+ /** The result of `extract_values`, an `Extraction`. */
316
348
  const EXTRACT_OUTPUT = object({
317
349
  data: anything("The values, in the shape of the schema."),
318
350
  fields: fieldSources,
319
351
  meta
320
352
  }, ["data"]);
353
+ /** The result of `read_product`, a `Product`. */
321
354
  const PRODUCT_OUTPUT = object({
322
355
  brand: str,
323
356
  category: str,
@@ -328,6 +361,7 @@ const PRODUCT_OUTPUT = object({
328
361
  url: str,
329
362
  variants: list(variant)
330
363
  }, ["variants"]);
364
+ /** The result of `map_site`, a `SiteMap`. */
331
365
  const MAP_OUTPUT = object({
332
366
  links: list(object({
333
367
  description: str,
@@ -336,6 +370,7 @@ const MAP_OUTPUT = object({
336
370
  }, ["url"])),
337
371
  meta
338
372
  }, ["links"]);
373
+ /** The result of `crawl_site`, a `Crawl`. */
339
374
  const CRAWL_OUTPUT = object({
340
375
  failed: failedUrls,
341
376
  id: str,
@@ -344,6 +379,7 @@ const CRAWL_OUTPUT = object({
344
379
  robotsBlocked: texts("URLs the site's robots.txt kept the crawl from."),
345
380
  total: number("Pages found to crawl, when the provider reports it.")
346
381
  }, ["pages"]);
382
+ /** The result of `answer_question`, an `Answer`. */
347
383
  const ANSWER_OUTPUT = object({
348
384
  answer: str,
349
385
  citations,
@@ -352,6 +388,7 @@ const ANSWER_OUTPUT = object({
352
388
  meta,
353
389
  output: anything("The answer in the shape of the schema, when one was given.")
354
390
  }, ["answer", "citations"]);
391
+ /** The result of `research_question`, a `Research`. */
355
392
  const RESEARCH_OUTPUT = object({
356
393
  continuationId: str,
357
394
  fields: fieldSources,
@@ -368,6 +405,7 @@ const RESEARCH_OUTPUT = object({
368
405
  "output",
369
406
  "sources"
370
407
  ]);
408
+ /** The result of `find_entities`, a `Discovery`. */
371
409
  const DISCOVER_OUTPUT = object({
372
410
  entities: list(entity),
373
411
  id: str,
@@ -379,11 +417,13 @@ const DISCOVER_OUTPUT = object({
379
417
  "status",
380
418
  "entities"
381
419
  ]);
420
+ /** The result of `make_decisions`, a `Decisions`. */
382
421
  const DECIDE_OUTPUT = object({
383
422
  answers: keyed(decisionAnswer, "One answer per question, under the question's name."),
384
423
  citations,
385
424
  meta
386
425
  }, ["answers", "citations"]);
426
+ /** The result of `run_browser_script`, an `ActResult`. */
387
427
  const ACT_OUTPUT = object({
388
428
  error: str,
389
429
  exitCode: number(),
@@ -394,6 +434,7 @@ const ACT_OUTPUT = object({
394
434
  stderr: str,
395
435
  stdout: str
396
436
  }, ["stdout", "stderr"]);
437
+ /** The result of `open_browser`, a `BrowserSession`. */
397
438
  const OPEN_BROWSER_OUTPUT = object({
398
439
  cdpUrl: str,
399
440
  expiresAt: str,
@@ -401,6 +442,7 @@ const OPEN_BROWSER_OUTPUT = object({
401
442
  liveViewUrl: str,
402
443
  meta
403
444
  }, ["id"]);
445
+ /** The result of `close_browser`: a confirmation, `{ closed: true, id }`. */
404
446
  const CLOSE_BROWSER_OUTPUT = object({
405
447
  closed: flag(),
406
448
  id: str
@@ -416,6 +458,7 @@ const box = object({
416
458
  "width",
417
459
  "height"
418
460
  ], "Where it sits on the page, as fractions of the page's width and height from its top-left corner.");
461
+ /** The result of `parse_document`, a `ParsedDocument`. */
419
462
  const PARSE_OUTPUT = object({
420
463
  blocks: list(object({
421
464
  box,
@@ -452,12 +495,16 @@ const PARSE_OUTPUT = object({
452
495
  pageNumber: whole("The physical page number, starting at 1.", 1)
453
496
  }, ["pageNumber", "markdown"]))
454
497
  }, ["markdown"]);
498
+ /** The result of `create_monitor` and `get_monitor`, a `MonitorInfo`. */
455
499
  const MONITOR_OUTPUT = monitorInfo;
500
+ /** The result of `list_monitors`: the `MonitorInfo`s, wrapped as `monitors`. */
456
501
  const MONITORS_OUTPUT = object({ monitors: list(monitorInfo) }, ["monitors"]);
502
+ /** The result of `delete_monitor`: a confirmation, `{ deleted: true, id }`. */
457
503
  const DELETE_MONITOR_OUTPUT = object({
458
504
  deleted: flag(),
459
505
  id: str
460
506
  }, ["deleted", "id"]);
507
+ /** The result of `list_monitor_events`, a `MonitorEvents`. */
461
508
  const MONITOR_EVENTS_OUTPUT = object({
462
509
  events: list(object({
463
510
  at: str,
@@ -469,6 +516,7 @@ const MONITOR_EVENTS_OUTPUT = object({
469
516
  })),
470
517
  next: str
471
518
  }, ["events"]);
519
+ /** The result of `check_usage`, an `AccountUsage`. */
472
520
  const USAGE_OUTPUT = object({
473
521
  breakdown: keyed(number()),
474
522
  limit: number(),
@@ -477,11 +525,13 @@ const USAGE_OUTPUT = object({
477
525
  used: number()
478
526
  });
479
527
  // src/tool-specs/answer.ts
528
+ /** The required `question` input, the tool's one positional argument. */
480
529
  const question = (description) => ({
481
530
  name: "question",
482
531
  required: true,
483
532
  schema: text(description)
484
533
  });
534
+ /** One question for `make_decisions`, in the three forms of the `DecisionQuestion` type: `yesno`, `choice` and `score`. */
485
535
  const decisionQuestion = { oneOf: [
486
536
  object({
487
537
  question: str,
@@ -506,6 +556,11 @@ const decisionQuestion = { oneOf: [
506
556
  "scale"
507
557
  ])
508
558
  ] };
559
+ /**
560
+ * The tools that answer or decide: `answer_question`, `research_question`,
561
+ * `find_entities` and `make_decisions`. `research_question` and
562
+ * `find_entities` run as jobs, so they take `resume` where the provider does.
563
+ */
509
564
  const ANSWER_SPECS = [
510
565
  {
511
566
  capability: "answer",
@@ -649,6 +704,13 @@ const ANSWER_SPECS = [
649
704
  }
650
705
  ];
651
706
  // src/tool-specs/browser.ts
707
+ /**
708
+ * The tools that drive a browser or convert a file: `run_browser_script`,
709
+ * `open_browser`, `close_browser` and `parse_document`. `toolsFor` leaves out
710
+ * 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.
713
+ */
652
714
  const BROWSER_SPECS = [
653
715
  {
654
716
  capability: "act",
@@ -689,6 +751,12 @@ const BROWSER_SPECS = [
689
751
  providers: ["browserbase"],
690
752
  schema: whole("Seconds the session may live, 60 to 21600. It closes by itself after that.", 60, 21600)
691
753
  },
754
+ {
755
+ name: "idleTimeout",
756
+ providers: ["kernel"],
757
+ schema: whole("Seconds without a CDP or live-view connection before the session closes by itself, 10 to 259200. Defaults to 60.", 10, 259200)
758
+ },
759
+ stealth(["kernel"]),
692
760
  country(["firecrawl"], "Browse from")
693
761
  ],
694
762
  idempotent: false,
@@ -763,6 +831,11 @@ const closed = (schema) => ({
763
831
  additionalProperties: false
764
832
  });
765
833
  const SCHEDULE_NOTE = "How often the monitor checks. Give exactly one of every or cron.";
834
+ /**
835
+ * The `schedule` input in the two forms providers take: Exa and Parallel an
836
+ * `every` interval only, Firecrawl an interval or a cron expression. Two fields
837
+ * of one name, because the accepted values differ.
838
+ */
766
839
  const schedules = [{
767
840
  name: "schedule",
768
841
  providers: ["exa", "parallel"],
@@ -781,16 +854,25 @@ const schedules = [{
781
854
  }
782
855
  }];
783
856
  const DOMAIN_NOTE = "Firecrawl takes domain lists only for a monitor that searches: give a query and no urls.";
857
+ /** Every provider with a monitor. */
784
858
  const MONITOR_PROVIDERS = [
785
859
  "exa",
786
860
  "firecrawl",
787
861
  "parallel"
788
862
  ];
863
+ /** The `cursor` input of `list_monitor_events`: the `next` of the previous page. */
789
864
  const cursor = {
790
865
  name: "cursor",
791
866
  providers: MONITOR_PROVIDERS,
792
867
  schema: text("The next value from the previous page of events.")
793
868
  };
869
+ /**
870
+ * The tools that manage monitors, `create_monitor`, `get_monitor`,
871
+ * `list_monitors`, `delete_monitor` and `list_monitor_events`, which call the
872
+ * methods of the `monitor` group, and `check_usage`, which calls `usage`.
873
+ * `toolsFor` leaves out the monitor tools unless asked, since a monitor keeps
874
+ * running and billing.
875
+ */
794
876
  const MONITOR_SPECS = [
795
877
  {
796
878
  capability: "monitor",
@@ -927,6 +1009,11 @@ const query = {
927
1009
  ],
928
1010
  schema: text("Also return the passages of each page that answer this, as excerpts.")
929
1011
  };
1012
+ /**
1013
+ * The tools that read pages: `read_page`, `read_pages`, `extract_values`,
1014
+ * `read_product`, `map_site` and `crawl_site`. Firecrawl runs `read_pages` and
1015
+ * `crawl_site` as jobs, so they take `resume` with it.
1016
+ */
930
1017
  const READ_SPECS = [
931
1018
  {
932
1019
  capability: "read",
@@ -937,7 +1024,8 @@ const READ_SPECS = [
937
1024
  query,
938
1025
  maxAge(["exa", "firecrawl"]),
939
1026
  maxAgeAtLeast600(),
940
- country(["browserbase"], "Fetch the page through a proxy in")
1027
+ country(["browserbase"], "Fetch the page through a proxy in"),
1028
+ stealth(["kernel"])
941
1029
  ],
942
1030
  idempotent: true,
943
1031
  name: "read_page",
@@ -1169,6 +1257,7 @@ const SPECS = [
1169
1257
  ];
1170
1258
  // src/tools/json.ts
1171
1259
  const isText = (value) => typeof value === "string";
1260
+ /** A finite number: JSON has no NaN or Infinity. */
1172
1261
  const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
1173
1262
  const isFlag = (value) => typeof value === "boolean";
1174
1263
  const isList = (value) => Array.isArray(value);
@@ -1183,14 +1272,28 @@ const operationFor = (web, spec) => {
1183
1272
  if (spec.method === void 0) return isOperation(entry) ? entry : void 0;
1184
1273
  return isGroup(entry) ? entry[spec.method] : void 0;
1185
1274
  };
1275
+ /** Standard-alphabet base64: no backtracking, so it is linear in the input. */
1276
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/u;
1277
+ /**
1278
+ * The `parse` file from the tool's `name` and base64 `contentBase64`.
1279
+ *
1280
+ * Throws `InvalidRequest` when either is not a string or the content is not
1281
+ * well-formed base64 (standard alphabet, padded to a multiple of 4).
1282
+ */
1186
1283
  const documentFrom = (name, content) => {
1187
1284
  if (!isText(name) || !isText(content)) throw new FieldworkError("InvalidRequest", "parse_document needs name and contentBase64");
1285
+ 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" : ""}`);
1188
1286
  return {
1189
1287
  data: new Uint8Array(Buffer.from(content, "base64")),
1190
1288
  name
1191
1289
  };
1192
1290
  };
1193
- /** The arguments for the spec's method, from validated input and the call settings. */
1291
+ /**
1292
+ * The arguments for the spec's method, from validated input and the call
1293
+ * settings: the `positional` fields in order, then one options object of the
1294
+ * other fields and the call settings (`signal`, `timeout`, `retries`). `parse`
1295
+ * is the exception: its two positional fields become one `DocumentArgument`.
1296
+ */
1194
1297
  const argumentsFor = (spec, values, call) => {
1195
1298
  const options = {
1196
1299
  ...Object.fromEntries(Object.entries(values).filter(([key]) => !spec.positional.includes(key))),
@@ -1233,12 +1336,19 @@ const rank = (key) => {
1233
1336
  if (SPEND_FIRST.includes(key)) return SPEND_FIRST.indexOf(key);
1234
1337
  return SPEND_LAST.includes(key) ? SPEND_FIRST.length + 1 + SPEND_LAST.indexOf(key) : SPEND_FIRST.length;
1235
1338
  };
1339
+ /** 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. */
1236
1340
  const cut = (value, budget) => {
1237
1341
  if (value.length <= SHORT_TEXT) return value;
1238
1342
  const kept = Math.min(value.length, budget.remaining);
1239
1343
  budget.remaining -= kept;
1240
1344
  return kept === value.length ? value : `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
1241
1345
  };
1346
+ /**
1347
+ * Applies `cut` and the `raw` rule through a value. Fields are visited in
1348
+ * `rank` order so the answer or page text gets the budget first, but each
1349
+ * object keeps its own key order. `verbatim` is set inside `VERBATIM` keys and
1350
+ * stays set below them.
1351
+ */
1242
1352
  const shape = (value, verbatim, budget) => {
1243
1353
  if (isText(value)) return cut(value, budget);
1244
1354
  if (isList(value)) return value.map((item) => shape(item, verbatim, budget) ?? null);
@@ -1259,15 +1369,14 @@ const forModel = (result, budget) => {
1259
1369
  return isJsonObject(shaped) ? shaped : {};
1260
1370
  };
1261
1371
  // src/tools/validate.ts
1262
- /**
1263
- * Checks a value against the schema subset the tools use and says what is
1264
- * wrong in words a model can act on, or returns nothing when it is fine.
1265
- */
1372
+ /** The shape only: 2026-02-31 passes and is the provider's to refuse. */
1266
1373
  const DATE = /^\d{4}-\d{2}-\d{2}$/u;
1374
+ /** Only http and https: "file:///x", "localhost:3000" and "a.com:80/p" parse as URLs with other schemes. */
1375
+ const isWebUrl = (value) => URL.canParse(value) && ["http:", "https:"].includes(new URL(value).protocol);
1267
1376
  const textProblem = (schema, value, name) => {
1268
1377
  if (value === "") return `${name} must not be empty`;
1269
1378
  if (schema.enum !== void 0 && !schema.enum.includes(value)) return `${name} must be one of ${schema.enum.join(", ")}`;
1270
- if (schema.format === "uri" && !URL.canParse(value)) return `${name} must be a full URL, including https://`;
1379
+ if (schema.format === "uri" && !isWebUrl(value)) return `${name} must be a full URL, including https://`;
1271
1380
  if (schema.format === "date" && !DATE.test(value)) return `${name} must be a date as YYYY-MM-DD`;
1272
1381
  if (schema.pattern !== void 0 && !new RegExp(schema.pattern, "u").test(value)) return `${name} must match the pattern ${schema.pattern}`;
1273
1382
  };
@@ -1313,7 +1422,12 @@ const typeProblem = (schema, value, name, check) => {
1313
1422
  if (type === "array") return isList(value) ? listProblem(schema, value, name, check) : `${name} must be a list`;
1314
1423
  if (type === "object") return isJsonObject(value) ? objectProblem(schema, value, name, check) : `${name} must be a JSON object`;
1315
1424
  };
1316
- /** What is wrong with `value` as `name`, in full ("limit must be a whole number from 1 to 20"), or nothing. */
1425
+ /**
1426
+ * What is wrong with `value` as `name`, in full ("limit must be a whole
1427
+ * number from 1 to 20"), or nothing. Checks only the keywords `FieldSchema`
1428
+ * has. A string must not be empty, and a schema with no `type` accepts any
1429
+ * value. With `oneOf`, one option that passes is enough.
1430
+ */
1317
1431
  const problem = (schema, value, name) => {
1318
1432
  if (schema.oneOf !== void 0) {
1319
1433
  const problems = schema.oneOf.map((option) => problem(option, value, name));
@@ -1332,9 +1446,18 @@ const EXCLUDED_BY_DEFAULT = [
1332
1446
  "browser",
1333
1447
  "monitor"
1334
1448
  ];
1449
+ /** Whether the field is offered to the provider: a field with no `providers` goes to every provider that has the capability. */
1335
1450
  const offers = (field, provider) => field.providers === void 0 || field.providers.some((name) => name === provider);
1451
+ /** Whether the field is required for the provider, either for all that are offered it or for this one. */
1336
1452
  const needs = (field, provider) => field.required === true || field.requiredFor?.some((name) => name === provider) === true;
1337
1453
  const invalid = (tool, provider, message) => new FieldworkError("InvalidRequest", `${tool}: ${message}`, { provider });
1454
+ /**
1455
+ * Checks a model's input against the fields offered to the provider and
1456
+ * returns it unchanged: it must be an object, with no key the provider does
1457
+ * not take, every required field present and each value valid for its schema.
1458
+ *
1459
+ * Throws `InvalidRequest`, prefixed with the tool's name, on the first problem.
1460
+ */
1338
1461
  const readInput = (tool, provider, fields, input) => {
1339
1462
  if (!isJsonObject(input)) throw invalid(tool, provider, "input must be an object");
1340
1463
  const known = new Set(fields.map((field) => field.name));
@@ -1350,7 +1473,11 @@ const readInput = (tool, provider, fields, input) => {
1350
1473
  }
1351
1474
  return input;
1352
1475
  };
1353
- /** The tool's result as an object: a list is wrapped, a confirmation is spelled out. */
1476
+ /**
1477
+ * The tool's result as an object: a list is wrapped, a confirmation is spelled
1478
+ * out. Any other result must already be an object, or this throws
1479
+ * `ProviderError`.
1480
+ */
1354
1481
  const resultObject = (spec, values, result) => {
1355
1482
  if (spec.wrapAs !== void 0) return { [spec.wrapAs]: result };
1356
1483
  if (spec.confirmAs !== void 0) return {
@@ -1360,6 +1487,7 @@ const resultObject = (spec, values, result) => {
1360
1487
  if (isJsonObject(result)) return result;
1361
1488
  throw new FieldworkError("ProviderError", `${spec.name} got a result that is not an object`);
1362
1489
  };
1490
+ /** The JSON Schema advertised for the tool's input: closed to other keys, requiring what `needs` says. */
1363
1491
  const inputSchema = (fields, provider) => ({
1364
1492
  additionalProperties: false,
1365
1493
  properties: Object.fromEntries(fields.map((field) => [field.name, { ...field.schema }])),
@@ -1390,7 +1518,11 @@ const toolFor = (spec, provider, operation, budget) => {
1390
1518
  provider
1391
1519
  };
1392
1520
  };
1393
- /** Makes one tool per capability, or per method of a group, the instance supports. */
1521
+ /**
1522
+ * Makes one tool per capability, or per method of a group, the instance
1523
+ * supports, in the order of `SPECS`. A router gives each tool the inputs of
1524
+ * the provider that serves its capability, and `provider` names it.
1525
+ */
1394
1526
  const toolsFor = (web, options = {}) => {
1395
1527
  const wanted = /* @__PURE__ */ new Set([...options.capabilities ?? CAPABILITIES.filter((capability) => !EXCLUDED_BY_DEFAULT.includes(capability)), ...options.allow ?? []]);
1396
1528
  const budget = options.maxCharacters ?? 2e4;
@@ -1403,7 +1535,9 @@ const toolsFor = (web, options = {}) => {
1403
1535
  };
1404
1536
  /**
1405
1537
  * An error as a model or an MCP client should see it: the code, the message
1406
- * and what to do next, without the provider's response.
1538
+ * and what to do next (`retryable`, `retryAfter`, `jobId`), without the
1539
+ * provider's response. An error that is not a `FieldworkError` becomes a
1540
+ * `ProviderError` that is not retryable.
1407
1541
  */
1408
1542
  const toolError = (cause) => {
1409
1543
  if (cause instanceof FieldworkError) return cause.toJSON();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.5.1",
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, LlamaParse and Reducto.",
3
+ "version": "0.6.0",
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",
7
7
  "brave",
@@ -10,6 +10,7 @@
10
10
  "exa",
11
11
  "extraction",
12
12
  "firecrawl",
13
+ "kernel",
13
14
  "llamaparse",
14
15
  "monitoring",
15
16
  "parallel",
@@ -75,6 +76,10 @@
75
76
  "types": "./dist/browserbase.d.ts",
76
77
  "import": "./dist/browserbase.js"
77
78
  },
79
+ "./kernel": {
80
+ "types": "./dist/kernel.d.ts",
81
+ "import": "./dist/kernel.js"
82
+ },
78
83
  "./llamaparse": {
79
84
  "types": "./dist/llamaparse.d.ts",
80
85
  "import": "./dist/llamaparse.js"
@@ -92,12 +97,14 @@
92
97
  "access": "public"
93
98
  },
94
99
  "dependencies": {
100
+ "turndown": "7.2.5",
95
101
  "zod": "^4.6.7"
96
102
  },
97
103
  "devDependencies": {
98
104
  "@howells/lint": "^3.9.1",
99
105
  "@howells/typescript-config": "^0.1.8",
100
106
  "@types/node": "^26.6.2",
107
+ "@types/turndown": "5.0.6",
101
108
  "tsdown": "^0.23.0",
102
109
  "typescript": "7.0.2",
103
110
  "vitest": "^5.0.1"