@howells/fieldwork-sdk 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tools.js CHANGED
@@ -1,577 +1,1367 @@
1
- import { t as FieldworkError } from "./errors-pzPMh82H.js";
2
- // src/tool-specs.ts
1
+ import { t as FieldworkError } from "./errors-BiIBG9zN.js";
2
+ import { t as CAPABILITIES } from "./types-CnomnF-6.js";
3
+ // src/tool-specs/schema.ts
4
+ /** A schema as plain JSON Schema, for clients. */
5
+ const toJsonSchema = (schema) => ({ ...schema });
6
+ const described = (schema, description) => description === void 0 ? schema : {
7
+ ...schema,
8
+ description
9
+ };
10
+ const text = (description, extra = {}) => ({
11
+ ...extra,
12
+ description,
13
+ type: "string"
14
+ });
15
+ const url = (description) => text(description, { format: "uri" });
16
+ const date = (description) => text(description, { format: "date" });
17
+ const choice = (description, values) => text(description, { enum: values });
18
+ const whole = (description, minimum, maximum) => maximum === void 0 ? {
19
+ description,
20
+ minimum,
21
+ type: "integer"
22
+ } : {
23
+ description,
24
+ maximum,
25
+ minimum,
26
+ type: "integer"
27
+ };
28
+ const number = (description) => described({ type: "number" }, description);
29
+ const flag = (description) => described({ type: "boolean" }, description);
30
+ const list = (items, description, extra = {}) => described({
31
+ ...extra,
32
+ items,
33
+ type: "array"
34
+ }, description);
35
+ const texts = (description) => list({ type: "string" }, description);
36
+ const object = (properties, required = [], description) => described(required.length === 0 ? {
37
+ properties,
38
+ type: "object"
39
+ } : {
40
+ properties,
41
+ required,
42
+ type: "object"
43
+ }, description);
44
+ /** An object whose keys the caller chooses and whose values share a schema. */
45
+ const keyed = (values, description) => described({
46
+ additionalProperties: values,
47
+ type: "object"
48
+ }, description);
49
+ /** Any JSON value. */
50
+ const anything = (description) => described({}, description);
51
+ const str = { type: "string" };
52
+ // src/tool-specs/fields.ts
53
+ /**
54
+ * Inputs that several tools share. Each helper takes the providers whose
55
+ * options type has the option with this meaning.
56
+ */
3
57
  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.";
4
- const url = {
58
+ const urlField = (description) => ({
5
59
  name: "url",
6
60
  required: true,
61
+ schema: url(description)
62
+ });
63
+ const PAGE_URL = "The page's full URL, including https://.";
64
+ const resume = (providers) => ({
65
+ name: "resume",
66
+ providers,
67
+ schema: text(RESUME_DESCRIPTION)
68
+ });
69
+ const limit = (description, maximum, providers) => ({
70
+ name: "limit",
71
+ providers,
72
+ schema: whole(description, 1, maximum)
73
+ });
74
+ const NOT_TOGETHER = "Firecrawl, Parallel and Perplexity refuse includeDomains and excludeDomains together.";
75
+ const includeDomains = (noun, providers, note = "") => ({
76
+ name: "includeDomains",
77
+ providers,
78
+ schema: texts(`Only use ${noun} from these domains, such as example.com. ${NOT_TOGETHER} ${note}`.trim())
79
+ });
80
+ const excludeDomains = (noun, providers, note = "") => ({
81
+ name: "excludeDomains",
82
+ providers,
83
+ schema: texts(`Leave out ${noun} from these domains, such as example.com. ${NOT_TOGETHER} ${note}`.trim())
84
+ });
85
+ const publishedAfter = (providers) => ({
86
+ name: "publishedAfter",
87
+ providers,
88
+ schema: date("Only pages published on or after this date, YYYY-MM-DD.")
89
+ });
90
+ const publishedBefore = (providers) => ({
91
+ name: "publishedBefore",
92
+ providers,
93
+ schema: date("Only pages published before this date, YYYY-MM-DD.")
94
+ });
95
+ const RECENCY_NOTE = "Not together with publishedAfter or publishedBefore.";
96
+ /**
97
+ * `withHour` providers accept all five windows; `fromDay` providers have no
98
+ * hour window. Two fields with one name, because the accepted values differ.
99
+ */
100
+ const recency = (withHour, fromDay) => [{
101
+ name: "recency",
102
+ providers: withHour,
103
+ schema: choice(`Only pages from the last hour, day, week, month or year. ${RECENCY_NOTE}`, [
104
+ "hour",
105
+ "day",
106
+ "week",
107
+ "month",
108
+ "year"
109
+ ])
110
+ }, {
111
+ name: "recency",
112
+ providers: fromDay,
113
+ schema: choice(`Only pages from the last day, week, month or year. ${RECENCY_NOTE}`, [
114
+ "day",
115
+ "week",
116
+ "month",
117
+ "year"
118
+ ])
119
+ }].filter((field) => field.providers.length > 0);
120
+ const country = (providers, what = "Prefer results for") => ({
121
+ name: "country",
122
+ providers,
123
+ schema: text(`${what} this country, as a two-letter ISO code such as GB.`, { pattern: "^[A-Za-z]{2}$" })
124
+ });
125
+ const language = (providers) => ({
126
+ name: "language",
127
+ providers,
128
+ schema: text("Prefer pages in this language, as an ISO 639-1 code such as en.")
129
+ });
130
+ const continueFrom = (providers) => ({
131
+ name: "continueFrom",
132
+ providers,
133
+ schema: text("The continuationId of an earlier result, to ask a follow-up in the same thread instead of starting over.")
134
+ });
135
+ const schemaField = (description, providers, required = false) => ({
136
+ name: "schema",
137
+ providers,
138
+ required,
7
139
  schema: {
8
- type: "string",
9
- format: "uri",
10
- description: "The page's full URL, including https://."
140
+ description,
141
+ type: "object"
11
142
  }
12
- };
13
- const domains = (verb) => ({
14
- type: "array",
15
- items: { type: "string" },
16
- description: `${verb} results from these domains, such as example.com.`
17
143
  });
18
- const str = { type: "string" };
19
- const strs = {
20
- type: "array",
21
- items: str
22
- };
23
- const citationList = {
24
- type: "array",
25
- items: {
26
- type: "object",
27
- properties: {
28
- url: str,
29
- title: str,
30
- excerpts: strs
31
- },
32
- required: ["url"]
33
- }
34
- };
35
- const fieldSources = {
36
- type: "array",
37
- description: "The sources the provider gave for each field.",
38
- items: {
39
- type: "object",
40
- properties: {
41
- field: str,
42
- citations: citationList,
43
- reasoning: str
44
- },
45
- required: ["field", "citations"]
46
- }
47
- };
48
- const pageShape = {
49
- type: "object",
50
- properties: {
51
- url: str,
52
- title: str,
53
- markdown: str,
54
- html: str,
55
- links: strs,
56
- images: strs,
57
- excerpts: strs
58
- },
59
- required: ["url"]
144
+ const CACHE = "Use a cached copy of the page if it is no older than this many seconds.";
145
+ /** Providers that can fetch fresh: 0 always does. */
146
+ const maxAge = (providers) => ({
147
+ name: "maxAge",
148
+ providers,
149
+ schema: whole(`${CACHE} 0 always fetches a fresh copy.`, 0)
150
+ });
151
+ /** Parallel never fetches fresh: it refuses a maximum age under 600 seconds. */
152
+ const maxAgeAtLeast600 = () => ({
153
+ name: "maxAge",
154
+ providers: ["parallel"],
155
+ schema: whole(`${CACHE} At least 600: Parallel cannot always fetch fresh.`, 600)
156
+ });
157
+ const monitorId = {
158
+ name: "id",
159
+ required: true,
160
+ schema: text("The monitor's id, from create_monitor or list_monitors.")
60
161
  };
61
- const object = (properties, required) => ({
62
- type: "object",
63
- properties,
64
- required
162
+ const condition = object({
163
+ description: text("The condition in plain words."),
164
+ name: text("A short name for the condition.")
165
+ }, ["name", "description"]);
166
+ const meta = object({
167
+ requestId: str,
168
+ usage: object({
169
+ costUsd: number(),
170
+ credits: number(),
171
+ units: keyed(number())
172
+ }),
173
+ warnings: texts()
174
+ }, [], "Request details from the provider: its request id, what it charged and any warnings.");
175
+ const citation = object({
176
+ excerpts: texts(),
177
+ title: str,
178
+ url: str
179
+ }, ["url"]);
180
+ const citations = list(citation);
181
+ const fieldSources = list(object({
182
+ citations,
183
+ confidence: anything("The provider's own confidence label or score."),
184
+ field: str,
185
+ reasoning: str
186
+ }, ["field", "citations"]), "The sources the provider gave for each field.");
187
+ const price = object({
188
+ amount: str,
189
+ currency: str,
190
+ formatted: str
65
191
  });
66
- const OUTPUTS = {
67
- search: object({
68
- results: {
69
- type: "array",
70
- items: {
71
- type: "object",
72
- properties: {
73
- url: str,
74
- title: str,
75
- snippet: str,
76
- content: str,
77
- publishedAt: str,
78
- score: { type: "number" }
79
- },
80
- required: ["url"]
81
- }
82
- },
83
- answer: str
84
- }, ["results"]),
85
- read: pageShape,
86
- extract: object({
87
- data: { description: "The values, in the shape of the schema." },
88
- fields: fieldSources
89
- }, ["data"]),
90
- product: object({
91
- title: str,
92
- brand: str,
93
- category: str,
192
+ const searchResult = object({
193
+ author: str,
194
+ content: str,
195
+ favicon: str,
196
+ image: str,
197
+ kind: str,
198
+ lastUpdatedAt: str,
199
+ place: object({
200
+ address: str,
201
+ latitude: number(),
202
+ longitude: number()
203
+ }),
204
+ price,
205
+ publishedAt: str,
206
+ rating: number(),
207
+ reviewCount: number(),
208
+ score: number(),
209
+ snippet: str,
210
+ title: str,
211
+ url: str
212
+ }, ["url"]);
213
+ const imageResult = object({
214
+ description: str,
215
+ height: number(),
216
+ sourceUrl: str,
217
+ thumbnailUrl: str,
218
+ title: str,
219
+ url: str,
220
+ width: number()
221
+ }, ["url"]);
222
+ const page = object({
223
+ author: str,
224
+ description: str,
225
+ excerpts: texts(),
226
+ favicon: str,
227
+ html: str,
228
+ image: str,
229
+ images: texts(),
230
+ language: str,
231
+ links: texts(),
232
+ markdown: str,
233
+ meta,
234
+ publishedAt: str,
235
+ rawHtml: str,
236
+ screenshot: str,
237
+ statusCode: number(),
238
+ summary: str,
239
+ title: str,
240
+ url: str
241
+ }, ["url"]);
242
+ const failedUrls = list(object({
243
+ error: str,
244
+ url: str
245
+ }, ["url", "error"]));
246
+ const productImages = list(object({
247
+ alt: str,
248
+ url: str
249
+ }, ["url"]));
250
+ const variant = object({
251
+ availability: str,
252
+ gtin: str,
253
+ id: str,
254
+ images: productImages,
255
+ inStock: flag(),
256
+ originalPrice: price,
257
+ price,
258
+ sku: str,
259
+ title: str,
260
+ values: keyed(str)
261
+ });
262
+ const runStatus = choice("completed for a finished run; partial for a run that stopped early (see stopReason) and still has output.", ["completed", "partial"]);
263
+ const entity = object({
264
+ citations,
265
+ data: anything("Values the run filled for the entity."),
266
+ description: str,
267
+ fields: fieldSources,
268
+ matched: flag("Whether the entity met every condition."),
269
+ name: str,
270
+ url: str
271
+ }, ["name"]);
272
+ const decisionAnswer = object({
273
+ choice: str,
274
+ confidence: anything(),
275
+ probabilities: keyed(number()),
276
+ probability: number(),
277
+ refusal: str
278
+ });
279
+ const monitorInfo = object({
280
+ createdAt: str,
281
+ id: str,
282
+ schedule: str,
283
+ status: str,
284
+ watch: str,
285
+ webhookUrl: str
286
+ }, ["id"]);
287
+ const SEARCH_OUTPUT = object({
288
+ answer: str,
289
+ images: list(imageResult),
290
+ meta,
291
+ results: list(searchResult)
292
+ }, ["results"]);
293
+ const IMAGES_OUTPUT = object({
294
+ meta,
295
+ results: list(imageResult)
296
+ }, ["results"]);
297
+ const PAGE_OUTPUT = page;
298
+ const PAGES_OUTPUT = object({
299
+ failed: failedUrls,
300
+ id: str,
301
+ meta,
302
+ pages: list(page)
303
+ }, ["pages", "failed"]);
304
+ const EXTRACT_OUTPUT = object({
305
+ data: anything("The values, in the shape of the schema."),
306
+ fields: fieldSources,
307
+ meta
308
+ }, ["data"]);
309
+ const PRODUCT_OUTPUT = object({
310
+ brand: str,
311
+ category: str,
312
+ description: str,
313
+ images: productImages,
314
+ meta,
315
+ title: str,
316
+ url: str,
317
+ variants: list(variant)
318
+ }, ["variants"]);
319
+ const MAP_OUTPUT = object({
320
+ links: list(object({
94
321
  description: str,
95
- url: str,
96
- variants: {
97
- type: "array",
98
- items: {
99
- type: "object",
100
- properties: {
101
- id: str,
102
- sku: str,
103
- title: str,
104
- values: {
105
- type: "object",
106
- additionalProperties: str
107
- },
108
- price: object({
109
- amount: str,
110
- currency: str
111
- }, []),
112
- inStock: { type: "boolean" },
113
- images: strs
114
- }
115
- }
116
- }
117
- }, ["variants"]),
118
- map: object({ links: {
119
- type: "array",
120
- items: object({
121
- url: str,
122
- title: str,
123
- description: str
124
- }, ["url"])
125
- } }, ["links"]),
126
- crawl: object({ pages: {
127
- type: "array",
128
- items: pageShape
129
- } }, ["pages"]),
130
- research: object({
322
+ title: str,
323
+ url: str
324
+ }, ["url"])),
325
+ meta
326
+ }, ["links"]);
327
+ const CRAWL_OUTPUT = object({
328
+ failed: failedUrls,
329
+ id: str,
330
+ meta,
331
+ pages: list(page),
332
+ robotsBlocked: texts("URLs the site's robots.txt kept the crawl from."),
333
+ total: number("Pages found to crawl, when the provider reports it.")
334
+ }, ["pages"]);
335
+ const ANSWER_OUTPUT = object({
336
+ answer: str,
337
+ citations,
338
+ continuationId: str,
339
+ fields: fieldSources,
340
+ meta,
341
+ output: anything("The answer in the shape of the schema, when one was given.")
342
+ }, ["answer", "citations"]);
343
+ const RESEARCH_OUTPUT = object({
344
+ continuationId: str,
345
+ fields: fieldSources,
346
+ id: str,
347
+ meta,
348
+ output: anything("Values in the shape of the schema, or the report text."),
349
+ retrieved: list(citation, "Every source the run looked at, when the provider lists them apart from what it cited."),
350
+ sources: list(citation, "The sources the output cites."),
351
+ status: runStatus,
352
+ stopReason: str
353
+ }, [
354
+ "id",
355
+ "status",
356
+ "output",
357
+ "sources"
358
+ ]);
359
+ const DISCOVER_OUTPUT = object({
360
+ entities: list(entity),
361
+ id: str,
362
+ meta,
363
+ status: runStatus,
364
+ stopReason: str
365
+ }, [
366
+ "id",
367
+ "status",
368
+ "entities"
369
+ ]);
370
+ const DECIDE_OUTPUT = object({
371
+ answers: keyed(decisionAnswer, "One answer per question, under the question's name."),
372
+ citations,
373
+ meta
374
+ }, ["answers", "citations"]);
375
+ const ACT_OUTPUT = object({
376
+ error: str,
377
+ exitCode: number(),
378
+ killed: flag(),
379
+ meta,
380
+ result: anything("The value the script returned."),
381
+ sessionId: str,
382
+ stderr: str,
383
+ stdout: str
384
+ }, ["stdout", "stderr"]);
385
+ const OPEN_BROWSER_OUTPUT = object({
386
+ cdpUrl: str,
387
+ expiresAt: str,
388
+ id: str,
389
+ liveViewUrl: str,
390
+ meta
391
+ }, ["id"]);
392
+ const CLOSE_BROWSER_OUTPUT = object({
393
+ closed: flag(),
394
+ id: str
395
+ }, ["closed", "id"]);
396
+ const PARSE_OUTPUT = object({
397
+ blocks: list(anything()),
398
+ markdown: str,
399
+ meta,
400
+ pageCount: whole("Pages in the file.", 0),
401
+ pages: list(object({
402
+ markdown: str,
403
+ pageNumber: whole("The physical page number, starting at 1.", 1)
404
+ }, ["pageNumber", "markdown"]))
405
+ }, ["markdown"]);
406
+ const MONITOR_OUTPUT = monitorInfo;
407
+ const MONITORS_OUTPUT = object({ monitors: list(monitorInfo) }, ["monitors"]);
408
+ const DELETE_MONITOR_OUTPUT = object({
409
+ deleted: flag(),
410
+ id: str
411
+ }, ["deleted", "id"]);
412
+ const MONITOR_EVENTS_OUTPUT = object({
413
+ events: list(object({
414
+ at: str,
415
+ citations,
131
416
  id: str,
132
- output: { description: "Values in the shape of the schema, or the report text." },
133
- sources: citationList,
134
- fields: fieldSources
417
+ output: anything(),
418
+ summary: str,
419
+ url: str
420
+ })),
421
+ next: str
422
+ }, ["events"]);
423
+ const USAGE_OUTPUT = object({
424
+ breakdown: keyed(number()),
425
+ limit: number(),
426
+ periodEnd: str,
427
+ remaining: number(),
428
+ used: number()
429
+ });
430
+ // src/tool-specs/answer.ts
431
+ const question = (description) => ({
432
+ name: "question",
433
+ required: true,
434
+ schema: text(description)
435
+ });
436
+ const decisionQuestion = { oneOf: [
437
+ object({
438
+ question: str,
439
+ type: choice("A yes or no question.", ["yesno"])
440
+ }, ["type", "question"]),
441
+ object({
442
+ choices: texts("The options, each a short label."),
443
+ question: str,
444
+ type: choice("A question with one answer from a list.", ["choice"])
135
445
  }, [
136
- "id",
137
- "output",
138
- "sources"
446
+ "type",
447
+ "question",
448
+ "choices"
139
449
  ]),
140
- act: object({
141
- stdout: str,
142
- stderr: str,
143
- result: {},
144
- exitCode: { type: "number" }
145
- }, ["stdout", "stderr"]),
146
- parse: object({
147
- markdown: str,
148
- pages: {
149
- type: "array",
150
- items: object({
151
- pageNumber: { type: "integer" },
152
- markdown: str
153
- }, ["pageNumber", "markdown"])
154
- },
155
- blocks: { type: "array" }
156
- }, ["markdown"])
157
- };
158
- const SPECS = [
450
+ object({
451
+ question: str,
452
+ scale: keyed(str, "Each score and what it means."),
453
+ type: choice("A question answered with a score on a rubric.", ["score"])
454
+ }, [
455
+ "type",
456
+ "question",
457
+ "scale"
458
+ ])
459
+ ] };
460
+ const ANSWER_SPECS = [
159
461
  {
160
- capability: "search",
161
- name: "search_web",
162
- title: "Search the web",
163
- description: "Search the web and return a ranked list of pages with their titles, URLs and matching snippets. Use when you need pages about a topic, product or fact and do not have a URL yet. Do not use to read a page you already have a URL for (use read_page), or for a question that needs several sources combined into an answer (use research_question).",
164
- subject: "query",
165
- readOnly: true,
462
+ capability: "answer",
463
+ description: "Answer a question in one call from the provider's own search, and return the answer with the sources it cites. Faster and cheaper than research_question. Use for a factual question with a short answer. Do not use for a question that needs many sources compared or a long report (use research_question), or to find pages (use search_web).",
464
+ destructive: false,
465
+ fields: [
466
+ question("The question, with any context the answer depends on."),
467
+ schemaField("A JSON Schema object for the answer, which then comes back as output.", [
468
+ "exa",
469
+ "parallel",
470
+ "perplexity"
471
+ ]),
472
+ continueFrom(["parallel", "perplexity"]),
473
+ limit("How many search results to base the answer on.", 20, ["tavily"]),
474
+ includeDomains("sources", ["tavily", "parallel"]),
475
+ excludeDomains("sources", ["tavily", "parallel"]),
476
+ publishedAfter(["tavily"]),
477
+ publishedBefore(["tavily"]),
478
+ ...recency([], ["tavily"]),
479
+ country([
480
+ "exa",
481
+ "tavily",
482
+ "brave"
483
+ ], "Localize the answer to"),
484
+ language(["tavily", "brave"]),
485
+ maxAge(["tavily"])
486
+ ],
166
487
  idempotent: true,
488
+ name: "answer_question",
489
+ output: ANSWER_OUTPUT,
490
+ positional: ["question"],
491
+ readOnly: true,
492
+ title: "Answer a question"
493
+ },
494
+ {
495
+ capability: "research",
496
+ description: "Research a question across the web and return an answer with its sources: a written report, or values matching a JSON Schema when one is given. Runs a job of many steps that can take minutes and costs more than a search. status is partial when the run stopped early (stopReason says why) but still has output. Use for questions that need several sources compared or combined. Do not use for a single lookup (use search_web or answer_question), or to read a page you have a URL for (use read_page).",
497
+ destructive: false,
498
+ fields: [
499
+ question("The question, with any context the answer depends on."),
500
+ schemaField("A JSON Schema object for the answer. Without one, the answer is a written report.", [
501
+ "exa",
502
+ "firecrawl",
503
+ "tavily",
504
+ "parallel",
505
+ "perplexity"
506
+ ]),
507
+ continueFrom([
508
+ "exa",
509
+ "firecrawl",
510
+ "parallel",
511
+ "perplexity"
512
+ ]),
513
+ includeDomains("sources", [
514
+ "tavily",
515
+ "parallel",
516
+ "perplexity"
517
+ ], "Tavily treats it as a preference, not a restriction."),
518
+ excludeDomains("sources", [
519
+ "tavily",
520
+ "parallel",
521
+ "perplexity"
522
+ ]),
523
+ publishedAfter(["parallel", "perplexity"]),
524
+ publishedBefore(["perplexity"]),
525
+ ...recency(["perplexity"], []),
526
+ country([
527
+ "firecrawl",
528
+ "parallel",
529
+ "perplexity"
530
+ ], "Search from"),
531
+ resume([
532
+ "exa",
533
+ "firecrawl",
534
+ "tavily",
535
+ "parallel",
536
+ "perplexity"
537
+ ])
538
+ ],
539
+ idempotent: false,
540
+ name: "research_question",
541
+ output: RESEARCH_OUTPUT,
542
+ positional: ["question"],
543
+ readOnly: true,
544
+ title: "Research a question"
545
+ },
546
+ {
547
+ capability: "discover",
548
+ description: "Find entities of one kind, such as companies, products or people, that meet every condition you list, and return each with its URL and description. Runs a job that can take minutes and costs more than a search. status is partial when the run stopped early (stopReason says why) but found entities. Use to build a list of things that match criteria. Do not use to answer a question (use answer_question or research_question) or to look up one named entity (use search_web).",
549
+ destructive: false,
167
550
  fields: [
168
551
  {
169
- name: "query",
552
+ name: "objective",
170
553
  required: true,
171
- schema: {
172
- type: "string",
173
- description: "What to search for."
174
- }
554
+ schema: text("What to find, in plain words, with any context that narrows it.")
175
555
  },
176
556
  {
177
- name: "limit",
178
- schema: {
179
- type: "integer",
180
- minimum: 1,
181
- maximum: 20,
182
- description: "How many results to return."
183
- }
557
+ name: "entityType",
558
+ required: true,
559
+ schema: text("The kind of entity to find, such as \"companies\" or \"people\".")
184
560
  },
185
561
  {
186
- name: "includeDomains",
187
- schema: domains("Only return")
562
+ name: "conditions",
563
+ required: true,
564
+ schema: list(condition, "Every entity found must meet all of these.", { minItems: 1 })
188
565
  },
566
+ limit("How many matching entities to find.", 1e3, ["parallel"]),
567
+ schemaField("A JSON Schema object of extra values to fill in for every matching entity, returned in its data.", ["parallel"]),
568
+ resume(["parallel"])
569
+ ],
570
+ idempotent: false,
571
+ name: "find_entities",
572
+ output: DISCOVER_OUTPUT,
573
+ positional: ["objective"],
574
+ readOnly: true,
575
+ title: "Find entities"
576
+ },
577
+ {
578
+ capability: "decide",
579
+ description: "Answer closed questions about a context: yes or no, one choice from a list, or a score on a rubric. Each answer carries probabilities, not only a verdict. Use to classify or judge a piece of text or data. Do not use for open questions (use answer_question).",
580
+ destructive: false,
581
+ fields: [
189
582
  {
190
- name: "excludeDomains",
191
- schema: domains("Leave out")
583
+ name: "context",
584
+ required: true,
585
+ schema: anything("What the questions are about: text, or any JSON value.")
192
586
  },
193
587
  {
194
- name: "publishedAfter",
195
- providers: [
196
- "exa",
197
- "tavily",
198
- "parallel",
199
- "perplexity"
200
- ],
201
- schema: {
202
- type: "string",
203
- format: "date",
204
- description: "Only pages published on or after this date, YYYY-MM-DD."
205
- }
588
+ name: "questions",
589
+ required: true,
590
+ schema: keyed(decisionQuestion, "The questions, each under a name of your choice: letters, digits, _ and -. The answers come back under the same names.")
591
+ },
592
+ country(["parallel"], "Search from")
593
+ ],
594
+ idempotent: true,
595
+ name: "make_decisions",
596
+ output: DECIDE_OUTPUT,
597
+ positional: ["context", "questions"],
598
+ readOnly: true,
599
+ title: "Make decisions"
600
+ }
601
+ ];
602
+ // src/tool-specs/browser.ts
603
+ const BROWSER_SPECS = [
604
+ {
605
+ capability: "act",
606
+ 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.",
607
+ destructive: true,
608
+ fields: [{
609
+ name: "code",
610
+ required: true,
611
+ schema: text("The script to run.")
612
+ }, {
613
+ name: "language",
614
+ providers: ["firecrawl"],
615
+ schema: choice("The script's language. Defaults to node.", [
616
+ "node",
617
+ "python",
618
+ "bash"
619
+ ])
620
+ }],
621
+ idempotent: false,
622
+ name: "run_browser_script",
623
+ output: ACT_OUTPUT,
624
+ positional: ["code"],
625
+ readOnly: false,
626
+ title: "Run a browser script"
627
+ },
628
+ {
629
+ capability: "browser",
630
+ description: "Open a remote browser session and return its Chrome DevTools Protocol (CDP) URL, a live-view URL and when it expires, for driving it yourself with Playwright or Puppeteer. The session bills until it expires or close_browser is called, and its effects on the sites it visits are real. Use only when you need a browser you control. Do not use to read pages or run a one-off script (use run_browser_script).",
631
+ destructive: true,
632
+ fields: [
633
+ {
634
+ name: "ttl",
635
+ providers: ["firecrawl"],
636
+ schema: whole("Seconds the session may live, 30 to 3600. It closes by itself after that.", 30, 3600)
206
637
  },
207
638
  {
208
- name: "publishedBefore",
209
- providers: [
210
- "exa",
211
- "tavily",
212
- "perplexity"
213
- ],
639
+ name: "ttl",
640
+ providers: ["browserbase"],
641
+ schema: whole("Seconds the session may live, 60 to 21600. It closes by itself after that.", 60, 21600)
642
+ },
643
+ country(["firecrawl"], "Browse from")
644
+ ],
645
+ idempotent: false,
646
+ method: "open",
647
+ name: "open_browser",
648
+ output: OPEN_BROWSER_OUTPUT,
649
+ positional: [],
650
+ readOnly: false,
651
+ title: "Open a browser"
652
+ },
653
+ {
654
+ capability: "browser",
655
+ confirmAs: "closed",
656
+ description: "Close a remote browser session opened with open_browser, so it stops billing. Anything still running in the session ends. Use when you are done with a session. Do not use on a session you did not open.",
657
+ destructive: true,
658
+ fields: [{
659
+ name: "id",
660
+ required: true,
661
+ schema: text("The session's id, from open_browser.")
662
+ }],
663
+ idempotent: true,
664
+ method: "close",
665
+ name: "close_browser",
666
+ output: CLOSE_BROWSER_OUTPUT,
667
+ positional: ["id"],
668
+ readOnly: false,
669
+ title: "Close a browser"
670
+ },
671
+ {
672
+ capability: "parse",
673
+ description: "Convert a document file (PDF, DOCX, XLSX, PPTX, HTML or CSV) to Markdown. Use when you have the file's bytes. Do not use for a document at a public URL (use read_page).",
674
+ destructive: false,
675
+ fields: [
676
+ {
677
+ name: "name",
678
+ required: true,
679
+ schema: text("The file name with its extension, such as spec-sheet.pdf. The extension tells the provider the type.")
680
+ },
681
+ {
682
+ name: "contentBase64",
683
+ required: true,
684
+ schema: text("The file's bytes, base64-encoded.")
685
+ },
686
+ {
687
+ name: "pages",
688
+ providers: ["firecrawl"],
689
+ schema: flag("Also return the Markdown of each page separately.")
690
+ }
691
+ ],
692
+ idempotent: true,
693
+ name: "parse_document",
694
+ output: PARSE_OUTPUT,
695
+ positional: ["name", "contentBase64"],
696
+ readOnly: true,
697
+ title: "Convert a document to Markdown"
698
+ }
699
+ ];
700
+ // src/tool-specs/monitor.ts
701
+ const every = {
702
+ properties: { every: text("How often: \"hour\", \"day\", \"week\", or a whole number of hours or days such as \"6h\" or \"3d\".", { pattern: "^(hour|day|week|[1-9][0-9]*h|[1-9][0-9]*d)$" }) },
703
+ required: ["every"],
704
+ type: "object"
705
+ };
706
+ const cron = {
707
+ properties: { cron: text("A cron expression with five fields, such as \"0 9 * * 1\" for Mondays at 09:00.") },
708
+ required: ["cron"],
709
+ type: "object"
710
+ };
711
+ const closed = (schema) => ({
712
+ ...schema,
713
+ additionalProperties: false
714
+ });
715
+ const SCHEDULE_NOTE = "How often the monitor checks. Give exactly one of every or cron.";
716
+ const schedules = [{
717
+ name: "schedule",
718
+ providers: ["exa", "parallel"],
719
+ requiredFor: ["parallel"],
720
+ schema: {
721
+ ...closed(every),
722
+ description: `${SCHEDULE_NOTE} This provider takes every only, from one hour (Parallel: up to 30 days); it has no cron.`
723
+ }
724
+ }, {
725
+ name: "schedule",
726
+ providers: ["firecrawl"],
727
+ required: true,
728
+ schema: {
729
+ description: `${SCHEDULE_NOTE} Cron checks must be at least 5 minutes apart.`,
730
+ oneOf: [closed(every), closed(cron)]
731
+ }
732
+ }];
733
+ const DOMAIN_NOTE = "Firecrawl takes domain lists only for a monitor that searches: give a query and no urls.";
734
+ const MONITOR_PROVIDERS = [
735
+ "exa",
736
+ "firecrawl",
737
+ "parallel"
738
+ ];
739
+ const cursor = {
740
+ name: "cursor",
741
+ providers: MONITOR_PROVIDERS,
742
+ schema: text("The next value from the previous page of events.")
743
+ };
744
+ const MONITOR_SPECS = [
745
+ {
746
+ capability: "monitor",
747
+ description: "Create a monitor that checks the web on a schedule and records what is new or changed, delivering it to a webhook and to list_monitor_events. A monitor keeps running, and billing, until delete_monitor removes it. Use when the user wants ongoing watching. Do not use for a one-time check (use search_web or read_page).",
748
+ destructive: false,
749
+ fields: [
750
+ {
751
+ name: "query",
752
+ providers: MONITOR_PROVIDERS,
753
+ requiredFor: ["exa", "parallel"],
754
+ schema: text("What to watch for, in plain words. With firecrawl and urls, what counts as a meaningful change; without urls, also the search it runs.")
755
+ },
756
+ {
757
+ name: "urls",
758
+ providers: ["firecrawl"],
214
759
  schema: {
215
- type: "string",
216
- format: "date",
217
- description: "Only pages published before this date, YYYY-MM-DD."
760
+ description: "Pages to watch. Give urls or a query, or both. Not together with domain lists.",
761
+ items: url("A page's full URL, including https://."),
762
+ minItems: 1,
763
+ type: "array"
218
764
  }
219
765
  },
766
+ ...schedules,
767
+ {
768
+ name: "webhookUrl",
769
+ providers: MONITOR_PROVIDERS,
770
+ requiredFor: ["exa"],
771
+ schema: url("An https address the provider calls with each event.")
772
+ },
773
+ {
774
+ name: "name",
775
+ providers: ["exa", "firecrawl"],
776
+ schema: text("A name for the monitor.")
777
+ },
778
+ schemaField("A JSON Schema object; each event comes back in this shape as output.", ["parallel"]),
779
+ limit("Results to check per run.", 100, ["exa"]),
780
+ includeDomains("results", MONITOR_PROVIDERS, DOMAIN_NOTE),
781
+ excludeDomains("results", MONITOR_PROVIDERS, DOMAIN_NOTE),
782
+ publishedAfter(["parallel"]),
783
+ country(["parallel"], "Search from"),
220
784
  {
221
785
  name: "content",
222
- providers: [
223
- "exa",
224
- "firecrawl",
225
- "tavily"
226
- ],
227
- schema: {
228
- type: "boolean",
229
- description: "Include each result's page text. Slower and longer; leave out to get snippets only."
230
- }
786
+ providers: ["exa"],
787
+ schema: flag("Include each result's page text with the event.")
231
788
  }
232
- ]
789
+ ],
790
+ idempotent: false,
791
+ method: "create",
792
+ name: "create_monitor",
793
+ output: MONITOR_OUTPUT,
794
+ positional: [],
795
+ readOnly: false,
796
+ title: "Create a monitor"
233
797
  },
234
798
  {
235
- capability: "read",
236
- name: "read_page",
237
- title: "Read a page",
238
- description: "Read one web page and return its title and its text as Markdown. Use when you have a URL and need what the page says. Do not use to pull specific values into a structure (use extract_values), or to read many pages of one site (use crawl_site).",
239
- subject: "url",
799
+ capability: "monitor",
800
+ description: "Get one monitor's settings and status. Use to check a monitor you created. Do not use to read what it found (use list_monitor_events).",
801
+ destructive: false,
802
+ fields: [monitorId],
803
+ idempotent: true,
804
+ method: "get",
805
+ name: "get_monitor",
806
+ output: MONITOR_OUTPUT,
807
+ positional: ["id"],
240
808
  readOnly: true,
809
+ title: "Get a monitor"
810
+ },
811
+ {
812
+ capability: "monitor",
813
+ description: "List every monitor on the account with its status. Use to find a monitor's id or to see what is still running and billing.",
814
+ destructive: false,
815
+ fields: [],
241
816
  idempotent: true,
242
- fields: [url]
817
+ method: "list",
818
+ name: "list_monitors",
819
+ output: MONITORS_OUTPUT,
820
+ positional: [],
821
+ readOnly: true,
822
+ title: "List monitors",
823
+ wrapAs: "monitors"
243
824
  },
244
825
  {
245
- capability: "extract",
246
- name: "extract_values",
247
- title: "Extract values from a page",
248
- description: "Read one web page and return the values a JSON Schema asks for, such as dimensions, materials or prices. Use when you have a URL and know which fields you need. Do not use when you need the whole page text (use read_page), or when the values are spread across several sites (use research_question).",
249
- subject: "url",
826
+ capability: "monitor",
827
+ confirmAs: "deleted",
828
+ description: "Delete a monitor so it stops running and billing. Its history may go with it, and this cannot be undone. Use when the watching is no longer wanted. Do not use to pause a monitor.",
829
+ destructive: true,
830
+ fields: [monitorId],
831
+ idempotent: true,
832
+ method: "delete",
833
+ name: "delete_monitor",
834
+ output: DELETE_MONITOR_OUTPUT,
835
+ positional: ["id"],
836
+ readOnly: false,
837
+ title: "Delete a monitor"
838
+ },
839
+ {
840
+ capability: "monitor",
841
+ description: "List what a monitor found, one event per check or per change, newest first. Use to read a monitor's results. Pass next back as cursor for the following page.",
842
+ destructive: false,
843
+ fields: [
844
+ monitorId,
845
+ cursor,
846
+ limit("How many events to return.", 100, ["exa", "parallel"])
847
+ ],
848
+ idempotent: true,
849
+ method: "events",
850
+ name: "list_monitor_events",
851
+ output: MONITOR_EVENTS_OUTPUT,
852
+ positional: ["id"],
250
853
  readOnly: true,
854
+ title: "List a monitor's events"
855
+ },
856
+ {
857
+ capability: "usage",
858
+ description: "Return the account's credits used and remaining in the current period, as the provider reports them. Use before a large job, or to explain a quota error. Changes nothing.",
859
+ destructive: false,
860
+ fields: [],
861
+ idempotent: true,
862
+ name: "check_usage",
863
+ output: USAGE_OUTPUT,
864
+ positional: [],
865
+ readOnly: true,
866
+ title: "Check usage"
867
+ }
868
+ ];
869
+ // src/tool-specs/read.ts
870
+ const query = {
871
+ name: "query",
872
+ providers: [
873
+ "exa",
874
+ "firecrawl",
875
+ "tavily",
876
+ "parallel"
877
+ ],
878
+ schema: text("Also return the passages of each page that answer this, as excerpts.")
879
+ };
880
+ const READ_SPECS = [
881
+ {
882
+ capability: "read",
883
+ description: "Read one web page and return its title and its text as Markdown. Use when you have a URL and need what the page says. Do not use to pull specific values into a structure (use extract_values), to read several pages (use read_pages), or to read many pages of one site (use crawl_site).",
884
+ destructive: false,
885
+ fields: [
886
+ urlField(PAGE_URL),
887
+ query,
888
+ maxAge(["exa", "firecrawl"]),
889
+ maxAgeAtLeast600(),
890
+ country(["browserbase"], "Fetch the page through a proxy in")
891
+ ],
251
892
  idempotent: true,
893
+ name: "read_page",
894
+ output: PAGE_OUTPUT,
895
+ positional: ["url"],
896
+ readOnly: true,
897
+ title: "Read a page"
898
+ },
899
+ {
900
+ capability: "readMany",
901
+ description: "Read several web pages in one call and return each page's title and text as Markdown. URLs that could not be read come back in failed; the call still succeeds. Use when you have a list of URLs. Do not use for one page (use read_page) or to follow links across a site (use crawl_site).",
902
+ destructive: false,
252
903
  fields: [
253
- url,
254
904
  {
255
- name: "schema",
905
+ name: "urls",
256
906
  required: true,
257
- schema: {
258
- type: "object",
259
- description: "A JSON Schema object describing the values to return, such as {\"type\":\"object\",\"properties\":{\"width\":{\"type\":\"string\"}}}."
260
- }
907
+ schema: list(url("A page's full URL, including https://."), "The pages' full URLs, including https://.", { minItems: 1 })
261
908
  },
909
+ query,
910
+ maxAge(["exa", "firecrawl"]),
911
+ maxAgeAtLeast600(),
912
+ resume(["firecrawl"])
913
+ ],
914
+ idempotent: true,
915
+ name: "read_pages",
916
+ output: PAGES_OUTPUT,
917
+ positional: ["urls"],
918
+ readOnly: true,
919
+ title: "Read several pages"
920
+ },
921
+ {
922
+ capability: "extract",
923
+ description: "Read one web page and return the values a JSON Schema asks for, such as dimensions, materials or prices. Use when you have a URL and know which fields you need. Do not use when you need the whole page text (use read_page), or when the values are spread across several sites (use research_question).",
924
+ destructive: false,
925
+ fields: [
926
+ urlField(PAGE_URL),
927
+ schemaField("A JSON Schema object describing the values to return, such as {\"type\":\"object\",\"properties\":{\"width\":{\"type\":\"string\"}}}.", void 0, true),
262
928
  {
263
929
  name: "prompt",
264
- schema: {
265
- type: "string",
266
- description: "What to extract, in plain words, when the schema alone is not enough."
267
- }
930
+ schema: text("What to extract, in plain words, when the schema alone is not enough.")
268
931
  },
269
- {
270
- name: "resume",
271
- providers: ["parallel"],
272
- schema: {
273
- type: "string",
274
- description: RESUME_DESCRIPTION
275
- }
276
- }
277
- ]
932
+ maxAge(["exa", "firecrawl"]),
933
+ country(["parallel"], "Search from"),
934
+ resume(["parallel"])
935
+ ],
936
+ idempotent: true,
937
+ name: "extract_values",
938
+ output: EXTRACT_OUTPUT,
939
+ positional: ["url"],
940
+ readOnly: true,
941
+ title: "Extract values from a page"
278
942
  },
279
943
  {
280
944
  capability: "product",
281
- name: "read_product",
282
- title: "Read a product page",
283
945
  description: "Read a product page's structured data and return the product with its variants: SKUs, option values such as color or size, prices, stock and images. No model reads the page, so it returns only what the page publishes. Use on one product page. Do not use on category or search pages, or for details the page's structured data does not carry (use extract_values).",
284
- subject: "url",
285
- readOnly: true,
946
+ destructive: false,
947
+ fields: [urlField(PAGE_URL), maxAge(["firecrawl"])],
286
948
  idempotent: true,
287
- fields: [url]
949
+ name: "read_product",
950
+ output: PRODUCT_OUTPUT,
951
+ positional: ["url"],
952
+ readOnly: true,
953
+ title: "Read a product page"
288
954
  },
289
955
  {
290
956
  capability: "map",
291
- name: "map_site",
292
- title: "List a site's pages",
293
957
  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).",
294
- subject: "url",
295
- readOnly: true,
958
+ destructive: false,
959
+ fields: [urlField("The site's address, such as https://example.com."), limit("The most URLs to return.", 5e3, ["firecrawl", "tavily"])],
296
960
  idempotent: true,
297
- fields: [{
298
- ...url,
299
- schema: {
300
- ...url.schema,
301
- description: "The site's address, such as https://example.com."
302
- }
303
- }, {
304
- name: "limit",
305
- schema: {
306
- type: "integer",
307
- minimum: 1,
308
- maximum: 5e3,
309
- description: "The most URLs to return."
310
- }
311
- }]
961
+ name: "map_site",
962
+ output: MAP_OUTPUT,
963
+ positional: ["url"],
964
+ readOnly: true,
965
+ title: "List a site's pages"
312
966
  },
313
967
  {
314
968
  capability: "crawl",
315
- name: "crawl_site",
316
- title: "Crawl a site",
317
969
  description: "Start at a URL, follow links within the site and return the text of every page reached, up to limit. Slower and costlier than reading single pages. Use when you need the content of many pages from one site. Do not use for one page (use read_page), or when you only need the list of URLs (use map_site).",
318
- subject: "url",
319
- readOnly: true,
320
- idempotent: false,
970
+ destructive: false,
321
971
  fields: [
322
- url,
323
- {
324
- name: "limit",
325
- schema: {
326
- type: "integer",
327
- minimum: 1,
328
- maximum: 100,
329
- description: "The most pages to read."
330
- }
331
- },
332
- {
333
- name: "resume",
334
- providers: ["firecrawl"],
335
- schema: {
336
- type: "string",
337
- description: RESUME_DESCRIPTION
338
- }
339
- }
340
- ]
341
- },
342
- {
343
- capability: "research",
344
- name: "research_question",
345
- title: "Research a question",
346
- description: "Research a question across the web and return an answer with its sources: a written report, or values matching a JSON Schema when one is given. Runs a job of many steps that can take minutes and costs more than a search. Use for questions that need several sources compared or combined. Do not use for a single lookup (use search_web), or to read a page you have a URL for (use read_page).",
347
- subject: "question",
348
- readOnly: true,
972
+ urlField("The page to start from, including https://."),
973
+ limit("The most pages to read.", 100, ["firecrawl", "tavily"]),
974
+ resume(["firecrawl"])
975
+ ],
349
976
  idempotent: false,
977
+ name: "crawl_site",
978
+ output: CRAWL_OUTPUT,
979
+ positional: ["url"],
980
+ readOnly: true,
981
+ title: "Crawl a site"
982
+ }
983
+ ];
984
+ // src/tool-specs/index.ts
985
+ /**
986
+ * What each agent tool is called, what it says about itself, which inputs
987
+ * each provider accepts and what it returns. `toolsFor` in tools.ts turns
988
+ * these into tools, in this order.
989
+ */
990
+ const SPECS = [
991
+ ...[{
992
+ capability: "search",
993
+ description: "Search the web and return a ranked list of pages with their titles, URLs and matching snippets. Use when you need pages about a topic, product or fact and do not have a URL yet. Do not use to read a page you already have a URL for (use read_page), for pictures (use search_images), or for a question that needs several sources combined into an answer (use research_question).",
994
+ destructive: false,
350
995
  fields: [
351
996
  {
352
- name: "question",
997
+ name: "query",
353
998
  required: true,
354
- schema: {
355
- type: "string",
356
- description: "The question, with any context the answer depends on."
357
- }
999
+ schema: text("What to search for.")
358
1000
  },
1001
+ limit("How many results to return.", 20, [
1002
+ "exa",
1003
+ "firecrawl",
1004
+ "tavily",
1005
+ "parallel",
1006
+ "perplexity",
1007
+ "brave",
1008
+ "browserbase"
1009
+ ]),
1010
+ includeDomains("results", [
1011
+ "exa",
1012
+ "firecrawl",
1013
+ "tavily",
1014
+ "parallel",
1015
+ "perplexity"
1016
+ ]),
1017
+ excludeDomains("results", [
1018
+ "exa",
1019
+ "firecrawl",
1020
+ "tavily",
1021
+ "parallel",
1022
+ "perplexity"
1023
+ ]),
1024
+ publishedAfter([
1025
+ "exa",
1026
+ "firecrawl",
1027
+ "tavily",
1028
+ "parallel",
1029
+ "perplexity",
1030
+ "brave",
1031
+ "serpapi"
1032
+ ]),
1033
+ publishedBefore([
1034
+ "exa",
1035
+ "firecrawl",
1036
+ "tavily",
1037
+ "perplexity",
1038
+ "brave",
1039
+ "serpapi"
1040
+ ]),
1041
+ ...recency([
1042
+ "firecrawl",
1043
+ "perplexity",
1044
+ "serpapi"
1045
+ ], ["tavily", "brave"]),
1046
+ country([
1047
+ "exa",
1048
+ "firecrawl",
1049
+ "tavily",
1050
+ "parallel",
1051
+ "perplexity",
1052
+ "brave",
1053
+ "serpapi"
1054
+ ], "Localize results to"),
1055
+ language([
1056
+ "tavily",
1057
+ "perplexity",
1058
+ "brave",
1059
+ "serpapi"
1060
+ ]),
359
1061
  {
360
- name: "schema",
361
- schema: {
362
- type: "object",
363
- description: "A JSON Schema object for the answer. Without one, the answer is a written report."
364
- }
365
- },
366
- {
367
- name: "resume",
1062
+ name: "content",
368
1063
  providers: [
369
1064
  "exa",
370
1065
  "firecrawl",
371
1066
  "tavily",
372
- "parallel"
373
- ],
374
- schema: {
375
- type: "string",
376
- description: RESUME_DESCRIPTION
377
- }
378
- }
379
- ]
380
- },
381
- {
382
- capability: "act",
383
- name: "run_browser_script",
384
- title: "Run a browser script",
385
- 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.",
386
- subject: "code",
387
- readOnly: false,
388
- idempotent: false,
389
- fields: [{
390
- name: "code",
391
- required: true,
392
- schema: {
393
- type: "string",
394
- description: "The script to run."
395
- }
396
- }, {
397
- name: "language",
398
- providers: ["firecrawl"],
399
- schema: {
400
- type: "string",
401
- enum: [
402
- "node",
403
- "python",
404
- "bash"
1067
+ "brave"
405
1068
  ],
406
- description: "The script's language. Defaults to node."
407
- }
408
- }]
409
- },
410
- {
411
- capability: "parse",
412
- name: "parse_document",
413
- title: "Convert a document to Markdown",
414
- description: "Convert a document file (PDF, DOCX, XLSX, PPTX, HTML or CSV) to Markdown. Use when you have the file's bytes. Do not use for a document at a public URL (use read_page).",
415
- subject: "document",
416
- readOnly: true,
1069
+ schema: flag("Include each result's page text. Slower and longer; leave out to get snippets only.")
1070
+ },
1071
+ maxAge(["exa", "tavily"]),
1072
+ maxAgeAtLeast600()
1073
+ ],
417
1074
  idempotent: true,
1075
+ name: "search_web",
1076
+ output: SEARCH_OUTPUT,
1077
+ positional: ["query"],
1078
+ readOnly: true,
1079
+ title: "Search the web"
1080
+ }, {
1081
+ capability: "images",
1082
+ description: "Search for images and return each image's URL, thumbnail, the page it appears on, its title and its size. Use when you need pictures of a subject. Do not use to find pages (use search_web) or to learn what is in an image.",
1083
+ destructive: false,
418
1084
  fields: [
419
1085
  {
420
- name: "name",
421
- required: true,
422
- schema: {
423
- type: "string",
424
- description: "The file name with its extension, such as spec-sheet.pdf. The extension tells the provider the type."
425
- }
426
- },
427
- {
428
- name: "contentBase64",
1086
+ name: "query",
429
1087
  required: true,
430
- schema: {
431
- type: "string",
432
- description: "The file's bytes, base64-encoded."
433
- }
1088
+ schema: text("What the images should show.")
434
1089
  },
435
- {
436
- name: "pages",
437
- providers: ["firecrawl"],
438
- schema: {
439
- type: "boolean",
440
- description: "Also return the Markdown of each page separately."
441
- }
442
- }
443
- ]
444
- }
1090
+ limit("How many images to return.", 20, [
1091
+ "firecrawl",
1092
+ "parallel",
1093
+ "brave"
1094
+ ]),
1095
+ includeDomains("images", ["tavily"]),
1096
+ excludeDomains("images", ["tavily"]),
1097
+ publishedAfter(["serpapi"]),
1098
+ publishedBefore(["serpapi"]),
1099
+ ...recency(["serpapi"], []),
1100
+ country([
1101
+ "firecrawl",
1102
+ "parallel",
1103
+ "brave",
1104
+ "serpapi"
1105
+ ], "Localize results to"),
1106
+ language(["brave", "serpapi"])
1107
+ ],
1108
+ idempotent: true,
1109
+ name: "search_images",
1110
+ output: IMAGES_OUTPUT,
1111
+ positional: ["query"],
1112
+ readOnly: true,
1113
+ title: "Search for images"
1114
+ }],
1115
+ ...READ_SPECS,
1116
+ ...ANSWER_SPECS,
1117
+ ...BROWSER_SPECS,
1118
+ ...MONITOR_SPECS
1119
+ ];
1120
+ // src/tools/json.ts
1121
+ const isText = (value) => typeof value === "string";
1122
+ const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
1123
+ const isFlag = (value) => typeof value === "boolean";
1124
+ const isList = (value) => Array.isArray(value);
1125
+ /** Narrows anything, such as a value a transport hands over, to a JSON object. */
1126
+ const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1127
+ // src/tools/dispatch.ts
1128
+ const isOperation = (value) => typeof value === "function";
1129
+ const isGroup = (value) => isJsonObject(value);
1130
+ /** The method behind a spec, or undefined when the instance lacks it. */
1131
+ const operationFor = (web, spec) => {
1132
+ const entry = web[spec.capability];
1133
+ if (spec.method === void 0) return isOperation(entry) ? entry : void 0;
1134
+ return isGroup(entry) ? entry[spec.method] : void 0;
1135
+ };
1136
+ const documentFrom = (name, content) => {
1137
+ if (!isText(name) || !isText(content)) throw new FieldworkError("InvalidRequest", "parse_document needs name and contentBase64");
1138
+ return {
1139
+ data: new Uint8Array(Buffer.from(content, "base64")),
1140
+ name
1141
+ };
1142
+ };
1143
+ /** The arguments for the spec's method, from validated input and the call settings. */
1144
+ const argumentsFor = (spec, values, call) => {
1145
+ const options = {
1146
+ ...Object.fromEntries(Object.entries(values).filter(([key]) => !spec.positional.includes(key))),
1147
+ ...call
1148
+ };
1149
+ const positional = spec.positional.map((name) => values[name]);
1150
+ if (spec.capability === "parse") return [documentFrom(positional[0], positional[1]), options];
1151
+ return [...positional, options];
1152
+ };
1153
+ // src/tools/model.ts
1154
+ /** Text of this length or less, such as titles, URLs and snippets, is never cut. */
1155
+ const SHORT_TEXT = 500;
1156
+ /**
1157
+ * Keys whose contents belong to the caller, the script or the extraction, not
1158
+ * to Fieldwork: a key called `raw` inside them is a value, so it stays.
1159
+ */
1160
+ const VERBATIM = /* @__PURE__ */ new Set([
1161
+ "answers",
1162
+ "breakdown",
1163
+ "data",
1164
+ "output",
1165
+ "result",
1166
+ "values"
1167
+ ]);
1168
+ /**
1169
+ * The order an object's fields spend the shared budget in: the readable
1170
+ * answer or page text first, other renderings of the same page last, and
1171
+ * everything else between, as it appears. The result keeps its own key order.
1172
+ */
1173
+ const SPEND_FIRST = [
1174
+ "answer",
1175
+ "output",
1176
+ "markdown",
1177
+ "content",
1178
+ "text",
1179
+ "summary"
445
1180
  ];
1181
+ const SPEND_LAST = ["html", "rawHtml"];
1182
+ const rank = (key) => {
1183
+ if (SPEND_FIRST.includes(key)) return SPEND_FIRST.indexOf(key);
1184
+ return SPEND_LAST.includes(key) ? SPEND_FIRST.length + 1 + SPEND_LAST.indexOf(key) : SPEND_FIRST.length;
1185
+ };
1186
+ const cut = (value, budget) => {
1187
+ if (value.length <= SHORT_TEXT) return value;
1188
+ const kept = Math.min(value.length, budget.remaining);
1189
+ budget.remaining -= kept;
1190
+ return kept === value.length ? value : `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
1191
+ };
1192
+ const shape = (value, verbatim, budget) => {
1193
+ if (isText(value)) return cut(value, budget);
1194
+ if (isList(value)) return value.map((item) => shape(item, verbatim, budget) ?? null);
1195
+ if (!isJsonObject(value)) return value;
1196
+ const entries = Object.entries(value).filter(([key]) => verbatim || key !== "raw");
1197
+ const shaped = /* @__PURE__ */ new Map();
1198
+ for (const [key, item] of entries.toSorted(([a], [b]) => rank(a) - rank(b))) shaped.set(key, shape(item, verbatim || VERBATIM.has(key), budget));
1199
+ return Object.fromEntries(entries.map(([key]) => [key, shaped.get(key)]));
1200
+ };
1201
+ /**
1202
+ * A result as a model should see it: the provider's `raw` response dropped at
1203
+ * every depth except inside extracted values, and long text cut to one budget
1204
+ * shared across the result. Within each object the answer or page text is
1205
+ * served first and alternate renderings such as HTML last.
1206
+ */
1207
+ const forModel = (result, budget) => {
1208
+ const shaped = shape(result, false, { remaining: budget });
1209
+ return isJsonObject(shaped) ? shaped : {};
1210
+ };
1211
+ // src/tools/validate.ts
1212
+ /**
1213
+ * Checks a value against the schema subset the tools use and says what is
1214
+ * wrong in words a model can act on, or returns nothing when it is fine.
1215
+ */
1216
+ const DATE = /^\d{4}-\d{2}-\d{2}$/u;
1217
+ const textProblem = (schema, value, name) => {
1218
+ if (value === "") return `${name} must not be empty`;
1219
+ if (schema.enum !== void 0 && !schema.enum.includes(value)) return `${name} must be one of ${schema.enum.join(", ")}`;
1220
+ if (schema.format === "uri" && !URL.canParse(value)) return `${name} must be a full URL, including https://`;
1221
+ if (schema.format === "date" && !DATE.test(value)) return `${name} must be a date as YYYY-MM-DD`;
1222
+ if (schema.pattern !== void 0 && !new RegExp(schema.pattern, "u").test(value)) return `${name} must match the pattern ${schema.pattern}`;
1223
+ };
1224
+ const range = (schema) => {
1225
+ const { maximum, minimum } = schema;
1226
+ if (minimum !== void 0 && maximum !== void 0) return ` from ${minimum} to ${maximum}`;
1227
+ if (minimum !== void 0) return ` of at least ${minimum}`;
1228
+ return maximum === void 0 ? "" : ` of at most ${maximum}`;
1229
+ };
1230
+ const numberMessage = (schema, name) => `${name} must be a ${schema.type === "integer" ? "whole number" : "number"}${range(schema)}`;
1231
+ const numberProblem = (schema, value, name) => {
1232
+ const outside = schema.minimum !== void 0 && value < schema.minimum || schema.maximum !== void 0 && value > schema.maximum;
1233
+ return schema.type === "integer" && !Number.isInteger(value) || outside ? numberMessage(schema, name) : void 0;
1234
+ };
1235
+ const listProblem = (schema, value, name, check) => {
1236
+ if (schema.minItems !== void 0 && value.length < schema.minItems) return `${name} needs at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`;
1237
+ const { items } = schema;
1238
+ if (items === void 0) return;
1239
+ for (const [index, item] of value.entries()) {
1240
+ const found = check(items, item, `${name}[${index}]`);
1241
+ if (found !== void 0) return found;
1242
+ }
1243
+ };
1244
+ const objectProblem = (schema, value, name, check) => {
1245
+ const properties = schema.properties ?? {};
1246
+ const missing = (schema.required ?? []).find((key) => value[key] === void 0);
1247
+ if (missing !== void 0) return `${name} needs ${missing}`;
1248
+ for (const [key, item] of Object.entries(value)) {
1249
+ if (item === void 0) continue;
1250
+ const own = properties[key];
1251
+ const { additionalProperties: extra } = schema;
1252
+ if (own === void 0 && extra === false) return `${name} has ${key}, which is not allowed; the keys are ${Object.keys(properties).join(", ")}`;
1253
+ const against = own ?? (extra === true || extra === false ? void 0 : extra);
1254
+ const found = against === void 0 ? void 0 : check(against, item, `${name}.${key}`);
1255
+ if (found !== void 0) return found;
1256
+ }
1257
+ };
1258
+ const typeProblem = (schema, value, name, check) => {
1259
+ const { type } = schema;
1260
+ if (type === "string") return isText(value) ? textProblem(schema, value, name) : `${name} must be a string`;
1261
+ if (type === "integer" || type === "number") return isNumber(value) ? numberProblem(schema, value, name) : numberMessage(schema, name);
1262
+ if (type === "boolean") return isFlag(value) ? void 0 : `${name} must be true or false`;
1263
+ if (type === "array") return isList(value) ? listProblem(schema, value, name, check) : `${name} must be a list`;
1264
+ if (type === "object") return isJsonObject(value) ? objectProblem(schema, value, name, check) : `${name} must be a JSON object`;
1265
+ };
1266
+ /** What is wrong with `value` as `name`, in full ("limit must be a whole number from 1 to 20"), or nothing. */
1267
+ const problem = (schema, value, name) => {
1268
+ if (schema.oneOf !== void 0) {
1269
+ const problems = schema.oneOf.map((option) => problem(option, value, name));
1270
+ return problems.includes(void 0) ? void 0 : `${name} matches none of the allowed forms: ${problems.join("; ")}`;
1271
+ }
1272
+ return typeProblem(schema, value, name, problem);
1273
+ };
446
1274
  // src/tools.ts
447
- /** Makes one tool per capability the instance supports. */
448
- function toolsFor(web, options = {}) {
449
- const wanted = new Set(options.capabilities ?? SPECS.map((spec) => spec.capability).filter((c) => c !== "act"));
450
- const budget = options.maxCharacters ?? 2e4;
451
- const methods = web;
452
- return SPECS.flatMap((spec) => {
453
- const provider = web.providerFor(spec.capability);
454
- if (!wanted.has(spec.capability) || provider === void 0) return [];
455
- const fields = spec.fields.filter((field) => field.providers === void 0 || field.providers.includes(provider));
456
- return [{
457
- name: spec.name,
458
- capability: spec.capability,
459
- provider,
460
- description: spec.description,
461
- inputSchema: {
462
- type: "object",
463
- properties: Object.fromEntries(fields.map((field) => [field.name, field.schema])),
464
- required: fields.filter((field) => field.required).map((field) => field.name),
465
- additionalProperties: false
466
- },
467
- outputSchema: OUTPUTS[spec.capability],
468
- annotations: {
469
- title: spec.title,
470
- readOnlyHint: spec.readOnly,
471
- destructiveHint: !spec.readOnly,
472
- idempotentHint: spec.idempotent,
473
- openWorldHint: true
474
- },
475
- async execute(input, call = {}) {
476
- const values = checkInput(spec.name, provider, fields, input);
477
- const { [spec.subject]: subject, ...rest } = values;
478
- return forModel(spec.capability === "parse" ? await methods.parse(toDocument(values), {
479
- pages: values.pages,
480
- ...call
481
- }) : await methods[spec.capability](subject, {
482
- ...rest,
483
- ...call
484
- }), budget);
485
- }
486
- }];
487
- });
488
- }
489
1275
  /**
490
- * An error as a model or an MCP client should see it: the code, the message
491
- * and what to do next, without the provider's response.
1276
+ * Capabilities that start remote browsers or create lasting or billed
1277
+ * resources. `toolsFor` leaves them out unless they are named in `allow` or
1278
+ * `capabilities`.
492
1279
  */
493
- function toolError(error) {
494
- if (error instanceof FieldworkError) return error.toJSON();
495
- return {
496
- name: "Error",
497
- code: "ProviderError",
498
- message: error instanceof Error ? error.message : String(error),
499
- retryable: false
500
- };
501
- }
502
- function invalid(tool, provider, message) {
503
- return new FieldworkError("InvalidRequest", `${tool}: ${message}`, { provider });
504
- }
505
- function checkInput(tool, provider, fields, input) {
506
- if (!input || typeof input !== "object" || Array.isArray(input)) throw invalid(tool, provider, "input must be an object");
507
- const values = input;
508
- const known = new Map(fields.map((field) => [field.name, field]));
509
- for (const key of Object.keys(values)) if (!known.has(key)) throw invalid(tool, provider, `${key} is not an input with ${provider}; the inputs are ${[...known.keys()].join(", ")}`);
1280
+ const EXCLUDED_BY_DEFAULT = [
1281
+ "act",
1282
+ "browser",
1283
+ "monitor"
1284
+ ];
1285
+ const offers = (field, provider) => field.providers === void 0 || field.providers.includes(provider);
1286
+ const needs = (field, provider) => field.required === true || field.requiredFor?.includes(provider) === true;
1287
+ const invalid = (tool, provider, message) => new FieldworkError("InvalidRequest", `${tool}: ${message}`, { provider });
1288
+ const readInput = (tool, provider, fields, input) => {
1289
+ if (!isJsonObject(input)) throw invalid(tool, provider, "input must be an object");
1290
+ const known = new Set(fields.map((field) => field.name));
1291
+ for (const key of Object.keys(input)) if (!known.has(key)) throw invalid(tool, provider, `${key} is not an input with ${provider}; the inputs are ${[...known].join(", ")}`);
510
1292
  for (const field of fields) {
511
- const value = values[field.name];
1293
+ const value = input[field.name];
512
1294
  if (value === void 0) {
513
- if (field.required) throw invalid(tool, provider, `${field.name} is required`);
1295
+ if (needs(field, provider)) throw invalid(tool, provider, `${field.name} is required`);
514
1296
  continue;
515
1297
  }
516
- const problem = checkValue(field.schema, value);
517
- if (problem) throw invalid(tool, provider, `${field.name} ${problem}`);
1298
+ const found = problem(field.schema, value, field.name);
1299
+ if (found !== void 0) throw invalid(tool, provider, found);
518
1300
  }
519
- return values;
520
- }
521
- function checkString(schema, value) {
522
- if (typeof value !== "string" || value === "") return "must be a non-empty string";
523
- const allowed = schema.enum;
524
- if (allowed && !allowed.includes(value)) return `must be one of ${allowed.join(", ")}`;
525
- if (schema.format === "uri" && !URL.canParse(value)) return "must be a full URL, including https://";
526
- if (schema.format === "date" && !/^\d{4}-\d{2}-\d{2}$/u.test(value)) return "must be a date as YYYY-MM-DD";
527
- }
528
- function checkInteger(schema, value) {
529
- const minimum = schema.minimum;
530
- const maximum = schema.maximum;
531
- return Number.isInteger(value) && value >= minimum && value <= maximum ? void 0 : `must be a whole number from ${minimum} to ${maximum}`;
532
- }
533
- const CHECKS = /* @__PURE__ */ new Map([
534
- ["string", checkString],
535
- ["integer", checkInteger],
536
- ["boolean", (_, value) => typeof value === "boolean" ? void 0 : "must be true or false"],
537
- ["array", (_, value) => Array.isArray(value) && value.every((item) => typeof item === "string" && item !== "") ? void 0 : "must be a list of strings"],
538
- ["object", (_, value) => value && typeof value === "object" && !Array.isArray(value) ? void 0 : "must be a JSON object"]
539
- ]);
540
- function checkValue(schema, value) {
541
- return CHECKS.get(schema.type)?.(schema, value);
542
- }
543
- function toDocument(values) {
1301
+ return input;
1302
+ };
1303
+ /** The tool's result as an object: a list is wrapped, a confirmation is spelled out. */
1304
+ const resultObject = (spec, values, result) => {
1305
+ if (spec.wrapAs !== void 0) return { [spec.wrapAs]: result };
1306
+ if (spec.confirmAs !== void 0) return {
1307
+ [spec.confirmAs]: true,
1308
+ id: values.id
1309
+ };
1310
+ if (isJsonObject(result)) return result;
1311
+ throw new FieldworkError("ProviderError", `${spec.name} got a result that is not an object`);
1312
+ };
1313
+ const inputSchema = (fields, provider) => ({
1314
+ additionalProperties: false,
1315
+ properties: Object.fromEntries(fields.map((field) => [field.name, toJsonSchema(field.schema)])),
1316
+ required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1317
+ type: "object"
1318
+ });
1319
+ const toolFor = (spec, provider, operation, budget) => {
1320
+ const fields = spec.fields.filter((field) => offers(field, provider));
544
1321
  return {
545
- name: values.name,
546
- data: new Uint8Array(Buffer.from(values.contentBase64, "base64"))
1322
+ annotations: {
1323
+ destructiveHint: spec.destructive,
1324
+ idempotentHint: spec.idempotent,
1325
+ openWorldHint: true,
1326
+ readOnlyHint: spec.readOnly,
1327
+ title: spec.title
1328
+ },
1329
+ capability: spec.capability,
1330
+ description: spec.description,
1331
+ execute: async (input, call = {}) => {
1332
+ const values = readInput(spec.name, provider, fields, input);
1333
+ const result = await operation(...argumentsFor(spec, values, call));
1334
+ return forModel(resultObject(spec, values, result), budget);
1335
+ },
1336
+ inputSchema: inputSchema(fields, provider),
1337
+ method: spec.method,
1338
+ name: spec.name,
1339
+ outputSchema: toJsonSchema(spec.output),
1340
+ provider
547
1341
  };
548
- }
549
- const SHORT_TEXT = 500;
1342
+ };
1343
+ /** Makes one tool per capability, or per method of a group, the instance supports. */
1344
+ const toolsFor = (web, options = {}) => {
1345
+ const wanted = /* @__PURE__ */ new Set([...options.capabilities ?? CAPABILITIES.filter((capability) => !EXCLUDED_BY_DEFAULT.includes(capability)), ...options.allow ?? []]);
1346
+ const budget = options.maxCharacters ?? 2e4;
1347
+ const dispatcher = web;
1348
+ return SPECS.flatMap((spec) => {
1349
+ const provider = web.providerFor(spec.capability);
1350
+ const operation = operationFor(dispatcher, spec);
1351
+ return wanted.has(spec.capability) && provider !== void 0 && operation !== void 0 ? [toolFor(spec, provider, operation, budget)] : [];
1352
+ });
1353
+ };
550
1354
  /**
551
- * Drops the provider's `raw` response (on the result and on each crawled
552
- * page) and cuts long text to a budget shared across the result. Keys inside
553
- * extracted data are left alone, whatever their names.
1355
+ * An error as a model or an MCP client should see it: the code, the message
1356
+ * and what to do next, without the provider's response.
554
1357
  */
555
- function strip(value) {
556
- if (!value || typeof value !== "object" || Array.isArray(value)) return value;
557
- const { raw: _raw, ...rest } = value;
558
- return rest;
559
- }
560
- function forModel(result, budget) {
561
- let remaining = budget;
562
- const cut = (value) => {
563
- if (typeof value === "string") {
564
- if (value.length <= SHORT_TEXT) return value;
565
- const kept = Math.min(value.length, remaining);
566
- remaining -= kept;
567
- return kept === value.length ? value : `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
568
- }
569
- if (Array.isArray(value)) return value.map((item) => cut(item));
570
- if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cut(item)]));
571
- return value;
1358
+ const toolError = (cause) => {
1359
+ if (cause instanceof FieldworkError) return cause.toJSON();
1360
+ return {
1361
+ code: "ProviderError",
1362
+ message: cause instanceof Error ? cause.message : String(cause),
1363
+ name: "Error",
1364
+ retryable: false
572
1365
  };
573
- const shaped = strip(result);
574
- if (shaped && typeof shaped === "object" && "pages" in shaped && Array.isArray(shaped.pages)) shaped.pages = shaped.pages.map((page) => strip(page));
575
- return cut(shaped);
576
- }
577
- export { toolError, toolsFor };
1366
+ };
1367
+ export { EXCLUDED_BY_DEFAULT, toolError, toolsFor };