@howells/fieldwork-sdk 0.0.0-stage → 0.2.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,174 @@
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, running research, driving a browser and parsing documents, across Exa, Firecrawl, Tavily, Parallel and Perplexity.
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.
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 | | | |
38
+
39
+ `web.capabilities` and `web.supports("crawl")` report the same table at runtime.
40
+
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`.
42
+
43
+ ## Results
44
+
45
+ Every result is normalized and keeps the provider's response in `raw`:
46
+
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 }`.
52
+
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.
54
+
55
+ 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
+
57
+ ```ts
58
+ try {
59
+ return await web.research(question, { timeout: 60_000 });
60
+ } catch (error) {
61
+ if (error instanceof FieldworkError && error.jobId) {
62
+ return await web.research(question, { resume: error.jobId });
63
+ }
64
+ throw error;
65
+ }
66
+ ```
67
+
68
+ ## Choosing a provider per capability
69
+
70
+ `router` sends each capability to exactly one adapter:
71
+
72
+ ```ts
73
+ import { Fieldwork, router } from "@howells/fieldwork-sdk";
74
+ import { exa } from "@howells/fieldwork-sdk/exa";
75
+ import { firecrawl } from "@howells/fieldwork-sdk/firecrawl";
76
+ import { parallel } from "@howells/fieldwork-sdk/parallel";
77
+
78
+ const web = new Fieldwork({
79
+ adapter: router({
80
+ search: parallel(),
81
+ read: firecrawl(),
82
+ product: firecrawl(),
83
+ research: exa(),
84
+ }),
85
+ });
86
+ ```
87
+
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.
89
+
90
+ ## Errors
91
+
92
+ Every failure is a `FieldworkError`. It carries:
93
+
94
+ - `code`, one of the codes below;
95
+ - `provider` and the HTTP `status`;
96
+ - `retryable`: whether repeating the same call can succeed;
97
+ - `retryAfter`, in seconds, when the provider sent one;
98
+ - `jobId`, when a job had already started;
99
+ - the provider's response, as `cause`.
100
+
101
+ `error.toJSON()` returns these fields without the provider's response.
102
+
103
+ | Code | What happened | What to do |
104
+ | --- | --- | --- |
105
+ | `Unsupported` | The provider does not offer this capability. | Use an adapter that does. Nothing was sent. |
106
+ | `Unauthorized` | The key is missing, wrong or not allowed. | Fix the key. Repeating does not help. |
107
+ | `RateLimited` | A rate or plan limit was reached. | Wait `retryAfter` seconds, then repeat. |
108
+ | `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. |
110
+ | `JobFailed` | The job ended without a result. | Start a new job if needed; resuming fails again. |
111
+ | `Timeout` | The call or job outlasted its time. | With `jobId`, pass it as `resume`. Without one, repeat. |
112
+ | `Aborted` | `signal` cancelled the call. | With `jobId`, the job may still be running; pass it as `resume`. |
113
+ | `ProviderError` | Any other provider failure. | Repeat when `retryable` is true (5xx and network failures). |
114
+
115
+ An error with a `jobId` is never `retryable`, because repeating the call would start and charge for a second job.
116
+
117
+ ## Agent tools
118
+
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:
120
+
121
+ - a description that says when to use it and which tool to use instead;
122
+ - a JSON Schema input that lists only the options its provider supports;
123
+ - an output schema;
124
+ - MCP annotations.
125
+
126
+ `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`).
127
+
128
+ ```ts
129
+ import { jsonSchema, tool } from "ai";
130
+ import { toolsFor } from "@howells/fieldwork-sdk/tools";
131
+
132
+ const tools = Object.fromEntries(
133
+ toolsFor(web).map((t) => [
134
+ t.name,
135
+ tool({
136
+ description: t.description,
137
+ inputSchema: jsonSchema(t.inputSchema),
138
+ execute: (input, { abortSignal }) =>
139
+ t.execute(input, { signal: abortSignal }),
140
+ }),
141
+ ])
142
+ );
143
+ ```
144
+
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.
146
+
147
+ 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
+
149
+ ## The provider's own API
150
+
151
+ `web.raw.request(method, path, options)` calls the provider's HTTP API with authentication applied, for anything Fieldwork does not wrap:
152
+
153
+ ```ts
154
+ const usage = await new Fieldwork({ adapter: tavily() }).raw.request(
155
+ "GET",
156
+ "/usage"
157
+ );
158
+ ```
159
+
160
+ On a router, `raw` is keyed by provider name.
161
+
162
+ ## Keys
163
+
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.
173
+
174
+ ESM only, Node 22 or later. No dependencies.
@@ -0,0 +1,178 @@
1
+ /**
2
+ * The shapes every adapter returns. Each result keeps the provider's own
3
+ * response in `raw`, so nothing the provider sent is lost by normalizing it.
4
+ */
5
+ /** A JSON Schema object describing the values to extract. */
6
+ type JsonSchema = Record<string, unknown>;
7
+ /** Every capability Fieldwork knows. An adapter implements a subset. */
8
+ declare const CAPABILITIES: readonly ["search", "read", "extract", "product", "map", "crawl", "research", "act", "parse"];
9
+ type Capability = (typeof CAPABILITIES)[number];
10
+ /** Settings every call accepts, whatever the provider. */
11
+ interface CallOptions {
12
+ /** Cancels the call, including any polling for an asynchronous job. */
13
+ signal?: AbortSignal;
14
+ /** Milliseconds before the call gives up. */
15
+ timeout?: number;
16
+ }
17
+ /** A source a provider cited. */
18
+ interface Citation {
19
+ url: string;
20
+ title?: string;
21
+ /** Passages the provider quoted from the source, when it returned any. */
22
+ excerpts?: string[];
23
+ }
24
+ /** The sources a provider gave for one field of a structured result. */
25
+ interface FieldSource {
26
+ /** The field's name or path, as the provider reports it. */
27
+ field: string;
28
+ citations: Citation[];
29
+ /** The provider's own confidence label or score, unchanged. */
30
+ confidence?: string | number;
31
+ reasoning?: string;
32
+ }
33
+ interface SearchResult {
34
+ url: string;
35
+ title?: string;
36
+ /** Text from the page that matched the query. */
37
+ snippet?: string;
38
+ /** Page text, when the search was asked to include it. */
39
+ content?: string;
40
+ publishedAt?: string;
41
+ score?: number;
42
+ }
43
+ interface SearchResponse {
44
+ results: SearchResult[];
45
+ /** A generated answer, when the provider was asked for one. */
46
+ answer?: string;
47
+ raw: unknown;
48
+ }
49
+ interface Page {
50
+ url: string;
51
+ title?: string;
52
+ /** The page as Markdown. */
53
+ markdown?: string;
54
+ /** Cleaned HTML. */
55
+ html?: string;
56
+ /** The HTML exactly as the provider received it. */
57
+ rawHtml?: string;
58
+ links?: string[];
59
+ images?: string[];
60
+ /** Passages that answer the query, when the read was given one. */
61
+ excerpts?: string[];
62
+ raw: unknown;
63
+ }
64
+ interface Extraction<T> {
65
+ /** The values, in the shape of the schema. */
66
+ data: T;
67
+ /** Per-field sources, when the provider returns them. */
68
+ fields?: FieldSource[];
69
+ raw: unknown;
70
+ }
71
+ interface ProductVariant {
72
+ id?: string;
73
+ sku?: string;
74
+ title?: string;
75
+ /** Option values that pick this variant, such as color or size. */
76
+ values?: Record<string, string>;
77
+ price?: {
78
+ amount?: string;
79
+ currency?: string;
80
+ };
81
+ inStock?: boolean;
82
+ images?: string[];
83
+ }
84
+ interface Product {
85
+ title?: string;
86
+ brand?: string;
87
+ category?: string;
88
+ description?: string;
89
+ url?: string;
90
+ variants: ProductVariant[];
91
+ raw: unknown;
92
+ }
93
+ interface SiteLink {
94
+ url: string;
95
+ title?: string;
96
+ description?: string;
97
+ }
98
+ interface SiteMap {
99
+ links: SiteLink[];
100
+ raw: unknown;
101
+ }
102
+ interface Crawl {
103
+ pages: Page[];
104
+ raw: unknown;
105
+ }
106
+ interface Research<T> {
107
+ /** The provider's id for the run. */
108
+ id: string;
109
+ /** Structured output when a schema was given, otherwise the report text. */
110
+ output: T;
111
+ sources: Citation[];
112
+ fields?: FieldSource[];
113
+ raw: unknown;
114
+ }
115
+ interface ActResult {
116
+ /** What the script printed. */
117
+ stdout: string;
118
+ stderr: string;
119
+ /** The value the script returned, as the provider reports it. */
120
+ result?: unknown;
121
+ exitCode?: number;
122
+ raw: unknown;
123
+ }
124
+ interface DocumentPage {
125
+ /** The physical page number, starting at 1. */
126
+ pageNumber: number;
127
+ markdown: string;
128
+ }
129
+ interface ParsedDocument {
130
+ markdown: string;
131
+ pages?: DocumentPage[];
132
+ /** Layout blocks with positions, as the provider returns them. */
133
+ blocks?: unknown[];
134
+ raw: unknown;
135
+ }
136
+ /** A file to parse: its bytes and its name, which tells the provider the type. */
137
+ interface DocumentInput {
138
+ data: Blob | Uint8Array | ArrayBuffer;
139
+ name: string;
140
+ }
141
+ interface RequestOptions extends CallOptions {
142
+ /** A JSON body. */
143
+ body?: unknown;
144
+ /** A multipart body, sent as is. */
145
+ form?: FormData;
146
+ query?: Record<string, string | number | boolean | undefined>;
147
+ }
148
+ /**
149
+ * The provider's HTTP API with authentication applied: the escape hatch for
150
+ * anything Fieldwork does not wrap. Paths are relative to the provider's base
151
+ * URL, so `raw.request("GET", "/usage")` calls the provider directly.
152
+ */
153
+ interface RawClient {
154
+ readonly provider: string;
155
+ readonly baseUrl: string;
156
+ request<T = unknown>(method: string, path: string, options?: RequestOptions): Promise<T>;
157
+ }
158
+ /** The methods an adapter implements, keyed by capability. */
159
+ type Operations = Partial<Record<Capability, (...args: never[]) => Promise<unknown>>>;
160
+ /**
161
+ * A provider bound to its credentials. `operations` holds only the
162
+ * capabilities the provider offers, each typed with that provider's options,
163
+ * so a capability or option the provider lacks cannot be called.
164
+ */
165
+ interface Adapter<Name extends string = string, Ops extends Operations = Operations, Raw = RawClient> {
166
+ readonly name: Name;
167
+ readonly operations: Ops;
168
+ /** The provider's HTTP API, for anything Fieldwork does not wrap. */
169
+ readonly raw: Raw;
170
+ /**
171
+ * The provider behind each capability, when it is not `name`. Only a router
172
+ * sets this.
173
+ */
174
+ readonly providers?: Partial<Record<Capability, string>>;
175
+ }
176
+ type AnyAdapter = Adapter<string, any, unknown>;
177
+ declare function defineAdapter<Name extends string, Ops extends Operations, Raw = RawClient>(adapter: Adapter<Name, Ops, Raw>): Adapter<Name, Ops, Raw>;
178
+ export { SearchResponse as C, SiteMap as E, Research as S, SiteLink as T, JsonSchema as _, RawClient as a, Product as b, CAPABILITIES as c, Citation as d, Crawl as f, FieldSource as g, Extraction as h, defineAdapter as i, CallOptions as l, DocumentPage as m, AnyAdapter as n, RequestOptions as o, DocumentInput as p, Operations as r, ActResult as s, Adapter as t, Capability as u, Page as v, SearchResult as w, ProductVariant as x, ParsedDocument as y };
@@ -0,0 +1,5 @@
1
+ // src/adapter.ts
2
+ function defineAdapter(adapter) {
3
+ return adapter;
4
+ }
5
+ export { defineAdapter as t };
@@ -0,0 +1,69 @@
1
+ // src/errors.ts
2
+ /** The one error type every adapter throws, with a normalized code. */
3
+ var FieldworkError = class extends Error {
4
+ name = "FieldworkError";
5
+ code;
6
+ provider;
7
+ status;
8
+ retryAfter;
9
+ /**
10
+ * The provider's id for an asynchronous job that was already created when
11
+ * the call failed. The job may still be running and billing: pass this id
12
+ * as `resume` to wait for it again rather than starting another.
13
+ */
14
+ jobId;
15
+ /**
16
+ * Whether repeating the same call can succeed. False whenever `jobId` is
17
+ * set, because repeating the call would start a second job; resume it.
18
+ */
19
+ retryable;
20
+ constructor(code, message, options = {}) {
21
+ super(message, { cause: options.cause });
22
+ this.code = code;
23
+ this.provider = options.provider;
24
+ this.status = options.status;
25
+ this.retryAfter = options.retryAfter;
26
+ this.jobId = options.jobId;
27
+ this.retryable = options.jobId === void 0 && (options.retryable ?? isRetryable(code, options.status));
28
+ }
29
+ /** The fields an agent or a log needs, without the provider's response. */
30
+ toJSON() {
31
+ return {
32
+ name: this.name,
33
+ code: this.code,
34
+ message: this.message,
35
+ provider: this.provider,
36
+ status: this.status,
37
+ retryable: this.retryable,
38
+ retryAfter: this.retryAfter,
39
+ jobId: this.jobId
40
+ };
41
+ }
42
+ };
43
+ function isRetryable(code, status) {
44
+ if (code === "RateLimited" || code === "Timeout") return true;
45
+ return status !== void 0 && status >= 500;
46
+ }
47
+ /**
48
+ * Attaches a job id to an error raised while following that job, so the
49
+ * caller can resume it. Errors that are not Fieldwork's pass through.
50
+ */
51
+ function withJob(error, jobId) {
52
+ if (!(error instanceof FieldworkError) || error.jobId !== void 0) return error;
53
+ return new FieldworkError(error.code, error.message, {
54
+ provider: error.provider,
55
+ status: error.status,
56
+ retryAfter: error.retryAfter,
57
+ jobId,
58
+ cause: error.cause
59
+ });
60
+ }
61
+ function codeForStatus(status) {
62
+ if (status === 401 || status === 403) return "Unauthorized";
63
+ if (status === 404) return "NotFound";
64
+ if (status === 408) return "Timeout";
65
+ if (status === 429 || status === 432 || status === 433) return "RateLimited";
66
+ if (status === 400 || status === 422) return "InvalidRequest";
67
+ return "ProviderError";
68
+ }
69
+ export { codeForStatus as n, withJob as r, FieldworkError as t };
package/dist/exa.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { C as SearchResponse, S as Research, _ as JsonSchema, a as RawClient, h as Extraction, l as CallOptions, t as Adapter, v as Page } from "./adapter-C_kRm6TT.js";
2
+ export interface ExaConfig {
3
+ /** Defaults to the EXA_API_KEY environment variable. */
4
+ apiKey?: string;
5
+ baseUrl?: string;
6
+ fetch?: typeof fetch;
7
+ }
8
+ export interface ExaSearchOptions extends CallOptions {
9
+ /** Results to return; Exa allows up to 100. */
10
+ limit?: number;
11
+ type?: "auto" | "lite" | "deep-lite" | "deep";
12
+ category?: "company" | "people" | "research paper" | "news" | "pdf" | "github" | "personal site" | "financial report";
13
+ includeDomains?: string[];
14
+ excludeDomains?: string[];
15
+ /** YYYY-MM-DD. */
16
+ publishedAfter?: string;
17
+ /** YYYY-MM-DD. */
18
+ publishedBefore?: string;
19
+ /** YYYY-MM-DD: only pages Exa crawled after this date. */
20
+ crawledAfter?: string;
21
+ crawledBefore?: string;
22
+ includeText?: string[];
23
+ excludeText?: string[];
24
+ /** Two-letter country code. */
25
+ country?: string;
26
+ /** Include each result's page text. */
27
+ content?: boolean;
28
+ additionalQueries?: string[];
29
+ }
30
+ export interface ExaReadOptions extends CallOptions {
31
+ /** Return passages that answer this query as `excerpts`. */
32
+ query?: string;
33
+ maxCharacters?: number;
34
+ /** 0 forces a live fetch, -1 reads only the cache. */
35
+ maxAgeHours?: number;
36
+ /** Read Exa's stored copy of the page as of this ISO date. */
37
+ snapshotAsOf?: string;
38
+ }
39
+ export interface ExaExtractOptions extends CallOptions {
40
+ schema: JsonSchema;
41
+ /** What to extract, in plain words. */
42
+ prompt?: string;
43
+ maxAgeHours?: number;
44
+ }
45
+ export interface ExaResearchOptions extends CallOptions {
46
+ schema?: JsonSchema;
47
+ effort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "auto" | "ultra";
48
+ /** Spend cap in dollars, for auto and ultra effort. */
49
+ maxCostDollars?: number;
50
+ maxDurationSeconds?: number;
51
+ /** Milliseconds between status checks. */
52
+ interval?: number;
53
+ /**
54
+ * The id of a job that timed out or was cancelled, from the error's
55
+ * `jobId`. Waits for that job instead of starting a new one.
56
+ */
57
+ resume?: string;
58
+ }
59
+ export interface ExaOperations {
60
+ search(query: string, options?: ExaSearchOptions): Promise<SearchResponse>;
61
+ read(url: string, options?: ExaReadOptions): Promise<Page>;
62
+ extract<T = unknown>(url: string, options: ExaExtractOptions): Promise<Extraction<T>>;
63
+ research<T = unknown>(question: string, options?: ExaResearchOptions): Promise<Research<T>>;
64
+ }
65
+ export declare function exa(config?: ExaConfig): Adapter<"exa", ExaOperations, RawClient>;
package/dist/exa.js ADDED
@@ -0,0 +1,163 @@
1
+ import { t as defineAdapter } from "./adapter-D-6-GFhJ.js";
2
+ import { t as FieldworkError } from "./errors-pzPMh82H.js";
3
+ import { a as list, c as record, d as strings, f as text, g as requireKey, h as poll, i as compact, l as requireId, m as createRawClient, o as num, p as uniqueCitations, r as citations, s as parseJson, t as callSettings } from "./util-DgcIZI2K.js";
4
+ // src/adapters/exa.ts
5
+ function exa(config = {}) {
6
+ const provider = "exa";
7
+ const raw = createRawClient({
8
+ provider,
9
+ baseUrl: config.baseUrl ?? "https://api.exa.ai",
10
+ headers: { "x-api-key": requireKey(provider, config.apiKey, "EXA_API_KEY") },
11
+ fetch: config.fetch
12
+ });
13
+ async function contents(url, body, call) {
14
+ const response = await raw.request("POST", "/contents", {
15
+ ...call,
16
+ body: {
17
+ urls: [url],
18
+ ...body
19
+ }
20
+ });
21
+ const status = record(list(record(response).statuses)[0]);
22
+ if (status.status && status.status !== "success") {
23
+ const reason = text(record(status.error).tag) ?? text(status.status) ?? "unknown";
24
+ throw new FieldworkError(reason === "CRAWL_NOT_FOUND" ? "NotFound" : "ProviderError", `exa could not read ${url}: ${reason}`, {
25
+ provider,
26
+ cause: response
27
+ });
28
+ }
29
+ return {
30
+ response,
31
+ result: record(list(record(response).results)[0])
32
+ };
33
+ }
34
+ return defineAdapter({
35
+ name: provider,
36
+ operations: {
37
+ async search(query, options) {
38
+ const { call, rest: o } = callSettings(options);
39
+ const response = record(await raw.request("POST", "/search", {
40
+ ...call,
41
+ body: compact({
42
+ query,
43
+ numResults: o.limit,
44
+ type: o.type,
45
+ category: o.category,
46
+ includeDomains: o.includeDomains,
47
+ excludeDomains: o.excludeDomains,
48
+ startPublishedDate: o.publishedAfter,
49
+ endPublishedDate: o.publishedBefore,
50
+ startCrawlDate: o.crawledAfter,
51
+ endCrawlDate: o.crawledBefore,
52
+ includeText: o.includeText,
53
+ excludeText: o.excludeText,
54
+ userLocation: o.country ? { country: o.country } : void 0,
55
+ additionalQueries: o.additionalQueries,
56
+ contents: o.content ? { text: true } : void 0
57
+ })
58
+ }));
59
+ return {
60
+ results: list(response.results).map((item) => {
61
+ const result = record(item);
62
+ return compact({
63
+ url: text(result.url) ?? "",
64
+ title: text(result.title),
65
+ snippet: strings(result.highlights)?.join(" … "),
66
+ content: text(result.text),
67
+ publishedAt: text(result.publishedDate),
68
+ score: num(result.score)
69
+ });
70
+ }),
71
+ raw: response
72
+ };
73
+ },
74
+ async read(url, options) {
75
+ const { call, rest: o } = callSettings(options);
76
+ const { response, result } = await contents(url, compact({
77
+ text: compact({ maxCharacters: o.maxCharacters }),
78
+ highlights: o.query ? { query: o.query } : void 0,
79
+ maxAgeHours: o.maxAgeHours,
80
+ snapshotAsOf: o.snapshotAsOf,
81
+ extras: {
82
+ links: 100,
83
+ imageLinks: 100
84
+ }
85
+ }), call);
86
+ const extras = record(result.extras);
87
+ return compact({
88
+ url: text(result.url) ?? url,
89
+ title: text(result.title),
90
+ markdown: text(result.text),
91
+ excerpts: strings(result.highlights),
92
+ links: strings(extras.links),
93
+ images: strings(extras.imageLinks),
94
+ raw: response
95
+ });
96
+ },
97
+ async extract(url, options) {
98
+ const { call, rest: o } = callSettings(options);
99
+ const { response, result } = await contents(url, compact({
100
+ text: true,
101
+ summary: compact({
102
+ query: o.prompt,
103
+ schema: o.schema
104
+ }),
105
+ maxAgeHours: o.maxAgeHours
106
+ }), call);
107
+ if (result.summary === void 0) throw new FieldworkError("ProviderError", `exa returned no structured summary for ${url}`, {
108
+ provider,
109
+ cause: response
110
+ });
111
+ return {
112
+ data: parseJson(provider, result.summary),
113
+ raw: response
114
+ };
115
+ },
116
+ async research(question, options) {
117
+ const { call, rest: o } = callSettings(options);
118
+ const budget = compact({
119
+ maxCostDollars: o.maxCostDollars,
120
+ maxDurationSeconds: o.maxDurationSeconds
121
+ });
122
+ const id = o.resume ?? requireId(provider, record(await raw.request("POST", "/agent/runs", {
123
+ ...call,
124
+ body: compact({
125
+ query: question,
126
+ outputSchema: o.schema,
127
+ effort: o.effort,
128
+ budget: Object.keys(budget).length > 0 ? budget : void 0
129
+ })
130
+ })).id);
131
+ const run = await poll(provider, id, async () => {
132
+ const current = record(await raw.request("GET", `/agent/runs/${id}`, { signal: call.signal }));
133
+ if (current.status === "failed" || current.status === "cancelled") throw new FieldworkError("JobFailed", `exa research run ${id} ended ${text(current.status) ?? "unknown"}`, {
134
+ provider,
135
+ cause: current
136
+ });
137
+ return current.status === "completed" ? current : void 0;
138
+ }, {
139
+ ...call,
140
+ interval: o.interval
141
+ });
142
+ const output = record(run.output);
143
+ const fields = list(output.grounding).map((item) => {
144
+ const grounding = record(item);
145
+ return compact({
146
+ field: text(grounding.field) ?? "",
147
+ citations: citations(grounding.citations),
148
+ confidence: text(grounding.confidence) ?? num(grounding.confidence)
149
+ });
150
+ });
151
+ return {
152
+ id,
153
+ output: o.schema ? output.structured : output.text,
154
+ sources: uniqueCitations(fields.flatMap((field) => field.citations)),
155
+ fields,
156
+ raw: run
157
+ };
158
+ }
159
+ },
160
+ raw
161
+ });
162
+ }
163
+ export { exa };