@howells/fieldwork-sdk 0.6.0 → 0.7.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/reducto.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { a as refuseLarger, n as documentPart } from "./document-Clmi51Sf.js";
2
+ import { n as documentPart, o as refuseLarger, r as documentUrl } from "./document-DOzhDFFt.js";
3
3
  import { t as FieldworkError } from "./errors-DROZyb9T.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, 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";
4
+ import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-lMLcxUsG.js";
5
+ import { i as startJob, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
6
+ import { a as compact, c as parseJson, p as requireJobId, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
6
7
  import * as z from "zod/mini";
7
8
  // src/adapters/reducto/response.ts
8
9
  /** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
@@ -109,18 +110,22 @@ const provider = "reducto";
109
110
  const MAX_UPLOAD_MB = 100;
110
111
  /** Uploads the file, then starts the parse, and returns the job id. Refuses a file over the size limit before sending. */
111
112
  const startParse = async (raw, document, o, call) => {
112
- refuseLarger(provider, document, MAX_UPLOAD_MB);
113
- const form = new FormData();
114
- form.set("file", documentPart(document), document.name);
115
- const uploaded = z.parse(UploadResponse, await raw.request("POST", "/upload", {
116
- creates: true,
117
- ...call,
118
- form
119
- }));
113
+ let input;
114
+ if (document.url === void 0) {
115
+ refuseLarger(provider, document, MAX_UPLOAD_MB);
116
+ const form = new FormData();
117
+ form.set("file", documentPart(document), document.name);
118
+ const uploaded = z.parse(UploadResponse, await raw.request("POST", "/upload", {
119
+ creates: true,
120
+ ...call,
121
+ form
122
+ }));
123
+ input = requireJobId(provider, uploaded.file_id);
124
+ } else input = documentUrl(provider, document);
120
125
  return await startJob(raw, "/parse_async", {
121
126
  ...call,
122
127
  body: compact({
123
- input: requireJobId(provider, uploaded.file_id),
128
+ input,
124
129
  settings: o.wordBoxes === true ? { return_citations: true } : void 0
125
130
  })
126
131
  }, ParseStart, (reply) => reply.job_id);
@@ -0,0 +1,136 @@
1
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
2
+ import { o as isText, r as isJsonObject, t as joinPath } from "./path-DL5P8XH2.js";
3
+ // src/schema-subset.ts
4
+ const MAPS = /* @__PURE__ */ new Set([
5
+ "properties",
6
+ "patternProperties",
7
+ "$defs",
8
+ "definitions",
9
+ "dependentSchemas"
10
+ ]);
11
+ const CHILDREN = /* @__PURE__ */ new Set([
12
+ "items",
13
+ "additionalItems",
14
+ "additionalProperties",
15
+ "contains",
16
+ "not",
17
+ "if",
18
+ "then",
19
+ "else",
20
+ "propertyNames",
21
+ "unevaluatedProperties",
22
+ "unevaluatedItems"
23
+ ]);
24
+ const LISTS = /* @__PURE__ */ new Set([
25
+ "allOf",
26
+ "anyOf",
27
+ "oneOf",
28
+ "prefixItems"
29
+ ]);
30
+ const refuse = (provider, path, message) => {
31
+ throw invalidRequest(provider, `${joinPath(path)}: ${message}`);
32
+ };
33
+ const exaSchema = (value, path) => {
34
+ if (!isJsonObject(value)) return;
35
+ if (Array.isArray(value.type)) refuse("exa", [...path, "type"], "JSON Schema type arrays are not supported; use a single type. Fieldwork will not remove null from the caller's schema");
36
+ for (const [key, child] of Object.entries(value)) {
37
+ const next = [...path, key];
38
+ if (MAPS.has(key) && isJsonObject(child)) for (const [name, entry] of Object.entries(child)) exaSchema(entry, [...next, name]);
39
+ else if ((LISTS.has(key) || key === "items") && Array.isArray(child)) for (const [index, entry] of child.entries()) exaSchema(entry, [...next, index]);
40
+ else if (CHILDREN.has(key)) exaSchema(child, next);
41
+ }
42
+ };
43
+ const TYPES = /* @__PURE__ */ new Set([
44
+ "object",
45
+ "string",
46
+ "integer",
47
+ "number",
48
+ "array"
49
+ ]);
50
+ const tavilyType = (node, path, kind) => {
51
+ const type = kind === "root" && node.type === void 0 ? "object" : node.type;
52
+ if (!isText(type) || !TYPES.has(type) || kind === "root" && type !== "object") return refuse("tavily", [...path, "type"], "must be object, string, integer, number or array (object at the root)");
53
+ if ((kind === "property" || node.description !== void 0) && !isText(node.description)) return refuse("tavily", [...path, "description"], "must be a string on every property");
54
+ const allowed = /* @__PURE__ */ new Set([
55
+ "type",
56
+ "description",
57
+ ...type === "object" ? ["properties", "required"] : [],
58
+ ...type === "array" ? ["items"] : []
59
+ ]);
60
+ for (const key of Object.keys(node)) if (!allowed.has(key)) refuse("tavily", [...path, key], "is not supported by research output_schema");
61
+ return type;
62
+ };
63
+ const requiredNames = (required, properties, path) => {
64
+ if (required === void 0) return;
65
+ if (!Array.isArray(required) || required.length === 0 || required.some((key) => !isText(key) || !Object.hasOwn(properties, key))) refuse("tavily", [...path, "required"], "must be a nonempty array of names from properties");
66
+ };
67
+ const tavilySchema = (value, path, kind) => {
68
+ if (!isJsonObject(value)) return refuse("tavily", path, "must be a schema object");
69
+ const type = tavilyType(value, path, kind);
70
+ if (type === "object") {
71
+ const { properties } = value;
72
+ if (!isJsonObject(properties)) return refuse("tavily", [...path, "properties"], "must be an object for an object schema");
73
+ for (const [key, child] of Object.entries(properties)) tavilySchema(child, [
74
+ ...path,
75
+ "properties",
76
+ key
77
+ ], "property");
78
+ requiredNames(value.required, properties, path);
79
+ } else if (type === "array") tavilySchema(value.items, [...path, "items"], "item");
80
+ };
81
+ /** Validates the provider's documented or observed subset without rewriting it. */
82
+ const checkSchemaSubset = (schema, provider) => {
83
+ if (provider === "exa") exaSchema(schema, ["schema"]);
84
+ else tavilySchema(schema, ["schema"], "root");
85
+ return schema;
86
+ };
87
+ // src/schema.ts
88
+ const isStandard = (schema) => "~standard" in schema;
89
+ /**
90
+ * The JSON Schema to send to a provider. A plain JSON Schema passes through as
91
+ * given; a Standard Schema is converted to `target`, without its `$schema` key,
92
+ * because the provider's docs, not the library, say which dialect it reads.
93
+ *
94
+ * Throws `InvalidRequest`, with the library's error as `cause`, when the
95
+ * library cannot write the schema as `target`.
96
+ */
97
+ const jsonSchemaOf = (schema, target = "draft-2020-12", subset) => {
98
+ if (!isStandard(schema)) return subset === void 0 ? schema : checkSchemaSubset(schema, subset);
99
+ let result;
100
+ try {
101
+ const converted = schema["~standard"].jsonSchema.input({ target });
102
+ result = Object.fromEntries(Object.entries(converted).filter(([key]) => key !== "$schema"));
103
+ } catch (error) {
104
+ throw new FieldworkError("InvalidRequest", `the ${schema["~standard"].vendor} schema cannot be written as ${target} JSON Schema: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
105
+ }
106
+ return subset === void 0 ? result : checkSchemaSubset(result, subset);
107
+ };
108
+ const MAX_ISSUES = 3;
109
+ const pathOf = (issue) => {
110
+ const segments = (issue.path ?? []).map((segment) => String(segment instanceof Object ? segment.key : segment));
111
+ return segments.length > 0 ? segments.join(".") : "(root)";
112
+ };
113
+ const describeIssues = (issues) => {
114
+ const shown = issues.slice(0, MAX_ISSUES).map((issue) => `${pathOf(issue)}: ${issue.message}`);
115
+ const more = issues.length - shown.length;
116
+ return `${shown.join("; ")}${more > 0 ? `; and ${more} more` : ""}`;
117
+ };
118
+ /**
119
+ * The provider's structured output as the caller's type. A Standard Schema
120
+ * checks it and throws `ProviderError` listing the first three issues with
121
+ * their paths, not `retryable` and carrying the context's `jobId`; the value
122
+ * returned is the schema's own output, so transforms and defaults apply. A
123
+ * plain JSON Schema, or no schema, leaves it unchecked.
124
+ */
125
+ const checkOutput = async (schema, value, context) => {
126
+ if (schema === void 0 || !isStandard(schema)) return value;
127
+ const result = await schema["~standard"].validate(value);
128
+ if (result.issues !== void 0) throw new FieldworkError("ProviderError", `${context.provider} returned output that does not match the schema: ${describeIssues(result.issues)}`, {
129
+ cause: result.issues,
130
+ jobId: context.jobId,
131
+ provider: context.provider,
132
+ retryable: false
133
+ });
134
+ return result.value;
135
+ };
136
+ export { jsonSchemaOf as n, checkOutput as t };
@@ -1,4 +1,4 @@
1
- import { M as JsonSchema } from "./adapter-Bh8EIrNe.js";
1
+ import { N as JsonSchema } from "./adapter-C1mzXyKH.js";
2
2
  /** Vendor-specific parameters a schema library may accept. */
3
3
  type LibraryOptions = JsonSchema;
4
4
  /** The path segment interface of an issue. */
package/dist/serpapi.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-Bh8EIrNe.js";
1
+ import { M as ImageSearch, X as SearchResponse, a as RawClient, p as CallOptions, q as Recency, s as AccountUsage, t as Adapter } from "./adapter-C1mzXyKH.js";
2
2
  import "./util-DhYr1OS3.js";
3
3
  /** Settings for `serpapi()`. */
4
4
  interface SerpApiConfig {
package/dist/serpapi.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { C as createRawClient, M as compact, P as meta, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, k as callSettings, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings, z as refuseTogether } from "./parse-COHKvfH9.js";
3
+ import { C as createRawClient, T as requireKey, a as looseObject, f as optionalNumber, h as optionalString, m as optionalScalar, o as nonEmptyString, r as arrayOf, x as warnings } from "./parse-lMLcxUsG.js";
4
+ import { a as compact, f as refuseTogether, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
4
5
  import * as z from "zod/mini";
5
6
  // src/adapters/serpapi/parse.ts
6
7
  /** The name this adapter reports in errors and results. */
package/dist/tavily.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { K as Recency, Q as SiteMap, R as Page, Y as SearchResponse, _ as Crawl, a as RawClient, j as ImageSearch, l as Answer, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-Bh8EIrNe.js";
2
- import { t as OutputSchema } from "./schema-BWWiMvkg.js";
1
+ import { $ as SiteMap, B as PageBatch, J as Research, M as ImageSearch, X as SearchResponse, _ as Crawl, a as RawClient, l as Answer, p as CallOptions, q as Recency, s as AccountUsage, t as Adapter, z as Page } from "./adapter-C1mzXyKH.js";
2
+ import { t as OutputSchema } from "./schema-DNYyDTlM.js";
3
3
  /** Settings for the Tavily adapter. */
4
4
  interface TavilyConfig {
5
5
  /** Defaults to the TAVILY_API_KEY environment variable. */
@@ -162,7 +162,7 @@ interface TavilyResearchFile {
162
162
  * names that do not end in `.txt`, `.md` or `.json`.
163
163
  */
164
164
  interface TavilyResearchOptions<T = unknown> extends CallOptions {
165
- /** Tavily accepts object, string, integer, number and array types only, and each property needs a description. */
165
+ /** Tavily accepts object, string, integer, number and array types only, and each property needs a description. Type arrays, including nullable unions, throw `InvalidRequest` before sending. */
166
166
  schema?: OutputSchema<T>;
167
167
  model?: "mini" | "pro" | "auto";
168
168
  citationFormat?: "numbered" | "mla" | "apa" | "chicago";
package/dist/tavily.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
2
  import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
- import { C as createRawClient, E as segment, M as compact, N as hours, 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 } from "./parse-COHKvfH9.js";
4
- import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
3
+ import { C as createRawClient, E as segment, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, m as optionalScalar, n as anything, r as arrayOf } from "./parse-lMLcxUsG.js";
4
+ import { i as startJob, n as requireOutput, r as runJob, t as jobState } from "./job-DBhGs7Ha.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-COAaWnZB.js";
6
+ import { a as compact, o as hours, s as meta, t as callSettings } from "./util-BqeRYF2b.js";
6
7
  import * as z from "zod/mini";
7
8
  // src/adapters/tavily/countries.ts
8
9
  /** Tavily's country names, by ISO 3166-1 alpha-2 code. */
@@ -188,6 +189,19 @@ const base64 = (bytes) => {
188
189
  for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCodePoint(...bytes.subarray(index, index + 32768));
189
190
  return btoa(binary);
190
191
  };
192
+ /** Checks and encodes Tavily research attachments before a job is started or resumed. */
193
+ const researchFiles = (input) => {
194
+ const files = input?.map((file) => {
195
+ if (!RESEARCH_FILE.test(file.name)) throw invalidRequest(provider, `reads .txt, .md and .json files, not ${file.name}`);
196
+ return {
197
+ data: base64(typeof file.data === "string" ? new TextEncoder().encode(file.data) : file.data),
198
+ name: file.name,
199
+ type: "base64"
200
+ };
201
+ });
202
+ if (files && files.length > 5) throw invalidRequest(provider, "research takes up to 5 files");
203
+ return files;
204
+ };
191
205
  // src/adapters/tavily/response.ts
192
206
  /** What a response reports about its own cost: the credits used, the id and the time taken. */
193
207
  const usageShape = {
@@ -421,15 +435,7 @@ const tavily = (config = {}) => {
421
435
  },
422
436
  async research(question, options) {
423
437
  const { call, rest: o } = callSettings(options);
424
- const files = o.files?.map((file) => {
425
- if (!RESEARCH_FILE.test(file.name)) throw invalidRequest(provider, `reads .txt, .md and .json files, not ${file.name}`);
426
- return {
427
- data: base64(typeof file.data === "string" ? new TextEncoder().encode(file.data) : file.data),
428
- name: file.name,
429
- type: "base64"
430
- };
431
- });
432
- if (files && files.length > 5) throw invalidRequest(provider, "research takes up to 5 files");
438
+ const files = researchFiles(o.files);
433
439
  return await runJob(provider, {
434
440
  check: async (id, request) => {
435
441
  const current = await raw.request("GET", `/research/${segment(id)}`, {
@@ -477,7 +483,7 @@ const tavily = (config = {}) => {
477
483
  input: question,
478
484
  model: o.model,
479
485
  output_length: o.outputLength,
480
- output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
486
+ output_schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema, "draft-2020-12", "tavily"),
481
487
  stream: false
482
488
  })
483
489
  }, ResearchStart, (reply) => reply.request_id)
package/dist/tools.d.ts CHANGED
@@ -1,11 +1,14 @@
1
- import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-BaWqUNI3.js";
2
- import { M as JsonSchema, m as Capability, n as AnyAdapter, p as CallOptions } from "./adapter-Bh8EIrNe.js";
1
+ import { i as FieldworkErrorCode, t as Fieldwork } from "./fieldwork-Dtlhkzf2.js";
2
+ import { N as JsonSchema, m as Capability, n as AnyAdapter, p as CallOptions } from "./adapter-C1mzXyKH.js";
3
3
  /** Any JSON value. */
4
4
  type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
5
5
  /** A JSON object. A key may be undefined, which reads as absent and is not serialized. */
6
6
  interface JsonObject {
7
7
  [key: string]: JsonValue | undefined;
8
8
  }
9
+ export declare const DEFAULT_MAX_CHARACTERS = 20000;
10
+ /** Checks configured and per-call budgets against the same optional cap. */
11
+ export declare const checkMaxCharacters: (value: JsonValue | undefined, limit?: number) => number;
9
12
  /** What a model sends a tool: a parsed JSON value, which must be an object. */
10
13
  export type ToolInput = JsonValue;
11
14
  /** The arguments a tool accepts, once they are known to be an object. */
@@ -74,6 +77,8 @@ export interface ToolsOptions {
74
77
  * fewer, such as titles, URLs and snippets, is never cut. Defaults to 20,000.
75
78
  */
76
79
  maxCharacters?: number;
80
+ /** Maximum configured or per-call budget; advertised in each input schema. */
81
+ maxCharactersLimit?: number;
77
82
  }
78
83
  /**
79
84
  * Makes one tool per capability, or per method of a group, the instance
package/dist/tools.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
+ import { f as refuseTogether } from "./util-BqeRYF2b.js";
3
+ import { a as isNumber, i as isList, n as isFlag, o as isText, r as isJsonObject, t as joinPath } from "./path-DL5P8XH2.js";
2
4
  import { t as CAPABILITIES } from "./types-CnomnF-6.js";
5
+ import * as z from "zod/mini";
3
6
  // src/tool-specs/schema.ts
4
7
  const described = (schema, description) => description === void 0 ? schema : {
5
8
  ...schema,
@@ -708,8 +711,8 @@ const ANSWER_SPECS = [
708
711
  * The tools that drive a browser or convert a file: `run_browser_script`,
709
712
  * `open_browser`, `close_browser` and `parse_document`. `toolsFor` leaves out
710
713
  * the first three unless asked, since they start billed sessions with real
711
- * effects; `parse_document` is a normal tool. Its `name` and `contentBase64`
712
- * become the one file argument `parse` takes.
714
+ * effects; `parse_document` is a normal tool. Its URL or name and bytes
715
+ * become the one document argument `parse` takes.
713
716
  */
714
717
  const BROWSER_SPECS = [
715
718
  {
@@ -787,19 +790,24 @@ const BROWSER_SPECS = [
787
790
  },
788
791
  {
789
792
  capability: "parse",
790
- description: "Convert a document file (PDF, DOCX, XLSX, PPTX, HTML or CSV) to Markdown. Use when you have the file's bytes. Do not use for a document at a public URL (use read_page).",
793
+ description: "Convert a document file (PDF, DOCX, XLSX, PPTX, HTML or CSV) to Markdown. Use name and contentBase64 for bytes, or a public url with LlamaParse or Reducto. Firecrawl accepts bytes here; use read_page for a public URL.",
791
794
  destructive: false,
792
795
  fields: [
793
796
  {
794
797
  name: "name",
795
- required: true,
798
+ requiredFor: ["firecrawl"],
796
799
  schema: text("The file name with its extension, such as spec-sheet.pdf. The extension tells the provider the type.")
797
800
  },
798
801
  {
799
802
  name: "contentBase64",
800
- required: true,
803
+ requiredFor: ["firecrawl"],
801
804
  schema: text("The file's bytes, base64-encoded.")
802
805
  },
806
+ {
807
+ name: "url",
808
+ providers: ["llamaparse", "reducto"],
809
+ schema: url("Public HTTP or HTTPS document URL; the provider fetches it. Use instead of name and contentBase64 for large files.")
810
+ },
803
811
  {
804
812
  name: "pages",
805
813
  providers: ["firecrawl"],
@@ -810,7 +818,11 @@ const BROWSER_SPECS = [
810
818
  idempotent: true,
811
819
  name: "parse_document",
812
820
  output: PARSE_OUTPUT,
813
- positional: ["name", "contentBase64"],
821
+ positional: [
822
+ "name",
823
+ "contentBase64",
824
+ "url"
825
+ ],
814
826
  readOnly: true,
815
827
  title: "Convert a document to Markdown"
816
828
  }
@@ -1255,14 +1267,14 @@ const SPECS = [
1255
1267
  ...BROWSER_SPECS,
1256
1268
  ...MONITOR_SPECS
1257
1269
  ];
1258
- // src/tools/json.ts
1259
- const isText = (value) => typeof value === "string";
1260
- /** A finite number: JSON has no NaN or Infinity. */
1261
- const isNumber = (value) => typeof value === "number" && Number.isFinite(value);
1262
- const isFlag = (value) => typeof value === "boolean";
1263
- const isList = (value) => Array.isArray(value);
1264
- /** Narrows anything, such as a value a transport hands over, to a JSON object. */
1265
- const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1270
+ // src/tools/budget.ts
1271
+ const DEFAULT_MAX_CHARACTERS = 2e4;
1272
+ /** Checks configured and per-call budgets against the same optional cap. */
1273
+ const checkMaxCharacters = (value, limit = Number.MAX_SAFE_INTEGER) => {
1274
+ const parsed = z.safeParse(z.number().check(z.int(), z.minimum(1), z.maximum(limit)), value);
1275
+ if (!parsed.success) throw new FieldworkError("InvalidRequest", `maxCharacters must be an integer from 1 to ${limit}`);
1276
+ return parsed.data;
1277
+ };
1266
1278
  // src/tools/dispatch.ts
1267
1279
  const isOperation = (value) => typeof value === "function";
1268
1280
  const isGroup = (value) => isJsonObject(value);
@@ -1280,8 +1292,12 @@ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/u;
1280
1292
  * Throws `InvalidRequest` when either is not a string or the content is not
1281
1293
  * well-formed base64 (standard alphabet, padded to a multiple of 4).
1282
1294
  */
1283
- const documentFrom = (name, content) => {
1284
- if (!isText(name) || !isText(content)) throw new FieldworkError("InvalidRequest", "parse_document needs name and contentBase64");
1295
+ const documentFrom = (provider, values) => {
1296
+ refuseTogether(provider, values, "url", "contentBase64");
1297
+ refuseTogether(provider, values, "url", "name");
1298
+ const { contentBase64: content, name, url } = values;
1299
+ if (isText(url)) return { url };
1300
+ if (!isText(name) || !isText(content)) throw new FieldworkError("InvalidRequest", "parse_document needs name and contentBase64, or a public url with llamaparse or reducto");
1285
1301
  if (content.length % 4 !== 0 || !BASE64.test(content)) throw new FieldworkError("InvalidRequest", `parse_document: contentBase64 must be standard base64 padded to a multiple of 4 characters${content.startsWith("data:") ? "; remove the data: prefix" : ""}`);
1286
1302
  return {
1287
1303
  data: new Uint8Array(Buffer.from(content, "base64")),
@@ -1292,15 +1308,15 @@ const documentFrom = (name, content) => {
1292
1308
  * The arguments for the spec's method, from validated input and the call
1293
1309
  * settings: the `positional` fields in order, then one options object of the
1294
1310
  * other fields and the call settings (`signal`, `timeout`, `retries`). `parse`
1295
- * is the exception: its two positional fields become one `DocumentArgument`.
1311
+ * is the exception: its source fields become one `DocumentArgument`.
1296
1312
  */
1297
- const argumentsFor = (spec, values, call) => {
1313
+ const argumentsFor = (spec, values, call, provider) => {
1298
1314
  const options = {
1299
1315
  ...Object.fromEntries(Object.entries(values).filter(([key]) => !spec.positional.includes(key))),
1300
1316
  ...call
1301
1317
  };
1302
1318
  const positional = spec.positional.map((name) => values[name]);
1303
- if (spec.capability === "parse") return [documentFrom(positional[0], positional[1]), options];
1319
+ if (spec.capability === "parse") return [documentFrom(provider, values), options];
1304
1320
  return [...positional, options];
1305
1321
  };
1306
1322
  // src/tools/model.ts
@@ -1337,11 +1353,17 @@ const rank = (key) => {
1337
1353
  return SPEND_LAST.includes(key) ? SPEND_FIRST.length + 1 + SPEND_LAST.indexOf(key) : SPEND_FIRST.length;
1338
1354
  };
1339
1355
  /** The text whole if it is short or the budget covers it; otherwise cut to what is left of the budget, with a note of how much was shown. Short text spends nothing. */
1340
- const cut = (value, budget) => {
1356
+ const cut = (value, budget, path) => {
1341
1357
  if (value.length <= SHORT_TEXT) return value;
1342
1358
  const kept = Math.min(value.length, budget.remaining);
1343
1359
  budget.remaining -= kept;
1344
- return kept === value.length ? value : `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
1360
+ if (kept === value.length) return value;
1361
+ budget.truncated.push({
1362
+ length: value.length,
1363
+ path: joinPath(path),
1364
+ shown: kept
1365
+ });
1366
+ return `${value.slice(0, kept)}\n\n[cut: ${kept} of ${value.length} characters shown]`;
1345
1367
  };
1346
1368
  /**
1347
1369
  * Applies `cut` and the `raw` rule through a value. Fields are visited in
@@ -1349,13 +1371,13 @@ const cut = (value, budget) => {
1349
1371
  * object keeps its own key order. `verbatim` is set inside `VERBATIM` keys and
1350
1372
  * stays set below them.
1351
1373
  */
1352
- const shape = (value, verbatim, budget) => {
1353
- if (isText(value)) return cut(value, budget);
1354
- if (isList(value)) return value.map((item) => shape(item, verbatim, budget) ?? null);
1374
+ const shape = (value, verbatim, budget, path) => {
1375
+ if (isText(value)) return cut(value, budget, path);
1376
+ if (isList(value)) return value.map((item, index) => shape(item, verbatim, budget, [...path, index]) ?? null);
1355
1377
  if (!isJsonObject(value)) return value;
1356
1378
  const entries = Object.entries(value).filter(([key]) => verbatim || key !== "raw");
1357
1379
  const shaped = /* @__PURE__ */ new Map();
1358
- for (const [key, item] of entries.toSorted(([a], [b]) => rank(a) - rank(b))) shaped.set(key, shape(item, verbatim || VERBATIM.has(key), budget));
1380
+ for (const [key, item] of entries.toSorted(([a], [b]) => rank(a) - rank(b))) shaped.set(key, shape(item, verbatim || VERBATIM.has(key), budget, [...path, key]));
1359
1381
  return Object.fromEntries(entries.map(([key]) => [key, shaped.get(key)]));
1360
1382
  };
1361
1383
  /**
@@ -1365,8 +1387,14 @@ const shape = (value, verbatim, budget) => {
1365
1387
  * served first and alternate renderings such as HTML last.
1366
1388
  */
1367
1389
  const forModel = (result, budget) => {
1368
- const shaped = shape(result, false, { remaining: budget });
1369
- return isJsonObject(shaped) ? shaped : {};
1390
+ const truncated = [];
1391
+ const shaped = shape(result, false, {
1392
+ remaining: budget,
1393
+ truncated
1394
+ }, []);
1395
+ const output = isJsonObject(shaped) ? shaped : {};
1396
+ if (truncated.length > 0) output.truncated = truncated;
1397
+ return output;
1370
1398
  };
1371
1399
  // src/tools/validate.ts
1372
1400
  /** The shape only: 2026-02-31 passes and is the provider's to refuse. */
@@ -1488,13 +1516,23 @@ const resultObject = (spec, values, result) => {
1488
1516
  throw new FieldworkError("ProviderError", `${spec.name} got a result that is not an object`);
1489
1517
  };
1490
1518
  /** The JSON Schema advertised for the tool's input: closed to other keys, requiring what `needs` says. */
1491
- const inputSchema = (fields, provider) => ({
1492
- additionalProperties: false,
1493
- properties: Object.fromEntries(fields.map((field) => [field.name, { ...field.schema }])),
1494
- required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1495
- type: "object"
1496
- });
1497
- const toolFor = (spec, provider, operation, budget) => {
1519
+ const inputSchema = (fields, provider, budget, limit) => {
1520
+ const schema = {
1521
+ additionalProperties: false,
1522
+ properties: Object.fromEntries([...fields.map((field) => [field.name, { ...field.schema }]), ["maxCharacters", { ...whole(`Shared long-text budget for this call; defaults to ${budget}. Never sent to the provider.`, 1, limit) }]]),
1523
+ required: fields.filter((field) => needs(field, provider)).map((field) => field.name),
1524
+ type: "object"
1525
+ };
1526
+ if (fields.some((field) => field.name === "contentBase64") && fields.some((field) => field.name === "url")) schema.oneOf = [{
1527
+ not: { anyOf: [{ required: ["name"] }, { required: ["contentBase64"] }] },
1528
+ required: ["url"]
1529
+ }, {
1530
+ not: { required: ["url"] },
1531
+ required: ["name", "contentBase64"]
1532
+ }];
1533
+ return schema;
1534
+ };
1535
+ const toolFor = (spec, provider, operation, budget, limit) => {
1498
1536
  const fields = spec.fields.filter((field) => offers(field, provider));
1499
1537
  return {
1500
1538
  annotations: {
@@ -1507,14 +1545,31 @@ const toolFor = (spec, provider, operation, budget) => {
1507
1545
  capability: spec.capability,
1508
1546
  description: spec.description,
1509
1547
  execute: async (input, call = {}) => {
1510
- const values = readInput(spec.name, provider, fields, input);
1511
- const result = await operation(...argumentsFor(spec, values, call));
1512
- return forModel(resultObject(spec, values, result), budget);
1548
+ if (!isJsonObject(input)) throw invalid(spec.name, provider, "input must be an object");
1549
+ const { maxCharacters, ...args } = input;
1550
+ const values = readInput(spec.name, provider, fields, args);
1551
+ const callBudget = maxCharacters === void 0 ? budget : checkMaxCharacters(maxCharacters, limit);
1552
+ const result = await operation(...argumentsFor(spec, values, call, provider));
1553
+ return forModel(resultObject(spec, values, result), callBudget);
1513
1554
  },
1514
- inputSchema: inputSchema(fields, provider),
1555
+ inputSchema: inputSchema(fields, provider, budget, limit),
1515
1556
  method: spec.method,
1516
1557
  name: spec.name,
1517
- outputSchema: { ...spec.output },
1558
+ outputSchema: {
1559
+ ...spec.output,
1560
+ properties: {
1561
+ ...spec.output.properties,
1562
+ truncated: list(object({
1563
+ length: whole("Original character length.", 0),
1564
+ path: str,
1565
+ shown: whole("Characters shown before the inline cut note.", 0)
1566
+ }, [
1567
+ "path",
1568
+ "shown",
1569
+ "length"
1570
+ ]), "One entry for each cut text field; absent when nothing was cut.")
1571
+ }
1572
+ },
1518
1573
  provider
1519
1574
  };
1520
1575
  };
@@ -1525,12 +1580,13 @@ const toolFor = (spec, provider, operation, budget) => {
1525
1580
  */
1526
1581
  const toolsFor = (web, options = {}) => {
1527
1582
  const wanted = /* @__PURE__ */ new Set([...options.capabilities ?? CAPABILITIES.filter((capability) => !EXCLUDED_BY_DEFAULT.includes(capability)), ...options.allow ?? []]);
1528
- const budget = options.maxCharacters ?? 2e4;
1583
+ const limit = options.maxCharactersLimit === void 0 ? void 0 : checkMaxCharacters(options.maxCharactersLimit);
1584
+ const budget = checkMaxCharacters(options.maxCharacters ?? 2e4, limit);
1529
1585
  const dispatcher = web;
1530
1586
  return SPECS.flatMap((spec) => {
1531
1587
  const provider = web.providerFor(spec.capability);
1532
1588
  const operation = operationFor(dispatcher, spec);
1533
- return wanted.has(spec.capability) && provider !== void 0 && operation !== void 0 ? [toolFor(spec, provider, operation, budget)] : [];
1589
+ return wanted.has(spec.capability) && provider !== void 0 && operation !== void 0 ? [toolFor(spec, provider, operation, budget, limit)] : [];
1534
1590
  });
1535
1591
  };
1536
1592
  /**
@@ -1548,4 +1604,4 @@ const toolError = (cause) => {
1548
1604
  retryable: false
1549
1605
  };
1550
1606
  };
1551
- export { EXCLUDED_BY_DEFAULT, toolError, toolsFor };
1607
+ export { DEFAULT_MAX_CHARACTERS, EXCLUDED_BY_DEFAULT, checkMaxCharacters, toolError, toolsFor };