llm-large-files 0.9.0 → 0.10.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.
Files changed (222) hide show
  1. package/CHANGELOG.md +500 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +298 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +27 -8
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +7 -5
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +133 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +158 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +264 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +189 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +273 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +484 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +301 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +31 -7
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +7 -5
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
@@ -0,0 +1,301 @@
1
+ // The line citations of an answer, checked against what the tools showed the model. New in 0.10.0.
2
+ import { mergeRanges, type Evidence, type NumberRange } from "./evidence.js";
3
+ import type { DocumentFormat } from "./types.js";
4
+
5
+ /** What `checkCitations` found in an answer (`AskResult.citations`). New in 0.10.0. */
6
+ export type CitationCheck = {
7
+ /** Citations matched to a file and a line. */
8
+ checked: number;
9
+ /** Of those, the ones inside what the tools showed. A file sent whole counts as shown. */
10
+ supported: number;
11
+ /** Citations recognized but not matched: no file name when there are several files, or the row of a workbook. */
12
+ unchecked: number;
13
+ /** The citations of lines the tools did not show: the document's name, and the line. */
14
+ unsupported: Array<{ document: string; line: number }>;
15
+ };
16
+
17
+ /** A citation found in the text: where it is, the lines it names, and whether it names lines or rows. */
18
+ type Cited = { start: number; end: number; from: number; to: number; form: "line" | "row"; bare: boolean };
19
+
20
+ /** Where a file name is written in the text (`from` with its prefix letter, `start` without), and the documents of that name. */
21
+ type Named = { from: number; start: number; end: number; ids: string[] };
22
+
23
+ /**
24
+ * Hebrew points and cantillation marks, which a word may carry ("שׁוּרָה"). Not the maqaf (־), the
25
+ * paseq, the sof pasuq or the nun hafukha, which are punctuation.
26
+ */
27
+ const POINTS = /[֑-ׇֽֿׁׂׅׄ]/gu;
28
+ /** Marks that set the direction of text and show nothing: LRM, RLM, the embeddings and overrides, the isolates, the Arabic letter mark. */
29
+ const DIRECTION_MARKS = /[؜‎‏‪-‮⁦-⁩]/gu;
30
+ /** A text without the marks a model may put in Hebrew or mixed text: what is left is read as a person reads it. */
31
+ const plain = (text: string) => text.replace(POINTS, "").replace(DIRECTION_MARKS, "");
32
+
33
+ /** Not a letter, a digit or "_" before or after: the edge of a word, in any script. */
34
+ const EDGE_BEFORE = String.raw`(?<![\p{L}\p{N}_])`;
35
+ const EDGE_AFTER = String.raw`(?![\p{L}\p{N}_])`;
36
+ /** The second number of a range: "12-14", "12–14", "12־14" (a maqaf), "12 to 14", "12 עד 14". */
37
+ const RANGE_END = String.raw`(?:\s*[-–—־]\s*|\s+(?:to|עד)\s+)`;
38
+ /** "L" or "l", and a space at most, before a line number: "L12", "l12", "L 12". */
39
+ const LINE_LETTER = String.raw`[Ll][  ]?`;
40
+ /**
41
+ * A line number: digits, or digits in groups of three after commas ("1,200", "12,345,678"), as a
42
+ * model writes a large number. "L12,14" is line 12, then something else: a group has three digits.
43
+ */
44
+ const NUMBER = String.raw`(\d{1,3}(?:,\d{3}){1,2}|\d{1,9})`;
45
+ /** The value of a line number as `NUMBER` reads it: its commas left out. */
46
+ const numberOf = (written: string) => Number(written.replaceAll(",", ""));
47
+
48
+ /**
49
+ * The forms of a citation, each with the numbers it names:
50
+ * - "L12", "L12-14", "L12-L14", "L 12", "l12", "L1,200": lines, as the tools and the closing request write them;
51
+ * - "line 12", "lines 12-14": lines, in words;
52
+ * - "Row 12": a row, which for a workbook may be Excel's row and not a line;
53
+ * - "שורה 12", "שורות 12-14", with a prefix letter ("בשורה 12") or "מס'": in Hebrew "שורה" is
54
+ * both a line and a row.
55
+ */
56
+ const FORMS: Array<{ pattern: RegExp; form: "line" | "row"; bare: boolean }> = [
57
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}${LINE_LETTER}${NUMBER}(?:${RANGE_END}(?:${LINE_LETTER})?${NUMBER})?${EDGE_AFTER}`, "gu"), form: "line", bare: true },
58
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[Ll]ines?\s+${NUMBER}(?:${RANGE_END}${NUMBER})?${EDGE_AFTER}`, "gu"), form: "line", bare: false },
59
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[Rr]ows?\s+${NUMBER}(?:${RANGE_END}${NUMBER})?${EDGE_AFTER}`, "gu"), form: "row", bare: false },
60
+ { pattern: new RegExp(String.raw`${EDGE_BEFORE}[בלמוהכש]{0,2}שור(?:ה|ות)\s+(?:(?:מס['׳]?|מספר)\s*)?${NUMBER}(?:${RANGE_END}${NUMBER})?${EDGE_AFTER}`, "gu"), form: "row", bare: false },
61
+ ];
62
+
63
+ /** How far, in characters on one line, a file name may be from the citation it goes with. */
64
+ const NAME_DISTANCE = 40;
65
+ /**
66
+ * What ends a clause between a citation and a name: a comma, a semicolon, the end of a sentence, or
67
+ * "and" ("ו" in Hebrew, alone or with a hyphen). A name across one is farther than its characters say.
68
+ */
69
+ const CLAUSE_BREAK = /[,;.!?]|(?<!\p{L})(?:and|ו)(?!\p{L})/iu;
70
+ /**
71
+ * What may stand between a citation and a name after it that it belongs to: "of", "in", "from",
72
+ * "בקובץ", "של" and the like, or only a space when the name carries the prefix letter "ב" or "מ"
73
+ * ("שורה 40 בחשבוניות.csv").
74
+ */
75
+ const INTRODUCED = /^\s*(?:of|in|from|בקובץ|מקובץ|בגיליון|של)\s*$/iu;
76
+ /** A name followed by a comma or a colon and then the citation: "app.log, line 97", "חוזה.docx: שורה 12". */
77
+ const LISTED = /^\s*[,:]\s*$/u;
78
+
79
+ /** A text for a regular expression that matches it as it is. */
80
+ const escaped = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
81
+
82
+ /** The index of the first item of `items`, in order of `key`, whose key is `value` or more: `items.length` when none is. */
83
+ function firstFrom<T>(items: T[], key: (item: T) => number, value: number): number {
84
+ let low = 0;
85
+ let high = items.length;
86
+ while (low < high) {
87
+ const middle = (low + high) >>> 1;
88
+ if (key(items[middle]!) < value) low = middle + 1;
89
+ else high = middle;
90
+ }
91
+ return low;
92
+ }
93
+
94
+ /**
95
+ * Every citation of `text`, in order. One place in the text is one citation, of the first form that
96
+ * reads it. The matches of each form come in order, so each is checked only against the citations
97
+ * already kept around it.
98
+ */
99
+ function citationsIn(text: string): Cited[] {
100
+ let kept: Cited[] = [];
101
+ for (const { pattern, form, bare } of FORMS) {
102
+ const added: Cited[] = [];
103
+ // The first citation kept that ends after the start of the match: the only one it may overlap first.
104
+ let next = 0;
105
+ for (const match of text.matchAll(pattern)) {
106
+ const start = match.index;
107
+ const end = start + match[0].length;
108
+ while (next < kept.length && kept[next]!.end <= start) next++;
109
+ if (next < kept.length && kept[next]!.start < end) continue;
110
+ const first = numberOf(match[1]!);
111
+ const second = match[2] === undefined ? first : numberOf(match[2]);
112
+ if (first < 1 || second < 1) continue;
113
+ added.push({ start, end, from: Math.min(first, second), to: Math.max(first, second), form, bare });
114
+ }
115
+ // The two lists, each in order and apart from the other, made one.
116
+ const merged: Cited[] = [];
117
+ let left = 0;
118
+ let right = 0;
119
+ while (left < kept.length || right < added.length) {
120
+ if (right >= added.length || (left < kept.length && kept[left]!.start < added[right]!.start)) merged.push(kept[left++]!);
121
+ else merged.push(added[right++]!);
122
+ }
123
+ kept = merged;
124
+ }
125
+ return kept;
126
+ }
127
+
128
+ /**
129
+ * Where the documents' names are written in `text`: each name whole, and without its extension
130
+ * when what is left has 3 characters or more ("report" for "report.docx"). A Hebrew prefix letter
131
+ * may come before it ("בדוח.docx"). Where two overlap, the longer one is taken. In order.
132
+ */
133
+ function namesIn(text: string, names: Map<string, string[]>): Named[] {
134
+ const aliases = new Map<string, Set<string>>();
135
+ const alias = (name: string, ids: string[]) => {
136
+ const key = name.toLocaleLowerCase();
137
+ const known = aliases.get(key) ?? new Set<string>();
138
+ for (const id of ids) known.add(id);
139
+ aliases.set(key, known);
140
+ };
141
+ for (const [written, ids] of names) {
142
+ const name = plain(written);
143
+ if (!name.trim()) continue;
144
+ alias(name, ids);
145
+ const dot = name.lastIndexOf(".");
146
+ if (dot >= 3) alias(name.slice(0, dot), ids);
147
+ }
148
+ const hits: Named[] = [];
149
+ for (const [name, ids] of aliases) {
150
+ const pattern = new RegExp(String.raw`${EDGE_BEFORE}(?:[בלמוהכש]{1,2}[-־]?)?(${escaped(name)})${EDGE_AFTER}`, "giud");
151
+ for (const match of text.matchAll(pattern)) {
152
+ const [start, end] = match.indices![1]!;
153
+ hits.push({ from: match.index, start, end, ids: [...ids] });
154
+ }
155
+ }
156
+ hits.sort((left, right) => left.start - right.start || (right.end - right.start) - (left.end - left.start));
157
+ const kept: Named[] = [];
158
+ for (const hit of hits) {
159
+ const last = kept.at(-1);
160
+ if (last && hit.start < last.end) continue;
161
+ kept.push(hit);
162
+ }
163
+ return kept;
164
+ }
165
+
166
+ /**
167
+ * A function that gives the parentheses around a place of `text`, on its line: their start and
168
+ * end, or undefined when it is not inside any. The parentheses and line breaks are found once.
169
+ */
170
+ function parenthesesOf(text: string): (start: number, end: number) => [number, number] | undefined {
171
+ const marks: number[] = [];
172
+ for (let index = 0; index < text.length; index++) {
173
+ const code = text.charCodeAt(index);
174
+ if (code === 0x28 || code === 0x29 || code === 0x0a) marks.push(index);
175
+ }
176
+ return (start, end) => {
177
+ // The mark nearest before the place must open parentheses; the nearest after it must close them.
178
+ const before = firstFrom(marks, (mark) => mark, start) - 1;
179
+ if (before < 0 || text[marks[before]!] !== "(") return undefined;
180
+ const after = firstFrom(marks, (mark) => mark, end);
181
+ return after < marks.length && text[marks[after]!] === ")" ? [marks[before]!, marks[after]! + 1] : undefined;
182
+ };
183
+ }
184
+
185
+ /** True when nothing between `from` and `to` breaks the line, and they are close enough. */
186
+ const near = (text: string, from: number, to: number) => to - from <= NAME_DISTANCE && !text.slice(from, to).includes("\n");
187
+
188
+ /**
189
+ * How far a name is from a citation, in characters, with `NAME_DISTANCE` more when a clause ends
190
+ * between them (`broken`, or a break in what is between). A long gap is not read: it is far.
191
+ */
192
+ function distance(text: string, from: number, to: number, broken: boolean): number {
193
+ if (to - from > 2 * NAME_DISTANCE) return to - from + NAME_DISTANCE;
194
+ return to - from + (broken || CLAUSE_BREAK.test(text.slice(from, to)) ? NAME_DISTANCE : 0);
195
+ }
196
+
197
+ /**
198
+ * The nearer of the name before a citation and the name after it. A name after it introduced as
199
+ * its own ("of x", "בקובץ x", "בx") is its name. A name before it followed by only a comma or a
200
+ * colon ("x, line 97") is as near as its characters say. Otherwise a citation that opens with "ו"
201
+ * ("ושורה 40") starts a clause of its own, and so does a name after it that opens with "ו". When
202
+ * both are as near, the name before.
203
+ */
204
+ function nearer(text: string, cited: Cited, before: Named | undefined, after: Named | undefined): Named | undefined {
205
+ if (!before || !after) return before ?? after;
206
+ const ahead = text.slice(cited.end, after.from);
207
+ // "line 40 of x", "שורה 40 בקובץ x", "שורה 40 בx": the name after is introduced as the citation's.
208
+ if (INTRODUCED.test(ahead) || (/^\s*$/u.test(ahead) && after.from < after.start && (text[after.from] === "ב" || text[after.from] === "מ"))) return after;
209
+ // "x, line 97" and "x: שורה 12": the comma gives the citation to the name before, no clause.
210
+ const back = LISTED.test(text.slice(before.end, cited.start)) ? cited.start - before.end : distance(text, before.end, cited.start, text[cited.start] === "ו");
211
+ const far = distance(text, cited.end, after.from, after.from < after.start && text[after.from] === "ו");
212
+ return far < back ? after : before;
213
+ }
214
+
215
+ /**
216
+ * The name a citation goes with: one inside the same parentheses, else one on its line within
217
+ * `NAME_DISTANCE` characters; of the name before it and the name after it, the nearer.
218
+ */
219
+ function nameOf(text: string, cited: Cited, named: Named[], around: [number, number] | undefined): Named | undefined {
220
+ // The names are in order and apart, so their ends are in order too.
221
+ const following = firstFrom(named, (hit) => hit.start, cited.end);
222
+ const before = named[firstFrom(named, (hit) => hit.end, cited.start + 1) - 1];
223
+ const after = named[following];
224
+ if (around) {
225
+ const inside = nearer(text, cited, before && before.start >= around[0] ? before : undefined, after && after.end <= around[1] ? after : undefined);
226
+ if (inside) return inside;
227
+ }
228
+ return nearer(text, cited, before && near(text, before.end, cited.start) ? before : undefined, after && near(text, cited.end, after.from) ? after : undefined);
229
+ }
230
+
231
+ /**
232
+ * The first line of `from`-`to` that `shown` does not hold, or undefined when it holds them all.
233
+ * `shown` is in order, its ranges apart and not touching (`mergeRanges`).
234
+ */
235
+ function firstNotShown(shown: NumberRange[] | "whole", from: number, to: number): number | undefined {
236
+ if (shown === "whole") return undefined;
237
+ // The range that holds `from`, if any: the last one that starts at or before it.
238
+ const holding = shown[firstFrom(shown, (range) => range[0], from + 1) - 1];
239
+ if (!holding || holding[1] < from) return from;
240
+ return holding[1] >= to ? undefined : holding[1] + 1;
241
+ }
242
+
243
+ /**
244
+ * Finds the line citations of `text` ("(name L12)", "(name L12-14)", "name L12", "line 12", "Row
245
+ * 12", and the Hebrew "שורה 12" and "שורות 12-14") and checks them against `evidence`. `names`
246
+ * gives each document ID's file name, and `formats` its format. Hebrew points and marks of
247
+ * direction in the text are not read.
248
+ *
249
+ * A citation goes with the file name next to it: in the same parentheses, or on the same line
250
+ * within 40 characters. A name after it introduced as its own ("line 40 of x", "בשורה 40 בקובץ
251
+ * x", "שורה 40 בx") is its name. Else, of the name before it and the name after it, the nearer
252
+ * one, where a comma, a semicolon, the end of a sentence or "and" ("ו") between them counts as far,
253
+ * except a comma or colon right after the name before ("x, line 97"). With one file it may have none. A bare "L12"
254
+ * with no name next to it counts only inside parentheses ("(L12)"): "L2 cache" is no citation. A
255
+ * citation is supported when every line it names was shown, by the lines of an evidence entry of
256
+ * that document. An entry with `whole` (a file read whole, or sent whole) and no lines shows every
257
+ * line; one with lines (`[[1, lines]]`) shows those, so a line past the end of the file is not
258
+ * supported. Two documents of one name support it by either. A row ("Row 12", "שורה 12") of a
259
+ * workbook (XLSX) is unchecked: it may be Excel's row, which is not the line. New in 0.10.0.
260
+ */
261
+ export function checkCitations(text: string, evidence: Evidence[], names: Record<string, string>, formats?: Record<string, DocumentFormat>): CitationCheck {
262
+ const check: CitationCheck = { checked: 0, supported: 0, unchecked: 0, unsupported: [] };
263
+ if (typeof text !== "string" || !text) return check;
264
+ const read = plain(text);
265
+ // The name of each document: the one given, else the one its evidence says.
266
+ const nameById = new Map<string, string>(Object.entries(names ?? {}).filter((entry): entry is [string, string] => typeof entry[1] === "string"));
267
+ for (const entry of evidence) if (typeof entry.document === "string" && !nameById.has(entry.documentId)) nameById.set(entry.documentId, entry.document);
268
+ const byName = new Map<string, string[]>();
269
+ for (const [id, name] of nameById) byName.set(name, [...byName.get(name) ?? [], id]);
270
+ // What was shown of each document: its lines, or all of it.
271
+ const shown = new Map<string, NumberRange[] | "whole">();
272
+ for (const entry of evidence) {
273
+ const before = shown.get(entry.documentId);
274
+ if (before === "whole") continue;
275
+ if (entry.whole === true && !Array.isArray(entry.lines)) shown.set(entry.documentId, "whole");
276
+ else if (entry.lines?.length) shown.set(entry.documentId, mergeRanges([...before ?? [], ...entry.lines]));
277
+ }
278
+ const only = nameById.size === 1 ? [...nameById.keys()] : undefined;
279
+ const named = namesIn(read, byName);
280
+ const parentheses = parenthesesOf(read);
281
+ for (const cited of citationsIn(read)) {
282
+ // A part of a file name ("report-L3.docx") is not a citation.
283
+ const overlapping = named[firstFrom(named, (hit) => hit.end, cited.start + 1)];
284
+ if (overlapping && overlapping.start < cited.end) continue;
285
+ const around = parentheses(cited.start, cited.end);
286
+ const hit = nameOf(read, cited, named, around);
287
+ if (!hit && cited.bare && !around) continue;
288
+ const ids = hit?.ids ?? only;
289
+ // A row of a workbook may be Excel's row: there is no line to check it against.
290
+ const lined = ids?.filter((id) => cited.form === "line" || formats?.[id] !== "xlsx");
291
+ if (!lined?.length) {
292
+ check.unchecked++;
293
+ continue;
294
+ }
295
+ check.checked++;
296
+ const missing = lined.map((id) => firstNotShown(shown.get(id) ?? [], cited.from, cited.to));
297
+ if (missing.some((line) => line === undefined)) check.supported++;
298
+ else check.unsupported.push({ document: nameById.get(lined[0]!) ?? lined[0]!, line: missing[0]! });
299
+ }
300
+ return check;
301
+ }
package/src/error-info.ts CHANGED
@@ -47,6 +47,28 @@ export type ErrorInfo = {
47
47
 
48
48
  /** How long to wait after a store failed, before the same call is made again. */
49
49
  export const STORE_RETRY_AFTER_MS = 5_000;
50
+ /** How long to wait after a disk was full (`ENOSPC`, `EDQUOT`), before the same call is made again. New in 0.10.0. */
51
+ export const NO_ROOM_RETRY_AFTER_MS = 30_000;
52
+
53
+ /**
54
+ * The codes of system errors that say the server, or a service it needs, could not answer just
55
+ * now: a time limit, a connection that was refused or cut, a name that could not be looked up, too
56
+ * many files open, a busy file or a stale handle on a network volume. The same call may work a
57
+ * moment later. New in 0.10.0: before, they were "unknown", 500, and not retryable.
58
+ */
59
+ export const TRANSIENT_CODES: ReadonlySet<string> = new Set([
60
+ "ETIMEDOUT", "ECONNRESET", "ECONNREFUSED", "EPIPE", "EAI_AGAIN", "EAGAIN", "EBUSY", "EMFILE", "ENFILE", "ESTALE", "EHOSTUNREACH", "ENETUNREACH",
61
+ ]);
62
+ /** The codes of a disk that is full: retryable too, later. New in 0.10.0. */
63
+ export const NO_ROOM_CODES: ReadonlySet<string> = new Set(["ENOSPC", "EDQUOT"]);
64
+
65
+ /** How long to wait before the same call is made again after a system error of `code`, or undefined when it is not one to retry. New in 0.10.0. */
66
+ export function retryAfterOfCode(code: unknown): number | undefined {
67
+ if (typeof code !== "string") return undefined;
68
+ if (TRANSIENT_CODES.has(code)) return STORE_RETRY_AFTER_MS;
69
+ if (NO_ROOM_CODES.has(code)) return NO_ROOM_RETRY_AFTER_MS;
70
+ return undefined;
71
+ }
50
72
 
51
73
  const SOMETHING_WENT_WRONG = "Something went wrong.";
52
74
  /**
@@ -223,9 +245,22 @@ function infoOf(error: unknown): ErrorInfo {
223
245
  /**
224
246
  * Anything else: "unknown", with the code of a system error (of its event, from the library's
225
247
  * words), never its message. `status`, of plain data, is kept when it is one of an error (400 to
226
- * 599), and says whether to retry.
248
+ * 599), and says whether to retry. Since 0.10.0 a code that says the server could not answer just
249
+ * now (`TRANSIENT_CODES`) is 503 and retryable, with 5 s to wait, and one of a full disk
250
+ * (`NO_ROOM_CODES`) the same with 30 s, whatever status the data holds.
227
251
  */
228
252
  function plainInfo(error: object, status: unknown, code = systemCode(error)): ErrorInfo {
253
+ const retryAfterMs = retryAfterOfCode(code);
254
+ if (code && retryAfterMs !== undefined) {
255
+ return {
256
+ category: "unknown",
257
+ code,
258
+ status: 503,
259
+ retryable: true,
260
+ retryAfterMs,
261
+ message: NO_ROOM_CODES.has(code) ? `The server has no room right now (${code}). Try again later.` : `The server could not do this just now (${code}). Try again in a moment.`,
262
+ };
263
+ }
229
264
  return {
230
265
  category: "unknown",
231
266
  ...(code ? { code } : {}),
package/src/errors.ts CHANGED
@@ -69,7 +69,9 @@ function storeMessage(operation: DocumentStoreOperation, code: string | undefine
69
69
  export class DocumentStoreError extends Error {
70
70
  /**
71
71
  * The code of the system error behind it (`EIO`, `EMFILE`, `ETIMEDOUT`), when there is one, or
72
- * the code it was made with: "NEWER_VERSION".
72
+ * the code it was made with: "NEWER_VERSION"; since 0.10.0, "ETIMEDOUT" for a store call that did
73
+ * not end within `storeTimeoutMs`, and "STORE_STUCK" for one refused at once because too many
74
+ * calls of the process are stuck (`maxStuckStoreCalls`).
73
75
  */
74
76
  readonly code?: string;
75
77
  /** The system call that failed (`open`, `read`), when there is one. */
package/src/events.ts CHANGED
@@ -79,12 +79,17 @@ export type RequestPurpose = "turn" | "nudge" | "closing" | "answer_again" | "di
79
79
  * - "error": it ran, or was checked, and returned `{ error }` (bad arguments, a document it cannot
80
80
  * read, a regex that took too long…), or it was ended because its turn failed (the question was
81
81
  * stopped, or a listener threw): then the model was sent nothing;
82
- * - "refused": it was not run, for a limit of the question (cost, room, reads of a whole file);
82
+ * - "refused": it was not run: for a limit of the question (cost, room, reads of a whole file), a
83
+ * tool the question does not have (since 0.10.0), or a `{ reject }` of `onToolResult` (0.10.0);
83
84
  * - "already_shown": it repeated a call whose result is still in the conversation, and was answered
84
85
  * with a pointer to it;
85
- * - "not_run": the turn had more calls than `limits.callsPerTurn`.
86
+ * - "not_run": the turn had more calls than `limits.callsPerTurn`;
87
+ * - "redacted": it ran, and `AskOptions.onToolResult` replaced its result: the model was sent the
88
+ * replacement. New in 0.10.0.
89
+ *
90
+ * A switch over every outcome must handle the outcomes added in a later version.
86
91
  */
87
- export type ToolOutcome = "ok" | "error" | "refused" | "already_shown" | "not_run";
92
+ export type ToolOutcome = "ok" | "error" | "refused" | "already_shown" | "not_run" | "redacted";
88
93
 
89
94
  /**
90
95
  * Something the run did that is not a request or a tool call:
@@ -104,7 +109,11 @@ export type ToolOutcome = "ok" | "error" | "refused" | "already_shown" | "not_ru
104
109
  * - "document_gone": a tool call found a document gone during the question (deleted or expired
105
110
  * since it was planned). The model was told so in the call's result. New in 0.9.0;
106
111
  * - "page_looks_busy": a look at pages waited its turn (`maxConcurrentPageLooks`) longer than
107
- * `pageLookWaitMs`, and was not run. The model was told so in the call's result. New in 0.9.0.
112
+ * `pageLookWaitMs`, and was not run. The model was told so in the call's result. New in 0.9.0;
113
+ * - "answer_filtered": a filter of the provider stopped the answer, with or without text
114
+ * (`AskResult.finish` "filtered"). New in 0.10.0;
115
+ * - "answer_cut": the answer stopped at the output limit (`AskResult.finish` "cut"). New in
116
+ * 0.10.0.
108
117
  *
109
118
  * A switch over every code must handle the codes added in a later version.
110
119
  */
@@ -122,7 +131,9 @@ export type NoticeCode =
122
131
  | "blocked"
123
132
  | "documents_missing"
124
133
  | "document_gone"
125
- | "page_looks_busy";
134
+ | "page_looks_busy"
135
+ | "answer_filtered"
136
+ | "answer_cut";
126
137
 
127
138
  /**
128
139
  * Where a notice went in the callbacks of earlier versions: "activity" to `onActivity`, "step" to
@@ -143,9 +154,13 @@ export type EventResult = Omit<AskResult, "toolTurns" | "plan"> & {
143
154
  * Which documents went in whole and which were searched, named as `DocumentRef`s: their full
144
155
  * `DocumentMeta` (owner, scope, the SHA-256 and the ref of the original, outline headings, the
145
156
  * commonest lines of a log) is left out unless `eventResults` is true. The returned result has
146
- * the full plan.
157
+ * the full plan. Since 0.10.0 the type of the full metadata here has no owner, scope, `sha256`,
158
+ * `original` or `metaVersion`, which stay on the server: they are left out at run time too.
147
159
  */
148
- plan: { inline: Array<DocumentRef | DocumentMeta>; searchable: Array<DocumentRef | DocumentMeta> };
160
+ plan: {
161
+ inline: Array<DocumentRef | Omit<DocumentMeta, "owner" | "scope" | "sha256" | "original" | "metaVersion">>;
162
+ searchable: Array<DocumentRef | Omit<DocumentMeta, "owner" | "scope" | "sha256" | "original" | "metaVersion">>;
163
+ };
149
164
  };
150
165
 
151
166
  /** The events of a question (`askWithFiles`, `askStream`), in the order they happen. */
@@ -195,6 +210,10 @@ export type AskEvent =
195
210
  finishReason?: string;
196
211
  /** How many tool calls the reply asked for. */
197
212
  toolCalls?: number;
213
+ /** The provider's ID of the response (`ModelReply.responseId`), when the adapter gives one. New in 0.10.0. */
214
+ responseId?: string;
215
+ /** The model that wrote the response, as the provider names it (`ModelReply.responseModel`). New in 0.10.0. */
216
+ responseModel?: string;
198
217
  /** With outcome "error": why. A request that failed may still be followed by others (an overflow made smaller, a part read in halves). */
199
218
  error?: EventError;
200
219
  })
@@ -279,6 +298,11 @@ export type AskEvent =
279
298
  * ("document_gone"), the one whose pages were not looked at ("page_looks_busy"). New in 0.9.0.
280
299
  */
281
300
  documentIds?: string[];
301
+ /**
302
+ * With "answer_filtered", under `AskOptions.filteredAnswer: "drop"`: text of the answer was
303
+ * already sent (`text` events, `onText`), and the page should take it away. New in 0.10.0.
304
+ */
305
+ discardText?: true;
282
306
  })
283
307
  /** Always last when the question returns. Nothing comes after it. */
284
308
  | (EventBase & { type: "run.finish"; result: EventResult })
package/src/evidence.ts CHANGED
@@ -94,8 +94,13 @@ export function evidenceOf(call: ToolCall, result: ToolResult): Evidence | undef
94
94
  if (total < 1) return entry;
95
95
  return withRanges(total > 30 ? [[1, 30], [Math.max(1, total - 19), total]] : [[1, total]], []);
96
96
  }
97
- case TOOL_NAMES.analyze:
98
- return { ...entry, whole: true, ...(typeof call.args.task === "string" ? { query: call.args.task } : {}) };
97
+ case TOOL_NAMES.analyze: {
98
+ // A read that lists items (since 0.10.0) also showed the lines of the items in its result,
99
+ // each checked against its quote: those can be cited.
100
+ const items = (Array.isArray(result.items) ? result.items : []) as Array<{ line?: unknown }>;
101
+ const lines = items.flatMap((item): NumberRange[] => (typeof item.line === "number" && Number.isInteger(item.line) && item.line > 0 ? [[item.line, item.line]] : []));
102
+ return { ...withRanges(lines, []), whole: true, ...(typeof call.args.task === "string" ? { query: call.args.task } : {}) };
103
+ }
99
104
  case TOOL_NAMES.aggregate: {
100
105
  // The rows read are all of the table; what can be cited is the header and each group's first rows.
101
106
  const groups = (Array.isArray(result.groups) ? result.groups : []) as Array<{ lines?: unknown }>;
@@ -117,6 +122,8 @@ const KEPT_ANSWER_CHARACTERS = 6_000;
117
122
  const MOST_RANGES = 60;
118
123
  /** The groups kept of a search with `group_by`, the largest (or, by time, the first) ones. */
119
124
  const KEPT_GROUPS = 30;
125
+ /** The items kept of a whole-file read that lists them: their counts are kept whole. */
126
+ const KEPT_ITEMS = 20;
120
127
 
121
128
  const rangeText = ([from, to]: NumberRange) => (to > from ? `${from}-${to}` : String(from));
122
129
 
@@ -176,6 +183,18 @@ function standIn(call: ToolCall, result: ToolResult): ToolResult {
176
183
  note: "This result was shown to you earlier and was shortened to make room: the largest groups are kept. Run aggregate_table again for the others.",
177
184
  };
178
185
  case TOOL_NAMES.analyze: {
186
+ // A read that lists items (since 0.10.0): its counts stay, and its first items.
187
+ if (typeof result.total_items === "number") {
188
+ return {
189
+ ...base,
190
+ ...(typeof result.parts_read === "number" ? { parts_read: result.parts_read } : {}),
191
+ total_items: result.total_items,
192
+ ...(result.counts_by_label && typeof result.counts_by_label === "object" ? { counts_by_label: result.counts_by_label } : {}),
193
+ ...(typeof result.unverified_items === "number" ? { unverified_items: result.unverified_items } : {}),
194
+ ...(Array.isArray(result.items) ? { items: result.items.slice(0, KEPT_ITEMS) } : {}),
195
+ note: "This is the start of the list of the whole-file read, with its counts. The rest of the list was dropped from the conversation to make room.",
196
+ };
197
+ }
179
198
  const answer = typeof result.answer === "string" ? result.answer : "";
180
199
  return {
181
200
  ...base,
package/src/extract.ts CHANGED
@@ -2,6 +2,7 @@ import { decodeText, plainText } from "./decode.js";
2
2
  import { html } from "./html.js";
3
3
  import { TimeSlicer } from "./pause.js";
4
4
  import { layoutPage, plainPageText, type LayoutBox, type PdfTextItem } from "./pdf-layout.js";
5
+ import { PdfHeadingFinder } from "./pdf-outline.js";
5
6
  import { findPicturePages, parsePdf, type PageGeometry } from "./pdf-pictures.js";
6
7
  import { checkPageWork, HeavyPage } from "./pdf-work.js";
7
8
  import { formatBytes } from "./plan.js";
@@ -268,6 +269,8 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
268
269
  const textLimit = Math.min(maxTextBytes, mostDrawn);
269
270
  const texts: string[] = [];
270
271
  const geometry: PageGeometry[] = [];
272
+ // The lines set larger than the body: the outline of a PDF whose text gives few headings (0.10.0).
273
+ const headingFinder = new PdfHeadingFinder();
271
274
  /** The page objects read so far: a page tree that lists one page twice is refused. */
272
275
  const seen = new Set<string>();
273
276
  // pdf.js reads a page through promises that never let a timer or another request run: other
@@ -287,6 +290,7 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
287
290
  const content = await page.getTextContent();
288
291
  const items = (content.items as unknown[]).filter((item): item is PdfTextItem => typeof (item as PdfTextItem).str === "string");
289
292
  const transform = page.getViewport({ scale: 1 }).transform as number[];
293
+ headingFinder.addPage(number, items);
290
294
  let text = "";
291
295
  let found: LayoutBox[] = [];
292
296
  if (tables) {
@@ -325,7 +329,8 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
325
329
  signal?.throwIfAborted();
326
330
  looked.rethrow();
327
331
  const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text ? ownLines(text) : PAGE_WITHOUT_TEXT}`);
328
- return { text: pages.join("\n\n"), pages: document.numPages };
332
+ const headings = headingFinder.headings();
333
+ return { text: pages.join("\n\n"), pages: document.numPages, ...(headings.length > 0 ? { headings } : {}) };
329
334
  };
330
335
  }
331
336