@howells/fieldwork-sdk 0.5.1 → 0.6.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.
@@ -1,8 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { a as refuseLarger, n as documentPart, r as enclosing } from "./document-Dpj01mGx.js";
3
- import { t as FieldworkError } from "./errors-Yvk42oZH.js";
4
- import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, 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, n as anything, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-n8MmaK1x.js";
5
- import { t as runJob } from "./job-BGTwH3F-.js";
2
+ import { a as refuseLarger, n as documentPart, r as enclosing } from "./document-Clmi51Sf.js";
3
+ import { t as FieldworkError } from "./errors-DROZyb9T.js";
4
+ import { C as createRawClient, E as segment, F as parseJson, 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, n as anything, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-COHKvfH9.js";
5
+ import { i as startJob, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/llamaparse/response.ts
8
8
  /** A box in page points, from the page's top-left corner. */
@@ -143,6 +143,7 @@ const provider = "llamaparse";
143
143
  const PAGE_IMAGE = /^page_(?<page>\d+)\.jpg$/u;
144
144
  /** The largest file LlamaParse takes, in megabytes. */
145
145
  const MAX_PARSE_MB = 512;
146
+ /** The upload's `configuration`. The tier and version are always sent; the rest only when asked for. */
146
147
  const configuration = (o) => compact({
147
148
  output_options: o.wordBoxes === true || o.pageImages === true ? compact({
148
149
  granular_bboxes: o.wordBoxes === true ? [
@@ -156,26 +157,35 @@ const configuration = (o) => compact({
156
157
  tier: o.tier ?? "agentic",
157
158
  version: o.version ?? "latest"
158
159
  });
160
+ /** Uploads the file and returns the job id. Refuses a missing document, or a file over the size limit, before sending. */
159
161
  const startParse = async (raw, document, o, call) => {
160
162
  if (document === void 0) throw new FieldworkError("InvalidRequest", "parse needs a document, or resume with the id of an earlier parse", { provider });
161
163
  refuseLarger(provider, document, MAX_PARSE_MB);
162
164
  const form = new FormData();
163
165
  form.set("configuration", JSON.stringify(configuration(o)));
164
166
  form.set("file", documentPart(document), document.name);
165
- const created = z.parse(JobStart, await raw.request("POST", "/api/v2/parse/upload", {
166
- creates: true,
167
+ return await startJob(raw, "/api/v2/parse/upload", {
167
168
  ...call,
168
169
  form
169
- }));
170
- return requireJobId(provider, created.id);
170
+ }, JobStart, (reply) => reply.id);
171
+ };
172
+ const JOB_STATES = {
173
+ done: ["COMPLETED"],
174
+ failed: ["FAILED", "CANCELLED"],
175
+ running: ["PENDING", "RUNNING"]
171
176
  };
172
- const finished = (found) => {
177
+ /** The result once the job has completed, undefined while it runs; throws `JobFailed` when LlamaParse failed or cancelled it. */
178
+ const finished = (id, found) => {
173
179
  const { error_message: message, status } = found.value.job;
174
- if (status === "FAILED" || status === "CANCELLED") throw new FieldworkError("JobFailed", `llamaparse job ${status.toLowerCase()}${message === void 0 ? "" : `: ${message}`}`, {
180
+ const state = jobState(provider, id, JOB_STATES, {
181
+ original: found.original,
182
+ value: status
183
+ });
184
+ if (state === "failed") throw new FieldworkError("JobFailed", `llamaparse job ${status?.toLowerCase()}${message === void 0 ? "" : `: ${message}`}`, {
175
185
  cause: found.original,
176
186
  provider
177
187
  });
178
- return status === "COMPLETED" ? found : void 0;
188
+ return state === "done" ? found : void 0;
179
189
  };
180
190
  /** The grounded items: one JSON line per page, each page's items with word and cell boxes. */
181
191
  const groundedPages = async (found, options) => {
@@ -235,6 +245,7 @@ const parsedDocument = async (found, id, o, read) => {
235
245
  }
236
246
  });
237
247
  };
248
+ /** Runs the job. `expand` names the sections of the result to include; blocks, word boxes and page images each add one. */
238
249
  const parse = async (raw, document, options, fetchImpl) => {
239
250
  const { call, rest: o } = callSettings(options);
240
251
  const expand = [
@@ -244,7 +255,7 @@ const parse = async (raw, document, options, fetchImpl) => {
244
255
  ...o.pageImages === true ? ["images_content_metadata"] : []
245
256
  ].join(",");
246
257
  return await runJob(provider, {
247
- check: async (id, request) => finished(z.parse(JobResult, await raw.request("GET", `/api/v2/parse/${segment(id)}`, {
258
+ check: async (id, request) => finished(id, z.parse(JobResult, await raw.request("GET", `/api/v2/parse/${segment(id)}`, {
248
259
  ...request,
249
260
  query: { expand }
250
261
  }))),
@@ -1,10 +1,13 @@
1
- import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, b as Decisions, g as Condition, j as ImageSearch, l as Answer, p as CallOptions, q as Research, t as Adapter, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-BgdfLBs-.js";
2
- import { t as OutputSchema } from "./schema-Cupy7-7q.js";
1
+ import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, b as Decisions, g as Condition, j as ImageSearch, l as Answer, p as CallOptions, q as Research, t as Adapter, x as Discovery, y as DecisionQuestion, z as PageBatch } from "./adapter-Bh8EIrNe.js";
2
+ import { t as OutputSchema } from "./schema-BWWiMvkg.js";
3
3
  import "./util-DhYr1OS3.js";
4
+ /** Settings for `parallel()`. */
4
5
  interface ParallelConfig {
5
6
  /** Defaults to the PARALLEL_API_KEY environment variable. */
6
7
  apiKey?: string;
8
+ /** Defaults to https://api.parallel.ai. */
7
9
  baseUrl?: string;
10
+ /** Used in place of the global `fetch`. */
8
11
  fetch?: typeof fetch;
9
12
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
10
13
  retries?: number;
@@ -22,12 +25,17 @@ interface ParallelSources {
22
25
  * Parallel ignores `excludeDomains`, so passing both is refused.
23
26
  */
24
27
  includeDomains?: string[];
28
+ /** Same forms as `includeDomains`. Not combinable with it. */
25
29
  excludeDomains?: string[];
26
- /** YYYY-MM-DD. */
30
+ /** YYYY-MM-DD. Sent as `after_date`; there is no `publishedBefore`. */
27
31
  publishedAfter?: string;
28
32
  }
29
33
  /** Task metadata: keys up to 16 characters, values up to 512. */
30
34
  type ParallelMetadata = Record<string, string | number | boolean>;
35
+ /**
36
+ * Options for `search` (`POST /v1/search`). A `maxAge` under 600 is refused. There
37
+ * is no `recency` or `publishedBefore`; use `publishedAfter`.
38
+ */
31
39
  interface ParallelSearchOptions extends CallOptions, ParallelSources {
32
40
  /** What the search is for, in plain words. Defaults to the query. */
33
41
  objective?: string;
@@ -38,6 +46,7 @@ interface ParallelSearchOptions extends CallOptions, ParallelSources {
38
46
  * `basic` or `advanced` (the default, richer retrieval).
39
47
  */
40
48
  mode?: "turbo" | "fast" | "basic" | "advanced";
49
+ /** Sent as `max_results`. */
41
50
  limit?: number;
42
51
  /** ISO 3166-1 alpha-2 code such as "GB", for geo-targeted results. */
43
52
  country?: string;
@@ -50,16 +59,23 @@ interface ParallelSearchOptions extends CallOptions, ParallelSources {
50
59
  /** Groups calls made for one larger task; Parallel may use it to improve later results. */
51
60
  sessionId?: string;
52
61
  }
62
+ /** Options for `images` (`POST /v1/images/search`). */
53
63
  interface ParallelImagesOptions extends CallOptions {
54
64
  /** The images wanted, in plain words, up to 5,000 characters. Defaults to the query. */
55
65
  objective?: string;
56
66
  /** Up to 5 image queries; defaults to the query alone. */
57
67
  queries?: string[];
58
68
  mode?: "fast" | "advanced";
69
+ /** Sent as `max_results`. */
59
70
  limit?: number;
71
+ /** ISO 3166-1 alpha-2 code such as "GB", for geo-targeted results. */
60
72
  country?: string;
61
73
  sessionId?: string;
62
74
  }
75
+ /**
76
+ * Options for `read` (`POST /v1/extract`). The page text comes back as `markdown`;
77
+ * `query` and `queries` add focused `excerpts`. A `maxAge` under 600 is refused.
78
+ */
63
79
  interface ParallelReadOptions extends CallOptions {
64
80
  /** Return passages that answer this as `excerpts`. Sent as Parallel's `objective`. */
65
81
  query?: string;
@@ -67,7 +83,10 @@ interface ParallelReadOptions extends CallOptions {
67
83
  queries?: string[];
68
84
  /** Seconds a cached copy may be old. Parallel's minimum is 600; lower values are refused. */
69
85
  maxAge?: number;
70
- /** Cap on the characters of the page text returned for each URL. */
86
+ /**
87
+ * Cap on the characters of the page text returned for each URL. Without it,
88
+ * or at 0, the full content is requested with no cap.
89
+ */
71
90
  maxContentChars?: number;
72
91
  /** Cap on the characters of excerpts returned for each URL. */
73
92
  maxCharsPerResult?: number;
@@ -75,7 +94,19 @@ interface ParallelReadOptions extends CallOptions {
75
94
  maxCharsTotal?: number;
76
95
  sessionId?: string;
77
96
  }
97
+ /**
98
+ * Options for `readMany`: the same as `read`, applied to every URL. Parallel takes
99
+ * at most 20 URLs in one call.
100
+ */
78
101
  type ParallelReadManyOptions = ParallelReadOptions;
102
+ /**
103
+ * Options for `extract`: a Task run, polled to completion, whose input names
104
+ * the URL and whose `source_policy.include_domains` holds one entry, the URL's
105
+ * hostname and path with any trailing slash dropped. The scheme, credentials,
106
+ * port, query string and fragment are not sent there, so the run is scoped by
107
+ * hostname and path, not by the exact URL. `resume` waits for an earlier run
108
+ * instead of starting another.
109
+ */
79
110
  interface ParallelExtractOptions<T = unknown> extends CallOptions {
80
111
  /**
81
112
  * The values to extract. Without one, Parallel picks the fields itself (its
@@ -84,6 +115,10 @@ interface ParallelExtractOptions<T = unknown> extends CallOptions {
84
115
  * checks `data`.
85
116
  */
86
117
  schema?: OutputSchema<T>;
118
+ /**
119
+ * Instructions for the run. Defaults to one that asks for the values in `schema`
120
+ * from this page only, or for the page's main facts when there is no schema.
121
+ */
87
122
  prompt?: string;
88
123
  /** Defaults to "base". */
89
124
  processor?: ParallelProcessor;
@@ -98,6 +133,10 @@ interface ParallelExtractOptions<T = unknown> extends CallOptions {
98
133
  */
99
134
  resume?: string;
100
135
  }
136
+ /**
137
+ * Options for `answer` (`POST /v1/responses`, synchronous). `includeDomains` and
138
+ * `excludeDomains` are refused together.
139
+ */
101
140
  interface ParallelAnswerOptions<T = unknown> extends CallOptions {
102
141
  /** The answer in the shape of this schema, in `output`. */
103
142
  schema?: OutputSchema<T>;
@@ -109,10 +148,15 @@ interface ParallelAnswerOptions<T = unknown> extends CallOptions {
109
148
  continueFrom?: string;
110
149
  /** Only these domains are searched. Parallel allows one of the two lists. */
111
150
  includeDomains?: string[];
151
+ /** These domains are not searched. Not combinable with `includeDomains`. */
112
152
  excludeDomains?: string[];
113
153
  /** Up to 16 keys, keys up to 64 characters, values up to 512. */
114
154
  metadata?: Record<string, string>;
115
155
  }
156
+ /**
157
+ * Options for `research`: a Task run polled to completion. `includeDomains` and
158
+ * `excludeDomains` are refused together.
159
+ */
116
160
  interface ParallelResearchOptions<T = unknown> extends CallOptions, ParallelSources {
117
161
  /** Structured output in the shape of this schema; without one the output is report text. */
118
162
  schema?: OutputSchema<T>;
@@ -131,6 +175,12 @@ interface ParallelResearchOptions<T = unknown> extends CallOptions, ParallelSour
131
175
  */
132
176
  resume?: string;
133
177
  }
178
+ /**
179
+ * Options for `discover`: a FindAll run (`/v1beta/findall`) that finds entities
180
+ * matching every condition, polled to completion. A run that stops early with at
181
+ * least one match returns `status: "partial"`; one that ends with no match throws
182
+ * `JobFailed`.
183
+ */
134
184
  interface ParallelDiscoverOptions<T = unknown> extends CallOptions {
135
185
  /** What kind of entity to find, such as "companies" or "people". */
136
186
  entityType: string;
@@ -162,13 +212,25 @@ interface ParallelDiscoverOptions<T = unknown> extends CallOptions {
162
212
  */
163
213
  resume?: string;
164
214
  }
215
+ /**
216
+ * Options for `decide` (`POST /v1/decisions`, synchronous). Parallel takes 1 to 100
217
+ * questions named with letters, numbers, underscores and hyphens. A choice
218
+ * question needs 2 to 255 distinct choices and a score scale 2 to 10 levels. All
219
+ * three are refused before sending.
220
+ */
165
221
  interface ParallelDecideOptions extends CallOptions {
166
222
  /** ISO 3166-1 alpha-2 code for geo-targeted search. */
167
223
  country?: string;
168
224
  /** Keep the passages each citation was taken from. Parallel defaults to true. */
169
225
  includeExcerpts?: boolean;
170
226
  }
227
+ /** The event types a monitor webhook can subscribe to. */
171
228
  type ParallelWebhookEvent = "monitor.event.detected" | "monitor.execution.completed" | "monitor.execution.failed";
229
+ /**
230
+ * Options for `monitor.create`. A `query` makes an event-stream monitor that
231
+ * searches the web on each run; a `taskRunId` makes a snapshot monitor of that
232
+ * Task run's output. Pass one of the two. `webhookEvents` needs a `webhookUrl`.
233
+ */
172
234
  interface ParallelMonitorCreateOptions extends CallOptions, ParallelSources {
173
235
  /**
174
236
  * What to watch for, in plain words. Parallel searches the web for it on
@@ -177,17 +239,22 @@ interface ParallelMonitorCreateOptions extends CallOptions, ParallelSources {
177
239
  query?: string;
178
240
  /**
179
241
  * Watch the output of an earlier Task run for changes instead of a query.
180
- * Cannot be combined with `query`, `schema`, `includeBackfill`, `country` or
181
- * the domain filters.
242
+ * Cannot be combined with `query`, `schema`, `includeBackfill`, `country`,
243
+ * `includeDomains`, `excludeDomains` or `publishedAfter`.
182
244
  */
183
245
  taskRunId?: string;
184
- /** Parallel runs at a fixed interval from 1 hour to 30 days; cron is refused. */
246
+ /**
247
+ * Parallel runs at a fixed interval from 1 hour to 30 days; cron is refused.
248
+ * `every` is "hour", "day", "week", or a count such as "6h" (up to 720h) or
249
+ * "3d" (up to 30d).
250
+ */
185
251
  schedule: MonitorSchedule;
186
252
  /** Events come back in the shape of this schema. Events are not checked against a Standard Schema. */
187
253
  schema?: OutputSchema<unknown>;
188
254
  /** The first run returns a sample of recent events (a preview, not exhaustive). */
189
255
  includeBackfill?: boolean;
190
256
  country?: string;
257
+ /** Where Parallel sends webhook events. */
191
258
  webhookUrl?: string;
192
259
  /** Needs `webhookUrl`. Parallel sends every event type when omitted. */
193
260
  webhookEvents?: ParallelWebhookEvent[];
@@ -196,6 +263,10 @@ interface ParallelMonitorCreateOptions extends CallOptions, ParallelSources {
196
263
  /** Keys up to 16 characters, values up to 512. */
197
264
  metadata?: Record<string, string>;
198
265
  }
266
+ /**
267
+ * Options for `monitor.events`: one page of a monitor's events. Pass the result's
268
+ * `next` as `cursor` for the following page.
269
+ */
199
270
  interface ParallelMonitorEventsOptions extends CallOptions {
200
271
  cursor?: string;
201
272
  /** 1 to 100. Parallel defaults to 20. */
@@ -212,6 +283,11 @@ interface ParallelMonitorEventsOptions extends CallOptions {
212
283
  type ParallelDiscovery<T> = Discovery<T> & {
213
284
  stopReason?: string;
214
285
  };
286
+ /**
287
+ * What Parallel offers: search, images, read, readMany, extract, answer, research,
288
+ * discover, decide and monitor. `extract`, `research` and `discover` run as jobs
289
+ * and accept `resume`.
290
+ */
215
291
  interface ParallelOperations {
216
292
  search: (query: string, options?: ParallelSearchOptions) => Promise<SearchResponse>;
217
293
  images: (query: string, options?: ParallelImagesOptions) => Promise<ImageSearch>;