@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,15 +1,31 @@
1
- import { n as codeForStatus, t as FieldworkError } from "./errors-Yvk42oZH.js";
1
+ import { n as codeForStatus, t as FieldworkError } from "./errors-DROZyb9T.js";
2
2
  import * as z from "zod/mini";
3
3
  // src/util.ts
4
4
  const isJson = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
+ /** The value as an object, or an empty one when it is null, an array or not an object, so a read of a missing body needs no guard. */
5
6
  const record = (value) => isJson(value) ? value : {};
7
+ /** Drops the keys whose value is undefined, so a request body or result carries only what was set. Shallow: nested objects are not touched. */
6
8
  const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
9
+ /** The longest `timeout` a timer holds, in milliseconds: about 24.8 days. */
10
+ const MAX_TIMEOUT = 2147483647;
11
+ /**
12
+ * Refuses a `timeout` or `retries` that no timer or retry count can hold,
13
+ * before anything is sent.
14
+ *
15
+ * Throws `InvalidRequest` naming the accepted range.
16
+ */
17
+ const checkCallSettings = (settings) => {
18
+ const { retries, timeout } = settings;
19
+ if (timeout !== void 0 && !(Number.isInteger(timeout) && timeout >= 0 && timeout <= MAX_TIMEOUT)) throw new FieldworkError("InvalidRequest", `timeout is ${timeout}: pass a whole number of milliseconds from 0 to ${MAX_TIMEOUT}`);
20
+ if (retries !== void 0 && !(Number.isInteger(retries) && retries >= 0)) throw new FieldworkError("InvalidRequest", `retries is ${retries}: pass a whole number from 0 up`);
21
+ };
7
22
  /**
8
23
  * Splits an operation's options into the provider's own and the call's
9
24
  * settings. The call's `signal` also carries its `timeout` as a deadline, set
10
25
  * now, so every request the operation makes (a start, each poll, a result
11
26
  * download) shares one budget instead of restarting it. An empty `resume`
12
- * names no job, so it is refused here, once for every adapter.
27
+ * names no job, and a `timeout` or `retries` out of range holds no deadline or
28
+ * count, so both are refused here, once for every adapter.
13
29
  *
14
30
  * `grace` extends the deadline past `timeout` for an operation that sends the
15
31
  * timeout to the provider and needs a moment more to hear its report.
@@ -17,15 +33,26 @@ const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, i
17
33
  const callSettings = (options, grace = 0) => {
18
34
  const { retries, signal, timeout, ...rest } = options ?? {};
19
35
  if ("resume" in rest && rest.resume === "") throw new FieldworkError("InvalidRequest", "resume is empty: pass the jobId an earlier call returned, or leave resume out to start a job");
36
+ checkCallSettings({
37
+ retries,
38
+ timeout
39
+ });
20
40
  return {
21
41
  call: {
22
42
  retries,
23
- signal: timeout === void 0 ? signal : AbortSignal.any([...signal === void 0 ? [] : [signal], AbortSignal.timeout(timeout + grace)]),
43
+ signal: timeout === void 0 ? signal : AbortSignal.any([...signal === void 0 ? [] : [signal], AbortSignal.timeout(Math.min(timeout + grace, MAX_TIMEOUT))]),
24
44
  timeout
25
45
  },
26
46
  rest
27
47
  };
28
48
  };
49
+ /**
50
+ * Reads a provider field that holds JSON text. A value that is not a string
51
+ * is returned as it is, already parsed.
52
+ *
53
+ * Throws `ProviderError` carrying the parse error as `cause` when the text is
54
+ * not valid JSON.
55
+ */
29
56
  const parseJson = (provider, value) => {
30
57
  if (typeof value !== "string") return value;
31
58
  try {
@@ -37,6 +64,7 @@ const parseJson = (provider, value) => {
37
64
  });
38
65
  }
39
66
  };
67
+ /** The citations with repeated URLs removed: the first of each URL stays, in order. */
40
68
  const uniqueCitations = (all) => {
41
69
  const seen = /* @__PURE__ */ new Map();
42
70
  for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
@@ -58,6 +86,12 @@ const requireJobId = (provider, id) => {
58
86
  });
59
87
  return id.value;
60
88
  };
89
+ /**
90
+ * Builds a result's `meta`, leaving out whatever is absent: `units` with an
91
+ * undefined count, an empty `usage`, no `warnings`. A single warning string
92
+ * becomes a one-item list. Returns undefined when nothing is left, so a result
93
+ * has no `meta` at all rather than an empty one.
94
+ */
61
95
  const meta = (parts) => {
62
96
  const units = Object.fromEntries(Object.entries(parts.units ?? {}).filter((entry) => entry[1] !== void 0));
63
97
  const usage = compact({
@@ -73,10 +107,22 @@ const meta = (parts) => {
73
107
  });
74
108
  return Object.keys(result).length > 0 ? result : void 0;
75
109
  };
110
+ /**
111
+ * Refuses a request that sets more than one of `names` (a name counts as set
112
+ * unless its value is undefined), for options the provider rejects or ignores
113
+ * when combined. Throws before anything is sent.
114
+ *
115
+ * Throws `InvalidRequest` naming the options that were set.
116
+ */
76
117
  const refuseTogether = (provider, options, ...names) => {
77
118
  const set = names.filter((name) => options[name] !== void 0);
78
119
  if (set.length > 1) throw new FieldworkError("InvalidRequest", `${provider} does not accept ${set.join(" and ")} together; pass one`, { provider });
79
120
  };
121
+ /**
122
+ * A `maxAge` in seconds as the whole hours Exa and Tavily count in, rounded
123
+ * up, so 1 second is 1 hour and 0 stays 0 (always fetch fresh). A negative age
124
+ * (read only the cache) becomes -1. Undefined stays undefined.
125
+ */
80
126
  const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
81
127
  /** Statuses that mean the page is not there, so a read of it has no page to return. */
82
128
  const GONE = /* @__PURE__ */ new Set([404, 410]);
@@ -100,14 +146,26 @@ const presentPages = (pages) => ({
100
146
  })),
101
147
  pages: pages.filter((page) => page.statusCode === void 0 || !GONE.has(page.statusCode))
102
148
  });
149
+ /**
150
+ * Waits `ms`. When `signal` aborts it resolves early rather than rejecting, so
151
+ * the caller checks the signal afterwards. A signal already aborted on entry
152
+ * returns at once. The abort listener is removed when the wait ends, so a
153
+ * signal shared by many polls does not collect them.
154
+ */
103
155
  const sleep = async (ms, signal) => {
156
+ if (signal?.aborted === true) return;
157
+ const cleanup = new AbortController();
104
158
  await new Promise((resolve) => {
105
159
  const timer = setTimeout(resolve, ms);
106
160
  signal?.addEventListener("abort", () => {
107
161
  clearTimeout(timer);
108
162
  resolve();
109
- }, { once: true });
163
+ }, {
164
+ once: true,
165
+ signal: cleanup.signal
166
+ });
110
167
  });
168
+ cleanup.abort();
111
169
  };
112
170
  /** The longest wait between attempts; a provider asking for longer gets the error instead. */
113
171
  const MAX_RETRY_WAIT = 3e4;
@@ -134,6 +192,23 @@ const timedOut = (signal) => signal.reason instanceof DOMException && signal.rea
134
192
  * requests), `Aborted` when the caller cancelled.
135
193
  */
136
194
  const stopped = (signal, message, options) => new FieldworkError(timedOut(signal) ? "Timeout" : "Aborted", message, options);
195
+ /**
196
+ * The error a request that creates something throws. After anything but a
197
+ * rate limit the provider may already have created it, and the error carries
198
+ * no `jobId` to resume, so it is not `retryable`: repeating the call could
199
+ * start and charge for a second one.
200
+ */
201
+ const createFailure = (error) => {
202
+ if (!error.retryable || error.code === "RateLimited") return error;
203
+ return new FieldworkError(error.code, `${error.message}; ${error.provider ?? "the provider"} may already have created it, so check before repeating the call`, {
204
+ cause: error.cause,
205
+ provider: error.provider,
206
+ retryAfter: error.retryAfter,
207
+ retryable: false,
208
+ status: error.status
209
+ });
210
+ };
211
+ /** The error for a fetch that threw: stopped by the signal (`Timeout` or `Aborted`), timed out on its own, or a lost connection, which can succeed on repeat. */
137
212
  const transportError = (provider, error, signal) => {
138
213
  if (signal?.aborted === true) return stopped(signal, `${provider} request stopped: ${timedOut(signal) ? "timed out" : "cancelled"}`, {
139
214
  cause: error,
@@ -157,12 +232,25 @@ const readText = async (provider, response, signal) => {
157
232
  throw transportError(provider, error, signal);
158
233
  }
159
234
  };
235
+ /**
236
+ * Builds the client for one provider. A request is sent to `baseUrl` plus its
237
+ * path, with JSON bodies and the config's headers, and `timeout` and `signal`
238
+ * stop it. A failed request is repeated as `CallOptions.retries` says, waiting
239
+ * as long as the provider's `Retry-After` or backing off exponentially, and
240
+ * never past the call's `timeout`. A request marked `creates` is repeated only
241
+ * after a rate limit.
242
+ */
160
243
  const createRawClient = (config) => {
161
244
  const doFetch = config.fetch ?? globalThis.fetch;
162
245
  return {
163
246
  baseUrl: config.baseUrl,
164
247
  provider: config.provider,
165
248
  async request(method, path, options = {}) {
249
+ const retries = options.retries ?? config.retries ?? 2;
250
+ checkCallSettings({
251
+ retries,
252
+ timeout: options.timeout
253
+ });
166
254
  const url = new URL(config.baseUrl.replace(/\/$/u, "") + path);
167
255
  for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
168
256
  const headers = new Headers({
@@ -213,7 +301,6 @@ const createRawClient = (config) => {
213
301
  status: response.status
214
302
  });
215
303
  };
216
- const retries = options.retries ?? config.retries ?? 2;
217
304
  const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
218
305
  const attempt = async (count) => {
219
306
  try {
@@ -226,7 +313,7 @@ const createRawClient = (config) => {
226
313
  retries,
227
314
  signal
228
315
  });
229
- if (wait === void 0 || deadline !== void 0 && Date.now() + wait >= deadline) throw error;
316
+ if (wait === void 0 || deadline !== void 0 && Date.now() + wait >= deadline) throw options.creates === true ? createFailure(error) : error;
230
317
  await sleep(wait, signal);
231
318
  if (options.signal?.aborted === true) throw stopped(options.signal, `${config.provider} request stopped while waiting to retry`, {
232
319
  cause: error,
@@ -301,6 +388,11 @@ const describe = (parsed, text) => {
301
388
  }
302
389
  return text.slice(0, 300);
303
390
  };
391
+ /**
392
+ * Seconds to wait from a `Retry-After` header, which is a number of seconds or
393
+ * an HTTP date. Undefined when the header is absent, empty or neither. `now`
394
+ * is for tests.
395
+ */
304
396
  const retryAfterSeconds = (header, now = Date.now()) => {
305
397
  if (header === null || header === "") return;
306
398
  const seconds = Number(header);
@@ -308,8 +400,23 @@ const retryAfterSeconds = (header, now = Date.now()) => {
308
400
  const date = Date.parse(header);
309
401
  return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
310
402
  };
311
- /** An id as one path segment, so a caller's `resume` cannot reach another endpoint. */
312
- const segment = (id) => encodeURIComponent(id);
403
+ /**
404
+ * An id as one path segment, so a caller's `resume` cannot reach another
405
+ * endpoint.
406
+ *
407
+ * Throws `InvalidRequest` for an empty id, "." or "..", which survive encoding
408
+ * and which the URL parser would resolve to another path.
409
+ */
410
+ const segment = (id) => {
411
+ if (id === "" || id === "." || id === "..") throw new FieldworkError("InvalidRequest", `${JSON.stringify(id)} is not an id: pass the id the provider returned`);
412
+ return encodeURIComponent(id);
413
+ };
414
+ /**
415
+ * The API key: `given`, else the environment variable. An empty `given` is
416
+ * not replaced by the variable.
417
+ *
418
+ * Throws `Unauthorized` when there is no key or it is empty.
419
+ */
313
420
  const requireKey = (provider, given, envName) => {
314
421
  const key = given ?? process.env[envName];
315
422
  if (key === void 0 || key === "") throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
@@ -337,15 +444,6 @@ const readSigned = async (provider, url, options) => {
337
444
  return text;
338
445
  };
339
446
  // src/parse.ts
340
- /**
341
- * Building blocks for the schemas that parse a provider's response at the
342
- * boundary. Every block is lenient: it never fails, so a provider that adds,
343
- * removes or retypes a field cannot make a working call throw. A field of the
344
- * wrong type reads as absent, and unknown keys pass through. Build each
345
- * adapter's response schema only from these, then `z.parse` the response once.
346
- * The provider's untouched response still goes in `raw`; the parsed value is
347
- * for reading only.
348
- */
349
447
  /** The result of a field that is absent or of the wrong type. */
350
448
  const nothing = () => void 0;
351
449
  /** Reads any value as absent. A union's last member, so a value of the wrong type does not fail. */
@@ -1,14 +1,22 @@
1
- import { K as Recency, Y as SearchResponse, a as RawClient, b as Decisions, l as Answer, p as CallOptions, q as Research, t as Adapter, y as DecisionQuestion } from "./adapter-BgdfLBs-.js";
2
- import { t as OutputSchema } from "./schema-Cupy7-7q.js";
1
+ import { K as Recency, Y as SearchResponse, a as RawClient, b as Decisions, l as Answer, p as CallOptions, q as Research, t as Adapter, y as DecisionQuestion } from "./adapter-Bh8EIrNe.js";
2
+ import { t as OutputSchema } from "./schema-BWWiMvkg.js";
3
+ /** Settings for `perplexity()`. */
3
4
  interface PerplexityConfig {
4
5
  /** Defaults to the PERPLEXITY_API_KEY environment variable. */
5
6
  apiKey?: string;
7
+ /** Defaults to https://api.perplexity.ai. */
6
8
  baseUrl?: string;
9
+ /** Used in place of the global `fetch`. */
7
10
  fetch?: typeof fetch;
8
11
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
12
  retries?: number;
10
13
  }
11
- /** The filters Perplexity applies to web search, on `/search` and inside the Agent API's `web_search` tool. */
14
+ /**
15
+ * The filters Perplexity applies to web search, on `/search` and inside the
16
+ * Agent API's `web_search` tool. Dates are given as YYYY-MM-DD and sent as
17
+ * MM/DD/YYYY, which Perplexity requires. Perplexity has one domain list, so
18
+ * `excludeDomains` entries are sent with a leading `-`.
19
+ */
12
20
  interface PerplexityFilters {
13
21
  /** Plain domains such as `nature.com`; Perplexity also accepts a path (`nature.com/articles`) or a top-level domain (`.gov`). At most 20. Not with `excludeDomains`. */
14
22
  includeDomains?: string[];
@@ -24,6 +32,11 @@ interface PerplexityFilters {
24
32
  lastUpdatedBefore?: string;
25
33
  recency?: Recency;
26
34
  }
35
+ /**
36
+ * Options for `search` (`POST /search`). Refused before sending: both domain lists,
37
+ * more than five queries in all, a `limit` over 20 (50 with `searchType: "people"`),
38
+ * and a date that is not YYYY-MM-DD.
39
+ */
27
40
  interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
28
41
  /** Results to return: up to 20, or up to 50 with `searchType: "people"`. */
29
42
  limit?: number;
@@ -36,7 +49,7 @@ interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
36
49
  searchType?: "web" | "fast" | "people";
37
50
  /** ISO 3166-1 alpha-2 code such as "GB". */
38
51
  country?: string;
39
- /** ISO 639-1 codes, at most 20. Several codes match any of them. */
52
+ /** ISO 639-1 codes, at most 20, lower-cased before sending. Several codes match any of them. */
40
53
  language?: string | string[];
41
54
  /** Page-content tokens across all results. */
42
55
  maxTokens?: number;
@@ -45,9 +58,11 @@ interface PerplexitySearchOptions extends CallOptions, PerplexityFilters {
45
58
  }
46
59
  /** An effort level, or a name pinned to a version such as `fast@2026-10-16.0`. */
47
60
  type Pinned<Name extends string> = Name | `${Name}@${string}`;
61
+ /** Options for `answer`: a synchronous Agent API call. It takes no search filters. */
48
62
  interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
49
63
  /** Defaults to "fast". Answers are synchronous, so only the quicker levels are offered. */
50
64
  effort?: Pinned<"fast" | "low" | "medium">;
65
+ /** System instructions for the answer. */
51
66
  instructions?: string;
52
67
  /** A JSON Schema, or a Zod, Valibot or ArkType schema that types and checks `output`. */
53
68
  schema?: OutputSchema<T>;
@@ -59,6 +74,12 @@ interface PerplexityAnswerOptions<T = unknown> extends CallOptions {
59
74
  * `ultra-preview` and version pins (`high@2026-10-28.0`) are accepted too.
60
75
  */
61
76
  type PerplexityEffort = "fast" | "low" | "medium" | "high" | "xhigh" | "ultra-preview" | (string & {});
77
+ /**
78
+ * Options for `research`: a background Agent API run, polled until it ends. The
79
+ * search filters go on the run's `web_search` tool, and both domain lists are
80
+ * refused together. A run that ends `incomplete` or `cancelled` with output returns
81
+ * `status: "partial"`.
82
+ */
62
83
  interface PerplexityResearchOptions<T = unknown> extends CallOptions, PerplexityFilters {
63
84
  schema?: OutputSchema<T>;
64
85
  /**
@@ -69,7 +90,11 @@ interface PerplexityResearchOptions<T = unknown> extends CallOptions, Perplexity
69
90
  effort?: PerplexityEffort;
70
91
  /** A model in `provider/model` form, such as `openai/gpt-6-luna`. Overrides the effort's model. */
71
92
  model?: string;
72
- /** Models to try in order, one to five; the first that works answers. Takes precedence over `model`. */
93
+ /**
94
+ * Models to try in order, one to five (more is refused); the first that works
95
+ * answers. Takes precedence over `model`. With `model` or `models` and no
96
+ * `effort`, the run gets the `web_search` and `fetch_url` tools.
97
+ */
73
98
  models?: string[];
74
99
  /**
75
100
  * Caps steps of the research loop (1 to 500), not money. With `model` or
@@ -78,6 +103,7 @@ interface PerplexityResearchOptions<T = unknown> extends CallOptions, Perplexity
78
103
  */
79
104
  maxSteps?: number;
80
105
  maxOutputTokens?: number;
106
+ /** System instructions for the run. */
81
107
  instructions?: string;
82
108
  /** ISO 639-1 code for the language of the report. */
83
109
  languagePreference?: string;
@@ -90,11 +116,17 @@ interface PerplexityResearchOptions<T = unknown> extends CallOptions, Perplexity
90
116
  /** Milliseconds between checks. Defaults to 2000. */
91
117
  interval?: number;
92
118
  }
119
+ /** Perplexity's decider models. The type is open so newer names are accepted. */
93
120
  type PerplexityDeciderModel = "pplx-decider-v1.2" | "pplx-decider-flash-v1.2" | "pplx-decider-latest" | "pplx-decider-flash-latest" | (string & {});
121
+ /** Options for `decide` (`POST /v1/decisions`). The result never has citations. */
94
122
  interface PerplexityDecideOptions extends CallOptions {
95
123
  /** Defaults to "pplx-decider-latest". The flash models are smaller and cheaper. */
96
124
  model?: PerplexityDeciderModel;
97
125
  }
126
+ /**
127
+ * What Perplexity offers: search, answer, research and decide. `research` runs as a
128
+ * job and accepts `resume`.
129
+ */
98
130
  interface PerplexityOperations {
99
131
  search: (query: string, options?: PerplexitySearchOptions) => Promise<SearchResponse>;
100
132
  answer: <T = unknown>(question: string, options?: PerplexityAnswerOptions<T>) => Promise<Answer<T>>;