llm-large-files 0.7.0 → 0.8.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/CHANGELOG.md +319 -1
- package/README.md +10 -8
- package/dist/analyze.d.ts +3 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +109 -14
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +4 -1
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +3 -3
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +72 -17
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +65 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +6 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +5 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +6 -0
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +7 -20
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +49 -751
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +9 -5
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +20 -3
- package/dist/gemini/generate.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +48 -12
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +8 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +69 -15
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +15 -1
- package/dist/openai/adapter.js.map +1 -1
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +2 -6
- package/dist/pdf-pages.js.map +1 -1
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +1 -1
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +99 -22
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +744 -140
- package/dist/search.js.map +1 -1
- package/dist/text-index.d.ts +3 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +3 -1
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +27 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +225 -23
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +200 -12
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/docs/README.md +8 -8
- package/docs/getting-started.md +1 -1
- package/docs/guides/costs-and-limits.md +7 -5
- package/docs/guides/deployment.md +95 -29
- package/docs/guides/errors-and-reliability.md +23 -10
- package/docs/guides/pdfs.md +127 -74
- package/docs/guides/storage.md +1 -1
- package/docs/guides/testing.md +5 -1
- package/docs/guides/web-app.md +10 -9
- package/docs/how-it-works.md +73 -50
- package/docs/reference/ask.md +26 -8
- package/docs/reference/errors-and-retries.md +5 -3
- package/docs/reference/events.md +14 -6
- package/docs/reference/gemini.md +6 -2
- package/docs/reference/library.md +205 -74
- package/docs/reference/node.md +200 -22
- package/docs/reference/openai.md +1 -1
- package/docs/reference/tools.md +170 -22
- package/docs/security.md +114 -69
- package/docs/troubleshooting.md +40 -20
- package/package.json +6 -2
- package/src/analyze.ts +117 -13
- package/src/anthropic/adapter.ts +4 -1
- package/src/ask.ts +73 -17
- package/src/decode.ts +89 -0
- package/src/errors.ts +108 -0
- package/src/events.ts +10 -1
- package/src/evidence.ts +6 -0
- package/src/extract.ts +52 -709
- package/src/gemini/adapter.ts +9 -5
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/generate.ts +19 -3
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/index.ts +2 -1
- package/src/library.ts +43 -12
- package/src/limiter.ts +6 -1
- package/src/model.ts +8 -1
- package/src/node/handlers.ts +66 -16
- package/src/node/index.ts +2 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +14 -1
- package/src/pdf-pages.ts +2 -5
- package/src/peers.ts +29 -0
- package/src/plan.ts +2 -0
- package/src/ranged.ts +4 -2
- package/src/search.ts +738 -146
- package/src/text-index.ts +4 -2
- package/src/text.ts +214 -23
- package/src/tools.ts +192 -12
- package/src/types.ts +3 -3
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
package/src/tools.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { safeErrorMessage } from "./errors.js";
|
|
2
|
+
import { GROUP_BY_VALUES, MAX_GROUP_KEYS, type GroupBy, type GroupResult } from "./groups.js";
|
|
2
3
|
import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
|
|
3
4
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
4
5
|
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource, type LineMatch } from "./search.js";
|
|
@@ -8,6 +9,12 @@ import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
|
|
|
8
9
|
import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
9
10
|
|
|
10
11
|
const DEFAULT_READ_LINES = 200;
|
|
12
|
+
/** Matching lines an exact or regex search shows: the default, and the most a call may ask for. */
|
|
13
|
+
const DEFAULT_GREP_RESULTS = 20;
|
|
14
|
+
const MAX_GREP_RESULTS = 50;
|
|
15
|
+
/** Groups a search with `group_by` shows: the default, and the most a call may ask for. */
|
|
16
|
+
const DEFAULT_GROUPS = 50;
|
|
17
|
+
const MAX_GROUPS = 200;
|
|
11
18
|
const MAX_READ_LINES = 600;
|
|
12
19
|
/** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
|
|
13
20
|
export const MAX_VIEW_PAGES = 5;
|
|
@@ -42,16 +49,21 @@ const documentId = { type: "string" as const, description: "The document_id from
|
|
|
42
49
|
const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
43
50
|
search: {
|
|
44
51
|
name: TOOL_NAMES.search,
|
|
45
|
-
description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\" finds the lines that contain the text; \"regex\" finds the lines that match a JavaScript regular expression. For exact and regex, total_matching_lines counts every matching line, and the result shows the first max_results of them and the last one. Results include line numbers to read further with read_document.",
|
|
52
|
+
description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\" finds the lines that contain the text; \"regex\" finds the lines that match a JavaScript regular expression (\\w and \\b know the letters of every language). For exact and regex, total_matching_lines counts every matching line, and the result shows the first max_results of them and the last one; search again from next_from_line for the ones after those shown, or with order \"last\" for the last ones. To count by group (per hour or day, per error code, per message shape), pass group_by: the result then counts each group, and shows no lines. from_line and to_line search part of the file. Results include line numbers to read further with read_document.",
|
|
46
53
|
parameters: {
|
|
47
54
|
type: "object",
|
|
48
55
|
properties: {
|
|
49
56
|
document_id: documentId,
|
|
50
57
|
query: { type: "string", description: "Keywords, exact text, or a regex, depending on mode." },
|
|
51
58
|
mode: { type: "string", enum: ["keywords", "exact", "regex"], description: "Defaults to keywords." },
|
|
52
|
-
max_results: { type: "integer", description:
|
|
59
|
+
max_results: { type: "integer", description: `Up to ${MAX_GREP_RESULTS} for exact/regex (default ${DEFAULT_GREP_RESULTS}), up to ${MAX_GROUPS} groups with group_by (default ${DEFAULT_GROUPS}), up to 10 passages for keywords (default 5).` },
|
|
53
60
|
context_lines: { type: "integer", description: "exact/regex only: lines to show before and after each match, 0-5." },
|
|
54
61
|
case_sensitive: { type: "boolean", description: "exact/regex only. Defaults to false." },
|
|
62
|
+
from_line: { type: "integer", description: "Search only from this line on (1-based). Pass a result's next_from_line to see the matches after those it shows." },
|
|
63
|
+
to_line: { type: "integer", description: "Search only up to this line." },
|
|
64
|
+
order: { type: "string", enum: ["first", "last"], description: "exact/regex only: \"last\" shows the last max_results matching lines (in file order) instead of the first. Defaults to \"first\"." },
|
|
65
|
+
group_by: { type: "string", enum: [...GROUP_BY_VALUES], description: "exact/regex only: count the matching lines by group instead of showing them. \"capture\": by the text of the regex's first (group); \"minute\", \"hour\", \"day\": by the timestamp on the line; \"shape\": by the line with its numbers, IDs and quoted values taken out." },
|
|
66
|
+
whole_word: { type: "boolean", description: "exact only: match the text only as a whole word, not inside a longer one. Defaults to false." },
|
|
55
67
|
},
|
|
56
68
|
required: ["document_id", "query"],
|
|
57
69
|
},
|
|
@@ -110,6 +122,16 @@ function integer(value: unknown, fallback: number, min: number, max: number): nu
|
|
|
110
122
|
return Math.min(max, Math.max(min, Math.trunc(Number.isFinite(number) ? number : fallback)));
|
|
111
123
|
}
|
|
112
124
|
|
|
125
|
+
/**
|
|
126
|
+
* A boolean given by the model: on for `true`, and for "true" (in any case) or 1, as a number or as
|
|
127
|
+
* text. A model sometimes sends a boolean as text, as it does numbers; read as off, "true" gave
|
|
128
|
+
* another search than true without a word about it. Anything else is off.
|
|
129
|
+
*/
|
|
130
|
+
function flag(value: unknown): boolean {
|
|
131
|
+
if (value === true || value === 1) return true;
|
|
132
|
+
return typeof value === "string" && /^\s*(?:true|1)\s*$/i.test(value);
|
|
133
|
+
}
|
|
134
|
+
|
|
113
135
|
const INCOMPLETE_ANALYSIS = "Incomplete: the model's output limit was reached, so some relevant items are missing from this answer. Tell the user it is incomplete. For a complete list or an exact count, use search_document in exact or regex mode (it returns total_matching_lines), or ask about a narrower part of the file.";
|
|
114
136
|
|
|
115
137
|
function text(value: unknown, name: string): string {
|
|
@@ -185,12 +207,16 @@ export function fitAnswer(result: ToolResult, limit: number): ToolResult {
|
|
|
185
207
|
function firstAndLastMatches(base: ToolResult, first: LineMatch[], last: LineMatch, total: number, limit: number): ToolResult {
|
|
186
208
|
const which = (kept: number) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
|
|
187
209
|
const shown = (kept: number) => `${kept + 1} of the ${total} matching lines`;
|
|
210
|
+
// Where a search for the ones in between goes on: after the last of the first ones shown.
|
|
211
|
+
const next = (kept: number) => (kept > 0 ? first[kept - 1]!.line + 1 : undefined);
|
|
212
|
+
const between = (kept: number) => (next(kept) !== undefined ? `To see the ones in between, search again with from_line ${next(kept)}, or count them with group_by.` : "Narrow the query or read specific lines.");
|
|
188
213
|
const withFirst = (kept: number, cut: boolean): ToolResult => ({
|
|
189
214
|
...base,
|
|
190
215
|
...(cut
|
|
191
|
-
? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}.
|
|
216
|
+
? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. ${between(kept)}` }
|
|
192
217
|
// When every match is shown, there is nothing to say.
|
|
193
|
-
: kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}.
|
|
218
|
+
: kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. ${between(kept)}` } : {}),
|
|
219
|
+
...(kept + 1 < total && next(kept) !== undefined ? { next_from_line: next(kept) } : {}),
|
|
194
220
|
matches: [...first.slice(0, kept), last],
|
|
195
221
|
});
|
|
196
222
|
const whole = withFirst(first.length, false);
|
|
@@ -207,8 +233,114 @@ function firstAndLastMatches(base: ToolResult, first: LineMatch[], last: LineMat
|
|
|
207
233
|
return fit(lastOnly, null, limit);
|
|
208
234
|
}
|
|
209
235
|
|
|
236
|
+
/**
|
|
237
|
+
* The result of a search with `order: "last"`: the last matching lines, in the order of the file,
|
|
238
|
+
* with a note that says so, and on which line the first match is. To fit `limit`, the earliest of
|
|
239
|
+
* them are dropped first: the very last stays. `stopped` is given when the scan stopped early: the
|
|
240
|
+
* last line of the lines searched, and the `to_line` of the call, which a search for the lines after
|
|
241
|
+
* those it found keeps.
|
|
242
|
+
*/
|
|
243
|
+
function lastMatches(base: ToolResult, first: LineMatch | undefined, last: LineMatch[], total: number, limit: number, stopped?: { end: number; toLine?: number }): ToolResult {
|
|
244
|
+
const build = (kept: number, cut: boolean): ToolResult => {
|
|
245
|
+
const shown = last.slice(last.length - kept);
|
|
246
|
+
const end = shown.at(-1)?.line;
|
|
247
|
+
// A scan that stopped early found these last: the lines after them were not all looked at. Its
|
|
248
|
+
// note starts as those of the other searches that stopped early do, which `alreadyShown` looks
|
|
249
|
+
// for: a later question has time of its own, and the call made then is run, not pointed back to.
|
|
250
|
+
if (stopped) {
|
|
251
|
+
// Nothing found means out of time (an exact search stops only past its limit on matches). It
|
|
252
|
+
// is not known where the scan stopped, so no line is named to search from.
|
|
253
|
+
if (end === undefined) {
|
|
254
|
+
return { ...base, note: "The scan stopped early, out of time, before it found a matching line: the lines it did not reach may have some. Try a simpler pattern, mode \"exact\", or fewer lines with from_line and to_line.", matches: shown };
|
|
255
|
+
}
|
|
256
|
+
const lines = `${shown.length} ${plural(shown.length, "matching line")}`;
|
|
257
|
+
const which = cut ? `Showing the last ${lines} it found to stay within the size limit` : `These are the last ${lines} it found`;
|
|
258
|
+
// The search goes on after the last line found, in the same range. When that line is the last
|
|
259
|
+
// of the range, the scan stopped there and missed none of it: there is nothing to search on.
|
|
260
|
+
const later = end < stopped.end
|
|
261
|
+
? ` There may be later ones, after line ${end}: search again with from_line ${end + 1}${stopped.toLine !== undefined ? ` and to_line ${stopped.toLine}` : ""}.`
|
|
262
|
+
: "";
|
|
263
|
+
return { ...base, note: `The scan stopped early; the total is a lower bound. ${which}, in the order of the file.${later}`, matches: shown };
|
|
264
|
+
}
|
|
265
|
+
const note = shown.length < total
|
|
266
|
+
// A cut result's note starts with "Showing ", as `alreadyShown` looks for: a call made later may have more room.
|
|
267
|
+
? cut
|
|
268
|
+
? `Showing the last ${shown.length} of the ${total} matching lines to stay within the size limit, in the order of the file: the last match is on line ${end}${first ? `, and the first on line ${first.line}` : ""}. Narrow the query or read specific lines.`
|
|
269
|
+
: `These are the last ${shown.length} of the ${total} matching lines, in the order of the file: the last match is on line ${end}${first ? `, and the first on line ${first.line}` : ""}.`
|
|
270
|
+
: undefined;
|
|
271
|
+
return { ...base, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), matches: shown };
|
|
272
|
+
};
|
|
273
|
+
const whole = build(last.length, false);
|
|
274
|
+
if (JSON.stringify(whole).length <= limit) return whole;
|
|
275
|
+
let kept = last.length;
|
|
276
|
+
while (kept > 1 && JSON.stringify(build(kept, true)).length > limit) kept--;
|
|
277
|
+
return fit(build(kept, true), null, limit);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** The result of a search with `group_by`: the total, then up to `shown` groups, cut further to fit `limit`. */
|
|
281
|
+
function groupedResult(base: ToolResult, counted: GroupResult, shown: number, limit: number): ToolResult {
|
|
282
|
+
const byTime = base.group_by === "minute" || base.group_by === "hour" || base.group_by === "day";
|
|
283
|
+
const all = counted.groups.map(({ key, count, firstLine, lastLine }) => ({ key, count, first_line: firstLine, last_line: lastLine }));
|
|
284
|
+
// By time, the groups shown are the largest, put back in time order; so are those kept when the
|
|
285
|
+
// result is cut to its room. Cutting the end of the list there kept the earliest groups, while the
|
|
286
|
+
// note said the largest, and a model named the wrong hour as the busiest. The sort is stable: of
|
|
287
|
+
// groups of the same size, the earlier comes first.
|
|
288
|
+
const largest = byTime ? [...all].sort((left, right) => right.count - left.count) : all;
|
|
289
|
+
const pick = (kept: number) => (byTime ? largest.slice(0, kept).sort((left, right) => left.first_line - right.first_line) : all.slice(0, kept));
|
|
290
|
+
const most = Math.min(shown, all.length);
|
|
291
|
+
const extra = {
|
|
292
|
+
total_groups: counted.totalGroups,
|
|
293
|
+
...(counted.otherCount > 0 ? { other_count: counted.otherCount, other_note: `Lines of groups past the first ${MAX_GROUP_KEYS.toLocaleString("en-US")} found.` } : {}),
|
|
294
|
+
...(counted.ungrouped > 0 ? { lines_without_group: counted.ungrouped } : {}),
|
|
295
|
+
};
|
|
296
|
+
const build = (kept: number, cut: boolean): ToolResult => {
|
|
297
|
+
const groups = pick(kept);
|
|
298
|
+
const order = byTime ? (groups.length < all.length ? "the largest, in time order" : "in time order") : "the largest first";
|
|
299
|
+
const note = groups.length < counted.totalGroups ? `${cut ? "Showing " : ""}${groups.length} of the ${counted.totalGroups} groups${cut ? " to stay within the size limit" : " are shown"}, ${order}. Narrow the search, or use from_line and to_line, for the others.` : undefined;
|
|
300
|
+
return { ...base, ...extra, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), groups };
|
|
301
|
+
};
|
|
302
|
+
const whole = build(most, false);
|
|
303
|
+
if (JSON.stringify(whole).length <= limit) return whole;
|
|
304
|
+
let kept = most;
|
|
305
|
+
while (kept > 1 && JSON.stringify(build(kept, true)).length > limit) kept--;
|
|
306
|
+
return fit(build(kept, true), null, limit);
|
|
307
|
+
}
|
|
308
|
+
|
|
210
309
|
const searchMode = (mode: unknown): "keywords" | "exact" | "regex" => (mode === "exact" || mode === "regex" ? mode : "keywords");
|
|
211
310
|
|
|
311
|
+
/** `group_by` as the search reads it: undefined when not given. A value it does not know is an error. */
|
|
312
|
+
function groupByOf(value: unknown): GroupBy | undefined {
|
|
313
|
+
if (value === undefined || value === null || value === "" || value === "none") return undefined;
|
|
314
|
+
if (typeof value === "string" && (GROUP_BY_VALUES as readonly string[]).includes(value)) return value as GroupBy;
|
|
315
|
+
throw new Error(`group_by must be one of ${GROUP_BY_VALUES.map((name) => `"${name}"`).join(", ")}.`);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** A line number of a search's range, as the search reads it: undefined when not given. */
|
|
319
|
+
const rangeLine = (value: unknown): number | undefined => (value === undefined || value === null || value === "" ? undefined : integer(value, 1, 1, Number.MAX_SAFE_INTEGER));
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* The arguments of a search that choose which lines it looks at and how it shows them, as the
|
|
323
|
+
* search reads them. The search, its key and its label all read them here, so that they agree.
|
|
324
|
+
*/
|
|
325
|
+
function searchScope(args: Record<string, unknown>): { fromLine?: number; toLine?: number; order: "first" | "last"; groupBy?: GroupBy; wholeWord: boolean; caseSensitive: boolean } {
|
|
326
|
+
const fromLine = rangeLine(args.from_line);
|
|
327
|
+
const toLine = rangeLine(args.to_line);
|
|
328
|
+
let groupBy: GroupBy | undefined;
|
|
329
|
+
try {
|
|
330
|
+
groupBy = groupByOf(args.group_by);
|
|
331
|
+
} catch {
|
|
332
|
+
groupBy = undefined;
|
|
333
|
+
}
|
|
334
|
+
return {
|
|
335
|
+
...(fromLine !== undefined ? { fromLine } : {}),
|
|
336
|
+
...(toLine !== undefined ? { toLine } : {}),
|
|
337
|
+
order: args.order === "last" ? "last" : "first",
|
|
338
|
+
...(groupBy ? { groupBy } : {}),
|
|
339
|
+
wholeWord: flag(args.whole_word),
|
|
340
|
+
caseSensitive: flag(args.case_sensitive),
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
212
344
|
/** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
|
|
213
345
|
function requestedLines(args: Record<string, unknown>): [number, number] {
|
|
214
346
|
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
@@ -226,9 +358,21 @@ export function toolCallKey(name: string, args: Record<string, unknown>): string
|
|
|
226
358
|
if (name === TOOL_NAMES.search) {
|
|
227
359
|
if (typeof args.query !== "string" || !args.query.trim()) return undefined;
|
|
228
360
|
const mode = searchMode(args.mode);
|
|
361
|
+
// A group_by the search refuses: the call answers with an error, and is not compared.
|
|
362
|
+
try {
|
|
363
|
+
groupByOf(args.group_by);
|
|
364
|
+
} catch {
|
|
365
|
+
return undefined;
|
|
366
|
+
}
|
|
367
|
+
const { fromLine, toLine, order, groupBy, wholeWord, caseSensitive } = searchScope(args);
|
|
368
|
+
// The arguments of 0.8.0 are added only when given: a call without them has the key it had.
|
|
369
|
+
const scope = [
|
|
370
|
+
...(fromLine !== undefined || toLine !== undefined ? [fromLine ?? 1, toLine ?? null] : []),
|
|
371
|
+
...(mode !== "keywords" && (order === "last" || groupBy || wholeWord) ? [order, groupBy ?? null, mode === "exact" && wholeWord] : []),
|
|
372
|
+
];
|
|
229
373
|
return JSON.stringify(mode === "keywords"
|
|
230
|
-
? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10)]
|
|
231
|
-
: [name, id, args.query, mode, integer(args.max_results,
|
|
374
|
+
? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10), ...scope]
|
|
375
|
+
: [name, id, args.query, mode, groupBy ? integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS) : integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS), groupBy ? 0 : integer(args.context_lines, 0, 0, 5), caseSensitive, ...scope]);
|
|
232
376
|
}
|
|
233
377
|
if (name === TOOL_NAMES.read) return JSON.stringify([name, id, ...requestedLines(args)]);
|
|
234
378
|
if (name === TOOL_NAMES.overview) return JSON.stringify([name, id]);
|
|
@@ -248,6 +392,9 @@ export function alreadyShown(call: { name: string; args: Record<string, unknown>
|
|
|
248
392
|
const { result } = earlier;
|
|
249
393
|
if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id) return undefined;
|
|
250
394
|
if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true) return undefined;
|
|
395
|
+
// A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
|
|
396
|
+
// those as off, 0.8.0 as on, so the call made now would not return what was stored.
|
|
397
|
+
if (stored && call.name === TOOL_NAMES.search && [earlier.call.args.case_sensitive, earlier.call.args.whole_word].some((value) => value !== undefined && value !== true && value !== false && flag(value))) return undefined;
|
|
251
398
|
// A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
|
|
252
399
|
// time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
|
|
253
400
|
if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early"))) return undefined;
|
|
@@ -309,7 +456,8 @@ export function failureKind(call: { name: string; args: Record<string, unknown>
|
|
|
309
456
|
export function toolResultSummary(label: string, result: ToolResult): string {
|
|
310
457
|
if (typeof result.error === "string") return ` — failed: ${result.error}`;
|
|
311
458
|
if (typeof result.total_matching_lines === "number") {
|
|
312
|
-
|
|
459
|
+
const groups = typeof result.total_groups === "number" ? ` in ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
|
|
460
|
+
return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}${groups}`;
|
|
313
461
|
}
|
|
314
462
|
if (Array.isArray(result.passages)) return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
|
|
315
463
|
if (typeof result.parts_read === "number") {
|
|
@@ -410,6 +558,12 @@ export function createDocumentTools(options: {
|
|
|
410
558
|
regexQueue = next.catch(() => undefined);
|
|
411
559
|
return next;
|
|
412
560
|
};
|
|
561
|
+
const givenReads: unknown = options.maxWholeDocumentReads;
|
|
562
|
+
// NaN failed every comparison, so it let a document be read whole any number of times.
|
|
563
|
+
if (givenReads !== undefined && (typeof givenReads !== "number" || Number.isNaN(givenReads))) {
|
|
564
|
+
const shown = typeof givenReads === "number" ? String(givenReads) : typeof givenReads === "string" ? JSON.stringify(givenReads) : typeof givenReads;
|
|
565
|
+
throw new (typeof givenReads === "number" ? RangeError : TypeError)(`maxWholeDocumentReads must be a number, and is ${shown}.`);
|
|
566
|
+
}
|
|
413
567
|
const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
|
|
414
568
|
/** Whole-document reads started, by document. */
|
|
415
569
|
const wholeReads = new Map<string, number>();
|
|
@@ -443,13 +597,24 @@ export function createDocumentTools(options: {
|
|
|
443
597
|
// Page numbers are added only for a PDF whose pages can be looked at: they are what
|
|
444
598
|
// view_pages takes. Everything else gets the results of 0.2.0 unchanged.
|
|
445
599
|
const paged = viewable.has(document.meta.id);
|
|
600
|
+
const groupBy = groupByOf(args.group_by);
|
|
601
|
+
const { fromLine, toLine, order, wholeWord, caseSensitive } = searchScope(args);
|
|
602
|
+
const total = document.lineCount;
|
|
603
|
+
if (fromLine !== undefined && fromLine > total) throw new Error(`from_line ${fromLine} is past the end of the file, which has ${total} ${plural(total, "line")}.`);
|
|
604
|
+
if (toLine !== undefined && toLine < (fromLine ?? 1)) throw new Error(`to_line ${toLine} is before from_line ${fromLine ?? 1}.`);
|
|
605
|
+
const ranged = fromLine !== undefined || toLine !== undefined;
|
|
606
|
+
const range = { from: fromLine ?? 1, to: Math.min(total, toLine ?? total) };
|
|
607
|
+
// Said in the result when part of the file was searched: the counts are of those lines.
|
|
608
|
+
const searched = ranged ? { searched_lines: `${range.from}-${range.to}` } : {};
|
|
446
609
|
if (mode === "keywords") {
|
|
610
|
+
if (groupBy) throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
|
|
447
611
|
const topK = integer(args.max_results, 5, 1, 10);
|
|
448
|
-
const ranked = await rankSource(document, query, topK, options.signal);
|
|
612
|
+
const ranked = await rankSource(document, query, topK, options.signal, ranged ? range : undefined);
|
|
449
613
|
const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
|
|
450
614
|
return fit({
|
|
451
615
|
document: document.meta.name,
|
|
452
616
|
mode,
|
|
617
|
+
...searched,
|
|
453
618
|
passages: ranked.map((passage, index) => {
|
|
454
619
|
const pages = paged ? document.pagesOfLines(passage.from, passage.to) : undefined;
|
|
455
620
|
return {
|
|
@@ -463,6 +628,7 @@ export function createDocumentTools(options: {
|
|
|
463
628
|
}, "passages", limit);
|
|
464
629
|
}
|
|
465
630
|
const regex = mode === "regex";
|
|
631
|
+
const shownGroups = integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS);
|
|
466
632
|
const grep = async () => {
|
|
467
633
|
const regexLeft = regexBudget - regexClock.usedMs;
|
|
468
634
|
if (regex && regexLeft <= 0) {
|
|
@@ -470,11 +636,15 @@ export function createDocumentTools(options: {
|
|
|
470
636
|
}
|
|
471
637
|
return grepSource(document, query, {
|
|
472
638
|
regex,
|
|
473
|
-
caseSensitive
|
|
474
|
-
maxResults: integer(args.max_results,
|
|
639
|
+
caseSensitive,
|
|
640
|
+
maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
|
|
475
641
|
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
476
642
|
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
477
643
|
...(options.signal ? { signal: options.signal } : {}),
|
|
644
|
+
...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
|
|
645
|
+
...(order === "last" ? { order } : {}),
|
|
646
|
+
...(groupBy ? { groupBy } : {}),
|
|
647
|
+
...(wholeWord && !regex ? { wholeWord } : {}),
|
|
478
648
|
});
|
|
479
649
|
};
|
|
480
650
|
const result = await (regex ? inRegexTurn(grep) : grep());
|
|
@@ -484,8 +654,15 @@ export function createDocumentTools(options: {
|
|
|
484
654
|
const page = document.pageOfLine(line);
|
|
485
655
|
return { line, ...(page ? { page } : {}), ...rest };
|
|
486
656
|
};
|
|
487
|
-
const base = { document: document.meta.name, mode, total_matching_lines: result.totalMatchingLines };
|
|
657
|
+
const base = { document: document.meta.name, mode, ...searched, total_matching_lines: result.totalMatchingLines };
|
|
658
|
+
const stopped = result.stoppedEarly ? { note: "The scan stopped early; the counts are lower bounds." } : {};
|
|
659
|
+
if (result.groups) return groupedResult({ ...base, group_by: groupBy!, ...stopped }, result.groups, shownGroups, limit);
|
|
488
660
|
const matches = result.matches.map(placed);
|
|
661
|
+
if (order === "last") {
|
|
662
|
+
// The range a search for the lines after those found goes on in, when the scan stopped early.
|
|
663
|
+
const rest = result.stoppedEarly ? { end: range.to, ...(toLine !== undefined ? { toLine: range.to } : {}) } : undefined;
|
|
664
|
+
return lastMatches({ ...base, order }, result.first ? placed(result.first) : undefined, matches, result.totalMatchingLines, limit, rest);
|
|
665
|
+
}
|
|
489
666
|
if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
|
|
490
667
|
// The last match is `last`, or, when every match is among the first ones, the last of them.
|
|
491
668
|
return result.last
|
|
@@ -707,7 +884,10 @@ export function createDocumentTools(options: {
|
|
|
707
884
|
}
|
|
708
885
|
if (name === TOOL_NAMES.search) {
|
|
709
886
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
710
|
-
|
|
887
|
+
const { fromLine, toLine, order, groupBy } = searchScope(args);
|
|
888
|
+
const where = fromLine !== undefined || toLine !== undefined ? ` in lines ${fromLine ?? 1}-${toLine ?? "end"}` : "";
|
|
889
|
+
const how = mode === "keywords" ? "" : groupBy ? `, counted by ${groupBy}` : order === "last" ? ", the last ones" : "";
|
|
890
|
+
return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”${where}${how}`;
|
|
711
891
|
}
|
|
712
892
|
if (name === TOOL_NAMES.read) {
|
|
713
893
|
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
package/src/types.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Public types. Everything a consumer touches is defined here, so the package can be
|
|
2
2
|
// published without exposing internal module layout.
|
|
3
3
|
|
|
4
|
-
export type DocumentFormat = "text" | "markdown" | "log" | "json" | "csv" | "pdf" | "docx" | "pptx";
|
|
4
|
+
export type DocumentFormat = "text" | "markdown" | "log" | "json" | "csv" | "pdf" | "docx" | "pptx" | "xlsx" | "html";
|
|
5
5
|
|
|
6
6
|
export type OutlineEntry = {
|
|
7
7
|
/** 1-based line number in the extracted text. */
|
|
@@ -235,8 +235,8 @@ export type ToolOutput = { result: ToolResult; files: ToolFile[] };
|
|
|
235
235
|
export type ToolCallLimits = {
|
|
236
236
|
/**
|
|
237
237
|
* The most bytes the files of this call may have together. Give the room left in your request,
|
|
238
|
-
* times 3/4 when files are sent as base64. Defaults to 3/8 of `maxRequestBytes`
|
|
239
|
-
*
|
|
238
|
+
* times 3/4 when files are sent as base64. Defaults to 3/8 of (`maxRequestBytes` − 262,144), the
|
|
239
|
+
* 256 KB the library keeps free in a request taken off first: 3,651,696 bytes for the default budget.
|
|
240
240
|
*/
|
|
241
241
|
maxFileBytes?: number;
|
|
242
242
|
/** The most pages this call may show. Lower it as the pages already shown use up your token budget. */
|