@howells/fieldwork-sdk 0.2.0 → 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.
@@ -0,0 +1,27 @@
1
+ // src/types.ts
2
+ /** Every capability Fieldwork knows. An adapter implements a subset. */
3
+ const CAPABILITIES = [
4
+ "search",
5
+ "images",
6
+ "read",
7
+ "readMany",
8
+ "extract",
9
+ "product",
10
+ "map",
11
+ "crawl",
12
+ "answer",
13
+ "research",
14
+ "discover",
15
+ "decide",
16
+ "act",
17
+ "browser",
18
+ "parse",
19
+ "monitor",
20
+ "usage"
21
+ ];
22
+ /**
23
+ * Capabilities whose operation is a group of methods rather than one method:
24
+ * `web.monitor.create(...)`, `web.browser.open(...)`.
25
+ */
26
+ const GROUP_CAPABILITIES = ["monitor", "browser"];
27
+ export { GROUP_CAPABILITIES as n, CAPABILITIES as t };
@@ -0,0 +1,265 @@
1
+ import { n as codeForStatus, r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
2
+ // src/http.ts
3
+ const createRawClient = (config) => {
4
+ const doFetch = config.fetch ?? globalThis.fetch;
5
+ return {
6
+ baseUrl: config.baseUrl,
7
+ provider: config.provider,
8
+ async request(method, path, options = {}) {
9
+ const url = new URL(config.baseUrl.replace(/\/$/u, "") + path);
10
+ for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
11
+ const headers = new Headers({
12
+ accept: "application/json",
13
+ ...config.headers
14
+ });
15
+ let body;
16
+ if (options.form) body = options.form;
17
+ else if (options.body !== void 0) {
18
+ headers.set("content-type", "application/json");
19
+ body = JSON.stringify(options.body);
20
+ }
21
+ const signal = combineSignals(options.signal, options.timeout);
22
+ const send = async (request) => {
23
+ try {
24
+ return await doFetch(request.url, {
25
+ body: request.body,
26
+ headers,
27
+ method: request.method,
28
+ redirect: "manual",
29
+ signal
30
+ });
31
+ } catch (error) {
32
+ throw transportError(config.provider, error, options.signal);
33
+ }
34
+ };
35
+ const response = await followRedirects(config.provider, send, {
36
+ body,
37
+ method,
38
+ url
39
+ });
40
+ const text = await response.text();
41
+ const parsed = parseBody(text);
42
+ if (!response.ok) throw new FieldworkError(codeForStatus(response.status), `${config.provider} ${method} ${path} returned ${response.status}: ${describe(parsed, text)}`, {
43
+ cause: parsed,
44
+ provider: config.provider,
45
+ retryAfter: retryAfterSeconds(response.headers.get("retry-after")),
46
+ status: response.status
47
+ });
48
+ return parsed;
49
+ }
50
+ };
51
+ };
52
+ const REDIRECTS = /* @__PURE__ */ new Set([
53
+ 301,
54
+ 302,
55
+ 303,
56
+ 307,
57
+ 308
58
+ ]);
59
+ const MAX_REDIRECTS = 5;
60
+ /**
61
+ * Follows a provider's redirects only within its own origin, so the key in
62
+ * the request's headers or query never reaches another host. A redirect to
63
+ * another origin, scheme or port fails before anything is sent there.
64
+ */
65
+ const followRedirects = async (provider, send, first) => {
66
+ let hop = first;
67
+ for (let count = 0; count <= MAX_REDIRECTS; count += 1) {
68
+ const response = await send(hop);
69
+ if (response.type === "opaqueredirect") throw new FieldworkError("ProviderError", `${provider} redirected the request, and this runtime hides where to; Fieldwork does not follow it`, { provider });
70
+ const location = response.headers.get("location");
71
+ if (!REDIRECTS.has(response.status) || location === null) return response;
72
+ const target = new URL(location, hop.url);
73
+ if (target.origin !== first.url.origin) throw new FieldworkError("ProviderError", `${provider} redirected the request to ${target.origin}; Fieldwork follows redirects only within ${first.url.origin}, so the key was not sent`, {
74
+ provider,
75
+ status: response.status
76
+ });
77
+ hop = response.status === 303 || (response.status === 301 || response.status === 302) && hop.method === "POST" ? {
78
+ body: void 0,
79
+ method: "GET",
80
+ url: target
81
+ } : {
82
+ ...hop,
83
+ url: target
84
+ };
85
+ }
86
+ throw new FieldworkError("ProviderError", `${provider} redirected the request more than ${MAX_REDIRECTS} times`, { provider });
87
+ };
88
+ const combineSignals = (signal, timeout) => {
89
+ const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((value) => value !== void 0);
90
+ return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
91
+ };
92
+ const transportError = (provider, error, signal) => {
93
+ if (signal?.aborted) return new FieldworkError("Aborted", `${provider} request was cancelled`, {
94
+ cause: error,
95
+ provider
96
+ });
97
+ if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
98
+ cause: error,
99
+ provider
100
+ });
101
+ return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
102
+ cause: error,
103
+ provider,
104
+ retryable: true
105
+ });
106
+ };
107
+ const parseBody = (text) => {
108
+ if (text === "") return;
109
+ try {
110
+ return JSON.parse(text);
111
+ } catch {
112
+ return text;
113
+ }
114
+ };
115
+ const describe = (parsed, text) => {
116
+ if (parsed && typeof parsed === "object") {
117
+ const record = parsed;
118
+ for (const key of [
119
+ "error",
120
+ "message",
121
+ "detail"
122
+ ]) {
123
+ const value = record[key];
124
+ if (typeof value === "string") return value;
125
+ if (value && typeof value === "object") return JSON.stringify(value).slice(0, 300);
126
+ }
127
+ }
128
+ return text.slice(0, 300);
129
+ };
130
+ const retryAfterSeconds = (header, now = Date.now()) => {
131
+ if (!header) return;
132
+ const seconds = Number(header);
133
+ if (Number.isFinite(seconds)) return seconds;
134
+ const date = Date.parse(header);
135
+ return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
136
+ };
137
+ const poll = async (provider, jobId, check, options = {}) => {
138
+ const interval = options.interval ?? 2e3;
139
+ const deadline = Date.now() + (options.timeout ?? 6e5);
140
+ for (;;) {
141
+ if (options.signal?.aborted) throw new FieldworkError("Aborted", `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
142
+ jobId,
143
+ provider
144
+ });
145
+ let value;
146
+ try {
147
+ value = await check();
148
+ } catch (error) {
149
+ throw withJob(error, jobId);
150
+ }
151
+ if (value !== void 0) return value;
152
+ if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
153
+ jobId,
154
+ provider
155
+ });
156
+ await sleep(interval, options.signal);
157
+ }
158
+ };
159
+ const sleep = async (ms, signal) => {
160
+ await new Promise((resolve) => {
161
+ const timer = setTimeout(resolve, ms);
162
+ signal?.addEventListener("abort", () => {
163
+ clearTimeout(timer);
164
+ resolve();
165
+ }, { once: true });
166
+ });
167
+ };
168
+ const requireKey = (provider, given, envName) => {
169
+ const key = given ?? process.env[envName];
170
+ if (!key) throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
171
+ return key;
172
+ };
173
+ // src/util.ts
174
+ const record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
175
+ const list = (value) => Array.isArray(value) ? value : [];
176
+ const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
177
+ const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
178
+ const strings = (value) => {
179
+ const items = list(value).filter((item) => typeof item === "string");
180
+ return items.length > 0 ? items : void 0;
181
+ };
182
+ const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
183
+ const callSettings = (options) => {
184
+ const { signal, timeout, ...rest } = options ?? {};
185
+ return {
186
+ call: {
187
+ signal,
188
+ timeout
189
+ },
190
+ rest
191
+ };
192
+ };
193
+ const parseJson = (provider, value) => {
194
+ if (typeof value !== "string") return value;
195
+ try {
196
+ return JSON.parse(value);
197
+ } catch (error) {
198
+ throw new FieldworkError("ProviderError", `${provider} returned output that is not valid JSON`, {
199
+ cause: error,
200
+ provider
201
+ });
202
+ }
203
+ };
204
+ const uniqueCitations = (all) => {
205
+ const seen = /* @__PURE__ */ new Map();
206
+ for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
207
+ return [...seen.values()];
208
+ };
209
+ const citation = (value) => {
210
+ const item = record(value);
211
+ const url = text(item.url);
212
+ if (!url) return;
213
+ const excerpts = typeof item.excerpts === "string" ? [item.excerpts] : strings(item.excerpts);
214
+ return compact({
215
+ excerpts,
216
+ title: text(item.title),
217
+ url
218
+ });
219
+ };
220
+ const citations = (value) => list(value).map((item) => citation(item)).filter((item) => item !== void 0);
221
+ const requireId = (provider, value) => {
222
+ const id = typeof value === "number" ? String(value) : text(value);
223
+ if (id === void 0) throw new FieldworkError("ProviderError", `${provider} did not return a job id`, {
224
+ cause: value,
225
+ provider
226
+ });
227
+ return id;
228
+ };
229
+ const scalar = (value) => {
230
+ if (typeof value === "string") return value;
231
+ return typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
232
+ };
233
+ const meta = (parts) => {
234
+ const units = Object.fromEntries(Object.entries(parts.units ?? {}).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])));
235
+ const usage = compact({
236
+ costUsd: num(parts.costUsd),
237
+ credits: num(parts.credits),
238
+ units: Object.keys(units).length > 0 ? units : void 0
239
+ });
240
+ const warnings = typeof parts.warnings === "string" ? [parts.warnings] : list(parts.warnings).map((item) => typeof item === "string" ? item : text(record(item).message) ?? text(record(item).detail)).filter((item) => item !== void 0);
241
+ const result = compact({
242
+ requestId: scalar(parts.requestId),
243
+ usage: Object.keys(usage).length > 0 ? usage : void 0,
244
+ warnings: warnings.length > 0 ? warnings : void 0
245
+ });
246
+ return Object.keys(result).length > 0 ? result : void 0;
247
+ };
248
+ const productImages = (value) => {
249
+ const items = list(value).map((item) => {
250
+ if (typeof item === "string") return item === "" ? void 0 : { url: item };
251
+ const image = record(item);
252
+ const url = text(image.url) ?? text(image.src);
253
+ return url ? compact({
254
+ alt: text(image.alt),
255
+ url
256
+ }) : void 0;
257
+ }).filter((item) => item !== void 0);
258
+ return items.length > 0 ? items : void 0;
259
+ };
260
+ const refuseTogether = (provider, options, ...names) => {
261
+ const set = names.filter((name) => options[name] !== void 0);
262
+ if (set.length > 1) throw new FieldworkError("InvalidRequest", `${provider} does not accept ${set.join(" and ")} together; pass one`, { provider });
263
+ };
264
+ const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
265
+ export { uniqueCitations as _, hours as a, requireKey as b, num as c, record as d, refuseTogether as f, text as g, strings as h, compact as i, parseJson as l, scalar as m, citation as n, list as o, requireId as p, citations as r, meta as s, callSettings as t, productImages as u, createRawClient as v, poll as y };
package/package.json CHANGED
@@ -1,17 +1,21 @@
1
1
  {
2
2
  "name": "@howells/fieldwork-sdk",
3
- "version": "0.2.0",
4
- "description": "One API for web search, page reading, extraction, crawling, research, browser actions and document parsing across Exa, Firecrawl, Tavily, Parallel and Perplexity.",
3
+ "version": "0.3.0",
4
+ "description": "One API for web search, page reading, extraction, crawling, answers, research, browser sessions, monitoring and document parsing across Exa, Firecrawl, Tavily, Parallel, Perplexity, Brave, SerpApi and Browserbase.",
5
5
  "keywords": [
6
6
  "agents",
7
+ "brave",
8
+ "browserbase",
7
9
  "exa",
8
10
  "extraction",
9
11
  "firecrawl",
12
+ "monitoring",
10
13
  "parallel",
11
14
  "perplexity",
12
15
  "research",
13
16
  "scraping",
14
17
  "sdk",
18
+ "serpapi",
15
19
  "tavily",
16
20
  "web-search"
17
21
  ],
@@ -55,6 +59,18 @@
55
59
  "types": "./dist/perplexity.d.ts",
56
60
  "import": "./dist/perplexity.js"
57
61
  },
62
+ "./brave": {
63
+ "types": "./dist/brave.d.ts",
64
+ "import": "./dist/brave.js"
65
+ },
66
+ "./serpapi": {
67
+ "types": "./dist/serpapi.d.ts",
68
+ "import": "./dist/serpapi.js"
69
+ },
70
+ "./browserbase": {
71
+ "types": "./dist/browserbase.d.ts",
72
+ "import": "./dist/browserbase.js"
73
+ },
58
74
  "./tools": {
59
75
  "types": "./dist/tools.d.ts",
60
76
  "import": "./dist/tools.js"
@@ -64,7 +80,7 @@
64
80
  "access": "public"
65
81
  },
66
82
  "devDependencies": {
67
- "@howells/lint": "^3.5.1",
83
+ "@howells/lint": "^3.9.1",
68
84
  "@howells/typescript-config": "^0.1.8",
69
85
  "@types/node": "^26.6.2",
70
86
  "tsdown": "^0.23.0",
@@ -1,178 +0,0 @@
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 };
@@ -1,5 +0,0 @@
1
- // src/adapter.ts
2
- function defineAdapter(adapter) {
3
- return adapter;
4
- }
5
- export { defineAdapter as t };
@@ -1,2 +0,0 @@
1
- type Json = Record<string, unknown>;
2
- export { Json as t };