llm-large-files 0.7.0 → 0.8.1
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 +370 -1
- package/README.md +12 -8
- package/dist/aggregate.d.ts +103 -0
- package/dist/aggregate.d.ts.map +1 -0
- package/dist/aggregate.js +651 -0
- package/dist/aggregate.js.map +1 -0
- 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 +23 -0
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +12 -18
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +82 -746
- 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 +57 -14
- 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 +3 -1
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +17 -1
- package/dist/plan.js.map +1 -1
- package/dist/quality.d.ts +16 -0
- package/dist/quality.d.ts.map +1 -0
- package/dist/quality.js +157 -0
- package/dist/quality.js.map +1 -0
- 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 +9 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +457 -16
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +23 -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 +80 -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 +221 -79
- package/docs/reference/node.md +201 -23
- package/docs/reference/openai.md +1 -1
- package/docs/reference/tools.md +269 -23
- package/docs/security.md +114 -69
- package/docs/troubleshooting.md +40 -20
- package/package.json +6 -2
- package/src/aggregate.ts +674 -0
- 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 +23 -0
- package/src/extract.ts +79 -701
- 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 +52 -14
- 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 +19 -1
- package/src/quality.ts +146 -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 +440 -16
- package/src/types.ts +20 -3
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
package/src/analyze.ts
CHANGED
|
@@ -4,26 +4,85 @@ import type { DocumentFormat, LogIssue, LogProfile, OutlineEntry } from "./types
|
|
|
4
4
|
|
|
5
5
|
const MAX_OUTLINE_ENTRIES = 400;
|
|
6
6
|
const MAX_TEMPLATES = 50_000;
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Timestamps of logs: ISO 8601 (2026-11-10T14:03:17.120Z), nginx's error log (2026/11/10
|
|
9
|
+
* 14:03:17), the access logs of Apache and nginx (10/Nov/2026:14:03:17 +0000), and syslog (Nov 10
|
|
10
|
+
* 14:03:17).
|
|
11
|
+
*/
|
|
12
|
+
const TIMESTAMP = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?|\b\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}|\b\d{2}\/[A-Z][a-z]{2}\/\d{4}:\d{2}:\d{2}:\d{2}(?: [+-]\d{4})?|\b[A-Z][a-z]{2} {1,2}\d{1,2} \d{2}:\d{2}:\d{2}/;
|
|
13
|
+
const LINE_START_TIMESTAMP = /^\[?(?:\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}|\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}|\d{2}\/\d{2}\/\d{4}|\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}|\w{3} {1,2}\d{1,2} \d{2}:\d{2}:\d{2}|\d{2}:\d{2}:\d{2})/;
|
|
14
|
+
/** Other shapes of log lines: an access log, a JSON log, klog, logfmt. */
|
|
15
|
+
const LOG_LINE = /^(?:\d{1,3}(?:\.\d{1,3}){3} \S+ \S+ \[\d{2}\/\w{3}\/\d{4}:|\{.*"(?:level|severity|time|timestamp|ts|@timestamp)"\s*:|[IWEF]\d{4} \d{2}:\d{2}:\d{2}|(?:time|ts|level|lvl)=)/;
|
|
16
|
+
/** A level word in upper case, anywhere on the line. */
|
|
9
17
|
const LEVEL = /\b(FATAL|CRITICAL|ERROR|ERR|WARN|WARNING|INFO|DEBUG|TRACE)\b/;
|
|
10
|
-
|
|
18
|
+
/**
|
|
19
|
+
* A level in lower or mixed case, where logs put one: in brackets as nginx and Apache do
|
|
20
|
+
* ("[error]"), after `level=` as logfmt, zap and logrus do, or in a JSON field ("level":"warn").
|
|
21
|
+
*/
|
|
22
|
+
const MARKED_LEVEL = /(?:\[|\b(?:level|lvl|severity)=\s*"?|"(?:level|severity)"\s*:\s*")(fatal|critical|crit|emerg|alert|error|err|warning|warn|notice|info|debug|trace)\b/i;
|
|
23
|
+
/** pino and bunyan write the level as a number. */
|
|
24
|
+
const NUMBER_LEVEL = /"level"\s*:\s*(10|20|30|40|50|60)\b/;
|
|
25
|
+
const NUMBER_LEVELS: Record<string, string> = { 10: "TRACE", 20: "DEBUG", 30: "INFO", 40: "WARN", 50: "ERROR", 60: "FATAL" };
|
|
26
|
+
/** klog and glog start a line with the level's letter, then the month and day. */
|
|
27
|
+
const LETTER_LEVEL = /^([IWEF])\d{4} \d{2}:\d{2}:\d{2}/;
|
|
28
|
+
const LETTER_LEVELS: Record<string, string> = { I: "INFO", W: "WARN", E: "ERROR", F: "FATAL" };
|
|
29
|
+
const LEVEL_NAMES: Record<string, string> = { ERR: "ERROR", WARNING: "WARN", CRITICAL: "FATAL", CRIT: "FATAL", EMERG: "FATAL", ALERT: "FATAL", NOTICE: "INFO" };
|
|
11
30
|
|
|
12
|
-
/**
|
|
31
|
+
/** The level of a log line, in upper case ("ERROR", "WARN"), or undefined. */
|
|
32
|
+
export function levelOf(line: string): string | undefined {
|
|
33
|
+
const raw = LEVEL.exec(line)?.[1]
|
|
34
|
+
?? MARKED_LEVEL.exec(line)?.[1]?.toUpperCase()
|
|
35
|
+
?? NUMBER_LEVELS[NUMBER_LEVEL.exec(line)?.[1] ?? ""]
|
|
36
|
+
?? LETTER_LEVELS[LETTER_LEVEL.exec(line)?.[1] ?? ""];
|
|
37
|
+
return raw === undefined ? undefined : LEVEL_NAMES[raw] ?? raw;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Treats text as a log when most early lines start with a timestamp or a level, or have the shape of a log line. */
|
|
13
41
|
export function looksLikeLog(lines: string[]): boolean {
|
|
14
42
|
const sample: string[] = [];
|
|
15
43
|
for (let index = 0; index < lines.length && sample.length < 200; index++) if (lines[index]!.trim()) sample.push(lines[index]!);
|
|
16
44
|
if (sample.length < 5) return false;
|
|
17
|
-
const hits = sample.filter((line) =>
|
|
45
|
+
const hits = sample.filter((line) => {
|
|
46
|
+
const trimmed = line.trim();
|
|
47
|
+
return LINE_START_TIMESTAMP.test(trimmed) || LOG_LINE.test(trimmed) || /^\[?(FATAL|ERROR|WARN|WARNING|INFO|DEBUG|TRACE)\b/i.test(trimmed);
|
|
48
|
+
}).length;
|
|
18
49
|
return hits / sample.length >= 0.4;
|
|
19
50
|
}
|
|
20
51
|
|
|
52
|
+
/** A line that opens or closes a fenced code block of Markdown: ``` or ~~~. */
|
|
53
|
+
const FENCE = /^\s{0,3}(`{3,}|~{3,})/;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Follows fenced code blocks line by line: a "# comment" in a block of shell or Python is not a
|
|
57
|
+
* heading. A fence closes with the same character, at least as long.
|
|
58
|
+
*/
|
|
59
|
+
class Fences {
|
|
60
|
+
private open: string | undefined;
|
|
61
|
+
|
|
62
|
+
/** Whether line `line` is inside a block, its fences included. */
|
|
63
|
+
inside(line: string): boolean {
|
|
64
|
+
const fence = FENCE.exec(line)?.[1];
|
|
65
|
+
if (this.open !== undefined) {
|
|
66
|
+
if (fence && fence[0] === this.open[0] && fence.length >= this.open.length && line.trim() === fence) this.open = undefined;
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
if (fence) {
|
|
70
|
+
this.open = fence;
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
21
77
|
/** Headings with line numbers: Markdown, slide/page markers, and common book and report patterns. */
|
|
22
78
|
export function buildOutline(lines: string[], format: DocumentFormat): OutlineEntry[] {
|
|
23
79
|
if (format === "log" || format === "json" || format === "csv") return [];
|
|
24
80
|
const entries: OutlineEntry[] = [];
|
|
81
|
+
const fences = new Fences();
|
|
82
|
+
const hashes = hashHeadings(lines, format);
|
|
25
83
|
for (let index = 0; index < lines.length; index++) {
|
|
26
|
-
|
|
84
|
+
if (fences.inside(lines[index] ?? "")) continue;
|
|
85
|
+
const entry = outlineEntry(lines, index, hashes);
|
|
27
86
|
if (entry) entries.push(entry);
|
|
28
87
|
}
|
|
29
88
|
return pickOutline(entries);
|
|
@@ -33,21 +92,67 @@ export function buildOutline(lines: string[], format: DocumentFormat): OutlineEn
|
|
|
33
92
|
export async function buildOutlineInSlices(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<OutlineEntry[]> {
|
|
34
93
|
if (format === "log" || format === "json" || format === "csv") return [];
|
|
35
94
|
const entries: OutlineEntry[] = [];
|
|
95
|
+
const fences = new Fences();
|
|
96
|
+
const hashes = hashHeadings(lines, format);
|
|
36
97
|
for (let index = 0; index < lines.length; index++) {
|
|
37
|
-
const entry = outlineEntry(lines, index);
|
|
38
|
-
if (entry) entries.push(entry);
|
|
39
98
|
if ((index & 4095) === 4095) await slicer.maybePause();
|
|
99
|
+
if (fences.inside(lines[index] ?? "")) continue;
|
|
100
|
+
const entry = outlineEntry(lines, index, hashes);
|
|
101
|
+
if (entry) entries.push(entry);
|
|
40
102
|
}
|
|
41
103
|
return pickOutline(entries);
|
|
42
104
|
}
|
|
43
105
|
|
|
106
|
+
/** Whether a line is a "# " line: a Markdown heading, or a comment of a script or a configuration file. */
|
|
107
|
+
const hashLine = (line: string | undefined) => /^\s*#{1,6}\s/.test(line ?? "");
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A line only code has: a shebang, an include, an import, a definition. One is enough. No two
|
|
111
|
+
* repeats in a row can match the same characters: `function\s*\w*\s*\(` split a run of spaces
|
|
112
|
+
* after "function" between its two `\s*` in as many ways as it is long, and a line of "function",
|
|
113
|
+
* 2,000 spaces and "x" took 20 ms; 300 of them held the server 8 seconds.
|
|
114
|
+
*/
|
|
115
|
+
const CODE_LINE = /^(?:#!\/|#include\b|import\s+[\w{*"']|from\s+[\w.]+\s+import\b|def\s+\w+\s*\(|class\s+\w+[\s:({]|function\s*(?:\w+\s*)?\(|package\s+[\w.]+;?\s*$|using\s+[\w.]+;\s*$)/;
|
|
116
|
+
/** A line common in code and configuration files, and rarer in prose: three are needed. */
|
|
117
|
+
const CODE_LIKE_LINE = /^(?:(?:const|let|var|export|public|private|return)\s|(?:if|for|while)\s*\(|echo\s|set\s+-\w|[A-Za-z_][\w.-]*\s*=\s*\S|[}\])];?$)/;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Whether a plain text file is a script, source code or a configuration file, where "# " starts
|
|
121
|
+
* a comment, not a heading: one of its first lines only code has, or three that code often has.
|
|
122
|
+
*/
|
|
123
|
+
function looksLikeCode(lines: string[]): boolean {
|
|
124
|
+
let likely = 0;
|
|
125
|
+
for (let index = 0; index < lines.length && index < 300; index++) {
|
|
126
|
+
// Trimmed first, and the end looked at apart: a regex over the leading spaces backtracked by their square.
|
|
127
|
+
const line = (lines[index] ?? "").trim();
|
|
128
|
+
if (CODE_LINE.test(line)) return true;
|
|
129
|
+
if ((CODE_LIKE_LINE.test(line) || line.endsWith("{") || line.endsWith(";")) && ++likely >= 3) return true;
|
|
130
|
+
}
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Which "# " lines are headings: all of them in Markdown and the other formats; in a plain text
|
|
136
|
+
* file, none when it reads as code ("strict" is false then), and otherwise only one after a blank
|
|
137
|
+
* line that is not followed by another "# " line, as comments come in blocks.
|
|
138
|
+
*/
|
|
139
|
+
type HashHeadings = "all" | "strict" | "none";
|
|
140
|
+
|
|
141
|
+
function hashHeadings(lines: string[], format: DocumentFormat): HashHeadings {
|
|
142
|
+
if (format !== "text") return "all";
|
|
143
|
+
return looksLikeCode(lines) ? "none" : "strict";
|
|
144
|
+
}
|
|
145
|
+
|
|
44
146
|
/** The heading on line `index` (0-based), if it is one. */
|
|
45
|
-
function outlineEntry(lines: string[], index: number): OutlineEntry | undefined {
|
|
147
|
+
function outlineEntry(lines: string[], index: number, hashes: HashHeadings = "all"): OutlineEntry | undefined {
|
|
46
148
|
const line = (lines[index] ?? "").trim();
|
|
47
149
|
if (!line || line.length > 120) return undefined;
|
|
48
150
|
const previousBlank = index === 0 || !(lines[index - 1] ?? "").trim();
|
|
49
151
|
const markdown = /^(#{1,6})\s+(.+)$/.exec(line);
|
|
50
|
-
if (markdown)
|
|
152
|
+
if (markdown) {
|
|
153
|
+
if (hashes === "none" || (hashes === "strict" && (!previousBlank || hashLine(lines[index + 1])))) return undefined;
|
|
154
|
+
return { line: index + 1, level: markdown[1]!.length, title: markdown[2]!.trim() };
|
|
155
|
+
}
|
|
51
156
|
// A lookahead, not \b: JavaScript's \b does not treat Hebrew letters as word characters.
|
|
52
157
|
if (/^(chapter|part|book|section|appendix|פרק|חלק|נספח)(?=[\s:.\d]|$)/iu.test(line) && previousBlank) {
|
|
53
158
|
return { line: index + 1, level: /^(part|book|חלק)(?=[\s:.\d]|$)/iu.test(line) ? 1 : 2, title: line };
|
|
@@ -122,9 +227,8 @@ class LogProfiler {
|
|
|
122
227
|
this.firstTimestamp ??= stamp;
|
|
123
228
|
this.lastTimestamp = stamp;
|
|
124
229
|
}
|
|
125
|
-
const
|
|
126
|
-
if (!
|
|
127
|
-
const level = LEVEL_NAMES[raw] ?? raw;
|
|
230
|
+
const level = levelOf(line);
|
|
231
|
+
if (!level) return;
|
|
128
232
|
this.levels[level] = (this.levels[level] ?? 0) + 1;
|
|
129
233
|
if (level !== "ERROR" && level !== "FATAL" && level !== "WARN") return;
|
|
130
234
|
const template = logTemplate(line);
|
package/src/anthropic/adapter.ts
CHANGED
|
@@ -559,7 +559,10 @@ export function anthropic(options: AnthropicOptions): ModelAdapter {
|
|
|
559
559
|
} else if (event.type === "message_delta") {
|
|
560
560
|
stopReason = event.delta?.stop_reason ?? stopReason;
|
|
561
561
|
stopDetails = (event.delta?.stop_details as Json | undefined) ?? stopDetails;
|
|
562
|
-
|
|
562
|
+
// Only the numbers it has: the input fields of message_delta may be null, and the real
|
|
563
|
+
// ones are message_start's (the official SDK keeps them the same way).
|
|
564
|
+
// (As own properties, whatever their names: no key of the provider's sets a prototype.)
|
|
565
|
+
usage = { ...usage, ...Object.fromEntries(Object.entries((event.usage ?? {}) as Json).filter(([, value]) => value !== null && value !== undefined)) };
|
|
563
566
|
}
|
|
564
567
|
}
|
|
565
568
|
} catch (error) {
|
package/src/ask.ts
CHANGED
|
@@ -42,14 +42,14 @@ import {
|
|
|
42
42
|
import type { Budget, DocumentMeta, DocumentPlan, GenerateText, ToolCallHooks, ToolCallLimits, ToolOutput, ToolRequestEnd, ToolRequestHandle, ToolRequestStart, ToolResult } from "./types.js";
|
|
43
43
|
|
|
44
44
|
/** Sent (invisibly to the user) when the model must stop using tools and answer. */
|
|
45
|
-
export const FINAL_ANSWER_REQUEST = "Stop using tools now. Answer my question using only what the tools returned above, with line citations. Say plainly what you could not find.";
|
|
45
|
+
export const FINAL_ANSWER_REQUEST = "Stop using tools now. Answer my question using only what the tools returned above, with line citations. Say plainly what you could not find. Answer in the language of my question.";
|
|
46
46
|
/** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
|
|
47
|
-
export const FINAL_ANSWER_AFTER_PAGES = "Stop using tools now. Answer my question from the text of the files and the pages you looked at. Say plainly what you could not see or find.";
|
|
47
|
+
export const FINAL_ANSWER_AFTER_PAGES = "Stop using tools now. Answer my question from the text of the files and the pages you looked at. Say plainly what you could not see or find. Answer in the language of my question.";
|
|
48
48
|
/**
|
|
49
49
|
* Sent when no tool ran (an explorer model called none, the first reply was empty, or no turn was
|
|
50
50
|
* left for tools), so there is no tool result to answer from.
|
|
51
51
|
*/
|
|
52
|
-
export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is in this conversation. No tools are available for this reply: if the answer needs a part of a file that is not shown here, say so plainly.";
|
|
52
|
+
export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is in this conversation. No tools are available for this reply: if the answer needs a part of a file that is not shown here, say so plainly. Answer in the language of my question.";
|
|
53
53
|
/**
|
|
54
54
|
* Added to the system instruction of an explorer model's requests: it gathers what the answer
|
|
55
55
|
* needs, and the other model writes the answer.
|
|
@@ -230,6 +230,17 @@ type Size = { tokens: number; bytes: number };
|
|
|
230
230
|
const count = (value: number) => Math.max(0, Math.round(value)).toLocaleString("en-US");
|
|
231
231
|
/** How many of a model's tokens one token of the library's estimate comes to. */
|
|
232
232
|
const scaleOf = (adapter: ModelAdapter): number => (adapter.capabilities.tokenScale && adapter.capabilities.tokenScale > 0 ? adapter.capabilities.tokenScale : 1);
|
|
233
|
+
/** What a page costs when a model does not say: the OpenAI adapter's default. */
|
|
234
|
+
const DEFAULT_PAGE_TOKENS = 1_000;
|
|
235
|
+
/**
|
|
236
|
+
* What a page costs a model, in its tokens: its `pageTokens`, or `DEFAULT_PAGE_TOKENS` when that is
|
|
237
|
+
* missing or not a finite number (an adapter written in JavaScript). NaN took away the page limit
|
|
238
|
+
* of the question and every count of the room left once a page was shown.
|
|
239
|
+
*/
|
|
240
|
+
const pageTokensOf = (adapter: ModelAdapter): number => {
|
|
241
|
+
const declared: unknown = adapter.capabilities.pageTokens;
|
|
242
|
+
return typeof declared === "number" && Number.isFinite(declared) && declared >= 0 ? declared : DEFAULT_PAGE_TOKENS;
|
|
243
|
+
};
|
|
233
244
|
const isRound = (message: ModelMessage): message is ModelToolRound => message.role === "tools";
|
|
234
245
|
|
|
235
246
|
/** How many pages a `view_pages` result showed: its `pages` is "12" or "12-14". */
|
|
@@ -287,6 +298,8 @@ class RequestMeter {
|
|
|
287
298
|
private readonly sizes = new WeakMap<ModelToolRound, Size>();
|
|
288
299
|
/** How much larger the provider counted the last request than the estimate did. Never below 1. */
|
|
289
300
|
private factor = 1;
|
|
301
|
+
/** The least `factor` may be for the rest of the question: what a request refused as too large showed. */
|
|
302
|
+
private floor = 1;
|
|
290
303
|
|
|
291
304
|
constructor(private readonly pageTokens: number) {}
|
|
292
305
|
|
|
@@ -336,20 +349,25 @@ class RequestMeter {
|
|
|
336
349
|
return { tokens: Math.ceil(size.tokens * this.factor), bytes: size.bytes };
|
|
337
350
|
}
|
|
338
351
|
|
|
339
|
-
/**
|
|
352
|
+
/**
|
|
353
|
+
* Takes note of what the provider counted for a request that was estimated at `estimated` tokens.
|
|
354
|
+
* A report raises the estimate up to twice; it never lowers it below what a refusal showed.
|
|
355
|
+
*/
|
|
340
356
|
observe(estimated: number, counted: number | undefined): void {
|
|
341
|
-
if (estimated > 0 && typeof counted === "number" && counted > 0) this.factor = Math.min(2, Math.max(1, counted / estimated));
|
|
357
|
+
if (estimated > 0 && typeof counted === "number" && counted > 0) this.factor = Math.max(this.floor, Math.min(2, Math.max(1, counted / estimated)));
|
|
342
358
|
}
|
|
343
359
|
|
|
344
360
|
/**
|
|
345
361
|
* Takes note of a request the provider refused as too large: it counted `counted` tokens (in the
|
|
346
362
|
* library's tokens by the model's scale) of one estimated at `estimated`, or, when it did not say,
|
|
347
363
|
* a quarter more than the estimate. Unlike `observe`, nothing caps it at twice the estimate: the
|
|
348
|
-
* refusal is the provider's word that the estimate was too low
|
|
364
|
+
* refusal is the provider's word that the estimate was too low, and it holds for the rest of the
|
|
365
|
+
* question: a later report does not take it back.
|
|
349
366
|
*/
|
|
350
367
|
overflowed(estimated: number, counted: number | undefined): void {
|
|
351
368
|
const ratio = estimated > 0 && typeof counted === "number" && counted > 0 ? counted / estimated : this.factor * 1.25;
|
|
352
369
|
this.factor = Math.min(8, Math.max(this.factor, ratio));
|
|
370
|
+
this.floor = this.factor;
|
|
353
371
|
}
|
|
354
372
|
}
|
|
355
373
|
|
|
@@ -386,8 +404,25 @@ function retryMessage({ error, delayMs }: RetryNotice): string {
|
|
|
386
404
|
return `${what}. Trying again${seconds}…`;
|
|
387
405
|
}
|
|
388
406
|
|
|
389
|
-
/**
|
|
390
|
-
|
|
407
|
+
/**
|
|
408
|
+
* What the question had found when it failed, by the error it threw: see `partialResultOf`. With
|
|
409
|
+
* the question it came from, and no result once a second question threw the same error.
|
|
410
|
+
*/
|
|
411
|
+
const partialResults = new WeakMap<object, { owner: RunState; result: AskResult | undefined }>();
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Keeps what the question run with `owner` had done when it threw `error`. The same error can be
|
|
415
|
+
* thrown by several questions: the reason of a signal they share (`AbortSignal.any` passes the
|
|
416
|
+
* reason on as it is). Then `partialResultOf` gives none of them a result for it, rather than one
|
|
417
|
+
* question's tool rounds and usage for another's. The question's own `run.error` still has its own.
|
|
418
|
+
*/
|
|
419
|
+
function keepPartial(error: unknown, owner: RunState, result: AskResult): void {
|
|
420
|
+
if (error === null || typeof error !== "object") return;
|
|
421
|
+
owner.failed = { error, result };
|
|
422
|
+
const kept = partialResults.get(error);
|
|
423
|
+
const shared = kept !== undefined && (kept.owner !== owner || kept.result === undefined);
|
|
424
|
+
partialResults.set(error, { owner, result: shared ? undefined : result });
|
|
425
|
+
}
|
|
391
426
|
|
|
392
427
|
/**
|
|
393
428
|
* What a question that failed had done before it failed: its tool steps, evidence, tool rounds and
|
|
@@ -398,7 +433,7 @@ const partialResults = new WeakMap<object, AskResult>();
|
|
|
398
433
|
* question under way (a document that is missing, a budget that does not work).
|
|
399
434
|
*/
|
|
400
435
|
export function partialResultOf(error: unknown): AskResult | undefined {
|
|
401
|
-
return error !== null && typeof error === "object" ? partialResults.get(error) : undefined;
|
|
436
|
+
return error !== null && typeof error === "object" ? partialResults.get(error)?.result : undefined;
|
|
402
437
|
}
|
|
403
438
|
|
|
404
439
|
/**
|
|
@@ -445,6 +480,21 @@ const MOST_NUDGES = 2;
|
|
|
445
480
|
/** The most requests sent again, smaller, after the provider refused one as too large. */
|
|
446
481
|
const MOST_OVERFLOW_RECOVERIES = 2;
|
|
447
482
|
|
|
483
|
+
/**
|
|
484
|
+
* The limits of a question, checked. A field that is NaN (`Number(process.env.X)` of a variable
|
|
485
|
+
* that is not set) or not a number is an error, as a budget field is: NaN fails every comparison,
|
|
486
|
+
* so it turned off the ceilings and the cap on whole-file reads, or every tool.
|
|
487
|
+
*/
|
|
488
|
+
function checkedLimits(given: AskLimits | undefined): AskLimits {
|
|
489
|
+
for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests"] as const) {
|
|
490
|
+
const value: unknown = given?.[field];
|
|
491
|
+
if (value === undefined) continue;
|
|
492
|
+
if (typeof value !== "number") throw new TypeError(`limits.${field} must be a number, and is ${typeof value === "string" ? JSON.stringify(value) : typeof value}.`);
|
|
493
|
+
if (Number.isNaN(value)) throw new RangeError(`limits.${field} must be a number, and is NaN. Leave it out for the default.`);
|
|
494
|
+
}
|
|
495
|
+
return given ?? {};
|
|
496
|
+
}
|
|
497
|
+
|
|
448
498
|
/** Said, once, when a ceiling of `limits` stops the tools. */
|
|
449
499
|
const BUDGET_REACHED = "No more tools: the question reached its limit of input tokens or requests.";
|
|
450
500
|
|
|
@@ -458,6 +508,8 @@ type RunState = {
|
|
|
458
508
|
calls: number;
|
|
459
509
|
/** True once "budget_reached" was said. */
|
|
460
510
|
budgetSaid: boolean;
|
|
511
|
+
/** The error the question failed with, and what it had done: for its own `run.error`. */
|
|
512
|
+
failed?: { error: unknown; result: AskResult };
|
|
461
513
|
};
|
|
462
514
|
|
|
463
515
|
/** A document as an event names it. */
|
|
@@ -498,7 +550,8 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
|
|
|
498
550
|
return result;
|
|
499
551
|
} catch (error) {
|
|
500
552
|
if (events.active) {
|
|
501
|
-
|
|
553
|
+
// The question's own, also when another question threw the same error (a shared signal's reason).
|
|
554
|
+
const partial = state.failed && state.failed.error === error ? state.failed.result : partialResultOf(error);
|
|
502
555
|
events.emit({ type: "run.error", error: eventErrorOf(error), ...(partial ? { partial: eventResultOf(partial, options.eventResults === true) } : {}) });
|
|
503
556
|
}
|
|
504
557
|
throw error;
|
|
@@ -551,8 +604,9 @@ async function askPlanned(options: AskOptions, state: RunState): Promise<AskResu
|
|
|
551
604
|
} catch (again) {
|
|
552
605
|
// Failed before it sent anything (a budget of the application's that cannot work with the
|
|
553
606
|
// smaller window): the provider's error, with what the first try found, is the one to report.
|
|
554
|
-
|
|
555
|
-
|
|
607
|
+
// (The question's own record: `partialResultOf` gives nothing for an error another question threw too.)
|
|
608
|
+
if (state.failed?.error !== again && (again as { status?: unknown } | null)?.status === undefined) {
|
|
609
|
+
keepPartial(error.overflow, state, error.partial);
|
|
556
610
|
throw error.overflow;
|
|
557
611
|
}
|
|
558
612
|
throw again;
|
|
@@ -567,7 +621,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
567
621
|
const explorer = options.explorer && options.explorer !== model ? options.explorer : undefined;
|
|
568
622
|
const toolModel = explorer ?? model;
|
|
569
623
|
const models = explorer ? [model, explorer] : [model];
|
|
570
|
-
const limits = options.limits
|
|
624
|
+
const limits = checkedLimits(options.limits);
|
|
571
625
|
// A question planned again goes on counting what its first try paid for.
|
|
572
626
|
const usage = carried?.usage ?? new UsageMeter();
|
|
573
627
|
|
|
@@ -587,8 +641,9 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
587
641
|
...(requestBytesLimit.length > 0 ? { maxRequestBytes: Math.min(...requestBytesLimit) } : {}),
|
|
588
642
|
});
|
|
589
643
|
// What a page costs, in the same terms. Pages are shown to every model of the question.
|
|
590
|
-
const pageTokens = Math.max(1, ...models.map(
|
|
591
|
-
|
|
644
|
+
const pageTokens = Math.max(1, ...models.map(pageTokensOf)) / scale;
|
|
645
|
+
// A value the type does not have (left out by an adapter in JavaScript) counts as "none".
|
|
646
|
+
const canShowFiles = models.every((adapter) => adapter.capabilities.toolFiles === "inside" || adapter.capabilities.toolFiles === "beside");
|
|
592
647
|
// Every model must be able to take a conversation whose earlier turns were made shorter.
|
|
593
648
|
const canShrink = models.every((adapter) => !adapter.capabilities.appendOnly);
|
|
594
649
|
// A call made again is answered with a pointer to its earlier result only while that result stays
|
|
@@ -1034,7 +1089,8 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1034
1089
|
if (searchable.length === 0 && viewable.length === 0) return result(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
|
|
1035
1090
|
|
|
1036
1091
|
// Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
|
|
1037
|
-
|
|
1092
|
+
// Bound to its adapter: a class with a `generateText` method that uses `this` keeps it.
|
|
1093
|
+
const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText?.bind(toolModel);
|
|
1038
1094
|
const generate: GenerateText | undefined = partReader && (async (part) => {
|
|
1039
1095
|
let reported = false;
|
|
1040
1096
|
const text = await partReader({
|
|
@@ -1552,7 +1608,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1552
1608
|
} catch (error) {
|
|
1553
1609
|
// What the question found and paid for until it failed, for the application to keep. The usage is
|
|
1554
1610
|
// a copy: a part reader that went on after the question was stopped may still report its own.
|
|
1555
|
-
if (!(error instanceof Replan) && error !== null && typeof error === "object")
|
|
1611
|
+
if (!(error instanceof Replan) && error !== null && typeof error === "object") keepPartial(error, state, { ...result(false), usage: structuredClone(usage.totals) });
|
|
1556
1612
|
throw error;
|
|
1557
1613
|
} finally {
|
|
1558
1614
|
signal?.removeEventListener("abort", stopTools);
|
package/src/decode.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { decodeNotUtf8, type DecodedText } from "./encoding.js";
|
|
2
|
+
import { TimeSlicer } from "./pause.js";
|
|
3
|
+
import type { Extractor } from "./types.js";
|
|
4
|
+
|
|
5
|
+
// Text files: their bytes decoded, in UTF-8, UTF-16 or the older encoding they were saved in.
|
|
6
|
+
|
|
7
|
+
/** A file in Microsoft's compound format, which holds the Office files of before 2007, and Office files protected by a password. */
|
|
8
|
+
export const LEGACY_OFFICE = "This is a Word, Excel or PowerPoint file of before 2007 (.doc, .xls, .ppt), an Outlook message (.msg), or an Office file protected by a password and stored that way. None of these can be read: save it as .docx, .xlsx, .pptx, PDF or text, without a password, and attach that.";
|
|
9
|
+
const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, Word, PowerPoint, Excel or HTML file.";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
|
|
13
|
+
* A file that is not UTF-8 is read in the older encoding it was saved in, or as UTF-8 with its
|
|
14
|
+
* characters that are not valid as U+FFFD (see encoding.ts). Throws a readable error for
|
|
15
|
+
* compressed and other binary files.
|
|
16
|
+
*/
|
|
17
|
+
export function decodeText(bytes: Uint8Array): string {
|
|
18
|
+
const steps = decodeSteps(bytes);
|
|
19
|
+
let step = steps.next();
|
|
20
|
+
while (!step.done) step = steps.next();
|
|
21
|
+
return step.value.text;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `decodeText` in steps: it yields between the steps of a file that is not valid UTF-8. */
|
|
25
|
+
export function* decodeSteps(bytes: Uint8Array): Generator<void, DecodedText> {
|
|
26
|
+
if (bytes[0] === 0xff && bytes[1] === 0xfe) return { text: new TextDecoder("utf-16le").decode(bytes.subarray(2)) };
|
|
27
|
+
if (bytes[0] === 0xfe && bytes[1] === 0xff) return { text: new TextDecoder("utf-16be").decode(bytes.subarray(2)) };
|
|
28
|
+
// Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
|
|
29
|
+
if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
|
|
30
|
+
throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
|
|
31
|
+
}
|
|
32
|
+
// Microsoft's compound file: Office before 2007, an Outlook message, or an Office file with a password.
|
|
33
|
+
if (bytes[0] === 0xd0 && bytes[1] === 0xcf && bytes[2] === 0x11 && bytes[3] === 0xe0 && bytes[4] === 0xa1 && bytes[5] === 0xb1 && bytes[6] === 0x1a && bytes[7] === 0xe1) {
|
|
34
|
+
throw new Error(LEGACY_OFFICE);
|
|
35
|
+
}
|
|
36
|
+
if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
|
|
37
|
+
throw new Error("This file is a ZIP archive. Extract it, then attach the text file you need.");
|
|
38
|
+
}
|
|
39
|
+
const sample = bytes.subarray(0, 8_192);
|
|
40
|
+
let zeros = 0;
|
|
41
|
+
for (const byte of sample) if (byte === 0) zeros++;
|
|
42
|
+
// UTF-16 without a BOM: about half the bytes of ASCII text are zero.
|
|
43
|
+
if (sample.length > 64 && zeros / sample.length > 0.3) {
|
|
44
|
+
let oddZeros = 0;
|
|
45
|
+
let evenText = 0;
|
|
46
|
+
for (let index = 0; index < sample.length; index++) {
|
|
47
|
+
if (index % 2 === 1 && sample[index] === 0) oddZeros++;
|
|
48
|
+
if (index % 2 === 0 && sample[index] !== 0) evenText++;
|
|
49
|
+
}
|
|
50
|
+
const half = sample.length / 2;
|
|
51
|
+
if (oddZeros / half > 0.6 && evenText / half > 0.6) return { text: new TextDecoder("utf-16le").decode(bytes) };
|
|
52
|
+
}
|
|
53
|
+
if (sample.length > 0 && zeros / sample.length > 0.01) throw new Error(NOT_TEXT);
|
|
54
|
+
// Compressed, encrypted, and media files spread control bytes evenly: about 1 byte in 10.
|
|
55
|
+
// Text has almost none, in UTF-8 or in a legacy single-byte encoding. Tab, line breaks, form
|
|
56
|
+
// feed, and ESC (colour codes) do not count.
|
|
57
|
+
let controls = 0;
|
|
58
|
+
for (const byte of sample) {
|
|
59
|
+
if (byte < 0x09 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f) controls++;
|
|
60
|
+
}
|
|
61
|
+
if (sample.length >= 64 && controls / sample.length > 0.03) throw new Error(NOT_TEXT);
|
|
62
|
+
try {
|
|
63
|
+
return { text: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (!(error instanceof TypeError)) throw error;
|
|
66
|
+
}
|
|
67
|
+
// Not valid UTF-8: decoded as it is, the text would be replacement characters.
|
|
68
|
+
return yield* decodeNotUtf8(bytes);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Text files. One that is not UTF-8 is read in the older encoding it was saved in, when that can
|
|
73
|
+
* be recognized, and other requests get a turn while it is read.
|
|
74
|
+
*/
|
|
75
|
+
export const plainText: Extractor = async (bytes, input) => {
|
|
76
|
+
const slicer = new TimeSlicer(input?.signal);
|
|
77
|
+
const steps = decodeSteps(bytes);
|
|
78
|
+
let step = steps.next();
|
|
79
|
+
// Only a file that is not UTF-8 takes steps: its decoding is told as one piece of progress, at the end.
|
|
80
|
+
const stepped = !step.done;
|
|
81
|
+
while (!step.done) {
|
|
82
|
+
await slicer.maybePause();
|
|
83
|
+
step = steps.next();
|
|
84
|
+
}
|
|
85
|
+
if (stepped) input?.onProgress?.({ stage: "decode", done: bytes.byteLength, total: bytes.byteLength, unit: "bytes" });
|
|
86
|
+
const { text, encoding, replacedCharacters } = step.value;
|
|
87
|
+
return { text, ...(encoding ? { encoding } : {}), ...(replacedCharacters ? { replacedCharacters } : {}) };
|
|
88
|
+
};
|
|
89
|
+
|
package/src/errors.ts
CHANGED
|
@@ -57,3 +57,111 @@ export function safeErrorMessage(error: unknown): string {
|
|
|
57
57
|
if (code && syscall) return `The file could not be read from storage (${code}). Try the call again.`;
|
|
58
58
|
return error instanceof Error ? error.message : String(error);
|
|
59
59
|
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Why `ingest` refused a file, for an application that tells its users in its own words (another
|
|
63
|
+
* language, its own tone) rather than with the message:
|
|
64
|
+
* - "empty": the file has no bytes.
|
|
65
|
+
* - "too_large": larger than `maxUploadBytes`.
|
|
66
|
+
* - "too_much_text": more text than `maxTextBytes`, or far more than its size can hold.
|
|
67
|
+
* - "too_many_pages": a PDF with more pages than `maxPdfPages`.
|
|
68
|
+
* - "not_text": a binary file of a kind the library does not read.
|
|
69
|
+
* - "compressed": a gzip or ZIP archive to extract first.
|
|
70
|
+
* - "legacy_office": a Word, Excel or PowerPoint file of before 2007 (.doc, .xls, .ppt), or an
|
|
71
|
+
* Office file protected by a password: both are stored the same way, and neither can be read.
|
|
72
|
+
* - "encrypted": a PDF protected by a password.
|
|
73
|
+
* - "no_text": nothing to read: a PDF without a text layer (a scan), a deck without slides, a
|
|
74
|
+
* workbook without sheets, a file of white space.
|
|
75
|
+
* - "hostile": a file built the way files that exhaust a server are: a zip bomb, pages that draw far
|
|
76
|
+
* more than they hold, a structure no program writes.
|
|
77
|
+
* - "timeout": reading it took longer than `ingestTimeoutMs`, or the kill timer of an isolated reader.
|
|
78
|
+
* - "out_of_memory": an isolated reader ran out of the memory it is given (`createIsolatedExtractors`).
|
|
79
|
+
* - "busy": every isolated reader is busy and the queue is full: try again in a moment
|
|
80
|
+
* (`IngestError.retryAfterMs`). The upload handler answers 503 with `Retry-After`.
|
|
81
|
+
* - "missing_dependency": the optional dependency for the format is not installed, could not be
|
|
82
|
+
* loaded, or (`unpdf`) is of a version that cannot read PDFs on this Node.
|
|
83
|
+
* - "unreadable": the file is damaged, or not of the type its name says.
|
|
84
|
+
*/
|
|
85
|
+
export type IngestErrorCode =
|
|
86
|
+
| "empty"
|
|
87
|
+
| "too_large"
|
|
88
|
+
| "too_much_text"
|
|
89
|
+
| "too_many_pages"
|
|
90
|
+
| "not_text"
|
|
91
|
+
| "compressed"
|
|
92
|
+
| "legacy_office"
|
|
93
|
+
| "encrypted"
|
|
94
|
+
| "no_text"
|
|
95
|
+
| "hostile"
|
|
96
|
+
| "timeout"
|
|
97
|
+
| "out_of_memory"
|
|
98
|
+
| "busy"
|
|
99
|
+
| "missing_dependency"
|
|
100
|
+
| "unreadable";
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* `ingest` could not read a file. The message says why, in words for the person who uploaded it,
|
|
104
|
+
* as it always did; `code` says it for the application. New in 0.8.0: before it, the same refusals
|
|
105
|
+
* were plain `Error`s, with the same messages. The error of an extractor, a parser or an isolated
|
|
106
|
+
* reader is `cause`.
|
|
107
|
+
*/
|
|
108
|
+
export class IngestError extends Error {
|
|
109
|
+
readonly code: IngestErrorCode;
|
|
110
|
+
/** For "busy": how long to wait before trying again, in milliseconds. */
|
|
111
|
+
declare readonly retryAfterMs?: number;
|
|
112
|
+
/** The HTTP status the upload handler answers with: 422 for a file that cannot be read, 413 for "too_large", 503 for "busy". */
|
|
113
|
+
readonly status: number;
|
|
114
|
+
|
|
115
|
+
constructor(code: IngestErrorCode, message: string, options: { cause?: unknown; retryAfterMs?: number } = {}) {
|
|
116
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
117
|
+
this.name = "IngestError";
|
|
118
|
+
this.code = code;
|
|
119
|
+
this.status = code === "busy" ? 503 : code === "too_large" ? 413 : 422;
|
|
120
|
+
if (options.retryAfterMs !== undefined) (this as { retryAfterMs?: number }).retryAfterMs = options.retryAfterMs;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The refusals of the library, by the words of their messages: the extractors give plain `Error`s. */
|
|
125
|
+
const REFUSALS: Array<[RegExp, IngestErrorCode]> = [
|
|
126
|
+
// First, and to the end of the message: the busy refusal of a file starts with its name, which
|
|
127
|
+
// may hold the words of any other refusal.
|
|
128
|
+
[/^The server is (?:reading other files right now|shutting down)\. Try again in a moment\.$| could not be read now: a reader could not be started(?: \([^()]*\))?\. Try again in a moment\.$/, "busy"],
|
|
129
|
+
[/ is empty\.$/, "empty"],
|
|
130
|
+
[/larger than the .* upload limit/, "too_large"],
|
|
131
|
+
// An unpdf that cannot run on this Node is told as its own message (checkUnpdf in extract.ts).
|
|
132
|
+
[/needs the optional dependency|is installed but could not be loaded|^The unpdf installed (?:cannot read PDF files|would stop the whole server)/, "missing_dependency"],
|
|
133
|
+
[/needed more memory than/, "out_of_memory"],
|
|
134
|
+
[/took too long to read|took longer than/, "timeout"],
|
|
135
|
+
[/may be built to exhaust the server|may be a zip bomb|cannot be checked before it is read|lists the same page more than once|far longer than any Office file writes/, "hostile"],
|
|
136
|
+
[/of text, more than is kept|more text than is (?:kept|read) from one file|million characters of text|draws more than .* of text|unpacks to more than/, "too_much_text"],
|
|
137
|
+
[/ pages, more than the .* read from one file/, "too_many_pages"],
|
|
138
|
+
[/gzip-compressed|is a ZIP archive/, "compressed"],
|
|
139
|
+
[/Word, Excel or PowerPoint file of before 2007|protected by a password and stored/, "legacy_office"],
|
|
140
|
+
[/PasswordException|No password given|Incorrect Password|is protected by a password/i, "encrypted"],
|
|
141
|
+
[/looks binary, not text/, "not_text"],
|
|
142
|
+
[/no text layer|did not contain any text|does not contain any slides|any sheets with cells/, "no_text"],
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The code of a refusal of the library, from its message; "unreadable" for any other error of
|
|
147
|
+
* reading a file. A "busy" message does not say how long to wait: give the `IngestError` a
|
|
148
|
+
* `retryAfterMs` of your own (the isolated readers use 5,000).
|
|
149
|
+
*/
|
|
150
|
+
export function ingestErrorCodeOf(message: string): IngestErrorCode {
|
|
151
|
+
for (const [pattern, code] of REFUSALS) if (pattern.test(message)) return code;
|
|
152
|
+
return "unreadable";
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* `error` as an `IngestError`: one already is kept, a plain `Error` gets the code of its message.
|
|
157
|
+
* Anything else is passed on as it is: a value that is not an `Error`, an error with an HTTP status
|
|
158
|
+
* of its own, and a system error, whose message names paths of the server (an extractor of your
|
|
159
|
+
* own that reads a file).
|
|
160
|
+
*/
|
|
161
|
+
export function toIngestError(error: unknown): unknown {
|
|
162
|
+
if (error instanceof IngestError || !(error instanceof Error)) return error;
|
|
163
|
+
const { code, syscall } = systemError(error);
|
|
164
|
+
const { status, statusCode } = error as { status?: unknown; statusCode?: unknown };
|
|
165
|
+
if ((code && syscall) || typeof status === "number" || typeof statusCode === "number") return error;
|
|
166
|
+
return new IngestError(ingestErrorCodeOf(error.message), error.message, { cause: error });
|
|
167
|
+
}
|
package/src/events.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// What a question or an ingest does while it runs, as typed data in order. The callbacks of
|
|
2
2
|
// earlier versions (onText, onActivity, onStep) still get the same strings, at the same moments.
|
|
3
3
|
import type { AskResult } from "./ask.js";
|
|
4
|
-
import { DocumentStoreError } from "./errors.js";
|
|
4
|
+
import { DocumentStoreError, IngestError, type IngestErrorCode } from "./errors.js";
|
|
5
5
|
import type { Evidence } from "./evidence.js";
|
|
6
6
|
import { modelFailureReason } from "./map-reduce.js";
|
|
7
7
|
import type { ModelErrorKind, ModelReply, ModelUsage, ToolTurn } from "./model.js";
|
|
@@ -41,6 +41,11 @@ export type EventError = {
|
|
|
41
41
|
status?: number;
|
|
42
42
|
/** The error's class name: "ModelRequestError", "AbortError", "DocumentsNotFoundError"… */
|
|
43
43
|
name?: string;
|
|
44
|
+
/**
|
|
45
|
+
* For a file `ingest` could not read: why, as `IngestError.code` ("too_large", "no_text",
|
|
46
|
+
* "busy"…), so a page can say it in its own words. New in 0.8.0.
|
|
47
|
+
*/
|
|
48
|
+
code?: IngestErrorCode;
|
|
44
49
|
};
|
|
45
50
|
|
|
46
51
|
/**
|
|
@@ -299,6 +304,10 @@ export function eventErrorOf(error: unknown, message?: string): EventError {
|
|
|
299
304
|
// It never throws: an error whose fields throw when read (a getter, a proxy) is told plainly.
|
|
300
305
|
try {
|
|
301
306
|
const record = (typeof error === "object" && error !== null ? error : {}) as { kind?: unknown; status?: unknown; name?: unknown };
|
|
307
|
+
if (error instanceof IngestError) {
|
|
308
|
+
// Its status is the upload's answer, not a model's.
|
|
309
|
+
return { message: message ?? error.message, name: error.name, code: error.code, ...(error.code === "busy" || error.code === "too_large" ? { status: error.status } : {}) };
|
|
310
|
+
}
|
|
302
311
|
const out: EventError = { message: message ?? userMessageOf(error) };
|
|
303
312
|
if (typeof record.kind === "string") out.kind = record.kind as ModelErrorKind;
|
|
304
313
|
if (typeof record.status === "number") out.status = record.status;
|