@howells/fieldwork-sdk 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Fieldwork
2
2
 
3
- One API for searching the web, reading pages, extracting values, walking sites, answering and researching questions, finding entities, watching for changes, driving a browser and parsing documents, across Exa, Firecrawl, Tavily, Parallel, Perplexity, Brave, SerpApi, Browserbase, LlamaParse and Reducto.
3
+ One API for searching the web, reading pages, extracting values, walking sites, answering and researching questions, finding entities, watching for changes, driving a browser and parsing documents, across Exa, Firecrawl, Tavily, Parallel, Perplexity, Brave, SerpApi, Browserbase, Kernel, LlamaParse and Reducto.
4
4
 
5
5
  ```sh
6
6
  npm i @howells/fieldwork-sdk
@@ -24,25 +24,25 @@ Swap the adapter to switch providers. Everything below the constructor stays the
24
24
 
25
25
  Each instance has only the methods its provider offers, so a call the provider cannot serve does not compile. `new Fieldwork({ adapter: tavily() }).act(...)` is a type error, because Tavily has no browser. Untyped JavaScript gets a `FieldworkError` with code `Unsupported`, and no request is sent. Nothing falls back to another provider, and nothing is emulated: a provider without an answer endpoint has no `answer`, even though search plus a model could imitate one.
26
26
 
27
- | Method | Exa | Firecrawl | Tavily | Parallel | Perplexity | Brave | SerpApi | Browserbase | LlamaParse | Reducto |
28
- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
29
- | `search(query)` | yes | yes | yes | yes | yes | yes | yes | yes | | |
30
- | `images(query)` | | yes | yes | yes | | yes | yes | | | |
31
- | `read(url)` | yes | yes | yes | yes | | | | yes | | |
32
- | `readMany(urls)` | yes | yes | yes | yes | | | | | | |
33
- | `extract(url, { schema })` | yes | yes | | yes | | | | | | |
34
- | `product(url)` | | yes | | | | | | | | |
35
- | `map(url)` | | yes | yes | | | | | | | |
36
- | `crawl(url)` | | yes | yes | | | | | | | |
37
- | `answer(question)` | yes | | yes | yes | yes | yes | | | | |
38
- | `research(question)` | yes | yes | yes | yes | yes | | | | | |
39
- | `discover(objective, { entityType, conditions })` | | | | yes | | | | | | |
40
- | `decide(context, questions)` | | | | yes | yes | | | | | |
41
- | `act(code)` | | yes | | | | | | | | |
42
- | `browser.open()`, `browser.close(id)` | | yes | | | | | | yes | | |
43
- | `parse(document)` | | yes | | | | | | | yes | yes |
44
- | `monitor.create()`, `.get`, `.list`, `.delete`, `.events` | yes | yes | | yes | | | | | | |
45
- | `usage()` | | yes | yes | | | | yes | yes | | |
27
+ | Method | Exa | Firecrawl | Tavily | Parallel | Perplexity | Brave | SerpApi | Browserbase | Kernel | LlamaParse | Reducto |
28
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
29
+ | `search(query)` | yes | yes | yes | yes | yes | yes | yes | yes | | | |
30
+ | `images(query)` | | yes | yes | yes | | yes | yes | | | | |
31
+ | `read(url)` | yes | yes | yes | yes | | | | yes | yes | | |
32
+ | `readMany(urls)` | yes | yes | yes | yes | | | | | | | |
33
+ | `extract(url, { schema })` | yes | yes | | yes | | | | | | | |
34
+ | `product(url)` | | yes | | | | | | | | | |
35
+ | `map(url)` | | yes | yes | | | | | | | | |
36
+ | `crawl(url)` | | yes | yes | | | | | | | | |
37
+ | `answer(question)` | yes | | yes | yes | yes | yes | | | | | |
38
+ | `research(question)` | yes | yes | yes | yes | yes | | | | | | |
39
+ | `discover(objective, { entityType, conditions })` | | | | yes | | | | | | | |
40
+ | `decide(context, questions)` | | | | yes | yes | | | | | | |
41
+ | `act(code)` | | yes | | | | | | | | | |
42
+ | `browser.open()`, `browser.close(id)` | | yes | | | | | | yes | yes | | |
43
+ | `parse(document)` | | yes | | | | | | | | yes | yes |
44
+ | `monitor.create()`, `.get`, `.list`, `.delete`, `.events` | yes | yes | | yes | | | | | | | |
45
+ | `usage()` | | yes | yes | | | | yes | yes | | | |
46
46
 
47
47
  `web.capabilities` and `web.supports("crawl")` report the same table at runtime.
48
48
 
@@ -110,7 +110,7 @@ A job that stopped early but produced output, for example on a credit or step li
110
110
 
111
111
  ### Long jobs
112
112
 
113
- Research, discovery, crawls, batch reads, Parallel extraction and LlamaParse and Reducto parses are polled until they finish. Pass `timeout` and `signal` to bound or cancel any call.
113
+ Research, discovery, crawls, batch reads, Parallel extraction and LlamaParse and Reducto parses are polled until they finish. A job status the provider does not document throws `ProviderError` with `jobId` at once, instead of polling until the timeout. Pass `timeout` and `signal` to bound or cancel any call.
114
114
 
115
115
  When a job outlasts `timeout`, or `signal` stops the wait, the provider keeps running it and charging for it. The error carries the job's id as `jobId`; pass it back as `resume` to collect the result instead of starting another job:
116
116
 
@@ -191,11 +191,11 @@ Every failure is a `FieldworkError`. It carries:
191
191
  | `NotFound` | The page, product or job does not exist. | Check the URL or id. |
192
192
  | `InvalidRequest` | The input was refused, by Fieldwork or by the provider. | Correct the input; the message says what is wrong. |
193
193
  | `JobFailed` | The job ended without a result. | Start a new job if needed; resuming fails again. |
194
- | `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat. |
194
+ | `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat when `retryable` is true. |
195
195
  | `Aborted` | `signal` cancelled the call. | With `jobId`, the job may still be running; pass it as `resume`. |
196
196
  | `ProviderError` | Any other provider failure. | Repeat when `retryable` is true (5xx and network failures). |
197
197
 
198
- An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job.
198
+ An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job. Nor is a failure, other than a rate limit, of the request that starts a job, session or monitor: the provider may already have started it, so check before repeating.
199
199
 
200
200
  ### Retries
201
201
 
@@ -265,9 +265,10 @@ On a router, `raw` is keyed by provider name.
265
265
  | `brave()` | `BRAVE_API_KEY` |
266
266
  | `serpapi()` | `SERPAPI_API_KEY` |
267
267
  | `browserbase()` | `BROWSERBASE_API_KEY` |
268
+ | `kernel()` | `KERNEL_API_KEY` |
268
269
  | `llamaparse()` | `LLAMA_CLOUD_API_KEY` |
269
270
  | `reducto()` | `REDUCTO_API_KEY` |
270
271
 
271
272
  Pass `apiKey` (and Browserbase's `projectId`) to override, and `fetch` to supply your own. Requests follow redirects only within the provider's origin; a redirect to any other host, scheme or port fails before the key is sent there.
272
273
 
273
- ESM only, Node 22 or later. The one dependency is Zod.
274
+ ESM only, Node 22 or later. The dependencies are Zod and, for Kernel's Markdown, Turndown.
@@ -1,7 +1,3 @@
1
- /**
2
- * The shapes every adapter returns. Each result keeps the provider's own
3
- * response in `raw`, so nothing the provider sent is lost by normalizing it.
4
- */
5
1
  /** A JSON Schema object describing the values to extract. */
6
2
  type JsonSchema = Record<string, unknown>;
7
3
  /** Every capability Fieldwork knows. An adapter implements a subset. */
@@ -488,7 +484,11 @@ interface MonitorEvent {
488
484
  /** What `monitor.events` returns: one page of events. */
489
485
  interface MonitorEvents {
490
486
  events: MonitorEvent[];
491
- /** Pass as `cursor` for the next page. */
487
+ /**
488
+ * Pass as `cursor` for the next page. Absent when there are no more events.
489
+ * A provider that reports no total sets it on every full page, so the page
490
+ * it leads to can be empty.
491
+ */
492
492
  next?: string;
493
493
  raw: unknown;
494
494
  }
@@ -512,12 +512,13 @@ interface RequestOptions extends CallOptions {
512
512
  body?: unknown;
513
513
  /** A multipart body, sent as is. */
514
514
  form?: FormData;
515
+ /** Query parameters. Undefined values are left out. */
515
516
  query?: Record<string, string | number | boolean | undefined>;
516
517
  /**
517
518
  * The request creates a job, session or monitor that the provider bills for
518
519
  * or keeps. After a 5xx or a dropped connection the provider may already
519
520
  * have created it, so only a rate limit, which it has certainly not acted
520
- * on, is retried.
521
+ * on, is retried, and any other failure is thrown not `retryable`.
521
522
  */
522
523
  creates?: boolean;
523
524
  /** The endpoint answers in text, such as an event stream, so its body is returned as a string. */
@@ -531,6 +532,17 @@ interface RequestOptions extends CallOptions {
531
532
  interface RawClient {
532
533
  readonly provider: string;
533
534
  readonly baseUrl: string;
535
+ /**
536
+ * Sends a request and returns the response body: its JSON as `T`, which the
537
+ * caller asserts and the client does not check (an empty body is undefined),
538
+ * or a string when `options.text` is set. Retries as `CallOptions.retries`
539
+ * says.
540
+ *
541
+ * Throws `FieldworkError`: from the status for an error response, and
542
+ * `ProviderError` for a success whose body is not JSON, for a connection that
543
+ * failed, and for a redirect to another origin. A stopped call is `Timeout` or
544
+ * `Aborted`.
545
+ */
534
546
  request: <T = unknown>(method: string, path: string, options?: RequestOptions) => Promise<T>;
535
547
  }
536
548
  type Method = (...args: never[]) => Promise<unknown>;
@@ -545,7 +557,9 @@ type Operations = Partial<Record<Capability, Method | Readonly<Record<string, Me
545
557
  * so a capability or option the provider lacks cannot be called.
546
558
  */
547
559
  interface Adapter<Name extends string = string, Ops extends Operations = Operations, Raw = RawClient> {
560
+ /** The provider's name, such as "exa"; "router" for a router. It becomes `Fieldwork.provider`. */
548
561
  readonly name: Name;
562
+ /** The capabilities the provider offers. Their absence is what makes `Fieldwork` refuse a call with `Unsupported`. */
549
563
  readonly operations: Ops;
550
564
  /** The provider's HTTP API, for anything Fieldwork does not wrap. */
551
565
  readonly raw: Raw;
package/dist/brave.d.ts CHANGED
@@ -1,13 +1,16 @@
1
- import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, t as Adapter } from "./adapter-BgdfLBs-.js";
1
+ import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, t as Adapter } from "./adapter-Bh8EIrNe.js";
2
+ /** Settings for `brave()`. */
2
3
  interface BraveConfig {
3
4
  /** Defaults to the BRAVE_API_KEY environment variable. */
4
5
  apiKey?: string;
5
6
  /** Defaults to https://api.search.brave.com/res/v1. */
6
7
  baseUrl?: string;
8
+ /** Used in place of the global `fetch`. */
7
9
  fetch?: typeof fetch;
8
10
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
11
  retries?: number;
10
12
  }
13
+ /** Brave's safe search levels, from "off" to the strictest. */
11
14
  type BraveSafeSearch = "off" | "moderate" | "strict";
12
15
  /** Brave's named freshness windows start at a day; it has no hour window. */
13
16
  type BraveRecency = Exclude<Recency, "hour">;
@@ -31,12 +34,15 @@ interface BraveSearchBase extends CallOptions {
31
34
  publishedAfter?: string;
32
35
  /** YYYY-MM-DD. Needs `publishedAfter`. Not combinable with `recency`. */
33
36
  publishedBefore?: string;
34
- /** Web and news default to "moderate"; Brave's news default is "strict". */
37
+ /** Left unset, Brave applies its own default for the endpoint. */
35
38
  safesearch?: BraveSafeSearch;
36
39
  }
37
40
  /** Result types web search can return besides web results. */
38
41
  type BraveResultType = "web" | "news" | "videos" | "discussions" | "locations";
39
- /** `/web/search`: web results, plus news, videos, discussions and locations. */
42
+ /**
43
+ * `/web/search`: web results, plus news, videos, discussions and locations. This
44
+ * is the default search, so `vertical` may be left out.
45
+ */
40
46
  interface BraveWebSearchOptions extends BraveSearchBase {
41
47
  vertical?: "web";
42
48
  content?: false;
@@ -106,7 +112,8 @@ interface BraveVideoSearchOptions extends BraveSearchBase {
106
112
  }
107
113
  /**
108
114
  * `/llm/context`: Brave fetches each result and returns the passages of its
109
- * text that fit the query, as `content`.
115
+ * text that fit the query, as `content`. `limit` is sent as both `count` and
116
+ * `maximum_number_of_urls`.
110
117
  */
111
118
  interface BraveContentSearchOptions extends BraveSearchBase {
112
119
  content: true;
@@ -129,7 +136,13 @@ interface BraveContentSearchOptions extends BraveSearchBase {
129
136
  operators?: boolean;
130
137
  goggles?: string | string[];
131
138
  }
139
+ /**
140
+ * The options of `search`. `content: true` selects the LLM context endpoint;
141
+ * otherwise `vertical` picks web (the default), news or videos. An option the
142
+ * chosen endpoint does not take is refused before sending.
143
+ */
132
144
  type BraveSearchOptions = BraveWebSearchOptions | BraveNewsSearchOptions | BraveVideoSearchOptions | BraveContentSearchOptions;
145
+ /** Options for `images` (`/images/search`). Images take no recency or date filter. */
133
146
  interface BraveImageOptions extends CallOptions {
134
147
  /** Images to return, 1 to 200 (Brave's default is 50). Brave has no paging. */
135
148
  limit?: number;
@@ -139,6 +152,10 @@ interface BraveImageOptions extends CallOptions {
139
152
  safesearch?: "off" | "strict";
140
153
  spellcheck?: boolean;
141
154
  }
155
+ /**
156
+ * Options for `answer` (`POST /chat/completions`). The answer is always streamed,
157
+ * because Brave returns citations only on a stream.
158
+ */
142
159
  interface BraveAnswerOptions extends CallOptions {
143
160
  /** Brave's answer model; "brave-pro" is its default. */
144
161
  model?: "brave" | "brave-pro";
@@ -157,6 +174,7 @@ interface BraveAnswerOptions extends CallOptions {
157
174
  timezone?: string;
158
175
  };
159
176
  }
177
+ /** What Brave offers: search, images and answer. */
160
178
  interface BraveOperations {
161
179
  search: (query: string, options?: BraveSearchOptions) => Promise<SearchResponse>;
162
180
  images: (query: string, options?: BraveImageOptions) => Promise<ImageSearch>;
package/dist/brave.js CHANGED
@@ -1,6 +1,6 @@
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, F as parseJson, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf, z as refuseTogether } from "./parse-n8MmaK1x.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
+ import { C as createRawClient, F as parseJson, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf, z as refuseTogether } from "./parse-COHKvfH9.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/brave/response.ts
6
6
  /** The `query` block every search response carries. */
@@ -27,6 +27,7 @@ const Result = looseObject({
27
27
  title: optionalString,
28
28
  url: optionalString
29
29
  });
30
+ /** A section of a web search response: its `results`. */
30
31
  const Section = looseObject({ results: arrayOf(Result) });
31
32
  /** `/web/search`: the sections are each optional in what Brave sends. */
32
33
  const WebSearchResponse = looseObject({
@@ -42,6 +43,7 @@ const VerticalSearchResponse = looseObject({
42
43
  query: Query,
43
44
  results: arrayOf(Result)
44
45
  });
46
+ /** One image result: `url` is the source page and `properties.url` the image. */
45
47
  const ImageItem = looseObject({
46
48
  properties: looseObject({
47
49
  height: optionalNumber,
@@ -57,12 +59,17 @@ const ImageSearchResponse = looseObject({
57
59
  query: Query,
58
60
  results: arrayOf(ImageItem)
59
61
  });
62
+ /**
63
+ * A grounding item of an LLM context response; `snippets` are the passages Brave
64
+ * chose from the page.
65
+ */
60
66
  const ContextItem = looseObject({
61
67
  name: optionalString,
62
68
  snippets: arrayOf(nonEmptyString),
63
69
  title: optionalString,
64
70
  url: optionalString
65
71
  });
72
+ /** The metadata of a grounding source, keyed by URL in `sources`. */
66
73
  const ContextSource = looseObject({
67
74
  description: optionalString,
68
75
  favicon: optionalString,
@@ -78,6 +85,7 @@ const ContextResponse = looseObject({
78
85
  }),
79
86
  sources: recordOf(ContextSource)
80
87
  });
88
+ /** One choice of a chat completion: `message` when sent whole, `delta` when streamed. */
81
89
  const Choice = looseObject({
82
90
  delta: looseObject({ content: optionalString }),
83
91
  message: looseObject({ content: optionalString })
@@ -98,13 +106,16 @@ const UsageTag = looseObject({
98
106
  "X-Request-Total-Cost": optionalNumber
99
107
  });
100
108
  // src/adapters/brave/parse.ts
109
+ /** The name this adapter reports in errors and results. */
101
110
  const provider = "brave";
111
+ /** Brave's `freshness` codes: past day, week, month and year. */
102
112
  const FRESHNESS = {
103
113
  day: "pd",
104
114
  month: "pm",
105
115
  week: "pw",
106
116
  year: "py"
107
117
  };
118
+ /** The options every search endpoint takes (`BraveSearchBase`). */
108
119
  const SHARED = [
109
120
  "limit",
110
121
  "country",
@@ -129,6 +140,7 @@ const ALLOWED = {
129
140
  news: [
130
141
  ...SHARED,
131
142
  "vertical",
143
+ "content",
132
144
  "offset",
133
145
  "extraSnippets",
134
146
  "spellcheck",
@@ -139,6 +151,7 @@ const ALLOWED = {
139
151
  videos: [
140
152
  ...SHARED,
141
153
  "vertical",
154
+ "content",
142
155
  "offset",
143
156
  "spellcheck",
144
157
  "uiLanguage",
@@ -159,17 +172,33 @@ const ALLOWED = {
159
172
  "textDecorations"
160
173
  ]
161
174
  };
175
+ /**
176
+ * The endpoint for a search: `content: true` is the LLM context endpoint; otherwise
177
+ * `vertical` picks web (the default), news or videos. Any other `vertical`, which
178
+ * only an untyped caller can pass, is refused.
179
+ */
162
180
  const modeOf = (o) => {
163
181
  if (o.content === true) return "context";
164
182
  if (o.vertical === void 0 || o.vertical === "web") return "web";
165
183
  if (o.vertical === "news" || o.vertical === "videos") return o.vertical;
166
184
  throw invalidRequest(provider, `has no "${o.vertical}" search; use web, news or videos`);
167
185
  };
186
+ /**
187
+ * Refuses every set option the endpoint does not take, naming all of them. An
188
+ * option set to undefined passes.
189
+ */
168
190
  const refuseUnsupported = (mode, o) => {
169
191
  const refused = Object.entries(o).filter(([name, value]) => value !== void 0 && !ALLOWED[mode].some((allowed) => allowed === name)).map(([name]) => name);
170
192
  if (refused.length > 0) throw invalidRequest(provider, `${mode} search does not accept ${refused.join(", ")}`);
171
193
  };
194
+ /** Today's date in UTC, as YYYY-MM-DD. */
172
195
  const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
196
+ /**
197
+ * Brave's `freshness` value: a code for `recency`, or `<after>to<before>` for
198
+ * dates, with `before` defaulting to today (UTC). Refuses `recency` with either
199
+ * date, `publishedBefore` without `publishedAfter`, a recency Brave has no window
200
+ * for (such as "hour") and dates that are not YYYY-MM-DD.
201
+ */
173
202
  const freshness = (o) => {
174
203
  refuseTogether(provider, o, "recency", "publishedAfter");
175
204
  refuseTogether(provider, o, "recency", "publishedBefore");
@@ -185,12 +214,20 @@ const freshness = (o) => {
185
214
  for (const date of [after, before]) if (!/^\d{4}-\d{2}-\d{2}$/u.test(date)) throw invalidRequest(provider, `dates must be YYYY-MM-DD, got "${date}"`);
186
215
  return `${after}to${before}`;
187
216
  };
217
+ /**
218
+ * The goggles as a list, so each is sent as its own `goggles` parameter. Refuses
219
+ * more than three.
220
+ */
188
221
  const gogglesOf = (value) => {
189
222
  if (value === void 0) return;
190
223
  const all = Array.isArray(value) ? value : [value];
191
224
  if (all.length > 3) throw invalidRequest(provider, "accepts at most 3 goggles per search");
192
225
  return all;
193
226
  };
227
+ /**
228
+ * The path with its parameters as a query string. Undefined parameters are left
229
+ * out and an array repeats its key.
230
+ */
194
231
  const withQuery = (path, params) => {
195
232
  const search = new URLSearchParams();
196
233
  for (const [key, value] of Object.entries(params)) {
@@ -200,14 +237,26 @@ const withQuery = (path, params) => {
200
237
  const query = search.toString();
201
238
  return query === "" ? path : `${path}?${query}`;
202
239
  };
240
+ /** Brave takes country codes in upper case. */
203
241
  const upper = (value) => value?.toUpperCase();
242
+ /** Brave takes language codes in lower case. */
204
243
  const lower = (value) => value?.toLowerCase();
244
+ /**
245
+ * Warnings from a response's `query` block: the spell-corrected query Brave
246
+ * searched, and strict safe search hiding results.
247
+ */
205
248
  const warningsOf = (query) => {
206
249
  const warnings = [];
207
250
  if (query.altered !== void 0) warnings.push(`brave searched the spell-corrected query "${query.altered}"`);
208
251
  if (query.show_strict_warning === true) warnings.push("strict safe search hid some results");
209
252
  return warnings;
210
253
  };
254
+ /**
255
+ * A web, news, video or discussion item as a result, of the given `kind`. The
256
+ * snippet is the description followed by any extra snippets, split by blank
257
+ * lines. `image` prefers the thumbnail's original over its resized `src`. An item
258
+ * with no URL is dropped.
259
+ */
211
260
  const result = (r, kind) => {
212
261
  if (r.url === void 0) return;
213
262
  const snippet = [r.description, ...r.extra_snippets].filter((s) => s !== void 0).join("\n\n");
@@ -221,6 +270,10 @@ const result = (r, kind) => {
221
270
  url: r.url
222
271
  });
223
272
  };
273
+ /**
274
+ * A `locations` item as a `place` result: its address, coordinates (Brave sends
275
+ * `[latitude, longitude]`), rating and review count.
276
+ */
224
277
  const placeResult = (r) => {
225
278
  const base = result(r, "place");
226
279
  if (!base) return;
@@ -237,7 +290,13 @@ const placeResult = (r) => {
237
290
  reviewCount: r.rating.reviewCount
238
291
  });
239
292
  };
293
+ /** The section's items through `map`, without the ones it drops. */
240
294
  const section = (items, map) => items.map((item) => map(item)).filter((item) => item !== void 0);
295
+ /**
296
+ * A grounding item as a result. The passages are the `content`; the description,
297
+ * favicon and image come from the source entry keyed by the item's URL. The title
298
+ * is the item's `title`, then its `name`, then the source's.
299
+ */
241
300
  const contextResult = (r, kind, sources) => {
242
301
  if (r.url === void 0) return;
243
302
  const source = sources[r.url];
@@ -251,6 +310,10 @@ const contextResult = (r, kind, sources) => {
251
310
  url: r.url
252
311
  });
253
312
  };
313
+ /**
314
+ * The results of an LLM context response: generic items as `web`, and the `poi`
315
+ * and `map` items as `place`.
316
+ */
254
317
  const parseContext = ({ grounding, sources }) => [
255
318
  ...grounding.generic.map((item) => contextResult(item, "web", sources)),
256
319
  contextResult(grounding.poi, "place", sources),
@@ -275,7 +338,9 @@ const completionText = (completion) => {
275
338
  const [choice] = completion.choices;
276
339
  return choice?.message.content ?? choice?.delta.content ?? "";
277
340
  };
341
+ /** Brave's inline `<citation>` tag in answer text; `body` captures its JSON. */
278
342
  const CITATION_TAG = /<citation>(?<body>[\s\S]*?)<\/citation>/gu;
343
+ /** Brave's inline `<usage>` tag in answer text; `body` captures its JSON. */
279
344
  const USAGE_TAG = /<usage>(?<body>[\s\S]*?)<\/usage>/gu;
280
345
  /** The JSON inside a tag, which Brave sometimes encodes twice, read through `schema`. */
281
346
  const parseTag = (body, schema) => {
@@ -289,6 +354,10 @@ const parseTag = (body, schema) => {
289
354
  };
290
355
  /** Every tag in the content whose body is JSON, read through `schema`. */
291
356
  const tagBodies = (content, tag, schema) => [...content.matchAll(tag)].flatMap((match) => parseTag(match.groups?.body ?? "", schema));
357
+ /**
358
+ * One citation per URL from the answer's `<citation>` tags, with each distinct
359
+ * snippet as an excerpt.
360
+ */
292
361
  const answerCitations = (content) => {
293
362
  const byUrl = /* @__PURE__ */ new Map();
294
363
  for (const item of tagBodies(content, CITATION_TAG, CitationTag)) {
@@ -1,4 +1,5 @@
1
- import { R as Page, Y as SearchResponse, a as RawClient, d as BrowserSession, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-BgdfLBs-.js";
1
+ import { R as Page, Y as SearchResponse, a as RawClient, d as BrowserSession, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-Bh8EIrNe.js";
2
+ /** Settings for `browserbase()`. */
2
3
  export interface BrowserbaseConfig {
3
4
  /** Defaults to the BROWSERBASE_API_KEY environment variable. */
4
5
  apiKey?: string;
@@ -8,7 +9,9 @@ export interface BrowserbaseConfig {
8
9
  * `usage` uses the key's only project.
9
10
  */
10
11
  projectId?: string;
12
+ /** Defaults to https://api.browserbase.com. */
11
13
  baseUrl?: string;
14
+ /** Defaults to the global `fetch`. A test passes a fake. */
12
15
  fetch?: typeof fetch;
13
16
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
14
17
  retries?: number;
@@ -21,15 +24,22 @@ export interface BrowserbaseGeolocation {
21
24
  state?: string;
22
25
  city?: string;
23
26
  }
27
+ /** Options for `read`, which fetches the page over HTTP without running a browser. */
24
28
  export interface BrowserbaseReadOptions extends CallOptions {
25
29
  /**
26
30
  * "markdown" converts the page to Markdown (`Page.markdown`). "raw" returns
27
31
  * the response body unchanged (`Page.rawHtml` for HTML). Defaults to
28
32
  * "markdown". Fetch never runs JavaScript, reads at most 5 MB and cannot
29
- * convert PDFs.
33
+ * convert PDFs. A binary response is not converted either: its Base64
34
+ * content stays in `raw`, with a warning.
30
35
  */
31
36
  format?: "markdown" | "raw";
32
- /** Follow HTTP redirects. Browserbase defaults to false. */
37
+ /**
38
+ * Follow HTTP redirects. Browserbase defaults to false, which returns the
39
+ * 3xx response itself; Fieldwork defaults to true so a read of an http, www
40
+ * or trailing-slash URL returns the page. `false` returns the redirect
41
+ * response, with a warning.
42
+ */
33
43
  allowRedirects?: boolean;
34
44
  /** Skip TLS certificate verification, for self-signed or expired certificates. */
35
45
  allowInsecureSsl?: boolean;
@@ -40,7 +50,7 @@ export interface BrowserbaseReadOptions extends CallOptions {
40
50
  proxies?: boolean | {
41
51
  geolocation?: BrowserbaseGeolocation;
42
52
  };
43
- /** ISO 3166-1 alpha-2 code. Sends the request through a proxy in that country. */
53
+ /** ISO 3166-1 alpha-2 code, upper-cased before sending. Sends the request through a proxy in that country. */
44
54
  country?: string;
45
55
  /** A context whose saved cookies are sent with the request. */
46
56
  contextId?: string;
@@ -63,6 +73,10 @@ export type BrowserbaseSearchOptions = BrowserbaseSearchBase & ({
63
73
  provider: "exa";
64
74
  mode?: "fast" | "deep-lite" | "deep";
65
75
  });
76
+ /**
77
+ * A proxy rule for a browser session: Browserbase's network, your own server,
78
+ * or no proxy. `domainPattern` limits a rule to the domains that match.
79
+ */
66
80
  export type BrowserbaseProxy = {
67
81
  type: "browserbase";
68
82
  geolocation?: BrowserbaseGeolocation;
@@ -78,6 +92,10 @@ export type BrowserbaseProxy = {
78
92
  type: "none";
79
93
  domainPattern?: string;
80
94
  };
95
+ /**
96
+ * Options for `browser.open`. The session is billed until it expires or
97
+ * `browser.close` releases it.
98
+ */
81
99
  export interface BrowserbaseOpenOptions extends CallOptions {
82
100
  region?: "us-west-2" | "us-east-1" | "eu-central-1" | "ap-southeast-1";
83
101
  /** Keep the session open after the client disconnects. Hobby plan and above. */
@@ -116,13 +134,20 @@ export interface BrowserbaseOpenOptions extends CallOptions {
116
134
  /** Tags stored with the session, searchable in the dashboard. */
117
135
  userMetadata?: Record<string, unknown>;
118
136
  }
137
+ /** What the Browserbase adapter offers. */
119
138
  export interface BrowserbaseOperations {
120
139
  search: (query: string, options?: BrowserbaseSearchOptions) => Promise<SearchResponse>;
121
140
  read: (url: string, options?: BrowserbaseReadOptions) => Promise<Page>;
122
141
  browser: {
142
+ /**
143
+ * Creates a session. A failure to get its live view URL does not fail the
144
+ * call: the session is billed already, so the result carries a warning.
145
+ */
123
146
  open: (options?: BrowserbaseOpenOptions) => Promise<BrowserSession>;
147
+ /** Asks Browserbase to release the session. */
124
148
  close: (id: string, options?: CallOptions) => Promise<void>;
125
149
  };
150
+ /** Browser minutes and proxy bytes of `projectId`, or of the key's only project. */
126
151
  usage: (options?: CallOptions) => Promise<AccountUsage>;
127
152
  }
128
153
  /**
@@ -1,6 +1,6 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { r as invalidRequest } from "./errors-Yvk42oZH.js";
3
- import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, M as compact, 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, r as arrayOf, s as optionalAnyString, z as refuseTogether } from "./parse-n8MmaK1x.js";
2
+ import { r as invalidRequest } from "./errors-DROZyb9T.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, M as compact, 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, r as arrayOf, s as optionalAnyString, z as refuseTogether } from "./parse-COHKvfH9.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/browserbase/response.ts
6
6
  /** `POST /v1/sessions`. The id keeps the value as it arrived, for the error raised when there is none. */
@@ -42,6 +42,7 @@ const UsageResponse = looseObject({
42
42
  /** `GET /v1/projects`: an array of projects. */
43
43
  const ProjectsResponse = arrayOf(looseObject({ id: withOriginal(optionalId) }));
44
44
  // src/adapters/browserbase.ts
45
+ /** The modes each search provider takes; `search` refuses any other. */
45
46
  const SEARCH_MODES = {
46
47
  exa: [
47
48
  "fast",
@@ -65,6 +66,7 @@ const browserbase = (config = {}) => {
65
66
  retries: config.retries
66
67
  });
67
68
  const { projectId } = config;
69
+ /** The `proxies` value to send: as given, or built from `country`. Refuses both together, and a state outside the US. */
68
70
  const fetchProxies = (o) => {
69
71
  refuseTogether(provider, o, "proxies", "country");
70
72
  const geolocation = o.country === void 0 ? void 0 : { country: o.country.toUpperCase() };
@@ -144,7 +146,7 @@ const browserbase = (config = {}) => {
144
146
  ...call,
145
147
  body: compact({
146
148
  allowInsecureSsl: o.allowInsecureSsl,
147
- allowRedirects: o.allowRedirects,
149
+ allowRedirects: o.allowRedirects ?? true,
148
150
  contextId: o.contextId,
149
151
  format,
150
152
  proxies: fetchProxies(o),
@@ -155,11 +157,13 @@ const browserbase = (config = {}) => {
155
157
  const { content } = body;
156
158
  const binary = body.encoding === "base64";
157
159
  const contentType = body.contentType ?? "";
160
+ const redirected = o.allowRedirects === false && body.statusCode !== void 0 && body.statusCode >= 300 && body.statusCode < 400;
161
+ const warnings = [...binary ? ["the response is binary; its Base64 content is in raw"] : [], ...redirected ? [`the page answered with a ${body.statusCode} redirect and allowRedirects is false, so nothing was followed`] : []];
158
162
  return presentPage(provider, compact({
159
163
  markdown: format === "markdown" && !binary ? content : void 0,
160
164
  meta: meta({
161
165
  requestId: body.id,
162
- warnings: binary ? ["the response is binary; its Base64 content is in raw"] : void 0
166
+ warnings: warnings.length > 0 ? warnings : void 0
163
167
  }),
164
168
  raw: response,
165
169
  rawHtml: format === "raw" && !binary && contentType.includes("html") ? content : void 0,
@@ -211,6 +215,7 @@ const browserbase = (config = {}) => {
211
215
  });
212
216
  }
213
217
  };
218
+ /** The key's project when it has exactly one; otherwise refuses rather than guess. */
214
219
  const onlyProject = async (call) => {
215
220
  const projects = z.parse(ProjectsResponse, await raw.request("GET", "/v1/projects", call));
216
221
  if (projects.length !== 1) throw invalidRequest(provider, `usage needs a project: pass projectId (this key has ${projects.length} projects)`);
@@ -1,4 +1,4 @@
1
- import { t as FieldworkError } from "./errors-Yvk42oZH.js";
1
+ import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
2
  // src/document.ts
3
3
  /** Content types of the document files parsers commonly take, by extension. */
4
4
  const MEDIA_TYPES = new Map(Object.entries({
@@ -30,9 +30,12 @@ const refuseLarger = (provider, document, maxMegabytes) => {
30
30
  const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
31
31
  if (size > maxMegabytes * 1024 * 1024) throw new FieldworkError("InvalidRequest", `${provider} parses files up to ${maxMegabytes} MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`, { provider });
32
32
  };
33
+ /** Whether the bytes sit on an ArrayBuffer rather than a SharedArrayBuffer. */
34
+ const onArrayBuffer = (bytes) => bytes.buffer instanceof ArrayBuffer;
33
35
  /** The file's bytes as a multipart part, with the content type its extension names. */
34
36
  const documentPart = (document) => {
35
- const part = document.data instanceof Uint8Array ? new Uint8Array(document.data) : document.data;
37
+ const { data } = document;
38
+ const part = data instanceof Uint8Array && !onArrayBuffer(data) ? new Uint8Array(data) : data;
36
39
  return new Blob([part], { type: mediaTypeOf(document.name) ?? "application/octet-stream" });
37
40
  };
38
41
  /** The smallest box that holds every one of `boxes`, or undefined when there are none. */
@@ -3,8 +3,11 @@
3
3
  var FieldworkError = class extends Error {
4
4
  name = "FieldworkError";
5
5
  code;
6
+ /** The provider the call was for, when the error came from one. */
6
7
  provider;
8
+ /** The HTTP status the provider answered with, when there was a response. */
7
9
  status;
10
+ /** Seconds the provider asked to wait before retrying, from its `Retry-After` header. */
8
11
  retryAfter;
9
12
  /**
10
13
  * The provider's id for an asynchronous job that was already created when
@@ -40,10 +43,16 @@ var FieldworkError = class extends Error {
40
43
  };
41
44
  }
42
45
  };
46
+ /** Rate limits, timeouts and 5xx statuses can succeed on repeat. The HTTP client still does not repeat a call whose own deadline ran out. */
43
47
  const isRetryable = (code, status) => {
44
48
  if (code === "RateLimited" || code === "Timeout") return true;
45
49
  return status !== void 0 && status >= 500;
46
50
  };
51
+ /**
52
+ * The error with the job it belongs to attached. An error that is not a
53
+ * `FieldworkError`, or that already has a `jobId`, comes back as it is.
54
+ * Otherwise a copy carries `jobId`, which also makes it not `retryable`.
55
+ */
47
56
  const withJob = (error, jobId) => {
48
57
  if (!(error instanceof FieldworkError) || error.jobId !== void 0) return error;
49
58
  return new FieldworkError(error.code, error.message, {
@@ -54,6 +63,10 @@ const withJob = (error, jobId) => {
54
63
  status: error.status
55
64
  });
56
65
  };
66
+ /**
67
+ * The code for a provider's HTTP error status. Statuses not listed, 5xx
68
+ * included, are `ProviderError`; a 5xx is still `retryable`.
69
+ */
57
70
  const codeForStatus = (status) => {
58
71
  if (status === 401 || status === 403) return "Unauthorized";
59
72
  if (status === 404) return "NotFound";