@howells/fieldwork-sdk 0.5.0 → 0.5.2

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,7 +1,8 @@
1
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, D as segment, E as requireKey, M as hours, N as meta, O as callSettings, S as withOriginal, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as compact, m as optionalScalar, n as anything, r as arrayOf, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
4
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.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-BY3R0oWO.js";
4
+ import { t as runJob } from "./job-DVsmQMKP.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.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. */
@@ -40,32 +41,39 @@ const COUNTRIES = new Map(`
40
41
  `.split(",").map((entry) => entry.trim()).map((entry) => [entry.slice(0, 2), entry.slice(3)]));
41
42
  // src/adapters/tavily/parse.ts
42
43
  const provider = "tavily";
44
+ /** The file names `research` takes. */
43
45
  const RESEARCH_FILE = /\.(?:txt|md|json)$/iu;
46
+ /** The passages in Tavily's text, which arrives as one string joined with `[...]`. Undefined when there are none. */
44
47
  const chunks = (content) => {
45
48
  if (content === void 0) return;
46
49
  const parts = content.split(/\s*\[\.\.\.\]\s*/u).map((part) => part.trim()).filter((part) => part !== "");
47
50
  return parts.length > 0 ? parts : void 0;
48
51
  };
52
+ /** Tavily's name for a country code, since Tavily takes names. Throws for a topic other than `general` and for a code Tavily does not list. */
49
53
  const countryName = (code, topic) => {
50
54
  if (topic !== void 0 && topic !== "general") throw invalidRequest(provider, `country only works with topic "general", not "${topic}"`);
51
55
  const name = COUNTRIES.get(code.toUpperCase());
52
56
  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
57
  return name;
54
58
  };
59
+ /** The images that parsed; undefined when there are none. */
55
60
  const imageResults = (images) => {
56
61
  const items = images.filter((item) => item !== void 0);
57
62
  return items.length > 0 ? items : void 0;
58
63
  };
64
+ /** The credits, request id and response time Tavily reports. */
59
65
  const responseMeta = (body) => meta({
60
66
  credits: body.usage.credits,
61
67
  requestId: body.request_id,
62
68
  units: { responseTimeSeconds: body.response_time }
63
69
  });
70
+ /** Refuses filters that need another option, or a depth that lacks them. */
64
71
  const checkFilters = (o) => {
65
72
  if (o.includeDomainsMode !== void 0 && (o.includeDomains?.length ?? 0) === 0) throw invalidRequest(provider, "includeDomainsMode needs includeDomains");
66
73
  if (o.filterByLanguage === true && o.language === void 0) throw invalidRequest(provider, "filterByLanguage needs language");
67
74
  if (o.safeSearch === true && (o.searchDepth === "fast" || o.searchDepth === "ultra-fast")) throw invalidRequest(provider, `safeSearch is not available with searchDepth "${o.searchDepth}"`);
68
75
  };
76
+ /** Refuses option combinations Tavily does not accept, and returns `maxAge` in whole hours. */
69
77
  const checkSearch = (o) => {
70
78
  checkFilters(o);
71
79
  if (o.chunksPerSource !== void 0 && o.searchDepth === "ultra-fast") throw invalidRequest(provider, "chunksPerSource is not available with searchDepth \"ultra-fast\"");
@@ -74,10 +82,15 @@ const checkSearch = (o) => {
74
82
  if (maxAgeHours !== void 0 && maxAgeHours > 720) throw invalidRequest(provider, "keeps cached copies for at most 30 days (2,592,000 seconds)");
75
83
  return maxAgeHours;
76
84
  };
85
+ /** Tavily's `include_raw_content`: `true` asks for Markdown, `false` for none. */
77
86
  const rawContent = (content) => {
78
87
  if (content === true) return "markdown";
79
88
  return content === false ? void 0 : content;
80
89
  };
90
+ /**
91
+ * The `/search` body. It always asks for usage, so credits are reported, and
92
+ * asks for each result's published date whenever a date window or `recency` is set.
93
+ */
81
94
  const searchBody = (query, o) => {
82
95
  const maxAgeHours = checkSearch(o);
83
96
  const dated = o.recency !== void 0 || o.publishedAfter !== void 0 || o.publishedBefore !== void 0;
@@ -109,6 +122,7 @@ const searchBody = (query, o) => {
109
122
  topic: o.topic
110
123
  });
111
124
  };
125
+ /** Search results: Tavily's `content` (passages) is the `snippet`, its `raw_content` (page text) the `content`. */
112
126
  const searchResults = (body) => body.results.map((result) => compact({
113
127
  content: result.raw_content,
114
128
  favicon: result.favicon,
@@ -118,10 +132,16 @@ const searchResults = (body) => body.results.map((result) => compact({
118
132
  title: result.title,
119
133
  url: result.url ?? ""
120
134
  }));
135
+ /** The URLs Tavily could not read. An entry without a URL is dropped. */
121
136
  const failures = (failed) => failed.flatMap((failure) => failure.url === void 0 ? [] : [{
122
137
  error: failure.error ?? "no content returned",
123
138
  url: failure.url
124
139
  }]);
140
+ /**
141
+ * A page from `/extract` or `/crawl`. When `query` is true, passages were asked
142
+ * for (a `query` on read, `instructions` on crawl) and the text goes to
143
+ * `excerpts`; otherwise it is the page's `markdown`.
144
+ */
125
145
  const page = (entry, query) => {
126
146
  const result = entry.value;
127
147
  return compact({
@@ -133,6 +153,7 @@ const page = (entry, query) => {
133
153
  url: result.url ?? ""
134
154
  });
135
155
  };
156
+ /** The `/extract` body for one or more URLs. `chunksPerSource` needs a `query`. */
136
157
  const extractBody = (urls, o) => {
137
158
  if (o.chunksPerSource !== void 0 && o.query === void 0) throw invalidRequest(provider, "chunksPerSource needs query");
138
159
  return compact({
@@ -147,6 +168,7 @@ const extractBody = (urls, o) => {
147
168
  urls
148
169
  });
149
170
  };
171
+ /** The body fields `map` and `crawl` share. */
150
172
  const traversal = (o) => compact({
151
173
  allow_external: o.allowExternal,
152
174
  exclude_domains: o.excludeDomainPatterns,
@@ -160,6 +182,7 @@ const traversal = (o) => compact({
160
182
  select_paths: o.selectPathPatterns,
161
183
  timeout: o.serverTimeout
162
184
  });
185
+ /** Base64 of the bytes, encoded in 32 KiB steps so a large file does not exceed the argument limit of `fromCodePoint`. */
163
186
  const base64 = (bytes) => {
164
187
  let binary = "";
165
188
  for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCodePoint(...bytes.subarray(index, index + 32768));
@@ -181,6 +204,7 @@ const Image = z.union([z.pipe(z.string(), z.transform((url) => url === "" ? void
181
204
  description: image.description,
182
205
  url: image.url
183
206
  })))]);
207
+ /** A search result. `content` holds Tavily's passages and `raw_content` the page text. */
184
208
  const SearchResult = looseObject({
185
209
  content: optionalString,
186
210
  favicon: optionalString,
@@ -197,12 +221,14 @@ const SearchResponse = looseObject({
197
221
  images: arrayOf(Image),
198
222
  results: arrayOf(SearchResult)
199
223
  });
224
+ /** A page from `/extract` or `/crawl`. `raw_content` is the page text, or passages when a query or instructions were given. */
200
225
  const PageResult = looseObject({
201
226
  favicon: optionalString,
202
227
  images: arrayOf(z.string()),
203
228
  raw_content: optionalString,
204
229
  url: optionalString
205
230
  });
231
+ /** A URL Tavily could not read, with its reason. */
206
232
  const FailedResult = looseObject({
207
233
  error: optionalString,
208
234
  url: optionalString
@@ -399,58 +425,59 @@ const tavily = (config = {}) => {
399
425
  };
400
426
  });
401
427
  if (files && files.length > 5) throw invalidRequest(provider, "research takes up to 5 files");
402
- const id = o.resume ?? requireJobId("tavily", z.parse(ResearchStart, await raw.request("POST", "/research", {
403
- creates: true,
404
- ...call,
405
- body: compact({
406
- citation_format: o.citationFormat,
407
- exclude_domains: o.excludeDomains,
408
- files,
409
- include_domains: o.includeDomains,
410
- input: question,
411
- model: o.model,
412
- output_length: o.outputLength,
413
- output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
414
- stream: false
415
- })
416
- })).request_id);
417
- const { body: run, response } = await poll(provider, id, async (request) => {
418
- const current = await raw.request("GET", `/research/${segment(id)}`, {
419
- ...request,
420
- query: { include_usage: true }
421
- });
422
- const parsed = z.parse(ResearchRun, current);
423
- if (parsed.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
424
- cause: current,
425
- provider
426
- });
427
- return parsed.status === "completed" ? {
428
- body: parsed,
429
- response: current
430
- } : void 0;
428
+ return await runJob(provider, {
429
+ check: async (id, request) => {
430
+ const current = await raw.request("GET", `/research/${segment(id)}`, {
431
+ ...request,
432
+ query: { include_usage: true }
433
+ });
434
+ const parsed = z.parse(ResearchRun, current);
435
+ if (parsed.status === "failed") throw new FieldworkError("JobFailed", `tavily research ${id} failed`, {
436
+ cause: current,
437
+ provider
438
+ });
439
+ return parsed.status === "completed" ? {
440
+ body: parsed,
441
+ response: current
442
+ } : void 0;
443
+ },
444
+ finish: async ({ body: run, response }, id) => {
445
+ const { content } = run;
446
+ if (content === void 0 || content === null || content === "") throw new FieldworkError("JobFailed", `tavily research ${id} finished without output`, {
447
+ cause: response,
448
+ provider
449
+ });
450
+ return compact({
451
+ id,
452
+ meta: responseMeta(run),
453
+ output: await checkOutput(o.schema, content, { provider }),
454
+ raw: response,
455
+ sources: run.sources.flatMap((source) => source.url === void 0 ? [] : [compact({
456
+ title: source.title,
457
+ url: source.url
458
+ })]),
459
+ status: "completed"
460
+ });
461
+ },
462
+ start: async () => requireJobId(provider, z.parse(ResearchStart, await raw.request("POST", "/research", {
463
+ creates: true,
464
+ ...call,
465
+ body: compact({
466
+ citation_format: o.citationFormat,
467
+ exclude_domains: o.excludeDomains,
468
+ files,
469
+ include_domains: o.includeDomains,
470
+ input: question,
471
+ model: o.model,
472
+ output_length: o.outputLength,
473
+ output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
474
+ stream: false
475
+ })
476
+ })).request_id)
431
477
  }, {
432
478
  ...call,
433
- interval: o.interval
434
- });
435
- const { content } = run;
436
- if (content === void 0 || content === null || content === "") throw new FieldworkError("JobFailed", `tavily research ${id} finished without output`, {
437
- cause: response,
438
- jobId: id,
439
- provider
440
- });
441
- return compact({
442
- id,
443
- meta: responseMeta(run),
444
- output: await checkOutput(o.schema, content, {
445
- jobId: id,
446
- provider
447
- }),
448
- raw: response,
449
- sources: run.sources.flatMap((source) => source.url === void 0 ? [] : [compact({
450
- title: source.title,
451
- url: source.url
452
- })]),
453
- status: "completed"
479
+ interval: o.interval,
480
+ resume: o.resume
454
481
  });
455
482
  },
456
483
  async search(query, options) {
package/dist/tools.d.ts CHANGED
@@ -1,21 +1,11 @@
1
- import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-CXNIcqSN.js";
2
- import { M as JsonSchema, m as Capability, n as AnyAdapter, p as CallOptions } from "./adapter-BgdfLBs-.js";
3
- /**
4
- * The JSON values that cross the tool boundary: what a model sends in, what a
5
- * tool sends back. Tools take and return these types, and the guards below are
6
- * the one place untyped data becomes one of them.
7
- */
1
+ import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-CseCD_-H.js";
2
+ import { M as JsonSchema, m as Capability, n as AnyAdapter, p as CallOptions } from "./adapter-BhTK51Yj.js";
3
+ /** Any JSON value. */
8
4
  type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
5
+ /** A JSON object. A key may be undefined, which reads as absent and is not serialized. */
9
6
  interface JsonObject {
10
7
  [key: string]: JsonValue | undefined;
11
8
  }
12
- /**
13
- * Tool definitions for agents, built from a Fieldwork instance. Each tool's
14
- * input schema lists only the options its provider supports, so a model is
15
- * never offered an option that would be ignored. The definitions are plain
16
- * JSON Schema with MCP-style annotations, so they work with the AI SDK, MCP
17
- * servers and any framework that accepts JSON Schema tools.
18
- */
19
9
  /** What a model sends a tool: a parsed JSON value, which must be an object. */
20
10
  export type ToolInput = JsonValue;
21
11
  /** The arguments a tool accepts, once they are known to be an object. */
@@ -31,13 +21,14 @@ export interface ToolAnnotations {
31
21
  destructiveHint: boolean;
32
22
  /** True when repeating a call with the same input has no further effect. */
33
23
  idempotentHint: boolean;
34
- /** True when the tool reaches the open web. */
24
+ /** True when the tool reaches outside Fieldwork. `toolsFor` sets it on every tool. */
35
25
  openWorldHint: boolean;
36
26
  }
37
27
  /** One agent tool, ready to register with an MCP server or a model's tool API. */
38
28
  export interface FieldworkTool {
39
29
  /** A verb_noun name, such as `search_web`. */
40
30
  name: string;
31
+ /** The capability this tool calls on the instance. */
41
32
  capability: Capability;
42
33
  /** For a group capability, the method this tool calls, such as `create` for `monitor`. */
43
34
  method?: string;
@@ -53,7 +44,8 @@ export interface FieldworkTool {
53
44
  /**
54
45
  * Checks the input against `inputSchema`, calls the capability and returns
55
46
  * the result shaped for a model: without the provider's `raw` response and
56
- * with long text cut to the `maxCharacters` budget. Throws a
47
+ * with long text cut to the `maxCharacters` budget. `options` are the call's
48
+ * `signal`, `timeout` and `retries`, passed through. Throws a
57
49
  * `FieldworkError`; bad input is `InvalidRequest`.
58
50
  */
59
51
  execute: (input: ToolInput, options?: CallOptions) => Promise<ToolOutput>;
@@ -83,11 +75,17 @@ export interface ToolsOptions {
83
75
  */
84
76
  maxCharacters?: number;
85
77
  }
86
- /** Makes one tool per capability, or per method of a group, the instance supports. */
78
+ /**
79
+ * Makes one tool per capability, or per method of a group, the instance
80
+ * supports, in the order of `SPECS`. A router gives each tool the inputs of
81
+ * the provider that serves its capability, and `provider` names it.
82
+ */
87
83
  export declare const toolsFor: (web: Fieldwork<AnyAdapter>, options?: ToolsOptions) => FieldworkTool[];
88
84
  /**
89
85
  * An error as a model or an MCP client should see it: the code, the message
90
- * and what to do next, without the provider's response.
86
+ * and what to do next (`retryable`, `retryAfter`, `jobId`), without the
87
+ * provider's response. An error that is not a `FieldworkError` becomes a
88
+ * `ProviderError` that is not retryable.
91
89
  */
92
90
  export declare const toolError: (cause: unknown) => {
93
91
  code: FieldworkErrorCode;