@howells/fieldwork-sdk 0.2.0 → 0.3.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, running research, driving a browser and parsing documents, across Exa, Firecrawl, Tavily, Parallel and Perplexity.
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.
4
4
 
5
5
  ```sh
6
6
  npm i @howells/fieldwork-sdk
@@ -22,35 +22,75 @@ Swap the adapter to switch providers. Everything below the constructor stays the
22
22
 
23
23
  ## Capabilities
24
24
 
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.
26
-
27
- | Method | Exa | Firecrawl | Tavily | Parallel | Perplexity |
28
- | --- | --- | --- | --- | --- | --- |
29
- | `search(query)` | yes | yes | yes | yes | yes |
30
- | `read(url)` | yes | yes | yes | yes | |
31
- | `extract(url, { schema })` | yes | yes | | yes | |
32
- | `product(url)` | | yes | | | |
33
- | `map(url)` | | yes | yes | | |
34
- | `crawl(url)` | | yes | yes | | |
35
- | `research(question)` | yes | yes | yes | yes | yes |
36
- | `act(code)` | | yes | | | |
37
- | `parse(document)` | | yes | | | |
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
+
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 |
38
46
 
39
47
  `web.capabilities` and `web.supports("crawl")` report the same table at runtime.
40
48
 
41
- Options are typed per provider too. Shared ideas share a name (`limit`, `includeDomains`, `excludeDomains`, `publishedAfter`, `country`); options only one provider has keep that provider's meaning, such as Tavily's `topic` or Exa's `category`.
49
+ - `answer` is a provider's own cited answer, returned in one call. `research` is a longer job of many steps, polled until it finishes.
50
+ - `discover` returns a list of entities, such as companies or products, that meet every condition you give.
51
+ - `decide` answers closed questions about a context: yes or no, a choice, or a score on a rubric, each with a probability.
52
+ - `browser.open()` starts a remote browser and returns its CDP URL for Playwright or Puppeteer; `act(code)` runs one script in a fresh session.
53
+ - `monitor` repeats a search or a page check on a schedule and reports what changed. Exa and Parallel monitors watch a query; Firecrawl monitors also watch specific pages (`urls`).
54
+
55
+ ### Options
56
+
57
+ Options are typed per provider. An option means the same thing under the same name everywhere:
58
+
59
+ | Option | Meaning |
60
+ | --- | --- |
61
+ | `limit` | The most results or pages to return. |
62
+ | `includeDomains`, `excludeDomains` | Plain domains such as `example.com`. Options that take regular expressions or paths have their own names, such as Firecrawl's `includePaths`. |
63
+ | `publishedAfter`, `publishedBefore` | Dates as `YYYY-MM-DD`. |
64
+ | `recency` | `"hour"`, `"day"`, `"week"`, `"month"` or `"year"`, narrowed to what the provider supports. |
65
+ | `maxAge` | Seconds a cached copy may be old; `0` always fetches the page fresh. |
66
+ | `country` | An ISO 3166-1 code such as `"GB"`. |
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. |
69
+ | `query` | On `read`: return the passages that answer it as `excerpts`. |
70
+ | `content` | On `search`: include each result's page text. |
71
+ | `continueFrom` | On `answer` and `research`: the `continuationId` of an earlier result, to ask a follow-up. |
72
+ | `resume`, `interval` | On jobs: collect an earlier job by its id, and the milliseconds between status checks. |
73
+
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.
42
75
 
43
76
  ## Results
44
77
 
45
- Every result is normalized and keeps the provider's response in `raw`:
78
+ 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.
79
+
80
+ - `search` returns `{ results, answer, images, meta, raw }`. Each result has `url`, `title`, `snippet` and, when the provider has them, `content`, `publishedAt`, `author`, `image`, `favicon` and `score`. Shopping, place, news, scholar and patent results set `kind` and carry `price`, `rating`, `reviewCount` and `place`.
81
+ - `read` returns a `Page`: `url`, `title`, `description`, `markdown`, `html`, `links`, `images`, `image` (the page's main image), `excerpts`, `summary`, `publishedAt`, `author`, `language`, `statusCode` and `screenshot`, as the provider has them. A page that answered 404 or 410 is not returned: `read` throws `NotFound` on every provider, and `readMany` lists the URL in `failed`.
82
+ - `readMany` returns `{ pages, failed }`. A URL that could not be read is listed in `failed` with the reason; it does not throw.
83
+ - `extract` returns `{ data, fields }`. `data` follows your schema; `fields` lists each field's citations when the provider returns them.
84
+ - `product` returns the product and its `variants`, each with `sku`, option `values`, `price` (`amount`, `currency`, `formatted`), `originalPrice`, `availability`, `gtin` and `images` (`{ url, alt }`).
85
+ - `answer` returns `{ answer, output, citations, continuationId }`.
86
+ - `research` returns `{ id, status, output, sources, fields, continuationId }`. `output` follows your schema when you pass one, otherwise it is the report text.
87
+ - `crawl` returns `{ pages, failed, robotsBlocked, total }`.
88
+
89
+ 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`.
46
90
 
47
- - `search` returns `{ results: [{ url, title, snippet, content, publishedAt, score }], answer, raw }`.
48
- - `read` returns a `Page`: `{ url, title, markdown, html, rawHtml, links, images, excerpts, raw }`.
49
- - `extract` returns `{ data, fields, raw }`. `data` follows your schema; `fields` lists each field's citations when the provider returns them (Parallel).
50
- - `research` returns `{ id, output, sources, fields, raw }`. `output` follows your schema when you pass one, otherwise it is the report text. Exa and Parallel return per-field sources in `fields`.
51
- - `product` returns `{ title, brand, category, url, variants: [{ sku, values, price, inStock, images }], raw }`.
91
+ ### Long jobs
52
92
 
53
- Asynchronous jobs (research on Exa, Firecrawl, Tavily and Parallel, Parallel extraction, and Firecrawl crawls) are polled until they finish. Pass `timeout` and `signal` to bound or cancel any call.
93
+ Research, discovery, crawls, batch reads and Parallel extraction are polled until they finish. Pass `timeout` and `signal` to bound or cancel any call.
54
94
 
55
95
  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:
56
96
 
@@ -65,27 +105,50 @@ try {
65
105
  }
66
106
  ```
67
107
 
108
+ ### Monitors and browsers
109
+
110
+ `monitor` and `browser` are groups of methods:
111
+
112
+ ```ts
113
+ const watch = await web.monitor.create({
114
+ urls: ["https://www.tilebar.com/portmore-aqua"],
115
+ query: "price or stock changes",
116
+ schedule: { every: "day" },
117
+ webhookUrl: "https://example.com/hooks/fieldwork",
118
+ });
119
+ const { events } = await web.monitor.events(watch.id);
120
+ await web.monitor.delete(watch.id);
121
+
122
+ const session = await web.browser.open();
123
+ // connect Playwright to session.cdpUrl
124
+ await web.browser.close(session.id);
125
+ ```
126
+
127
+ A schedule is `{ every: "day" }`, `{ every: "6h" }` or `{ cron: "0 9 * * 1" }`. A schedule the provider cannot express throws `InvalidRequest`.
128
+
68
129
  ## Choosing a provider per capability
69
130
 
70
131
  `router` sends each capability to exactly one adapter:
71
132
 
72
133
  ```ts
73
134
  import { Fieldwork, router } from "@howells/fieldwork-sdk";
135
+ import { brave } from "@howells/fieldwork-sdk/brave";
74
136
  import { exa } from "@howells/fieldwork-sdk/exa";
75
137
  import { firecrawl } from "@howells/fieldwork-sdk/firecrawl";
76
138
  import { parallel } from "@howells/fieldwork-sdk/parallel";
77
139
 
78
140
  const web = new Fieldwork({
79
141
  adapter: router({
80
- search: parallel(),
142
+ search: brave(),
81
143
  read: firecrawl(),
82
144
  product: firecrawl(),
145
+ answer: parallel(),
83
146
  research: exa(),
84
147
  }),
85
148
  });
86
149
  ```
87
150
 
88
- A capability without a route is unsupported. A route to an adapter that lacks the capability is a type error and throws when the router is built.
151
+ A capability without a route is unsupported. A route to an adapter that lacks the capability is a type error and throws when the router is built. For routes known only at run time, such as from flags or configuration, `runtimeRouter(routes)` makes the same check when it is called.
89
152
 
90
153
  ## Errors
91
154
 
@@ -106,7 +169,7 @@ Every failure is a `FieldworkError`. It carries:
106
169
  | `Unauthorized` | The key is missing, wrong or not allowed. | Fix the key. Repeating does not help. |
107
170
  | `RateLimited` | A rate or plan limit was reached. | Wait `retryAfter` seconds, then repeat. |
108
171
  | `NotFound` | The page, product or job does not exist. | Check the URL or id. |
109
- | `InvalidRequest` | The provider rejected the input. | Correct the input; the message says what is wrong. |
172
+ | `InvalidRequest` | The input was refused, by Fieldwork or by the provider. | Correct the input; the message says what is wrong. |
110
173
  | `JobFailed` | The job ended without a result. | Start a new job if needed; resuming fails again. |
111
174
  | `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat. |
112
175
  | `Aborted` | `signal` cancelled the call. | With `jobId`, the job may still be running; pass it as `resume`. |
@@ -116,7 +179,7 @@ An error with a `jobId` is never `retryable`, because repeating the call would s
116
179
 
117
180
  ## Agent tools
118
181
 
119
- `@howells/fieldwork-sdk/tools` turns an instance into tool definitions for a model: one per capability, named `search_web`, `read_page`, `extract_values`, `read_product`, `map_site`, `crawl_site`, `research_question`, `parse_document` and `run_browser_script`. Each tool has:
182
+ `@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:
120
183
 
121
184
  - a description that says when to use it and which tool to use instead;
122
185
  - a JSON Schema input that lists only the options its provider supports;
@@ -142,7 +205,7 @@ const tools = Object.fromEntries(
142
205
  );
143
206
  ```
144
207
 
145
- `run_browser_script` runs code in a remote browser, so it is left out unless you name it: `toolsFor(web, { capabilities: ["read", "act"] })`. `toolError(error)` formats an error for a model.
208
+ Tools that start remote browsers or create lasting, billed resources are left out unless you allow them: `toolsFor(web, { allow: ["act", "browser", "monitor"] })`. `toolError(error)` formats an error for a model.
146
209
 
147
210
  For MCP clients such as Claude, Cursor and Codex, [`@howells/fieldwork-mcp`](https://www.npmjs.com/package/@howells/fieldwork-mcp) serves these tools over stdio.
148
211
 
@@ -151,9 +214,9 @@ For MCP clients such as Claude, Cursor and Codex, [`@howells/fieldwork-mcp`](htt
151
214
  `web.raw.request(method, path, options)` calls the provider's HTTP API with authentication applied, for anything Fieldwork does not wrap:
152
215
 
153
216
  ```ts
154
- const usage = await new Fieldwork({ adapter: tavily() }).raw.request(
217
+ const check = await new Fieldwork({ adapter: firecrawl() }).raw.request(
155
218
  "GET",
156
- "/usage"
219
+ `/monitor/${monitorId}/checks/${checkId}`
157
220
  );
158
221
  ```
159
222
 
@@ -161,14 +224,17 @@ On a router, `raw` is keyed by provider name.
161
224
 
162
225
  ## Keys
163
226
 
164
- | Adapter | Environment variable |
165
- | ----------------------- | -------------------- |
166
- | `exa()` | `EXA_API_KEY` |
167
- | `firecrawl()` | `FIRECRAWL_API_KEY` |
168
- | `tavily()` | `TAVILY_API_KEY` |
169
- | `parallel()` | `PARALLEL_API_KEY` |
170
- | `perplexity({ model })` | `PERPLEXITY_API_KEY` |
171
-
172
- Pass `apiKey` to override. Perplexity research also needs a `model`, on the adapter or the call.
227
+ | Adapter | Environment variable |
228
+ | --- | --- |
229
+ | `exa()` | `EXA_API_KEY` |
230
+ | `firecrawl()` | `FIRECRAWL_API_KEY` |
231
+ | `tavily()` | `TAVILY_API_KEY` |
232
+ | `parallel()` | `PARALLEL_API_KEY` |
233
+ | `perplexity()` | `PERPLEXITY_API_KEY` |
234
+ | `brave()` | `BRAVE_API_KEY` |
235
+ | `serpapi()` | `SERPAPI_API_KEY` |
236
+ | `browserbase()` | `BROWSERBASE_API_KEY`, and optionally `BROWSERBASE_PROJECT_ID` |
237
+
238
+ 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.
173
239
 
174
240
  ESM only, Node 22 or later. No dependencies.
@@ -0,0 +1,3 @@
1
+ // src/adapter.ts
2
+ const defineAdapter = (adapter) => adapter;
3
+ export { defineAdapter as t };