@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/dist/exa.js ADDED
@@ -0,0 +1,471 @@
1
+ import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
2
+ import { t as FieldworkError } from "./errors-BiIBG9zN.js";
3
+ import { _ as uniqueCitations, a as hours, b as requireKey, c as num, d as record, g as text, h as strings, i as compact, l as parseJson, o as list, p as requireId, r as citations, s as meta, t as callSettings, v as createRawClient, y as poll } from "./util-CYenIQQT.js";
4
+ const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
5
+ const DEEP_TYPES = /* @__PURE__ */ new Set([
6
+ "deep-lite",
7
+ "deep",
8
+ "deep-reasoning"
9
+ ]);
10
+ const invalid = (message) => {
11
+ throw new FieldworkError("InvalidRequest", `exa ${message}`, { provider: "exa" });
12
+ };
13
+ const dateTime = (value, endOfDay) => {
14
+ if (value === void 0 || !DATE_ONLY.test(value)) return value;
15
+ return endOfDay ? `${value}T23:59:59.999Z` : `${value}T00:00:00.000Z`;
16
+ };
17
+ const costOf = (response) => num(record(response.costDollars).total);
18
+ const responseMeta = (response, warnings) => meta({
19
+ costUsd: costOf(response),
20
+ requestId: response.requestId,
21
+ warnings
22
+ });
23
+ const summaryOption = (summary, schema) => {
24
+ if (summary === void 0 || summary === false) return schema ? compact({ schema }) : void 0;
25
+ return compact({
26
+ query: typeof summary === "object" ? summary.query : void 0,
27
+ schema
28
+ });
29
+ };
30
+ const checkSearch = (o) => {
31
+ if (o.type === "lite") {
32
+ const unsupported = [
33
+ "additionalQueries",
34
+ "outputSchema",
35
+ "systemPrompt",
36
+ "summary",
37
+ "maxAge"
38
+ ].filter((name) => o[name] !== void 0);
39
+ if (unsupported.length > 0) invalid(`search type "lite" does not accept ${unsupported.join(", ")}`);
40
+ }
41
+ if (o.additionalQueries !== void 0 && !DEEP_TYPES.has(o.type ?? "")) invalid("additionalQueries needs search type \"deep-lite\", \"deep\" or \"deep-reasoning\"");
42
+ const dated = o.publishedAfter !== void 0 || o.publishedBefore !== void 0;
43
+ if ((o.category === "company" || o.category === "people") && dated) invalid(`category "${o.category}" does not accept publishedAfter or publishedBefore`);
44
+ if (o.category === "people" && o.excludeDomains !== void 0) invalid("category \"people\" does not accept excludeDomains");
45
+ };
46
+ const highlightsOption = (highlights) => typeof highlights === "object" ? compact({
47
+ maxCharacters: highlights.maxCharacters,
48
+ query: highlights.query
49
+ }) : true;
50
+ const searchContents = (o) => {
51
+ const contents = compact({
52
+ highlights: o.highlights === false ? void 0 : highlightsOption(o.highlights),
53
+ maxAgeHours: hours(o.maxAge),
54
+ summary: summaryOption(o.summary),
55
+ text: o.content ? true : void 0
56
+ });
57
+ return Object.keys(contents).length > 0 ? contents : void 0;
58
+ };
59
+ const searchResult = (item) => {
60
+ const result = record(item);
61
+ return compact({
62
+ author: text(result.author),
63
+ content: text(result.text),
64
+ favicon: text(result.favicon),
65
+ image: text(result.image),
66
+ publishedAt: text(result.publishedDate),
67
+ score: num(result.score),
68
+ snippet: strings(result.highlights)?.join(" … "),
69
+ title: text(result.title),
70
+ url: text(result.url) ?? ""
71
+ });
72
+ };
73
+ const generatedAnswer = (output) => {
74
+ const { content } = output;
75
+ if (typeof content === "string") return text(content);
76
+ return content === void 0 || content === null ? void 0 : JSON.stringify(content);
77
+ };
78
+ const readBody = (o) => {
79
+ const links = o.linkLimit ?? 100;
80
+ const images = o.imageLimit ?? 100;
81
+ const extras = compact({
82
+ imageLinks: images > 0 ? images : void 0,
83
+ links: links > 0 ? links : void 0
84
+ });
85
+ return compact({
86
+ extras: Object.keys(extras).length > 0 ? extras : void 0,
87
+ highlights: o.query ? { query: o.query } : void 0,
88
+ maxAgeHours: hours(o.maxAge),
89
+ snapshotAsOf: o.snapshotAsOf,
90
+ summary: summaryOption(o.summary),
91
+ text: o.maxCharacters === void 0 ? true : { maxCharacters: o.maxCharacters }
92
+ });
93
+ };
94
+ const failureCode = (tag, httpStatus) => {
95
+ if (tag === "CRAWL_NOT_FOUND" || tag === "CONTENT_NOT_CACHED") return "NotFound";
96
+ if (tag === "CRAWL_TIMEOUT") return "Timeout";
97
+ if (httpStatus === 404 || httpStatus === 410) return "NotFound";
98
+ return httpStatus === 408 || httpStatus === 504 ? "Timeout" : "ProviderError";
99
+ };
100
+ const statusReason = (status) => {
101
+ const error = record(status.error);
102
+ const httpStatus = num(error.httpStatusCode);
103
+ return text(error.tag) ?? (httpStatus === void 0 ? void 0 : `HTTP ${httpStatus}`) ?? text(status.status) ?? "unknown";
104
+ };
105
+ const failedStatuses = (response) => list(response.statuses).map((item) => record(item)).filter((status) => status.status !== void 0 && status.status !== "success");
106
+ const pageFrom = (url, item, rawValue) => {
107
+ const result = record(item);
108
+ const extras = record(result.extras);
109
+ return compact({
110
+ author: text(result.author),
111
+ excerpts: strings(result.highlights),
112
+ favicon: text(result.favicon),
113
+ image: text(result.image),
114
+ images: strings(extras.imageLinks),
115
+ links: strings(extras.links),
116
+ markdown: text(result.text),
117
+ publishedAt: text(result.publishedDate),
118
+ raw: rawValue,
119
+ summary: text(result.summary),
120
+ title: text(result.title),
121
+ url: text(result.url) ?? url
122
+ });
123
+ };
124
+ const hasOutput = (run, structured) => {
125
+ const output = record(run.output);
126
+ return structured ? output.structured !== void 0 && output.structured !== null : text(output.text) !== void 0;
127
+ };
128
+ const runMeta = (run) => {
129
+ const usage = record(run.usage);
130
+ return meta({
131
+ costUsd: costOf(run),
132
+ units: {
133
+ agentComputeUnits: usage.agentComputeUnits,
134
+ emails: usage.emails,
135
+ phoneNumbers: usage.phoneNumbers,
136
+ searches: usage.searches
137
+ }
138
+ });
139
+ };
140
+ const checkResearch = (o) => {
141
+ const effort = o.effort ?? "auto";
142
+ if (o.maxCostDollars !== void 0 && effort !== "auto" && effort !== "ultra") invalid(`maxCostDollars needs effort "auto" or "ultra", not "${effort}"`);
143
+ if (o.maxDurationSeconds !== void 0 && effort !== "ultra") invalid(`maxDurationSeconds needs effort "ultra", not "${effort}"`);
144
+ };
145
+ const researchBody = (question, o) => {
146
+ const budget = compact({
147
+ maxCostDollars: o.maxCostDollars,
148
+ maxDurationSeconds: o.maxDurationSeconds
149
+ });
150
+ const input = compact({
151
+ data: o.input?.data,
152
+ exclusion: o.input?.exclusion
153
+ });
154
+ return compact({
155
+ budget: Object.keys(budget).length > 0 ? budget : void 0,
156
+ effort: o.effort,
157
+ input: Object.keys(input).length > 0 ? input : void 0,
158
+ outputSchema: o.schema,
159
+ previousRunId: o.continueFrom,
160
+ query: question,
161
+ systemPrompt: o.systemPrompt
162
+ });
163
+ };
164
+ const researchResult = (id, run, structured) => {
165
+ const stopReason = text(run.stopReason);
166
+ const status = text(run.status) ?? "unknown";
167
+ if (status !== "completed" && !hasOutput(run, structured)) {
168
+ const error = record(run.error);
169
+ const message = text(error.message);
170
+ const detail = message ? `${text(error.code) ?? text(error.type) ?? "error"}: ${message}` : stopReason;
171
+ throw new FieldworkError("JobFailed", `exa research run ${id} ended ${status}${detail ? ` (${detail})` : ""}`, {
172
+ cause: run,
173
+ jobId: id,
174
+ provider: "exa"
175
+ });
176
+ }
177
+ const output = record(run.output);
178
+ const fields = list(output.grounding).map((item) => {
179
+ const grounding = record(item);
180
+ return compact({
181
+ citations: citations(grounding.citations),
182
+ confidence: text(grounding.confidence) ?? num(grounding.confidence),
183
+ field: text(grounding.field) ?? ""
184
+ });
185
+ });
186
+ const finished = status === "completed" && (stopReason === void 0 || stopReason === "schema_satisfied");
187
+ return compact({
188
+ continuationId: status === "completed" ? id : void 0,
189
+ fields: fields.length > 0 ? fields : void 0,
190
+ id,
191
+ meta: runMeta(run),
192
+ output: structured ? output.structured : output.text,
193
+ raw: run,
194
+ sources: uniqueCitations(fields.flatMap((field) => field.citations)),
195
+ status: finished ? "completed" : "partial",
196
+ stopReason: finished ? void 0 : stopReason ?? status
197
+ });
198
+ };
199
+ const intervalPeriod = (schedule) => {
200
+ const { every } = schedule;
201
+ if (typeof every !== "string") return invalid("monitors run on an interval of whole hours or days; Exa has no cron");
202
+ let value = every;
203
+ if (every === "hour") value = "1h";
204
+ else if (every === "day") value = "1d";
205
+ else if (every === "week") value = "7d";
206
+ if (!/^[1-9]\d*[hd]$/u.test(value)) return invalid(`monitor schedule "${every}" is not whole hours or days, at least 1h`);
207
+ return value;
208
+ };
209
+ const period = (schedule) => schedule === void 0 ? void 0 : intervalPeriod(schedule);
210
+ const monitorInfo = (value) => {
211
+ const found = record(value);
212
+ return compact({
213
+ createdAt: text(found.createdAt),
214
+ id: requireId("exa", found.id),
215
+ raw: value,
216
+ schedule: text(record(found.trigger).period),
217
+ status: text(found.status),
218
+ watch: text(record(found.search).query),
219
+ webhookUrl: text(record(found.webhook).url)
220
+ });
221
+ };
222
+ const eventSummary = (run, content) => {
223
+ if (typeof content === "string") return text(content);
224
+ if (run.status === "failed") {
225
+ const reason = text(run.failReason);
226
+ return `Run failed${reason ? `: ${reason}` : ""}`;
227
+ }
228
+ };
229
+ const monitorEvent = (item) => {
230
+ const run = record(item);
231
+ const output = record(run.output);
232
+ const { content } = output;
233
+ const grounded = uniqueCitations(list(output.grounding).flatMap((entry) => citations(record(entry).citations)));
234
+ const structured = content !== void 0 && content !== null && typeof content !== "string";
235
+ return compact({
236
+ at: text(run.completedAt) ?? text(run.createdAt),
237
+ citations: grounded.length > 0 ? grounded : void 0,
238
+ id: text(run.id),
239
+ output: structured ? content : void 0,
240
+ raw: item,
241
+ summary: eventSummary(run, content)
242
+ });
243
+ };
244
+ // src/adapters/exa.ts
245
+ const exa = (config = {}) => {
246
+ const raw = createRawClient({
247
+ baseUrl: config.baseUrl ?? "https://api.exa.ai",
248
+ fetch: config.fetch,
249
+ headers: { "x-api-key": requireKey("exa", config.apiKey, "EXA_API_KEY") },
250
+ provider: "exa"
251
+ });
252
+ const fetchContents = async (urls, body, call) => record(await raw.request("POST", "/contents", {
253
+ ...call,
254
+ body: {
255
+ urls,
256
+ ...body
257
+ }
258
+ }));
259
+ const readOne = async (url, body, call) => {
260
+ const response = await fetchContents([url], body, call);
261
+ const [failed] = failedStatuses(response);
262
+ if (failed) {
263
+ const error = record(failed.error);
264
+ throw new FieldworkError(failureCode(text(error.tag), num(error.httpStatusCode)), `exa could not read ${url}: ${statusReason(failed)}`, {
265
+ cause: response,
266
+ provider: "exa",
267
+ status: num(error.httpStatusCode)
268
+ });
269
+ }
270
+ const [result] = list(response.results);
271
+ if (result === void 0) throw new FieldworkError("ProviderError", `exa returned no content for ${url}`, {
272
+ cause: response,
273
+ provider: "exa"
274
+ });
275
+ return {
276
+ response,
277
+ result
278
+ };
279
+ };
280
+ return defineAdapter({
281
+ name: "exa",
282
+ operations: {
283
+ async answer(question, options) {
284
+ const { call, rest: o } = callSettings(options);
285
+ const response = record(await raw.request("POST", "/answer", {
286
+ ...call,
287
+ body: compact({
288
+ model: o.model,
289
+ outputSchema: o.schema,
290
+ query: question,
291
+ systemPrompt: o.systemPrompt,
292
+ userLocation: o.country ? { country: o.country } : void 0
293
+ })
294
+ }));
295
+ const { answer: value } = response;
296
+ const structured = typeof value === "object" && value !== null;
297
+ return compact({
298
+ answer: structured ? JSON.stringify(value) : text(value) ?? "",
299
+ citations: uniqueCitations(citations(response.citations)),
300
+ meta: responseMeta(response),
301
+ output: structured ? value : void 0,
302
+ raw: response
303
+ });
304
+ },
305
+ async extract(url, options) {
306
+ const { call, rest: o } = callSettings(options);
307
+ const { response, result } = await readOne(url, compact({
308
+ maxAgeHours: hours(o.maxAge),
309
+ summary: compact({
310
+ query: o.prompt,
311
+ schema: o.schema
312
+ })
313
+ }), call);
314
+ const { summary } = record(result);
315
+ if (summary === void 0) throw new FieldworkError("ProviderError", `exa returned no structured summary for ${url}`, {
316
+ cause: response,
317
+ provider: "exa"
318
+ });
319
+ return compact({
320
+ data: parseJson("exa", summary),
321
+ meta: responseMeta(response),
322
+ raw: response
323
+ });
324
+ },
325
+ monitor: {
326
+ async create(options) {
327
+ const { call, rest: o } = callSettings(options);
328
+ const every = period(o.schedule);
329
+ const body = compact({
330
+ metadata: o.metadata,
331
+ name: o.name,
332
+ outputSchema: o.outputSchema,
333
+ search: compact({
334
+ contents: o.content ? { text: true } : void 0,
335
+ excludeDomains: o.excludeDomains,
336
+ includeDomains: o.includeDomains,
337
+ numResults: o.limit,
338
+ query: o.query
339
+ }),
340
+ trigger: every ? {
341
+ period: every,
342
+ type: "interval"
343
+ } : void 0,
344
+ webhook: compact({
345
+ events: o.webhookEvents,
346
+ url: o.webhookUrl
347
+ })
348
+ });
349
+ return monitorInfo(await raw.request("POST", "/monitors", {
350
+ ...call,
351
+ body
352
+ }));
353
+ },
354
+ async delete(id, options) {
355
+ const { call } = callSettings(options);
356
+ await raw.request("DELETE", `/monitors/${encodeURIComponent(id)}`, call);
357
+ },
358
+ async events(id, options) {
359
+ const { call, rest: o } = callSettings(options);
360
+ const response = record(await raw.request("GET", `/monitors/${encodeURIComponent(id)}/runs`, {
361
+ ...call,
362
+ query: {
363
+ cursor: o.cursor,
364
+ limit: o.limit
365
+ }
366
+ }));
367
+ return compact({
368
+ events: list(response.data).map((item) => monitorEvent(item)),
369
+ next: response.hasMore === true ? text(response.nextCursor) : void 0,
370
+ raw: response
371
+ });
372
+ },
373
+ async get(id, options) {
374
+ const { call } = callSettings(options);
375
+ return monitorInfo(await raw.request("GET", `/monitors/${encodeURIComponent(id)}`, call));
376
+ },
377
+ async list(options) {
378
+ const { call } = callSettings(options);
379
+ const monitors = [];
380
+ const seen = /* @__PURE__ */ new Set();
381
+ let cursor;
382
+ for (;;) {
383
+ const page = record(await raw.request("GET", "/monitors", {
384
+ ...call,
385
+ query: {
386
+ cursor,
387
+ limit: 100
388
+ }
389
+ }));
390
+ monitors.push(...list(page.data).map((item) => monitorInfo(item)));
391
+ cursor = text(page.nextCursor);
392
+ if (page.hasMore !== true || cursor === void 0 || seen.has(cursor)) return monitors;
393
+ seen.add(cursor);
394
+ }
395
+ }
396
+ },
397
+ async read(url, options) {
398
+ const { call, rest: o } = callSettings(options);
399
+ const { response, result } = await readOne(url, readBody(o), call);
400
+ return compact({
401
+ ...pageFrom(url, result, response),
402
+ meta: responseMeta(response)
403
+ });
404
+ },
405
+ async readMany(urls, options) {
406
+ const { call, rest: o } = callSettings(options);
407
+ if (urls.length === 0) invalid("readMany needs at least one URL");
408
+ if (urls.length > 100) invalid(`readMany reads at most 100 URLs per call`);
409
+ const response = await fetchContents(urls, readBody(o), call);
410
+ return {
411
+ failed: failedStatuses(response).map((status) => ({
412
+ error: statusReason(status),
413
+ url: text(status.id) ?? ""
414
+ })),
415
+ meta: responseMeta(response),
416
+ pages: list(response.results).map((item) => pageFrom("", item, item)),
417
+ raw: response
418
+ };
419
+ },
420
+ async research(question, options) {
421
+ const { call, rest: o } = callSettings(options);
422
+ checkResearch(o);
423
+ const id = o.resume ?? requireId("exa", record(await raw.request("POST", "/agent/runs", {
424
+ ...call,
425
+ body: researchBody(question, o)
426
+ })).id);
427
+ const run = await poll("exa", id, async () => {
428
+ const current = record(await raw.request("GET", `/agent/runs/${encodeURIComponent(id)}`, { signal: call.signal }));
429
+ return current.status === "completed" || current.status === "failed" || current.status === "cancelled" ? current : void 0;
430
+ }, {
431
+ ...call,
432
+ interval: o.interval
433
+ });
434
+ const { outputSchema } = record(run.request);
435
+ const structured = o.schema !== void 0 || outputSchema !== void 0 && outputSchema !== null;
436
+ return researchResult(id, run, structured);
437
+ },
438
+ async search(query, options) {
439
+ const { call, rest: o } = callSettings(options);
440
+ checkSearch(o);
441
+ const response = record(await raw.request("POST", "/search", {
442
+ ...call,
443
+ body: compact({
444
+ additionalQueries: o.additionalQueries,
445
+ category: o.category,
446
+ contents: searchContents(o),
447
+ endPublishedDate: dateTime(o.publishedBefore, true),
448
+ excludeDomains: o.excludeDomains,
449
+ includeDomains: o.includeDomains,
450
+ moderation: o.moderation,
451
+ numResults: o.limit,
452
+ outputSchema: o.outputSchema,
453
+ query,
454
+ startPublishedDate: dateTime(o.publishedAfter, false),
455
+ systemPrompt: o.systemPrompt,
456
+ type: o.type,
457
+ userLocation: o.country ? { country: o.country } : void 0
458
+ })
459
+ }));
460
+ return compact({
461
+ answer: generatedAnswer(record(response.output)),
462
+ meta: responseMeta(response, [...list(response.warnings), ...list(response.notices)]),
463
+ raw: response,
464
+ results: list(response.results).map((item) => searchResult(item))
465
+ });
466
+ }
467
+ },
468
+ raw
469
+ });
470
+ };
471
+ export { exa };
@@ -0,0 +1,78 @@
1
+ import { n as AnyAdapter, p as Capability } from "./adapter-DGehHCMo.js";
2
+ type FieldworkErrorCode =
3
+ /** The adapter's provider does not offer this capability. */
4
+ "Unsupported" |
5
+ /** The API key is missing or the provider rejected it. */
6
+ "Unauthorized" |
7
+ /** The provider refused the request because of a rate or plan limit. */
8
+ "RateLimited" | "NotFound" |
9
+ /** The provider rejected the request as malformed. */
10
+ "InvalidRequest" |
11
+ /** An asynchronous job finished without a result. */
12
+ "JobFailed" | "Timeout" | "Aborted" |
13
+ /** Any other provider failure. */
14
+ "ProviderError";
15
+ interface FieldworkErrorOptions {
16
+ provider?: string;
17
+ status?: number;
18
+ /** Seconds the provider asked to wait before retrying. */
19
+ retryAfter?: number;
20
+ /** The provider's id for an asynchronous job that was already created. */
21
+ jobId?: string;
22
+ /** Overrides the default, which follows from the code and status. */
23
+ retryable?: boolean;
24
+ cause?: unknown;
25
+ }
26
+ /** The one error type every adapter throws, with a normalized code. */
27
+ declare class FieldworkError extends Error {
28
+ readonly name = "FieldworkError";
29
+ readonly code: FieldworkErrorCode;
30
+ readonly provider?: string;
31
+ readonly status?: number;
32
+ readonly retryAfter?: number;
33
+ /**
34
+ * The provider's id for an asynchronous job that was already created when
35
+ * the call failed. The job may still be running and billing: pass this id
36
+ * as `resume` to wait for it again rather than starting another.
37
+ */
38
+ readonly jobId?: string;
39
+ /**
40
+ * Whether repeating the same call can succeed. False whenever `jobId` is
41
+ * set, because repeating the call would start a second job; resume it.
42
+ */
43
+ readonly retryable: boolean;
44
+ constructor(code: FieldworkErrorCode, message: string, options?: FieldworkErrorOptions);
45
+ /** The fields an agent or a log needs, without the provider's response. */
46
+ toJSON(): {
47
+ code: FieldworkErrorCode;
48
+ jobId: string | undefined;
49
+ message: string;
50
+ name: string;
51
+ provider: string | undefined;
52
+ retryAfter: number | undefined;
53
+ retryable: boolean;
54
+ status: number | undefined;
55
+ };
56
+ }
57
+ interface FieldworkOptions<A extends AnyAdapter> {
58
+ adapter: A;
59
+ }
60
+ interface FieldworkBase<A extends AnyAdapter> {
61
+ /** The adapter's name, such as "firecrawl" or "router". */
62
+ readonly provider: A["name"];
63
+ /** Which capabilities this instance can call. */
64
+ readonly capabilities: Readonly<Record<Capability, boolean>>;
65
+ /** The provider's HTTP API, for anything Fieldwork does not wrap. */
66
+ readonly raw: A["raw"];
67
+ supports(capability: Capability): boolean;
68
+ /** The provider that serves a capability, or undefined when none does. */
69
+ providerFor(capability: Capability): string | undefined;
70
+ }
71
+ /**
72
+ * A Fieldwork instance has exactly the methods its adapter's provider offers.
73
+ * `new Fieldwork({ adapter: tavily() }).act(...)` does not compile, because
74
+ * Tavily has no browser.
75
+ */
76
+ type Fieldwork<A extends AnyAdapter> = FieldworkBase<A> & Readonly<A["operations"]>;
77
+ declare const Fieldwork: new <A extends AnyAdapter>(options: FieldworkOptions<A>) => Fieldwork<A>;
78
+ export { FieldworkErrorCode as i, FieldworkOptions as n, FieldworkError as r, Fieldwork as t };