@howells/fieldwork-sdk 0.5.2 → 0.6.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, Browserbase, LlamaParse and Reducto.
3
+ One API for searching the web, reading pages, extracting values, walking sites, answering and researching questions, finding entities, watching for changes, driving a browser and parsing documents, across Exa, Firecrawl, Tavily, Parallel, Perplexity, Brave, SerpApi, Browserbase, Kernel, LlamaParse and Reducto.
4
4
 
5
5
  ```sh
6
6
  npm i @howells/fieldwork-sdk
@@ -24,25 +24,25 @@ Swap the adapter to switch providers. Everything below the constructor stays the
24
24
 
25
25
  Each instance has only the methods its provider offers, so a call the provider cannot serve does not compile. `new Fieldwork({ adapter: tavily() }).act(...)` is a type error, because Tavily has no browser. Untyped JavaScript gets a `FieldworkError` with code `Unsupported`, and no request is sent. Nothing falls back to another provider, and nothing is emulated: a provider without an answer endpoint has no `answer`, even though search plus a model could imitate one.
26
26
 
27
- | Method | Exa | Firecrawl | Tavily | Parallel | Perplexity | Brave | SerpApi | Browserbase | LlamaParse | Reducto |
28
- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
29
- | `search(query)` | yes | yes | yes | yes | yes | yes | yes | yes | | |
30
- | `images(query)` | | yes | yes | yes | | yes | yes | | | |
31
- | `read(url)` | yes | yes | yes | yes | | | | yes | | |
32
- | `readMany(urls)` | yes | yes | yes | yes | | | | | | |
33
- | `extract(url, { schema })` | yes | yes | | yes | | | | | | |
34
- | `product(url)` | | yes | | | | | | | | |
35
- | `map(url)` | | yes | yes | | | | | | | |
36
- | `crawl(url)` | | yes | yes | | | | | | | |
37
- | `answer(question)` | yes | | yes | yes | yes | yes | | | | |
38
- | `research(question)` | yes | yes | yes | yes | yes | | | | | |
39
- | `discover(objective, { entityType, conditions })` | | | | yes | | | | | | |
40
- | `decide(context, questions)` | | | | yes | yes | | | | | |
41
- | `act(code)` | | yes | | | | | | | | |
42
- | `browser.open()`, `browser.close(id)` | | yes | | | | | | yes | | |
43
- | `parse(document)` | | yes | | | | | | | yes | yes |
44
- | `monitor.create()`, `.get`, `.list`, `.delete`, `.events` | yes | yes | | yes | | | | | | |
45
- | `usage()` | | yes | yes | | | | yes | yes | | |
27
+ | Method | Exa | Firecrawl | Tavily | Parallel | Perplexity | Brave | SerpApi | Browserbase | Kernel | LlamaParse | Reducto |
28
+ | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
29
+ | `search(query)` | yes | yes | yes | yes | yes | yes | yes | yes | | | |
30
+ | `images(query)` | | yes | yes | yes | | yes | yes | | | | |
31
+ | `read(url)` | yes | yes | yes | yes | | | | yes | yes | | |
32
+ | `readMany(urls)` | yes | yes | yes | yes | | | | | | | |
33
+ | `extract(url, { schema })` | yes | yes | | yes | | | | | | | |
34
+ | `product(url)` | | yes | | | | | | | | | |
35
+ | `map(url)` | | yes | yes | | | | | | | | |
36
+ | `crawl(url)` | | yes | yes | | | | | | | | |
37
+ | `answer(question)` | yes | | yes | yes | yes | yes | | | | | |
38
+ | `research(question)` | yes | yes | yes | yes | yes | | | | | | |
39
+ | `discover(objective, { entityType, conditions })` | | | | yes | | | | | | | |
40
+ | `decide(context, questions)` | | | | yes | yes | | | | | | |
41
+ | `act(code)` | | yes | | | | | | | | | |
42
+ | `browser.open()`, `browser.close(id)` | | yes | | | | | | yes | yes | | |
43
+ | `parse(document)` | | yes | | | | | | | | yes | yes |
44
+ | `monitor.create()`, `.get`, `.list`, `.delete`, `.events` | yes | yes | | yes | | | | | | | |
45
+ | `usage()` | | yes | yes | | | | yes | yes | | | |
46
46
 
47
47
  `web.capabilities` and `web.supports("crawl")` report the same table at runtime.
48
48
 
@@ -69,7 +69,7 @@ Options are typed per provider. An option means the same thing under the same na
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. |
72
- | `resume`, `interval` | On jobs: collect an earlier job by its id, and the milliseconds between status checks. |
72
+ | `resume`, `interval` | On jobs: collect an earlier job by its id, and the milliseconds between status checks (unset: 500, doubling to 2000). |
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
 
@@ -110,7 +110,7 @@ A job that stopped early but produced output, for example on a credit or step li
110
110
 
111
111
  ### Long jobs
112
112
 
113
- Research, discovery, crawls, batch reads, Parallel extraction and LlamaParse and Reducto parses are polled until they finish. Pass `timeout` and `signal` to bound or cancel any call.
113
+ Research, discovery, crawls, batch reads, Parallel extraction and LlamaParse and Reducto parses are polled until they finish. A job status the provider does not document throws `ProviderError` with `jobId` at once, instead of polling until the timeout. Pass `timeout` and `signal` to bound or cancel any call.
114
114
 
115
115
  When a job outlasts `timeout`, or `signal` stops the wait, the provider keeps running it and charging for it. The error carries the job's id as `jobId`; pass it back as `resume` to collect the result instead of starting another job:
116
116
 
@@ -191,11 +191,11 @@ Every failure is a `FieldworkError`. It carries:
191
191
  | `NotFound` | The page, product or job does not exist. | Check the URL or id. |
192
192
  | `InvalidRequest` | The input was refused, by Fieldwork or by the provider. | Correct the input; the message says what is wrong. |
193
193
  | `JobFailed` | The job ended without a result. | Start a new job if needed; resuming fails again. |
194
- | `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat. |
194
+ | `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat when `retryable` is true. |
195
195
  | `Aborted` | `signal` cancelled the call. | With `jobId`, the job may still be running; pass it as `resume`. |
196
196
  | `ProviderError` | Any other provider failure. | Repeat when `retryable` is true (5xx and network failures). |
197
197
 
198
- An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job.
198
+ An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job. Nor is a failure, other than a rate limit, of the request that starts a job, session or monitor: the provider may already have started it, so check before repeating.
199
199
 
200
200
  ### Retries
201
201
 
@@ -265,9 +265,10 @@ On a router, `raw` is keyed by provider name.
265
265
  | `brave()` | `BRAVE_API_KEY` |
266
266
  | `serpapi()` | `SERPAPI_API_KEY` |
267
267
  | `browserbase()` | `BROWSERBASE_API_KEY` |
268
+ | `kernel()` | `KERNEL_API_KEY` |
268
269
  | `llamaparse()` | `LLAMA_CLOUD_API_KEY` |
269
270
  | `reducto()` | `REDUCTO_API_KEY` |
270
271
 
271
272
  Pass `apiKey` (and Browserbase's `projectId`) to override, and `fetch` to supply your own. Requests follow redirects only within the provider's origin; a redirect to any other host, scheme or port fails before the key is sent there.
272
273
 
273
- ESM only, Node 22 or later. The one dependency is Zod.
274
+ ESM only, Node 22 or later. The dependencies are Zod and, for Kernel's Markdown, Turndown.
@@ -518,7 +518,7 @@ interface RequestOptions extends CallOptions {
518
518
  * The request creates a job, session or monitor that the provider bills for
519
519
  * or keeps. After a 5xx or a dropped connection the provider may already
520
520
  * have created it, so only a rate limit, which it has certainly not acted
521
- * on, is retried.
521
+ * on, is retried, and any other failure is thrown not `retryable`.
522
522
  */
523
523
  creates?: boolean;
524
524
  /** The endpoint answers in text, such as an event stream, so its body is returned as a string. */
package/dist/brave.d.ts CHANGED
@@ -1,4 +1,4 @@
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-BhTK51Yj.js";
1
+ import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, t as Adapter } from "./adapter-Bh8EIrNe.js";
2
2
  /** Settings for `brave()`. */
3
3
  interface BraveConfig {
4
4
  /** Defaults to the BRAVE_API_KEY environment variable. */
package/dist/brave.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { C as createRawClient, F as parseJson, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf, z as refuseTogether } from "./parse-BY3R0oWO.js";
3
+ import { C as createRawClient, F as parseJson, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, l as optionalBoolean, o as nonEmptyString, r as arrayOf, v as recordOf, z as refuseTogether } from "./parse-COHKvfH9.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/brave/response.ts
6
6
  /** The `query` block every search response carries. */
@@ -140,6 +140,7 @@ const ALLOWED = {
140
140
  news: [
141
141
  ...SHARED,
142
142
  "vertical",
143
+ "content",
143
144
  "offset",
144
145
  "extraSnippets",
145
146
  "spellcheck",
@@ -150,6 +151,7 @@ const ALLOWED = {
150
151
  videos: [
151
152
  ...SHARED,
152
153
  "vertical",
154
+ "content",
153
155
  "offset",
154
156
  "spellcheck",
155
157
  "uiLanguage",
@@ -1,4 +1,4 @@
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-BhTK51Yj.js";
1
+ import { R as Page, Y as SearchResponse, a as RawClient, d as BrowserSession, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-Bh8EIrNe.js";
2
2
  /** Settings for `browserbase()`. */
3
3
  export interface BrowserbaseConfig {
4
4
  /** Defaults to the BROWSERBASE_API_KEY environment variable. */
@@ -34,7 +34,12 @@ export interface BrowserbaseReadOptions extends CallOptions {
34
34
  * content stays in `raw`, with a warning.
35
35
  */
36
36
  format?: "markdown" | "raw";
37
- /** Follow HTTP redirects. Browserbase defaults to false. */
37
+ /**
38
+ * Follow HTTP redirects. Browserbase defaults to false, which returns the
39
+ * 3xx response itself; Fieldwork defaults to true so a read of an http, www
40
+ * or trailing-slash URL returns the page. `false` returns the redirect
41
+ * response, with a warning.
42
+ */
38
43
  allowRedirects?: boolean;
39
44
  /** Skip TLS certificate verification, for self-signed or expired certificates. */
40
45
  allowInsecureSsl?: boolean;
@@ -1,6 +1,6 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest } from "./errors-DROZyb9T.js";
3
- import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, r as arrayOf, s as optionalAnyString, z as refuseTogether } from "./parse-BY3R0oWO.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, r as arrayOf, s as optionalAnyString, z as refuseTogether } from "./parse-COHKvfH9.js";
4
4
  import * as z from "zod/mini";
5
5
  // src/adapters/browserbase/response.ts
6
6
  /** `POST /v1/sessions`. The id keeps the value as it arrived, for the error raised when there is none. */
@@ -146,7 +146,7 @@ const browserbase = (config = {}) => {
146
146
  ...call,
147
147
  body: compact({
148
148
  allowInsecureSsl: o.allowInsecureSsl,
149
- allowRedirects: o.allowRedirects,
149
+ allowRedirects: o.allowRedirects ?? true,
150
150
  contextId: o.contextId,
151
151
  format,
152
152
  proxies: fetchProxies(o),
@@ -157,11 +157,13 @@ const browserbase = (config = {}) => {
157
157
  const { content } = body;
158
158
  const binary = body.encoding === "base64";
159
159
  const contentType = body.contentType ?? "";
160
+ const redirected = o.allowRedirects === false && body.statusCode !== void 0 && body.statusCode >= 300 && body.statusCode < 400;
161
+ const warnings = [...binary ? ["the response is binary; its Base64 content is in raw"] : [], ...redirected ? [`the page answered with a ${body.statusCode} redirect and allowRedirects is false, so nothing was followed`] : []];
160
162
  return presentPage(provider, compact({
161
163
  markdown: format === "markdown" && !binary ? content : void 0,
162
164
  meta: meta({
163
165
  requestId: body.id,
164
- warnings: binary ? ["the response is binary; its Base64 content is in raw"] : void 0
166
+ warnings: warnings.length > 0 ? warnings : void 0
165
167
  }),
166
168
  raw: response,
167
169
  rawHtml: format === "raw" && !binary && contentType.includes("html") ? content : void 0,
@@ -30,9 +30,12 @@ const refuseLarger = (provider, document, maxMegabytes) => {
30
30
  const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
31
31
  if (size > maxMegabytes * 1024 * 1024) throw new FieldworkError("InvalidRequest", `${provider} parses files up to ${maxMegabytes} MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`, { provider });
32
32
  };
33
+ /** Whether the bytes sit on an ArrayBuffer rather than a SharedArrayBuffer. */
34
+ const onArrayBuffer = (bytes) => bytes.buffer instanceof ArrayBuffer;
33
35
  /** The file's bytes as a multipart part, with the content type its extension names. */
34
36
  const documentPart = (document) => {
35
- const part = document.data instanceof Uint8Array ? new Uint8Array(document.data) : document.data;
37
+ const { data } = document;
38
+ const part = data instanceof Uint8Array && !onArrayBuffer(data) ? new Uint8Array(data) : data;
36
39
  return new Blob([part], { type: mediaTypeOf(document.name) ?? "application/octet-stream" });
37
40
  };
38
41
  /** The smallest box that holds every one of `boxes`, or undefined when there are none. */
package/dist/exa.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, l as Answer, p as CallOptions, q as Research, t as Adapter, z as PageBatch } from "./adapter-BhTK51Yj.js";
2
- import { t as OutputSchema } from "./schema-CNd51xdD.js";
1
+ import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, l as Answer, p as CallOptions, q as Research, t as Adapter, z as PageBatch } from "./adapter-Bh8EIrNe.js";
2
+ import { t as OutputSchema } from "./schema-BWWiMvkg.js";
3
3
  /** Settings for the Exa adapter. */
4
4
  interface ExaConfig {
5
5
  /** Defaults to the EXA_API_KEY environment variable. */
package/dist/exa.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, N as hours, P as meta, R as record, S as withOriginal, T as requireKey, V as uniqueCitations, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, j as citationsOf, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-BY3R0oWO.js";
4
- import { t as runJob } from "./job-DVsmQMKP.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, N as hours, P as meta, R as record, S as withOriginal, T as requireKey, V as uniqueCitations, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, j as citationsOf, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source } from "./parse-COHKvfH9.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-FE9e6HOI.js";
5
5
  import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
6
  import * as z from "zod/mini";
7
7
  const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
@@ -187,9 +187,20 @@ const researchBody = (question, o) => {
187
187
  systemPrompt: o.systemPrompt
188
188
  });
189
189
  };
190
+ const RUN_STATES = {
191
+ done: ["completed"],
192
+ failed: ["failed", "cancelled"],
193
+ running: ["queued", "running"]
194
+ };
195
+ /** The run once it has stopped, undefined while it runs. A failed or cancelled run can still carry partial output, so `researchResult` decides what it amounts to. */
196
+ const runState = (id, entry) => jobState("exa", id, RUN_STATES, {
197
+ original: entry.original,
198
+ value: entry.value.status
199
+ }) === "running" ? void 0 : entry;
190
200
  /**
191
201
  * The result of a finished run. A run that did not complete and has no output
192
- * throws `JobFailed` with Exa's error. Otherwise the result is `completed`
202
+ * throws `JobFailed` with Exa's error, and so does a completed run without
203
+ * it. Otherwise the result is `completed`
193
204
  * only when the run completed and stopped for no reason or with
194
205
  * `schema_satisfied`; any other finish is `partial`, with the stop reason.
195
206
  * `continuationId` is the run's id once it has completed.
@@ -218,7 +229,10 @@ const researchResult = (id, entry, structured) => {
218
229
  fields: fields.length > 0 ? fields : void 0,
219
230
  id,
220
231
  meta: runMeta(run),
221
- output: structured ? output.structured : output.text,
232
+ output: requireOutput("exa", id, {
233
+ original: entry.original,
234
+ value: structured ? output.structured : output.text
235
+ }),
222
236
  raw: entry.original,
223
237
  sources: uniqueCitations(fields.flatMap((field) => field.citations)),
224
238
  status: finished ? "completed" : "partial",
@@ -616,11 +630,7 @@ const exa = (config = {}) => {
616
630
  const { call, rest: o } = callSettings(options);
617
631
  checkResearch(o);
618
632
  return await runJob("exa", {
619
- check: async (id, request) => {
620
- const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request));
621
- const { status } = current.value;
622
- return status === "completed" || status === "failed" || status === "cancelled" ? current : void 0;
623
- },
633
+ check: async (id, request) => runState(id, z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request))),
624
634
  finish: async (run, id) => {
625
635
  const { outputSchema } = run.value.request;
626
636
  const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
@@ -630,11 +640,10 @@ const exa = (config = {}) => {
630
640
  output: await checkOutput(o.schema, result.output, { provider: "exa" })
631
641
  };
632
642
  },
633
- start: async () => requireJobId("exa", z.parse(RunStart, await raw.request("POST", "/agent/runs", {
634
- creates: true,
643
+ start: async () => await startJob(raw, "/agent/runs", {
635
644
  ...call,
636
645
  body: researchBody(question, o)
637
- })).id)
646
+ }, RunStart, (reply) => reply.id)
638
647
  }, {
639
648
  ...call,
640
649
  interval: o.interval,
@@ -1,4 +1,4 @@
1
- import { m as Capability, n as AnyAdapter } from "./adapter-BhTK51Yj.js";
1
+ import { m as Capability, n as AnyAdapter } from "./adapter-Bh8EIrNe.js";
2
2
  /** Why a call failed. Branch on this, not on the message, which can change. */
3
3
  type FieldworkErrorCode =
4
4
  /** The adapter's provider does not offer this capability. */
@@ -1,5 +1,5 @@
1
- import { B as ParsedDocument, C as DocumentInput, E as Extraction, F as MonitorEvents, I as MonitorInfo, K as Recency, L as MonitorSchedule, Q as SiteMap, R as Page, U as Product, Y as SearchResponse, _ as Crawl, a as RawClient, c as ActResult, d as BrowserSession, j as ImageSearch, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-BhTK51Yj.js";
2
- import { t as OutputSchema } from "./schema-CNd51xdD.js";
1
+ import { B as ParsedDocument, C as DocumentInput, E as Extraction, F as MonitorEvents, I as MonitorInfo, K as Recency, L as MonitorSchedule, Q as SiteMap, R as Page, U as Product, Y as SearchResponse, _ as Crawl, a as RawClient, c as ActResult, d as BrowserSession, j as ImageSearch, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-Bh8EIrNe.js";
2
+ import { t as OutputSchema } from "./schema-BWWiMvkg.js";
3
3
  /** Settings for the Firecrawl adapter. */
4
4
  interface FirecrawlConfig {
5
5
  /** Defaults to the FIRECRAWL_API_KEY environment variable. */
package/dist/firecrawl.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-BY3R0oWO.js";
4
- import { t as runJob } from "./job-DVsmQMKP.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-COHKvfH9.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-FE9e6HOI.js";
5
5
  import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
- import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-CjMeBtV5.js";
6
+ import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-Clmi51Sf.js";
7
7
  import * as z from "zod/mini";
8
8
  // src/adapters/firecrawl/shared.ts
9
9
  const provider = "firecrawl";
@@ -511,6 +511,31 @@ const failedPages = (errors) => errors.value.errors.map((entry) => ({
511
511
  error: entry.error ?? "unknown error",
512
512
  url: entry.url ?? ""
513
513
  }));
514
+ const BATCH_STATES = {
515
+ done: ["completed"],
516
+ failed: ["failed", "cancelled"],
517
+ missingIsRunning: true,
518
+ running: ["scraping"]
519
+ };
520
+ const AGENT_STATES = {
521
+ done: ["completed"],
522
+ failed: ["failed", "cancelled"],
523
+ missingIsRunning: true,
524
+ running: ["processing"]
525
+ };
526
+ /** A crawl or batch scrape when it has finished, undefined while it runs; throws `JobFailed` when it failed or was cancelled. */
527
+ const batchState = (kind, id, entry) => {
528
+ const { status } = entry.value;
529
+ const state = jobState(provider, id, BATCH_STATES, {
530
+ original: entry.original,
531
+ value: status
532
+ });
533
+ if (state === "failed") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${status}`, {
534
+ cause: entry.original,
535
+ provider
536
+ });
537
+ return state === "done" ? entry : void 0;
538
+ };
514
539
  /**
515
540
  * The run when it has finished, undefined while it runs. A `failed` run that
516
541
  * left partial output counts as finished; any other `failed` or `cancelled`
@@ -518,20 +543,22 @@ const failedPages = (errors) => errors.value.errors.map((entry) => ({
518
543
  */
519
544
  const researchState = (id, entry) => {
520
545
  const status = entry.value;
521
- const state = status.status;
546
+ const state = jobState(provider, id, AGENT_STATES, {
547
+ original: entry.original,
548
+ value: status.status
549
+ });
522
550
  const hasPartial = status.partial !== void 0 && status.partial !== null;
523
- const done = state === "completed" || state === "failed" && hasPartial;
524
- if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
551
+ if (state === "failed" && !(status.status === "failed" && hasPartial)) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${status.status}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
525
552
  cause: entry.original,
526
553
  provider
527
554
  });
528
- return done ? entry : void 0;
555
+ return state === "running" ? void 0 : entry;
529
556
  };
530
557
  /**
531
558
  * The result of a finished run. A `failed` run with partial output is
532
559
  * `partial`, with that output and a `stopReason`; any other is `completed`
533
- * with `data`, else the message. `sources` is always empty. The continuation
534
- * id is the run's thread.
560
+ * with `data`, else the message, and throws `JobFailed` when it has neither.
561
+ * `sources` is always empty. The continuation id is the run's thread.
535
562
  */
536
563
  const researchResult = (id, started, entry) => {
537
564
  const run = entry.value;
@@ -545,7 +572,10 @@ const researchResult = (id, started, entry) => {
545
572
  requestId: id,
546
573
  warnings: stopped ? [run.message.note, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0].filter((note) => note !== void 0) : void 0
547
574
  }),
548
- output: stopped ? run.partial : run.data ?? run.message.value,
575
+ output: stopped ? run.partial : requireOutput(provider, id, {
576
+ original: entry.original,
577
+ value: run.data ?? run.message.value
578
+ }),
549
579
  raw: entry.original,
550
580
  sources: [],
551
581
  status,
@@ -1001,26 +1031,18 @@ const firecrawl = (config = {}) => {
1001
1031
  response
1002
1032
  };
1003
1033
  };
1004
- /** The path of a `next` link, relative to the base URL, so the next page of results goes through the same client. */
1034
+ /** The path of a `next` link, absolute or relative to the base URL, so the next page of results goes through the same client. */
1005
1035
  const pathOf = (link) => {
1006
- const next = new URL(link);
1007
- const base = new URL(baseUrl).pathname.replace(/\/$/u, "");
1008
- return next.pathname.slice(base.length) + next.search;
1036
+ const base = new URL(`${baseUrl.replace(/\/$/u, "")}/`);
1037
+ const next = new URL(link, base);
1038
+ return next.pathname.slice(base.pathname.length - 1) + next.search;
1009
1039
  };
1010
1040
  /**
1011
1041
  * Runs a crawl or batch scrape: waits for it, then reads every page of its
1012
1042
  * results and the pages that failed.
1013
1043
  */
1014
1044
  const batchJob = async (kind, start, settings, finish) => await runJob(provider, {
1015
- check: async (id, request) => {
1016
- const status = z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request));
1017
- const state = status.value.status;
1018
- if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
1019
- cause: status.original,
1020
- provider
1021
- });
1022
- return state === "completed" ? status : void 0;
1023
- },
1045
+ check: async (id, request) => batchState(kind, id, z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request))),
1024
1046
  finish: async (first, id) => {
1025
1047
  const path = `/${kind}/${segment(id)}`;
1026
1048
  const request = {
@@ -1120,27 +1142,27 @@ const firecrawl = (config = {}) => {
1120
1142
  },
1121
1143
  async crawl(url, options) {
1122
1144
  const { call, rest: o } = callSettings(options);
1123
- return await batchJob("crawl", async () => requireJobId(provider, z.parse(CrawlStart, await raw.request("POST", "/crawl", {
1124
- creates: true,
1145
+ return await batchJob("crawl", async () => await startJob(raw, "/crawl", {
1125
1146
  ...call,
1126
1147
  body: crawlBody(url, o)
1127
- })).id), {
1148
+ }, CrawlStart, (reply) => reply.id), {
1128
1149
  ...call,
1129
1150
  interval: o.interval,
1130
1151
  resume: o.resume
1131
1152
  }, (job, id) => {
1132
1153
  const { robotsBlocked } = job.errors.value;
1154
+ const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1155
+ ...toPage(item.value, url),
1156
+ raw: item.original
1157
+ }))));
1133
1158
  return compact({
1134
- failed: job.failed,
1159
+ failed: [...job.failed, ...gone],
1135
1160
  id,
1136
1161
  meta: meta({
1137
1162
  credits: job.first.value.creditsUsed,
1138
1163
  requestId: id
1139
1164
  }),
1140
- pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1141
- ...toPage(item.value, url),
1142
- raw: item.original
1143
- }))),
1165
+ pages,
1144
1166
  raw: {
1145
1167
  batches: job.batches.map((batch) => batch.original),
1146
1168
  errors: job.errors.original
@@ -1158,6 +1180,10 @@ const firecrawl = (config = {}) => {
1158
1180
  schema: jsonSchemaOf(schema),
1159
1181
  type: "json"
1160
1182
  })], page, call);
1183
+ presentPage(provider, {
1184
+ ...toPage(data, url),
1185
+ raw: response
1186
+ });
1161
1187
  if (data.json === void 0) {
1162
1188
  const why = data.warning.text;
1163
1189
  throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why === void 0 ? "" : `: ${why}`}`, {
@@ -1285,19 +1311,18 @@ const firecrawl = (config = {}) => {
1285
1311
  const { call, rest: o } = callSettings(options);
1286
1312
  const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
1287
1313
  let started = z.parse(RunStart, {});
1288
- return await batchJob("batch/scrape", async () => {
1289
- started = z.parse(RunStart, await raw.request("POST", "/batch/scrape", {
1290
- creates: true,
1291
- ...call,
1292
- body: compact({
1293
- urls,
1294
- ...readBody(read),
1295
- maxConcurrency,
1296
- ignoreInvalidURLs
1297
- })
1298
- }));
1299
- return requireJobId(provider, started.value.id);
1300
- }, {
1314
+ return await batchJob("batch/scrape", async () => await startJob(raw, "/batch/scrape", {
1315
+ ...call,
1316
+ body: compact({
1317
+ urls,
1318
+ ...readBody(read),
1319
+ maxConcurrency,
1320
+ ignoreInvalidURLs
1321
+ })
1322
+ }, RunStart, (reply) => {
1323
+ started = reply;
1324
+ return reply.value.id;
1325
+ }), {
1301
1326
  ...call,
1302
1327
  interval,
1303
1328
  resume
@@ -1342,14 +1367,13 @@ const firecrawl = (config = {}) => {
1342
1367
  output: await checkOutput(o.schema, result.output, { provider })
1343
1368
  };
1344
1369
  },
1345
- start: async () => {
1346
- started = z.parse(RunStart, await raw.request("POST", "/agent", {
1347
- creates: true,
1348
- ...call,
1349
- body: researchBody(question, o)
1350
- }));
1351
- return requireJobId(provider, started.value.id);
1352
- }
1370
+ start: async () => await startJob(raw, "/agent", {
1371
+ ...call,
1372
+ body: researchBody(question, o)
1373
+ }, RunStart, (reply) => {
1374
+ started = reply;
1375
+ return reply.value.id;
1376
+ })
1353
1377
  }, {
1354
1378
  ...call,
1355
1379
  interval: o.interval,
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { $ as TableCell, A as ImageResult, B as ParsedDocument, C as DocumentInput, D as FailedUrl, E as Extraction, F as MonitorEvents, G as ProductVariant, H as Price, I as MonitorInfo, J as RunStatus, K as Recency, L as MonitorSchedule, M as JsonSchema, N as Meta, O as FieldSource, P as MonitorEvent, Q as SiteMap, R as Page, S as DocumentBlock, T as Entity, U as Product, V as Place, W as ProductImage, X as SearchResult, Y as SearchResponse, Z as SiteLink, _ as Crawl, a as RawClient, b as Decisions, c as ActResult, d as BrowserSession, et as Usage, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, j as ImageSearch, k as GROUP_CAPABILITIES, l as Answer, m as Capability, n as AnyAdapter, o as RequestOptions, p as CallOptions, q as Research, r as Operations, s as AccountUsage, t as Adapter, tt as WordBox, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-BhTK51Yj.js";
2
- import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-CseCD_-H.js";
3
- import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-CNd51xdD.js";
1
+ import { $ as TableCell, A as ImageResult, B as ParsedDocument, C as DocumentInput, D as FailedUrl, E as Extraction, F as MonitorEvents, G as ProductVariant, H as Price, I as MonitorInfo, J as RunStatus, K as Recency, L as MonitorSchedule, M as JsonSchema, N as Meta, O as FieldSource, P as MonitorEvent, Q as SiteMap, R as Page, S as DocumentBlock, T as Entity, U as Product, V as Place, W as ProductImage, X as SearchResult, Y as SearchResponse, Z as SiteLink, _ as Crawl, a as RawClient, b as Decisions, c as ActResult, d as BrowserSession, et as Usage, f as CAPABILITIES, g as Condition, h as Citation, i as defineAdapter, j as ImageSearch, k as GROUP_CAPABILITIES, l as Answer, m as Capability, n as AnyAdapter, o as RequestOptions, p as CallOptions, q as Research, r as Operations, s as AccountUsage, t as Adapter, tt as WordBox, u as Box, v as DecisionAnswer, w as DocumentPage, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-Bh8EIrNe.js";
2
+ import { i as FieldworkErrorCode, n as FieldworkOptions, r as FieldworkError, t as Fieldwork } from "./fieldwork-BaWqUNI3.js";
3
+ import { n as StandardSchemaWithJSON, t as OutputSchema } from "./schema-BWWiMvkg.js";
4
4
  /** Which adapter serves each capability, for `router`. */
5
5
  type Routes = Partial<Record<Capability, AnyAdapter>>;
6
6
  /** Each route must name an adapter whose provider offers that capability. */
package/dist/index.js CHANGED
@@ -23,7 +23,7 @@ const unsupported = (provider, capability) => {
23
23
  throw new FieldworkError("Unsupported", `${provider} does not offer ${capability}`, { provider });
24
24
  };
25
25
  if (!GROUP_CAPABILITIES.includes(capability)) return refuse;
26
- return new Proxy({}, { get: () => refuse });
26
+ return new Proxy({}, { get: (_target, key) => typeof key === "symbol" || key === "then" ? void 0 : refuse });
27
27
  };
28
28
  /**
29
29
  * The implementation behind `Fieldwork`, typed loosely: each capability name