@howells/fieldwork-sdk 0.3.1 → 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/README.md CHANGED
@@ -65,7 +65,7 @@ Options are typed per provider. An option means the same thing under the same na
65
65
  | `maxAge` | Seconds a cached copy may be old; `0` always fetches the page fresh. |
66
66
  | `country` | An ISO 3166-1 code such as `"GB"`. |
67
67
  | `language` | An ISO 639-1 code such as `"de"`. |
68
- | `schema`, `prompt` | A JSON Schema for structured output, and extraction instructions in plain words. |
68
+ | `schema`, `prompt` | A JSON Schema or a Standard Schema such as Zod for structured output, and extraction instructions in plain words. |
69
69
  | `query` | On `read`: return the passages that answer it as `excerpts`. |
70
70
  | `content` | On `search`: include each result's page text. |
71
71
  | `continueFrom` | On `answer` and `research`: the `continuationId` of an earlier result, to ask a follow-up. |
@@ -73,6 +73,25 @@ Options are typed per provider. An option means the same thing under the same na
73
73
 
74
74
  Options only one provider has keep that provider's meaning and values, such as Tavily's `topic`, Exa's `category`, SerpApi's `engine` or Firecrawl's `proxy`. A combination a provider would reject or silently ignore, such as `includeDomains` with `excludeDomains` on Parallel, throws `InvalidRequest` before anything is sent.
75
75
 
76
+ ### Structured output
77
+
78
+ `schema` takes a plain JSON Schema, or a Zod, Valibot or ArkType schema. Any library that implements Standard Schema with JSON Schema support works. Use the full `zod` package: `zod/mini` schemas do not write JSON Schema.
79
+
80
+ ```ts
81
+ import { z } from "zod";
82
+
83
+ const page = await web.extract(url, {
84
+ schema: z.object({ price: z.number(), title: z.string() }),
85
+ });
86
+ page.data; // { price: number; title: string }
87
+ ```
88
+
89
+ Fieldwork turns the schema into the JSON Schema the provider reads, and checks the provider's output against your schema before returning it. Output that does not match throws `ProviderError` with the first paths that failed, such as `price: Invalid input: expected number, received string`. The error carries `jobId` when the call was a job. `data` and `output` are what your schema returns, so defaults and transforms apply.
90
+
91
+ A plain JSON Schema is sent as written and the output is not checked. Pass the type yourself: `web.extract<{ price: number }>(url, { schema })`. Without one the type is `unknown`. Agent tools take plain JSON Schema only.
92
+
93
+ Providers differ in which keywords they accept; Exa reads draft 7 and the others draft 2020-12, and Fieldwork drops the `$schema` key. Tavily and Parallel accept only a subset, so keep schemas for them simple.
94
+
76
95
  ## Results
77
96
 
78
97
  Every result is normalized and keeps the provider's response in `raw`. Most also carry `meta`: the provider's `requestId`, `usage` (credits, US dollars, or counted units such as tokens) and `warnings`, when the provider returns them.
@@ -177,6 +196,17 @@ Every failure is a `FieldworkError`. It carries:
177
196
 
178
197
  An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job.
179
198
 
199
+ ### Retries
200
+
201
+ Fieldwork repeats a request that fails in a way that can succeed on repeat, twice by default, before throwing: a rate limit, a 5xx or a dropped connection. It waits as long as the provider's `retry-after` asks, up to 30 seconds, or backs off from half a second with jitter. A provider that asks for a longer wait gets the `RateLimited` error at once, with `retryAfter` set.
202
+
203
+ A request that starts a job, session or monitor, or runs a browser script, is repeated only after a rate limit. After a 5xx the provider may already have started it, and a second attempt could charge twice. `timeout` bounds the whole call, retries included: a wait that would outlast it throws the error at once. `signal` stops the wait between attempts.
204
+
205
+ ```ts
206
+ const web = new Fieldwork({ adapter: exa({ retries: 4 }) }); // every call
207
+ await web.search("tiles", { retries: 0 }); // this call only
208
+ ```
209
+
180
210
  ## Agent tools
181
211
 
182
212
  `@howells/fieldwork-sdk/tools` turns an instance into tool definitions for a model, one per capability or group method: `search_web`, `search_images`, `read_page`, `read_pages`, `extract_values`, `read_product`, `map_site`, `crawl_site`, `answer_question`, `research_question`, `find_entities`, `make_decisions`, `parse_document`, `check_usage`, `run_browser_script`, `open_browser`, `close_browser`, `create_monitor`, `get_monitor`, `list_monitors`, `delete_monitor` and `list_monitor_events`. Each tool has:
@@ -237,4 +267,4 @@ On a router, `raw` is keyed by provider name.
237
267
 
238
268
  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.
239
269
 
240
- ESM only, Node 22 or later. No dependencies.
270
+ ESM only, Node 22 or later. The one dependency is Zod.
@@ -16,8 +16,15 @@ declare const GROUP_CAPABILITIES: readonly Capability[];
16
16
  interface CallOptions {
17
17
  /** Cancels the call, including any polling for an asynchronous job. */
18
18
  signal?: AbortSignal;
19
- /** Milliseconds before the call gives up. */
19
+ /** Milliseconds before the call gives up, across every attempt. */
20
20
  timeout?: number;
21
+ /**
22
+ * How many times to repeat a request that failed in a way that can succeed
23
+ * on repeat: a rate limit, a 5xx, or a failed connection. Waits as long as
24
+ * the provider asks, or backs off exponentially. Overrides the adapter's
25
+ * `retries`; `0` turns retrying off.
26
+ */
27
+ retries?: number;
21
28
  }
22
29
  /** How recent results must be, where a provider filters by a named window. */
23
30
  type Recency = "hour" | "day" | "week" | "month" | "year";
@@ -432,6 +439,13 @@ interface RequestOptions extends CallOptions {
432
439
  /** A multipart body, sent as is. */
433
440
  form?: FormData;
434
441
  query?: Record<string, string | number | boolean | undefined>;
442
+ /**
443
+ * The request creates a job, session or monitor that the provider bills for
444
+ * or keeps. After a 5xx or a dropped connection the provider may already
445
+ * have created it, so only a rate limit, which it has certainly not acted
446
+ * on, is retried.
447
+ */
448
+ creates?: boolean;
435
449
  }
436
450
  /**
437
451
  * The provider's HTTP API with authentication applied: the escape hatch for
@@ -441,7 +455,7 @@ interface RequestOptions extends CallOptions {
441
455
  interface RawClient {
442
456
  readonly provider: string;
443
457
  readonly baseUrl: string;
444
- request<T = unknown>(method: string, path: string, options?: RequestOptions): Promise<T>;
458
+ request: <T = unknown>(method: string, path: string, options?: RequestOptions) => Promise<T>;
445
459
  }
446
460
  type Method = (...args: never[]) => Promise<unknown>;
447
461
  /**
package/dist/brave.d.ts CHANGED
@@ -1,10 +1,12 @@
1
- import { W as Recency, a as RawClient, f as CallOptions, k as ImageSearch, l as Answer, q as SearchResponse, t as Adapter } from "./adapter-DGehHCMo.js";
1
+ import { W as Recency, a as RawClient, f as CallOptions, k as ImageSearch, l as Answer, q as SearchResponse, t as Adapter } from "./adapter-CDY8qczv.js";
2
2
  interface BraveConfig {
3
3
  /** Defaults to the BRAVE_API_KEY environment variable. */
4
4
  apiKey?: string;
5
5
  /** Defaults to https://api.search.brave.com/res/v1. */
6
6
  baseUrl?: string;
7
7
  fetch?: typeof fetch;
8
+ /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
+ retries?: number;
8
10
  }
9
11
  type BraveSafeSearch = "off" | "moderate" | "strict";
10
12
  /** Brave's named freshness windows start at a day; it has no hour window. */
@@ -156,9 +158,9 @@ interface BraveAnswerOptions extends CallOptions {
156
158
  };
157
159
  }
158
160
  interface BraveOperations {
159
- search(query: string, options?: BraveSearchOptions): Promise<SearchResponse>;
160
- images(query: string, options?: BraveImageOptions): Promise<ImageSearch>;
161
- answer(question: string, options?: BraveAnswerOptions): Promise<Answer<unknown>>;
161
+ search: (query: string, options?: BraveSearchOptions) => Promise<SearchResponse>;
162
+ images: (query: string, options?: BraveImageOptions) => Promise<ImageSearch>;
163
+ answer: (question: string, options?: BraveAnswerOptions) => Promise<Answer<unknown>>;
162
164
  }
163
165
  export declare const brave: (config?: BraveConfig) => Adapter<"brave", BraveOperations, RawClient>;
164
166
  export type { BraveAnswerOptions, BraveConfig, BraveContentSearchOptions, BraveImageOptions, BraveNewsSearchOptions, BraveOperations, BraveRecency, BraveResultType, BraveSafeSearch, BraveSearchOptions, BraveVideoSearchOptions, BraveWebSearchOptions };
package/dist/brave.js CHANGED
@@ -1,6 +1,102 @@
1
1
  import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
2
  import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { S as requireKey, b as createRawClient, c as num, i as compact, m as refuseTogether, o as list, p as record, s as meta, t as callSettings, v as text } from "./util-YaZYZDSk.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, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf } from "./parse-CxOri73y.js";
4
+ import * as z from "zod/mini";
5
+ // src/adapters/brave/response.ts
6
+ /** The `query` block every search response carries. */
7
+ const Query = looseObject({
8
+ altered: optionalString,
9
+ show_strict_warning: optionalBoolean
10
+ });
11
+ /** One result of a web, news, video, discussion or place section. */
12
+ const Result = looseObject({
13
+ coordinates: arrayOf(optionalNumber),
14
+ description: optionalString,
15
+ extra_snippets: arrayOf(nonEmptyString),
16
+ meta_url: looseObject({ favicon: optionalString }),
17
+ page_age: optionalString,
18
+ postal_address: looseObject({ displayAddress: optionalString }),
19
+ rating: looseObject({
20
+ ratingValue: optionalNumber,
21
+ reviewCount: optionalNumber
22
+ }),
23
+ thumbnail: looseObject({
24
+ original: optionalString,
25
+ src: optionalString
26
+ }),
27
+ title: optionalString,
28
+ url: optionalString
29
+ });
30
+ const Section = looseObject({ results: arrayOf(Result) });
31
+ /** `/web/search`: the sections are each optional in what Brave sends. */
32
+ const WebSearchResponse = looseObject({
33
+ discussions: Section,
34
+ locations: Section,
35
+ news: Section,
36
+ query: Query,
37
+ videos: Section,
38
+ web: Section
39
+ });
40
+ /** `/news/search` and `/videos/search`. */
41
+ const VerticalSearchResponse = looseObject({
42
+ query: Query,
43
+ results: arrayOf(Result)
44
+ });
45
+ const ImageItem = looseObject({
46
+ properties: looseObject({
47
+ height: optionalNumber,
48
+ url: optionalString,
49
+ width: optionalNumber
50
+ }),
51
+ thumbnail: looseObject({ src: optionalString }),
52
+ title: optionalString,
53
+ url: optionalString
54
+ });
55
+ /** `/images/search`. */
56
+ const ImageSearchResponse = looseObject({
57
+ query: Query,
58
+ results: arrayOf(ImageItem)
59
+ });
60
+ const ContextItem = looseObject({
61
+ name: optionalString,
62
+ snippets: arrayOf(nonEmptyString),
63
+ title: optionalString,
64
+ url: optionalString
65
+ });
66
+ const ContextSource = looseObject({
67
+ description: optionalString,
68
+ favicon: optionalString,
69
+ thumbnail: optionalString,
70
+ title: optionalString
71
+ });
72
+ /** `/llm/context`: grounding items, and their sources keyed by URL. */
73
+ const ContextResponse = looseObject({
74
+ grounding: looseObject({
75
+ generic: arrayOf(ContextItem),
76
+ map: arrayOf(ContextItem),
77
+ poi: ContextItem
78
+ }),
79
+ sources: recordOf(ContextSource)
80
+ });
81
+ const Choice = looseObject({
82
+ delta: looseObject({ content: optionalString }),
83
+ message: looseObject({ content: optionalString })
84
+ });
85
+ /** A chat completion, whole or as one streamed chunk. */
86
+ const Completion = looseObject({ choices: arrayOf(Choice) });
87
+ /** The `<citation>` tag the answer stream embeds. */
88
+ const CitationTag = looseObject({
89
+ snippet: optionalString,
90
+ url: optionalString
91
+ });
92
+ /** The `<usage>` tag the answer stream embeds. */
93
+ const UsageTag = looseObject({
94
+ "X-Request-Queries": optionalNumber,
95
+ "X-Request-Requests": optionalNumber,
96
+ "X-Request-Tokens-In": optionalNumber,
97
+ "X-Request-Tokens-Out": optionalNumber,
98
+ "X-Request-Total-Cost": optionalNumber
99
+ });
4
100
  // src/adapters/brave/parse.ts
5
101
  const provider = "brave";
6
102
  const FRESHNESS = {
@@ -71,7 +167,7 @@ const modeOf = (o) => {
71
167
  throw invalid(`has no "${o.vertical}" search; use web, news or videos`);
72
168
  };
73
169
  const refuseUnsupported = (mode, o) => {
74
- const refused = Object.keys(o).filter((name) => o[name] !== void 0 && !ALLOWED[mode].includes(name));
170
+ const refused = Object.entries(o).filter(([name, value]) => value !== void 0 && !ALLOWED[mode].some((allowed) => allowed === name)).map(([name]) => name);
75
171
  if (refused.length > 0) throw invalid(`${mode} search does not accept ${refused.join(", ")}`);
76
172
  };
77
173
  const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
@@ -108,115 +204,99 @@ const withQuery = (path, params) => {
108
204
  const upper = (value) => value?.toUpperCase();
109
205
  const lower = (value) => value?.toLowerCase();
110
206
  const warningsOf = (query) => {
111
- const q = record(query);
112
207
  const warnings = [];
113
- const altered = text(q.altered);
114
- if (altered !== void 0) warnings.push(`brave searched the spell-corrected query "${altered}"`);
115
- if (q.show_strict_warning === true) warnings.push("strict safe search hid some results");
208
+ if (query.altered !== void 0) warnings.push(`brave searched the spell-corrected query "${query.altered}"`);
209
+ if (query.show_strict_warning === true) warnings.push("strict safe search hid some results");
116
210
  return warnings;
117
211
  };
118
- const result = (item, kind) => {
119
- const r = record(item);
120
- const url = text(r.url);
121
- if (url === void 0) return;
122
- const thumbnail = record(r.thumbnail);
123
- const extra = list(r.extra_snippets).filter((s) => typeof s === "string" && s !== "");
124
- const snippet = [text(r.description), ...extra].filter((s) => s !== void 0).join("\n\n");
212
+ const result = (r, kind) => {
213
+ if (r.url === void 0) return;
214
+ const snippet = [r.description, ...r.extra_snippets].filter((s) => s !== void 0).join("\n\n");
125
215
  return compact({
126
- favicon: text(record(r.meta_url).favicon),
127
- image: text(thumbnail.original) ?? text(thumbnail.src),
216
+ favicon: r.meta_url.favicon,
217
+ image: r.thumbnail.original ?? r.thumbnail.src,
128
218
  kind,
129
- publishedAt: text(r.page_age),
219
+ publishedAt: r.page_age,
130
220
  snippet: snippet === "" ? void 0 : snippet,
131
- title: text(r.title),
132
- url
221
+ title: r.title,
222
+ url: r.url
133
223
  });
134
224
  };
135
- const placeResult = (item) => {
136
- const base = result(item, "place");
225
+ const placeResult = (r) => {
226
+ const base = result(r, "place");
137
227
  if (!base) return;
138
- const r = record(item);
139
- const [latitude, longitude] = list(r.coordinates);
228
+ const [latitude, longitude] = r.coordinates;
140
229
  const place = compact({
141
- address: text(record(r.postal_address).displayAddress),
142
- latitude: num(latitude),
143
- longitude: num(longitude)
230
+ address: r.postal_address.displayAddress,
231
+ latitude,
232
+ longitude
144
233
  });
145
- const rating = record(r.rating);
146
234
  return compact({
147
235
  ...base,
148
236
  place: Object.keys(place).length > 0 ? place : void 0,
149
- rating: num(rating.ratingValue),
150
- reviewCount: num(rating.reviewCount)
237
+ rating: r.rating.ratingValue,
238
+ reviewCount: r.rating.reviewCount
151
239
  });
152
240
  };
153
- const section = (response, name, map) => list(record(response[name]).results).map((item) => map(item)).filter((item) => item !== void 0);
154
- const contextResult = (item, kind, sources) => {
155
- const r = record(item);
156
- const url = text(r.url);
157
- if (url === void 0) return;
158
- const source = record(sources[url]);
159
- const passages = list(r.snippets).filter((s) => typeof s === "string" && s !== "");
241
+ const section = (items, map) => items.map((item) => map(item)).filter((item) => item !== void 0);
242
+ const contextResult = (r, kind, sources) => {
243
+ if (r.url === void 0) return;
244
+ const source = sources[r.url];
160
245
  return compact({
161
- content: passages.length > 0 ? passages.join("\n\n") : void 0,
162
- favicon: text(source.favicon),
163
- image: text(source.thumbnail),
246
+ content: r.snippets.length > 0 ? r.snippets.join("\n\n") : void 0,
247
+ favicon: source?.favicon,
248
+ image: source?.thumbnail,
164
249
  kind,
165
- snippet: text(source.description),
166
- title: text(r.title) ?? text(r.name) ?? text(source.title),
167
- url
250
+ snippet: source?.description,
251
+ title: r.title ?? r.name ?? source?.title,
252
+ url: r.url
168
253
  });
169
254
  };
170
- const parseContext = (response) => {
171
- const grounding = record(response.grounding);
172
- const sources = record(response.sources);
173
- const poi = record(grounding.poi);
174
- return [
175
- ...list(grounding.generic).map((item) => contextResult(item, "web", sources)),
176
- ...Object.keys(poi).length > 0 ? [contextResult(poi, "place", sources)] : [],
177
- ...list(grounding.map).map((item) => contextResult(item, "place", sources))
178
- ].filter((item) => item !== void 0);
179
- };
180
- const completionText = (response) => {
181
- if (typeof response === "string") {
182
- let content = "";
183
- for (const line of response.split(/\r?\n/u)) {
184
- if (!line.startsWith("data:")) continue;
185
- const payload = line.slice(5).trim();
186
- if (payload === "" || payload === "[DONE]") continue;
187
- try {
188
- for (const choice of list(record(JSON.parse(payload)).choices)) {
189
- const delta = text(record(record(choice).delta).content);
190
- content += delta ?? "";
191
- }
192
- } catch {}
193
- }
194
- return content;
255
+ const parseContext = ({ grounding, sources }) => [
256
+ ...grounding.generic.map((item) => contextResult(item, "web", sources)),
257
+ contextResult(grounding.poi, "place", sources),
258
+ ...grounding.map.map((item) => contextResult(item, "place", sources))
259
+ ].filter((item) => item !== void 0);
260
+ /** The text of a streamed answer: the content of each `data:` line's chunk. */
261
+ const streamText = (stream) => {
262
+ let content = "";
263
+ for (const line of stream.split(/\r?\n/u)) {
264
+ if (!line.startsWith("data:")) continue;
265
+ const payload = line.slice(5).trim();
266
+ if (payload === "" || payload === "[DONE]") continue;
267
+ try {
268
+ const chunk = z.parse(Completion, JSON.parse(payload));
269
+ for (const choice of chunk.choices) content += choice.delta.content ?? "";
270
+ } catch {}
195
271
  }
196
- const choice = record(list(record(response).choices)[0]);
197
- return text(record(choice.message).content) ?? text(record(choice.delta).content) ?? "";
272
+ return content;
273
+ };
274
+ /** The text of an answer sent whole, from its first choice. */
275
+ const completionText = (completion) => {
276
+ const [choice] = completion.choices;
277
+ return choice?.message.content ?? choice?.delta.content ?? "";
198
278
  };
199
279
  const CITATION_TAG = /<citation>(?<body>[\s\S]*?)<\/citation>/gu;
200
280
  const USAGE_TAG = /<usage>(?<body>[\s\S]*?)<\/usage>/gu;
201
- const tagJson = (body) => {
281
+ /** The JSON inside a tag, which Brave sometimes encodes twice, read through `schema`. */
282
+ const parseTag = (body, schema) => {
202
283
  try {
203
- let value = JSON.parse(body);
204
- if (typeof value === "string") value = JSON.parse(value);
205
- return record(value);
284
+ const value = JSON.parse(body);
285
+ const twice = z.safeParse(z.string(), value);
286
+ return [z.parse(schema, twice.success ? JSON.parse(twice.data) : value)];
206
287
  } catch {
207
- return;
288
+ return [];
208
289
  }
209
290
  };
210
- const tagBodies = (content, tag) => [...content.matchAll(tag)].map((match) => tagJson(match.groups?.body ?? "")).filter((item) => item !== void 0);
291
+ /** Every tag in the content whose body is JSON, read through `schema`. */
292
+ const tagBodies = (content, tag, schema) => [...content.matchAll(tag)].flatMap((match) => parseTag(match.groups?.body ?? "", schema));
211
293
  const answerCitations = (content) => {
212
294
  const byUrl = /* @__PURE__ */ new Map();
213
- for (const item of tagBodies(content, CITATION_TAG)) {
214
- const url = text(item.url);
215
- if (url === void 0) continue;
216
- const excerpts = byUrl.get(url) ?? [];
217
- const snippet = text(item.snippet);
218
- if (snippet !== void 0 && !excerpts.includes(snippet)) excerpts.push(snippet);
219
- byUrl.set(url, excerpts);
295
+ for (const item of tagBodies(content, CITATION_TAG, CitationTag)) {
296
+ if (item.url === void 0) continue;
297
+ const excerpts = byUrl.get(item.url) ?? [];
298
+ if (item.snippet !== void 0 && !excerpts.includes(item.snippet)) excerpts.push(item.snippet);
299
+ byUrl.set(item.url, excerpts);
220
300
  }
221
301
  return [...byUrl].map(([url, excerpts]) => compact({
222
302
  excerpts: excerpts.length > 0 ? excerpts : void 0,
@@ -229,7 +309,8 @@ const brave = (config = {}) => {
229
309
  baseUrl: config.baseUrl ?? "https://api.search.brave.com/res/v1",
230
310
  fetch: config.fetch,
231
311
  headers: { "X-Subscription-Token": requireKey(provider, config.apiKey, "BRAVE_API_KEY") },
232
- provider
312
+ provider,
313
+ retries: config.retries
233
314
  });
234
315
  return defineAdapter({
235
316
  name: provider,
@@ -266,23 +347,24 @@ const brave = (config = {}) => {
266
347
  web_search_options: Object.keys(searchOptions).length > 0 ? searchOptions : void 0
267
348
  })
268
349
  });
269
- const content = completionText(response);
350
+ const stream = z.safeParse(z.string(), response);
351
+ const content = stream.success ? streamText(stream.data) : completionText(z.parse(Completion, response));
270
352
  const answer = content.replace(CITATION_TAG, "").replace(USAGE_TAG, "").trim();
271
353
  if (answer === "") throw new FieldworkError("ProviderError", "brave returned no answer text", {
272
354
  cause: response,
273
355
  provider
274
356
  });
275
- const usage = tagBodies(content, USAGE_TAG).at(-1) ?? {};
357
+ const usage = tagBodies(content, USAGE_TAG, UsageTag).at(-1);
276
358
  return compact({
277
359
  answer,
278
360
  citations: answerCitations(content),
279
361
  meta: meta({
280
- costUsd: usage["X-Request-Total-Cost"],
362
+ costUsd: usage?.["X-Request-Total-Cost"],
281
363
  units: {
282
- queries: usage["X-Request-Queries"],
283
- requests: usage["X-Request-Requests"],
284
- tokensIn: usage["X-Request-Tokens-In"],
285
- tokensOut: usage["X-Request-Tokens-Out"]
364
+ queries: usage?.["X-Request-Queries"],
365
+ requests: usage?.["X-Request-Requests"],
366
+ tokensIn: usage?.["X-Request-Tokens-In"],
367
+ tokensOut: usage?.["X-Request-Tokens-Out"]
286
368
  }
287
369
  }),
288
370
  raw: response
@@ -290,34 +372,33 @@ const brave = (config = {}) => {
290
372
  },
291
373
  async images(query, options) {
292
374
  const { call, rest: o } = callSettings(options);
293
- const response = record(await raw.request("GET", withQuery("/images/search", {
375
+ const response = await raw.request("GET", withQuery("/images/search", {
294
376
  count: o.limit,
295
377
  country: upper(o.country),
296
378
  q: query,
297
379
  safesearch: o.safesearch,
298
380
  search_lang: lower(o.language),
299
381
  spellcheck: o.spellcheck
300
- }), call));
382
+ }), call);
383
+ const body = z.parse(ImageSearchResponse, response);
301
384
  const results = [];
302
385
  let withoutImage = 0;
303
- for (const item of list(response.results)) {
304
- const r = record(item);
305
- const properties = record(r.properties);
306
- const url = text(properties.url);
386
+ for (const item of body.results) {
387
+ const { url } = item.properties;
307
388
  if (url === void 0) {
308
389
  withoutImage += 1;
309
390
  continue;
310
391
  }
311
392
  results.push(compact({
312
- height: num(properties.height),
313
- sourceUrl: text(r.url),
314
- thumbnailUrl: text(record(r.thumbnail).src),
315
- title: text(r.title),
393
+ height: item.properties.height,
394
+ sourceUrl: item.url,
395
+ thumbnailUrl: item.thumbnail.src,
396
+ title: item.title,
316
397
  url,
317
- width: num(properties.width)
398
+ width: item.properties.width
318
399
  }));
319
400
  }
320
- const warnings = [...warningsOf(response.query), ...withoutImage > 0 ? [`${withoutImage} results had no image URL and were left out`] : []];
401
+ const warnings = [...warningsOf(body.query), ...withoutImage > 0 ? [`${withoutImage} results had no image URL and were left out`] : []];
321
402
  return compact({
322
403
  meta: meta({ warnings }),
323
404
  raw: response,
@@ -342,35 +423,36 @@ const brave = (config = {}) => {
342
423
  search_lang: lower(o.language)
343
424
  };
344
425
  if (mode === "context") {
345
- const response = record(await raw.request("GET", withQuery("/llm/context", {
426
+ const response = await raw.request("GET", withQuery("/llm/context", {
346
427
  ...shared,
347
428
  context_threshold_mode: o.relevance,
348
429
  enable_source_metadata: o.sourceMetadata,
349
430
  maximum_number_of_tokens: o.maxTokens,
350
431
  maximum_number_of_tokens_per_url: o.maxTokensPerUrl,
351
432
  maximum_number_of_urls: o.limit
352
- }), call));
433
+ }), call);
353
434
  return compact({
354
435
  raw: response,
355
- results: parseContext(response)
436
+ results: parseContext(z.parse(ContextResponse, response))
356
437
  });
357
438
  }
358
439
  if (mode === "news" || mode === "videos") {
359
- const response = record(await raw.request("GET", withQuery(`/${mode}/search`, {
440
+ const response = await raw.request("GET", withQuery(`/${mode}/search`, {
360
441
  ...shared,
361
442
  extra_snippets: mode === "news" ? o.extraSnippets : void 0,
362
443
  offset: o.offset,
363
444
  spellcheck: o.spellcheck,
364
445
  ui_lang: o.uiLanguage
365
- }), call));
446
+ }), call);
447
+ const body = z.parse(VerticalSearchResponse, response);
366
448
  const kind = mode === "news" ? "news" : "video";
367
449
  return compact({
368
- meta: meta({ warnings: warningsOf(response.query) }),
450
+ meta: meta({ warnings: warningsOf(body.query) }),
369
451
  raw: response,
370
- results: list(response.results).map((item) => result(item, kind)).filter((item) => item !== void 0)
452
+ results: section(body.results, (item) => result(item, kind))
371
453
  });
372
454
  }
373
- const response = record(await raw.request("GET", withQuery("/web/search", {
455
+ const response = await raw.request("GET", withQuery("/web/search", {
374
456
  ...shared,
375
457
  extra_snippets: o.extraSnippets,
376
458
  offset: o.offset,
@@ -379,16 +461,17 @@ const brave = (config = {}) => {
379
461
  text_decorations: o.textDecorations ?? false,
380
462
  ui_lang: o.uiLanguage,
381
463
  units: o.units
382
- }), call));
464
+ }), call);
465
+ const body = z.parse(WebSearchResponse, response);
383
466
  return compact({
384
- meta: meta({ warnings: warningsOf(response.query) }),
467
+ meta: meta({ warnings: warningsOf(body.query) }),
385
468
  raw: response,
386
469
  results: [
387
- ...section(response, "web", (item) => result(item, "web")),
388
- ...section(response, "news", (item) => result(item, "news")),
389
- ...section(response, "discussions", (item) => result(item, "discussion")),
390
- ...section(response, "videos", (item) => result(item, "video")),
391
- ...section(response, "locations", placeResult)
470
+ ...section(body.web.results, (item) => result(item, "web")),
471
+ ...section(body.news.results, (item) => result(item, "news")),
472
+ ...section(body.discussions.results, (item) => result(item, "discussion")),
473
+ ...section(body.videos.results, (item) => result(item, "video")),
474
+ ...section(body.locations.results, placeResult)
392
475
  ]
393
476
  });
394
477
  }
@@ -1,4 +1,4 @@
1
- import { I as Page, a as RawClient, f as CallOptions, q as SearchResponse, s as AccountUsage, t as Adapter, u as BrowserSession } from "./adapter-DGehHCMo.js";
1
+ import { I as Page, a as RawClient, f as CallOptions, q as SearchResponse, s as AccountUsage, t as Adapter, u as BrowserSession } from "./adapter-CDY8qczv.js";
2
2
  export interface BrowserbaseConfig {
3
3
  /** Defaults to the BROWSERBASE_API_KEY environment variable. */
4
4
  apiKey?: string;
@@ -11,6 +11,8 @@ export interface BrowserbaseConfig {
11
11
  projectId?: string;
12
12
  baseUrl?: string;
13
13
  fetch?: typeof fetch;
14
+ /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
15
+ retries?: number;
14
16
  }
15
17
  /** Where Browserbase's proxy network exits, as a country with optional state and city. */
16
18
  export interface BrowserbaseGeolocation {
@@ -116,13 +118,13 @@ export interface BrowserbaseOpenOptions extends CallOptions {
116
118
  userMetadata?: Record<string, unknown>;
117
119
  }
118
120
  export interface BrowserbaseOperations {
119
- search(query: string, options?: BrowserbaseSearchOptions): Promise<SearchResponse>;
120
- read(url: string, options?: BrowserbaseReadOptions): Promise<Page>;
121
+ search: (query: string, options?: BrowserbaseSearchOptions) => Promise<SearchResponse>;
122
+ read: (url: string, options?: BrowserbaseReadOptions) => Promise<Page>;
121
123
  browser: {
122
- open(options?: BrowserbaseOpenOptions): Promise<BrowserSession>;
123
- close(id: string, options?: CallOptions): Promise<void>;
124
+ open: (options?: BrowserbaseOpenOptions) => Promise<BrowserSession>;
125
+ close: (id: string, options?: CallOptions) => Promise<void>;
124
126
  };
125
- usage(options?: CallOptions): Promise<AccountUsage>;
127
+ usage: (options?: CallOptions) => Promise<AccountUsage>;
126
128
  }
127
129
  export declare const browserbase: (config?: BrowserbaseConfig) => Adapter<"browserbase", BrowserbaseOperations, RawClient>;
128
130
  export {};