@howells/fieldwork-sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tavily.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
2
  import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { a as hours, b as requireKey, c as num, d as record, g as text, h as strings, i as compact, o as list, p as requireId, s as meta, t as callSettings, v as createRawClient, y as poll } from "./util-CYenIQQT.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";
5
+ import * as z from "zod/mini";
4
6
  // src/adapters/tavily/countries.ts
5
7
  /** Tavily's country names, by ISO 3166-1 alpha-2 code. */
6
8
  const COUNTRIES = new Map(`
@@ -39,41 +41,35 @@ const COUNTRIES = new Map(`
39
41
  // src/adapters/tavily/parse.ts
40
42
  const RESEARCH_FILE = /\.(?:txt|md|json)$/iu;
41
43
  const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider: "tavily" });
42
- const chunks = (value) => {
43
- const content = text(value);
44
- if (!content) return;
44
+ const chunks = (content) => {
45
+ if (content === void 0) return;
45
46
  const parts = content.split(/\s*\[\.\.\.\]\s*/u).map((part) => part.trim()).filter((part) => part !== "");
46
47
  return parts.length > 0 ? parts : void 0;
47
48
  };
48
49
  const countryName = (code, topic) => {
49
50
  if (topic !== void 0 && topic !== "general") throw invalid(`tavily country only works with topic "general", not "${topic}"`);
50
51
  const name = COUNTRIES.get(code.toUpperCase());
51
- if (!name) throw invalid(`tavily has no country for "${code}"; pass an ISO 3166-1 alpha-2 code from its supported list`);
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`);
52
53
  return name;
53
54
  };
54
- const imageResults = (value) => {
55
- const items = list(value).map((item) => {
56
- if (typeof item === "string") return item === "" ? void 0 : { url: item };
57
- const image = record(item);
58
- const url = text(image.url);
59
- return url ? compact({
60
- description: text(image.description),
61
- url
62
- }) : void 0;
63
- }).filter((item) => item !== void 0);
55
+ const imageResults = (images) => {
56
+ const items = images.filter((item) => item !== void 0);
64
57
  return items.length > 0 ? items : void 0;
65
58
  };
66
- const responseMeta = (response) => meta({
67
- credits: record(response.usage).credits,
68
- requestId: response.request_id,
69
- units: { responseTimeSeconds: response.response_time }
59
+ const responseMeta = (body) => meta({
60
+ credits: body.usage.credits,
61
+ requestId: body.request_id,
62
+ units: { responseTimeSeconds: body.response_time }
70
63
  });
64
+ 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}"`);
68
+ };
71
69
  const checkSearch = (o) => {
72
- if (o.includeDomainsMode !== void 0 && !o.includeDomains?.length) throw invalid("tavily includeDomainsMode needs includeDomains");
73
- if (o.filterByLanguage && o.language === void 0) throw invalid("tavily filterByLanguage needs language");
74
- if (o.safeSearch && (o.searchDepth === "fast" || o.searchDepth === "ultra-fast")) throw invalid(`tavily safeSearch is not available with searchDepth "${o.searchDepth}"`);
70
+ checkFilters(o);
75
71
  if (o.chunksPerSource !== void 0 && o.searchDepth === "ultra-fast") throw invalid("tavily chunksPerSource is not available with searchDepth \"ultra-fast\"");
76
- if (o.imageDescriptions && !o.includeImages) throw invalid("tavily imageDescriptions needs includeImages");
72
+ if (o.imageDescriptions === true && o.includeImages !== true) throw invalid("tavily imageDescriptions needs includeImages");
77
73
  const maxAgeHours = hours(o.maxAge);
78
74
  if (maxAgeHours !== void 0 && maxAgeHours > 720) throw invalid("tavily keeps cached copies for at most 30 days (2,592,000 seconds)");
79
75
  return maxAgeHours;
@@ -113,36 +109,28 @@ const searchBody = (query, o) => {
113
109
  topic: o.topic
114
110
  });
115
111
  };
116
- const searchResults = (response) => list(response.results).map((item) => {
117
- const result = record(item);
118
- return compact({
119
- content: text(result.raw_content),
120
- favicon: text(result.favicon),
121
- publishedAt: text(result.published_date),
122
- score: num(result.score),
123
- snippet: text(result.content),
124
- title: text(result.title),
125
- url: text(result.url) ?? ""
126
- });
127
- });
128
- const failures = (response) => list(response.failed_results).flatMap((item) => {
129
- const failure = record(item);
130
- const url = text(failure.url);
131
- return url ? [{
132
- error: text(failure.error) ?? "no content returned",
133
- url
134
- }] : [];
135
- });
136
- const page = (item, query) => {
137
- const result = record(item);
138
- const passages = query ? chunks(result.raw_content) : void 0;
112
+ const searchResults = (body) => body.results.map((result) => compact({
113
+ content: result.raw_content,
114
+ favicon: result.favicon,
115
+ publishedAt: result.published_date,
116
+ score: result.score,
117
+ snippet: result.content,
118
+ title: result.title,
119
+ url: result.url ?? ""
120
+ }));
121
+ const failures = (failed) => failed.flatMap((failure) => failure.url === void 0 ? [] : [{
122
+ error: failure.error ?? "no content returned",
123
+ url: failure.url
124
+ }]);
125
+ const page = (entry, query) => {
126
+ const result = entry.value;
139
127
  return compact({
140
- excerpts: passages,
141
- favicon: text(result.favicon),
142
- images: strings(result.images),
143
- markdown: query ? void 0 : text(result.raw_content),
144
- raw: item,
145
- url: text(result.url) ?? ""
128
+ excerpts: query ? chunks(result.raw_content) : void 0,
129
+ favicon: result.favicon,
130
+ images: result.images.length > 0 ? result.images : void 0,
131
+ markdown: query ? void 0 : result.raw_content,
132
+ raw: entry.original,
133
+ url: result.url ?? ""
146
134
  });
147
135
  };
148
136
  const extractBody = (urls, o) => {
@@ -177,17 +165,97 @@ const base64 = (bytes) => {
177
165
  for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCodePoint(...bytes.subarray(index, index + 32768));
178
166
  return btoa(binary);
179
167
  };
168
+ // src/adapters/tavily/response.ts
169
+ /** What a response reports about its own cost: the credits used, the id and the time taken. */
170
+ const usageShape = {
171
+ request_id: optionalScalar,
172
+ response_time: optionalNumber,
173
+ usage: looseObject({ credits: optionalNumber })
174
+ };
175
+ looseObject(usageShape);
176
+ /** An image: a bare URL, or an object with a URL and a description. Anything else, or one without a URL, reads as undefined. */
177
+ const Image = z.union([z.pipe(z.string(), z.transform((url) => url === "" ? void 0 : { url })), z.pipe(looseObject({
178
+ description: optionalString,
179
+ url: optionalString
180
+ }), z.transform((image) => image.url === void 0 ? void 0 : compact({
181
+ description: image.description,
182
+ url: image.url
183
+ })))]);
184
+ const SearchResult = looseObject({
185
+ content: optionalString,
186
+ favicon: optionalString,
187
+ published_date: optionalString,
188
+ raw_content: optionalString,
189
+ score: optionalNumber,
190
+ title: optionalString,
191
+ url: optionalString
192
+ });
193
+ /** `/search`, whole or as the part of an answer, image or search call. */
194
+ const SearchResponse = looseObject({
195
+ ...usageShape,
196
+ answer: optionalString,
197
+ images: arrayOf(Image),
198
+ results: arrayOf(SearchResult)
199
+ });
200
+ const PageResult = looseObject({
201
+ favicon: optionalString,
202
+ images: arrayOf(z.string()),
203
+ raw_content: optionalString,
204
+ url: optionalString
205
+ });
206
+ const FailedResult = looseObject({
207
+ error: optionalString,
208
+ url: optionalString
209
+ });
210
+ /** `/crawl`, and `/extract` for one URL or several. Each page keeps its own entry as it arrived. */
211
+ const PagesResponse = looseObject({
212
+ ...usageShape,
213
+ failed_results: arrayOf(FailedResult),
214
+ results: arrayOf(withOriginal(PageResult))
215
+ });
216
+ /** `/map`: the links are bare strings. */
217
+ const MapResponse = looseObject({
218
+ ...usageShape,
219
+ results: arrayOf(z.string())
220
+ });
221
+ /** The reply to starting a research task. */
222
+ const ResearchStart = looseObject({ request_id: withOriginal(optionalId) });
223
+ /** A research task while it runs and when it is done. `content` is the report, or the object the output schema asked for. */
224
+ const ResearchRun = looseObject({
225
+ ...usageShape,
226
+ content: anything,
227
+ sources: arrayOf(looseObject({
228
+ title: optionalString,
229
+ url: optionalString
230
+ })),
231
+ status: optionalString
232
+ });
233
+ /** `/usage`. */
234
+ const UsageResponse = looseObject({
235
+ account: looseObject({
236
+ crawl_usage: optionalNumber,
237
+ extract_usage: optionalNumber,
238
+ map_usage: optionalNumber,
239
+ paygo_usage: optionalNumber,
240
+ plan_limit: optionalNumber,
241
+ plan_usage: optionalNumber,
242
+ research_usage: optionalNumber,
243
+ search_usage: optionalNumber
244
+ }),
245
+ key: looseObject({ usage: optionalNumber })
246
+ });
180
247
  // src/adapters/tavily.ts
181
248
  const tavily = (config = {}) => {
182
249
  const provider = "tavily";
183
250
  const raw = createRawClient({
184
251
  baseUrl: config.baseUrl ?? "https://api.tavily.com",
185
252
  fetch: config.fetch,
186
- headers: compact({
253
+ headers: Object.fromEntries(Object.entries({
187
254
  authorization: `Bearer ${requireKey(provider, config.apiKey, "TAVILY_API_KEY")}`,
188
255
  "x-project-id": config.projectId
189
- }),
190
- provider
256
+ }).filter((entry) => entry[1] !== void 0)),
257
+ provider,
258
+ retries: config.retries
191
259
  });
192
260
  return defineAdapter({
193
261
  name: provider,
@@ -195,19 +263,20 @@ const tavily = (config = {}) => {
195
263
  async answer(question, options) {
196
264
  const { call, rest } = callSettings(options);
197
265
  const { answerDepth, ...o } = rest;
198
- const response = record(await raw.request("POST", "/search", {
266
+ const response = await raw.request("POST", "/search", {
199
267
  ...call,
200
268
  body: {
201
269
  ...searchBody(question, o),
202
270
  include_answer: answerDepth ?? "basic"
203
271
  }
204
- }));
205
- const answer = text(response.answer);
272
+ });
273
+ const body = z.parse(SearchResponse, response);
274
+ const { answer } = body;
206
275
  if (answer === void 0) throw new FieldworkError("ProviderError", "tavily returned no answer", {
207
276
  cause: response,
208
277
  provider
209
278
  });
210
- const sources = searchResults(response).filter((result) => result.url !== "").map((result) => compact({
279
+ const sources = searchResults(body).filter((result) => result.url !== "").map((result) => compact({
211
280
  excerpts: chunks(result.snippet),
212
281
  title: result.title,
213
282
  url: result.url
@@ -215,14 +284,14 @@ const tavily = (config = {}) => {
215
284
  return compact({
216
285
  answer,
217
286
  citations: sources,
218
- meta: responseMeta(response),
287
+ meta: responseMeta(body),
219
288
  raw: response
220
289
  });
221
290
  },
222
291
  async crawl(url, options) {
223
292
  const { call, rest: o } = callSettings(options);
224
293
  if (o.chunksPerSource !== void 0 && o.instructions === void 0) throw invalid("tavily chunksPerSource needs instructions");
225
- const response = record(await raw.request("POST", "/crawl", {
294
+ const response = await raw.request("POST", "/crawl", {
226
295
  ...call,
227
296
  body: compact({
228
297
  url,
@@ -233,16 +302,17 @@ const tavily = (config = {}) => {
233
302
  include_images: o.includeImages,
234
303
  include_favicon: o.favicon
235
304
  })
236
- }));
305
+ });
306
+ const body = z.parse(PagesResponse, response);
237
307
  return compact({
238
- meta: responseMeta(response),
239
- pages: list(response.results).map((item) => page(item, o.instructions !== void 0)),
308
+ meta: responseMeta(body),
309
+ pages: body.results.map((entry) => page(entry, o.instructions !== void 0)),
240
310
  raw: response
241
311
  });
242
312
  },
243
313
  async images(query, options) {
244
314
  const { call, rest: o } = callSettings(options);
245
- const response = record(await raw.request("POST", "/search", {
315
+ const response = await raw.request("POST", "/search", {
246
316
  ...call,
247
317
  body: searchBody(query, {
248
318
  excludeDomains: o.excludeDomains,
@@ -253,37 +323,40 @@ const tavily = (config = {}) => {
253
323
  searchDepth: o.searchDepth,
254
324
  topic: o.topic
255
325
  })
256
- }));
326
+ });
327
+ const body = z.parse(SearchResponse, response);
257
328
  return compact({
258
- meta: responseMeta(response),
329
+ meta: responseMeta(body),
259
330
  raw: response,
260
- results: imageResults(response.images) ?? []
331
+ results: imageResults(body.images) ?? []
261
332
  });
262
333
  },
263
334
  async map(url, options) {
264
335
  const { call, rest: o } = callSettings(options);
265
- const response = record(await raw.request("POST", "/map", {
336
+ const response = await raw.request("POST", "/map", {
266
337
  ...call,
267
338
  body: {
268
339
  url,
269
340
  ...traversal(o)
270
341
  }
271
- }));
342
+ });
343
+ const body = z.parse(MapResponse, response);
272
344
  return compact({
273
- links: list(response.results).flatMap((item) => typeof item === "string" ? [{ url: item }] : []),
274
- meta: responseMeta(response),
345
+ links: body.results.map((link) => ({ url: link })),
346
+ meta: responseMeta(body),
275
347
  raw: response
276
348
  });
277
349
  },
278
350
  async read(url, options) {
279
351
  const { call, rest: o } = callSettings(options);
280
- const response = record(await raw.request("POST", "/extract", {
352
+ const response = await raw.request("POST", "/extract", {
281
353
  ...call,
282
354
  body: extractBody([url], o)
283
- }));
284
- const [result] = list(response.results);
285
- if (!text(record(result).url)) {
286
- const [failure] = failures(response);
355
+ });
356
+ const body = z.parse(PagesResponse, response);
357
+ const [result] = body.results;
358
+ if (result?.value.url === void 0) {
359
+ const [failure] = failures(body.failed_results);
287
360
  const reason = failure?.error ?? "no content returned";
288
361
  throw new FieldworkError(/\b404\b|not found/iu.test(reason) ? "NotFound" : "ProviderError", `tavily could not read ${url}: ${reason}`, {
289
362
  cause: response,
@@ -292,21 +365,22 @@ const tavily = (config = {}) => {
292
365
  }
293
366
  return compact({
294
367
  ...page(result, o.query !== void 0),
295
- meta: responseMeta(response),
368
+ meta: responseMeta(body),
296
369
  raw: response
297
370
  });
298
371
  },
299
372
  async readMany(urls, options) {
300
373
  const { call, rest: o } = callSettings(options);
301
374
  if (urls.length === 0 || urls.length > 20) throw invalid("tavily reads 1 to 20 URLs in one call");
302
- const response = record(await raw.request("POST", "/extract", {
375
+ const response = await raw.request("POST", "/extract", {
303
376
  ...call,
304
377
  body: extractBody(urls, o)
305
- }));
378
+ });
379
+ const body = z.parse(PagesResponse, response);
306
380
  return compact({
307
- failed: failures(response),
308
- meta: responseMeta(response),
309
- pages: list(response.results).map((item) => page(item, o.query !== void 0)),
381
+ failed: failures(body.failed_results),
382
+ meta: responseMeta(body),
383
+ pages: body.results.map((entry) => page(entry, o.query !== void 0)),
310
384
  raw: response
311
385
  });
312
386
  },
@@ -321,7 +395,8 @@ const tavily = (config = {}) => {
321
395
  };
322
396
  });
323
397
  if (files && files.length > 5) throw invalid("tavily research takes up to 5 files");
324
- const id = o.resume ?? requireId(provider, record(await raw.request("POST", "/research", {
398
+ const id = o.resume ?? requireJobId(provider, z.parse(ResearchStart, await raw.request("POST", "/research", {
399
+ creates: true,
325
400
  ...call,
326
401
  body: compact({
327
402
  citation_format: o.citationFormat,
@@ -331,69 +406,68 @@ const tavily = (config = {}) => {
331
406
  input: question,
332
407
  model: o.model,
333
408
  output_length: o.outputLength,
334
- output_schema: o.schema,
409
+ output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
335
410
  stream: false
336
411
  })
337
412
  })).request_id);
338
- const run = await poll(provider, id, async () => {
339
- const current = record(await raw.request("GET", `/research/${id}`, {
413
+ const { body: run, response } = await poll(provider, id, async () => {
414
+ const current = await raw.request("GET", `/research/${id}`, {
340
415
  query: { include_usage: true },
341
416
  signal: call.signal
342
- }));
343
- if (current.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
417
+ });
418
+ const parsed = z.parse(ResearchRun, current);
419
+ if (parsed.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
344
420
  cause: current,
345
421
  provider
346
422
  });
347
- return current.status === "completed" ? current : void 0;
423
+ return parsed.status === "completed" ? {
424
+ body: parsed,
425
+ response: current
426
+ } : void 0;
348
427
  }, {
349
428
  ...call,
350
429
  interval: o.interval
351
430
  });
352
431
  const { content } = run;
353
432
  if (content === void 0 || content === null || content === "") throw new FieldworkError("JobFailed", `tavily research ${id} finished without output`, {
354
- cause: run,
433
+ cause: response,
355
434
  jobId: id,
356
435
  provider
357
436
  });
358
437
  return compact({
359
438
  id,
360
- meta: meta({
361
- credits: record(run.usage).credits,
362
- requestId: run.request_id,
363
- units: { responseTimeSeconds: run.response_time }
364
- }),
365
- output: content,
366
- raw: run,
367
- sources: list(run.sources).flatMap((item) => {
368
- const source = record(item);
369
- const url = text(source.url);
370
- return url ? [compact({
371
- title: text(source.title),
372
- url
373
- })] : [];
439
+ meta: responseMeta(run),
440
+ output: await checkOutput(o.schema, content, {
441
+ jobId: id,
442
+ provider
374
443
  }),
444
+ raw: response,
445
+ sources: run.sources.flatMap((source) => source.url === void 0 ? [] : [compact({
446
+ title: source.title,
447
+ url: source.url
448
+ })]),
375
449
  status: "completed"
376
450
  });
377
451
  },
378
452
  async search(query, options) {
379
453
  const { call, rest: o } = callSettings(options);
380
- const response = record(await raw.request("POST", "/search", {
454
+ const response = await raw.request("POST", "/search", {
381
455
  ...call,
382
456
  body: searchBody(query, o)
383
- }));
457
+ });
458
+ const body = z.parse(SearchResponse, response);
384
459
  return compact({
385
- answer: text(response.answer),
386
- images: imageResults(response.images),
387
- meta: responseMeta(response),
460
+ answer: body.answer,
461
+ images: imageResults(body.images),
462
+ meta: responseMeta(body),
388
463
  raw: response,
389
- results: searchResults(response)
464
+ results: searchResults(body)
390
465
  });
391
466
  },
392
467
  async usage(options) {
393
468
  const { call } = callSettings(options);
394
- const response = record(await raw.request("GET", "/usage", call));
395
- const key = record(response.key);
396
- const account = record(response.account);
469
+ const response = await raw.request("GET", "/usage", call);
470
+ const { account, key } = z.parse(UsageResponse, response);
397
471
  const breakdown = Object.fromEntries(Object.entries({
398
472
  crawl: account.crawl_usage,
399
473
  extract: account.extract_usage,
@@ -402,12 +476,12 @@ const tavily = (config = {}) => {
402
476
  paygo: account.paygo_usage,
403
477
  research: account.research_usage,
404
478
  search: account.search_usage
405
- }).filter((entry) => num(entry[1]) !== void 0));
479
+ }).filter((entry) => entry[1] !== void 0));
406
480
  return compact({
407
481
  breakdown: Object.keys(breakdown).length > 0 ? breakdown : void 0,
408
- limit: num(account.plan_limit),
482
+ limit: account.plan_limit,
409
483
  raw: response,
410
- used: num(account.plan_usage)
484
+ used: account.plan_usage
411
485
  });
412
486
  }
413
487
  },
package/dist/tools.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-B3x3cxDJ.js";
2
- import { A as JsonSchema, f as CallOptions, n as AnyAdapter, p as Capability } from "./adapter-DGehHCMo.js";
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";
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
@@ -0,0 +1 @@
1
+ import "zod/mini";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
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.",
5
5
  "keywords": [
6
6
  "agents",
@@ -79,6 +79,9 @@
79
79
  "publishConfig": {
80
80
  "access": "public"
81
81
  },
82
+ "dependencies": {
83
+ "zod": "^4.6.7"
84
+ },
82
85
  "devDependencies": {
83
86
  "@howells/lint": "^3.9.1",
84
87
  "@howells/typescript-config": "^0.1.8",