@howells/fieldwork-sdk 0.4.0 → 0.5.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/serpapi.js CHANGED
@@ -1,10 +1,9 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { C as createRawClient, E as callSettings, I as refuseTogether, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, j as meta, k as compact, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings } from "./parse-CxOri73y.js";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
+ import { C as createRawClient, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings, z as refuseTogether } from "./parse-n8MmaK1x.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/serpapi/parse.ts
6
6
  const provider = "serpapi";
7
- const invalid = (message) => new FieldworkError("InvalidRequest", `${provider} ${message}`, { provider });
8
7
  const priceOf = (item) => {
9
8
  const price = compact({
10
9
  amount: item.extracted_price,
@@ -150,7 +149,7 @@ const googleCountry = (value) => {
150
149
  };
151
150
  const isoDate = (name, value) => {
152
151
  if (value === void 0) return;
153
- if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) throw invalid(`${name} must be YYYY-MM-DD`);
152
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) throw invalidRequest(provider, `${name} must be YYYY-MM-DD`);
154
153
  return value;
155
154
  };
156
155
  const compactDate = (name, value) => isoDate(name, value)?.replaceAll("-", "");
@@ -160,7 +159,7 @@ const usDate = (name, value) => {
160
159
  };
161
160
  const bounded = (engine, value, min, max) => {
162
161
  if (value === void 0) return;
163
- if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) throw invalid(`${engine} limit must be a whole number from ${min} to ${max}`);
162
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) throw invalidRequest(provider, `${engine} limit must be a whole number from ${min} to ${max}`);
164
163
  return value;
165
164
  };
166
165
  /** The code for the recency window the caller set; undefined when it names none. */
@@ -181,10 +180,10 @@ const googleTbs = (o) => {
181
180
  const duckDuckGoFilter = (o) => {
182
181
  refuseTogether(provider, o, "recency", "publishedAfter");
183
182
  refuseTogether(provider, o, "recency", "publishedBefore");
184
- if (o.recency === "hour") throw invalid("duckduckgo has no hour window; use day, week, month or year");
183
+ if (o.recency === "hour") throw invalidRequest(provider, "duckduckgo has no hour window; use day, week, month or year");
185
184
  if (o.recency !== void 0) return recencyCode(o);
186
185
  if (o.publishedAfter === void 0 && o.publishedBefore === void 0) return;
187
- if (o.publishedAfter === void 0 || o.publishedBefore === void 0) throw invalid("duckduckgo filters a date range by both ends: pass publishedAfter and publishedBefore together");
186
+ if (o.publishedAfter === void 0 || o.publishedBefore === void 0) throw invalidRequest(provider, "duckduckgo filters a date range by both ends: pass publishedAfter and publishedBefore together");
188
187
  return `${isoDate("publishedAfter", o.publishedAfter)}..${isoDate("publishedBefore", o.publishedBefore)}`;
189
188
  };
190
189
  const patentDate = (name, value) => {
@@ -195,10 +194,10 @@ const mapsOrigin = (o) => {
195
194
  refuseTogether(provider, o, "location", "latitude");
196
195
  refuseTogether(provider, o, "location", "longitude");
197
196
  const coordinates = o.latitude !== void 0 || o.longitude !== void 0;
198
- if (coordinates && (o.latitude === void 0 || o.longitude === void 0)) throw invalid("google_maps needs latitude and longitude together");
197
+ if (coordinates && (o.latitude === void 0 || o.longitude === void 0)) throw invalidRequest(provider, "google_maps needs latitude and longitude together");
199
198
  const origin = coordinates || o.location !== void 0;
200
- if (origin && o.zoom === void 0) throw invalid("google_maps needs zoom with location or latitude and longitude");
201
- if (!origin && o.zoom !== void 0) throw invalid("google_maps zoom needs location or latitude and longitude");
199
+ if (origin && o.zoom === void 0) throw invalidRequest(provider, "google_maps needs zoom with location or latitude and longitude");
200
+ if (!origin && o.zoom !== void 0) throw invalidRequest(provider, "google_maps zoom needs location or latitude and longitude");
202
201
  return {
203
202
  lat: count(o.latitude),
204
203
  location: str(o.location),
@@ -399,7 +398,7 @@ const IMAGE_OPTIONS = [
399
398
  ];
400
399
  const onlyAllowed = (engine, options, allowed) => {
401
400
  const refused = Object.keys(options).filter((name) => options[name] !== void 0 && !allowed.includes(name));
402
- if (refused.length > 0) throw invalid(`${engine} does not accept ${refused.join(", ")}`);
401
+ if (refused.length > 0) throw invalidRequest(provider, `${engine} does not accept ${refused.join(", ")}`);
403
402
  };
404
403
  // src/adapters/serpapi/response.ts
405
404
  /** SerpApi's `error` note: its text when it is a non-empty string, and the warnings it amounts to. */
@@ -509,6 +508,11 @@ const AccountResponse = looseObject({
509
508
  this_month_usage: optionalNumber
510
509
  });
511
510
  // src/adapters/serpapi.ts
511
+ /**
512
+ * An adapter for SerpApi: search, images and usage. Pass it to `new Fieldwork({ adapter })`.
513
+ *
514
+ * Throws `Unauthorized` when neither `apiKey` nor `SERPAPI_API_KEY` is set.
515
+ */
512
516
  const serpapi = (config = {}) => {
513
517
  const key = requireKey(provider, config.apiKey, "SERPAPI_API_KEY");
514
518
  const authenticated = async (input, init) => {
@@ -578,7 +582,7 @@ const serpapi = (config = {}) => {
578
582
  const { call, rest } = callSettings(options);
579
583
  const { engine = "google", ...chosen } = rest;
580
584
  const o = { ...chosen };
581
- if (!Object.hasOwn(ENGINES, engine)) throw invalid(`does not offer the engine "${engine}"`);
585
+ if (!Object.hasOwn(ENGINES, engine)) throw invalidRequest(provider, `does not offer the engine "${engine}"`);
582
586
  const spec = ENGINES[engine];
583
587
  onlyAllowed(engine, o, spec.allowed);
584
588
  const { body, response } = await searchCall(call, compact({
package/dist/tavily.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { G as Research, I as Page, L as PageBatch, W as Recency, X as SiteMap, a as RawClient, f as CallOptions, g as Crawl, k as ImageSearch, l as Answer, q as SearchResponse, s as AccountUsage, t as Adapter } from "./adapter-CDY8qczv.js";
2
- import { t as OutputSchema } from "./schema-EZlBkY5B.js";
1
+ import { K as Recency, Q as SiteMap, R as Page, Y as SearchResponse, _ as Crawl, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-BgdfLBs-.js";
2
+ import { t as OutputSchema } from "./schema-Cupy7-7q.js";
3
3
  interface TavilyConfig {
4
4
  /** Defaults to the TAVILY_API_KEY environment variable. */
5
5
  apiKey?: string;
@@ -156,5 +156,10 @@ interface TavilyOperations {
156
156
  research: <T = unknown>(question: string, options?: TavilyResearchOptions<T>) => Promise<Research<T>>;
157
157
  usage: (options?: CallOptions) => Promise<AccountUsage>;
158
158
  }
159
+ /**
160
+ * An adapter for Tavily: search, images, read, readMany, map, crawl, answer, research and usage. Pass it to `new Fieldwork({ adapter })`.
161
+ *
162
+ * Throws `Unauthorized` when neither `apiKey` nor `TAVILY_API_KEY` is set.
163
+ */
159
164
  export declare const tavily: (config?: TavilyConfig) => Adapter<"tavily", TavilyOperations, RawClient>;
160
165
  export type { TavilyAnswerOptions, TavilyConfig, TavilyCrawlOptions, TavilyImagesOptions, TavilyMapOptions, TavilyOperations, TavilyReadManyOptions, TavilyReadOptions, TavilyResearchFile, TavilyResearchOptions, TavilySearchDepth, TavilySearchOptions };
package/dist/tavily.js CHANGED
@@ -1,7 +1,8 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { A as hours, C as createRawClient, E as callSettings, L as requireJobId, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as meta, k as compact, m as optionalScalar, n as anything, r as arrayOf, w as poll } from "./parse-CxOri73y.js";
4
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-teOy7Od-.js";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, M as compact, N as hours, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, n as anything, r as arrayOf } from "./parse-n8MmaK1x.js";
4
+ import { t as runJob } from "./job-BGTwH3F-.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
6
  import * as z from "zod/mini";
6
7
  // src/adapters/tavily/countries.ts
7
8
  /** Tavily's country names, by ISO 3166-1 alpha-2 code. */
@@ -39,17 +40,17 @@ const COUNTRIES = new Map(`
39
40
  YE yemen,ZA south africa,ZM zambia,ZW zimbabwe
40
41
  `.split(",").map((entry) => entry.trim()).map((entry) => [entry.slice(0, 2), entry.slice(3)]));
41
42
  // src/adapters/tavily/parse.ts
43
+ const provider = "tavily";
42
44
  const RESEARCH_FILE = /\.(?:txt|md|json)$/iu;
43
- const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider: "tavily" });
44
45
  const chunks = (content) => {
45
46
  if (content === void 0) return;
46
47
  const parts = content.split(/\s*\[\.\.\.\]\s*/u).map((part) => part.trim()).filter((part) => part !== "");
47
48
  return parts.length > 0 ? parts : void 0;
48
49
  };
49
50
  const countryName = (code, topic) => {
50
- if (topic !== void 0 && topic !== "general") throw invalid(`tavily country only works with topic "general", not "${topic}"`);
51
+ if (topic !== void 0 && topic !== "general") throw invalidRequest(provider, `country only works with topic "general", not "${topic}"`);
51
52
  const name = COUNTRIES.get(code.toUpperCase());
52
- if (name === void 0) throw invalid(`tavily has no country for "${code}"; pass an ISO 3166-1 alpha-2 code from its supported list`);
53
+ if (name === void 0) throw invalidRequest(provider, `has no country for "${code}"; pass an ISO 3166-1 alpha-2 code from its supported list`);
53
54
  return name;
54
55
  };
55
56
  const imageResults = (images) => {
@@ -62,16 +63,16 @@ const responseMeta = (body) => meta({
62
63
  units: { responseTimeSeconds: body.response_time }
63
64
  });
64
65
  const checkFilters = (o) => {
65
- if (o.includeDomainsMode !== void 0 && (o.includeDomains?.length ?? 0) === 0) throw invalid("tavily includeDomainsMode needs includeDomains");
66
- if (o.filterByLanguage === true && o.language === void 0) throw invalid("tavily filterByLanguage needs language");
67
- if (o.safeSearch === true && (o.searchDepth === "fast" || o.searchDepth === "ultra-fast")) throw invalid(`tavily safeSearch is not available with searchDepth "${o.searchDepth}"`);
66
+ if (o.includeDomainsMode !== void 0 && (o.includeDomains?.length ?? 0) === 0) throw invalidRequest(provider, "includeDomainsMode needs includeDomains");
67
+ if (o.filterByLanguage === true && o.language === void 0) throw invalidRequest(provider, "filterByLanguage needs language");
68
+ if (o.safeSearch === true && (o.searchDepth === "fast" || o.searchDepth === "ultra-fast")) throw invalidRequest(provider, `safeSearch is not available with searchDepth "${o.searchDepth}"`);
68
69
  };
69
70
  const checkSearch = (o) => {
70
71
  checkFilters(o);
71
- if (o.chunksPerSource !== void 0 && o.searchDepth === "ultra-fast") throw invalid("tavily chunksPerSource is not available with searchDepth \"ultra-fast\"");
72
- if (o.imageDescriptions === true && o.includeImages !== true) throw invalid("tavily imageDescriptions needs includeImages");
72
+ if (o.chunksPerSource !== void 0 && o.searchDepth === "ultra-fast") throw invalidRequest(provider, "chunksPerSource is not available with searchDepth \"ultra-fast\"");
73
+ if (o.imageDescriptions === true && o.includeImages !== true) throw invalidRequest(provider, "imageDescriptions needs includeImages");
73
74
  const maxAgeHours = hours(o.maxAge);
74
- if (maxAgeHours !== void 0 && maxAgeHours > 720) throw invalid("tavily keeps cached copies for at most 30 days (2,592,000 seconds)");
75
+ if (maxAgeHours !== void 0 && maxAgeHours > 720) throw invalidRequest(provider, "keeps cached copies for at most 30 days (2,592,000 seconds)");
75
76
  return maxAgeHours;
76
77
  };
77
78
  const rawContent = (content) => {
@@ -134,7 +135,7 @@ const page = (entry, query) => {
134
135
  });
135
136
  };
136
137
  const extractBody = (urls, o) => {
137
- if (o.chunksPerSource !== void 0 && o.query === void 0) throw invalid("tavily chunksPerSource needs query");
138
+ if (o.chunksPerSource !== void 0 && o.query === void 0) throw invalidRequest(provider, "chunksPerSource needs query");
138
139
  return compact({
139
140
  chunks_per_source: o.chunksPerSource,
140
141
  extract_depth: o.extractDepth,
@@ -245,8 +246,12 @@ const UsageResponse = looseObject({
245
246
  key: looseObject({ usage: optionalNumber })
246
247
  });
247
248
  // src/adapters/tavily.ts
249
+ /**
250
+ * An adapter for Tavily: search, images, read, readMany, map, crawl, answer, research and usage. Pass it to `new Fieldwork({ adapter })`.
251
+ *
252
+ * Throws `Unauthorized` when neither `apiKey` nor `TAVILY_API_KEY` is set.
253
+ */
248
254
  const tavily = (config = {}) => {
249
- const provider = "tavily";
250
255
  const raw = createRawClient({
251
256
  baseUrl: config.baseUrl ?? "https://api.tavily.com",
252
257
  fetch: config.fetch,
@@ -290,7 +295,7 @@ const tavily = (config = {}) => {
290
295
  },
291
296
  async crawl(url, options) {
292
297
  const { call, rest: o } = callSettings(options);
293
- if (o.chunksPerSource !== void 0 && o.instructions === void 0) throw invalid("tavily chunksPerSource needs instructions");
298
+ if (o.chunksPerSource !== void 0 && o.instructions === void 0) throw invalidRequest(provider, "chunksPerSource needs instructions");
294
299
  const response = await raw.request("POST", "/crawl", {
295
300
  ...call,
296
301
  body: compact({
@@ -371,7 +376,7 @@ const tavily = (config = {}) => {
371
376
  },
372
377
  async readMany(urls, options) {
373
378
  const { call, rest: o } = callSettings(options);
374
- if (urls.length === 0 || urls.length > 20) throw invalid("tavily reads 1 to 20 URLs in one call");
379
+ if (urls.length === 0 || urls.length > 20) throw invalidRequest(provider, "reads 1 to 20 URLs in one call");
375
380
  const response = await raw.request("POST", "/extract", {
376
381
  ...call,
377
382
  body: extractBody(urls, o)
@@ -387,66 +392,67 @@ const tavily = (config = {}) => {
387
392
  async research(question, options) {
388
393
  const { call, rest: o } = callSettings(options);
389
394
  const files = o.files?.map((file) => {
390
- if (!RESEARCH_FILE.test(file.name)) throw invalid(`tavily reads .txt, .md and .json files, not ${file.name}`);
395
+ if (!RESEARCH_FILE.test(file.name)) throw invalidRequest(provider, `reads .txt, .md and .json files, not ${file.name}`);
391
396
  return {
392
397
  data: base64(typeof file.data === "string" ? new TextEncoder().encode(file.data) : file.data),
393
398
  name: file.name,
394
399
  type: "base64"
395
400
  };
396
401
  });
397
- if (files && files.length > 5) throw invalid("tavily research takes up to 5 files");
398
- const id = o.resume ?? requireJobId(provider, z.parse(ResearchStart, await raw.request("POST", "/research", {
399
- creates: true,
400
- ...call,
401
- body: compact({
402
- citation_format: o.citationFormat,
403
- exclude_domains: o.excludeDomains,
404
- files,
405
- include_domains: o.includeDomains,
406
- input: question,
407
- model: o.model,
408
- output_length: o.outputLength,
409
- output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
410
- stream: false
411
- })
412
- })).request_id);
413
- const { body: run, response } = await poll(provider, id, async () => {
414
- const current = await raw.request("GET", `/research/${id}`, {
415
- query: { include_usage: true },
416
- signal: call.signal
417
- });
418
- const parsed = z.parse(ResearchRun, current);
419
- if (parsed.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
420
- cause: current,
421
- provider
422
- });
423
- return parsed.status === "completed" ? {
424
- body: parsed,
425
- response: current
426
- } : void 0;
402
+ if (files && files.length > 5) throw invalidRequest(provider, "research takes up to 5 files");
403
+ return await runJob(provider, {
404
+ check: async (id, request) => {
405
+ const current = await raw.request("GET", `/research/${segment(id)}`, {
406
+ ...request,
407
+ query: { include_usage: true }
408
+ });
409
+ const parsed = z.parse(ResearchRun, current);
410
+ if (parsed.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
411
+ cause: current,
412
+ provider
413
+ });
414
+ return parsed.status === "completed" ? {
415
+ body: parsed,
416
+ response: current
417
+ } : void 0;
418
+ },
419
+ finish: async ({ body: run, response }, id) => {
420
+ const { content } = run;
421
+ if (content === void 0 || content === null || content === "") throw new FieldworkError("JobFailed", `tavily research ${id} finished without output`, {
422
+ cause: response,
423
+ provider
424
+ });
425
+ return compact({
426
+ id,
427
+ meta: responseMeta(run),
428
+ output: await checkOutput(o.schema, content, { provider }),
429
+ raw: response,
430
+ sources: run.sources.flatMap((source) => source.url === void 0 ? [] : [compact({
431
+ title: source.title,
432
+ url: source.url
433
+ })]),
434
+ status: "completed"
435
+ });
436
+ },
437
+ start: async () => requireJobId(provider, z.parse(ResearchStart, await raw.request("POST", "/research", {
438
+ creates: true,
439
+ ...call,
440
+ body: compact({
441
+ citation_format: o.citationFormat,
442
+ exclude_domains: o.excludeDomains,
443
+ files,
444
+ include_domains: o.includeDomains,
445
+ input: question,
446
+ model: o.model,
447
+ output_length: o.outputLength,
448
+ output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
449
+ stream: false
450
+ })
451
+ })).request_id)
427
452
  }, {
428
453
  ...call,
429
- interval: o.interval
430
- });
431
- const { content } = run;
432
- if (content === void 0 || content === null || content === "") throw new FieldworkError("JobFailed", `tavily research ${id} finished without output`, {
433
- cause: response,
434
- jobId: id,
435
- provider
436
- });
437
- return compact({
438
- id,
439
- meta: responseMeta(run),
440
- output: await checkOutput(o.schema, content, {
441
- jobId: id,
442
- provider
443
- }),
444
- raw: response,
445
- sources: run.sources.flatMap((source) => source.url === void 0 ? [] : [compact({
446
- title: source.title,
447
- url: source.url
448
- })]),
449
- status: "completed"
454
+ interval: o.interval,
455
+ resume: o.resume
450
456
  });
451
457
  },
452
458
  async search(query, options) {
package/dist/tools.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-DTNVIOzp.js";
2
- import { A as JsonSchema, f as CallOptions, n as AnyAdapter, p as Capability } from "./adapter-CDY8qczv.js";
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
3
  /**
4
4
  * The JSON values that cross the tool boundary: what a model sends in, what a
5
5
  * tool sends back. Tools take and return these types, and the guards below are
@@ -22,6 +22,7 @@ export type ToolInput = JsonValue;
22
22
  export type ToolArguments = JsonObject;
23
23
  /** What a tool returns: a JSON object, shaped for a model. */
24
24
  export type ToolOutput = JsonObject;
25
+ /** MCP tool annotations, which clients use to decide when to ask before calling. */
25
26
  export interface ToolAnnotations {
26
27
  title: string;
27
28
  /** True when the tool changes nothing outside Fieldwork. */
@@ -33,6 +34,7 @@ export interface ToolAnnotations {
33
34
  /** True when the tool reaches the open web. */
34
35
  openWorldHint: boolean;
35
36
  }
37
+ /** One agent tool, ready to register with an MCP server or a model's tool API. */
36
38
  export interface FieldworkTool {
37
39
  /** A verb_noun name, such as `search_web`. */
38
40
  name: string;
@@ -62,6 +64,7 @@ export interface FieldworkTool {
62
64
  * `capabilities`.
63
65
  */
64
66
  export declare const EXCLUDED_BY_DEFAULT: readonly Capability[];
67
+ /** Which tools `toolsFor` makes, and how much text each result may return. */
65
68
  export interface ToolsOptions {
66
69
  /**
67
70
  * Capabilities to make tools for. Defaults to every capability the instance
package/dist/tools.js CHANGED
@@ -1,8 +1,6 @@
1
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
1
+ import { t as FieldworkError } from "./errors-Yvk42oZH.js";
2
2
  import { t as CAPABILITIES } from "./types-CnomnF-6.js";
3
3
  // src/tool-specs/schema.ts
4
- /** A schema as plain JSON Schema, for clients. */
5
- const toJsonSchema = (schema) => ({ ...schema });
6
4
  const described = (schema, description) => description === void 0 ? schema : {
7
5
  ...schema,
8
6
  description
@@ -92,7 +90,21 @@ const publishedBefore = (providers) => ({
92
90
  providers,
93
91
  schema: date("Only pages published before this date, YYYY-MM-DD.")
94
92
  });
95
- const RECENCY_NOTE = "Not together with publishedAfter or publishedBefore.";
93
+ /** The providers whose adapters refuse recency with a date bound, as each one's API does. */
94
+ const RECENCY_REFUSERS = /* @__PURE__ */ new Map([
95
+ ["brave", "Brave"],
96
+ ["firecrawl", "Firecrawl"],
97
+ ["serpapi", "SerpApi"]
98
+ ]);
99
+ /** Names the refusers among `providers`, so a model is told only what applies. */
100
+ const recencyNote = (providers) => {
101
+ const names = providers.flatMap((name) => {
102
+ const label = RECENCY_REFUSERS.get(name);
103
+ return label === void 0 ? [] : [label];
104
+ });
105
+ if (names.length === 0) return "";
106
+ return ` ${names.length === 1 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1) ?? ""}`} refuse it together with publishedAfter or publishedBefore.`;
107
+ };
96
108
  /**
97
109
  * `withHour` providers accept all five windows; `fromDay` providers have no
98
110
  * hour window. Two fields with one name, because the accepted values differ.
@@ -100,7 +112,7 @@ const RECENCY_NOTE = "Not together with publishedAfter or publishedBefore.";
100
112
  const recency = (withHour, fromDay) => [{
101
113
  name: "recency",
102
114
  providers: withHour,
103
- schema: choice(`Only pages from the last hour, day, week, month or year. ${RECENCY_NOTE}`, [
115
+ schema: choice(`Only pages from the last hour, day, week, month or year.${recencyNote(withHour)}`, [
104
116
  "hour",
105
117
  "day",
106
118
  "week",
@@ -110,7 +122,7 @@ const recency = (withHour, fromDay) => [{
110
122
  }, {
111
123
  name: "recency",
112
124
  providers: fromDay,
113
- schema: choice(`Only pages from the last day, week, month or year. ${RECENCY_NOTE}`, [
125
+ schema: choice(`Only pages from the last day, week, month or year.${recencyNote(fromDay)}`, [
114
126
  "day",
115
127
  "week",
116
128
  "month",
@@ -393,8 +405,45 @@ const CLOSE_BROWSER_OUTPUT = object({
393
405
  closed: flag(),
394
406
  id: str
395
407
  }, ["closed", "id"]);
408
+ const box = object({
409
+ height: number(),
410
+ left: number(),
411
+ top: number(),
412
+ width: number()
413
+ }, [
414
+ "left",
415
+ "top",
416
+ "width",
417
+ "height"
418
+ ], "Where it sits on the page, as fractions of the page's width and height from its top-left corner.");
396
419
  const PARSE_OUTPUT = object({
397
- blocks: list(anything()),
420
+ blocks: list(object({
421
+ box,
422
+ cells: list(object({
423
+ box,
424
+ column: whole("The column, from 0.", 0),
425
+ columnSpan: whole("Columns the cell spans.", 1),
426
+ row: whole("The row, from 0.", 0),
427
+ rowSpan: whole("Rows the cell spans.", 1),
428
+ text: str
429
+ }, [
430
+ "row",
431
+ "column",
432
+ "text"
433
+ ])),
434
+ page: whole("The physical page number, starting at 1.", 1),
435
+ text: str,
436
+ type: str,
437
+ words: list(object({
438
+ box,
439
+ text: str
440
+ }, ["text", "box"]))
441
+ }, [
442
+ "page",
443
+ "type",
444
+ "text"
445
+ ])),
446
+ id: str,
398
447
  markdown: str,
399
448
  meta,
400
449
  pageCount: whole("Pages in the file.", 0),
@@ -687,7 +736,8 @@ const BROWSER_SPECS = [
687
736
  name: "pages",
688
737
  providers: ["firecrawl"],
689
738
  schema: flag("Also return the Markdown of each page separately.")
690
- }
739
+ },
740
+ resume(["llamaparse", "reducto"])
691
741
  ],
692
742
  idempotent: true,
693
743
  name: "parse_document",
@@ -1282,8 +1332,8 @@ const EXCLUDED_BY_DEFAULT = [
1282
1332
  "browser",
1283
1333
  "monitor"
1284
1334
  ];
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;
1335
+ const offers = (field, provider) => field.providers === void 0 || field.providers.some((name) => name === provider);
1336
+ const needs = (field, provider) => field.required === true || field.requiredFor?.some((name) => name === provider) === true;
1287
1337
  const invalid = (tool, provider, message) => new FieldworkError("InvalidRequest", `${tool}: ${message}`, { provider });
1288
1338
  const readInput = (tool, provider, fields, input) => {
1289
1339
  if (!isJsonObject(input)) throw invalid(tool, provider, "input must be an object");
@@ -1312,7 +1362,7 @@ const resultObject = (spec, values, result) => {
1312
1362
  };
1313
1363
  const inputSchema = (fields, provider) => ({
1314
1364
  additionalProperties: false,
1315
- properties: Object.fromEntries(fields.map((field) => [field.name, toJsonSchema(field.schema)])),
1365
+ properties: Object.fromEntries(fields.map((field) => [field.name, { ...field.schema }])),
1316
1366
  required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1317
1367
  type: "object"
1318
1368
  });
@@ -1336,7 +1386,7 @@ const toolFor = (spec, provider, operation, budget) => {
1336
1386
  inputSchema: inputSchema(fields, provider),
1337
1387
  method: spec.method,
1338
1388
  name: spec.name,
1339
- outputSchema: toJsonSchema(spec.output),
1389
+ outputSchema: { ...spec.output },
1340
1390
  provider
1341
1391
  };
1342
1392
  };
package/package.json CHANGED
@@ -1,17 +1,21 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.4.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 and Browserbase.",
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.",
5
5
  "keywords": [
6
6
  "agents",
7
7
  "brave",
8
8
  "browserbase",
9
+ "document-parsing",
9
10
  "exa",
10
11
  "extraction",
11
12
  "firecrawl",
13
+ "llamaparse",
12
14
  "monitoring",
13
15
  "parallel",
16
+ "pdf",
14
17
  "perplexity",
18
+ "reducto",
15
19
  "research",
16
20
  "scraping",
17
21
  "sdk",
@@ -71,6 +75,14 @@
71
75
  "types": "./dist/browserbase.d.ts",
72
76
  "import": "./dist/browserbase.js"
73
77
  },
78
+ "./llamaparse": {
79
+ "types": "./dist/llamaparse.d.ts",
80
+ "import": "./dist/llamaparse.js"
81
+ },
82
+ "./reducto": {
83
+ "types": "./dist/reducto.d.ts",
84
+ "import": "./dist/reducto.js"
85
+ },
74
86
  "./tools": {
75
87
  "types": "./dist/tools.d.ts",
76
88
  "import": "./dist/tools.js"
@@ -1,3 +0,0 @@
1
- // src/adapter.ts
2
- const defineAdapter = (adapter) => adapter;
3
- export { defineAdapter as t };