@howells/fieldwork-sdk 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 and Browserbase.
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.
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 |
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 | | | | | | |
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 | 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 | | |
46
46
 
47
47
  `web.capabilities` and `web.supports("crawl")` report the same table at runtime.
48
48
 
@@ -104,12 +104,13 @@ Every result is normalized and keeps the provider's response in `raw`. Most also
104
104
  - `answer` returns `{ answer, output, citations, continuationId }`.
105
105
  - `research` returns `{ id, status, output, sources, fields, continuationId }`. `output` follows your schema when you pass one, otherwise it is the report text.
106
106
  - `crawl` returns `{ pages, failed, robotsBlocked, total }`.
107
+ - `parse` returns `{ id, markdown, pages, blocks, pageCount }`. With `blocks: true`, `blocks` lists the layout in reading order: each block's `page`, `type` (the provider's own word), `text` and `box`. With `wordBoxes: true` (LlamaParse and Reducto), blocks also carry `words` and table `cells`, each with its own box. With `pageImages: true` (LlamaParse), each page carries `image`, an address for a picture of the page that expires after about an hour; `parse({ resume: id, pageImages: true })` collects fresh addresses without the file. Every box is `{ left, top, width, height }` in fractions of the page from its top-left corner, whatever units the provider used, so boxes from different providers line up.
107
108
 
108
109
  A job that stopped early but produced output, for example on a credit or step limit, returns `status: "partial"` with `stopReason`. A job with no usable output throws `JobFailed`.
109
110
 
110
111
  ### Long jobs
111
112
 
112
- Research, discovery, crawls, batch reads and Parallel extraction 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. Pass `timeout` and `signal` to bound or cancel any call.
113
114
 
114
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:
115
116
 
@@ -254,16 +255,18 @@ On a router, `raw` is keyed by provider name.
254
255
 
255
256
  ## Keys
256
257
 
257
- | Adapter | Environment variable |
258
- | --- | --- |
259
- | `exa()` | `EXA_API_KEY` |
260
- | `firecrawl()` | `FIRECRAWL_API_KEY` |
261
- | `tavily()` | `TAVILY_API_KEY` |
262
- | `parallel()` | `PARALLEL_API_KEY` |
263
- | `perplexity()` | `PERPLEXITY_API_KEY` |
264
- | `brave()` | `BRAVE_API_KEY` |
265
- | `serpapi()` | `SERPAPI_API_KEY` |
266
- | `browserbase()` | `BROWSERBASE_API_KEY`, and optionally `BROWSERBASE_PROJECT_ID` |
258
+ | Adapter | Environment variable |
259
+ | --------------- | --------------------- |
260
+ | `exa()` | `EXA_API_KEY` |
261
+ | `firecrawl()` | `FIRECRAWL_API_KEY` |
262
+ | `tavily()` | `TAVILY_API_KEY` |
263
+ | `parallel()` | `PARALLEL_API_KEY` |
264
+ | `perplexity()` | `PERPLEXITY_API_KEY` |
265
+ | `brave()` | `BRAVE_API_KEY` |
266
+ | `serpapi()` | `SERPAPI_API_KEY` |
267
+ | `browserbase()` | `BROWSERBASE_API_KEY` |
268
+ | `llamaparse()` | `LLAMA_CLOUD_API_KEY` |
269
+ | `reducto()` | `REDUCTO_API_KEY` |
267
270
 
268
271
  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.
269
272
 
@@ -6,6 +6,7 @@
6
6
  type JsonSchema = Record<string, unknown>;
7
7
  /** Every capability Fieldwork knows. An adapter implements a subset. */
8
8
  declare const CAPABILITIES: readonly ["search", "images", "read", "readMany", "extract", "product", "map", "crawl", "answer", "research", "discover", "decide", "act", "browser", "parse", "monitor", "usage"];
9
+ /** A capability's name, such as `search` or `monitor`. */
9
10
  type Capability = (typeof CAPABILITIES)[number];
10
11
  /**
11
12
  * Capabilities whose operation is a group of methods rather than one method:
@@ -73,11 +74,13 @@ interface Price {
73
74
  /** The price as the page showed it: "$12.50". */
74
75
  formatted?: string;
75
76
  }
77
+ /** Where a place result is. */
76
78
  interface Place {
77
79
  address?: string;
78
80
  latitude?: number;
79
81
  longitude?: number;
80
82
  }
83
+ /** One result of `search`. Fields a provider does not return are absent. */
81
84
  interface SearchResult {
82
85
  url: string;
83
86
  title?: string;
@@ -106,6 +109,7 @@ interface SearchResult {
106
109
  /** Place results. */
107
110
  place?: Place;
108
111
  }
112
+ /** One image from `images`, or from a search asked for images. */
109
113
  interface ImageResult {
110
114
  /** The image itself. */
111
115
  url: string;
@@ -117,6 +121,7 @@ interface ImageResult {
117
121
  width?: number;
118
122
  height?: number;
119
123
  }
124
+ /** What `search` returns. */
120
125
  interface SearchResponse {
121
126
  results: SearchResult[];
122
127
  /** A generated answer, when the provider was asked for one. */
@@ -126,11 +131,13 @@ interface SearchResponse {
126
131
  meta?: Meta;
127
132
  raw: unknown;
128
133
  }
134
+ /** What `images` returns. */
129
135
  interface ImageSearch {
130
136
  results: ImageResult[];
131
137
  meta?: Meta;
132
138
  raw: unknown;
133
139
  }
140
+ /** What `read` returns: one page, in the formats the call asked for. */
134
141
  interface Page {
135
142
  url: string;
136
143
  title?: string;
@@ -166,6 +173,7 @@ interface FailedUrl {
166
173
  url: string;
167
174
  error: string;
168
175
  }
176
+ /** What `readMany` returns. A URL that fails goes in `failed` rather than failing the call. */
169
177
  interface PageBatch {
170
178
  /** The provider's job id, for providers that read in a background job. */
171
179
  id?: string;
@@ -174,6 +182,7 @@ interface PageBatch {
174
182
  meta?: Meta;
175
183
  raw: unknown;
176
184
  }
185
+ /** What `extract` returns: values in the shape of the schema. */
177
186
  interface Extraction<T> {
178
187
  /** The values, in the shape of the schema. */
179
188
  data: T;
@@ -182,10 +191,12 @@ interface Extraction<T> {
182
191
  meta?: Meta;
183
192
  raw: unknown;
184
193
  }
194
+ /** A product photo. */
185
195
  interface ProductImage {
186
196
  url: string;
187
197
  alt?: string;
188
198
  }
199
+ /** One purchasable version of a product, such as a size or colour. */
189
200
  interface ProductVariant {
190
201
  id?: string;
191
202
  sku?: string;
@@ -202,6 +213,7 @@ interface ProductVariant {
202
213
  /** Barcode: GTIN, EAN or UPC. */
203
214
  gtin?: string;
204
215
  }
216
+ /** What `product` returns: a product page read into its variants and prices. */
205
217
  interface Product {
206
218
  title?: string;
207
219
  brand?: string;
@@ -213,16 +225,19 @@ interface Product {
213
225
  meta?: Meta;
214
226
  raw: unknown;
215
227
  }
228
+ /** One URL `map` found. */
216
229
  interface SiteLink {
217
230
  url: string;
218
231
  title?: string;
219
232
  description?: string;
220
233
  }
234
+ /** What `map` returns: a site's URLs, without their content. */
221
235
  interface SiteMap {
222
236
  links: SiteLink[];
223
237
  meta?: Meta;
224
238
  raw: unknown;
225
239
  }
240
+ /** What `crawl` returns: the pages reached by following links from the start URL. */
226
241
  interface Crawl {
227
242
  /** The provider's job id, for providers that crawl in a background job. */
228
243
  id?: string;
@@ -242,6 +257,7 @@ interface Crawl {
242
257
  * says why. A run with no output throws `JobFailed`.
243
258
  */
244
259
  type RunStatus = "completed" | "partial";
260
+ /** What `answer` returns: a cited answer to a question. */
245
261
  interface Answer<T> {
246
262
  /** The answer text. */
247
263
  answer: string;
@@ -255,6 +271,11 @@ interface Answer<T> {
255
271
  meta?: Meta;
256
272
  raw: unknown;
257
273
  }
274
+ /**
275
+ * What `research` returns once the run ends.
276
+ *
277
+ * A run that fails or ends without output throws `JobFailed` with its `jobId`.
278
+ */
258
279
  interface Research<T> {
259
280
  /** The provider's id for the run. */
260
281
  id: string;
@@ -285,6 +306,7 @@ interface Entity<T = Record<string, unknown>> {
285
306
  citations?: Citation[];
286
307
  fields?: FieldSource[];
287
308
  }
309
+ /** What `discover` returns: the entities a run found. */
288
310
  interface Discovery<T = Record<string, unknown>> {
289
311
  /** The provider's id for the run. */
290
312
  id: string;
@@ -317,6 +339,7 @@ type DecisionQuestion = {
317
339
  /** The rubric: each score and what it means. */
318
340
  scale: Record<string, string>;
319
341
  };
342
+ /** The answer to one `DecisionQuestion`. Which fields are set follows the question's `type`. */
320
343
  interface DecisionAnswer {
321
344
  /** For `yesno`: the probability that the answer is yes, 0 to 1. */
322
345
  probability?: number;
@@ -328,6 +351,7 @@ interface DecisionAnswer {
328
351
  /** Set when the provider declined to answer, with its reason. */
329
352
  refusal?: string;
330
353
  }
354
+ /** What `decide` returns. */
331
355
  interface Decisions {
332
356
  /** Answers keyed by the question names given. */
333
357
  answers: Record<string, DecisionAnswer>;
@@ -336,6 +360,7 @@ interface Decisions {
336
360
  meta?: Meta;
337
361
  raw: unknown;
338
362
  }
363
+ /** What `act` returns: the outcome of a script run in a remote browser. */
339
364
  interface ActResult {
340
365
  /** What the script printed. */
341
366
  stdout: string;
@@ -364,16 +389,62 @@ interface BrowserSession {
364
389
  meta?: Meta;
365
390
  raw: unknown;
366
391
  }
392
+ /** One page of a parsed document, as Markdown. */
367
393
  interface DocumentPage {
368
394
  /** The physical page number, starting at 1. */
369
395
  pageNumber: number;
370
396
  markdown: string;
397
+ /** An address for a picture of the page, when the parse asked for page images. It expires. */
398
+ image?: string;
371
399
  }
400
+ /**
401
+ * Where something sits on its page, as fractions of the page's width and
402
+ * height measured from its top-left corner, whatever units the provider used.
403
+ */
404
+ interface Box {
405
+ left: number;
406
+ top: number;
407
+ width: number;
408
+ height: number;
409
+ }
410
+ /** A word and where it sits. */
411
+ interface WordBox {
412
+ text: string;
413
+ box: Box;
414
+ }
415
+ /** A table cell and where it sits. Rows and columns count from 0. */
416
+ interface TableCell {
417
+ row: number;
418
+ column: number;
419
+ /** Rows the cell spans, when more than one. */
420
+ rowSpan?: number;
421
+ /** Columns the cell spans, when more than one. */
422
+ columnSpan?: number;
423
+ text: string;
424
+ box?: Box;
425
+ }
426
+ /** One piece of a page's layout: a heading, a paragraph, a table, a figure. */
427
+ interface DocumentBlock {
428
+ /** The physical page number, starting at 1. */
429
+ page: number;
430
+ /** The kind of block in the provider's own words, such as "Table", "heading" or "page_header". */
431
+ type: string;
432
+ /** The block's content as the provider gave it: Markdown, or HTML for some tables. */
433
+ text: string;
434
+ box?: Box;
435
+ /** Where each word sits, when the parse asked for word boxes. */
436
+ words?: WordBox[];
437
+ /** A table's cells, when the parse asked for word boxes. */
438
+ cells?: TableCell[];
439
+ }
440
+ /** What `parse` returns: a document as Markdown, with pages and layout when asked for. */
372
441
  interface ParsedDocument {
442
+ /** The provider's job id, for providers that parse in a background job. */
443
+ id?: string;
373
444
  markdown: string;
374
445
  pages?: DocumentPage[];
375
- /** Layout blocks with positions, as the provider returns them. */
376
- blocks?: unknown[];
446
+ /** The layout, in reading order, when the parse asked for blocks. */
447
+ blocks?: DocumentBlock[];
377
448
  /** Pages in the file; more than `pages.length` means the parse was cut short. */
378
449
  pageCount?: number;
379
450
  meta?: Meta;
@@ -390,6 +461,7 @@ type MonitorSchedule = {
390
461
  } | {
391
462
  every: "hour" | "day" | "week" | `${number}h` | `${number}d`;
392
463
  };
464
+ /** A monitor, as `monitor.create`, `monitor.get` and `monitor.list` return it. */
393
465
  interface MonitorInfo {
394
466
  id: string;
395
467
  /** What the monitor watches: a query, a URL list or a goal. */
@@ -413,6 +485,7 @@ interface MonitorEvent {
413
485
  citations?: Citation[];
414
486
  raw: unknown;
415
487
  }
488
+ /** What `monitor.events` returns: one page of events. */
416
489
  interface MonitorEvents {
417
490
  events: MonitorEvent[];
418
491
  /** Pass as `cursor` for the next page. */
@@ -433,6 +506,7 @@ interface AccountUsage {
433
506
  periodEnd?: string;
434
507
  raw: unknown;
435
508
  }
509
+ /** Options for one request through an adapter's `raw` client. */
436
510
  interface RequestOptions extends CallOptions {
437
511
  /** A JSON body. */
438
512
  body?: unknown;
@@ -446,6 +520,8 @@ interface RequestOptions extends CallOptions {
446
520
  * on, is retried.
447
521
  */
448
522
  creates?: boolean;
523
+ /** The endpoint answers in text, such as an event stream, so its body is returned as a string. */
524
+ text?: boolean;
449
525
  }
450
526
  /**
451
527
  * The provider's HTTP API with authentication applied: the escape hatch for
@@ -479,6 +555,12 @@ interface Adapter<Name extends string = string, Ops extends Operations = Operati
479
555
  */
480
556
  readonly providers?: Partial<Record<Capability, string>>;
481
557
  }
558
+ /** Any adapter, whatever its provider and operations. Use it to accept an adapter generically. */
482
559
  type AnyAdapter = Adapter<string, any, unknown>;
560
+ /**
561
+ * Types an adapter literal without widening it, so `Fieldwork` keeps each operation's own options.
562
+ *
563
+ * It returns its argument unchanged; write a custom adapter with it.
564
+ */
483
565
  declare const defineAdapter: <Name extends string, Ops extends Operations, Raw = RawClient>(adapter: Adapter<Name, Ops, Raw>) => Adapter<Name, Ops, Raw>;
484
- export { JsonSchema as A, Price as B, Entity as C, GROUP_CAPABILITIES as D, FieldSource as E, MonitorSchedule as F, Research as G, ProductImage as H, Page as I, SearchResult as J, RunStatus as K, PageBatch as L, MonitorEvent as M, MonitorEvents as N, ImageResult as O, MonitorInfo as P, ParsedDocument as R, DocumentPage as S, FailedUrl as T, ProductVariant as U, Product as V, Recency as W, SiteMap as X, SiteLink as Y, Usage as Z, DecisionAnswer as _, RawClient as a, Discovery as b, ActResult as c, CAPABILITIES as d, CallOptions as f, Crawl as g, Condition as h, defineAdapter as i, Meta as j, ImageSearch as k, Answer as l, Citation as m, AnyAdapter as n, RequestOptions as o, Capability as p, SearchResponse as q, Operations as r, AccountUsage as s, Adapter as t, BrowserSession as u, DecisionQuestion as v, Extraction as w, DocumentInput as x, Decisions as y, Place as z };
566
+ export { TableCell as $, ImageResult as A, ParsedDocument as B, DocumentInput as C, FailedUrl as D, Extraction as E, MonitorEvents as F, ProductVariant as G, Price as H, MonitorInfo as I, RunStatus as J, Recency as K, MonitorSchedule as L, JsonSchema as M, Meta as N, FieldSource as O, MonitorEvent as P, SiteMap as Q, Page as R, DocumentBlock as S, Entity as T, Product as U, Place as V, ProductImage as W, SearchResult as X, SearchResponse as Y, SiteLink as Z, Crawl as _, RawClient as a, Decisions as b, ActResult as c, BrowserSession as d, Usage as et, CAPABILITIES as f, Condition as g, Citation as h, defineAdapter as i, ImageSearch as j, GROUP_CAPABILITIES as k, Answer as l, Capability as m, AnyAdapter as n, RequestOptions as o, CallOptions as p, Research as q, Operations as r, AccountUsage as s, Adapter as t, WordBox as tt, Box as u, DecisionAnswer as v, DocumentPage as w, Discovery as x, DecisionQuestion as y, PageBatch as z };
@@ -0,0 +1,8 @@
1
+ // src/adapter.ts
2
+ /**
3
+ * Types an adapter literal without widening it, so `Fieldwork` keeps each operation's own options.
4
+ *
5
+ * It returns its argument unchanged; write a custom adapter with it.
6
+ */
7
+ const defineAdapter = (adapter) => adapter;
8
+ export { defineAdapter as t };
package/dist/brave.d.ts CHANGED
@@ -1,4 +1,4 @@
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";
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";
2
2
  interface BraveConfig {
3
3
  /** Defaults to the BRAVE_API_KEY environment variable. */
4
4
  apiKey?: string;
@@ -162,5 +162,10 @@ interface BraveOperations {
162
162
  images: (query: string, options?: BraveImageOptions) => Promise<ImageSearch>;
163
163
  answer: (question: string, options?: BraveAnswerOptions) => Promise<Answer<unknown>>;
164
164
  }
165
+ /**
166
+ * An adapter for Brave: search, images and answer. Pass it to `new Fieldwork({ adapter })`.
167
+ *
168
+ * Throws `Unauthorized` when neither `apiKey` nor `BRAVE_API_KEY` is set.
169
+ */
165
170
  export declare const brave: (config?: BraveConfig) => Adapter<"brave", BraveOperations, RawClient>;
166
171
  export type { BraveAnswerOptions, BraveConfig, BraveContentSearchOptions, BraveImageOptions, BraveNewsSearchOptions, BraveOperations, BraveRecency, BraveResultType, BraveSafeSearch, BraveSearchOptions, BraveVideoSearchOptions, BraveWebSearchOptions };
package/dist/brave.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { C as createRawClient, E as callSettings, I as refuseTogether, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, j as meta, k as compact, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf } from "./parse-CxOri73y.js";
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
+ import { C as createRawClient, 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";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/brave/response.ts
6
6
  /** The `query` block every search response carries. */
@@ -159,16 +159,15 @@ const ALLOWED = {
159
159
  "textDecorations"
160
160
  ]
161
161
  };
162
- const invalid = (message) => new FieldworkError("InvalidRequest", `brave ${message}`, { provider });
163
162
  const modeOf = (o) => {
164
163
  if (o.content === true) return "context";
165
164
  if (o.vertical === void 0 || o.vertical === "web") return "web";
166
165
  if (o.vertical === "news" || o.vertical === "videos") return o.vertical;
167
- throw invalid(`has no "${o.vertical}" search; use web, news or videos`);
166
+ throw invalidRequest(provider, `has no "${o.vertical}" search; use web, news or videos`);
168
167
  };
169
168
  const refuseUnsupported = (mode, o) => {
170
169
  const refused = Object.entries(o).filter(([name, value]) => value !== void 0 && !ALLOWED[mode].some((allowed) => allowed === name)).map(([name]) => name);
171
- if (refused.length > 0) throw invalid(`${mode} search does not accept ${refused.join(", ")}`);
170
+ if (refused.length > 0) throw invalidRequest(provider, `${mode} search does not accept ${refused.join(", ")}`);
172
171
  };
173
172
  const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
174
173
  const freshness = (o) => {
@@ -176,20 +175,20 @@ const freshness = (o) => {
176
175
  refuseTogether(provider, o, "recency", "publishedBefore");
177
176
  if (o.recency !== void 0) {
178
177
  const window = FRESHNESS[o.recency];
179
- if (!window) throw invalid(`has no "${o.recency}" recency window; use day, week, month or year`);
178
+ if (!window) throw invalidRequest(provider, `has no "${o.recency}" recency window; use day, week, month or year`);
180
179
  return window;
181
180
  }
182
- if (o.publishedBefore !== void 0 && o.publishedAfter === void 0) throw invalid("needs publishedAfter with publishedBefore: its date range has two ends");
181
+ if (o.publishedBefore !== void 0 && o.publishedAfter === void 0) throw invalidRequest(provider, "needs publishedAfter with publishedBefore: its date range has two ends");
183
182
  if (o.publishedAfter === void 0) return;
184
183
  const after = o.publishedAfter;
185
184
  const before = o.publishedBefore ?? today();
186
- for (const date of [after, before]) if (!/^\d{4}-\d{2}-\d{2}$/u.test(date)) throw invalid(`dates must be YYYY-MM-DD, got "${date}"`);
185
+ 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}"`);
187
186
  return `${after}to${before}`;
188
187
  };
189
188
  const gogglesOf = (value) => {
190
189
  if (value === void 0) return;
191
190
  const all = Array.isArray(value) ? value : [value];
192
- if (all.length > 3) throw invalid("accepts at most 3 goggles per search");
191
+ if (all.length > 3) throw invalidRequest(provider, "accepts at most 3 goggles per search");
193
192
  return all;
194
193
  };
195
194
  const withQuery = (path, params) => {
@@ -303,7 +302,28 @@ const answerCitations = (content) => {
303
302
  url
304
303
  }));
305
304
  };
305
+ /**
306
+ * The answer text of a reply to `/chat/completions`, and the response to keep
307
+ * in `raw`. A stream arrives as event lines; a plain completion as one JSON
308
+ * object.
309
+ */
310
+ const replyContent = (reply) => {
311
+ if (!reply.trimStart().startsWith("{")) return {
312
+ content: streamText(reply),
313
+ response: reply
314
+ };
315
+ const completion = parseJson(provider, reply);
316
+ return {
317
+ content: completionText(z.parse(Completion, completion)),
318
+ response: completion
319
+ };
320
+ };
306
321
  // src/adapters/brave.ts
322
+ /**
323
+ * An adapter for Brave: search, images and answer. Pass it to `new Fieldwork({ adapter })`.
324
+ *
325
+ * Throws `Unauthorized` when neither `apiKey` nor `BRAVE_API_KEY` is set.
326
+ */
307
327
  const brave = (config = {}) => {
308
328
  const raw = createRawClient({
309
329
  baseUrl: config.baseUrl ?? "https://api.search.brave.com/res/v1",
@@ -330,7 +350,7 @@ const brave = (config = {}) => {
330
350
  type: "approximate"
331
351
  } : void 0
332
352
  });
333
- const response = await raw.request("POST", "/chat/completions", {
353
+ const reply = await raw.request("POST", "/chat/completions", {
334
354
  ...call,
335
355
  body: compact({
336
356
  country: upper(o.country),
@@ -345,10 +365,10 @@ const brave = (config = {}) => {
345
365
  safesearch: o.safesearch,
346
366
  stream: true,
347
367
  web_search_options: Object.keys(searchOptions).length > 0 ? searchOptions : void 0
348
- })
368
+ }),
369
+ text: true
349
370
  });
350
- const stream = z.safeParse(z.string(), response);
351
- const content = stream.success ? streamText(stream.data) : completionText(z.parse(Completion, response));
371
+ const { content, response } = replyContent(reply);
352
372
  const answer = content.replace(CITATION_TAG, "").replace(USAGE_TAG, "").trim();
353
373
  if (answer === "") throw new FieldworkError("ProviderError", "brave returned no answer text", {
354
374
  cause: response,
@@ -1,12 +1,11 @@
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";
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";
2
2
  export interface BrowserbaseConfig {
3
3
  /** Defaults to the BROWSERBASE_API_KEY environment variable. */
4
4
  apiKey?: string;
5
5
  /**
6
6
  * The project that new browser sessions belong to and whose usage `usage`
7
- * reads. Defaults to the BROWSERBASE_PROJECT_ID environment variable.
8
- * Browserbase infers the project from the API key when it is not set, and
9
- * `usage` then uses the key's only project.
7
+ * reads. Without it, Browserbase infers the project from the API key, and
8
+ * `usage` uses the key's only project.
10
9
  */
11
10
  projectId?: string;
12
11
  baseUrl?: string;
@@ -126,5 +125,10 @@ export interface BrowserbaseOperations {
126
125
  };
127
126
  usage: (options?: CallOptions) => Promise<AccountUsage>;
128
127
  }
128
+ /**
129
+ * An adapter for Browserbase: search, read, browser and usage. Pass it to `new Fieldwork({ adapter })`.
130
+ *
131
+ * Throws `Unauthorized` when neither `apiKey` nor `BROWSERBASE_API_KEY` is set.
132
+ */
129
133
  export declare const browserbase: (config?: BrowserbaseConfig) => Adapter<"browserbase", BrowserbaseOperations, RawClient>;
130
134
  export {};
@@ -1,6 +1,6 @@
1
- import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
- import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
- import { C as createRawClient, E as callSettings, I as refuseTogether, L as requireJobId, N as presentPage, 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, r as arrayOf, s as optionalAnyString } from "./parse-CxOri73y.js";
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";
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. */
@@ -50,6 +50,11 @@ const SEARCH_MODES = {
50
50
  ],
51
51
  parallel: ["fast", "advanced"]
52
52
  };
53
+ /**
54
+ * An adapter for Browserbase: search, read, browser and usage. Pass it to `new Fieldwork({ adapter })`.
55
+ *
56
+ * Throws `Unauthorized` when neither `apiKey` nor `BROWSERBASE_API_KEY` is set.
57
+ */
53
58
  const browserbase = (config = {}) => {
54
59
  const provider = "browserbase";
55
60
  const raw = createRawClient({
@@ -59,21 +64,18 @@ const browserbase = (config = {}) => {
59
64
  provider,
60
65
  retries: config.retries
61
66
  });
62
- const projectId = config.projectId ?? process.env.BROWSERBASE_PROJECT_ID;
63
- const invalid = (message) => {
64
- throw new FieldworkError("InvalidRequest", `${provider} ${message}`, { provider });
65
- };
67
+ const { projectId } = config;
66
68
  const fetchProxies = (o) => {
67
69
  refuseTogether(provider, o, "proxies", "country");
68
70
  const geolocation = o.country === void 0 ? void 0 : { country: o.country.toUpperCase() };
69
71
  const proxies = o.proxies ?? (geolocation ? { geolocation } : void 0);
70
72
  const place = typeof proxies === "object" ? proxies.geolocation : void 0;
71
- if (place !== void 0 && place.state !== void 0 && place.state !== "" && place.country.toUpperCase() !== "US") invalid("accepts a proxy state only with country US");
73
+ if (place !== void 0 && place.state !== void 0 && place.state !== "" && place.country.toUpperCase() !== "US") throw invalidRequest(provider, "accepts a proxy state only with country US");
72
74
  return proxies;
73
75
  };
74
76
  const liveView = async (id, call) => {
75
77
  try {
76
- const urls = z.parse(DebugResponse, await raw.request("GET", `/v1/sessions/${encodeURIComponent(id)}/debug`, call));
78
+ const urls = z.parse(DebugResponse, await raw.request("GET", `/v1/sessions/${segment(id)}/debug`, call));
77
79
  return { url: urls.debuggerFullscreenUrl ?? urls.debuggerUrl };
78
80
  } catch (error) {
79
81
  return { warning: `could not get the live view URL: ${error instanceof Error ? error.message : String(error)}` };
@@ -83,7 +85,7 @@ const browserbase = (config = {}) => {
83
85
  browser: {
84
86
  async close(id, options) {
85
87
  const { call } = callSettings(options);
86
- await raw.request("POST", `/v1/sessions/${encodeURIComponent(id)}`, {
88
+ await raw.request("POST", `/v1/sessions/${segment(id)}`, {
87
89
  ...call,
88
90
  body: { status: "REQUEST_RELEASE" }
89
91
  });
@@ -168,9 +170,9 @@ const browserbase = (config = {}) => {
168
170
  async search(query, options) {
169
171
  const { call, rest: o } = callSettings(options);
170
172
  if (o.mode !== void 0) {
171
- if (o.provider === void 0) invalid("accepts a search mode only together with provider");
173
+ if (o.provider === void 0) throw invalidRequest(provider, "accepts a search mode only together with provider");
172
174
  const allowed = SEARCH_MODES[o.provider];
173
- if (!allowed.includes(o.mode)) invalid(`search provider ${o.provider} has no mode ${o.mode}; use ${allowed.join(", ")}`);
175
+ if (!allowed.includes(o.mode)) throw invalidRequest(provider, `search provider ${o.provider} has no mode ${o.mode}; use ${allowed.join(", ")}`);
174
176
  }
175
177
  const response = await raw.request("POST", "/v1/search", {
176
178
  ...call,
@@ -198,7 +200,7 @@ const browserbase = (config = {}) => {
198
200
  async usage(options) {
199
201
  const { call } = callSettings(options);
200
202
  const id = projectId ?? await onlyProject(call);
201
- const response = await raw.request("GET", `/v1/projects/${encodeURIComponent(id)}/usage`, call);
203
+ const response = await raw.request("GET", `/v1/projects/${segment(id)}/usage`, call);
202
204
  const body = z.parse(UsageResponse, response);
203
205
  return compact({
204
206
  breakdown: Object.fromEntries(Object.entries({
@@ -211,7 +213,7 @@ const browserbase = (config = {}) => {
211
213
  };
212
214
  const onlyProject = async (call) => {
213
215
  const projects = z.parse(ProjectsResponse, await raw.request("GET", "/v1/projects", call));
214
- if (projects.length !== 1) invalid(`usage needs a project: pass projectId or set BROWSERBASE_PROJECT_ID (this key has ${projects.length} projects)`);
216
+ if (projects.length !== 1) throw invalidRequest(provider, `usage needs a project: pass projectId (this key has ${projects.length} projects)`);
215
217
  return requireJobId(provider, projects[0]?.id ?? {
216
218
  original: void 0,
217
219
  value: void 0