@howells/fieldwork-sdk 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Daniel Howells
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,240 @@
1
- # Temporary Holding Version
1
+ # Fieldwork
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+
5
+ ```sh
6
+ npm i @howells/fieldwork-sdk
7
+ ```
8
+
9
+ ```ts
10
+ import { Fieldwork } from "@howells/fieldwork-sdk";
11
+ import { firecrawl } from "@howells/fieldwork-sdk/firecrawl";
12
+
13
+ // Reads FIRECRAWL_API_KEY
14
+ const web = new Fieldwork({ adapter: firecrawl() });
15
+
16
+ const { results } = await web.search("TileBar Portmore Aqua 3x8");
17
+ const page = await web.read(results[0].url);
18
+ const product = await web.product(page.url); // variants, without a model
19
+ ```
20
+
21
+ Swap the adapter to switch providers. Everything below the constructor stays the same, as long as the new provider offers the capability.
22
+
23
+ ## Capabilities
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, 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 |
46
+
47
+ `web.capabilities` and `web.supports("crawl")` report the same table at runtime.
48
+
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.
75
+
76
+ ## Results
77
+
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.
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`.
90
+
91
+ ### Long jobs
92
+
93
+ Research, discovery, crawls, batch reads and Parallel extraction are polled until they finish. Pass `timeout` and `signal` to bound or cancel any call.
94
+
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:
96
+
97
+ ```ts
98
+ try {
99
+ return await web.research(question, { timeout: 60_000 });
100
+ } catch (error) {
101
+ if (error instanceof FieldworkError && error.jobId) {
102
+ return await web.research(question, { resume: error.jobId });
103
+ }
104
+ throw error;
105
+ }
106
+ ```
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
+
129
+ ## Choosing a provider per capability
130
+
131
+ `router` sends each capability to exactly one adapter:
132
+
133
+ ```ts
134
+ import { Fieldwork, router } from "@howells/fieldwork-sdk";
135
+ import { brave } from "@howells/fieldwork-sdk/brave";
136
+ import { exa } from "@howells/fieldwork-sdk/exa";
137
+ import { firecrawl } from "@howells/fieldwork-sdk/firecrawl";
138
+ import { parallel } from "@howells/fieldwork-sdk/parallel";
139
+
140
+ const web = new Fieldwork({
141
+ adapter: router({
142
+ search: brave(),
143
+ read: firecrawl(),
144
+ product: firecrawl(),
145
+ answer: parallel(),
146
+ research: exa(),
147
+ }),
148
+ });
149
+ ```
150
+
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.
152
+
153
+ ## Errors
154
+
155
+ Every failure is a `FieldworkError`. It carries:
156
+
157
+ - `code`, one of the codes below;
158
+ - `provider` and the HTTP `status`;
159
+ - `retryable`: whether repeating the same call can succeed;
160
+ - `retryAfter`, in seconds, when the provider sent one;
161
+ - `jobId`, when a job had already started;
162
+ - the provider's response, as `cause`.
163
+
164
+ `error.toJSON()` returns these fields without the provider's response.
165
+
166
+ | Code | What happened | What to do |
167
+ | --- | --- | --- |
168
+ | `Unsupported` | The provider does not offer this capability. | Use an adapter that does. Nothing was sent. |
169
+ | `Unauthorized` | The key is missing, wrong or not allowed. | Fix the key. Repeating does not help. |
170
+ | `RateLimited` | A rate or plan limit was reached. | Wait `retryAfter` seconds, then repeat. |
171
+ | `NotFound` | The page, product or job does not exist. | Check the URL or id. |
172
+ | `InvalidRequest` | The input was refused, by Fieldwork or by the provider. | Correct the input; the message says what is wrong. |
173
+ | `JobFailed` | The job ended without a result. | Start a new job if needed; resuming fails again. |
174
+ | `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat. |
175
+ | `Aborted` | `signal` cancelled the call. | With `jobId`, the job may still be running; pass it as `resume`. |
176
+ | `ProviderError` | Any other provider failure. | Repeat when `retryable` is true (5xx and network failures). |
177
+
178
+ An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job.
179
+
180
+ ## Agent tools
181
+
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:
183
+
184
+ - a description that says when to use it and which tool to use instead;
185
+ - a JSON Schema input that lists only the options its provider supports;
186
+ - an output schema;
187
+ - MCP annotations.
188
+
189
+ `execute(input)` checks the input, calls the capability, and returns the result without `raw`, with long text cut to a shared budget of 20,000 characters (`maxCharacters`).
190
+
191
+ ```ts
192
+ import { jsonSchema, tool } from "ai";
193
+ import { toolsFor } from "@howells/fieldwork-sdk/tools";
194
+
195
+ const tools = Object.fromEntries(
196
+ toolsFor(web).map((t) => [
197
+ t.name,
198
+ tool({
199
+ description: t.description,
200
+ inputSchema: jsonSchema(t.inputSchema),
201
+ execute: (input, { abortSignal }) =>
202
+ t.execute(input, { signal: abortSignal }),
203
+ }),
204
+ ])
205
+ );
206
+ ```
207
+
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.
209
+
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.
211
+
212
+ ## The provider's own API
213
+
214
+ `web.raw.request(method, path, options)` calls the provider's HTTP API with authentication applied, for anything Fieldwork does not wrap:
215
+
216
+ ```ts
217
+ const check = await new Fieldwork({ adapter: firecrawl() }).raw.request(
218
+ "GET",
219
+ `/monitor/${monitorId}/checks/${checkId}`
220
+ );
221
+ ```
222
+
223
+ On a router, `raw` is keyed by provider name.
224
+
225
+ ## Keys
226
+
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.
239
+
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 };